Search code examples
ruby

undefined method `api_key=' for OpenAI:Module for ruby


I have the following code:

require 'openai'

# Set up your API key
OpenAI.api_key = "your_api_key_here"

# Create a function to interact with the API
def generate_text(prompt, temperature=0.7, max_tokens=100, top_p=1.0)
  begin
    response = OpenAI::Completion.create(
      engine: "text-davinci-002", # You can choose from available engines like "text-davinci-002", "text-curie-002", "text-babbage-002", etc.
      prompt: prompt,
      temperature: temperature,
      max_tokens: max_tokens,
      top_p: top_p,
      n: 1,
      stop: nil,
      echo: false
    )

    return response.choices.first.text.strip
  rescue StandardError => e
    puts "Error generating text: #{e.message}"
    return nil
  end
end

# Use the function with a clear and specific prompt
prompt = "Translate the following English text to French: 'Hello, how are you?'"
generated_text = generate_text(prompt)

puts "Generated text: #{generated_text}"

...and when I run this I get the error undefined method api_key= for OpenAI:Module .

I am using the ruby-openai gem and ruby 3.2.2:

gem list ruby-openai
*** LOCAL GEMS ***
ruby-openai (7.3.1)

Thanks in advance!


Solution

  • OK, finally carved out some time to work this out. Here is a soltuion that works:

    require 'openai'
    require 'dotenv'
    
    Dotenv.load
    
    # Configure the OpenAI API client
    OpenAI.configure do |config|
      config.access_token = ENV.fetch("OPENAI_API_KEY") # Assumes you've set the environment variable
    end
    
    
    # Initialize the OpenAI client
    client = OpenAI::Client.new
    
    # Define a simple prompt
    prompt = "Translate the following English text to French: 'Hello, how are you?'"
    
    # Make a request to the ChatGPT API (GPT-4)
    response = client.chat(
      parameters: {
        model: "gpt-4", # Or "gpt-3.5-turbo" if you prefer
        messages: [
          { role: "system", content: "You are a helpful assistant." },
          { role: "user", content: prompt }
        ],
        temperature: 0.7
      }
    )
    
    # Display the response
    if response && response['choices']
      puts "ChatGPT says: #{response['choices'].first['message']['content']}"
    else
      puts "Error: No response from ChatGPT."
    end