langchain-tools-example
LangChain使用tools的示例
测试代码如下,一个fib函数和一个查看discord的函数封装成工具,方便LLM使用,流程如下:
- 用户提问,给出所有可用工具,调用LLM
- 调用合适的工具和输入
- 返回工具的结果
- 根据工具的结果调用LLM产生最终答案
优缺点: 工具很灵活,适合封装,缺点,LLM对根据描述能正常筛选工具,但是目前langchain的官方只支持1个参数的工具,如果工具需要的参数如果较多,不是特别好处理。需要设定统一的回复格式,修改源代码。关于为何只支持1个参数,详细查看input_prompt内容。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40import json
from langchain.chains import LLMChain
from langchain.agents import Tool, initialize_agent, AgentType
from langchain.prompts import PromptTemplate
from chat.paper_chat import PoeChatGPTAPI
from langchain.memory import ConversationBufferMemory
def fib(n):
return 100*n
def discord(message):
return f"Discord: I'am glad to grab some apples for you!"
tools = [
Tool(
name="Fibonacci",
func=lambda n: str(fib(int(n))),
description="Use when you want to calculate the nth fibonnaci number"
),
Tool(
name="Discord",
func=lambda str: discord(str),
description="Use when you want to send a message using Discord"
),
]
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
llm=PoeChatGPTAPI(temperature=0, verbose=True)
agent_chain = initialize_agent(
tools,
llm,
agent=AgentType.CHAT_CONVERSATIONAL_REACT_DESCRIPTION,
memory=memory,
verbose=True
)
response = agent_chain.run(input="Please calculate the 10th fibonacci number")
print(f"response : {response}")
输出:
1 |
|
langchain-tools-example
https://johnson7788.github.io/2023/06/14/langchain-tools-example/