通过自然语言执行SQL命令

我们通过 SQLDatabaseToolkit 或者 SQLDatabaseChain 都可以实现执行SQL命令的操作

  1. from langchain.agents import create_sql_agent
  2. from langchain.agents.agent_toolkits import SQLDatabaseToolkit
  3. from langchain.sql_database import SQLDatabase
  4. from langchain.llms.openai import OpenAI
  5. db = SQLDatabase.from_uri("sqlite:///../notebooks/Chinook.db")
  6. toolkit = SQLDatabaseToolkit(db=db)
  7. agent_executor = create_sql_agent(
  8. llm=OpenAI(temperature=0),
  9. toolkit=toolkit,
  10. verbose=True
  11. )
  12. agent_executor.run("Describe the playlisttrack table")
  1. from langchain import OpenAI, SQLDatabase, SQLDatabaseChain
  2. db = SQLDatabase.from_uri("mysql+pymysql://root:root@127.0.0.1/chinook")
  3. llm = OpenAI(temperature=0)
  4. db_chain = SQLDatabaseChain(llm=llm, database=db, verbose=True)
  5. db_chain.run("How many employees are there?")

这里可以参考这两篇文档:

https://python.langchain.com/en/latest/modules/agents/toolkits/examples/sql_database.html

https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html