from langchain.agents import initialize_agent, AgentType
from langchain.tools import Tool
from langchain.chat_models import ChatOpenAI
from langchain.memory import ConversationBufferMemory
from langchain.utilities import GoogleSearchAPIWrapper
search = GoogleSearchAPIWrapper()
tools = [
Tool(
name="Current Search",
func=search.run,
description="useful for when you need to answer questions about current events or the current state of the world"
),
]
memory = ConversationBufferMemory(memory_key="chat_history")
llm = ChatOpenAI(temperature=0)
agent_chain = initialize_agent(
tools,
llm,
agent=AgentType.CONVERSATIONAL_REACT_DESCRIPTION,
verbose=True,
memory=memory
)
print(agent_chain.run(input="用中文回答中国人口数量"))
利用 OpenAI 的 Function Calling 功能,让模型直接输出函数调用参数,提高工具调用的准确性。
from langchain.chat_models import ChatOpenAI
from langchain.agents import initialize_agent, AgentType
from langchain.utilities import GoogleSearchAPIWrapper
from langchain.chains import LLMMathChain
llm = ChatOpenAI(temperature=0, model="gpt-3.5-turbo-0613")
search = GoogleSearchAPIWrapper()
llm_math_chain = LLMMathChain.from_llm(llm=llm, verbose=True)
tools = [
Tool(
name="Search",
func=search.run,
description="useful for when you need to answer questions about current events. You should ask targeted questions"
),
Tool(
name="Calculator",
func=llm_math_chain.run,
description="useful for when you need to answer questions about math"
)
]
agent = initialize_agent(
tools,
llm,
agent=AgentType.OPENAI_FUNCTIONS,
verbose=True
)
print(agent.run("2 的 33 次方是多少?"))
from langchain.experimental.plan_and_execute import PlanAndExecute, load_agent_executor, load_chat_planner
from langchain.chat_models import ChatOpenAI
from langchain.utilities import GoogleSearchAPIWrapper
from langchain.chains import LLMMathChain
search = GoogleSearchAPIWrapper()
llm = ChatOpenAI(temperature=0)
llm_math_chain = LLMMathChain.from_llm(llm=llm, verbose=True)
tools = [
Tool(
name="Search",
func=search.run,
description="useful for when you need to answer questions about current events"
),
Tool(
name="Calculator",
func=llm_math_chain.run,
description="useful for when you need to answer questions about math"
),
]
model = ChatOpenAI(temperature=0)
planner = load_chat_planner(model)
executor = load_agent_executor(model, tools, verbose=True)
agent = PlanAndExecute(planner=planner, executor=executor, verbose=True)
print(agent.run("用中文回答美国和日本的 GDP 相差多少?"))
# 预期流程:1.Search Tool 查询美国 GDP 2.Calculator Tool 查询日本 GDP 3.Calculator Tool 计算差值
> Entering new chain...
Thought: I need to find out the population of China.
Action: Search
Action Input: Population of China
Observation: The current population of China is1,455,977,205asof Wednesday, July 5, 2023...
Thought: I now know the final answer.
Final Answer: The current population of China is1,455,977,205.
> Finished chain.