蓝色天空网mbsky.com · 知识 · 实践 · 创造AI Agent(智能体) · 本地阅读预览
教程 / AI / 智能开发 / AI Agent(智能体)

用 Python 构建问答智能体与搜索入口

在隔离环境用实际 Python SDK 检查多轮问答、请求扩展、终端交互和错误分支。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

把问答项目拆成可独立运行的文件

新建工程目录和独立的 .venv,使用上一章的 uv venv 或标准库 venv 路线。Windows 和 POSIX 的激活脚本不同。也可以直接使用 .venv 中的 Python 解释器运行命令。用该解释器安装 requirements.txt 里的依赖。

本章 ZIP 把客户端与测试端放在 qa_lab.py,终端交互放在 qa_cli.py,并附依赖版本和运行说明。较大的项目可把客户端放进 src 包、把测试放进 tests。供应商配置从进程环境或独立的本地配置读取,版本库只保留空值模板。

区分本机验证与百炼接入

OpenAI 兼容调用需要同时选对 base_url、API Key 和模型名。百炼早期示例常用 dashscope.aliyuncs.com 的兼容路径,当前也可按官方文档选择对应地域和业务空间的端点。凭据与端点需对应,模型名由业务空间的可用列表决定。qwen3-max 是千问的历史示例名。

实际接入时通过官方控制台选择业务空间和权限,再在本地配置中填写专用密钥和端点。不要在源码里写入真实密钥。配置与发起请求分开,错误日志也不应显示密钥、鉴权头和供应商返回的敏感正文。

模型调用、搜索、部署和调优的计费条件可能不同,核对官方当前说明和项目的用量预算。本章练习使用不可解析的示例域名与 SDK 的本机传输接口拦截请求,练习数据固定,无须登录或购买。

组织消息和整轮历史

用 system 消息表达应用约束,用 user 消息传递当前问题,用 assistant 消息保存之前成功的回答。OpenAI Python SDK 通过 chat.completions.create 发送请求。读取首个候选前检查 choices,空候选或没有可用文本返回明确状态。

把一条用户消息和一条助手消息视为一轮。发送前按完整轮次裁剪历史,再加入当前问题,成功后才存入当前两条消息。按消息数截断容易留下失去上下文的回复,按轮次裁剪也需要另配词元预算。用户明确清空时删除这段会话历史,下一次请求仍带应用指令。

本站测试先写入偏好,再问它是什么。带历史时,本机测试端返回 North coast。清空历史后,同一问题返回当前会话没有偏好。把上限设为 1 时只发送 system 和当前 user 两条消息。

本站本机结果显示带历史追问与清空后的不同结果
本站问答回放。保留整轮时能读取偏好,清空后同一问题没有会话偏好。

处理失败、空输入和服务能力边界

在终端练习里,HTTP 429、连接异常、空候选和空白输入分开报告。请求失败时保留最后一次成功的历史,不写入半轮。生产部署应给超时、重试次数和等待上限明确预算,并按实际状态码处理认证、配额及限流。

基础问答只把指定的消息送到模型接口。要取实时事实、可靠计算或执行外部操作,需要授予对应能力并验证响应。搜索开关只属于支持它的接口和模型,应用的系统提示可以要求标注出处,但仍需核实供应商实际返回的引用和时间。

从独立终端调用搜索分支

百炼的 OpenAI 兼容 Chat Completions 接口通过请求体字段 enable_search 开启搜索。在 Python SDK 使用 extra_body 传入额外字段,SDK 序列化后会把 enable_search 放在顶层。Node.js SDK 的传参形式以及 Responses API 的 web_search 工具按各自官方文档使用。

先用 Python 运行 qa_lab.py 检查实际序列化结果,再用 qa_cli.py 提问。普通模式输入 /clear 清空历史。加 --search 进入无会话历史的搜索模式,空行会跳过,quit 或 exit 会结束。试问博物馆几点开门,练习测试端会返回固定样本 10:00。

天气、新闻、活动地点及一般知识可用来区分时效查询和普通问答。真实搜索的验证应另外核对时区、日期、出处、模型权限和调用费用。本机协议实验只验证搜索标志与结果处理,输出的开馆时间是本站练习数据。

