OpenAI SDK 使用教程
本教程介绍如何使用 OpenAI 官方 SDK 接入 ClaudeHub API。
Python SDK
安装
bash
pip install openai基本使用
python
from openai import OpenAI
client = OpenAI(
api_key="sk-你的APIKey",
base_url="https://api.qinzhiai.com/v1"
)
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "你是一个有帮助的助手。"},
{"role": "user", "content": "你好!"}
]
)
print(response.choices[0].message.content)流式输出
python
stream = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "user", "content": "写一首诗"}
],
stream=True
)
for chunk in stream:
if chunk.choices[0].delta.content is not None:
print(chunk.choices[0].delta.content, end="")图片分析
python
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "描述这张图片"},
{
"type": "image_url",
"image_url": {
"url": "https://example.com/image.jpg"
}
}
]
}
]
)Node.js SDK
安装
bash
npm install openai基本使用
javascript
import OpenAI from 'openai';
const client = new OpenAI({
apiKey: 'sk-你的APIKey',
baseURL: 'https://api.qinzhiai.com/v1'
});
async function main() {
const response = await client.chat.completions.create({
model: 'gpt-4o',
messages: [
{ role: 'user', content: '你好!' }
]
});
console.log(response.choices[0].message.content);
}
main();流式输出
javascript
const stream = await client.chat.completions.create({
model: 'gpt-4o',
messages: [{ role: 'user', content: '写一个故事' }],
stream: true
});
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0]?.delta?.content || '');
}函数调用
python
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "获取指定城市的天气",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "城市名称"
}
},
"required": ["city"]
}
}
}
]
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "北京今天天气怎么样?"}],
tools=tools
)常见问题
Q: 连接超时
A: 检查网络设置,或设置更长的超时时间:
python
client = OpenAI(
api_key="sk-xxx",
base_url="https://api.qinzhiai.com/v1",
timeout=60.0
)Q: 编码问题
A: 确保使用 UTF-8 编码处理响应内容。
