Skip to content

completions api

Nagendra Dhanakeerthi edited this page Oct 30, 2024 · 1 revision

Completions API

The Completions API provides methods to generate text completions using OpenAI's models.

Basic Usage

client = ChatGPT::Client.new
response = client.completions("Write a poem about Ruby")

Parameters

client.completions(prompt, {
  engine: "text-davinci-002",  # Optional, defaults to configured value
  max_tokens: 50,             # Optional
  temperature: 0.7,           # Optional (0.0 to 1.0)
  top_p: 0.9,                # Optional
  n: 1                       # Optional, number of completions
})

Response Format

{
  "choices" => [{
    "text" => "Completion text here",
    "index" => 0,
    "finish_reason" => "stop"
  }],
  "usage" => {
    "prompt_tokens" => 10,
    "completion_tokens" => 20,
    "total_tokens" => 30
  }
}

Error Handling

begin
  response = client.completions(prompt)
rescue ChatGPT::AuthenticationError => e
  # Handle authentication errors
rescue ChatGPT::RateLimitError => e
  # Handle rate limit errors
rescue ChatGPT::APIError => e
  # Handle other API errors
end

Best Practices

  1. Prompt Engineering
# Be specific in your prompts
prompt = "Write a haiku about Ruby programming, following 5-7-5 syllable pattern"
  1. Parameter Tuning
# More deterministic results
response = client.completions(prompt, {
  temperature: 0.3,
  max_tokens: 50
})

# More creative results
response = client.completions(prompt, {
  temperature: 0.8,
  max_tokens: 100
})
  1. Error Recovery
def complete_with_retry(prompt, max_attempts = 3)
  attempts = 0
  begin
    attempts += 1
    client.completions(prompt)
  rescue ChatGPT::RateLimitError => e
    retry if attempts < max_attempts
    raise
  end
end

Examples

Simple Completion

response = client.completions("Write a poem about Ruby")
puts response["choices"][0]["text"]

Multiple Completions

response = client.completions(
  "Write a slogan for Ruby",
  { n: 3 }
)
response["choices"].each do |choice|
  puts choice["text"]
end

With Parameters

response = client.completions(
  "Explain what Ruby is",
  {
    engine: "text-davinci-002",
    max_tokens: 100,
    temperature: 0.5
  }
)
Clone this wiki locally