Langchain二次開發專欄
- 【Langchain系列一】常用大模型的key獲取與連接方式
- 【Langchain系列二】LangChain+Prompt +LLM智能問答入門
- 【Langchain系列三】GraphGPT——LangChain+NebulaGraph+llm構建智能圖數據庫問答系統
- 【Langchain系列四】RAG——基于非結構化數據庫的智能問答
- 【Langchain系列五】DbGPT——Langchain+PG構建結構化數據庫智能問答系統
- 【Langchain系列六】Langchain+Gradio界面化
- 【Langchain系列七】Langchain+FastAPI(字符串輸出與OpenAI規范流式輸出)+FastGPT
1. 官方資料
- 構建一個基于SQL數據的問答系統
- 構建基于SQL數據的問答系統
2. 安裝依賴
pip install langchain langchain_community pyjwt langgraph psycopg2
3. 完整代碼
import os
import re
import time
from operator import itemgetterfrom langchain.chains.sql_database.query import create_sql_query_chain
from langchain_community.agent_toolkits import SQLDatabaseToolkit
from langchain_community.chat_models.zhipuai import ChatZhipuAI
from langchain_community.tools import QuerySQLDataBaseTool
from langchain_community.utilities import SQLDatabase
from langchain_core.messages import AIMessage, SystemMessage, HumanMessage
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import PromptTemplate, FewShotPromptTemplate, ChatPromptTemplate, MessagesPlaceholder
from langchain_core.runnables import RunnablePassthrough
from langchain_ollama import ChatOllama
from langgraph.prebuilt import create_react_agent# 設置OpenAI API密鑰(GLM-4-Flash是免費模型,其它模型會消耗token,智譜的是目前免費模型最好的)
os.environ["ZHIPUAI_API_KEY"] = "你的key"
# llm = ChatZhipuAI(model="GLM-4-Flash", temperature=0.5)
# 本地模型也可以,但是glm4(9b)的效果明顯優于qwen2.5:7b,和線上GLM-4-Flash的差不多
# llm=ChatOllama(base_url="http://localhost:11434", model="qwen2.5:7b", temperature=0.5)
llm = ChatOllama(base_url="http://localhost:11434", model="glm4:latest", temperature=0.5)
# qwen 效果有點差,羅里吧嗦還不對
# os.environ["DASHSCOPE_API_KEY"] = "密鑰"
# llm = ChatTongyi(model="qwen-turbo", verbose=True)
# 訊飛星火(貌似不支持數據庫的智能問答,會報錯找不到model kwords
# llm = ChatSparkLLM(spark_app_id='應用id',spark_api_key='應用key',spark_api_secret='應用密鑰',spark_llm_domain='generalv3.5')ai_db = SQLDatabase.from_uri("postgresql://postgres:123456@localhost:5433/ai_data",include_tables=['engineering_defect_detail'])def query_with_agent(q: str):"""基于代理的agent+提示詞的查詢優化(給定提示詞后,可以解決枚舉問題,但是給出的答案不是基于sql真實執行的結果):return:"""prompt = '''Given an input question, first create a syntactically correct {dialect} query to run, then look at the results of the query and return the answer.Use the following format strictly:Question: "Question here"SQLQuery: "SQL Query to run"SQLResult: "The actual result after executing the SQLQuery in the database"Answer: "Final answer here"Only use the following tables:['engineering_defect_detail(pk_defect_id, defect_component_id (部件), defect_component_type_id (部件種類), defect_position_id (部位), defect_description_id (缺陷描述), message (缺陷描述), detail (詳情), levl ('1'一般,'2'嚴重,'3'危急), type ('0'可見光,'1'紅外線), tower_name (桿塔名稱), contri_company_name (出資單位名稱), property_company_name (資產單位名稱), maintain_company_name (運維單位名稱), start_tower_no (起始桿號), end_tower_code (終止桿號), search_defect_name (查缺發現人), search_defect_num (查缺發現人人資編碼), polling_time (