You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

45 lines
1.5 KiB

1 month ago
import os
import requests
# 配置 API Key 和 URL
# API_KEY = "473ac711-84a6-4899-b35b-672e4333e269" # 从环境变量读取 API Key
API_KEY = "e0430cc0-a75f-4398-bcb2-c455344fd837"
BASE_URL = "https://ark.cn-beijing.volces.com/api/v3/chat/completions"
# 构造请求头和数据
def ask_question(question):
headers = {
"Authorization": f"Bearer {API_KEY}", # 使用 Bearer Token 授权方式 [[1]]
"Content-Type": "application/json"
}
data = {
# "model": "doubao-lite-32k-240828", # 模型名称,推荐使用 32k 版本 [[4]]
"model": "doubao-1-5-pro-32k-250115",
"messages": [
{"role": "user", "content": question}
],
"max_tokens": 4096, # 控制返回的最大 token 数
"top_p": 0.7,
# "temperature": 0.7, # 控制随机性
"stream": False # 禁用流式传输,确保一次性返回完整结果 [[10]]
}
# 发起 POST 请求
response = requests.post(BASE_URL, headers=headers, json=data)
# 检查响应状态码
if response.status_code == 200:
result = response.json()
return result.get("choices", [{}])[0].get("message", {}).get("content", "")
else:
print(f"请求失败,状态码: {response.status_code}, 错误信息: {response.text}")
return None
# 测试提问
if __name__ == "__main__":
question = "Python如何实现多线程?"
answer = ask_question(question)
if answer:
print(f"问题: {question}")
print(f"回答: {answer}")