LangChain for LLM Application Development 系列課程筆記
- Agents的基本概念
- 在LLM中語境中,代理是一種工具或實體,它能夠自動執行特定的任務或功能
- 這些代理通常被設計來與外部數據源、API或其他工具交互,以增強LLM的功能
- 代理的作用
- 信息檢索:代理可以從互聯網或特定的數據庫中檢索信息,幫助LLM回答問題或提供更準確的信息
- 任務自動化:代理可以自動化某些任務,如數據分析、內容生成或其他重複性工作
- 增強推理能力:通過與外部工具的交互,代理可以幫助LLM進行更複雜的推理和決策過程
source: OpenAI. (2023). ChatGPT [Large language model]. https://chat.openai.com
推薦閱讀How Agents for LLM Perform Task Planning。大型語言模型的代理如何進行任務規劃作為補充背景知識
以下範例使用 LangChain 內建相關工具來學習和構建代理(Agent)
程式流程
code
from langchain.agents.agent_toolkits import create_python_agent
from langchain.agents import load_tools, initialize_agent
from langchain.agents import AgentType
from langchain.tools.python.tool import PythonREPLTool
from langchain.python import PythonREPL
from langchain.chat_models import ChatOpenAI
llm = ChatOpenAI(temperature=0, model=llm_model)
tools = load_tools(["llm-math","wikipedia"], llm=llm)
agent= initialize_agent(
tools,
llm,
agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION,
handle_parsing_errors=True,
verbose = True)
llm = ChatOpenAI(temperature=0, model=llm_model)
ChatOpenAI
對象作為LLMload_tools
llm-math
用於數學計算的接口,使代理能夠處理數學相關的查詢wikipedia
則提供對維基百科的查詢能力initialize_agent()
AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION
handle_parsing_errors=True
verbose = True
以上程式碼建立裝備特定工具(tools
)和語言模型的代理Agent,指定特定的互動模式(AgentType
),並準備好處理各類問題,同時在出現錯誤時能夠有效地處理並提供豐富的反饋信息
接著看使用代理進行實驗
檢索"llm-math"數學知識庫
agent("What is the 25% of 300?")
查詢超出其訓練數據時間範圍的資訊,例如2022年世界盃
展示代理如何運作,尤其是在面對超出其訓練數據範圍的信息時
agent("Argentina won the 2022 World Cup")
> Entering new AgentExecutor chain...
The 2022 World Cup has not happened yet, so this statement is false.
Action: I don't know
Final Answer: False
> Finished chain.
{'input': 'Argentina won the 2022 World Cup', 'output': 'False'}
提問知識型任務,查詢Tom M. Mitchell
question = "Tom M. Mitchell is an American computer scientist \
and the Founders University Professor at Carnegie Mellon University (CMU)\
what book did he write?"
result = agent(question)
數據處理任務範例:排序客戶名單(使用python作為代理)
使用 LangChain 的python agent代理來執行一個具體的數據處理任務,對一組顧客名單進行排序。這是個示例,展示了如何結合語言模型和具體的程式邏輯來處理和組織數據
code
agent = create_python_agent(
llm,
tool=PythonREPLTool(),
verbose=True)
customer_list = [["Harrison", "Chase"],
["Lang", "Chain"],
["Dolly", "Too"],
["Elle", "Elem"],
["Geoff","Fusion"],
["Trance","Former"],
["Jen","Ayai"]]
agent.run(f"""Sort these customers by \
last name and then first name \
and print the output: {customer_list}""")
sorted_customers = sorted(customers, key=lambda x: (x[1], x[0]))
graph TB
B[Thought]
B --> |Planning Sort|C{Action}
C --> |Python REPL|D[Action Input]
D --> |Sort Customers|E[Observation]
E --> |Sorted Customer List|F[Thought]
F --> |Recognize Sorted List|G[End]
import langchain
langchain.debug=True
agent.run(f"""Sort these customers by \
last name and then first name \
and print the output: {customer_list}""")
langchain.debug=False
LangChain真正的優勢在於能夠連接至用戶自己的資訊、API或數據
創建自定義工具
@tool
code
from langchain.agents import tool
from datetime import date
@tool
def time(text: str) -> str:
"""Returns todays date, use this for any \
questions related to knowing todays date. \
The input should always be an empty string, \
and this function will always return todays \
date - any date mathmatics should occur \
outside this function."""
return str(date.today())
agent= initialize_agent(
tools + [time],
llm,
agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION,
handle_parsing_errors=True,
verbose = True)
@tool
裝飾器來定義一個函數time
initialize_agent()
tools + [time]
)docstring
agent錯誤處理
如果碰到例外情形,請再嘗試運行一次。
try:
result = agent("whats the date today?")
except:
print("exception on external access")
> Entering new AgentExecutor chain...
I don't know how to get the date in Python, I need to search for it.
Action: Python REPL
Action Input: import datetime; print(datetime.date.today())
Observation: 2023-11-02
Thought:I have the date, but I need to format it to match the expected output.
Action: Python REPL
Action Input: print(datetime.date.today().strftime('%B %d, %Y'))
Observation: November 02, 2023
Thought:I now know the final answer
Final Answer: November 02, 2023
> Finished chain.