|
| 1 | +""" |
| 2 | +File name: answer_generator.py |
| 3 | +Author: Luigi Saetta |
| 4 | +Date last modified: 2025-03-31 |
| 5 | +Python Version: 3.11 |
| 6 | +
|
| 7 | +Description: |
| 8 | + This module implements the last step in the workflow: generation |
| 9 | + of the answer form the LLM: |
| 10 | +
|
| 11 | +
|
| 12 | +Usage: |
| 13 | + Import this module into other scripts to use its functions. |
| 14 | + Example: |
| 15 | + from answer_generator import AnswerGenerator |
| 16 | +
|
| 17 | +License: |
| 18 | + This code is released under the MIT License. |
| 19 | +
|
| 20 | +Notes: |
| 21 | + This is a part of a demo showing how to implement an advanced |
| 22 | + RAG solution as a LangGraph agent. |
| 23 | +
|
| 24 | +Warnings: |
| 25 | + This module is in development, may change in future versions. |
| 26 | +""" |
| 27 | + |
| 28 | +from langchain_core.runnables import Runnable |
| 29 | +from langchain_core.messages import SystemMessage, HumanMessage |
| 30 | +from langchain.prompts import PromptTemplate |
| 31 | + |
| 32 | +# integration with APM |
| 33 | +from py_zipkin.zipkin import zipkin_span |
| 34 | + |
| 35 | +from agent_state import State |
| 36 | +from oci_models import get_llm |
| 37 | +from prompts import ( |
| 38 | + ANSWER_PROMPT_TEMPLATE, |
| 39 | +) |
| 40 | + |
| 41 | +from utils import get_console_logger |
| 42 | +from config import AGENT_NAME, DEBUG |
| 43 | + |
| 44 | +logger = get_console_logger() |
| 45 | + |
| 46 | + |
| 47 | +class AnswerGenerator(Runnable): |
| 48 | + """ |
| 49 | + Takes the user request and the chat history and rewrite the user query |
| 50 | + in a standalone question that is used for the semantic search |
| 51 | + """ |
| 52 | + |
| 53 | + def __init__(self): |
| 54 | + """ |
| 55 | + Init |
| 56 | + """ |
| 57 | + self.dict_languages = { |
| 58 | + "en": "English", |
| 59 | + "fr": "French", |
| 60 | + "it": "Italian", |
| 61 | + "es": "Spanish", |
| 62 | + } |
| 63 | + |
| 64 | + def build_context_for_llm(self, docs: list): |
| 65 | + """ |
| 66 | + Build the context for the final answer from LLM |
| 67 | +
|
| 68 | + docs: list[Documents] |
| 69 | + """ |
| 70 | + _context = "" |
| 71 | + |
| 72 | + for doc in docs: |
| 73 | + _context += doc.page_content + "\n\n" |
| 74 | + |
| 75 | + return _context |
| 76 | + |
| 77 | + @zipkin_span(service_name=AGENT_NAME, span_name="answer_generation") |
| 78 | + def invoke(self, input: State, config=None, **kwargs): |
| 79 | + """ |
| 80 | + Generate the final answer |
| 81 | + """ |
| 82 | + # get the config |
| 83 | + model_id = config["configurable"]["model_id"] |
| 84 | + |
| 85 | + if config["configurable"]["main_language"] in self.dict_languages: |
| 86 | + # want to change language |
| 87 | + main_language = self.dict_languages.get( |
| 88 | + config["configurable"]["main_language"] |
| 89 | + ) |
| 90 | + else: |
| 91 | + # "same as the question" (default) |
| 92 | + # answer will be in the same language as the question |
| 93 | + main_language = None |
| 94 | + |
| 95 | + if DEBUG: |
| 96 | + logger.info("AnswerGenerator, model_id: %s", model_id) |
| 97 | + logger.info("AnswerGenerator, main_language: %s", main_language) |
| 98 | + |
| 99 | + final_answer = "" |
| 100 | + error = None |
| 101 | + |
| 102 | + try: |
| 103 | + llm = get_llm(model_id=model_id) |
| 104 | + |
| 105 | + _context = self.build_context_for_llm(input["reranker_docs"]) |
| 106 | + |
| 107 | + system_prompt = PromptTemplate( |
| 108 | + input_variables=["context"], |
| 109 | + template=ANSWER_PROMPT_TEMPLATE, |
| 110 | + ).format(context=_context) |
| 111 | + |
| 112 | + messages = [ |
| 113 | + SystemMessage(content=system_prompt), |
| 114 | + ] |
| 115 | + # add the chat history |
| 116 | + for msg in input["chat_history"]: |
| 117 | + messages.append(msg) |
| 118 | + |
| 119 | + # to force the answer in the selected language |
| 120 | + if main_language is not None: |
| 121 | + the_question = f"{input['user_request']}. Answer in {main_language}." |
| 122 | + else: |
| 123 | + # no cross language |
| 124 | + the_question = input["user_request"] |
| 125 | + |
| 126 | + messages.append(HumanMessage(content=the_question)) |
| 127 | + |
| 128 | + # here we invoke the LLM and we return the generator |
| 129 | + final_answer = llm.stream(messages) |
| 130 | + |
| 131 | + except Exception as e: |
| 132 | + logger.error("Error in generate_answer: %s", e) |
| 133 | + error = str(e) |
| 134 | + |
| 135 | + return {"final_answer": final_answer, "error": error} |
0 commit comments