Skip to content

Commit 95613c1

Browse files
committed
langchain agent
1 parent a326add commit 95613c1

File tree

4 files changed

+418
-2
lines changed

4 files changed

+418
-2
lines changed

langchain/23.agent.ipynb

Lines changed: 199 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,199 @@
1+
{
2+
"cells": [
3+
{
4+
"cell_type": "markdown",
5+
"metadata": {},
6+
"source": [
7+
"## Agent Example"
8+
]
9+
},
10+
{
11+
"cell_type": "code",
12+
"execution_count": 38,
13+
"metadata": {},
14+
"outputs": [],
15+
"source": [
16+
"from langchain.agents import load_tools, AgentExecutor\n",
17+
"from langchain_experimental.plan_and_execute import PlanAndExecute, load_chat_planner\n",
18+
"\n",
19+
"from langchain.agents.output_parsers import ReActSingleInputOutputParser\n",
20+
"from langchain.agents.format_scratchpad import format_log_to_messages\n",
21+
"from langchain.tools.render import render_text_description\n",
22+
"from langchain import hub\n",
23+
"\n",
24+
"from chat_model_client import get_model\n",
25+
"from pprint import pprint"
26+
]
27+
},
28+
{
29+
"cell_type": "markdown",
30+
"metadata": {},
31+
"source": [
32+
"## 示例代码\n",
33+
"\n",
34+
"本示例的目的是让大模型在问答问题的过程中,可以自动调用搜索引擎和计算器来完成用的任务。"
35+
]
36+
},
37+
{
38+
"cell_type": "code",
39+
"execution_count": 20,
40+
"metadata": {},
41+
"outputs": [
42+
{
43+
"name": "stderr",
44+
"output_type": "stream",
45+
"text": [
46+
"/var/folders/5x/c0q41fpx6l540lsl42_bzk5h0000gq/T/ipykernel_36659/2448424658.py:1: UserWarning: Parameters {'frequency_penalty', 'top_p', 'presence_penalty'} should be specified explicitly. Instead they were passed in as part of `model_kwargs` parameter.\n",
47+
" llm = get_model(\"openai\")\n",
48+
"/Users/shaon/anaconda3/envs/wrenv3.10/lib/python3.10/site-packages/langsmith/client.py:253: LangSmithMissingAPIKeyWarning: API key must be provided when using hosted LangSmith API\n",
49+
" warnings.warn(\n"
50+
]
51+
},
52+
{
53+
"name": "stdout",
54+
"output_type": "stream",
55+
"text": [
56+
"\n",
57+
"\n",
58+
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
59+
"\u001b[32;1m\u001b[1;3mAction: duckduckgo_search\n",
60+
"Action Input: \"北京飞海南今天温度差\"\u001b[0m\u001b[36;1m\u001b[1;3m北京市气象台今晨6时发布天气预报,预计,今天白天晴间多云,北转南风二三级,最高气温6℃;夜间晴转多云,南转北风一二级,最低气温零下6℃。 周末两天,北京以晴到多云天气为主,气温变化不大,最高气温6℃,最低气温零下3℃至零下4℃。 中国天气网讯 今天(1月5日),北京天气多云间晴,山区有零星小雪,偏北风二三级间四级,最低气温仅-3℃,公众外出需注意防风防寒。 明后天,北京空气持续干燥,昼夜温差仍较大,需持续做好防寒工作,及时补水润燥。 海南天气预报,及时准确发布中央气象台天气信息,便捷查询北京今日天气,海南周末天气,海南一周天气预报,海南15日天气预报,海南40日天气预报,海南天气预报还提供海南各区县的生活指数、健康指数、交通指数、旅游指数,及时发布海南气象预警信号、各类气象资讯。 未来三天,北京天气将以晴到多云为主,多北风,后天将有强冷空气到访,带来大风降温天气。 北京市气象台预计,今天白天,北京晴转多云,高海拔山区零星小雪,偏北风3级左右,阵风6级左右,最高气温1℃。 今天(12月16日),我国大部气温回升,但昼夜温差将拉大至10℃至15℃,公众请适时调整着装,谨防感冒。 17日之后,两轮冷空气影响我国,气温又将 ...\u001b[0m\u001b[32;1m\u001b[1;3mAction: duckduckgo_search\n",
61+
"Action Input: \"北京飞海南今天温度差\"\u001b[0m\u001b[36;1m\u001b[1;3m中国天气网讯 今天(1月5日),北京天气多云间晴,山区有零星小雪,偏北风二三级间四级,最低气温仅-3℃,公众外出需注意防风防寒。 明后天,北京空气持续干燥,昼夜温差仍较大,需持续做好防寒工作,及时补水润燥。 海南天气预报,及时准确发布中央气象台天气信息,便捷查询北京今日天气,海南周末天气,海南一周天气预报,海南15日天气预报,海南40日天气预报,海南天气预报还提供海南各区县的生活指数、健康指数、交通指数、旅游指数,及时发布海南气象预警信号、各类气象资讯。 北京市气象台今晨6时发布天气预报,预计,今天白天晴间多云,北转南风二三级,最高气温6℃;夜间晴转多云,南转北风一二级,最低气温零下6℃。 周末两天,北京以晴到多云天气为主,气温变化不大,最高气温6℃,最低气温零下3℃至零下4℃。 据海南省气象台17日夜间到20日气温缓慢回升21日受冷空气补充影响,气温下降 近期气温多变记得及时增添衣物注意保暖一起来看详细天气预报陆地 ... 央广网海口12月14日消息(记者 付美斌)记者从海南省气象台了解到,受持续强冷空气影响,海南岛气温明显下降,未来一周持续低温天气,须防范 ...\u001b[0m\u001b[32;1m\u001b[1;3mAction: duckduckgo_search\n",
62+
"Action Input: \"北京飞海南今天温度差\"\u001b[0m\u001b[36;1m\u001b[1;3m海南天气预报,及时准确发布中央气象台天气信息,便捷查询北京今日天气,海南周末天气,海南一周天气预报,海南15日天气预报,海南40日天气预报,海南天气预报还提供海南各区县的生活指数、健康指数、交通指数、旅游指数,及时发布海南气象预警信号、各类气象资讯。 中国天气网讯 今天(10月27日)早晨,受冷空气影响,北京大部地区能见度明显好转。 预计今天白天,北京晴间多云,最高气温19℃,天气适宜人们户外活动和赏秋,但昼夜温差较大,早晚时段出行需注意防寒保暖。 中国天气网讯 今天(1月5日),北京天气多云间晴,山区有零星小雪,偏北风二三级间四级,最低气温仅-3℃,公众外出需注意防风防寒。 明后天,北京空气持续干燥,昼夜温差仍较大,需持续做好防寒工作,及时补水润燥。 【海南省各市县未来24小时天气预报】 12月7日 海南省气象台今天11时发布的预报: 今天下午: 海口,多云,气温21-24度 三亚,多云,气温24-30度 儋州,多云,气温20-27度 五指山,多云,气温20-28度 琼海,多云,... 据海南省气象台17日夜间到20日气温缓慢回升21日受冷空气补充影响,气温下降 近期气温多变记得及时增添衣物注意保暖一起来看详细天气预报陆地 ...\u001b[0m\u001b[32;1m\u001b[1;3mThought: I need to find out the temperature difference between Beijing and Hainan today.\n",
63+
"Action: duckduckgo_search\n",
64+
"Action Input: \"北京飞海南今天温度差\"\u001b[0m\u001b[36;1m\u001b[1;3m中国天气网讯 今天(1月5日),北京天气多云间晴,山区有零星小雪,偏北风二三级间四级,最低气温仅-3℃,公众外出需注意防风防寒。 明后天,北京空气持续干燥,昼夜温差仍较大,需持续做好防寒工作,及时补水润燥。 海南天气预报,及时准确发布中央气象台天气信息,便捷查询北京今日天气,海南周末天气,海南一周天气预报,海南15日天气预报,海南40日天气预报,海南天气预报还提供海南各区县的生活指数、健康指数、交通指数、旅游指数,及时发布海南气象预警信号、各类气象资讯。 北京市气象台今晨6时发布天气预报,预计,今天白天晴间多云,北转南风二三级,最高气温6℃;夜间晴转多云,南转北风一二级,最低气温零下6℃。 周末两天,北京以晴到多云天气为主,气温变化不大,最高气温6℃,最低气温零下3℃至零下4℃。 央广网海口12月14日消息(记者 付美斌)记者从海南省气象台了解到,受持续强冷空气影响,海南岛气温明显下降,未来一周持续低温天气,须防范 ... 雾和霾又来了 【北京今天大气扩散条件差能见度不佳 周日前后冷空气来袭】北京市气象台预计,今天早晨至白天晴间多云,早晨有雾或轻雾,北转南风二三级,最高气温19℃;夜间晴转多云,有轻雾,南转北风一二级,最低气温7℃。 周日前后将有明显冷空气来袭,周六夜间北京山区有雨夹雪,周日 ...\u001b[0m\u001b[32;1m\u001b[1;3mThought: I need to find out the temperature difference between Beijing and Hainan today.\n",
65+
"Action: duckduckgo_search\n",
66+
"Action Input: \"北京飞海南今天温度差\"\u001b[0m\u001b[36;1m\u001b[1;3m海南天气预报,及时准确发布中央气象台天气信息,便捷查询北京今日天气,海南周末天气,海南一周天气预报,海南15日天气预报,海南40日天气预报,海南天气预报还提供海南各区县的生活指数、健康指数、交通指数、旅游指数,及时发布海南气象预警信号、各类气象资讯。 中国天气网讯 今天(1月5日),北京天气多云间晴,山区有零星小雪,偏北风二三级间四级,最低气温仅-3℃,公众外出需注意防风防寒。 明后天,北京空气持续干燥,昼夜温差仍较大,需持续做好防寒工作,及时补水润燥。 北京市气象台今晨6时发布天气预报,预计,今天白天晴间多云,北转南风二三级,最高气温6℃;夜间晴转多云,南转北风一二级,最低气温零下6℃。 周末两天,北京以晴到多云天气为主,气温变化不大,最高气温6℃,最低气温零下3℃至零下4℃。 周日前后将有明显冷空气来袭,周六夜间北京山区有雨夹雪,周日北风加大。 周末最高气温维持在17℃,下周一降至13℃;最低气温也是逐渐下降,周六还有8℃,下周一仅1℃。 中国天气提醒,今天早晨有轻雾或雾,能见度不佳,公众驾车出行注意交通安全。 据海南省气象台17日夜间到20日气温缓慢回升21日受冷空气补充影响,气温下降 近期气温多变记得及时增添衣物注意保暖一起来看详细天气预报陆地 ...\u001b[0m\u001b[32;1m\u001b[1;3mFinal Answer: The temperature difference between Beijing and Hainan today is 12 degrees Celsius. To dress appropriately when flying from Beijing to Hainan, it is recommended to wear warm clothing due to the cold temperatures in Beijing and the potential temperature drop in Hainan.\u001b[0m\n",
67+
"\n",
68+
"\u001b[1m> Finished chain.\u001b[0m\n"
69+
]
70+
},
71+
{
72+
"data": {
73+
"text/plain": [
74+
"{'input': '今天北京飞海南温度相差几度?从北京飞海南需要怎么穿衣?',\n",
75+
" 'output': 'The temperature difference between Beijing and Hainan today is 12 degrees Celsius. To dress appropriately when flying from Beijing to Hainan, it is recommended to wear warm clothing due to the cold temperatures in Beijing and the potential temperature drop in Hainan.'}"
76+
]
77+
},
78+
"execution_count": 20,
79+
"metadata": {},
80+
"output_type": "execute_result"
81+
}
82+
],
83+
"source": [
84+
"llm = get_model(\"deepseek\")\n",
85+
"llm_with_stop = llm.bind(stop=[\"\\nObservation\"])\n",
86+
"\n",
87+
"tools = load_tools([\"ddg-search\", \"llm-math\"], llm=llm)\n",
88+
"\n",
89+
"prompt = hub.pull(\"hwchase17/react\")\n",
90+
"prompt = prompt.partial(\n",
91+
" tools=render_text_description(tools),\n",
92+
" tool_names=\", \".join([t.name for t in tools]),\n",
93+
")\n",
94+
"\n",
95+
"agent = (\n",
96+
" {\n",
97+
" \"input\": lambda x: x[\"input\"],\n",
98+
" \"agent_scratchpad\": lambda x: format_log_to_messages(x[\"intermediate_steps\"])\n",
99+
" }\n",
100+
" | prompt\n",
101+
" | llm_with_stop\n",
102+
" | ReActSingleInputOutputParser()\n",
103+
")\n",
104+
"\n",
105+
"agnet_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)\n",
106+
"\n",
107+
"agnet_executor.invoke({\"input\": \"今天北京飞海南温度相差几度?从北京飞海南需要怎么穿衣?\"})"
108+
]
109+
},
110+
{
111+
"cell_type": "markdown",
112+
"metadata": {},
113+
"source": [
114+
"## 输出Graph流程"
115+
]
116+
},
117+
{
118+
"cell_type": "code",
119+
"execution_count": 33,
120+
"metadata": {},
121+
"outputs": [
122+
{
123+
"name": "stdout",
124+
"output_type": "stream",
125+
"text": [
126+
"[PromptTemplate(input_variables=['agent_scratchpad', 'input'], input_types={}, partial_variables={'tools': 'duckduckgo_search - A wrapper around DuckDuckGo Search. Useful for when you need to answer questions about current events. Input should be a search query.\\nCalculator(*args: Any, callbacks: Union[list[langchain_core.callbacks.base.BaseCallbackHandler], langchain_core.callbacks.base.BaseCallbackManager, NoneType] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) -> Any - Useful for when you need to answer questions about math.', 'tool_names': 'duckduckgo_search, Calculator'}, metadata={'lc_hub_owner': 'hwchase17', 'lc_hub_repo': 'react', 'lc_hub_commit_hash': 'd15fe3c426f1c4b3f37c9198853e4a86e20c425ca7f4752ec0c9b0e97ca7ea4d'}, template='Answer the following questions as best you can. You have access to the following tools:\\n\\n{tools}\\n\\nUse the following format:\\n\\nQuestion: the input question you must answer\\nThought: you should always think about what to do\\nAction: the action to take, should be one of [{tool_names}]\\nAction Input: the input to the action\\nObservation: the result of the action\\n... (this Thought/Action/Action Input/Observation can repeat N times)\\nThought: I now know the final answer\\nFinal Answer: the final answer to the original input question\\n\\nBegin!\\n\\nQuestion: {input}\\nThought:{agent_scratchpad}')]\n",
127+
"+---------------------------------------+ \n",
128+
"| Parallel<input,agent_scratchpad>Input | \n",
129+
"+---------------------------------------+ \n",
130+
" * * \n",
131+
" ** ** \n",
132+
" * * \n",
133+
" +--------+ +--------+ \n",
134+
" | Lambda | | Lambda | \n",
135+
" +--------+ +--------+ \n",
136+
" * * \n",
137+
" ** ** \n",
138+
" * * \n",
139+
"+----------------------------------------+ \n",
140+
"| Parallel<input,agent_scratchpad>Output | \n",
141+
"+----------------------------------------+ \n",
142+
" * \n",
143+
" * \n",
144+
" * \n",
145+
" +----------------+ \n",
146+
" | PromptTemplate | \n",
147+
" +----------------+ \n",
148+
" * \n",
149+
" * \n",
150+
" * \n",
151+
" +------------+ \n",
152+
" | ChatOpenAI | \n",
153+
" +------------+ \n",
154+
" * \n",
155+
" * \n",
156+
" * \n",
157+
" +------------------------------+ \n",
158+
" | ReActSingleInputOutputParser | \n",
159+
" +------------------------------+ \n",
160+
" * \n",
161+
" * \n",
162+
" * \n",
163+
" +------------------------------------+ \n",
164+
" | ReActSingleInputOutputParserOutput | \n",
165+
" +------------------------------------+ \n",
166+
"None\n"
167+
]
168+
}
169+
],
170+
"source": [
171+
"# prompt.invoke({\"input\": \"{input}\"})\n",
172+
"# render_text_description(tools)\n",
173+
"print(agent.get_prompts())\n",
174+
"pprint(agent.get_graph().print_ascii())"
175+
]
176+
}
177+
],
178+
"metadata": {
179+
"kernelspec": {
180+
"display_name": "wrenv3.10",
181+
"language": "python",
182+
"name": "python3"
183+
},
184+
"language_info": {
185+
"codemirror_mode": {
186+
"name": "ipython",
187+
"version": 3
188+
},
189+
"file_extension": ".py",
190+
"mimetype": "text/x-python",
191+
"name": "python",
192+
"nbconvert_exporter": "python",
193+
"pygments_lexer": "ipython3",
194+
"version": "3.10.16"
195+
}
196+
},
197+
"nbformat": 4,
198+
"nbformat_minor": 2
199+
}

langchain/chat_model_client.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,8 @@ def get_openai():
3333
llm = ChatOpenAI(
3434
api_key=env_config['OPENAI_API_KEY'],
3535
model='gpt-3.5-turbo',
36+
# model="gpt-3.5-turbo-1106",
37+
# model="gpt-4o",
3638
temperature=0, # 设置成0最稳定;structured generation中稳定最重要
3739
max_tokens=2000,
3840
model_kwargs = {

0 commit comments

Comments
 (0)