|
import requests |
|
import json |
|
import sseclient |
|
|
|
def test_non_stream_chat(): |
|
"""测试非流式调用 /api/chat 接口""" |
|
url = "http://localhost:9621/api/chat" |
|
|
|
|
|
data = { |
|
"model": "lightrag:latest", |
|
"messages": [ |
|
{ |
|
"role": "user", |
|
"content": "孙悟空" |
|
} |
|
], |
|
"stream": False |
|
} |
|
|
|
|
|
response = requests.post(url, json=data) |
|
|
|
|
|
print("\n=== 非流式调用响应 ===") |
|
response_json = response.json() |
|
|
|
|
|
print("=== 响应内容 ===") |
|
print(json.dumps({ |
|
"model": response_json["model"], |
|
"message": response_json["message"] |
|
}, ensure_ascii=False, indent=2)) |
|
|
|
|
|
print("\n=== 性能统计 ===") |
|
stats = { |
|
"total_duration": response_json["total_duration"], |
|
"load_duration": response_json["load_duration"], |
|
"prompt_eval_count": response_json["prompt_eval_count"], |
|
"prompt_eval_duration": response_json["prompt_eval_duration"], |
|
"eval_count": response_json["eval_count"], |
|
"eval_duration": response_json["eval_duration"] |
|
} |
|
print(json.dumps(stats, ensure_ascii=False, indent=2)) |
|
|
|
def test_stream_chat(): |
|
"""测试流式调用 /api/chat 接口""" |
|
url = "http://localhost:9621/api/chat" |
|
|
|
|
|
data = { |
|
"model": "lightrag:latest", |
|
"messages": [ |
|
{ |
|
"role": "user", |
|
"content": "孙悟空有什么法力,性格特征是什么" |
|
} |
|
], |
|
"stream": True |
|
} |
|
|
|
|
|
response = requests.post(url, json=data, stream=True) |
|
client = sseclient.SSEClient(response) |
|
|
|
print("\n=== 流式调用响应 ===") |
|
output_buffer = [] |
|
try: |
|
for event in client.events(): |
|
try: |
|
data = json.loads(event.data) |
|
if data.get("done", False): |
|
if "total_duration" in data: |
|
print("\n=== 性能统计 ===") |
|
print(json.dumps(data, ensure_ascii=False, indent=2)) |
|
break |
|
else: |
|
message = data.get("message", {}) |
|
content = message.get("content", "") |
|
if content: |
|
output_buffer.append(content) |
|
except json.JSONDecodeError: |
|
print("Error decoding JSON from SSE event") |
|
finally: |
|
response.close() |
|
|
|
|
|
print("".join(output_buffer)) |
|
|
|
if __name__ == "__main__": |
|
|
|
test_non_stream_chat() |
|
|
|
|
|
test_stream_chat() |
|
|