-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_claude_api.py
More file actions
61 lines (53 loc) · 2.1 KB
/
test_claude_api.py
File metadata and controls
61 lines (53 loc) · 2.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import requests
import json
# API 端点
api_url = "https://xxxx/v1/chat/completions"
# API 密钥
api_key = "xxxx"
# 构建请求头
headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
# 构建请求体 (OpenAI 格式)
data = {
"model": "claude-3-5-sonnet-20240620",
"messages": [{"role": "user", "content": "你好,请用中文回答:今天天气怎么样?"}],
"temperature": 0.7,
"stream": True,
}
# 打印请求信息,便于调试
print(f"请求URL: {api_url}")
print(f"请求头: {json.dumps(headers, indent=2)}")
print(f"请求体: {json.dumps(data, indent=2)}")
try:
# 发送请求
response = requests.post(api_url, headers=headers, json=data, stream=True)
# 打印响应状态码
print(f"响应状态码: {response.status_code}")
if response.status_code == 200:
# 处理流式响应
print("收到流式响应:")
for line in response.iter_lines():
if line:
decoded_line = line.decode("utf-8")
if decoded_line.startswith("data: "):
content = decoded_line[6:] # 移除 'data: ' 前缀
if content == "[DONE]":
print("响应完成")
else:
try:
json_content = json.loads(content)
if (
"choices" in json_content
and len(json_content["choices"]) > 0
):
choice = json_content["choices"][0]
if "delta" in choice and "content" in choice["delta"]:
print(
choice["delta"]["content"], end="", flush=True
)
except json.JSONDecodeError:
print(f"无法解析JSON: {content}")
else:
# 打印错误信息
print(f"错误响应: {response.text}")
except Exception as e:
print(f"请求发生错误: {e}")