|
| 1 | +""" |
| 2 | +Single Agent for Doc-aware chat with user. |
| 3 | +
|
| 4 | +- user asks question |
| 5 | +- LLM decides whether to: |
| 6 | + - ask user for follow-up/clarifying information, or |
| 7 | + - retrieve relevant passages from documents, or |
| 8 | + - provide a final answer, if it has enough information from user and documents. |
| 9 | +
|
| 10 | +To reduce response latency, in the DocChatAgentConfig, |
| 11 | +you can set the `relevance_extractor_config=None`, |
| 12 | +to turn off the relevance_extraction step, which uses the LLM |
| 13 | +to extract verbatim relevant portions of retrieved chunks. |
| 14 | +
|
| 15 | +Run like this: |
| 16 | +
|
| 17 | +python3 examples/docqa/doc-aware-chat.py |
| 18 | +""" |
| 19 | + |
| 20 | +from typing import Optional, Any |
| 21 | + |
| 22 | +from rich import print |
| 23 | +from rich.prompt import Prompt |
| 24 | +import os |
| 25 | + |
| 26 | +from langroid import ChatDocument |
| 27 | +from langroid.agent.special.doc_chat_agent import ( |
| 28 | + DocChatAgent, |
| 29 | + DocChatAgentConfig, |
| 30 | +) |
| 31 | +import langroid.language_models as lm |
| 32 | +from langroid.mytypes import Entity |
| 33 | +from langroid.parsing.parser import ParsingConfig, PdfParsingConfig, Splitter |
| 34 | +from langroid.agent.chat_agent import ChatAgent |
| 35 | +from langroid.agent.task import Task |
| 36 | +from langroid.agent.tools.orchestration import ForwardTool |
| 37 | +from langroid.agent.tools.retrieval_tool import RetrievalTool |
| 38 | +from langroid.utils.configuration import set_global, Settings |
| 39 | +from fire import Fire |
| 40 | + |
| 41 | +os.environ["TOKENIZERS_PARALLELISM"] = "false" |
| 42 | + |
| 43 | + |
| 44 | +class DocAwareChatAgent(DocChatAgent): |
| 45 | + def __init__(self, config: DocChatAgentConfig): |
| 46 | + super().__init__(config) |
| 47 | + self.enable_message(RetrievalTool) |
| 48 | + |
| 49 | + def retrieval_tool(self, msg: RetrievalTool) -> str: |
| 50 | + results = super().retrieval_tool(msg) |
| 51 | + return f""" |
| 52 | + |
| 53 | + RELEVANT PASSAGES: |
| 54 | + ===== |
| 55 | + {results} |
| 56 | + ==== |
| 57 | + |
| 58 | + |
| 59 | + BASED on these RELEVANT PASSAGES, DECIDE: |
| 60 | + - If this is sufficient to provide the user a final answer specific to |
| 61 | + their situation, do so. |
| 62 | + - Otherwise, |
| 63 | + - ASK the user for more information to get a better understanding |
| 64 | + of their situation or context, OR |
| 65 | + - use this tool again to get more relevant passages. |
| 66 | + """ |
| 67 | + |
| 68 | + def llm_response( |
| 69 | + self, |
| 70 | + query: None | str | ChatDocument = None, |
| 71 | + ) -> Optional[ChatDocument]: |
| 72 | + # override DocChatAgent's default llm_response |
| 73 | + return ChatAgent.llm_response(self, query) |
| 74 | + |
| 75 | + def handle_message_fallback(self, msg: str | ChatDocument) -> Any: |
| 76 | + # we are here if there is no tool in the msg |
| 77 | + if isinstance(msg, ChatDocument) and msg.metadata.sender == Entity.LLM: |
| 78 | + # Any non-tool message must be meant for user, so forward it to user |
| 79 | + return ForwardTool(agent="User") |
| 80 | + |
| 81 | + |
| 82 | +def main( |
| 83 | + debug: bool = False, |
| 84 | + nocache: bool = False, |
| 85 | + model: str = lm.OpenAIChatModel.GPT4o, |
| 86 | +) -> None: |
| 87 | + llm_config = lm.OpenAIGPTConfig(chat_model=model) |
| 88 | + config = DocChatAgentConfig( |
| 89 | + llm=llm_config, |
| 90 | + n_query_rephrases=0, |
| 91 | + hypothetical_answer=False, |
| 92 | + relevance_extractor_config=None, |
| 93 | + # this turns off standalone-query reformulation; set to False to enable it. |
| 94 | + assistant_mode=True, |
| 95 | + n_neighbor_chunks=2, |
| 96 | + parsing=ParsingConfig( # modify as needed |
| 97 | + splitter=Splitter.TOKENS, |
| 98 | + chunk_size=100, # aim for this many tokens per chunk |
| 99 | + n_neighbor_ids=5, |
| 100 | + overlap=20, # overlap between chunks |
| 101 | + max_chunks=10_000, |
| 102 | + # aim to have at least this many chars per chunk when |
| 103 | + # truncating due to punctuation |
| 104 | + min_chunk_chars=200, |
| 105 | + discard_chunk_chars=5, # discard chunks with fewer than this many chars |
| 106 | + n_similar_docs=5, |
| 107 | + # NOTE: PDF parsing is extremely challenging, each library has its own |
| 108 | + # strengths and weaknesses. Try one that works for your use case. |
| 109 | + pdf=PdfParsingConfig( |
| 110 | + # alternatives: "unstructured", "pdfplumber", "fitz" |
| 111 | + library="fitz", |
| 112 | + ), |
| 113 | + ), |
| 114 | + ) |
| 115 | + |
| 116 | + set_global( |
| 117 | + Settings( |
| 118 | + debug=debug, |
| 119 | + cache=not nocache, |
| 120 | + ) |
| 121 | + ) |
| 122 | + |
| 123 | + doc_agent = DocAwareChatAgent(config) |
| 124 | + print("[blue]Welcome to the document chatbot!") |
| 125 | + url = Prompt.ask("[blue]Enter the URL of a document") |
| 126 | + doc_agent.ingest_doc_paths([url]) |
| 127 | + |
| 128 | + # For a more flexible/elaborate user doc-ingest dialog, use this: |
| 129 | + # doc_agent.user_docs_ingest_dialog() |
| 130 | + |
| 131 | + doc_task = Task( |
| 132 | + doc_agent, |
| 133 | + interactive=False, |
| 134 | + name="DocAgent", |
| 135 | + system_message=f""" |
| 136 | + You are a DOCUMENT-AWARE-GUIDE, but you do NOT have direct access to documents. |
| 137 | + Instead you can use the `retrieval_tool` to get passages from the documents |
| 138 | + that are relevant to a certain query or search phrase or topic. |
| 139 | + DO NOT ATTEMPT TO ANSWER THE USER'S QUESTION WITHOUT RETRIEVING RELEVANT |
| 140 | + PASSAGES FROM THE DOCUMENTS. DO NOT use your own existing knowledge!! |
| 141 | + Everything you tell the user MUST be based on the documents. |
| 142 | + |
| 143 | + The user will ask you a question that you will NOT be able to answer |
| 144 | + immediately, because you are MISSING some information about: |
| 145 | + - the user or their context or situation, etc |
| 146 | + - the documents relevant to the question |
| 147 | + |
| 148 | + At each turn you must decide among these possible ACTIONS: |
| 149 | + - use the `{RetrievalTool.name()}` to get more relevant passages from the |
| 150 | + documents, OR |
| 151 | + - ANSWER the user if you think you have enough information |
| 152 | + from the user AND the documents, to answer the question. |
| 153 | + |
| 154 | + You can use the `{RetrievalTool.name()}` multiple times to get more |
| 155 | + relevant passages, if you think the previous ones were not sufficient. |
| 156 | + |
| 157 | + REMEMBER - your goal is to be VERY HELPFUL to the user; this means |
| 158 | + you should NOT OVERWHELM them by throwing them a lot of information and |
| 159 | + ask them to figure things out. Instead, you must GUIDE them |
| 160 | + by asking SIMPLE QUESTIONS, ONE at at time, and finally provide them |
| 161 | + a clear, DIRECTLY RELEVANT answer that is specific to their situation. |
| 162 | + """, |
| 163 | + ) |
| 164 | + |
| 165 | + print("[cyan]Enter x or q to quit, or ? for evidence") |
| 166 | + |
| 167 | + doc_task.run("Can you help me with some questions?") |
| 168 | + |
| 169 | + |
| 170 | +if __name__ == "__main__": |
| 171 | + Fire(main) |
0 commit comments