ai_agent.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  1. from langchain_community.chat_models import ChatOllama
  2. from langchain_core.output_parsers import JsonOutputParser
  3. from langchain_core.prompts import PromptTemplate
  4. from langchain.prompts import ChatPromptTemplate
  5. from langchain_core.output_parsers import StrOutputParser
  6. # graph usage
  7. from pprint import pprint
  8. from typing import List
  9. from langchain_core.documents import Document
  10. from typing_extensions import TypedDict
  11. from langgraph.graph import END, StateGraph, START
  12. from langgraph.pregel import RetryPolicy
  13. # supabase db
  14. from langchain_community.utilities import SQLDatabase
  15. import os
  16. from dotenv import load_dotenv
  17. load_dotenv()
  18. URI: str = os.environ.get('SUPABASE_URI')
  19. db = SQLDatabase.from_uri(URI)
  20. # LLM
  21. # local_llm = "llama3.1:8b-instruct-fp16"
  22. local_llm = "llama3-groq-tool-use:latest"
  23. llm_json = ChatOllama(model=local_llm, format="json", temperature=0)
  24. llm = ChatOllama(model=local_llm, temperature=0)
  25. # RAG usage
  26. from faiss_index import create_faiss_retriever, faiss_query
  27. retriever = create_faiss_retriever()
  28. # text-to-sql usage
  29. from text_to_sql_private import run, get_query, query_to_nl, table_description
  30. from post_processing_sqlparse import get_query_columns, parse_sql_where, get_table_name
  31. progress_bar = []
  32. def faiss_query(question: str, docs, llm, multi_query: bool = False) -> str:
  33. context = docs
  34. system_prompt: str = "你是一個來自台灣的AI助理,樂於以台灣人的立場幫助使用者,會用繁體中文回答問題。"
  35. template = """
  36. <|begin_of_text|>
  37. <|start_header_id|>system<|end_header_id|>
  38. 你是一個來自台灣的ESG的AI助理,請用繁體中文回答問題 \n
  39. You should not mention anything about "根據提供的文件內容" or other similar terms.
  40. Use five sentences maximum and keep the answer concise.
  41. 如果你不知道答案請回答:"很抱歉,目前我無法回答您的問題,請將您的詢問發送至 test@systex.com 以便獲得更進一步的幫助,謝謝。"
  42. 勿回答無關資訊
  43. <|eot_id|>
  44. <|start_header_id|>user<|end_header_id|>
  45. Answer the following question based on this context:
  46. {context}
  47. Question: {question}
  48. 用繁體中文回答問題
  49. 如果你不知道答案請回答:"很抱歉,目前我無法回答您的問題,請將您的詢問發送至 test@systex.com 以便獲得更進一步的幫助,謝謝。"
  50. <|eot_id|>
  51. <|start_header_id|>assistant<|end_header_id|>
  52. """
  53. prompt = ChatPromptTemplate.from_template(
  54. system_prompt + "\n\n" +
  55. template
  56. )
  57. rag_chain = prompt | llm | StrOutputParser()
  58. return rag_chain.invoke({"context": context, "question": question})
  59. ### Hallucination Grader
  60. def Hallucination_Grader():
  61. # Prompt
  62. prompt = PromptTemplate(
  63. template=""" <|begin_of_text|><|start_header_id|>system<|end_header_id|>
  64. You are a grader assessing whether an answer is grounded in / supported by a set of facts.
  65. Give 'yes' or 'no' score to indicate whether the answer is grounded in / supported by a set of facts.
  66. Provide 'yes' or 'no' score as a JSON with a single key 'score' and no preamble or explanation.
  67. Return the a JSON with a single key 'score' and no premable or explanation.
  68. <|eot_id|><|start_header_id|>user<|end_header_id|>
  69. Here are the facts:
  70. \n ------- \n
  71. {documents}
  72. \n ------- \n
  73. Here is the answer: {generation}
  74. Provide 'yes' or 'no' score as a JSON with a single key 'score' and no premable or explanation.
  75. <|eot_id|><|start_header_id|>assistant<|end_header_id|>""",
  76. input_variables=["generation", "documents"],
  77. )
  78. hallucination_grader = prompt | llm_json | JsonOutputParser()
  79. return hallucination_grader
  80. ### Answer Grader
  81. def Answer_Grader():
  82. # Prompt
  83. prompt = PromptTemplate(
  84. template="""
  85. <|begin_of_text|><|start_header_id|>system<|end_header_id|> You are a grader assessing whether an
  86. answer is useful to resolve a question. Give a binary score 'yes' or 'no' to indicate whether the answer is
  87. useful to resolve a question. Provide the binary score as a JSON with a single key 'score' and no preamble or explanation.
  88. <|eot_id|><|start_header_id|>user<|end_header_id|> Here is the answer:
  89. \n ------- \n
  90. {generation}
  91. \n ------- \n
  92. Here is the question: {question}
  93. <|eot_id|><|start_header_id|>assistant<|end_header_id|>""",
  94. input_variables=["generation", "question"],
  95. )
  96. answer_grader = prompt | llm_json | JsonOutputParser()
  97. return answer_grader
  98. # Text-to-SQL
  99. def run_text_to_sql(question: str):
  100. selected_table = ['用水度數', '用水度數', '建準碳排放清冊數據new']
  101. # question = "建準去年的固定燃燒總排放量是多少?"
  102. query, result, answer = run(db, question, selected_table, llm)
  103. return answer, query
  104. def _get_query(question: str):
  105. selected_table = ['用水度數', '用水度數', '建準碳排放清冊數據new']
  106. query, result = get_query(db, question, selected_table, llm)
  107. return query, result
  108. def _query_to_nl(question: str, query: str, result):
  109. answer = query_to_nl(question, query, result, llm)
  110. return answer
  111. def generate_additional_question(sql_query):
  112. terms = parse_sql_where(sql_query)
  113. question_list = []
  114. for term in terms:
  115. if term is None: continue
  116. question_format = [f"什麼是{term}?", f"{term}的用途是什麼"]
  117. question_list.extend(question_format)
  118. return question_list
  119. def generate_additional_detail(sql_query):
  120. terms = parse_sql_where(sql_query)
  121. answer = ""
  122. for term in list(set(terms)):
  123. if term is None: continue
  124. question_format = [f"請解釋什麼是{term}?"]
  125. for question in question_format:
  126. # question = f"什麼是{term}?"
  127. documents = retriever.get_relevant_documents(question, k=5)
  128. generation = faiss_query(question, documents, llm) + "\n"
  129. if "test@systex.com" in generation:
  130. generation = ""
  131. answer += generation
  132. # print(question)
  133. # print(generation)
  134. return answer
  135. ### SQL Grader
  136. def SQL_Grader():
  137. prompt = PromptTemplate(
  138. template="""<|begin_of_text|><|start_header_id|>system<|end_header_id|>
  139. You are a SQL query grader assessing correctness of PostgreSQL query to a user question.
  140. Based on following database description, you need to grade whether the PostgreSQL query exactly matches the user question.
  141. Here is database description:
  142. {table_info}
  143. You need to check that each where statement is correctly filtered out what user question need.
  144. For example, if user question is "建準去年的固定燃燒總排放量是多少?", and the PostgreSQL query is
  145. "SELECT SUM("排放量(公噸CO2e)") AS "下游租賃總排放量"
  146. FROM "建準碳排放清冊數據new"
  147. WHERE "事業名稱" like '%建準%'
  148. AND "排放源" = '下游租賃'
  149. AND "盤查標準" = 'GHG'
  150. AND "年度" = EXTRACT(YEAR FROM CURRENT_DATE)-1;"
  151. For the above example, we can find that user asked for "固定燃燒", but the PostgreSQL query gives "排放源" = '下游租賃' in WHERE statement, which means the PostgreSQL query is incorrect for the user question.
  152. Another example like "建準去年的固定燃燒總排放量是多少?", and the PostgreSQL query is
  153. "SELECT SUM("排放量(公噸CO2e)") AS "固定燃燒總排放量"
  154. FROM "建準碳排放清冊數據new"
  155. WHERE "事業名稱" like '%台積電%'
  156. AND "排放源" = '固定燃燒'
  157. AND "盤查標準" = 'GHG'
  158. AND "年度" = EXTRACT(YEAR FROM CURRENT_DATE)-1;"
  159. For the above example, we can find that user asked for "建準", but the PostgreSQL query gives "事業名稱" like '%台積電%' in WHERE statement, which means the PostgreSQL query is incorrect for the user question.
  160. and so on. You need to strictly examine whether the sql PostgreSQL query matches the user question.
  161. If the PostgreSQL query do not exactly matches the user question, grade it as incorrect.
  162. You need to strictly examine whether the sql PostgreSQL query matches the user question.
  163. Give a binary score 'yes' or 'no' score to indicate whether the PostgreSQL query is correct to the question. \n
  164. Provide the binary score as a JSON with a single key 'score' and no premable or explanation.
  165. <|eot_id|>
  166. <|start_header_id|>user<|end_header_id|>
  167. Here is the PostgreSQL query: \n\n {sql_query} \n\n
  168. Here is the user question: {question} \n <|eot_id|><|start_header_id|>assistant<|end_header_id|>
  169. """,
  170. input_variables=["table_info", "question", "sql_query"],
  171. )
  172. sql_query_grader = prompt | llm_json | JsonOutputParser()
  173. return sql_query_grader
  174. ### Router
  175. def Router():
  176. prompt = PromptTemplate(
  177. template="""<|begin_of_text|><|start_header_id|>system<|end_header_id|>
  178. You are an expert at routing a user question to a 專業知識 or 自有數據.
  179. Use company private data for questions about the informations about a company's greenhouse gas emissions data.
  180. Otherwise, use the 專業知識 for questions on ESG field knowledge or news about ESG.
  181. You do not need to be stringent with the keywords in the question related to these topics.
  182. Give a binary choice '自有數據' or '專業知識' based on the question.
  183. Return the a JSON with a single key 'datasource' and no premable or explanation.
  184. Question to route: {question}
  185. <|eot_id|><|start_header_id|>assistant<|end_header_id|>""",
  186. input_variables=["question"],
  187. )
  188. question_router = prompt | llm_json | JsonOutputParser()
  189. return question_router
  190. class GraphState(TypedDict):
  191. """
  192. Represents the state of our graph.
  193. Attributes:
  194. question: question
  195. generation: LLM generation
  196. company_private_data: whether to search company private data
  197. documents: list of documents
  198. """
  199. progress_bar: List[str]
  200. route: str
  201. question: str
  202. question_list: List[str]
  203. generation: str
  204. documents: List[str]
  205. retry: int
  206. sql_query: str
  207. sql_result: str
  208. # Node
  209. def show_progress(state, progress: str):
  210. global progress_bar
  211. # progress_bar = state["progress_bar"] if state["progress_bar"] else []
  212. print(progress)
  213. progress_bar.append(progress)
  214. return progress_bar
  215. def retrieve_and_generation(state):
  216. """
  217. Retrieve documents from vectorstore
  218. Args:
  219. state (dict): The current graph state
  220. Returns:
  221. state (dict): New key added to state, documents, that contains retrieved documents, and generation, genrating by LLM
  222. """
  223. progress_bar = show_progress(state, "---RETRIEVE---")
  224. # progress_bar = state["progress"] if state["progress"] else []
  225. # progress = "---RETRIEVE---"
  226. # print(progress)
  227. # progress_bar.append(progress)
  228. if not state["route"]:
  229. route = "RAG"
  230. else:
  231. route = state["route"]
  232. question = state["question"]
  233. # print(state)
  234. question_list = state["question_list"]
  235. # Retrieval
  236. if not question_list:
  237. # documents = retriever.invoke(question)
  238. # TODO: correct Retrieval function
  239. documents = retriever.get_relevant_documents(question, k=5)
  240. for doc in documents:
  241. print(doc)
  242. # docs_documents = "\n\n".join(doc.page_content for doc in documents)
  243. # print(documents)
  244. generation = faiss_query(question, documents, llm)
  245. else:
  246. generation = state["generation"]
  247. for sub_question in list(set(question_list)):
  248. print(sub_question)
  249. documents = retriever.get_relevant_documents(sub_question, k=10)
  250. generation += faiss_query(sub_question, documents, llm)
  251. generation += "\n"
  252. print(generation)
  253. return {"progress_bar": progress_bar, "route": route, "documents": documents, "question": question, "generation": generation}
  254. def company_private_data_get_sql_query(state):
  255. """
  256. Get PostgreSQL query according to question
  257. Args:
  258. state (dict): The current graph state
  259. Returns:
  260. state (dict): return generated PostgreSQL query and record retry times
  261. """
  262. # print("---SQL QUERY---")
  263. progress_bar = show_progress(state, "---SQL QUERY---")
  264. if not state["route"]:
  265. route = "SQL"
  266. else:
  267. route = state["route"]
  268. question = state["question"]
  269. if state["retry"]:
  270. retry = state["retry"]
  271. retry += 1
  272. else:
  273. retry = 0
  274. # print("RETRY: ", retry)
  275. sql_query, sql_result = _get_query(question)
  276. print(type(sql_result))
  277. return {"progress_bar": progress_bar, "route": route, "sql_query": sql_query, "sql_result": sql_result, "question": question, "retry": retry}
  278. def company_private_data_search(state):
  279. """
  280. Execute PostgreSQL query and convert to nature language.
  281. Args:
  282. state (dict): The current graph state
  283. Returns:
  284. state (dict): Appended sql results to state
  285. """
  286. # print("---SQL TO NL---")
  287. progress_bar = show_progress(state, "---SQL TO NL---")
  288. # print(state)
  289. question = state["question"]
  290. sql_query = state["sql_query"]
  291. sql_result = state["sql_result"]
  292. generation = _query_to_nl(question, sql_query, sql_result)
  293. # generation = [company_private_data_result]
  294. return {"progress_bar": progress_bar, "sql_query": sql_query, "question": question, "generation": generation}
  295. def additional_explanation_question(state):
  296. """
  297. Args:
  298. state (_type_): _description_
  299. Returns:
  300. state (dict): Appended additional explanation to state
  301. """
  302. # print("---ADDITIONAL EXPLANATION---")
  303. progress_bar = show_progress(state, "---ADDITIONAL EXPLANATION---")
  304. # print(state)
  305. question = state["question"]
  306. sql_query = state["sql_query"]
  307. # print(sql_query)
  308. generation = state["generation"]
  309. generation += "\n"
  310. generation += generate_additional_detail(sql_query)
  311. question_list = []
  312. # question_list = generate_additional_question(sql_query)
  313. # print(question_list)
  314. # generation = [company_private_data_result]
  315. return {"progress_bar": progress_bar, "sql_query": sql_query, "question": question, "generation": generation, "question_list": question_list}
  316. def error(state):
  317. # print("---SOMETHING WENT WRONG---")
  318. progress_bar = show_progress(state, "---SOMETHING WENT WRONG---")
  319. generation = "很抱歉,目前我無法回答您的問題,請將您的詢問發送至 test@systex.com 以便獲得更進一步的幫助,謝謝。"
  320. return {"progress_bar": progress_bar, "generation": generation}
  321. ### Conditional edge
  322. def route_question(state):
  323. """
  324. Route question to web search or RAG.
  325. Args:
  326. state (dict): The current graph state
  327. Returns:
  328. str: Next node to call
  329. """
  330. # print("---ROUTE QUESTION---")
  331. progress_bar = show_progress(state, "---ROUTE QUESTION---")
  332. question = state["question"]
  333. # print(question)
  334. question_router = Router()
  335. source = question_router.invoke({"question": question})
  336. if "建準" in question:
  337. source["datasource"] = "自有數據"
  338. # print(source)
  339. print(source["datasource"])
  340. if source["datasource"] == "自有數據":
  341. # print("---ROUTE QUESTION TO TEXT-TO-SQL---")
  342. progress_bar = show_progress(state, "---ROUTE QUESTION TO TEXT-TO-SQL---")
  343. return "自有數據"
  344. elif source["datasource"] == "專業知識":
  345. # print("---ROUTE QUESTION TO RAG---")
  346. progress_bar = show_progress(state, "---ROUTE QUESTION TO RAG---")
  347. return "專業知識"
  348. def grade_generation_v_documents_and_question(state):
  349. """
  350. Determines whether the generation is grounded in the document and answers question.
  351. Args:
  352. state (dict): The current graph state
  353. Returns:
  354. str: Decision for next node to call
  355. """
  356. # print("---CHECK HALLUCINATIONS---")
  357. question = state["question"]
  358. documents = state["documents"]
  359. generation = state["generation"]
  360. progress_bar = show_progress(state, "---GRADE GENERATION vs QUESTION---")
  361. answer_grader = Answer_Grader()
  362. score = answer_grader.invoke({"question": question, "generation": generation})
  363. grade = score["score"]
  364. if grade in ["yes", "true", 1, "1"]:
  365. # print("---DECISION: GENERATION ADDRESSES QUESTION---")
  366. progress_bar = show_progress(state, "---DECISION: GENERATION ADDRESSES QUESTION---")
  367. return "useful"
  368. else:
  369. # print("---DECISION: GENERATION DOES NOT ADDRESS QUESTION---")
  370. progress_bar = show_progress(state, "---DECISION: GENERATION DOES NOT ADDRESS QUESTION---")
  371. return "not useful"
  372. # progress_bar = show_progress(state, "---CHECK HALLUCINATIONS---")
  373. # # print(docs_documents)
  374. # # print(generation)
  375. # hallucination_grader = Hallucination_Grader()
  376. # score = hallucination_grader.invoke(
  377. # {"documents": documents, "generation": generation}
  378. # )
  379. # # print(score)
  380. # grade = score["score"]
  381. # # Check hallucination
  382. # if grade in ["yes", "true", 1, "1"]:
  383. # # print("---DECISION: GENERATION IS GROUNDED IN DOCUMENTS---")
  384. # progress_bar = show_progress(state, "---DECISION: GENERATION IS GROUNDED IN DOCUMENTS---")
  385. # # Check question-answering
  386. # # print("---GRADE GENERATION vs QUESTION---")
  387. # progress_bar = show_progress(state, "---GRADE GENERATION vs QUESTION---")
  388. # answer_grader = Answer_Grader()
  389. # score = answer_grader.invoke({"question": question, "generation": generation})
  390. # grade = score["score"]
  391. # if grade in ["yes", "true", 1, "1"]:
  392. # # print("---DECISION: GENERATION ADDRESSES QUESTION---")
  393. # progress_bar = show_progress(state, "---DECISION: GENERATION ADDRESSES QUESTION---")
  394. # return "useful"
  395. # else:
  396. # # print("---DECISION: GENERATION DOES NOT ADDRESS QUESTION---")
  397. # progress_bar = show_progress(state, "---DECISION: GENERATION DOES NOT ADDRESS QUESTION---")
  398. # return "not useful"
  399. # else:
  400. # # pprint("---DECISION: GENERATION IS NOT GROUNDED IN DOCUMENTS, RE-TRY---")
  401. # progress_bar = show_progress(state, "---DECISION: GENERATION IS NOT GROUNDED IN DOCUMENTS, RE-TRY---")
  402. # return "not supported"
  403. def grade_sql_query(state):
  404. """
  405. Determines whether the Postgresql query are correct to the question
  406. Args:
  407. state (dict): The current graph state
  408. Returns:
  409. state (dict): Decision for retry or continue
  410. """
  411. # print("---CHECK SQL CORRECTNESS TO QUESTION---")
  412. progress_bar = show_progress(state, "---CHECK SQL CORRECTNESS TO QUESTION---")
  413. question = state["question"]
  414. sql_query = state["sql_query"]
  415. sql_result = state["sql_result"]
  416. if "None" in sql_result:
  417. progress_bar = show_progress(state, "---INCORRECT SQL QUERY---")
  418. return "incorrect"
  419. else:
  420. progress_bar = show_progress(state, "---CORRECT SQL QUERY---")
  421. return "correct"
  422. # retry = state["retry"]
  423. # # Score each doc
  424. # sql_query_grader = SQL_Grader()
  425. # score = sql_query_grader.invoke({"table_info": table_description(), "question": question, "sql_query": sql_query})
  426. # grade = score["score"]
  427. # # Document relevant
  428. # if grade in ["yes", "true", 1, "1"]:
  429. # # print("---GRADE: CORRECT SQL QUERY---")
  430. # progress_bar = show_progress(state, "---GRADE: CORRECT SQL QUERY---")
  431. # return "correct"
  432. # elif retry >= 5:
  433. # # print("---GRADE: INCORRECT SQL QUERY AND REACH RETRY LIMIT---")
  434. # progress_bar = show_progress(state, "---GRADE: INCORRECT SQL QUERY AND REACH RETRY LIMIT---")
  435. # return "failed"
  436. # else:
  437. # # print("---GRADE: INCORRECT SQL QUERY---")
  438. # progress_bar = show_progress(state, "---GRADE: INCORRECT SQL QUERY---")
  439. # return "incorrect"
  440. def build_graph():
  441. workflow = StateGraph(GraphState)
  442. # Define the nodes
  443. workflow.add_node("Text-to-SQL", company_private_data_get_sql_query, retry=RetryPolicy(max_attempts=5)) # web search
  444. workflow.add_node("SQL Answer", company_private_data_search, retry=RetryPolicy(max_attempts=5)) # web search
  445. workflow.add_node("Additoinal Explanation", additional_explanation_question, retry=RetryPolicy(max_attempts=5)) # retrieve
  446. workflow.add_node("RAG", retrieve_and_generation, retry=RetryPolicy(max_attempts=5)) # retrieve
  447. workflow.add_node("ERROR", error) # retrieve
  448. workflow.add_conditional_edges(
  449. START,
  450. route_question,
  451. {
  452. "自有數據": "Text-to-SQL",
  453. "專業知識": "RAG",
  454. },
  455. )
  456. workflow.add_conditional_edges(
  457. "RAG",
  458. grade_generation_v_documents_and_question,
  459. {
  460. "useful": END,
  461. "not useful": "ERROR",
  462. },
  463. )
  464. workflow.add_conditional_edges(
  465. "Text-to-SQL",
  466. grade_sql_query,
  467. {
  468. "correct": "SQL Answer",
  469. "incorrect": "RAG",
  470. },
  471. )
  472. workflow.add_edge("SQL Answer", "Additoinal Explanation")
  473. workflow.add_edge("Additoinal Explanation", END)
  474. app = workflow.compile()
  475. return app
  476. app = build_graph()
  477. draw_mermaid = app.get_graph().draw_mermaid()
  478. print(draw_mermaid)
  479. def main(question: str):
  480. # app = build_graph()
  481. # draw_mermaid = app.get_graph().draw_mermaid()
  482. # print(draw_mermaid)
  483. #建準去年的類別一排放量?
  484. # inputs = {"question": "溫室氣體是什麼"}
  485. inputs = {"question": question, "progress_bar": None}
  486. for output in app.stream(inputs, {"recursion_limit": 10}):
  487. for key, value in output.items():
  488. pprint(f"Finished running: {key}:")
  489. # pprint(value["generation"])
  490. # pprint(value)
  491. value["progress_bar"] = progress_bar
  492. # pprint(value["progress_bar"])
  493. return value["generation"]
  494. if __name__ == "__main__":
  495. # result = main("建準去年的逸散排放總排放量是多少?")
  496. result = main("建準夏威夷去年的綠電使用量是多少?")
  497. # result = main("溫室氣體是什麼?")
  498. # result = main("什麼是外購電力(綠電)?")
  499. print("------------------------------------------------------")
  500. print(result)