Many AI-driven projects leverage OpenAI’s API SDK to interact with large language models (LLMs). While there is no universal standard, OpenAI’s method has become widely adopted. Understanding this approach is crucial for seamless integration and effective utilization of an LLM.
This guide will walk you through connecting to an LLM using the OpenAI Python SDK. We will explore how to interface with a GPT-4 model, process its responses, track token usage, and structure effective message inputs.
To follow along with this tutorial,
You need to follow the below guidelines to connect LLM with OpenAI:
Start by creating a new Python virtual environment and installing the required packages. Run the following command in your terminal:
> pip install openai python-dotenvThis installs the OpenAI SDK for API interactions and python-dotenv to manage environment variables securely.
Launch VS Code on your system. Create a new Python file, connect_llm.py, and add the following code:
import os
from openai import OpenAI
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
raise ValueError("No API key found. Please set it in the .env file.")
# Initialize OpenAI client
client = OpenAI(api_key=api_key)
def ask_llm(prompt):
response = client.chat.completions.create(
model="gpt-4-turbo", # Use the latest GPT-4 model
messages=[
{"role": "system", "content": "You are an intelligent assistant."},
{"role": "user", "content": prompt}
],
temperature=0.7,
)
return response.choices[0].message.content
# Example usage
query = "What is the capital of Germany?"
result = ask_llm(query)
print(result)Ensure your .env file is configured correctly:
OPENAI_API_KEY="your-api-key-here"Run the script, and you should see the correct response: The capital of Germany is Berlin.
LLMs process structured message history to maintain context. Consider the following JSON format, which includes user queries and assistant responses:
[
{"role": "system", "content": "You are a helpful AI assistant."},
{"role": "user", "content": "Who discovered gravity?"},
{"role": "assistant", "content": "Sir Isaac Newton discovered gravity."},
{"role": "user", "content": "When did he make this discovery?"}
]Using structured conversations improves contextual understanding and provides more relevant responses.
A typical response from OpenAI’s chat completion API looks like this:
{
"id": "chatcmpl-123456789",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "The capital of Germany is Berlin."
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 50,
"completion_tokens": 20,
"total_tokens": 70
}
}Key Elements:
Experiment with different settings to find what works best for your use case.
Integrating OpenAI’s LLMs into applications is straightforward when following best practices. By setting up a secure environment, structuring messages effectively, and optimizing API calls, you can maximize efficiency while minimizing costs.
In future posts, we will explore using open-source LLMs for greater customization and flexibility. Stay tuned!