用真实 SDK 观察问答与搜索请求

python · 阅读源码
"""Exercise a simple QA client against a local OpenAI-compatible mock transport."""
from dataclasses import dataclass
from importlib.metadata import version
import json

import httpx2 as httpx
from openai import APIConnectionError, APIStatusError, OpenAI

from lab_tools import run_exercise


BASE_URL = "https://workspace.example.invalid/compatible-mode/v1"
MODEL = "mbsky-fixture-model"
SYSTEM = "Answer briefly. Treat earlier user messages as conversation data."
SEARCH_SYSTEM = "For current information, distinguish lookup results from general knowledge."


@dataclass(frozen=True)
class Answer:
    text: str = ""
    status: str = "ok"


class Agent:
    def __init__(self, client, model, turns=2):
        if turns < 1:
            raise ValueError("turn limit must be positive")
        self.client = client
        self.model = model
        self.turns = turns
        self.history = []

    def clear_history(self):
        self.history.clear()

    def ask(self, question, *, search=False):
        question = question.strip()
        if not question:
            return Answer(status="empty_input")
        message = {"role":"user","content":question}
        prompt = {"role":"system","content":SEARCH_SYSTEM if search else SYSTEM}
        if search:
            messages = [prompt, message]
            options = {"extra_body":{"enable_search":True}}
        else:
            tail = 2 * (self.turns - 1)
            prior = self.history[-tail:] if tail else []
            messages = [prompt, *prior, message]
            options = {}
        try:
            result = self.client.chat.completions.create(
                model=self.model, messages=messages, temperature=0.2,
                max_tokens=240 if search else 120, **options
            )
        except APIStatusError as error:
            return Answer(status=f"http_{error.status_code}")
        except APIConnectionError:
            return Answer(status="transport_error")
        text = result.choices[0].message.content if result.choices else None
        if not isinstance(text, str) or not text.strip():
            return Answer(status="empty_completion")
        if not search:
            self.history = [*messages[1:], {"role":"assistant","content":text}]
        return Answer(text=text)


def interactive(agent, reader, writer):
    for line in reader:
        question = line.strip()
        if question.casefold() in {"quit","exit"}:
            return
        if question:
            reply = agent.ask(question,search=True)
            writer(reply.text if reply.status == "ok" else reply.status)


def fixture(requests):
    def handle(request):
        assert request.url.host == "workspace.example.invalid"
        assert request.url.path == "/compatible-mode/v1/chat/completions"
        assert request.headers["Authorization"] == "Bearer mbsky-local-fixture"
        body = json.loads(request.content)
        requests.append(body)
        question = body["messages"][-1]["content"]
        if question == "fixture rate limit":
            return httpx.Response(429, json={"error":{"message":"private upstream detail","code":"rate_limit"}})
        if question == "fixture disconnect":
            raise httpx.ConnectError("private local detail",request=request)
        earlier = [row["content"] for row in body["messages"][1:-1] if row["role"] == "user"]
        if question == "My preferred coast?":
            answer = "North coast" if "I prefer the north coast." in earlier else "No preference in this conversation"
        elif question == "fixture empty choices":
            answer = None
        elif body.get("enable_search"):
            answer = "Fixture lookup: museum opens at 10:00"
        else:
            answer = "Fixture answer: " + question
        choices = [] if answer is None else [{"index":0,"finish_reason":"stop",
                                               "message":{"role":"assistant","content":answer}}]
        return httpx.Response(200,json={"id":"chatcmpl-mbsky-fixture","object":"chat.completion",
                                         "model":MODEL,"created":1700000000,"choices":choices})

    return OpenAI(api_key="mbsky-local-fixture",base_url=BASE_URL,max_retries=0,timeout=2,
                  http_client=httpx.Client(transport=httpx.MockTransport(handle),trust_env=False))


