示例1
室外计算机器与天气搜索引擎,但在使用天气查询的时候好像不可以用了
提示词模版:LangSmith
import os
from dotenv import load_dotenv
from langchain_community.llms import Tongyi
load_dotenv('key.env') # 指定加载 env 文件
key = os.getenv('DASHSCOPE_API_KEY') # 获得指定环境变量
DASHSCOPE_API_KEY = os.environ["DASHSCOPE_API_KEY"] # 获得指定环境变量
llm = Tongyi(temperature=1)from langchain import hub
from langchain.agents import load_tools
from langchain.agents import AgentExecutor
from langchain.agents.output_parsers import ReActSingleInputOutputParser
from langchain.agents.format_scratchpad import format_log_to_str
from langchain.tools.render import render_text_descriptionllm_with_stop = llm.bind(stop=["\nObservation"])# 准备我们的工具:这里用到 DuckDuckGo 搜索引擎,和一个基于 LLM 的计算器
tools = load_tools(["ddg-search", "llm-math"], llm=llm)# 准备核心提示词:这里从 LangChain Hub 加载了 ReAct 模式的提示词,并填充工具的文本描述
prompt = hub.pull("hwchase17/react-json")
prompt = prompt.partial(tools=render_text_description(tools),tool_names=", ".join([t.name for t in tools]),
)# 构建 Agent 的工作链:这里最重要的是把中间步骤的结构要保存到提示词的 agent_scratchpad 中
agent = ({"input": lambda x: x["input"],"agent_scratchpad": lambda x: format_log_to_str(x["intermediate_steps"]),}| prompt| llm_with_stop| ReActSingleInputOutputParser()
)# 构建 Agent 执行器:执行器负责执行 Agent 工作链,直至得到最终答案(的标识)并输出回答
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
print(agent_executor.invoke({"input": "今天上海和北京的气温差几度?"}))
示例2
使用 playwright 工具访问网页,提取上面内容,大模型总结网页内容
pip install playwright
playwright install
提示词模版:LangSmith
import os
from dotenv import load_dotenv
from langchain_community.llms import Tongyi
from langchain import hub
from langchain.agents import AgentExecutor
from langchain.agents.format_scratchpad import format_log_to_str
from langchain.agents.output_parsers import JSONAgentOutputParser
from langchain_community.chat_models.openai import ChatOpenAI
from langchain_community.agent_toolkits import PlayWrightBrowserToolkit
from langchain_community.tools.playwright.utils import create_async_playwright_browser
from langchain.tools.render import render_text_description_and_argsload_dotenv('key.env') # 指定加载 env 文件
key = os.getenv('DASHSCOPE_API_KEY') # 获得指定环境变量
DASHSCOPE_API_KEY = os.environ["DASHSCOPE_API_KEY"] # 获得指定环境变量
llm = Tongyi(temperature=1)# 避免 Jupyter Notebook 产生 EventLoop 问题
import nest_asyncio
nest_asyncio.apply()llm_with_stop = llm.bind(stop=["\nObservation"])async def run_agent():async_browser = create_async_playwright_browser()browser_toolkit = PlayWrightBrowserToolkit.from_browser(async_browser=async_browser)tools = browser_toolkit.get_tools()prompt = hub.pull("hwchase17/react-multi-input-json")prompt = prompt.partial(tools=render_text_description_and_args(tools),tool_names=", ".join([t.name for t in tools]),)agent = ({"input": lambda x: x["input"],"agent_scratchpad": lambda x: format_log_to_str(x["intermediate_steps"]),}| prompt| llm_with_stop| JSONAgentOutputParser())agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)result = await agent_executor.ainvoke({"input": "请访问这个网页并总结一下上面的内容:https://v.qq.com/"})print(result)return result# 在主程序中调用异步函数并等待其完成
if __name__ == "__main__":import asyncioasyncio.run(run_agent())