使用响应 API 生成响应
OoenAI 响应 API 将两个以前独立的 API(ChatCompletions 和 Assistants)中的功能组合在一起,以统一的体验。 它提供有状态的多轮次响应生成,使其非常适合对话式 AI 应用程序。 可以使用 Foundry SDK 或 OpenAI SDK 通过与 OpenAI 兼容的客户端访问响应 API。
了解响应 API
响应 API 比传统聊天完成提供了多种优势:
- 有状态对话:跨多个轮次维护会话上下文
- 统一体验:整合聊天补全与 Assistants API 模式
- Foundry 直接模型:适用于直接托管在 Microsoft Foundry 中的模型,而不仅仅是 Azure OpenAI 模型
- 简单集成:通过兼容OpenAI的客户端进行访问
注释
响应 API 是建议在 Microsoft Foundry 应用程序中生成 AI 响应的方法。 它替换了大多数方案的较旧的 ChatCompletions API。
生成简单的响应
使用与 OpenAI 兼容的客户端,可以使用 responses.create() 方法生成响应:
# Generate a response using the OpenAI-compatible client
response = openai_client.responses.create(
model="gpt-4.1", # Your model deployment name
input="What is Microsoft Foundry?"
)
# Display the response
print(response.output_text)
输入参数接受包含提示的文本字符串。 模型基于此输入生成响应。
了解响应结构
响应对象包含多个有用的属性:
- output_text:生成的文本响应
- id:此响应的唯一标识符
- 状态:响应状态(例如“已完成”)
- 用法:令牌使用情况信息(输入、输出和令牌总数)
- 模型:用于生成响应的模型
可以访问这些属性,以便有效处理响应。
response = openai_client.responses.create(
model="gpt-4.1",
input="Explain machine learning in simple terms."
)
print(f"Response: {response.output_text}")
print(f"Response ID: {response.id}")
print(f"Tokens used: {response.usage.total_tokens}")
print(f"Status: {response.status}")
添加操作说明
除了用户 输入之外,还可以提供指导模型行为 的说明 (通常称为 系统提示):
response = client.responses.create(
model="gpt-4.1",
instructions="You are a helpful AI assistant that answers questions clearly and concisely.",
input="Explain neural networks."
)
print(response.output_text)
控制响应生成
可以使用其他参数控制响应生成:
response = openai_client.responses.create(
model="gpt-4.1",
instructions="You are a helpful AI assistant that answers questions clearly and concisely.",
input="Write a creative story about AI.",
temperature=0.8, # Higher temperature for more creativity
max_output_tokens=200 # Limit response length
)
print(response.output_text)
- 温度:控制随机性(0.0-2.0)。 较高的值使输出更具创造性和变化
- max_output_tokens:限制响应中令牌的最大数目
- top_p:用于控制随机性的温度替代参数
使用 Foundry 的直接模型
使用 FoundrySDK 或 AzureOpenAI 客户端连接到 项目 终结点时,响应 API 适用于 Azure OpenAI 模型和 Foundry 直接模型(如 Microsoft Phi、DeepSeek 或其他直接托管在 Microsoft Foundry 中的模型):
# Using a Foundry direct model
response = openai_client.responses.create(
model="microsoft-phi-4", # Example Foundry direct model
instructions="You are a helpful AI assistant that answers questions clearly and concisely.",
input="What are the benefits of small language models?"
)
print(response.output_text)
创建对话体验
对于更复杂的聊天方案,可以提供系统说明并生成多轮对话:
# First turn in the conversation
response1 = openai_client.responses.create(
model="gpt-4.1",
instructions="You are a helpful AI assistant that explains technology concepts clearly.",
input="What is machine learning?"
)
print("Assistant:", response1.output_text)
# Continue the conversation
response2 = openai_client.responses.create(
model="gpt-4.1",
instructions="You are a helpful AI assistant that explains technology concepts clearly.",
input="Can you give me an example?",
previous_response_id=response1.id
)
print("Assistant:", response2.output_text)
实际上,实现可能构造为一个循环,在此循环中,用户可以根据从模型收到的每个响应以交互方式输入消息:
# Track responses
last_response_id = None
# Loop until the user wants to quit
print("Assistant: Enter a prompt (or type 'quit' to exit)")
while True:
input_text = input('\nYou: ')
if input_text.lower() == "quit":
print("Assistant: Goodbye!")
break
# Get a response
response = openai_client.responses.create(
model=model_name,
instructions="You are a helpful AI assistant that explains technology concepts clearly.",
input=input_text,
previous_response_id=last_response_id
)
assistant_text = response.output_text
print("\nAssistant:", assistant_text)
last_response_id = response.id
此示例的输出如下所示:
Assistant: Enter a prompt (or type 'quit' to exit)
You: What is machine learning?
Assistant: Machine learning is a type of artificial intelligence (AI) that enables computers to learn from data and improve their performance over time without being explicitly programmed. It involves training algorithms on large datasets to recognize patterns, make predictions, or take actions based on those patterns. This allows machines to become more accurate and efficient in their tasks as they are exposed to more data.
You: Can you give me an example?
Assistant: Certainly! Let's look at a simple example of supervised learning—predicting house prices based on features like size, location, and number of rooms.
Imagine you want to build a machine learning model that can predict the price of a house based on various factors.
...
{ the example provided in the model response may be extensive}
...
You: quit
Assistant: Goodbye!
当用户在每个轮次中输入新输入时,发送到模型的数据包括 指令 系统消息、来自用户的 输入 以及从模型收到的 上一 个响应。 这样,新输入就植根于模型为上一输入生成的响应所提供的上下文中。
替代方案:手动对话串联
可以通过自行生成消息历史记录来手动管理对话。 此方法可让你更好地控制包含哪些上下文:
try:
# Start with initial message
conversation_history = [
{
"type": "message",
"role": "user",
"content": "What is machine learning?"
}
]
# First response
response1 = openai_client.responses.create(
model="gpt-4.1",
input=conversation_history
)
print("Assistant:", response1.output_text)
# Add assistant response to history
conversation_history += response1.output
# Add new user message
conversation_history.append({
"type": "message",
"role": "user",
"content": "Can you give me an example?"
})
# Second response with full history
response2 = openai_client.responses.create(
model="gpt-4.1",
input=conversation_history
)
print("Assistant:", response2.output_text)
except Exception as ex:
print(f"Error: {ex}")
在需要以下情况时,此手动方法非常有用:
- 自定义要在上下文中包含的消息
- 实现对话裁剪以管理令牌限制
- 从数据库存储和还原聊天历史记录
检索特定以前的响应
响应 API 维护响应历史记录,使你能够检索以前的响应:
try:
# Retrieve a previous response
response_id = "resp_67cb61fa3a448190bcf2c42d96f0d1a8" # Example ID
previous_response = openai_client.responses.retrieve(response_id)
print(f"Previous response: {previous_response.output_text}")
except Exception as ex:
print(f"Error: {ex}")
上下文窗口注意事项
previous_response_id参数将响应链接在一起,在多个 API 调用中维护会话上下文。
请务必注意,保留会话历史记录会增加令牌使用量。 对于单个运行,活动上下文窗口可以包括:
- 系统说明(说明、安全规则)
- 你当前的提示
- 对话历史记录(以前的用户 + 助理消息)
- 工具架构(函数、OpenAPI 规范、MCP 工具等)
- 工具输出(搜索结果、代码解释器输出、文件)
- 检索的内存或文档(从内存存储、RAG、文件搜索)
所有这些内容都连接、标记化,并在每个请求中一起发送到模型。 SDK 可帮助你管理状态,但它不会自动使令牌使用更便宜。
创建响应式聊天应用
来自模型的响应可能需要一些时间才能生成,具体取决于所使用的特定模型、上下文窗口大小和提示大小等因素。 如果用户在等待响应时似乎“冻结”,则用户可能会感到沮丧,因此在实现中考虑应用响应非常重要。
流式响应
对于长时间的响应,可以使用流式处理以增量方式接收输出 - 因此,用户会在输出可用时看到部分完整的响应:
stream = openai_client.responses.create(
model="gpt-4.1",
input="Write a short story about a robot learning to paint.",
stream=True
)
for event in stream:
print(event, end="", flush=True)
如果要在流式传输时跟踪聊天历史记录,则可以在流结束时获取响应 ID,如下所示:
stream = openai_client.responses.create(
model="gpt-4.1",
input="Write a short story about a robot learning to paint.",
stream=True
)
for event in stream:
if event.type == "response.output_text.delta":
print(event.delta, end="")
elif event.type == "response.completed":
response_id = event.response.id
异步用法
对于高性能应用程序,可以使用异步客户端进行非阻止 API 调用。 异步用法非常适合长时间运行的请求,或者想要同时处理多个请求而不阻止应用程序。 若要使用它,请导入 AsyncOpenAI 而不是 OpenAI ,并在每个 API 调用中使用 await。
import asyncio
from openai import AsyncOpenAI
client = AsyncOpenAI(
base_url="https://<resource-name>.openai.azure.com/openai/v1/",
api_key=token_provider,
)
async def main():
response = await client.responses.create(
model="gpt-4.1",
input="Explain quantum computing briefly."
)
print(response.output_text)
asyncio.run(main())
异步流式处理的工作方式相同:
async def stream_response():
stream = await client.responses.create(
model="gpt-4.1",
input="Write a haiku about coding.",
stream=True
)
async for event in stream:
print(event, end="", flush=True)
asyncio.run(stream_response())
通过 Microsoft Foundry SDK 使用 响应 API,可以构建复杂的聊天式 AI 应用程序,以维护上下文、支持多个模型类型并提供响应式用户体验。