
在使用openai api时,除了获取模型生成的文本内容外,有时我们还需要访问api响应的http头部信息。这些头部信息通常包含重要的元数据,例如:
然而,OpenAI Python SDK的默认调用方式(如client.chat.completions.create)通常会直接返回经过解析的模型输出对象,而将底层的HTTP响应细节(包括头部)进行了抽象。
为了访问这些被抽象的HTTP头部,OpenAI Python SDK提供了一个特殊的修饰符with_raw_response。当与API调用方法(如create)结合使用时,它会返回一个包含原始HTTP响应数据的对象,而不是直接解析后的模型输出。
以下是获取API响应头部的具体步骤和示例代码:
步骤一:导入OpenAI库并初始化客户端
立即学习“Python免费学习笔记(深入)”;
首先,确保你已经安装了openai库,并按照常规方式初始化OpenAI客户端。
from openai import OpenAI
import os # 通常用于获取API密钥
# 确保你的OPENAI_API_KEY环境变量已设置
# 或者直接传递 api_key="Your_API_Key"
client = OpenAI(
api_key=os.environ.get("OPENAI_API_KEY")
)步骤二:使用with_raw_response进行API调用
在调用API方法(例如chat.completions.create)之前,在其前面加上.with_raw_response。这将返回一个APIRawResponse对象。
raw_response = client.chat.completions.with_raw_response.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": "Hello world"}]
)这个raw_response对象封装了HTTP响应的所有细节。
步骤三:解析模型输出和提取HTTP头部
从raw_response对象中,你可以通过.parse()方法获取到标准解析后的模型输出(例如ChatCompletion对象),并通过.headers属性访问HTTP头部字典。
# 解析出ChatCompletion对象
chat_completion = raw_response.parse()
print("Chat Completion:", chat_completion.choices[0].message.content)
# 获取HTTP头部信息
response_headers = raw_response.headers
print("\nHTTP Response Headers:")
for key, value in response_headers.items():
print(f" {key}: {value}")
# 示例:获取速率限制信息
print("\nRate Limit Information (if available):")
print(f" X-RateLimit-Limit-Requests: {response_headers.get('x-ratelimit-limit-requests', 'N/A')}")
print(f" X-RateLimit-Remaining-Requests: {response_headers.get('x-ratelimit-remaining-requests', 'N/A')}")
print(f" X-RateLimit-Reset-Requests: {response_headers.get('x-ratelimit-reset-requests', 'N/A')}")完整示例代码:
from openai import OpenAI
import os
client = OpenAI(
api_key=os.environ.get("OPENAI_API_KEY")
)
try:
raw_response = client.chat.completions.with_raw_response.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": "Hello world"}]
)
# 解析ChatCompletion对象
chat_completion = raw_response.parse()
print("模型响应内容:", chat_completion.choices[0].message.content)
# 获取HTTP头部信息
response_headers = raw_response.headers
print("\nHTTP响应头部信息:")
for key, value in response_headers.items():
print(f" {key}: {value}")
# 提取并打印速率限制信息
print("\n速率限制信息:")
print(f" 请求限制 (Requests): {response_headers.get('x-ratelimit-limit-requests', '未提供')}")
print(f" 剩余请求 (Requests): {response_headers.get('x-ratelimit-remaining-requests', '未提供')}")
print(f" 重置时间 (Requests): {response_headers.get('x-ratelimit-reset-requests', '未提供')}")
print(f" 令牌限制 (Tokens): {response_headers.get('x-ratelimit-limit-tokens', '未提供')}")
print(f" 剩余令牌 (Tokens): {response_headers.get('x-ratelimit-remaining-tokens', '未提供')}")
print(f" 重置时间 (Tokens): {response_headers.get('x-ratelimit-reset-tokens', '未提供')}")
except Exception as e:
print(f"发生错误: {e}")
通过使用OpenAI Python SDK的with_raw_response方法,开发者可以轻松地获取API调用的原始HTTP响应,进而访问包括速率限制在内的各种HTTP头部信息。这对于精细化管理API使用、进行调试以及理解API行为模式都非常重要。掌握这一技巧,能帮助你更有效地利用OpenAI API。
以上就是OpenAI Python SDK:获取API响应头部的实用指南的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号