langchain +SQLDatabase+Mysql+OpenAI

通过langchain +SQLDatabase+Mysql来获取数据

参照:https://github.com/hwchase17/langchain/issues/2333

from langchain import OpenAI, SQLDatabase, SQLDatabaseChain
from sqlalchemy import create_engine

from common.keys import OPENAI_API_KEY

engine = create_engine(
    'mysql+pymysql://root:root@localhost:127.0.0.1:3306/dbname')

include_tables = ['recommend_words']
db = SQLDatabase(engine, include_tables=include_tables)  # This will only include a list of tables you want!!!
print(db.get_table_names())

llm = OpenAI(temperature=0, verbose=True, max_tokens=1000, openai_api_key=OPENAI_API_KEY)

db_chain = SQLDatabaseChain(llm=llm, database=db, verbose=True)

db_chain.run("这个表一共有多少条记录?")

langchain +SQLDatabase+Mysql+OpenAI_第1张图片

如果按照官网的例子,会报错

https://python.langchain.com/docs/modules/chains/popular/sqlite

openai.error.InvalidRequestError: This model's maximum context length is 4097 tokens, however you requested 11836 tokens (11580 in your prompt; 256 for the completion). Please reduce your prompt; or completion length

你可能感兴趣的:(langchain,mysql,chatgpt)