-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_client.py
More file actions
executable file
·186 lines (158 loc) · 6.68 KB
/
Copy pathtest_client.py
File metadata and controls
executable file
·186 lines (158 loc) · 6.68 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
#!/usr/bin/env python3
"""
测试客户端 - 用于测试Rovo Dev OpenAI API
"""
import asyncio
import json
import sys
from typing import Dict, Any
import httpx
class RovoAPIClient:
"""Rovo API测试客户端"""
def __init__(self, base_url: str = "http://localhost:8000", api_key: str = None):
self.base_url = base_url.rstrip('/')
self.api_key = api_key
self.headers = {
"Content-Type": "application/json"
}
if api_key:
self.headers["Authorization"] = f"Bearer {api_key}"
async def test_health(self):
"""测试健康检查"""
print("🔍 测试健康检查...")
async with httpx.AsyncClient() as client:
try:
response = await client.get(f"{self.base_url}/health")
print(f"✅ 健康检查: {response.status_code}")
print(f" 响应: {response.json()}")
return response.status_code == 200
except Exception as e:
print(f"❌ 健康检查失败: {e}")
return False
async def test_models(self):
"""测试模型列表"""
print("\n🔍 测试模型列表...")
async with httpx.AsyncClient() as client:
try:
response = await client.get(
f"{self.base_url}/v1/models",
headers=self.headers
)
print(f"✅ 模型列表: {response.status_code}")
if response.status_code == 200:
data = response.json()
print(f" 可用模型: {[model['id'] for model in data['data']]}")
else:
print(f" 错误: {response.text}")
return response.status_code == 200
except Exception as e:
print(f"❌ 模型列表测试失败: {e}")
return False
async def test_chat_completion(self, message: str = "你好,请介绍一下你自己"):
"""测试聊天完成"""
print(f"\n🔍 测试聊天完成: {message}")
payload = {
"model": "rovo-dev",
"messages": [
{"role": "user", "content": message}
],
"stream": False,
"temperature": 0.3
}
async with httpx.AsyncClient(timeout=60.0) as client:
try:
response = await client.post(
f"{self.base_url}/v1/chat/completions",
headers=self.headers,
json=payload
)
print(f"✅ 聊天完成: {response.status_code}")
if response.status_code == 200:
data = response.json()
content = data['choices'][0]['message']['content']
print(f" 响应内容: {content[:200]}...")
if 'usage' in data:
usage = data['usage']
print(f" Token使用: {usage}")
else:
print(f" 错误: {response.text}")
return response.status_code == 200
except Exception as e:
print(f"❌ 聊天完成测试失败: {e}")
return False
async def test_stream_completion(self, message: str = "请解释什么是人工智能"):
"""测试流式聊天完成"""
print(f"\n🔍 测试流式聊天完成: {message}")
payload = {
"model": "rovo-dev",
"messages": [
{"role": "user", "content": message}
],
"stream": True,
"temperature": 0.3
}
async with httpx.AsyncClient(timeout=60.0) as client:
try:
async with client.stream(
"POST",
f"{self.base_url}/v1/chat/completions",
headers=self.headers,
json=payload
) as response:
print(f"✅ 流式响应: {response.status_code}")
if response.status_code == 200:
print(" 流式内容:")
async for line in response.aiter_lines():
if line.startswith("data: "):
data_str = line[6:] # 移除 "data: " 前缀
if data_str.strip() == "[DONE]":
print(" [完成]")
break
try:
data = json.loads(data_str)
if 'choices' in data and data['choices']:
delta = data['choices'][0].get('delta', {})
if 'content' in delta:
print(delta['content'], end='', flush=True)
except json.JSONDecodeError:
continue
print() # 换行
else:
print(f" 错误: {await response.aread()}")
return response.status_code == 200
except Exception as e:
print(f"❌ 流式聊天完成测试失败: {e}")
return False
async def run_all_tests(self):
"""运行所有测试"""
print("🚀 开始运行Rovo Dev OpenAI API测试...")
tests = [
self.test_health(),
self.test_models(),
self.test_chat_completion(),
self.test_stream_completion()
]
results = []
for test in tests:
result = await test
results.append(result)
print(f"\n📊 测试结果: {sum(results)}/{len(results)} 通过")
if all(results):
print("🎉 所有测试通过!")
return True
else:
print("❌ 部分测试失败")
return False
async def main():
"""主函数"""
# 从命令行参数获取配置
base_url = sys.argv[1] if len(sys.argv) > 1 else "http://localhost:8000"
api_key = sys.argv[2] if len(sys.argv) > 2 else None
if not api_key:
print("警告: 未提供API密钥,如果服务器需要认证可能会失败")
print("使用方法: python test_client.py <base_url> <api_key>")
client = RovoAPIClient(base_url, api_key)
success = await client.run_all_tests()
sys.exit(0 if success else 1)
if __name__ == "__main__":
asyncio.run(main())