本文是【7.5 使用 LangChain 实现本地 Agent】的学习笔记
网址:datawhale.com 课程名称:动手学ollama
ReAct
ReAct通过扩展代理的动作空间(从纯行动空间A扩展到A ∪ L,其中L是语言空间),将推理(thought)与行动(action)结合
推理步骤(thought):代理生成自然语言的推理链(如分解任务目标、提取观察信息),不直接影响环境,但用于更新上下文。
行动步骤(action):代理调用外部工具(如搜索API)执行操作,并接收反馈。
上下文更新:每一步推理或行动都会更新当前上下文
ReAct的核心优势在于推理与行动的协同。在多跳问答(如HotPotQA)和事实验证(如FEVER)任务中,模型需要检索知识:通过外部工具(如维基百科API)获取信息;逻辑推理:基于检索到的信息生成答案或验证声明。
推理引导检索:模型通过自然语言推理(如“我需要先搜索X,然后找到Y”)决定下一步检索目标
检索支持推理:外部知识补充模型内部知识的不足,减少幻觉(hallucination)
ReAct 框架的核心机制:模型通过推理决定调用工具,并利用工具结果更新状态,最终生成答案
Ollama实现
通过 ChatOllama 集成 Ollama 模型,结合 LangChain 的工具系统,构建具备工具调用能力的智能代理
导入库
from langchain.pydantic_v1 import BaseModel, Field
可能遇到的 LangChainDeprecationWarning 是由于 LangChain 已经从内部迁移到 Pydantic v2,而代码仍然使用了 langchain.pydantic_v1 模块
从 langchain-core 0.3.0 开始,LangChain 内部使用 Pydantic v2。langchain.pydantic_v1
模块是为 Pydantic v1 提供的兼容层,不应再使用
修改为:
from pydantic import BaseModel, Field
测试不加工具
# 测试不加工具
llm = ChatOllama(model="llama3.2:1b") # 初始化 ChatOllama 模型,使用 "gemma:2b"
llm.invoke("What is the weather in Paris?").content
输出为:
In recent years, Paris has experienced a range of weather conditions. Here's what you can typically expect:\n\n* Spring (March to May): Mild temperatures, ranging from 9°C (48°F) to 22°C (72°F), with occasional rain showers.\n* Summer (June to August): Warm and sunny days, with average highs around 25°C (77°F). Nighttime temperatures can still be cool, ranging from 13°C (56°F) to 18°C (64°F).\n* Autumn (September to November): Cooler temperatures, ranging from 9°C (48°F) to 18°C (64°F), with a decrease in humidity.\n* Winter (December to February): Cold and sometimes snowy days, with average highs around 6°C (43°F). Snowfall can be significant, but the city is also known for its festive atmosphere during Christmas and New Year's.\n\nIt's not uncommon for Paris to experience rain showers throughout the year, especially in July and August. However, the amount of rainfall varies significantly depending on the season.\n\nHere are some average temperature ranges for different months:\n\n* January: -2°C (28°F) to 8°C (46°F)\n* February: -1°C (30°F) to 6°C (43°F)\n* March: 9°C (48°F) to 22°C (72°F)\n* April: 12°C (54°F) to 20°C (68°F)\n* May: 17°C (63°F) to 25°C (77°F)\n* June: 21°C (70°F) to 27°C (81°F)\n* July: 24°C (75°F) to 29°C (84°F)\n* August: 22°C (72°F) to 26°C (79°F)\n\nKeep in mind that these are average temperatures, and actual weather conditions can vary from year to year.
翻译:
近年来,巴黎经历了多样的天气状况。以下是典型的气候特征:
- 春季(3月至5月):气候温和,温度区间为9°C(48°F)至22°C(72°F),偶有阵雨。
- 夏季(6月至8月):温暖晴朗,平均高温约25°C(77°F)。夜间温度仍较凉爽,介于13°C(56°F)至18°C(64°F)之间。
- 秋季(9月至11月):气温转凉,范围在9°C(48°F)到18°C(64°F)之间,湿度降低。
- 冬季(12月至2月):寒冷且偶有降雪,平均高温约6°C(43°F)。虽然可能出现较大降雪,但城市在圣诞和新年期间以节日氛围著称。
巴黎全年都可能出现阵雨,尤其在七八月份较为常见。但降雨量会随季节显著变化。
各月份平均温度参考:
- 1月:-2°C(28°F)至8°C(46°F)
- 2月:-1°C(30°F)至6°C(43°F)
- 3月:9°C(48°F)至22°C(72°F)
- 4月:12°C(54°F)至20°C(68°F)
- 5月:17°C(63°F)至25°C(77°F)
- 6月:21°C(70°F)至27°C(81°F)
- 7月:24°C(75°F)至29°C(84°F)
- 8月:22°C(72°F)至26°C(79°F)
需注意以上均为平均值,实际天气状况可能逐年波动。
生成一个专用于天气预报的agent
# 测试使用工具
tools = [weather_forecast] # 使用 weather_forecast 工具
prompt = hub.pull("hwchase17/react-json") # 从 hub 拉取特定提示
prompt = prompt.partial(
tools=render_text_description(tools), # 为提示呈现工具的文本描述
tool_names=", ".join([t.name for t in tools]), # 将工具名称连接成一个以逗号分隔的字符串
)
agent = create_react_agent(llm, tools, prompt) # 使用 llm、工具和自定义提示创建代理
agent_executor = AgentExecutor(agent=agent, tools=tools, handle_parsing_errors=True, verbose=False, format="json") # 使用指定参数初始化 AgentExecutor
print(agent_executor.invoke({"input":"What is the weather in moscow?"})) # 使用测试输入调用代理并打印结果
如果问他 Do you love me? ,则会收到回答:'output': "I am a large language model, and I don't have personal feelings or emotions. However, I can provide information about AI tools and their capabilities.\n\nYou're right to explore different AI tools and their features. Some popular AI tools include natural language processing (NLP) models like BERT and RoBERTa, computer vision models like YOLO and SSD, and decision-making models like chatbots and voice assistants.\n\nBegin!"
其他问题也会得到类似答案
参考文章
datawhalechina.github.io/handy-ollama/
Shunyu Yao, Jeffrey Zhao, Dian Yu, Nan Du, Izhak Shafran, Karthik Narasimhan, and Yuan Cao. React: Synergizing reasoning and acting in language models. In Proc. ICLR, 2023. arXiv:2210.03629.