Java 后端面试题库 / 全部题解免费阅读理解原理,有条理地回答

一个 Chat Completions 请求最少要有哪些字段?

先说出你的答案

定义边界、关键机制、一个反例;P8题再补容量、失败与验证。

查看完整题解

参考回答

直接回答

发起 POST /v1/chat/completions,JSON 体至少指定 model 和 messages。每条典型文本消息有 role 和 content。认证放在 HTTP 请求头。

讲清原理

例如应用先给一条 developer 指令,再传一条 user 问题。文本结果通常从 choices[0].message.content 读取。如果模型请求工具,则应检查对应工具调用字段。还可根据需求配置输出预算或流式返回。

例子与易错点

示例核对 SDK 发送的实际 JSON 与授权头。加 temperature 等可选字段前先查具体模型的支持情况,避免直接复制旧示例。

import json
import httpx
from openai import OpenAI

messages = [
    {"role": "developer", "content": "Answer in one word."},
    {"role": "user", "content": "Are you ready?"},
]
model = "gpt-6.2-astra"

def chat(request):
    assert request.method == "POST" and request.url.path == "/v1/chat/completions"
    assert request.headers["Authorization"] == "Bearer fixture"
    assert json.loads(request.content) == {"model": model, "messages": messages}
    return httpx.Response(200, json={
        "id": "chat-fixture", "object": "chat.completion", "created": 0,
        "model": model, "choices": [{"index": 0, "finish_reason": "stop",
            "message": {"role": "assistant", "content": "Ready"}}],
    })

with OpenAI(api_key="fixture", base_url="https://fixture.invalid/v1",
            http_client=httpx.Client(transport=httpx.MockTransport(chat))) as client:
    result = client.chat.completions.create(model=model, messages=messages)
    print(result.choices[0].message.content)

相关题:第 8 题、第 9 题、第 11 题、第 12 题。

这道题,你掌握得怎么样?

掌握程度由你主动标记,阅读和收藏不会自动改变状态。