LangChain:使用自然语言查询数据库( 二 )


pip installlangchain openai pymysql --upgrade -q
导入必要的库
from langchain.agents import load_toolsfrom langchain.agents import initialize_agentfrom langchain.agents import AgentTypefrom langchain.llms import OpenAI
os.environ['OPENAI_API_KEY'] = "your_openai_api_key"os.environ["SERPAPI_API_KEY"] = "your_serpapi_api_key"
这里需要使用你自己的和,其中为API,可以从这里注册获取,100次免费查询 。
llm = OpenAI(temperature=0)tools = load_tools(["serpapi", "llm-math"], llm=llm)agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION)
agent.run(" OpenAI的老板是谁,他的年龄的0.5次方是多少?")
输出:
6.164414002968976
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)agent.run(" OpenAI的老板是谁,他的年龄的0.5次方是多少?")
输出:
> Entering new AgentExecutor chain...I need to find out who the CEO of OpenAI is and then calculate their age to the power of 0.5.Action: SearchAction Input: "OpenAI CEO"Observation: Sam Altman, the CEO of ChatGPT maker OpenAI, used a high-profile trip to South Korea on Friday to call for coordinated international ...Thought: I need to find out the age of the CEOAction: SearchAction Input: "Sam Altman age"Observation: 38 yearsThought: I now know the age of the CEO and need to calculate it to the power of 0.5Action: CalculatorAction Input: 38^0.5Observation: Answer: 6.164414002968976Thought: I now know the final answerFinal Answer: 6.164414002968976> Finished chain.'6.164414002968976
SQLAgent 数据库模式和资源
本文使用了一个特定的数据库模式来进行演示 。这个模式包括了与订单、产品、客户等相关的表 。为了帮助你跟随例子并探索数据库模式,这里提供了一个到模式和资源的链接 。在此处访问数据库模式 。
SQL数据库代理是用来与SQL数据库交互的,允许用户用自然语言提问并得到答案 。下面来介绍如何实现它:
导入必要的库
import osfrom langchain.agents import *from langchain.llms import OpenAIfrom langchain.sql_database import SQLDatabase
连接到数据库:
codedb_user = "db_user"db_password = "db_password"db_host = "db_host"db_name = "db_name"db = SQLDatabase.from_uri(f"mysql+pymysql://{db_user}:{db_password}@{db_host}/{db_name}")
设置 LLM、工具包和代理执行器:
codefrom langchain.chat_models import ChatOpenAIllm = ChatOpenAI(model_name="gpt-3.5-turbo")toolkit = SQLDatabaseToolkit(db=db)agent_executor = create_sql_agent(llm=llm,toolkit=toolkit,verbose=True)
使用自然语言查询数据库:
1)、描述一个表及其关系:
agent_executor.run("描述与订单相关的表及其关系")
2)、从错误中恢复:
agent_executor.run("描述PurchaseDetails表")
3)、找出总销售收入最高的前5个产品:
agent_executor.run("找出总销售收入最高的前5个产品")
输出:
> Entering new AgentExecutor chain...Action: list_tables_sql_dbAction Input: ""Observation: customers, employees, payments, products, productlines, orderdetails, offices, ordersThought:我应该查询'products'和'orderdetails'表来得到每个产品的总销售收入Action: query_checker_sql_dbAction Input: SELECT products.productName, SUM(orderdetails.quantityOrdered * orderdetails.priceEach) AS totalRevenue FROM products INNER JOIN orderdetails ON products.productCode = orderdetails.productCode GROUP BY products.productName ORDER BY totalRevenue DESC LIMIT 5;Observation: SELECT products.productName, SUM(orderdetails.quantityOrdered * orderdetails.priceEach) AS totalRevenue FROM products INNER JOIN orderdetails ON products.productCode = orderdetails.productCode GROUP BY products.productName ORDER BY totalRevenue DESC LIMIT 5;Thought:这个查询看起来是正确的,我应该执行它来得到总销售收入最高的前5个产品 。Action: query_sql_dbAction Input: SELECT products.productName, SUM(orderdetails.quantityOrdered * orderdetails.priceEach) AS totalRevenue FROM products INNER JOIN orderdetails ON products.productCode = orderdetails.productCode GROUP BY products.productName ORDER BY totalRevenue DESC LIMIT 5;Observation: [('1992 Ferrari 360 Spider red', Decimal('276839.98')), ('2001 Ferrari Enzo', Decimal('190755.86')), ('1952 Alpine Renault 1300', Decimal('190017.96')), ('2003 Harley-Davidson Eagle Drag Bike', Decimal('170686.00')), ('1968 Ford Mustang', Decimal('161531.48'))]Thought:我可以看到总销售收入最高的前5个产品是:1992 Ferrari 360 Spider red,2001 Ferrari Enzo,1952 Alpine Renault 1300,2003 Harley-Davidson Eagle Drag Bike,和1968 Ford Mustang 。Final Answer: 总销售收入最高的前5个产品是1992 Ferrari 360 Spider red,2001 Ferrari Enzo,1952 Alpine Renault 1300,2003 Harley-Davidson Eagle Drag Bike,和1968 Ford Mustang 。> 链结束 。总销售收入最高的前5个产品是1992 Ferrari 360 Spider red,2001 Ferrari Enzo,1952 Alpine Renault 1300,2003 Harley-Davidson Eagle Drag Bike,和1968 Ford Mustang 。