背景
LangChain学习中,尝试改了一下哈里森和吴恩达课程当中的问题,看看gpt-3.5-turbo在集成了ReAct和wikipedia后,如何回答《三体》的主要内容是什么这个问题,当然,主要是为了回答这问题时LangChain内部发生了什么。所以将langchain.debug 设置为 True。
代码出奇简洁👇
代码
import sys
import os# 添加 parent_dir 到 sys.path
current_dir = os.path.dirname(__file__)
parent_dir = os.path.dirname(current_dir)
sys.path.append(parent_dir)from constants import PROXY_URL,KEYimport warnings
warnings.filterwarnings("ignore")import langchain
langchain.debug = Truefrom langchain.agents import load_tools, initialize_agent
from langchain.agents import AgentType
from langchain.python import PythonREPL
from langchain.chat_models import ChatOpenAIllm = ChatOpenAI(temperature=0.0,model_name="gpt-3.5-turbo", openai_api_key=KEY,openai_api_base=PROXY_URL
)tools = load_tools(["wikipedia"],llm=llm
)agent= initialize_agent(tools, #第二步加载的工具llm, #第一步初始化的模型agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION, #代理类型handle_parsing_errors=True, #处理解析错误verbose = True #输出中间步骤
)response = agent("What is the main content of the science fiction novel The Three-Body Problem?")print(response)
输出异常繁琐👇
控制台输出
[chain/start] [1:chain:AgentExecutor] Entering Chain run with input:
{
"input": "What is the main content of the science fiction novel The Three-Body Problem?"
}
[chain/start] [1:chain:AgentExecutor > 2:chain:LLMChain] Entering Chain run with input:
{
"input": "What is the main content of the science fiction novel The Three-Body Problem?",
"agent_scratchpad": "",
"stop": [
"Observation:"
]
}
[llm/start] [1:chain:AgentExecutor > 2:chain:LLMChain > 3:llm:ChatOpenAI]
Entering LLM run with input:
{
"prompts": [
"System: Answer the following questions as best you can. You have access to the following tools:\n\nwikipedia: A wrapper around Wikipedia. Useful for when you need to answer general questions about people, places, companies, facts, historical events, or other subjects. Input should be a search query.\n\nThe way you use the tools is by specifying a json blob.\nSpecifically, this json should have a `action` key (with the name of the tool
to use) and a `action_input` key (with the input to the tool going here).\n\nThe only values that should be in the \"action\" field are: wikipedia\n\nThe $JSON_BLOB should only contain a SINGLE action, do NOT return a list of multiple actions. Here is an example of a valid $JSON_BLOB:\n\n```\n{\n \"action\": $TOOL_NAME,\n \"action_input\": $INPUT\n}\n```\n\nALWAYS use the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction:\n```\n$JSON_BLOB\n```\nObservation: the result of the action\n... (this Thought/Action/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question\n\nBegin! Reminder to always use the exact characters `Final Answer` when responding.\nHuman: What is the main content of the science fiction novel The Three-Body Problem?"
]
}
[llm/end] [1:chain:AgentExecutor > 2:chain:LLMChain > 3:llm:ChatOpenAI] [3.96s] Exiting LLM run with output:
{
"generations": [
[
{
"text": "Thought: I can use Wikipedia to find information about the main content of the science fiction novel \"The Three-Body Problem\".\n\nAction:\n```\n{\n \"action\": \"wikipedia\",\n \"action_input\": \"The
Three-Body Problem (novel)\"\n}\n```",
"generation_info": {
"finish_reason": "stop",
"logprobs": null
},
"type": "ChatGeneration",
"message": {
"lc": 1,
"type": "constructor",
"id": [
"langchain",
"schema",
"messages",
"AIMessage"
],
"kwargs": {
"content": "Thought: I can use Wikipedia to find information about the main content of the science fiction novel \"The Three-Body Problem\".\n\nAction:\n```\n{\n \"action\": \"wikipedia\",\n \"action_input\": \"The Three-Body Problem (novel)\"\n}\n```",
"additional_kwargs": {}
}
}
}
]
],
"llm_output": {
"token_usage": {
"completion_tokens": 55,
"prompt_tokens": 306,
"total_tokens": 361
},
"model_name": "gpt-3.5-turbo",
"system_fingerprint": "fp_3bc1b5746c"
},
"run": null
}
[chain/end] [1:chain:AgentExecutor > 2:chain:LLMChain] [3.96s] Exiting Chain run with output:
{
"text": "Thought: I can use Wikipedia to find information about the main content of the science fiction novel \"The Three-Body Problem\".\n\nAction:\n```\n{\n \"action\": \"wikipedia\",\n \"action_input\": \"The Three-Body Problem (novel)\"\n}\n```"
}
[tool/start] [1:chain:AgentExecutor > 4:tool:wikipedia] Entering Tool run
with input:
"The Three-Body Problem (novel)"
[tool/end] [1:chain:AgentExecutor > 4:tool:wikipedia] [5.47s] Exiting Tool run with output:
"Page: The Three-Body Problem (novel)
Summary: The Three-Body Problem (Chinese: 三体; lit. 'Three-Body') is a story by Chinese science fiction author Liu Cixin, the first novel in the Remembrance of Earth's Past trilogy. The series portrays a fictional past, present and future wherein Earth encounters an alien civilization from a nearby system of three sun-like stars orbiting one another, a representative example of the three-body problem in orbital mechanics.
The story was originally serialized in Science Fiction World in 2006 before it was published as a standalone book in 2008. In 2006, it received the
Galaxy Award for Chinese science fiction. In 2012, it was described as one of China's most successful full-length novels of the past two decades. The English translation by Ken Liu was published by Tor Books in 2014. That
translation was the first novel by an Asian writer to win a Hugo Award for Best Novel; it was also nominated for the Nebula Award for Best Novel.The book has been adapted into other media. In 2015, a Chinese film adaptation of the same name was in production, but it was never released. A Chinese TV series, Three-Body, released in early 2023 to critical success locally. An English language Netflix series, 3 Body Problem, was released in March 2024.Page: Three-body problem
Summary: In physics and classical mechanics, the three-body problem is the problem of taking the initial positions and velocities (or momenta) of three point masses and solving for their subsequent motion according to Newton's laws of motion and Newton's law of universal gravitation. The three-body problem is a special case of the n-body problem. Unlike two-body problems, no general closed-form solution exists, as the resulting dynamical system is chaotic for most initial conditions, and numerical methods are generally required.
Historically, the first specific three-body problem to receive extended study was the one involving the Moon, Earth, and the Sun. In an extended modern sense, a three-body problem is any problem in classical mechanics or quantum mechanics that models the motion of three particles.Page: 3 Body Problem (TV series)
Summary: 3 Body Problem is an American science fiction television series created by David Benioff, D. B. Weiss and Alexander Woo, loosely based on the Hugo Award-winning Chinese novel The Three-Body Problem by Liu Cixin. It is the second live-action adaptation after the 2023 Chinese television series.
The series premiered on Netflix with its eight episodes on March 21, 2024."
[chain/start] [1:chain:AgentExecutor > 5:chain:LLMChain] Entering Chain run with input:
{
"input": "What is the main content of the science fiction novel The Three-Body Problem?",
"agent_scratchpad": "This was your previous work (but I haven't seen any of it! I only see what you return as final answer):\nThought: I can use Wikipedia to find information about the main content of the science fiction novel \"The Three-Body Problem\".\n\nAction:\n```\n{\n \"action\": \"wikipedia\",\n \"action_input\": \"The Three-Body Problem (novel)\"\n}\n```\nObservation: Page: The Three-Body Problem (novel)\nSummary: The Three-Body Problem (Chinese: 三体; lit. 'Three-Body') is a story by Chinese science fiction author Liu Cixin, the first novel in the Remembrance of Earth's Past trilogy. The series portrays a fictional past, present and future wherein Earth encounters an alien civilization from a nearby system of three sun-like stars orbiting one another, a representative example of the three-body problem in orbital mechanics.\nThe story was originally serialized in Science Fiction World in 2006 before it was published as a standalone book in 2008. In 2006, it received the Galaxy Award for Chinese science fiction. In 2012, it was described as one of China's most successful full-length novels of the past two decades. The English translation by Ken Liu was published by Tor Books in 2014. That translation was the first novel by an
Asian writer to win a Hugo Award for Best Novel; it was also nominated for the Nebula Award for Best Novel.The book has been adapted into other media. In 2015, a Chinese film adaptation of the same name was in production,
but it was never released. A Chinese TV series, Three-Body, released in early 2023 to critical success locally. An English language Netflix series,
3 Body Problem, was released in March 2024.\n\nPage: Three-body problem\nSummary: In physics and classical mechanics, the three-body problem is the
problem of taking the initial positions and velocities (or momenta) of three point masses and solving for their subsequent motion according to Newton's laws of motion and Newton's law of universal gravitation. The three-body problem is a special case of the n-body problem. Unlike two-body problems, no general closed-form solution exists, as the resulting dynamical system is chaotic for most initial conditions, and numerical methods are generally required.\nHistorically, the first specific three-body problem to receive extended study was the one involving the Moon, Earth, and the Sun. In an extended modern sense, a three-body problem is any problem in classical mechanics or quantum mechanics that models the motion of three particles.\n\n\n\nPage: 3 Body Problem (TV series)\nSummary: 3 Body Problem is an
American science fiction television series created by David Benioff, D. B. Weiss and Alexander Woo, loosely based on the Hugo Award-winning Chinese
novel The Three-Body Problem by Liu Cixin. It is the second live-action adaptation after the 2023 Chinese television series.\nThe series premiered on Netflix with its eight episodes on March 21, 2024.\n\n\nThought:",
"stop": [
"Observation:"
]
}
[llm/start] [1:chain:AgentExecutor > 5:chain:LLMChain > 6:llm:ChatOpenAI]
Entering LLM run with input:
{
"prompts": [
"System: Answer the following questions as best you can. You have access to the following tools:\n\nwikipedia: A wrapper around Wikipedia. Useful for when you need to answer general questions about people, places, companies, facts, historical events, or other subjects. Input should be a search query.\n\nThe way you use the tools is by specifying a json blob.\nSpecifically, this json should have a `action` key (with the name of the tool
to use) and a `action_input` key (with the input to the tool going here).\n\nThe only values that should be in the \"action\" field are: wikipedia\n\nThe $JSON_BLOB should only contain a SINGLE action, do NOT return a list of multiple actions. Here is an example of a valid $JSON_BLOB:\n\n```\n{\n \"action\": $TOOL_NAME,\n \"action_input\": $INPUT\n}\n```\n\nALWAYS use the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction:\n```\n$JSON_BLOB\n```\nObservation: the result of the action\n... (this Thought/Action/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question\n\nBegin! Reminder to always use the exact characters `Final Answer` when responding.\nHuman: What is the main content of the science fiction novel The Three-Body Problem?\n\nThis was your previous work (but I haven't seen any of it! I only see what you return as final answer):\nThought: I can use Wikipedia to find information about the main content of the science fiction novel \"The
Three-Body Problem\".\n\nAction:\n```\n{\n \"action\": \"wikipedia\",\n
\"action_input\": \"The Three-Body Problem (novel)\"\n}\n```\nObservation: Page: The Three-Body Problem (novel)\nSummary: The Three-Body Problem (Chinese: 三体; lit. 'Three-Body') is a story by Chinese science fiction author Liu Cixin, the first novel in the Remembrance of Earth's Past trilogy.
The series portrays a fictional past, present and future wherein Earth encounters an alien civilization from a nearby system of three sun-like stars orbiting one another, a representative example of the three-body problem
in orbital mechanics.\nThe story was originally serialized in Science Fiction World in 2006 before it was published as a standalone book in 2008. In 2006, it received the Galaxy Award for Chinese science fiction. In 2012,
it was described as one of China's most successful full-length novels of the past two decades. The English translation by Ken Liu was published by Tor Books in 2014. That translation was the first novel by an Asian writer
to win a Hugo Award for Best Novel; it was also nominated for the Nebula Award for Best Novel.The book has been adapted into other media. In 2015, a Chinese film adaptation of the same name was in production, but it was never released. A Chinese TV series, Three-Body, released in early 2023 to critical success locally. An English language Netflix series, 3 Body Problem, was released in March 2024.\n\nPage: Three-body problem\nSummary: In physics and classical mechanics, the three-body problem is the problem of taking the initial positions and velocities (or momenta) of three point masses and solving for their subsequent motion according to Newton's laws of motion and Newton's law of universal gravitation. The three-body problem is a special case of the n-body problem. Unlike two-body problems, no general closed-form solution exists, as the resulting dynamical system is chaotic for most initial conditions, and numerical methods are generally required.\nHistorically, the first specific three-body problem to receive extended study was the one involving the Moon, Earth, and the Sun. In an extended modern sense, a three-body problem is any problem in classical mechanics
or quantum mechanics that models the motion of three particles.\n\n\n\nPage: 3 Body Problem (TV series)\nSummary: 3 Body Problem is an American science fiction television series created by David Benioff, D. B. Weiss and Alexander Woo, loosely based on the Hugo Award-winning Chinese novel The Three-Body Problem by Liu Cixin. It is the second live-action adaptation after the 2023 Chinese television series.\nThe series premiered on Netflix with its eight episodes on March 21, 2024.\n\n\nThought:"
]
}
[llm/end] [1:chain:AgentExecutor > 5:chain:LLMChain > 6:llm:ChatOpenAI] [4.10s] Exiting LLM run with output:
{
"generations": [
[
{
"text": "I have found information about the main content of the science fiction novel \"The Three-Body Problem\" by Liu Cixin. It is a story that portrays a fictional past, present, and future where Earth encounters an alien civilization from a nearby system of three sun-like stars orbiting one another. The novel is the first in the Remembrance of Earth's Past trilogy and has received critical acclaim.\n\nFinal Answer: The main content of the science fiction novel \"The Three-Body Problem\" involves Earth encountering an alien civilization from a nearby system of three sun-like stars.",
"generation_info": {
"finish_reason": "stop",
"logprobs": null
},
"type": "ChatGeneration",
"message": {
"lc": 1,
"type": "constructor",
"id": [
"langchain",
"schema",
"messages",
"AIMessage"
],
"kwargs": {
"content": "I have found information about the main content of the science fiction novel \"The Three-Body Problem\" by Liu Cixin. It is
a story that portrays a fictional past, present, and future where Earth encounters an alien civilization from a nearby system of three sun-like stars orbiting one another. The novel is the first in the Remembrance of Earth's Past trilogy and has received critical acclaim.\n\nFinal Answer: The main content of the science fiction novel \"The Three-Body Problem\" involves Earth encountering an alien civilization from a nearby system of three sun-like stars.",
"additional_kwargs": {}
}
}
}
]
],
"llm_output": {
"token_usage": {
"completion_tokens": 113,
"prompt_tokens": 924,
"total_tokens": 1037
},
"model_name": "gpt-3.5-turbo",
"system_fingerprint": "fp_3bc1b5746c"
},
"run": null
}
[chain/end] [1:chain:AgentExecutor > 5:chain:LLMChain] [4.10s] Exiting Chain run with output:
{
"text": "I have found information about the main content of the science
fiction novel \"The Three-Body Problem\" by Liu Cixin. It is a story that
portrays a fictional past, present, and future where Earth encounters an alien civilization from a nearby system of three sun-like stars orbiting one another. The novel is the first in the Remembrance of Earth's Past trilogy and has received critical acclaim.\n\nFinal Answer: The main content of the science fiction novel \"The Three-Body Problem\" involves Earth encountering an alien civilization from a nearby system of three sun-like stars."
}
[chain/end] [1:chain:AgentExecutor] [13.57s] Exiting Chain run with output:
{
"output": "The main content of the science fiction novel \"The Three-Body Problem\" involves Earth encountering an alien civilization from a nearby system of three sun-like stars."
}
{'input': 'What is the main content of the science fiction novel The Three-Body Problem?', 'output': 'The main content of the science fiction novel
"The Three-Body Problem" involves Earth encountering an alien civilization from a nearby system of three sun-like stars.'}
最终结果
The Three-Body Problem" involves Earth encountering an alien civilization from a nearby system of three sun-like stars.
翻译:《三体问题》涉及地球遇到来自附近三颗类太阳恒星系统的外星文明。