Python 调用示例
本教程提供多种 Python 调用 ClaudeHub API 的方法。
使用 requests 库
最简单的调用方式,无需额外依赖。
安装
bash
pip install requests基本调用
python
import requests
url = "https://api.qinzhiai.com/v1/chat/completions"
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer sk-你的APIKey"
}
data = {
"model": "gpt-4o",
"messages": [
{"role": "user", "content": "你好!"}
]
}
response = requests.post(url, headers=headers, json=data)
result = response.json()
print(result["choices"][0]["message"]["content"])流式调用
python
import requests
import json
def stream_chat(message):
url = "https://api.qinzhiai.com/v1/chat/completions"
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer sk-你的APIKey"
}
data = {
"model": "gpt-4o",
"messages": [{"role": "user", "content": message}],
"stream": True
}
response = requests.post(url, headers=headers, json=data, stream=True)
for line in response.iter_lines():
if line:
line = line.decode('utf-8')
if line.startswith('data: '):
data = line[6:]
if data != '[DONE]':
chunk = json.loads(data)
content = chunk['choices'][0]['delta'].get('content', '')
print(content, end='', flush=True)
stream_chat("写一首关于春天的诗")使用 httpx(异步)
适合需要异步调用的场景。
python
import httpx
import asyncio
async def async_chat(message):
url = "https://api.qinzhiai.com/v1/chat/completions"
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer sk-你的APIKey"
}
data = {
"model": "gpt-4o",
"messages": [{"role": "user", "content": message}]
}
async with httpx.AsyncClient() as client:
response = await client.post(url, headers=headers, json=data)
result = response.json()
return result["choices"][0]["message"]["content"]
# 使用
result = asyncio.run(async_chat("你好"))
print(result)使用 Claude 原生格式
调用 Claude 模型时,可以使用 Anthropic 原生格式:
python
import requests
url = "https://api.qinzhiai.com/v1/messages"
headers = {
"Content-Type": "application/json",
"x-api-key": "sk-你的APIKey",
"anthropic-version": "2023-06-01"
}
data = {
"model": "claude-sonnet-4-20250514",
"max_tokens": 1024,
"messages": [
{"role": "user", "content": "你好!"}
]
}
response = requests.post(url, headers=headers, json=data)
result = response.json()
print(result["content"][0]["text"])错误处理
python
import requests
def safe_chat(message):
try:
url = "https://api.qinzhiai.com/v1/chat/completions"
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer sk-你的APIKey"
}
data = {
"model": "gpt-4o",
"messages": [{"role": "user", "content": message}]
}
response = requests.post(url, headers=headers, json=data, timeout=60)
response.raise_for_status()
return response.json()["choices"][0]["message"]["content"]
except requests.exceptions.Timeout:
return "请求超时,请重试"
except requests.exceptions.HTTPError as e:
return f"HTTP 错误: {e.response.status_code}"
except Exception as e:
return f"错误: {str(e)}"常见问题
Q: SSL 证书错误
A: 更新 certifi 包:pip install --upgrade certifi
Q: 响应乱码
A: 确保正确处理 UTF-8 编码:response.encoding = 'utf-8'
