一起学LangGraph构建agent专题---预构建的代理(四),大模型入门到精通,收藏这篇就足够了!
下面开始第二部分-预构建的代理;下面演示完整的示例代码及输出的结果;详细的概念定义可以参考每小节对应的官方描述
下面开始第二部分-预构建的代理;下面演示完整的示例代码及输出的结果;详细的概念定义可以参考每小节对应的官方描述,本文在这里就不在详细描述了;
官方文档:https://langchain-ai.github.io/langgraph/agents/overview/
本文介绍 预构建的代理 的第4个小结,完整代码已经上传到github上;文末自取;
4自定义工具
4自定义工具
参考文档:
https://langchain-ai.github.io/langgraph/agents/tools/
工具是一种封装函数及其输入架构的方法,其方式可以传递给支持工具调用的聊天模型。这允许模型请求使用特定输入执行此函数。
您可以定义自己的工具,也可以使用 LangChain 提供的预构建集成。
# 创建llm
import os
from langchain.chat_models import init_chat_model
from langgraph.prebuilt import create_react_agent
API_KEY = "sk-123"
BASE_URL = "https://api.deepseek.com"
os.environ["OPENAI_API_KEY"] = API_KEY
os.environ["OPENAI_API_BASE"] = BASE_URL
llm = init_chat_model(model="openai:deepseek-chat",
disable_streaming=True,# 禁用流式传输
temperature=0.1,
max_tokens=10240
)
# 定义工具
from langchain_core.tools import tool
@tool("multiply_tool", parse_docstring=True)
defmultiply(a: int, b: int) -> int:
"""Multiply two numbers.
Args:
a: First operand
b: Second operand
"""
return a * b
#您还可以使用 Pydantic 定义自定义输入架构:
from pydantic import BaseModel, Field
classMultiplyInputSchema(BaseModel):
"""Multiply two numbers"""
a: int = Field(description="First operand")
b: int = Field(description="Second operand")
@tool("multiply_tool", args_schema=MultiplyInputSchema)
defmultiply_pydantic(a: int, b: int) -> int:
return a * b
agent = create_react_agent(
model=llm,
tools=[multiply],
)
agent.invoke(
{"messages": [{"role": "user", "content": "what's 3 + 5 and 4 * 7?"}]}
)
{'messages': [HumanMessage(content="what's 3 + 5 and 4 * 7?", additional_kwargs={}, response_metadata={}, id='fceea18f-cb68-461a-a690-1dbcc6d52567'),
AIMessage(content='3 + 5 equals **8**.\n\nFor 4 * 7, let me calculate that for you.', additional_kwargs={'tool_calls': [{'id': 'call_0_e9c90af1-c68c-41dc-be12-4612284ebe54', 'function': {'arguments': '{"a":4,"b":7}', 'name': 'multiply_tool'}, 'type': 'function', 'index': 0}], 'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 46, 'prompt_tokens': 149, 'total_tokens': 195, 'completion_tokens_details': None, 'prompt_tokens_details': {'audio_tokens': None, 'cached_tokens': 0}, 'prompt_cache_hit_tokens': 0, 'prompt_cache_miss_tokens': 149}, 'model_name': 'deepseek-chat', 'system_fingerprint': 'fp_8802369eaa_prod0425fp8', 'id': '87e4552d-220f-4338-ac35-ac635321d25d', 'service_tier': None, 'finish_reason': 'tool_calls', 'logprobs': None}, id='run--93c67b97-d22e-407e-ad0b-02074b3953b8-0', tool_calls=[{'name': 'multiply_tool', 'args': {'a': 4, 'b': 7}, 'id': 'call_0_e9c90af1-c68c-41dc-be12-4612284ebe54', 'type': 'tool_call'}], usage_metadata={'input_tokens': 149, 'output_tokens': 46, 'total_tokens': 195, 'input_token_details': {'cache_read': 0}, 'output_token_details': {}}),
ToolMessage(content='28', name='multiply_tool', id='bdcfafb4-56fe-4ea7-89a4-8766ef707872', tool_call_id='call_0_e9c90af1-c68c-41dc-be12-4612284ebe54'),
AIMessage(content='4 * 7 equals **28**. \n\nSo, the answers are:\n- 3 + 5 = **8**\n- 4 * 7 = **28**', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 35, 'prompt_tokens': 204, 'total_tokens': 239, 'completion_tokens_details': None, 'prompt_tokens_details': {'audio_tokens': None, 'cached_tokens': 128}, 'prompt_cache_hit_tokens': 128, 'prompt_cache_miss_tokens': 76}, 'model_name': 'deepseek-chat', 'system_fingerprint': 'fp_8802369eaa_prod0425fp8', 'id': '34be8093-45e0-4b2e-a6da-911eaa09d8f5', 'service_tier': None, 'finish_reason': 'stop', 'logprobs': None}, id='run--145ee016-f074-476c-b38f-5d8183d323f5-0', usage_metadata={'input_tokens': 204, 'output_tokens': 35, 'total_tokens': 239, 'input_token_details': {'cache_read': 128}, 'output_token_details': {}})]}
# 直接返回工具结果¶
# 用于立即返回工具结果并停止代理循环:return_direct=True
from langchain_core.tools import tool
@tool(return_direct=True)
defadd(a: int, b: int) -> int:
"""Add two numbers"""
return a + b
agent = create_react_agent(
model=llm,
tools=[add]
)
agent.invoke(
{"messages": [{"role": "user", "content": "what's 3 + 5?"}]}
)
{'messages': [HumanMessage(content="what's 3 + 5?", additional_kwargs={}, response_metadata={}, id='c9095131-05b8-4423-8c99-fa5a29f583d7'),
AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_0_e3d3f882-752a-4df9-bba6-79cdc2047151', 'function': {'arguments': '{"a":3,"b":5}', 'name': 'add'}, 'type': 'function', 'index': 0}], 'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 22, 'prompt_tokens': 121, 'total_tokens': 143, 'completion_tokens_details': None, 'prompt_tokens_details': {'audio_tokens': None, 'cached_tokens': 0}, 'prompt_cache_hit_tokens': 0, 'prompt_cache_miss_tokens': 121}, 'model_name': 'deepseek-chat', 'system_fingerprint': 'fp_8802369eaa_prod0425fp8', 'id': '785c221b-bd94-48f8-9b68-7ef7838eb5ac', 'service_tier': None, 'finish_reason': 'tool_calls', 'logprobs': None}, id='run--06a2b4b5-8aea-485f-9b62-515958aac8d5-0', tool_calls=[{'name': 'add', 'args': {'a': 3, 'b': 5}, 'id': 'call_0_e3d3f882-752a-4df9-bba6-79cdc2047151', 'type': 'tool_call'}], usage_metadata={'input_tokens': 121, 'output_tokens': 22, 'total_tokens': 143, 'input_token_details': {'cache_read': 0}, 'output_token_details': {}}),
ToolMessage(content='8', name='add', id='a4ddc71d-0243-4aff-abb1-68df21bb3563', tool_call_id='call_0_e3d3f882-752a-4df9-bba6-79cdc2047151')]}
# 强制使用工具¶
# 要强制代理使用特定工具,您可以在 :tool_choicemodel.bind_tools()
import os
from langchain.chat_models import init_chat_model
from langgraph.prebuilt import create_react_agent
API_KEY = "sk-123"
BASE_URL = "https://api.deepseek.com"
os.environ["OPENAI_API_KEY"] = API_KEY
os.environ["OPENAI_API_BASE"] = BASE_URL
llm = init_chat_model(model="openai:deepseek-chat",
disable_streaming=True,# 禁用流式传输
temperature=0.1,
max_tokens=10240
)
from langchain_core.tools import tool
@tool(return_direct=True)
defgreet(user_name: str) -> int:
"""Greet user."""
returnf"Hello {user_name}!"
tools = [greet]
llm.bind_tools(tools, tool_choice={"type": "tool", "name": "greet"})
agent = create_react_agent(
model=llm,
tools=tools
)
agent.invoke(
{"messages": [{"role": "user", "content": "Hi, I am Bob"}]}
)
{'messages': [HumanMessage(content='Hi, I am Bob', additional_kwargs={}, response_metadata={}, id='36e5a489-a431-457f-9b6b-f10da043223d'),
AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_0_f3aeca2e-8434-4224-a8c8-1d1a173a9f9d', 'function': {'arguments': '{"user_name":"Bob"}', 'name': 'greet'}, 'type': 'function', 'index': 0}], 'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 20, 'prompt_tokens': 104, 'total_tokens': 124, 'completion_tokens_details': None, 'prompt_tokens_details': {'audio_tokens': None, 'cached_tokens': 0}, 'prompt_cache_hit_tokens': 0, 'prompt_cache_miss_tokens': 104}, 'model_name': 'deepseek-chat', 'system_fingerprint': 'fp_8802369eaa_prod0425fp8', 'id': '0439d763-8d04-449b-baaf-753ebbbda378', 'service_tier': None, 'finish_reason': 'tool_calls', 'logprobs': None}, id='run--7ee1aaa2-ddc7-4aea-81f0-4578c83bf5e6-0', tool_calls=[{'name': 'greet', 'args': {'user_name': 'Bob'}, 'id': 'call_0_f3aeca2e-8434-4224-a8c8-1d1a173a9f9d', 'type': 'tool_call'}], usage_metadata={'input_tokens': 104, 'output_tokens': 20, 'total_tokens': 124, 'input_token_details': {'cache_read': 0}, 'output_token_details': {}}),
ToolMessage(content='Hello Bob!', name='greet', id='7a1c9e96-520b-44c5-8334-92e6efd4a34b', tool_call_id='call_0_f3aeca2e-8434-4224-a8c8-1d1a173a9f9d')]}
# 处理工具错误¶
# 默认情况下,代理将捕获工具调用期间引发的所有异常,并将这些异常作为工具消息传递给 LLM。要控制错误的处理方式,您可以通过其参数使用预构建的 ToolNode(在其中执行工具的节点)
from langgraph.prebuilt import create_react_agent
defmultiply(a: int, b: int) -> int:
"""Multiply two numbers."""
if a == 42:
raise ValueError("The ultimate error")
return a * b
# Run with error handling (default)
agent = create_react_agent(
model="openai:deepseek-chat",
tools=[multiply]
)
agent.invoke(
{"messages": [{"role": "user", "content": "what's 42 x 7?"}]}
)
{'messages': [HumanMessage(content="what's 42 x 7?", additional_kwargs={}, response_metadata={}, id='2f76cea0-a04a-4f63-9cf0-78e814babfc2'),
AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_0_3e20f59c-8e73-4db7-afb1-0a9bf9abcf07', 'function': {'arguments': '{"a":42,"b":7}', 'name': 'multiply'}, 'type': 'function', 'index': 0}], 'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 23, 'prompt_tokens': 123, 'total_tokens': 146, 'completion_tokens_details': None, 'prompt_tokens_details': {'audio_tokens': None, 'cached_tokens': 0}, 'prompt_cache_hit_tokens': 0, 'prompt_cache_miss_tokens': 123}, 'model_name': 'deepseek-chat', 'system_fingerprint': 'fp_8802369eaa_prod0425fp8', 'id': '3c6dca32-12a1-4826-b419-2a9a852496db', 'service_tier': None, 'finish_reason': 'tool_calls', 'logprobs': None}, id='run--0d66d28c-f0e0-4d92-b5dd-813435065e82-0', tool_calls=[{'name': 'multiply', 'args': {'a': 42, 'b': 7}, 'id': 'call_0_3e20f59c-8e73-4db7-afb1-0a9bf9abcf07', 'type': 'tool_call'}], usage_metadata={'input_tokens': 123, 'output_tokens': 23, 'total_tokens': 146, 'input_token_details': {'cache_read': 0}, 'output_token_details': {}}),
ToolMessage(content="Error: ValueError('The ultimate error')\n Please fix your mistakes.", name='multiply', id='ac156e21-0945-4474-90e0-71d392d0b8e0', tool_call_id='call_0_3e20f59c-8e73-4db7-afb1-0a9bf9abcf07', status='error'),
AIMessage(content='It seems there was an error calculating the product of 42 and 7. Let me try again manually:\n\n42 × 7 = 294.\n\nThe answer is 294.', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 36, 'prompt_tokens': 166, 'total_tokens': 202, 'completion_tokens_details': None, 'prompt_tokens_details': {'audio_tokens': None, 'cached_tokens': 64}, 'prompt_cache_hit_tokens': 64, 'prompt_cache_miss_tokens': 102}, 'model_name': 'deepseek-chat', 'system_fingerprint': 'fp_8802369eaa_prod0425fp8', 'id': '2b35551a-4aab-40f6-8d95-5bb1fc334b3e', 'service_tier': None, 'finish_reason': 'stop', 'logprobs': None}, id='run--36d6b13c-680a-4aec-bd83-0eb20f8994bc-0', usage_metadata={'input_tokens': 166, 'output_tokens': 36, 'total_tokens': 202, 'input_token_details': {'cache_read': 64}, 'output_token_details': {}})]}
完整代码访问github地址:
https://github.com/aixiaoxin123/langgraph_project
大模型算是目前当之无愧最火的一个方向了,算是新时代的风口!有小伙伴觉得,作为新领域、新方向
人才需求必然相当大,与之相应的人才缺乏、人才竞争自然也会更少,那转行去做大模型是不是一个更好的选择呢?是不是更好就业
呢?是不是就暂时能抵抗35岁中年危机呢?
答案当然是这样,大模型必然是新风口!
那如何学习大模型 ?
由于新岗位的生产效率,要优于被取代岗位的生产效率,所以实际上整个社会的生产效率是提升的。但是具体到个人,只能说是:
最先掌握AI的人,将会比较晚掌握AI的人有竞争优势。
这句话,放在计算机、互联网、移动互联网的开局时期,都是一样的道理。
但现在很多想入行大模型的人苦于现在网上的大模型老课程老教材
,学也不是不学也不是,基于此我用做产品的心态来打磨这份大模型教程
,深挖痛点并持续修改了近100余次
后,终于把整个AI大模型的学习路线完善出来!
在这个版本当中:
您只需要听我讲,跟着我做即可,为了让学习的道路变得更简单,这份大模型路线+学习教程已经给大家整理并打包分享出来
, 😝有需要的小伙伴,可以 扫描下方二维码领取
🆓↓↓↓
一、大模型经典书籍(免费分享)
AI大模型已经成为了当今科技领域的一大热点,那以下这些大模型书籍就是非常不错的学习资源。
二、640套大模型报告(免费分享)
这套包含640份报告的合集,涵盖了大模型的理论研究、技术实现、行业应用等多个方面。无论您是科研人员、工程师,还是对AI大模型感兴趣的爱好者,这套报告合集都将为您提供宝贵的信息和启示。(几乎涵盖所有行业)
三、大模型系列视频教程(免费分享)
四、2025最新大模型学习路线(免费分享)
我们把学习路线分成L1到L4四个阶段,一步步带你从入门到进阶,从理论到实战。
L1阶段:启航篇丨极速破界AI新时代
L1阶段:了解大模型的基础知识,以及大模型在各个行业的应用和分析,学习理解大模型的核心原理、关键技术以及大模型应用场景。
L2阶段:攻坚篇丨RAG开发实战工坊
L2阶段:AI大模型RAG应用开发工程,主要学习RAG检索增强生成:包括Naive RAG、Advanced-RAG以及RAG性能评估,还有GraphRAG在内的多个RAG热门项目的分析。
L3阶段:跃迁篇丨Agent智能体架构设计
L3阶段:大模型Agent应用架构进阶实现,主要学习LangChain、 LIamaIndex框架,也会学习到AutoGPT、 MetaGPT等多Agent系统,打造Agent智能体。
L4阶段:精进篇丨模型微调与私有化部署
L4阶段:大模型的微调和私有化部署,更加深入的探讨Transformer架构,学习大模型的微调技术,利用DeepSpeed、Lamam Factory等工具快速进行模型微调,并通过Ollama、vLLM等推理部署框架,实现模型的快速部署。
L5阶段:专题集丨特训篇 【录播课】
全套的AI大模型学习资源
已经整理打包,有需要的小伙伴可以微信扫描下方二维码
,免费领取
更多推荐
所有评论(0)