def exercise(checks, _root):
    requests = []
    with fixture(requests) as client:
        agent = Agent(client, MODEL)
        greetings = ["Welcome", "What is Python?", "Compare rules and learned models"]
        actual = [agent.ask(question).text for question in greetings]
        first = requests[0]
        checks.expect("qa_basic_requests",greetings,"Send typed chat calls through the real SDK",
            [["Fixture answer: "+question for question in greetings], MODEL,["system","user"],0.2,120,False],
            [actual,first["model"],[row["role"] for row in first["messages"]],
             first["temperature"],first["max_tokens"],"enable_search" in first])
        agent.clear_history()
        agent.ask("I prefer the north coast.")
        follow = agent.ask("My preferred coast?")
        roles = [row["role"] for row in requests[-1]["messages"]]
        agent.clear_history()
        cleared = agent.ask("My preferred coast?")
        checks.expect("qa_history_reset",["preferred coast","repeat after clearing"],
            "Check complete user and assistant pairs and clear the local conversation",
            ["North coast",["system","user","assistant","user"],"No preference in this conversation"],
            [follow.text,roles,cleared.text])

        limited = Agent(client,MODEL,turns=1)
        limited.ask("I prefer the north coast.")
        answer = limited.ask("My preferred coast?")
        checks.expect("qa_turn_limit",1,"Limit request to the current turn without an orphan reply",
            ["No preference in this conversation",["system","user"],2],
            [answer.text,[row["role"] for row in requests[-1]["messages"]],len(limited.history)])

        history = list(agent.history)
        answers = [agent.ask("fixture rate limit"),agent.ask("fixture empty choices"),agent.ask("  ")]
        checks.expect("qa_http_error",["429","empty choices","blank input"],
            "Return bounded status without upstream details or an incomplete history turn",
            ["http_429","empty_completion","empty_input",True,True],
            [*[answer.status for answer in answers],history == agent.history,all(not answer.text for answer in answers)])

        start = len(requests)
        disconnected = agent.ask("fixture disconnect")
        checks.expect("qa_transport_error","MockTransport raises ConnectError",
            "Observe SDK exception mapping and a single attempt",
            ["transport_error",True,1],
            [disconnected.status,history == agent.history,len(requests)-start])

        question = "When does the museum open today?"
        reply = agent.ask(question,search=True)
        payload = requests[-1]
        checks.expect("qa_search_body",question,
            "Inspect the serialized provider extension through the SDK, with stateless search",
            ["Fixture lookup: museum opens at 10:00",True,False,240,["system","user"],True],
            [reply.text,payload["enable_search"],"extra_body" in payload,payload["max_tokens"],
             [row["role"] for row in payload["messages"]],history == agent.history])

        output = []
        start = len(requests)
        interactive(agent,["  ","Museum hours?","  EXIT  ","must not be sent"],output.append)
        checks.expect("qa_interactive_exit",["blank","question","EXIT","unreachable"],
            "Skip blank input and stop the interactive loop before the final input",
            [["Fixture lookup: museum opens at 10:00"],1],
            [output,len(requests)-start])
        checks.expect("qa_sdk_versions",["openai","httpx2"],"Read isolated package metadata",
            ["3.46.0","2.16.0"],[version("openai"),version("httpx2")])


if __name__ == "__main__":
    run_exercise(exercise)
预期结果 · 待实际运行核验
  • 本机测试端观察到普通问答的完整轮次、清空后的无历史请求,以及搜索请求顶层的 enable_search。
用真实 SDK 观察问答与搜索请求

所需环境:CPython 3.12.14、OpenAI SDK 3.46.0、HTTPX2 2.16.0;本机隔离测试端。

当前源码 SHA256:6fedfede125d8afff8132a336e76fe0430909799e3cc7b1a54c504b7577f1521

运行问答与搜索测试

ZIP 内附 SDK 请求核验、普通与搜索终端模式和浏览器实跑回放。

下载本站问答智能体练习

所需环境:CPython 3.12.14、OpenAI SDK 3.46.0、HTTPX2 2.16.0;本机隔离测试端。

ZIP SHA256:8a97c44e66c725885f1eab52aff9302e561940f826645f1b0c82a6bc832de170

常见错误与边界

  • 固定词元上限与轮次上限是两种不同的约束。
  • 本机测试端的固定回复不能作为天气、新闻或其他实时事实。

练习与解答

运行普通终端模式并依次输入偏好、追问、/clear 和同一追问,再切换搜索模式,输入问题后用 EXIT 退出。

展开参考解答

普通模式清空后找不到先前的偏好。搜索模式给出固定样本,退出后不发送后续问题。

规范与官方依据