Chapter 1: OpenAI API Deep Dive
Basic Usage
from openai import OpenAI
client = OpenAI()
response = client.chat.completions.create(
model="gpt-4",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello!"}
],
temperature=0.7,
max_tokens=150
)
print(response.choices[0].message.content)
Key Parameters
| Parameter | Purpose | Range |
|---|---|---|
| temperature | Randomness | 0-2 |
| max_tokens | Output limit | Model-dependent |
| top_p | Nucleus sampling | 0-1 |
| frequency_penalty | Repetition control | -2 to 2 |
Function Calling
response = client.chat.completions.create(
model="gpt-4",
messages=[{"role": "user", "content": "What's the weather in Paris?"}],
tools=[{
"type": "function",
"function": {
"name": "get_weather",
"parameters": {
"type": "object",
"properties": {"location": {"type": "string"}}
}
}
}]
)
Streaming
stream = client.chat.completions.create(
model="gpt-4",
messages=[{"role": "user", "content": "Tell me a story"}],
stream=True
)
for chunk in stream:
print(chunk.choices[0].delta.content, end="")