免费获取学习方案
ARTICLE DETAIL

资讯详情

深耕编程基础知识与建站技术分享的一线实战洞察。

OGX 实战:用 Responses API 与 Prompts API 构建自我优化的 ResearchAgent

OGX 实战:用 Responses API 与 Prompts API 构建自我优化的 ResearchAgent OGX 实战用 Responses API 与 Prompts API 构建自我优化的 ResearchAgent【免费下载链接】ogxOpen GenAI Stack项目地址: https://gitcode.com/GitHub_Trending/ll/ogx本文以 OGXOpen GenAI Stack仓库中的官方教程为蓝本完整讲解如何用 Responses API 的 Agent 循环while True、服务端file_search工具、客户端函数工具以及 Prompts API 的版本化能力构建一个能自我评估并重写自己系统提示词的 ResearchAgent。读完本文你将掌握Responses API 两种工具服务端/客户端的混用模式、通过 Vector Store 让 Agent 主动策展知识库的方法以及评测—改进—落账的确定性自优化闭环。我们要构建什么文章核心是一个名为ResearchAgent的单一类它同时承担两种职责完整实现见 self_improving_agent.py研究Agentic使用 Responses API 的while True循环混合服务端file_search检索 Vector Store与客户端函数工具read_local_file、index_document、list_local_files。Agent 自己决定搜什么、发现未索引的本地文件、读取它们、把相关文档索引进知识库、再带着增强后的知识库重新搜索。自我改进确定性每 N 次research()调用后运行evaluate_self()用测试用例做基准评测再运行improve_self()重写自己的系统提示词。这是固定序列——不由 LLM 驱动工具选择而是 Agent 自己度量并改进自身表现。这构成了一个字面意义上的自指系统一个 OGX Agent 用 Responses API、Prompts API 和 Vector Stores 作为工具集来评估和改进自己。┌──────────────────────────────────────────────────────────┐ │ ResearchAgent │ │ │ │ research(question) │ │ Responses API agentic loop (while True): │ │ Server-side: file_search → Vector Store │ │ Client-side: read_local_file, index_document, │ │ list_local_files │ │ Increments call counter; triggers self-improvement │ │ every N calls │ │ │ │ evaluate_self() │ │ Run all test cases → judge answers (Responses API) │ │ → log scores (SQLite ledger) │ │ │ │ improve_self() │ │ Read feedback → propose new prompt (Responses API) │ │ → save new version (Prompts API) │ └──────────────────────────────────────────────────────────┘前置条件本地运行 [Ollama]并拉取两个模型llama3.1:8b作为研究 Agent 的推理模型gpt-oss:20b作为裁判judge模型一个使用 starter 发行版的 OGX 服务器通过OLLAMA_URL环境变量指向 OllamaPython SDKuv pip install ogx-client注Ollama 为本地推理服务OGX 通过OLLAMA_URL将其接入作为 inference provider模型名以ollama/为前缀如ollama/llama3.1:8b。研究循环Responses API 的 Agent 模式实战研究 Agent 是整个系统的核心也是 Responses API Agent 模式的示范。与单次调用的朴素 RAG Agent 不同它有真实的决策要做向量库可能上下文不够于是 Agent 可以发现本地文件、读取、索引相关文档、再重新搜索。它拥有一个服务端工具和三个客户端函数工具file_search服务端检索向量库中的相关文档。Responses API 自动执行该工具——无需任何客户端代码。read_local_file(path)读取一个尚未索引的本地文件例如刚写完、还没进知识库的 postmortem。index_document(file_path)通过 Files API 上传文件并调用vector_stores.files.create()挂载到向量库。这是关键洞察Agent 在主动策展自己的知识库。list_local_files(directory)发现目录下可用的.md和.txt文件。内部方法_run_query()是标准的 Responses API Agent 循环——持续调用responses.create()直到模型不再输出工具调用class ResearchAgent: def __init__(self, client, model, vector_store_id, prompt_id, **kwargs): self.client client self.model model self.vector_store_id vector_store_id self.prompt_id prompt_id # The agent owns its prompt self._call_count 0 self._tools { read_local_file: self._read_local_file, index_document: self._index_document, list_local_files: self._list_local_files, } # Also accepts: judge_model, ledger, test_cases, optimize_every def _run_query(self, question, system_prompt): Agentic loop: search, read local files, index, repeat. inputs question tools self._tool_schemas() while True: response self.client.responses.create( modelself.model, inputinputs, instructionssystem_prompt, toolstools, streamFalse, ) # file_search is handled server-side; collect client-side calls function_calls [o for o in response.output if o.type function_call] if not function_calls: return response.output_text # Done — no more tool calls # Execute each function call and feed results back inputs [] for fc in function_calls: result self._toolsfc.name) inputs.append(fc) inputs.append( { type: function_call_output, call_id: fc.call_id, output: result, } )公开方法research()读取 Agent 当前的提示词、运行 Agent 循环并递增计数器。每 N 次调用触发自我改进class ResearchAgent: ... def research(self, question): Answer a question. Automatically self-improves every N calls. current self.client.prompts.retrieve(self.prompt_id) answer self._run_query(question, current.prompt) self._call_count 1 if self.test_cases and self._call_count % self.optimize_every 0: self.evaluate_self() self.improve_self() return answer在典型调用中Agent 先通过file_search检索向量库由服务端处理。如果检索到的上下文不够——比如某个问题涉及最近一次事故而对应 postmortem 尚未索引——Agent 会调用list_local_files发现可用文档、read_local_file检查相关文件、index_document将其加入向量库然后用增强后的知识库再次搜索并写出最终答案。index_documentAgent 亲自策展知识库index_document工具值得特别说明——这是 Agent 主动策展自己知识库的体现class ResearchAgent: ... def _index_document(self, file_path): Upload a local file to the vector store so it becomes searchable. file self.client.files.create( fileopen(file_path, rb), purposeassistants ) attach self.client.vector_stores.files.create( vector_store_idself.vector_store_id, file_idfile.id ) while attach.status in_progress: time.sleep(0.5) attach self.client.vector_stores.files.retrieve( vector_store_idself.vector_store_id, file_idfile.id ) return fIndexed {file_path} (file_id{file.id}, status{attach.status})它先用 Files API 上传文档再通过vector_stores.files.create()挂载到向量库。轮询直到索引完成后该文件即可被同一查询的后续轮次——或未来的查询——中的file_search检索到。工具 schema 的自动生成实现细节完整实现 self_improving_agent.py 中还有一个值得借鉴的细节fn_to_tool_schema()函数根据 Python 函数签名type hints Annotated描述自动推导 OpenAI 函数工具 schema并处理Optional (T | None)联合类型与必填参数判定。这意味着你只需用 Python 类型注解写工具函数即可获得结构正确的{type: function, name: ..., parameters: ...}定义避免手写 JSON schema 出错。_tool_schemas()将服务端file_search携带vector_store_ids与三个客户端函数 schema 合并成一次responses.create()调用传入的完整工具列表。自我改进评测、改进与优化自我改进循环是 Agent 先给自己打基准分、再根据反馈重写提示词的过程。evaluate_self用裁判模型打分并落账evaluate_self用当前系统提示词在每个测试用例上运行 Agent用裁判模型评判每个答案并把分数写入账本ledgerclass ResearchAgent: ... def evaluate_self(self): Benchmark against test cases and log scores. current self.client.prompts.retrieve(self.prompt_id) results [] for tc in self.test_cases: answer self._run_query(tc[question], current.prompt) judgment self.client.responses.create( modelself.judge_model, input( fScore the following answer on a scale of 0.0 to 1.0.\n\n fQuestion: {tc[question]}\n fExpected: {tc[expected]}\nActual: {answer}\n\n fRespond with JSON: {{score: float, reasoning: ...}} ), streamFalse, ) score_data json.loads(judgment.output_text) results.append({**tc, actual: answer, **score_data}) avg_score sum(r[score] for r in results) / len(results) self.ledger.log(self.prompt_id, current.version, avg_score, feedback) return {results: results, average_score: avg_score, feedback: feedback}裁判模型被要求以 0.0~1.0 的分数评分并以 JSON 形式返回{score: ..., reasoning: ...}随后被解析为结构化数据。在仓库完整实现中裁判提示词还要求Expected answer与Actual answer逐项比对并把每条反馈聚合成可读的feedback摘要Q: question… → score (reasoning)后存入账本——这样后续improve_self就能直接消费为什么得分低的原因。improve_self基于反馈重写自己的提示词improve_self从账本读取最新评测反馈让裁判模型生成改进后的系统提示词再通过 Prompts API 保存class ResearchAgent: ... def improve_self(self): Propose and save an improved system prompt. history self.ledger.history(self.prompt_id) latest history[-1] current self.client.prompts.retrieve(self.prompt_id) response self.client.responses.create( modelself.judge_model, input( fImprove this research agents system prompt based on feedback.\n\n fCurrent prompt:\n{current.prompt}\n\n fFeedback:\n{latest[reasoning]}\n\n fReturn ONLY the improved prompt text. ), streamFalse, ) new_prompt response.output_text.strip() self.client.prompts.update( self.prompt_id, promptnew_prompt, versioncurrent.version )裁判模型身兼二职——既打分又基于自己的反馈提出改进建议。Prompts API 在每次update()时自动递增版本号而version参数提供乐观锁optimistic locking确保并发的实验不会静默覆盖彼此。optimize上线前的批量调优在 Agent 正式服务查询之前可以用optimize以for循环批量执行 evaluate/improve 周期class ResearchAgent: ... def optimize(self, max_iterations5): Run the evaluate/improve cycle for N iterations. for iteration in range(max_iterations): self.evaluate_self() self.improve_self()每次迭代产生一个新提示词版本并记录其平均分best_prompt()从账本中挑出得分最高的版本max(history, keylambda h: h[score])并检索其原文返回供人工审查或作为最终上线版本。ScoreLedgerSQLite 驱动的版本成绩单账本实现同见 self_improving_agent.py是一个基于 SQLite 的ScoreLedger类建表记录prompt_id / version / score / reasoning / timestamp提供log()写入与history()按版本升序查询。它是哪个提示词版本表现如何的单一事实来源也是improve_self读取反馈、best_prompt挑选最优版本的依据。运行起来首先拉取模型并启动 Ollama然后运行指向它的 OGX starter 发行版ollama pull llama3.1:8b ollama pull gpt-oss:20b OLLAMA_URLhttp://localhost:11434/v1 uv run --with ogx ogx run starterOLLAMA_URL环境变量告诉 starter 发行版使用 Ollama 作为推理提供方。服务器默认启动在http://localhost:8321。然后创建带工程文档的 Agent。部分文档预先索引进向量库其余文档放在本地目录供 Agent 按需发现并索引from ogx_client import OgxClient client OgxClient(base_urlhttp://localhost:8321) # Create the initial system prompt initial client.prompts.create( promptYou are a helpful assistant. Answer questions based on the provided context., ) # Create the self-improving research agent agent ResearchAgent.from_files( client, modelollama/llama3.1:8b, nameengineering-kb, file_paths[ docs/blog/building-agentic-flows/design/user_service_v2.md, docs/blog/building-agentic-flows/runbooks/deployment_rollback.md, ], prompt_idinitial.prompt_id, local_docs_dirdocs/blog/building-agentic-flows/postmortems, judge_modelollama/gpt-oss:20b, ledgerScoreLedger(), test_cases[ { question: What is the deployment rollback procedure?, expected: Revert the Kubernetes deployment to the previous revision using kubectl rollout undo, }, { question: What authentication method does the user service use?, expected: JWT tokens issued by the auth gateway with RS256 signing, }, { question: What was the root cause of the 2025-02 checkout outage?, expected: Connection pool exhaustion in the payments service due to missing timeout configuration, }, ], optimize_every10, ) # Run an initial optimization pass agent.optimize(max_iterations5) # Show the best prompt result agent.best_prompt() print(fBest prompt (v{result[version]}, score{result[score]:.2f}):) print(f {result[prompt]}) # Normal usage — the agent self-improves every 10 research() calls answer agent.research(What is the deployment rollback procedure?) print(fAgent says: {answer})关键参数说明from_files类方法自动创建以embedding_model默认all-MiniLM-L6-v2和embedding_dimension默认 384配置的 Vector Store并把file_paths中的文档逐一遍历上传、挂载、轮询至索引完成。仓库中三个测试用例对应的答案恰好都能在上述示例文档中找到出处——deployment_rollback.md 中的kubectl rollout undo步骤、user_service_v2.md 中的 RS256 JWT 认证以及 2025-02-checkout-outage.md 中的连接池耗尽根因构成一套自洽的知识库—测试用例体系。optimize_every10每 10 次research()调用自动触发一次 evaluate improve。judge_model与test_cases缺一不可完整实现中research()的自动优化仅在judge_model与test_cases都非空时才触发避免未配置评测体系时误触发。底层原理两种工具如何协同Agent 在研究中同时使用了 Responses API 的两类工具服务端工具Server-side tools如file_search由 Responses API 自动执行——API 检索向量库、取回相关片段并喂给模型全程无需客户端代码。这正是知识库检索 一次 API 调用的原因。客户端函数工具Client-side function toolsread_local_file、index_document、list_local_files返回工具调用对象由客户端执行。while True循环分派这些调用结果回填到下一次responses.create()。这让 Agent 得以主动策展知识库。Agent 在同一个循环中组合两者file_search的结果随响应自动返回函数调用则需要客户端执行。模型同时看到两类信息源自己决定下一步做什么。自我改进方法则完全不需要这套机制它们直接调用responses.create()完成评判与提示词生成——不涉及工具调用也没有 Agent 循环。Prompts API 以乐观锁存储版本化提示词文本详见 prompts/models.pyversion从 1 开始、每次保存递增UpdatePromptRequest要求携带当前version作为乐观锁prompt_id采用pmpt_48位十六进制格式SQLite 账本则记录每个版本的表现。research()的计数器把一切串起来Agent 正常服务查询每 N 次调用暂停片刻评估并改进自己。扩展方向自我改进的 Agent 周期性地打基准分并重写自己提示词这一模式远不止适用于研究助手MCP 工具连接外部服务数据库、API、代码执行沙箱——研究 Agent 可以在静态文档之外拉取实时数据Web 搜索与file_search并用让 Agent 结合本地知识与实时网页结果多个研究 Agent各自使用不同的向量库、独立自我改进、分别专精不同知识领域进一步阅读Responses API 与 Agents 对比OpenAI API 兼容性ConversationsOpenAI API 兼容性总览Vector Stores 与 RAG 文档完整实现源码【免费下载链接】ogxOpen GenAI Stack项目地址: https://gitcode.com/GitHub_Trending/ll/ogx创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表