ai_agent.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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_sql2 import run, get_query, query_to_nl, table_description
  30. from post_processing_sqlparse import get_query_columns, parse_sql_for_stock_info, get_table_name
  31. def faiss_query(question: str, docs, llm, multi_query: bool = False) -> str:
  32. context = docs
  33. system_prompt: str = "你是一個來自台灣的AI助理,樂於以台灣人的立場幫助使用者,會用繁體中文回答問題。"
  34. template = """
  35. <|begin_of_text|>
  36. <|start_header_id|>system<|end_header_id|>
  37. 你是一個來自台灣的ESG的AI助理,請用繁體中文回答問題 \n
  38. You should not mention anything about "根據提供的文件內容" or other similar terms.
  39. Use five sentences maximum and keep the answer concise.
  40. 如果你不知道答案請回答:"很抱歉,目前我無法回答您的問題,請將您的詢問發送至 test@systex.com 以便獲得更進一步的幫助,謝謝。"
  41. 勿回答無關資訊
  42. <|eot_id|>
  43. <|start_header_id|>user<|end_header_id|>
  44. Answer the following question based on this context:
  45. {context}
  46. Question: {question}
  47. 用繁體中文回答問題
  48. <|eot_id|>
  49. <|start_header_id|>assistant<|end_header_id|>
  50. """
  51. prompt = ChatPromptTemplate.from_template(
  52. system_prompt + "\n\n" +
  53. template
  54. )
  55. rag_chain = prompt | llm | StrOutputParser()
  56. return rag_chain.invoke({"context": context, "question": question})
  57. ### Hallucination Grader
  58. def Hallucination_Grader():
  59. # Prompt
  60. prompt = PromptTemplate(
  61. template=""" <|begin_of_text|><|start_header_id|>system<|end_header_id|>
  62. You are a grader assessing whether an answer is grounded in / supported by a set of facts.
  63. Give 'yes' or 'no' score to indicate whether the answer is grounded in / supported by a set of facts.
  64. Provide 'yes' or 'no' score as a JSON with a single key 'score' and no preamble or explanation.
  65. Return the a JSON with a single key 'score' and no premable or explanation.
  66. <|eot_id|><|start_header_id|>user<|end_header_id|>
  67. Here are the facts:
  68. \n ------- \n
  69. {documents}
  70. \n ------- \n
  71. Here is the answer: {generation}
  72. Provide 'yes' or 'no' score as a JSON with a single key 'score' and no premable or explanation.
  73. <|eot_id|><|start_header_id|>assistant<|end_header_id|>""",
  74. input_variables=["generation", "documents"],
  75. )
  76. hallucination_grader = prompt | llm_json | JsonOutputParser()
  77. return hallucination_grader
  78. ### Answer Grader
  79. def Answer_Grader():
  80. # Prompt
  81. prompt = PromptTemplate(
  82. template="""
  83. <|begin_of_text|><|start_header_id|>system<|end_header_id|> You are a grader assessing whether an
  84. answer is useful to resolve a question. Give a binary score 'yes' or 'no' to indicate whether the answer is
  85. useful to resolve a question. Provide the binary score as a JSON with a single key 'score' and no preamble or explanation.
  86. <|eot_id|><|start_header_id|>user<|end_header_id|> Here is the answer:
  87. \n ------- \n
  88. {generation}
  89. \n ------- \n
  90. Here is the question: {question}
  91. <|eot_id|><|start_header_id|>assistant<|end_header_id|>""",
  92. input_variables=["generation", "question"],
  93. )
  94. answer_grader = prompt | llm_json | JsonOutputParser()
  95. return answer_grader
  96. # Text-to-SQL
  97. def run_text_to_sql(question: str):
  98. selected_table = ['104_112碳排放公開及建準資料', '水電使用量(GHG)', '水電使用量(ISO)']
  99. # question = "建準去年的固定燃燒總排放量是多少?"
  100. query, result, answer = run(db, question, selected_table, llm)
  101. return answer, query
  102. def _get_query(question: str):
  103. selected_table = ['104_112碳排放公開及建準資料', '水電使用量(GHG)', '水電使用量(ISO)']
  104. query = get_query(db, question, selected_table, llm)
  105. return query
  106. def _query_to_nl(question: str, query: str):
  107. answer = query_to_nl(db, question, query, llm)
  108. return answer
  109. def generate_additional_detail(sql_query):
  110. terms = parse_sql_for_stock_info(sql_query)
  111. answer = ""
  112. for term in terms:
  113. if term is None: continue
  114. question_format = [f"什麼是{term}?", f"{term}的用途是什麼", f"如何計算{term}?"]
  115. for question in question_format:
  116. # question = f"什麼是{term}?"
  117. documents = retriever.get_relevant_documents(question, k=30)
  118. generation = faiss_query(question, documents, llm)
  119. answer += generation
  120. answer += "\n"
  121. # print(question)
  122. # print(generation)
  123. return answer
  124. ### SQL Grader
  125. def SQL_Grader():
  126. prompt = PromptTemplate(
  127. template="""<|begin_of_text|><|start_header_id|>system<|end_header_id|>
  128. You are a SQL query grader assessing correctness of PostgreSQL query to a user question.
  129. Based on following database description, you need to grade whether the PostgreSQL query exactly matches the user question.
  130. Here is database description:
  131. {table_info}
  132. You need to check that each where statement is correctly filtered out what user question need.
  133. For example, if user question is "建準去年的固定燃燒總排放量是多少?", and the PostgreSQL query is
  134. "SELECT SUM("排放量(公噸CO2e)") AS "下游租賃總排放量"
  135. FROM "104_112碳排放公開及建準資料"
  136. WHERE "事業名稱" like '%建準%'
  137. AND "排放源" = '下游租賃'
  138. AND "盤查標準" = 'GHG'
  139. AND "年度" = EXTRACT(YEAR FROM CURRENT_DATE)-1;"
  140. 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.
  141. Another example like "建準去年的固定燃燒總排放量是多少?", and the PostgreSQL query is
  142. "SELECT SUM("排放量(公噸CO2e)") AS "固定燃燒總排放量"
  143. FROM "104_112碳排放公開及建準資料"
  144. WHERE "事業名稱" like '%台積電%'
  145. AND "排放源" = '固定燃燒'
  146. AND "盤查標準" = 'GHG'
  147. AND "年度" = EXTRACT(YEAR FROM CURRENT_DATE)-1;"
  148. 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.
  149. and so on. You need to strictly examine whether the sql PostgreSQL query matches the user question.
  150. If the PostgreSQL query do not exactly matches the user question, grade it as incorrect.
  151. You need to strictly examine whether the sql PostgreSQL query matches the user question.
  152. Give a binary score 'yes' or 'no' score to indicate whether the PostgreSQL query is correct to the question. \n
  153. Provide the binary score as a JSON with a single key 'score' and no premable or explanation.
  154. <|eot_id|>
  155. <|start_header_id|>user<|end_header_id|>
  156. Here is the PostgreSQL query: \n\n {sql_query} \n\n
  157. Here is the user question: {question} \n <|eot_id|><|start_header_id|>assistant<|end_header_id|>
  158. """,
  159. input_variables=["table_info", "question", "sql_query"],
  160. )
  161. sql_query_grader = prompt | llm_json | JsonOutputParser()
  162. return sql_query_grader
  163. ### Router
  164. def Router():
  165. prompt = PromptTemplate(
  166. template="""<|begin_of_text|><|start_header_id|>system<|end_header_id|>
  167. You are an expert at routing a user question to a 專業知識 or 自有數據.
  168. Use company private data for questions about the informations about a company's greenhouse gas emissions data.
  169. Otherwise, use the 專業知識 for questions on ESG field knowledge or news about ESG.
  170. You do not need to be stringent with the keywords in the question related to these topics.
  171. Give a binary choice '自有數據' or '專業知識' based on the question.
  172. Return the a JSON with a single key 'datasource' and no premable or explanation.
  173. Question to route: {question}
  174. <|eot_id|><|start_header_id|>assistant<|end_header_id|>""",
  175. input_variables=["question"],
  176. )
  177. question_router = prompt | llm_json | JsonOutputParser()
  178. return question_router
  179. class GraphState(TypedDict):
  180. """
  181. Represents the state of our graph.
  182. Attributes:
  183. question: question
  184. generation: LLM generation
  185. company_private_data: whether to search company private data
  186. documents: list of documents
  187. """
  188. question: str
  189. generation: str
  190. documents: List[str]
  191. retry: int
  192. sql_query: str
  193. # Node
  194. def retrieve_and_generation(state):
  195. """
  196. Retrieve documents from vectorstore
  197. Args:
  198. state (dict): The current graph state
  199. Returns:
  200. state (dict): New key added to state, documents, that contains retrieved documents, and generation, genrating by LLM
  201. """
  202. print("---RETRIEVE---")
  203. question = state["question"]
  204. # Retrieval
  205. # documents = retriever.invoke(question)
  206. # TODO: correct Retrieval function
  207. documents = retriever.get_relevant_documents(question, k=30)
  208. # docs_documents = "\n\n".join(doc.page_content for doc in documents)
  209. # print(documents)
  210. generation = faiss_query(question, documents, llm)
  211. return {"documents": documents, "question": question, "generation": generation}
  212. def company_private_data_get_sql_query(state):
  213. """
  214. Get PostgreSQL query according to question
  215. Args:
  216. state (dict): The current graph state
  217. Returns:
  218. state (dict): return generated PostgreSQL query and record retry times
  219. """
  220. print("---SQL QUERY---")
  221. question = state["question"]
  222. if state["retry"]:
  223. retry = state["retry"]
  224. retry += 1
  225. else:
  226. retry = 0
  227. # print("RETRY: ", retry)
  228. sql_query = _get_query(question)
  229. return {"sql_query": sql_query, "question": question, "retry": retry}
  230. def company_private_data_search(state):
  231. """
  232. Execute PostgreSQL query and convert to nature language.
  233. Args:
  234. state (dict): The current graph state
  235. Returns:
  236. state (dict): Appended sql results to state
  237. """
  238. print("---SQL TO NL---")
  239. # print(state)
  240. question = state["question"]
  241. sql_query = state["sql_query"]
  242. generation = _query_to_nl(question, sql_query)
  243. # generation = [company_private_data_result]
  244. return {"sql_query": sql_query, "question": question, "generation": generation}
  245. def additional_explanation(state):
  246. """
  247. Args:
  248. state (_type_): _description_
  249. Returns:
  250. state (dict): Appended additional explanation to state
  251. """
  252. print("---ADDITIONAL EXPLANATION---")
  253. print(state)
  254. question = state["question"]
  255. sql_query = state["sql_query"]
  256. generation = state["generation"]
  257. generation += "\n"
  258. generation += generate_additional_detail(sql_query)
  259. # generation = [company_private_data_result]
  260. return {"sql_query": sql_query, "question": question, "generation": generation}
  261. ### Conditional edge
  262. def route_question(state):
  263. """
  264. Route question to web search or RAG.
  265. Args:
  266. state (dict): The current graph state
  267. Returns:
  268. str: Next node to call
  269. """
  270. print("---ROUTE QUESTION---")
  271. question = state["question"]
  272. # print(question)
  273. question_router = Router()
  274. source = question_router.invoke({"question": question})
  275. # print(source)
  276. print(source["datasource"])
  277. if source["datasource"] == "自有數據":
  278. print("---ROUTE QUESTION TO TEXT-TO-SQL---")
  279. return "自有數據"
  280. elif source["datasource"] == "專業知識":
  281. print("---ROUTE QUESTION TO RAG---")
  282. return "專業知識"
  283. def grade_generation_v_documents_and_question(state):
  284. """
  285. Determines whether the generation is grounded in the document and answers question.
  286. Args:
  287. state (dict): The current graph state
  288. Returns:
  289. str: Decision for next node to call
  290. """
  291. print("---CHECK HALLUCINATIONS---")
  292. question = state["question"]
  293. documents = state["documents"]
  294. generation = state["generation"]
  295. # print(docs_documents)
  296. # print(generation)
  297. hallucination_grader = Hallucination_Grader()
  298. score = hallucination_grader.invoke(
  299. {"documents": documents, "generation": generation}
  300. )
  301. # print(score)
  302. grade = score["score"]
  303. # Check hallucination
  304. if grade in ["yes", "true", 1, "1"]:
  305. print("---DECISION: GENERATION IS GROUNDED IN DOCUMENTS---")
  306. # Check question-answering
  307. print("---GRADE GENERATION vs QUESTION---")
  308. answer_grader = Answer_Grader()
  309. score = answer_grader.invoke({"question": question, "generation": generation})
  310. grade = score["score"]
  311. if grade in ["yes", "true", 1, "1"]:
  312. print("---DECISION: GENERATION ADDRESSES QUESTION---")
  313. return "useful"
  314. else:
  315. print("---DECISION: GENERATION DOES NOT ADDRESS QUESTION---")
  316. return "not useful"
  317. else:
  318. pprint("---DECISION: GENERATION IS NOT GROUNDED IN DOCUMENTS, RE-TRY---")
  319. return "not supported"
  320. def grade_sql_query(state):
  321. """
  322. Determines whether the Postgresql query are correct to the question
  323. Args:
  324. state (dict): The current graph state
  325. Returns:
  326. state (dict): Decision for retry or continue
  327. """
  328. print("---CHECK SQL CORRECTNESS TO QUESTION---")
  329. question = state["question"]
  330. sql_query = state["sql_query"]
  331. retry = state["retry"]
  332. # Score each doc
  333. sql_query_grader = SQL_Grader()
  334. score = sql_query_grader.invoke({"table_info": table_description(), "question": question, "sql_query": sql_query})
  335. grade = score["score"]
  336. # Document relevant
  337. if grade in ["yes", "true", 1, "1"]:
  338. print("---GRADE: CORRECT SQL QUERY---")
  339. return "correct"
  340. elif retry >= 5:
  341. print("---GRADE: INCORRECT SQL QUERY AND REACH RETRY LIMIT---")
  342. return "failed"
  343. else:
  344. print("---GRADE: INCORRECT SQL QUERY---")
  345. return "incorrect"
  346. def build_graph():
  347. workflow = StateGraph(GraphState)
  348. # Define the nodes
  349. workflow.add_node("Text-to-SQL", company_private_data_get_sql_query, retry=RetryPolicy(max_attempts=5)) # web search
  350. workflow.add_node("SQL Answer", company_private_data_search, retry=RetryPolicy(max_attempts=5)) # web search
  351. workflow.add_node("Additoinal Explanation", additional_explanation, retry=RetryPolicy(max_attempts=5)) # retrieve
  352. workflow.add_node("RAG", retrieve_and_generation, retry=RetryPolicy(max_attempts=5)) # retrieve
  353. workflow.add_conditional_edges(
  354. START,
  355. route_question,
  356. {
  357. "自有數據": "Text-to-SQL",
  358. "專業知識": "RAG",
  359. },
  360. )
  361. workflow.add_conditional_edges(
  362. "RAG",
  363. grade_generation_v_documents_and_question,
  364. {
  365. "not supported": "RAG",
  366. "useful": END,
  367. "not useful": "RAG",
  368. },
  369. )
  370. workflow.add_conditional_edges(
  371. "Text-to-SQL",
  372. grade_sql_query,
  373. {
  374. "correct": "SQL Answer",
  375. "incorrect": "Text-to-SQL",
  376. "failed": "RAG"
  377. },
  378. )
  379. workflow.add_edge("SQL Answer", "Additoinal Explanation")
  380. workflow.add_edge("Additoinal Explanation", END)
  381. app = workflow.compile()
  382. return app
  383. def main(question: str):
  384. app = build_graph()
  385. #建準去年的類別一排放量?
  386. # inputs = {"question": "溫室氣體是什麼"}
  387. inputs = {"question": question}
  388. for output in app.stream(inputs, {"recursion_limit": 10}):
  389. for key, value in output.items():
  390. pprint(f"Finished running: {key}:")
  391. pprint(value["generation"])
  392. return value["generation"]
  393. if __name__ == "__main__":
  394. result = main("建準去年的直接排放排放量?")
  395. print("------------------------------------------------------")
  396. print(result)