接着前两节的Langchain,继续实现Langchain中的Agent
- LangChain 实现给动物取名字,
- LangChain 2模块化prompt template并用streamlit生成网站 实现给动物取名字
代码实现
# 从langchain库中导入模块
from langchain.llms import OpenAI # 从langchain.llms导入OpenAI模块
from langchain.prompts import PromptTemplate # 从langchain.prompts导入PromptTemplate模块
from langchain.chains import LLMChain # 从langchain.chains导入LLMChain模块
from dotenv import load_dotenv # 从dotenv导入load_dotenv,用于加载环境变量
from langchain.agents import load_tools # 从langchain.agents导入load_tools函数
from langchain.agents import initialize_agent # 从langchain.agents导入initialize_agent函数
from langchain.agents import AgentType # 从langchain.agents导入AgentType枚举类
from langchain.tools import WikipediaQueryRun # 从langchain.tools导入WikipediaQueryRun
from langchain.utilities import WikipediaAPIWrapper # 从langchain.utilities导入WikipediaAPIWrapper
load_dotenv() # 加载.env文件中的环境变量
def langchain_agent():
llm = OpenAI(temperature=0.5) # 创建OpenAI模型实例,设置temperature参数为0.5以调整响应的多样性
tools = load_tools(["wikipedia", "llm-math"], llm=llm) # 加载wikipedia和llm-math工具,与OpenAI模型实例一起使用
agent = initialize_agent(
tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True # 使用指定的工具、模型、agent类型和详细模式初始化agent
)
result = agent.run(
"What is the average age of a dog? Multiply the age by 3" # 使用一个提示语来运行agent进行处理
)
print(result) # 打印agent的输出
# 主执行检查
if __name__ == "__main__":
langchain_agent() # 如果脚本是主程序,则运行langchain_agent函数
安装lib
pip install wikipedia
运行代码
python langchain_helper.py
> Entering new AgentExecutor chain...
I need to find out the average age of a dog first.
Action: Wikipedia
Action Input: Average age of a dog
Observation: Page: Aging in dogs
Summary: Aging in dogs varies from breed to breed, and affects the dog's health and physical ability. As with humans, advanced years often bring changes in a dog's ability to hear, see, and move about easily. Skin condition, appetite, and energy levels often degrade with geriatric age. Medical conditions such as cancer, kidney failure, arthritis, dementia, and joint conditions, and other signs of old age may appear.
The aging profile of dogs varies according to their adult size (often determined by their breed): smaller dogs often live over 15–16 years (sometimes longer than 20 years), medium and large size dogs typically 10 to 20 years, and some giant dog breeds such as mastiffs, often only 7 to 8 years. The latter reach maturity at a slightly older age than smaller breeds—giant breeds becoming adult around two years old compared to the norm of around 13–15 months for other breeds.
Page: Dog
Summary: The dog (Canis familiaris or Canis lupus familiaris) is a domesticated descendant of the wolf. Also called the domestic dog, it is derived from extinct Pleistocene wolves, and the modern wolf is the dog's nearest living relative. The dog was the first species to be domesticated by humans. Hunter-gatherers did this, over 15,000 years ago in Germany, which was before the development of agriculture. Due to their long association with humans, dogs have expanded to a large number of domestic individuals and gained the ability to thrive on a starch-rich diet that would be inadequate for other canids.The dog has been selectively bred over millennia for various behaviors, sensory capabilities, and physical attributes. Dog breeds vary widely in shape, size, and color. They perform many roles for humans, such as hunting, herding, pulling loads, protection, assisting police and the military, companionship, therapy, and aiding disabled people. Over the millennia, dogs became uniquely adapted to human behavior, and the human–canine bond has been a topic of frequent study. This influence on human society has given them the sobriquet of "man's best friend".
Page: Bluey (dog)
Summary: Bluey (7 June 1910 – 14 November 1939) was a female Australian Cattle Dog owned by Les and Rosalie Hall of Rochester, Victoria. She previously held the Guinness World Records as the oldest dog to ever live, until being surpassed by Bobi from Portugal in 2023.
Thought: I now know the average age of a dog.
Action: Calculator
Action Input: Multiply the average age of a dog by 3
Observation: Answer: 45.0
Thought: I now know the final answer.
Final Answer: The average age of a dog multiplied by 3 is 45.0 years.
> Finished chain.
The average age of a dog multiplied by 3 is 45.0 years.
如果运行发生如下两种错误
错误一
resp = self.send(
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/requests/sessions.py", line 645, in send
r = adapter.send(request, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/requests/adapters.py", line 517, in send
raise SSLError(e, request=request)
requests.exceptions.SSLError: HTTPSConnectionPool(host='en.wikipedia.org', port=443): Max retries exceeded with url: /w/api.php?prop=info%7Cpageprops&inprop=url&ppprop=disambiguation&redirects=&titles=Aging+in+dogs&format=json&action=query (Caused by SSLError(SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:997)')))
错误二
Action Input: Average age of a dogTraceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/requests/models.py", line 910, in json
return complexjson.loads(self.text, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/json/__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
莫慌,笔者尝试问GPT4和google得到的答案都不正确。解决方案是切换梯子到不同的国家试试。笔者试了目前德国是好的。美国、香港、日本、新加坡是有问题的。
参考
- https://github.com/zgpeace/pets-name-langchain/tree/feature/agent
- https://youtu.be/lG7Uxts9SXs?si=H1CISGkoYiKRSF5V