Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

OpenAI SDK 无法与 One API 配合使用,但通过 requests 库请求正常 #2017

Open
bruce-gene opened this issue Jan 5, 2025 · 0 comments
Labels
bug Something isn't working

Comments

@bruce-gene
Copy link

Issue Title:
OpenAI SDK 无法与 One API 配合使用,但通过 requests 库请求正常

描述:
在使用最新版的 OpenAI SDK 调用 One API 时,遇到了 AuthenticationError: 无效的令牌 的问题,而通过 requests 库直接请求 One API 的接口却可以正常工作。

以下是问题的详细说明和测试代码。

问题表现:
使用 OpenAI SDK 初始化客户端并发起请求时,返回以下错误:

报错内容:
plaintext
复制代码
File "D:\web\py\CrewAITest\venv\Lib\site-packages\openai_base_client.py", line 1061, in _request
raise self._make_status_error_from_response(err.response) from None
openai.AuthenticationError: Error code: 401 - {'error': {'message': '无效的令牌 (request id: 2025010521101424970277384233457)', 'type': 'one_api_error'}}
SDK 示例代码:
以下是使用 OpenAI SDK 调用 One API 的代码:

python
复制代码
from openai import OpenAI

配置 One API 的基础 URL 和 API Key

OPENAI_API_BASE = "https://xxxx.com/v1" # 替换为 One API 的部署地址
OPENAI_API_KEY = "sk-bddddddddd45A9" # 替换为 One API 令牌

初始化 OpenAI 客户端

client = OpenAI(
base_url=OPENAI_API_BASE, # 设置 One API 的 Base 地址
api_key=OPENAI_API_KEY # 替换为你的 One API 令牌
)

发送流式请求

stream = client.chat.completions.create(
model="qwen-max", # 替换为你使用的模型名称
messages=[{"role": "user", "content": "Say this is a test"}], # ChatGPT 消息格式
stream=True # 开启流式返回
)

逐块打印返回内容

for chunk in stream:
if chunk.choices[0].delta.get("content"):
print(chunk.choices[0].delta["content"], end="")
实际结果:
上述代码报错,返回 401 - 无效的令牌,显示请求未通过认证。

测试对比: 使用 requests 库请求 One API
通过 requests 库直接向 One API 的 /v1/chat/completions 端点发送请求,可以正常返回结果。

代码:
python
复制代码
import requests

配置 One API 的 URL 和 API Key

url = "https://xxxx.com/v1/chat/completions" # 替换为 One API 的部署地址
api_key = "sk-bddddddddd45A9" # 替换为 One API 的令牌

请求数据

payload = {
"model": "qwen-max", # 模型名称
"messages": [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "你是谁"}
],
"max_tokens": 50,
"temperature": 0.7
}

请求头

headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}

发送 POST 请求

response = requests.post(url, json=payload, headers=headers)

输出响应

if response.status_code == 200:
print("Response:", response.json()["choices"][0]["message"]["content"])
else:
print("Error:", response.status_code, response.text)
结果:
通过 requests 库可以正常返回结果。

预期行为:
希望 OpenAI SDK 的行为和 requests 库一致,可以正常发送请求到 One API,并返回正确的响应。

@bruce-gene bruce-gene added the bug Something isn't working label Jan 5, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

1 participant