9.多工具Agent设计:工具注册、选择机制与执行流程解析

张开发
2026/5/26 5:43:33 15 分钟阅读
9.多工具Agent设计:工具注册、选择机制与执行流程解析
目 录前言创建工具创建智能体前言咱们咱们已经将做的项目进行了简单分层今天咱们需要做两件事一个是给咱们的智能体创建工具另一个是开始写一个简单的智能体今天咱们需要新建两个文件分别是tools.py和agent.py他们分别用来存放工具和智能体项目结构如下RagAgent/ │ ├── app.py # FastAPI入口 ├── rag_system.py # RAG核心类含rag_tool ├── llm_utils.py # embedding / decide_tool / LLM调用 ├── data_loader.py # PDF处理 ├── tools.py # ⭐ 新增所有工具 ├── agent.py # ⭐ 新增Agent调度逻辑 └── data/创建工具首先再tools.py文件夹下咱们需要定义三个工具分别是rag_tool、calculator_tool和time_tool他们分别是执行rag检索的工具计算表达式的工具以及一个返回当前时间的工具。完整代码如下# tools.pyfromrag_systemimportRAGSystemfromdatetimeimportdatetimedefrag_tool(query,rag:RAGSystem):returnrag.ask(query)defcalculator_tool(expression):try:returnstr(eval(expression))except:returnInvalid expressiondeftime_tool(_):returndatetime.now().strftime(%Y-%m-%d %H:%M:%S)TOOLS[{name:rag,description:Use for paper/document questions,func:rag_tool},{name:calculator,description:Use for math calculations,func:calculator_tool},{name:time,description:Get current time,func:time_tool}]这里有一个坑我们注意写法上我们再语句上有在这里func: rag_tool这种写法其实是将咱们前面写的函数作为一个变量装进了TOOLS这种方式也称为工具注册。未来在调用该工具的时候只要选出对应字段的func然后传入参数就可以使用了。创建智能体有了对应的工具就可以利用创建智能体了智能体应该是可以根据任务自主选择合适的工具执行并给出合理的运行结果他相当于一个大脑可以完成决策调度# agent.pyimportjsonfromllm_utilsimportclientdefchoose_tool(query,tools):tool_desc\n.join([f{t[name]}:{t[description]}fortintools])promptf You are an AI agent. Available tools:{tool_desc}User question:{query}Return JSON: {{tool: ..., input: ...}} responseclient.chat.completions.create(modeldeepseek-chat,messages[{role:user,content:prompt}])returnjson.loads(response.choices[0].message.content)defrun_agent(query,tools,ragNone):decisionchoose_tool(query,tools)tool_namedecision[tool]tool_inputdecision[input]#print(input:)#print(tool_input)fortintools:ift[name]tool_name:# 特殊处理 rag_tool需要rag实例iftool_namerag:returnt[func](tool_input,rag)else:returnt[func](tool_input)returnNo valid tool found最后咱们需要对咱们的FastAPI进行调整让他只负责传入问题即可fromfastapiimportFastAPIfrompydanticimportBaseModelfromrag_systemimportRAGSystemfromdata_loaderimportload_pdfs,process_documentsfromtoolsimportTOOLSfromagentimportrun_agent appFastAPI()ragNoneclassQueryRequest(BaseModel):question:strapp.on_event(startup)defstartup():globalrag docsload_pdfs(data)chunksprocess_documents(docs)ragRAGSystem(chunks)rag.build_index()app.post(/ask)defask(req:QueryRequest):answerrun_agent(req.question,TOOLS,rag)return{question:req.question,answer:answer}至此咱们的智能体可以运行了这个智能体的逻辑框图如下┌──────────────┐ │ FastAPI │ └──────┬───────┘ │ ┌──────▼───────┐ │ Agent │ ← agent.py └──────┬───────┘ │ ┌──────────────┼──────────────┐ ▼ ▼ ▼ RAG Tool Calculator Tool Time Tool │ ┌────▼─────┐ │ RAGSystem│ └──────────┘如果这篇文章对你有帮助可以点个赞完整代码地址https://github.com/1186141415/A-Paper-Rag-Agent

更多文章