-
Notifications
You must be signed in to change notification settings - Fork 4
completions api
Nagendra Dhanakeerthi edited this page Oct 30, 2024
·
1 revision
The Completions API provides methods to generate text completions using OpenAI's models.
client = ChatGPT::Client.new
response = client.completions("Write a poem about Ruby")
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
})
{
"choices" => [{
"text" => "Completion text here",
"index" => 0,
"finish_reason" => "stop"
}],
"usage" => {
"prompt_tokens" => 10,
"completion_tokens" => 20,
"total_tokens" => 30
}
}
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
- Prompt Engineering
# Be specific in your prompts
prompt = "Write a haiku about Ruby programming, following 5-7-5 syllable pattern"
- 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
})
- 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
response = client.completions("Write a poem about Ruby")
puts response["choices"][0]["text"]
response = client.completions(
"Write a slogan for Ruby",
{ n: 3 }
)
response["choices"].each do |choice|
puts choice["text"]
end
response = client.completions(
"Explain what Ruby is",
{
engine: "text-davinci-002",
max_tokens: 100,
temperature: 0.5
}
)