main
py 55 lines 2 KB
Raw
1 import asyncio
2
3 from helpers.tool import Tool, Response
4 from plugins._document_query.helpers.document_query import DocumentQueryHelper
5
6
7 class DocumentQueryTool(Tool):
8
9 async def execute(self, **kwargs):
10 document_uri = kwargs.get("document")
11 document_uris = []
12
13 if isinstance(document_uri, list):
14 document_uris = document_uri
15 elif isinstance(document_uri, str):
16 document_uris = [document_uri]
17
18 if not document_uris:
19 return Response(message="Error: no document provided", break_loop=False)
20
21 queries = (
22 kwargs["queries"]
23 if "queries" in kwargs
24 else [kwargs["query"]]
25 if ("query" in kwargs and kwargs["query"])
26 else []
27 )
28 try:
29 progress = []
30
31 def progress_callback(msg):
32 progress.append(msg)
33 self.log.update(progress="\n".join(progress))
34
35 helper = DocumentQueryHelper(self.agent, progress_callback)
36 if not queries:
37 gather_timeout = helper.config.get("gather_timeout", 120)
38 try:
39 contents = await asyncio.wait_for(
40 asyncio.gather(
41 *[helper.document_get_content(uri) for uri in document_uris]
42 ),
43 timeout=gather_timeout,
44 )
45 except asyncio.TimeoutError:
46 return Response(
47 message=f"Error: document processing timed out after {gather_timeout}s",
48 break_loop=False,
49 )
50 content = "\n\n---\n\n".join(contents)
51 else:
52 _, content = await helper.document_qa(document_uris, queries)
53 return Response(message=content, break_loop=False)
54 except Exception as e: # pylint: disable=broad-exception-caught
55 return Response(message=f"Error processing document: {e}", break_loop=False)