AI API Development
AI API Development
Using the AI chat tool in the web interface is convenient, but to truly integrate AI capabilities into your own products, workflows, or automation scripts, you need an API.
API (Application Programming Interface) is a bridge for communication between applications; through an API, your code can directly send requests to the AI model and receive responses without manually opening a webpage to copy and paste.
Imagine these scenarios:
-
Your e-commerce website automatically generates product descriptions for every item.
-
Your note-taking app automatically summarizes long texts entered by users.
-
Your customer service system automatically classifies and replies to user inquiries.
-
These functions can all be implemented through AI APIs.
The goal of this module is to help you transition from "only using AI for chatting" to "making AI work within your code."
API Fundamentals
Before writing code, first understand a few core concepts.
What is an API
An API is a set of agreed-upon communication methods; we send requests in a specific format, and the other party returns results in a specific format.
To use a dining analogy:
-
You walk into a restaurant and get a menu (API documentation), knowing what you can order and how to order it (request format).
-
You tell the waiter: one Kung Pao Chicken, less spicy (sending an API request).
-
The kitchen prepares the dish and brings it to you (returning an API response).
In this process, you don't need to go into the kitchen or know how the dish is made—this is the value of an API: encapsulating complex details and only exposing a simple interface.
Basic principles of REST API
REST (Representational State Transfer) is the most popular API design style currently.
Simply put, it is communicating using the HTTP protocol:
| HTTP Methods | Purpose | Examples in AI APIs |
|---|---|---|
| POST | Create resources | Send chat requests, generate images |
| GET | Get resources | Query model list, get billing information |
| DELETE | Delete resources | Delete conversation history |
Most AI APIs are POST requests because we need to "send content to the AI for processing".
JSON format introduction
JSON (JavaScript Object Notation) is the most commonly used data format for API communication.
The syntax of JSON is simple, which is a combination of key-value pairs.
Example
{
"model"
:
"gpt-4"
,
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Hello, please introduce RUNOOB"
}
]
,
"temperature"
:
0.7
,
"max_tokens"
:
1000
}
This is a typical AI API request body.
Several core rules:
-
Objects are wrapped with
{ }Arrays are wrapped with.[ ]Strings use double quotes -
, not single quotes.
"Key-value pairs are separated by a colon, and keys must be strings. -
Key-value pairs use a colon
:Separator, the key must be a string. -
Multiple key-value pairs separated by commas.
,Separation.
JSON looks similar to Python dictionaries, but there are syntax differences to be aware of when writing code.
Development environment setup
A journey of a thousand miles begins with a single step.
Python installation and configuration
Python is the most commonly used language for calling AI APIs, with a complete ecosystem and rich libraries.
First, check if you have Python installed on your computer:
Original prompt (Chinese, left untranslated)
# Check Python version (Universal for Windows, macOS, Linux)
python --version
# 或者
python3 --version
It is recommended to use Python 3.9 or higher.
If you haven't installed it yet, download the latest stable version from python.org.
pip package management
pip is Python's package manager, used to install third-party libraries.
Original prompt (Chinese, left untranslated)
# Check pip version
pip --version
# 或者
pip3 --version
# Upgrade pip to the latest version
pip install --upgrade pip
# Configure domestic mirror source (optional, improve download speed)
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
Code editor selection
For writing AI API code, one of the following editors is recommended:
| Editor | Features | Target audience |
|---|---|---|
| VS Code | Free, rich in plugins, lightweight | Most developers |
| Cursor | Built-in AI assistance, can directly generate code | Want AI to help write code |
| PyCharm | Most comprehensive features, best Python support | Professional Python Developer |
The example code in this tutorial can run in any editor.
Introduction to OpenAI API
OpenAI API is the most classic and best-developed AI API, and many other vendors are compatible with its format.
Registration and Obtaining API Key
The API Key is your pass, proving your identity, recording your usage. Steps:
-
1. Visit platform.openai.com to register an account
-
2. Go to the API Keys page
-
3. Click "Create new secret key"
-
4. Copy and save this Key (displayed only once!)
Important:Never commit the API Key to a public code repository.Once leaked, others may use your quota and incur charges.
First API call
First, install the official OpenAI SDK:
pip install openai
Now write the first API call program:
Example
File path: first_api_call.py
First OpenAI API call example
from
openai
import
OpenAI
Initialize client
Note: It is recommended to read the API Key from an environment variable, and not hardcode it in the code
This is written directly for demonstration convenience; please use environment variables in actual projects
client
=
OpenAI
(
api_key
=
"your-api-key-here"
Replace with your API Key
)
Send chat request
response
=
client.
chat
.
completions
.
create
(
model
=
"gpt-3.5-turbo"
,
Select model
messages
=
[
{
"role"
:
"user"
,
Role: user indicates the user
"content"
:
"Please introduce the RUNOOB beginner tutorial in one sentence"
User input content
}
]
)
Print the full response (see what was returned)
(
"Full response:"
)
(
response
)
(
"\n"
"="
50
"\n"
)
Extract AI's reply
ai_reply
=
response.
choices
[
0
]
.
message
.
content
(
"AI Reply:"
)
(
ai_reply
)
If you do not have an OpenAI api_key, you can also use a domestic alternative. Many domestic models are compatible with OpenAI, such as DeepSeek. You can apply for an api_key and then replace your api_key and model in the following code. DeepSeek supports the models deepseek-v4-flash and deepseek-v4-pro (thinking mode) for API calls to large models:https://platform.deepseek.com/api_keysApply for an api_key, then replace your api_key and model in the following code. DeepSeek supports the models deepseek-v4-flash and deepseek-v4-pro (thinking mode) for API calls to large models:
Instance
from
openai
import
OpenAI
Initialize client
Note: It is recommended to read the API Key from environment variables and not hardcode it in the code.
Here it is written directly for demonstration convenience; please use environment variables in actual projects.
client
=
OpenAI
(
api_key
=
"sk-xxxx"
,
Set api_key
base_url
=
"https://api.deepseek.com"
)
Set request address
Send chat request
response
=
client.
chat
.
completions
.
create
(
model
=
"deepseek-v4-flash"
,
Select model
messages
=
[
{
"role"
:
"user"
,
Role: user indicates the user
"content"
:
"Please introduce the RUNOOB beginner tutorial in one sentence"
User input content
}
]
)
Print the full response (see what was returned)
(
"Full response:"
)
(
response
)
(
"\n"
"="
50
"\n"
)
Extract AI's response
ai_reply
=
response.
choices
[
0
]
.
message
.
content
(
"AI Reply:"
)
(
ai_reply
)
Run this program:
python first_api_call.py
If everything is normal, you will see output similar to this:
Original prompt (Chinese, left untranslated)
Full response:
ChatCompletion(
id='chatcmpl-xxx',
choices=[Choice(finish_reason='stop', index=0, message=ChatMessage(content='RUNOOB 菜鸟教程是一个专注于提供编程技术教程的学习平台...', role='assistant'))],
model='gpt-3.5-turbo',
usage=CompletionUsage(completion_tokens=30, prompt_tokens=18, total_tokens=48)
)
==================================================
AI 回复:
RUNOOB 菜鸟教程是一个专注于提供编程技术教程的学习平台,涵盖多种编程语言和技术领域。
Congratulations! You have successfully called the AI API once.
Request parameter details
The OpenAI API has many parameters that can be adjusted; here are some of the most commonly used ones:
| Parameter name | Type | Required | Description | Default value |
|---|---|---|---|---|
| model | string | Yes | Model ID used, such as gpt-3.5-turbo, gpt-4 | None |
| messages | array | is | list of conversation history messages | None |
| temperature | number | No | Sampling temperature, between 0 and 2, higher means more random, lower means more deterministic | 1.0 |
| max_tokens | integer | No | Maximum number of tokens to generate | Unlimited |
| top_p | number | No | Nucleus sampling parameter, between 0 and 1 | 1.0 |
| stop | string/array | No | Stop the sequence, stop generating when these characters are encountered | null |
Focus on temperature, this is the most commonly used tuning parameter:
Example
File path: temperature_demo.py
Demonstrates the effect of the temperature parameter on the output
from
openai
import
OpenAI
client
=
OpenAI
(
api_key
=
"your-api-key-here"
)
def
ask_ai
(
temperature_value:
float
,
question:
str
)
str
:
"""Specify temperature question"""
response
=
client.
chat
.
completions
.
create
(
model
=
"gpt-3.5-turbo"
,
messages
=
[
{
"role"
:
"user"
,
"content"
: question
}
]
,
temperature
=
temperature_value
,
max_tokens
=
200
)
return
response.
choices
[
0
]
.
message
.
content
Ask the same question three times with different temperatures
question
=
"Create a slogan for RUNOOB"
(
"--- temperature=0 (most certain, results are similar each time) ---"
)
(
ask_ai
(
0.0
,
question
)
)
(
"\n--- temperature=0.7 (balanced, recommended for daily use) ---"
)
(
ask_ai
(
0.7
,
question
)
)
(
"\n--- temperature=1.8 (most random, large difference in results each time) ---"
)
(
ask_ai
(
1.8
,
question
)
)
A rule of thumb:
-
temperature=0: factual answers, code generation, scenarios requiring precise results
-
temperature=0.7: daily conversations, general tasks
-
temperature>1.0: creative writing, brainstorming
Anthropic Claude API
Claude is a large model from Anthropic, known for its safety and long text processing capabilities.
Differences and similarities with the OpenAI API
Both can perform text generation, but their design philosophies are somewhat different:
| Comparison items | OpenAI API | Claude API |
|---|---|---|
| Message structure | Alternating system, user, assistant | System set separately, alternating user, assistant |
| Context length | 16k-128k and so on | Claude 3 series supports 200k |
| Parameter design | temperature, top_p, etc. | temperature, top_p, etc., concepts are similar |
Claude Messages API structure
First install the Claude SDK:
pip install anthropic
Basic calls to the Claude API:
Instance
File path: claude_first_call.py
Basic Claude API call example
import
anthropic
Initialize client
client
=
anthropic.
Anthropic
(
api_key
=
"your-api-key-here"
Replace with your Claude API Key
)
Send message request
response
=
client.
messages
.
create
(
model
=
"claude-3-sonnet-20240229"
,
Select Claude model
max_tokens
=
1024
,
Claude requires setting max_tokens
messages
=
[
{
"role"
:
"user"
,
"content"
:
"Please introduce the RUNOOB beginner tutorial in three sentences."
}
]
)
Print response
(
"Full response:"
)
(
response
)
(
"\n"
"="
50
"\n"
)
Extract reply
(
"Claude reply:"
)
(
response.
content
[
0
]
.
text
)
Similarly, we can replace it with a domestically compatible large model, such as DeepSeek, by specifying the three parameters: api_key, base_url, and model:
Instance
import
anthropic
Initialize client
client
=
anthropic.
Anthropic
(
api_key
=
"sk-xxx"
,
Replace with your API Key
base_url
=
"https://api.deepseek.com/anthropic"
Claude API base URL
)
Send message request
response
=
client.
messages
.
create
(
model
=
"deepseek-v4-flash"
,
Select Claude model
max_tokens
=
1024
,
Claude requires max_tokens to be set
messages
=
[
{
"role"
:
"user"
,
"content"
:
"Please introduce the RUNOOB beginner tutorial in three sentences."
}
]
)
Print response
(
"Full response:"
)
(
response
)
(
"\n"
"="
50
"\n"
)
Extract reply
(
"Claude reply:"
)
(
response.
content
[
0
]
.
thinking
)
System Prompt Settings
In the Claude API, the System Prompt is a separate parameter and is not placed in the messages array:
Example
File path: claude_system_prompt.py
Example of using Claude System Prompt
import
anthropic
client
=
anthropic.
Anthropic
(
api_key
=
"your-api-key-here"
)
response
=
client.
messages
.
create
(
model
=
"claude-3-sonnet-20240229"
,
max_tokens
=
1024
,
Set the System Prompt here
system
=
"You are a professional technical documentation editor, and your answers must be concise and accurate, using lists as much as possible."
,
messages
=
[
{
"role"
:
"user"
,
"content"
:
"What core knowledge points should I master to learn Python?"
}
]
)
(
response.
content
[
0
]
.
text
)
Multi-turn dialogue management
Single-turn dialogue is simple, but truly useful applications require "remembering context".
How to maintain dialogue history
The logic is simple: save all previous conversations and send them to the AI with each request.
Example
File path: multi_turn_chat.py
Multi-turn chat management example
from
openai
import
OpenAI
client
=
OpenAI
(
api_key
=
"your-api-key-here"
)
class
ChatBot:
"""A simple multi-turn dialogue robot"""
def
init
(
self
,
system_prompt:
str
=
"You are a helpful assistant"
)
:
self
.
messages
=
[
]
Save conversation history using a list
First add the system prompt
self
.
messages
.
append
(
{
"role"
:
"system"
,
"content"
: system_prompt
}
)
def
chat
(
self
,
user_input:
str
)
str
:
"""Send a message and get a reply"""
Add user message to history
self
.
messages
.
append
(
{
"role"
:
"user"
,
"content"
: user_input
}
)
Call API
response
=
client.
chat
.
completions
.
create
(
model
=
"gpt-3.5-turbo"
,
messages
=
self
.
messages
)
Get AI response
ai_reply
=
response.
choices
[
0
]
.
message
.
content
Add AI replies to history as well
self
.
messages
.
append
(
{
"role"
:
"assistant"
,
"content"
: ai_reply
}
)
return
ai_reply
def
get_history
(
self
)
list
:
"""Get conversation history"""
return
self
.
messages
Usage example
if
name
==
"main"
:
bot
=
ChatBot
(
system_prompt
=
You are a programming assistant specialized in answering questions about RUNOOB and Python
)
(
"=== Multi-turn conversation demonstration ==="
)
Round 1
r1
=
bot.
chat
(
"What is Python?"
)
(
"User: What is Python?"
)
(
"AI:"
,
r1
)
(
)
Second round (AI can remember the topic of the previous round)
r2
=
bot.
chat
(
"What are its characteristics?"
)
(
"User: What are its features?"
)
(
"AI:"
,
r2
)
(
)
Third round
r3
=
bot.
chat
(
Is there a Python tutorial on RUNOOB?
)
(
"User: Is there a Python tutorial on RUNOOB?"
)
(
"AI:"
,
r3
)
Key point: The conversation history is an ordered list, strictly alternating between user-assistant-user-assistant. The complete history must be sent with every request for the AI to understand the context. History consumes tokens, so it needs to be cleaned up periodically.
Context window overflow handling
Each model has a context window limit, for example, gpt-3.5-turbo is 16k, and gpt-4 is 8k or 32k.
An error will be triggered when the conversation history is too long.
Several common handling strategies:
Instance
File path: context_management.py
Example of context window management strategy
from
openai
import
OpenAI
client
=
OpenAI
(
api_key
=
"your-api-key-here"
)
class
ChatBotWithContextLimit:
"""Chatbot with context limit"""
def
init
(
self
,
system_prompt:
str
,
max_messages:
int
=
10
)
:
self
.
system_prompt
=
system_prompt
self
.
max_messages
=
max_messages
Maximum number of messages to retain
self
.
messages
=
[
]
def
_trim_messages
(
self
)
:
"Trim the message list, keeping the most recent messages"
Always keep the system prompt, then only keep the most recent max_messages
if
len
(
self
.
messages
)
self
.
max_messages
:
Keep the last N entries
self
.
messages
=
self
.
messages
[
self
.
max_messages
:
]
def
chat
(
self
,
user_input:
str
)
str
:
Add user message
self
.
messages
.
append
(
{
"role"
:
"user"
,
"content"
: user_input
}
)
Trim history
self
._trim_messages
(
)
Construct the complete request (system prompt + history)
full_messages
=
[
{
"role"
:
"system"
,
"content"
:
self
.
system_prompt
}
]
self
.
messages
try
:
response
=
client.
chat
.
completions
.
create
(
model
=
"gpt-3.5-turbo"
,
messages
=
full_messages
)
ai_reply
=
response.
choices
[
0
]
.
message
.
content
self
.
messages
.
append
(
{
"role"
:
"assistant"
,
"content"
: ai_reply
}
)
return
ai_reply
except
Exception
as
e:
If it still throws an error, more aggressive pruning may be required
return
f
"An error occurred: {str(e)}"
Strategy two: Use AI to summarize the conversation history
def
summarize_conversation
(
messages:
list
)
str
:
"""Use AI to summarize the history conversation, replacing the original history"""
history_text
=
"\n"
.
join
(
[
f
"{m['role']}: {m['content']}"
for
m
in
messages
]
)
prompt
=
f
"""Please summarize the following conversation into a concise abstract, retaining key information:
{history_text}
Abstract:"""
response
=
client.
chat
.
completions
.
create
(
model
=
"gpt-3.5-turbo"
,
messages
=
[
{
"role"
:
"user"
,
"content"
: prompt
}
]
,
temperature
=
0
)
return
response.
choices
[
0
]
.
message
.
content
Use summary strategy
(
"--- Conversation history summary example ---"
)
sample_history
=
[
{
"role"
:
"user"
,
"content"
:
"What is my name?"
}
,
{
"role"
:
"assistant"
,
"content"
:
"Sorry, I don't know your name, can you tell me."
}
,
{
"role"
:
"user"
,
"content"
:
"My name is Xiaoming, and I am learning Python on RUNOOB."
}
,
{
"role"
:
"assistant"
,
"content"
:
"Hello Xiao Ming! Nice to meet you. RUNOOB is a great learning platform."
}
,
{
"role"
:
"user"
,
"content"
:
"I want to learn about lists, can you teach me?"
}
,
{
"role"
:
"assistant"
,
"content"
:
Of course! Python lists are...
}
,
]
summary
=
summarize_conversation
(
sample_history
)
(
"Conversation summary:"
,
summary
)
Summarize the context management methods:
| Strategy | Advantages | Disadvantages | Applicable scenarios |
|---|---|---|---|
| Keep only the last N entries | Simple, fast | Potential loss of important information | Short conversations, casual chat scenarios |
| Summarizing history with AI | Retaining semantic information | Requires additional API calls | Long conversations with a lot of important information |
| Sliding window | Balancing simplicity and completeness | Slightly complex implementation | General purpose for common scenarios |
Streaming output
When chatting with AI on a webpage, you see the text appear character by character—this is streaming output.
What is streaming output
-
Normal mode: The AI returns the complete response all at once after generating it, so you might have to wait several seconds or even tens of seconds.
-
Streaming mode: The AI sends one token at a time as it generates it, which provides a better user experience.
Technically, streaming output uses the SSE (Server-Sent Events) protocol, where the server continuously pushes data.
Implement typewriter effect
Example
File path: streaming_demo.py
Streaming output demo (typewriter effect)
from
openai
import
OpenAI
client
=
OpenAI
(
api_key
=
"your-api-key-here"
)
(
"=== Streaming Output Demo ==="
)
(
"Q: Please write an introduction about RUNOOB\n"
)
(
"Answer:"
,
end
=
""
,
flush
=
True
)
Key parameter: stream=True
response
=
client.
chat
.
completions
.
create
(
model
=
"gpt-3.5-turbo"
,
messages
=
[
{
"role"
:
"user"
,
"content"
:
"Please write an introduction about the RUNOOB beginner tutorial"
}
]
,
stream
=
True
Enable streaming output
)
collected_reply
=
[
]
for
chunk
in
response:
Extract the content of the current chunk
if
chunk
.
choices
[
0
]
.
delta
.
content
:
content
=
chunk
.
choices
[
0
]
.
delta
.
content
(
content
,
end
=
""
,
flush
=
True
)
Real-time printing, no newlines
collected_reply.
append
(
content
)
(
)
Finally output a newline
(
"\n"
"="
50
)
(
"Full reply:"
,
""
.
join
(
collected_reply
)
)
When you run this program, you will see the text appear character by character.
Claude's streaming output usage is similar:
Instance
File path: claude_streaming.py
Claude streaming output example
import
anthropic
client
=
anthropic.
Anthropic
(
api_key
=
"your-api-key-here"
)
(
"=== Claude streaming output ==="
)
(
"Question: How to learn programming?\n"
)
(
"Answer:"
,
end
=
""
,
flush
=
True
)
with
client.
messages
.
stream
(
model
=
"claude-3-sonnet-20240229"
,
max_tokens
=
1024
,
messages
=
[
{
"role"
:
"user"
,
"content"
:
How to systematically learn programming?
}
]
)
as
stream:
for
text
in
stream.
text_stream
:
(
text
,
end
=
""
,
flush
=
True
)
(
)
User experience suggestion: Unless the scenario requires "waiting for the complete result," prioritize using streaming output. Showing the user progress can significantly improve the experience.
API fee calculation and optimization
The AI API is billed based on usage, so the more you use, the more you pay.
Token Billing Principle
The AI API is not billed by word count or conversation count, but by Tokens, where a Token is the basic unit for AI text processing.
One token is approximately equal to:
-
English: 0.75 words (or 4 characters)
-
Chinese: 1-2 characters
For example:
-
"Hello, world" — approximately 3-4 tokens
-
"RUNOOB beginner tutorial is great" — approximately 6-8 tokens
Billing method:
Original prompt (Chinese, left untranslated)
Prompt tokens(你发给 AI 的) + Completion tokens(AI 返回给你的)= 总 tokens
Different models have different prices, for example, gpt-3.5-turbo is $0.0015/1k prompt tokens and $0.002/1k completion tokens.
How to control API costs
Example
File path: cost_tracking.py
API fee tracking and control example
from
openai
import
OpenAI
client
=
OpenAI
(
api_key
=
"your-api-key-here"
)
Model Price List (Example, please check official documentation for actual prices)
Unit: USD / 1k tokens
MODEL_PRICES
=
{
"gpt-3.5-turbo"
:
{
"prompt"
:
0.0015
,
"completion"
:
0.002
}
,
"gpt-4"
:
{
"prompt"
:
0.03
,
"completion"
:
0.06
}
}
def
chat_with_cost_tracking
(
model:
str
,
messages:
list
)
:
"Chat with cost statistics"
response
=
client.
chat
.
completions
.
create
(
model
=
model
,
messages
=
messages
)
Get token usage from the response
usage
=
response.
usage
prompt_tokens
=
usage.
prompt_tokens
completion_tokens
=
usage.
completion_tokens
total_tokens
=
usage.
total_tokens
Calculate cost
price
=
MODEL_PRICES.
get
(
model
,
{
"prompt"
:
0
,
"completion"
:
0
}
)
prompt_cost
=
(
prompt_tokens /
1000
)
- price
[
"prompt"
]
completion_cost
=
(
completion_tokens /
1000
)
- price
[
"completion"
]
total_cost
=
prompt_cost + completion_cost
return
{
"reply"
: response.
choices
[
0
]
.
message
.
content
,
"usage"
:
{
"prompt_tokens"
: prompt_tokens
,
"completion_tokens"
: completion_tokens
,
"total_tokens"
: total_tokens
}
,
"cost"
:
{
"prompt_cost"
: prompt_cost
,
"completion_cost"
: completion_cost
,
"total_cost"
: total_cost
}
}
Usage example
if
name
==
"main"
:
result
=
chat_with_cost_tracking
(
model
=
"gpt-3.5-turbo"
,
messages
=
[
{
"role"
:
"user"
,
"content"
:
"Introduce RUNOOB"
}
]
)
(
"AI response:"
,
result
[
"reply"
]
)
(
)
(
"Usage statistics:"
)
(
f
" Prompt tokens: {result['usage']['prompt_tokens']}"
)
(
f
" Completion tokens: {result['usage']['completion_tokens']}"
)
(
f
Total tokens: {result['usage']['total_tokens']}
)
(
)
(
"Cost statistics (USD):"
)
(
f
" Prompt cost: ${result['cost']['prompt_cost']:.6f}"
)
(
f
" Completion cost: ${result['cost']['completion_cost']:.6f}"
)
(
f
" Total cost: ${result['cost']['total_cost']:.6f}"
)
Several practical tips for cost optimization:
| Tips | How to do it | Saving ratio |
|---|---|---|
| Choose the appropriate model | Use gpt-3.5-turbo for simple tasks, no need for gpt-4 | 90%+ |
| Limit max_tokens | Set a reasonable upper limit to prevent the AI from saying too much | Depending on the situation |
| Truncate the context | Only keep necessary historical conversations | 50%+ |
| Prompts should be concise | Do not write the system prompt too long | Depending on the situation |
| Result caching | Directly return cached results for the same question | Depending on the situation |
Caching Strategy
For repeated questions, caching results can save a lot of money:
Instance
File path: response_cache.py
Simple response caching implementation
import
hashlib
import
json
from
openai
import
OpenAI
client
=
OpenAI
(
api_key
=
"your-api-key-here"
)
class
SimpleCache:
"Simple memory cache"
def
init
(
self
)
:
self
.
cache
=
{
}
def
_make_key
(
self
,
model:
str
,
messages:
list
)
str
:
"""Generates a cache key based on the request content"""
Serialize key information and take the hash
key_data
=
{
"model"
: model
,
"messages"
: messages
}
key_str
=
json.
dumps
(
key_data
,
sort_keys
=
True
)
return
hashlib.
md5
(
key_str.
encode
(
)
)
.
hexdigest
(
)
def
get
(
self
,
model:
str
,
messages:
list
)
:
"""Get cache"""
key
=
self
._make_key
(
model
,
messages
)
return
self
.
cache
.
get
(
key
)
def
set
(
self
,
model:
str
,
messages:
list
,
value:
str
)
:
"""Set cache"""
key
=
self
._make_key
(
model
,
messages
)
self
.
cache
[
key
]
=
value
Chat function with cache
cache
=
SimpleCache
(
)
def
chat_with_cache
(
model:
str
,
messages:
list
)
:
First check cache
cached
=
cache.
get
(
model
,
messages
)
if
cached:
(
"Cache hit, returning directly"
)
return
cached
Cache miss, calling API
response
=
client.
chat
.
completions
.
create
(
model
=
model
,
messages
=
messages
)
reply
=
response.
choices
[
0
]
.
message
.
content
Store in cache
cache.
set
(
model
,
messages
,
reply
)
return
reply
test
if
name
==
"main"
:
messages
=
[
{
"role"
:
"user"
,
"content"
:
What is the RUNOOB website?
}
]
(
"First call..."
)
r1
=
chat_with_cache
(
"gpt-3.5-turbo"
,
messages
)
(
r1
)
(
)
(
"Second call (same question)..."
)
r2
=
chat_with_cache
(
"gpt-3.5-turbo"
,
messages
)
(
r2
)
Error Handling and Retry Mechanism
Network requests will always fail, and APIs are no exception. Robust code must handle various exception scenarios.
Common Error Types
| Error Type | HTTP Status Code | Reason | Handling Method |
|---|---|---|---|
| Authentication Failed | 401 | API Key is incorrect or expired | Check API Key |
| Insufficient quota | 402 | Account has no money | Recharge or change account |
| Exceeded limit | 429 | Request too fast or quota exhausted | Try again later |
| Server error | 5xx | AI service backend issue | Retry |
Exponential backoff retry
When encountering temporary errors (such as 429, 5xx), the most common strategy is exponential backoff retry:
-
First failure -> wait 1 second -> retry
-
Second failure -> wait 2 seconds -> retry
-
Third failure -> wait 4 seconds -> retry
-
Fourth failure -> Wait 8 seconds -> Retry
The waiting time doubles each time, giving the service a chance to recover.
Instance
File path: error_handling.py
Error handling and exponential backoff retry
import
time
from
openai
import
OpenAI
,
APIError
,
RateLimitError
,
APIConnectionError
client
=
OpenAI
(
api_key
=
"your-api-key-here"
)
def
chat_with_retry
(
model:
str
,
messages:
list
,
max_retries:
int
=
3
,
initial_wait:
float
=
1.0
)
:
"""Chat function with retry mechanism"""
retries
=
0
while
retries
<=
max_retries:
try
:
response
=
client.
chat
.
completions
.
create
(
model
=
model
,
messages
=
messages
)
return
{
"success"
:
True
,
"reply"
: response.
choices
[
0
]
.
message
.
content
}
except
RateLimitError
as
e:
Rate limit error: please try again later
retries +
=
1
if
retries
max_retries:
return
{
"success"
:
False
,
"error"
: f
"Retry attempts exhausted: {str(e)}"
}
wait_time
=
initial_wait *
(
2
**
(
retries -
1
)
)
(
f
"Rate limit triggered, retrying in {wait_time} seconds..."
)
time
.
sleep
(
wait_time
)
except
APIConnectionError
as
e:
Network connection error: Retry
retries +
=
1
if
retries
max_retries:
return
{
"success"
:
False
,
"error"
: f
"Network connection failed: {str(e)}"
}
wait_time
=
initial_wait *
(
2
**
(
retries -
1
)
)
(
f
"Network error, retrying in {wait_time} seconds..."
)
time
.
sleep
(
wait_time
)
except
APIError
as
e:
API error: Retry as needed
if
e.
status_code
and
500
<=
e.
status_code
<
600
:
retries +
=
1
if
retries
max_retries:
return
{
"success"
:
False
,
"error"
: f
"Server error: {str(e)}"
}
wait_time
=
initial_wait *
(
2
**
(
retries -
1
)
)
(
f
"Server error, retrying in {wait_time} seconds..."
)
time
.
sleep
(
wait_time
)
else
:
Non-5xx error, no retry
return
{
"success"
:
False
,
"error"
: f
"API Error: {str(e)}"
}
except
Exception
as
e:
Other errors, no retry
return
{
"success"
:
False
,
"error"
: f
"Unknown error: {str(e)}"
}
Usage example
if
name
==
"main"
:
result
=
chat_with_retry
(
model
=
"gpt-3.5-turbo"
,
messages
=
[
{
"role"
:
"user"
,
"content"
:
"Hello, RUNOOB"
}
]
)
if
result
[
"success"
]
:
(
"Success:"
,
result
[
"reply"
]
)
else
:
(
"Failed:"
,
result
[
"error"
]
)
You can also use existing libraries to simplify retry logic, such as tenacity. Install it using the following command:
pip install tenacity
instance
File path: tenacity_demo.py
Use the tenacity library to simplify retry logic
from
tenacity
import
retry
,
stop_after_attempt
,
wait_exponential
,
retry_if_exception_type
from
openai
import
OpenAI
,
RateLimitError
,
APIError
client
=
OpenAI
(
api_key
=
"your-api-key-here"
)
@
retry
(
stop
=
stop_after_attempt
(
3
)
,
Retry at most 3 times
wait
=
wait_exponential
(
multiplier
=
1
,
min
=
1
,
max
=
10
)
,
Exponential backoff: 1, 2, 4... up to 10 seconds
retry
=
retry_if_exception_type
(
(
RateLimitError
,
APIError
)
)
Retry only for specific exceptions
)
def
chat_with_tenacity
(
model:
str
,
messages:
list
)
:
"""Implement retry using the tenacity decorator"""
response
=
client.
chat
.
completions
.
create
(
model
=
model
,
messages
=
messages
)
return
response.
choices
[
0
]
.
message
.
content
Usage
try
:
reply
=
chat_with_tenacity
(
"gpt-3.5-turbo"
,
[
{
"role"
:
"user"
,
"content"
:
"Introduce RUNOOB"
}
]
)
(
reply
)
except
Exception
as
e:
(
f
"Final failure: {e}"
)
Practical Project: Command-Line AI Chat Tool
Now, integrate the knowledge learned previously to create a complete command-line chat tool.
Example
File Path: runoob_chatbot.py
RUNOOB AI Chatbot - Complete Command-Line Tool
import
sys
import
json
import
os
from
datetime
import
datetime
from
openai
import
OpenAI
class
RunoobChatBot:
"""A fully functional command-line chatbot"""
def
init
(
self
,
config_file:
str
=
"config.json"
)
:
Load configuration
self
.
config
=
self
._load_config
(
config_file
)
self
.
client
=
OpenAI
(
api_key
=
self
.
config
[
"api_key"
]
)
Conversation state
self
.
messages
=
[
]
self
.
total_tokens
=
0
self
.
total_cost
=
0.0
Initialize system prompt
self
._init_system_prompt
(
)
def
_load_config
(
self
,
config_file:
str
)
dict
:
"""Load configuration file"""
default_config
=
{
"api_key"
:
"your-api-key-here"
,
"model"
:
"gpt-3.5-turbo"
,
"system_prompt"
:
"You are a helpful AI assistant provided by RUNOOB Technical Support."
,
"max_history"
:
20
,
"stream"
:
True
,
"temperature"
:
0.7
}
if
os
.
path
.
exists
(
config_file
)
:
with
open
(
config_file
,
"r"
,
encoding
=
"utf-8"
)
as
f:
user_config
=
json.
load
(
f
)
default_config.
update
(
user_config
)
return
default_config
def
_save_config
(
self
,
config_file:
str
=
"config.json"
)
:
"""Save configuration file"""
with
open
(
config_file
,
"w"
,
encoding
=
"utf-8"
)
as
f:
json.
dump
(
self
.
config
,
f
,
indent
=
2
,
ensure_ascii
=
False
)
def
_init_system_prompt
(
self
)
:
"""Initialize system prompt"""
self
.
messages
=
[
{
"role"
:
"system"
,
"content"
:
self
.
config
[
"system_prompt"
]
}
]
def
_trim_history
(
self
)
:
"""Trim conversation history"""
Keep system prompt + the last N messages
max_messages
=
self
.
config
[
"max_history"
]
if
len
(
self
.
messages
)
max_messages +
1
:
self
.
messages
=
[
self
.
messages
[
0
]
]
self
.
messages
[
-max_messages:
]
def
chat
(
self
,
user_input:
str
)
str
:
"""Send a message and get a reply"""
Add user message
self
.
messages
.
append
(
{
"role"
:
"user"
,
"content"
: user_input
}
)
Crop history
self
._trim_history
(
)
if
self
.
config
[
"stream"
]
:
return
self
._chat_stream
(
)
else
:
return
self
._chat_normal
(
)
def
_chat_normal
(
self
)
str
:
"""Normal mode (non-streaming)"""
response
=
self
.
client
.
chat
.
completions
.
create
(
model
=
self
.
config
[
"model"
]
,
messages
=
self
.
messages
,
temperature
=
self
.
config
[
"temperature"
]
)
ai_reply
=
response.
choices
[
0
]
.
message
.
content
Usage statistics
if
hasattr
(
response
,
"usage"
)
:
self
.
total_tokens
=
response.
usage
.
total_tokens
Simple cost estimation (gpt-3.5-turbo price)
self
.
total_cost
=
(
response.
usage
.
total_tokens
/
1000
)
0.002
self
.
messages
.
append
(
{
"role"
:
"assistant"
,
"content"
: ai_reply
}
)
return
ai_reply
def
_chat_stream
(
self
)
str
:
"Streaming mode"
response
=
self
.
client
.
chat
.
completions
.
create
(
model
=
self
.
config
[
"model"
]
,
messages
=
self
.
messages
,
temperature
=
self
.
config
[
"temperature"
]
,
stream
=
True
)
collected_chunks
=
[
]
(
"AI:"
,
end
=
""
,
flush
=
True
)
for
chunk
in
response:
if
chunk
.
choices
[
0
]
.
delta
.
content
:
content
=
chunk
.
choices
[
0
]
.
delta
.
content
(
content
,
end
=
""
,
flush
=
True
)
collected_chunks.
append
(
content
)
(
)
ai_reply
=
""
.
join
(
collected_chunks
)
self
.
messages
.
append
(
{
"role"
:
"assistant"
,
"content"
: ai_reply
}
)
Token statistics in streaming mode require extra processing, which is simplified here
In actual projects, you can call the usage interface or estimate
self
.
total_tokens
=
len
(
ai_reply
)
//
2
Rough estimate
return
ai_reply
def
save_conversation
(
self
,
filename:
str
=
None
)
:
"""Save conversation history"""
if
not
filename:
timestamp
=
datetime
.
now
(
)
.
strftime
(
"%Y%m%d_%H%M%S"
)
filename
=
f
"conversation_{timestamp}.json"
data
=
{
"model"
:
self
.
config
[
"model"
]
,
"total_tokens"
:
self
.
total_tokens
,
"estimated_cost"
:
self
.
total_cost
,
"messages"
:
self
.
messages
,
"saved_at"
:
datetime
.
now
(
)
.
isoformat
(
)
}
with
open
(
filename
,
"w"
,
encoding
=
"utf-8"
)
as
f:
json.
dump
(
data
,
f
,
indent
=
2
,
ensure_ascii
=
False
)
return
filename
def
clear_history
(
self
)
:
"Clear conversation history"
self
._init_system_prompt
(
)
self
.
total_tokens
=
0
self
.
total_cost
=
0.0
def
show_stats
(
self
)
:
"""Display statistics"""
(
"\n"
"="
40
)
(
"Conversation statistics"
)
(
"="
40
)
(
f
"Model: {self.config['model']}"
)
(
f
"Number of messages: {len(self.messages) - 1}"
)
(
f
"Total tokens: {self.total_tokens}"
)
(
f
"Estimated cost: ${self.total_cost:.4f}"
)
(
"="
40
"\n"
)
def
print_help
(
)
:
"""Print help information"""
(
"\n"
"="
40
)
(
"RUNOOB AI Chat Tool - Command List"
)
(
"="
40
)
(
"/help - Display help"
)
(
"/clear - Clear conversation history"
)
(
"/stats - Display statistics"
)
(
"/save - Save conversation history"
)
(
"/model - Switch model"
)
(
"/temp - adjust temperature"
)
(
"/system - modify system prompt"
)
(
"/quit - Exit program"
)
(
"="
40
"\n"
)
def
main
(
)
:
(
"="
40
)
(
" RUNOOB AI Chat Tool"
)
(
"="
40
)
(
"Type /help to view commands, or type text directly to start chatting\n"
)
bot
=
RunoobChatBot
(
)
while
True
:
try
:
user_input
=
input
(
"You:"
)
.
strip
(
)
if
not
user_input:
continue
Process command
if
user_input.
startswith
(
"/"
)
:
cmd
=
user_input.
lower
(
)
if
cmd
in
[
"/quit"
,
"/exit"
,
"/q"
]
:
(
"Goodbye!"
)
break
elif
cmd
==
"/help"
:
print_help
(
)
elif
cmd
==
"/clear"
:
bot.
clear_history
(
)
(
"Conversation history has been cleared"
)
elif
cmd
==
"/stats"
:
bot.
show_stats
(
)
elif
cmd
==
"/save"
:
filename
=
bot.
save_conversation
(
)
(
f
"Conversation saved to: {filename}"
)
elif
cmd
.
startswith
(
"/model "
)
:
model
=
user_input
[
7
:
]
.
strip
(
)
bot.
config
[
"model"
]
=
model
bot._save_config
(
)
(
f
"Model switched to: {model}"
)
elif
cmd
.
startswith
(
"/temp "
)
:
try
:
temp
=
float
(
user_input
[
6
:
]
.
strip
(
)
)
if
0
<=
temp
<=
2
:
bot.
config
[
"temperature"
]
=
temp
bot._save_config
(
)
(
f
"Temperature is set to: {temp}"
)
else
:
(
"Temperature must be between 0-2"
)
except
ValueError
:
(
"Please enter a valid number"
)
elif
cmd
.
startswith
(
"/system "
)
:
system_prompt
=
user_input
[
8
:
]
.
strip
(
)
bot.
config
[
"system_prompt"
]
=
system_prompt
bot.
clear_history
(
)
bot._save_config
(
)
(
"System prompt has been updated, conversation has been reset"
)
else
:
(
Unknown command, type /help to view help
)
else
:
Normal chat
if
not
bot.
config
[
"stream"
]
:
(
"AI:"
,
end
=
""
)
bot.
chat
(
user_input
)
(
)
except
KeyboardInterrupt
:
(
"Enter /quit to exit, or continue chatting"
)
except
Exception
as
e:
(
f
"An error occurred: {e}"
)
if
name
==
"main"
:
main
(
)
Create a configuration file:
Original prompt (Chinese, left untranslated)
{
"api_key": "your-api-key-here",
"model": "gpt-3.5-turbo",
"system_prompt": "你是一个乐于助人的 AI 助手,由 RUNOOB 提供技术支持。",
"max_history": 20,
"stream": true,
"temperature": 0.7
}
You can now run this chat tool:
python runoob_chatbot.py
You will see:
Original prompt (Chinese, left untranslated)
========================================
RUNOOB AI 聊天工具
========================================
输入 /help 查看命令,直接输入文字开始聊天
你:你好
AI:你好!很高兴见到你。我是由 RUNOOB 提供技术支持的 AI 助手,有什么可以帮你的吗?
你:/stats
========================================
对话统计
========================================
模型:gpt-3.5-turbo
消息数:2
总 tokens:50
估算费用:$0.0001
========================================
你:/quit
再见!