LangChain最近蛮火的,主要也是因为AutoGPT的出圈。现在也有蛮多的介绍文章,简单讲,LangChain 是一个开发AI应用的框架。如果把OpenAI比做是发动机,那么LangChain就是整车啰!普通开发者不用再担心怎么造车,只要会开车就行,这大大给AI开发降维了。
这里简单地来个案例实操,感觉下LangChain的强大功能,这里试一下让ChatGPT联网。先借助 Serpapi来进行(google 搜索)查询数据,再喂给OpenAI,最后给出结果。
from langchain.agents import load_tools
from langchain.agents import initialize_agent
from langchain.agents import AgentType
from langchain.llms import OpenAI
import os
os.environ["OPENAI_API_KEY"] = 'sk-vgxxxxxxx'
os.environ["SERPAPI_API_KEY"] = '97e85bxxxxx'
# 加载 OpenAI 模型
llm = OpenAI(temperature=0.2,max_tokens=2048)
# 加载 serpapi 工具
tools = load_tools(["serpapi"])
# 工具加载后都需要初始化,verbose 参数为 True,会打印全部的执行详情
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
# 运行 agent
agent.run("What's the date today? What great events have taken place today in history?")
运行后的结果如下:
> Entering new AgentExecutor chain...
I should look up the current date and then search for any events that have taken place on that day.
Action: Search
Action Input: Current date
Observation: Today's current date and time with time zone and date picker: Select locale. en-US. Wednesday, May 3, 2023. 5:00:05 PM. PST8PDT (GMT-7).
Thought: I should now search for any events that have taken place on this day.
Action: Search
Action Input: Events that have taken place on May 3
Observation: On this day - May 3
Thought: I now know the events that have taken place on this day.
Final Answer: Today is Wednesday, May 3, 2023. On this day in history, the first successful ascent of Mount Everest was made by Edmund Hillary and Tenzing Norgay in 1953.
感觉不错,成功运行,并得到了正确结果!
总体来讲,LangChain封装得挺好,各种工具应有尽有,你能想到的,它都有贴心地提供。尤其是现在流行的向量数据库,都提供了集成的接口。刚试了下Chroma,就是安装有点费事,其它用起来倒还好。随着AI的一步步火爆,LangChain这种开发框架也会越来越流行。