01。
概述
02。
核心技术
02。
传统RAG实现
03。
新方案
fromlangchainimportOpenAI,LLMChain
fromlangchain.promptsimportPromptTemplate
fromlangchain.utilitiesimportSQLDatabase
fromsqlalchemyimportcreate_engine,MetaData,Table,Column,inspect
fromlangchain_experimental.sqlimportSQLDatabaseChain
#wekeptthetemp=0aswedontwantLLMtousecreativityandrandomness
llm=OpenAI(temperature=0,openai_api_key="your_openai_api_key")
defextract_schema(db_url):
engine=create_engine(db_url)
inspector=inspect(engine)
schema_info=[]
fortable_nameininspector.get_table_names():
columns=inspector.get_columns(table_name)
schema_info.append(f"Table:{table_name}")
forcolumnincolumns:
schema_info.append(f"-{column['name']}({column['type']})")
return"\n".join(schema_info)
prompt_template="""
YouareanAIassistantthatgeneratesSQLqueriesbasedonuserrequests.
Youhaveaccesstothefollowingdatabaseschema:
{schema}
Basedonthisschema,generateaSQLquerytoanswerthefollowingquestion:
{question}
SQLQuery:
"""
prompt=PromptTemplate(
input_variables=["schema","question"],
template=prompt_template,
)
chain=LLMChain(llm=llm,prompt=prompt)
defgenerate_sql_query(question):
returnchain.run(schema=schema,question=question)
user_question="Findmetheregistrationidofthehackathon"
sql_query=generate_sql_query(user_question)
print(f"GeneratedSQLQuery:{sql_query}")
04。
结论
| 欢迎光临 链载Ai (https://www.lianzai.com/) | Powered by Discuz! X3.5 |