Overview
This example demonstrates how to create a simple chat completion using the OpenAI Ruby SDK. Chat completions are the foundation of interacting with GPT models for conversational AI applications.Prerequisites
Before running this example, ensure you have:Basic Example
Here’s a complete example of creating a basic chat completion:Key Concepts
Client Initialization
The SDK automatically reads your API key from theOPENAI_API_KEY environment variable:
Creating a Completion
Use thechat.completions.create method to send a request:
Accessing the Response
The response contains an array of choices. Each choice has a message with the generated content:The
&. operator is Ruby’s safe navigation operator, which prevents errors if the value is nil.Message Roles
Chat completions support three primary message roles:user- Messages from the end userassistant- Messages from the AI assistantsystem- Instructions that guide the assistant’s behavior
Next Steps
Streaming Responses
Learn how to stream chat completions for real-time responses
Function Calling
Integrate tools and function calling into your chat completions