Files
ETH_TCP_Demo/tools/test_ai_api.py
2026-03-04 17:07:08 +08:00

69 lines
1.7 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
API测试模块
功能:
- 测试OpenRouter AI API的调用
- 验证API响应是否正常
- 提供简单的测试接口
依赖:
- requests
"""
import requests
import json
def test_openrouter_api():
"""测试OpenRouter AI API"""
# API配置
api_key = "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"
url = "https://openrouter.ai/api/v1/chat/completions"
model = "arcee-ai/trinity-large-preview:free"
# 请求体
payload = {
"model": model,
"messages": [
{
"role": "system",
"content": "中文对话"
},
{
"role": "user",
"content": "你好"
}
],
"temperature": 0.7
}
# 请求头
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}"
}
try:
# 发送请求
response = requests.post(url, json=payload, headers=headers)
# 检查响应状态码
if response.status_code == 200:
# 解析响应
result = response.json()
print("API调用成功")
print(f"响应时间: {response.elapsed.total_seconds():.2f}")
print(f"生成的内容: {result['choices'][0]['message']['content']}")
return True
else:
print(f"API调用失败状态码: {response.status_code}")
print(f"错误信息: {response.text}")
return False
except Exception as e:
print(f"请求发生错误: {str(e)}")
return False
if __name__ == "__main__":
test_openrouter_api()