ws-bom-robot-app 0.0.30__tar.gz → 0.0.31__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. {ws_bom_robot_app-0.0.30/ws_bom_robot_app.egg-info → ws_bom_robot_app-0.0.31}/PKG-INFO +2 -5
  2. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/README.md +1 -4
  3. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/setup.py +1 -1
  4. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/llm/agent_description.py +124 -124
  5. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/llm/agent_handler.py +167 -167
  6. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/llm/agent_lcel.py +64 -64
  7. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/llm/defaut_prompt.py +9 -9
  8. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/llm/main.py +102 -102
  9. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/llm/settings.py +4 -4
  10. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/llm/tools/tool_builder.py +19 -19
  11. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/llm/tools/tool_manager.py +101 -101
  12. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/llm/tools/utils.py +25 -25
  13. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/llm/utils/agent_utils.py +16 -16
  14. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/llm/utils/download.py +79 -79
  15. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/llm/utils/print.py +29 -29
  16. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/llm/vector_store/generator.py +137 -137
  17. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/llm/vector_store/loader/base.py +2 -2
  18. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/llm/vector_store/loader/json_loader.py +25 -25
  19. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31/ws_bom_robot_app.egg-info}/PKG-INFO +2 -5
  20. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/MANIFEST.in +0 -0
  21. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/pyproject.toml +0 -0
  22. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/requirements.txt +0 -0
  23. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/setup.cfg +0 -0
  24. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/__init__.py +0 -0
  25. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/auth.py +0 -0
  26. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/config.py +0 -0
  27. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/cron_manager.py +0 -0
  28. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/llm/__init__.py +0 -0
  29. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/llm/api.py +0 -0
  30. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/llm/models/__init__.py +0 -0
  31. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/llm/models/api.py +0 -0
  32. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/llm/models/base.py +0 -0
  33. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/llm/models/kb.py +0 -0
  34. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/llm/tools/__init__.py +0 -0
  35. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/llm/tools/models/__init__.py +0 -0
  36. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/llm/tools/models/main.py +0 -0
  37. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/llm/utils/__init__.py +0 -0
  38. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/llm/utils/chunker.py +0 -0
  39. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/llm/utils/faiss_helper.py +0 -0
  40. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/llm/utils/kb.py +0 -0
  41. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/llm/utils/webhooks.py +0 -0
  42. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/llm/vector_store/__init__.py +0 -0
  43. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/llm/vector_store/integration/__init__.py +0 -0
  44. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/llm/vector_store/integration/azure.py +0 -0
  45. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/llm/vector_store/integration/base.py +0 -0
  46. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/llm/vector_store/integration/confluence.py +0 -0
  47. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/llm/vector_store/integration/dropbox.py +0 -0
  48. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/llm/vector_store/integration/gcs.py +0 -0
  49. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/llm/vector_store/integration/github.py +0 -0
  50. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/llm/vector_store/integration/googledrive.py +0 -0
  51. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/llm/vector_store/integration/jira.py +0 -0
  52. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/llm/vector_store/integration/manager.py +0 -0
  53. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/llm/vector_store/integration/s3.py +0 -0
  54. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/llm/vector_store/integration/sftp.py +0 -0
  55. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/llm/vector_store/integration/sharepoint.py +0 -0
  56. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/llm/vector_store/integration/sitemap.py +0 -0
  57. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/llm/vector_store/integration/slack.py +0 -0
  58. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/llm/vector_store/loader/__init__.py +0 -0
  59. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/llm/vector_store/loader/docling.py +0 -0
  60. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/main.py +0 -0
  61. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/task_manager.py +0 -0
  62. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app/util.py +0 -0
  63. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app.egg-info/SOURCES.txt +0 -0
  64. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app.egg-info/dependency_links.txt +0 -0
  65. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app.egg-info/requires.txt +0 -0
  66. {ws_bom_robot_app-0.0.30 → ws_bom_robot_app-0.0.31}/ws_bom_robot_app.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.2
2
2
  Name: ws_bom_robot_app
3
- Version: 0.0.30
3
+ Version: 0.0.31
4
4
  Summary: A FastAPI application serving ws bom/robot/llm platform ai.
5
5
  Home-page: https://github.com/websolutespa/bom
6
6
  Author: Websolute Spa
@@ -185,10 +185,7 @@ py -m pip install --upgrade setuptools build twine streamlit
185
185
  ### 🪛 build
186
186
 
187
187
  ```pwsh
188
- if (Test-Path ./dist) {rm ./dist -r -force}; `
189
- cp .\requirements.txt .\ws_bom_robot_app\ && `
190
- py -m build && `
191
- twine check dist/*
188
+ py -m build && twine check dist/*
192
189
  ```
193
190
 
194
191
  ### 📦 test / 🧪 debugger
@@ -135,10 +135,7 @@ py -m pip install --upgrade setuptools build twine streamlit
135
135
  ### 🪛 build
136
136
 
137
137
  ```pwsh
138
- if (Test-Path ./dist) {rm ./dist -r -force}; `
139
- cp .\requirements.txt .\ws_bom_robot_app\ && `
140
- py -m build && `
141
- twine check dist/*
138
+ py -m build && twine check dist/*
142
139
  ```
143
140
 
144
141
  ### 📦 test / 🧪 debugger
@@ -4,7 +4,7 @@ _requirements = [line.split('#')[0].strip() for line in open("requirements.txt")
4
4
 
5
5
  setup(
6
6
  name="ws_bom_robot_app",
7
- version="0.0.30",
7
+ version="0.0.31",
8
8
  description="A FastAPI application serving ws bom/robot/llm platform ai.",
9
9
  long_description=open("README.md", encoding='utf-8').read(),
10
10
  long_description_content_type="text/markdown",
@@ -1,124 +1,124 @@
1
- import json, requests, re
2
- from typing import Any
3
- from abc import ABC, abstractmethod
4
- from langchain_openai import ChatOpenAI
5
- from langchain_core.prompts import ChatPromptTemplate
6
- from langchain_core.messages import AIMessage
7
- from langchain_core.runnables import RunnableSerializable
8
- from langchain_core.runnables import RunnableLambda
9
- from bs4 import BeautifulSoup
10
- from ws_bom_robot_app.llm.models.api import LlmRules
11
- from ws_bom_robot_app.llm.utils.agent_utils import get_rules
12
-
13
- # SafeDict helper class
14
- class SafeDict(dict):
15
- def __missing__(self, key):
16
- return ''
17
-
18
- # Strategy Interface
19
- class AgentDescriptorStrategy(ABC):
20
- @abstractmethod
21
- def enrich_prompt(self, prompt: str, input: dict) -> str:
22
- pass
23
-
24
- @abstractmethod
25
- def rule_input(self, input: dict) -> str:
26
- pass
27
-
28
- # Concrete Strategy for Default Agent
29
- class DefaultAgentDescriptor(AgentDescriptorStrategy):
30
- def enrich_prompt(self, prompt: str, input: dict) -> str:
31
- # Default enrichment logic (could be minimal or no-op)
32
- return prompt.format_map(SafeDict(input))
33
-
34
- def rule_input(self, input: dict) -> str:
35
- return input.get('content', "")
36
-
37
- # Concrete Strategy for URL2Text Agent
38
- class URL2TextAgentDescriptor(AgentDescriptorStrategy):
39
- def enrich_prompt(self, prompt: str, input: dict) -> str:
40
- input["context"] = self._get_page_text(input)
41
- return prompt.format_map(SafeDict(input))
42
-
43
- def rule_input(self, input: dict) -> str:
44
- return input.get('context', "")
45
-
46
- def _get_page_text(self, input: dict) -> str:
47
- url = input.get("content", "")
48
- exclusions = input.get("exclude", {})
49
- response = requests.get(url)
50
- response.raise_for_status()
51
- soup = BeautifulSoup(response.content, 'html5lib')
52
- classes_to_exclude = exclusions.get("classes", [])
53
- ids_to_exclude = exclusions.get("ids", [])
54
- for class_name in classes_to_exclude:
55
- for element in soup.find_all(class_=class_name):
56
- element.extract()
57
- for id_name in ids_to_exclude:
58
- for element in soup.find_all(id=id_name):
59
- element.extract()
60
- for script in soup(["script", "noscript", "style", "head", "footer", "iframe"]):
61
- script.extract()
62
- return re.sub(' +', ' ', soup.get_text())
63
-
64
-
65
- class AgentDescriptor:
66
- # Dictionary to hold all agent strategies
67
- _list: dict[str,AgentDescriptorStrategy] = {
68
- "default": DefaultAgentDescriptor(),
69
- "url2text": URL2TextAgentDescriptor(),
70
- }
71
-
72
- # Functions to manage strategies
73
- @staticmethod
74
- def add_strategy(name: str, strategy: AgentDescriptorStrategy):
75
- """_summary_
76
- add a new strategy to the dictionary
77
- Args:
78
- name (str): name of the strategy, in lowercase
79
- strategy (AgentDescriptorStrategy): class implementing the strategy
80
- Examples:
81
- AgentDescriptor.add_strategy("custom_agent_descriptor", CustomAgentDescriptor())
82
- """
83
- AgentDescriptor._list[name.lower()] = strategy
84
-
85
- @staticmethod
86
- def get_strategy(name: str) -> AgentDescriptorStrategy:
87
- return AgentDescriptor._list.get(name.lower(), DefaultAgentDescriptor())
88
-
89
- def __init__(self, api_key: str, prompt: str, mode: str, rules: LlmRules = None):
90
- self.__prompt = prompt
91
- self.__llm = ChatOpenAI(model="gpt-4o", temperature=0, api_key=api_key) # type: ignore
92
- self.api_key = api_key
93
- self.rules= rules
94
- self.strategy = self.get_strategy(mode) # Selects the strategy from the dictionary
95
-
96
- async def __create_prompt(self, input_dict: dict):
97
- input_data = json.loads(input_dict.get("input", {}))
98
- system = self.strategy.enrich_prompt(self.__prompt, input_data)
99
- if self.rules:
100
- rule_input = self.strategy.rule_input(input_data)
101
- rules_prompt = await get_rules(self.rules,self.api_key, rule_input)
102
- system += rules_prompt
103
- return ChatPromptTemplate.from_messages(
104
- [
105
- ("system", system),
106
- ("user", input_data.get("content", ""))
107
- ]
108
- )
109
-
110
- def __create_agent_descriptor(self, content) -> RunnableSerializable[Any, Any]:
111
- content = json.loads(content)
112
- agent = (
113
- {
114
- "input": lambda x: x["input"],
115
- }
116
- | RunnableLambda(self.__create_prompt)
117
- | self.__llm
118
- )
119
- return agent
120
-
121
- async def run_agent(self, content) -> Any:
122
- agent_descriptor = self.__create_agent_descriptor(content)
123
- response: AIMessage = await agent_descriptor.ainvoke({"input": content})
124
- return response
1
+ import json, requests, re
2
+ from typing import Any
3
+ from abc import ABC, abstractmethod
4
+ from langchain_openai import ChatOpenAI
5
+ from langchain_core.prompts import ChatPromptTemplate
6
+ from langchain_core.messages import AIMessage
7
+ from langchain_core.runnables import RunnableSerializable
8
+ from langchain_core.runnables import RunnableLambda
9
+ from bs4 import BeautifulSoup
10
+ from ws_bom_robot_app.llm.models.api import LlmRules
11
+ from ws_bom_robot_app.llm.utils.agent_utils import get_rules
12
+
13
+ # SafeDict helper class
14
+ class SafeDict(dict):
15
+ def __missing__(self, key):
16
+ return ''
17
+
18
+ # Strategy Interface
19
+ class AgentDescriptorStrategy(ABC):
20
+ @abstractmethod
21
+ def enrich_prompt(self, prompt: str, input: dict) -> str:
22
+ pass
23
+
24
+ @abstractmethod
25
+ def rule_input(self, input: dict) -> str:
26
+ pass
27
+
28
+ # Concrete Strategy for Default Agent
29
+ class DefaultAgentDescriptor(AgentDescriptorStrategy):
30
+ def enrich_prompt(self, prompt: str, input: dict) -> str:
31
+ # Default enrichment logic (could be minimal or no-op)
32
+ return prompt.format_map(SafeDict(input))
33
+
34
+ def rule_input(self, input: dict) -> str:
35
+ return input.get('content', "")
36
+
37
+ # Concrete Strategy for URL2Text Agent
38
+ class URL2TextAgentDescriptor(AgentDescriptorStrategy):
39
+ def enrich_prompt(self, prompt: str, input: dict) -> str:
40
+ input["context"] = self._get_page_text(input)
41
+ return prompt.format_map(SafeDict(input))
42
+
43
+ def rule_input(self, input: dict) -> str:
44
+ return input.get('context', "")
45
+
46
+ def _get_page_text(self, input: dict) -> str:
47
+ url = input.get("content", "")
48
+ exclusions = input.get("exclude", {})
49
+ response = requests.get(url)
50
+ response.raise_for_status()
51
+ soup = BeautifulSoup(response.content, 'html5lib')
52
+ classes_to_exclude = exclusions.get("classes", [])
53
+ ids_to_exclude = exclusions.get("ids", [])
54
+ for class_name in classes_to_exclude:
55
+ for element in soup.find_all(class_=class_name):
56
+ element.extract()
57
+ for id_name in ids_to_exclude:
58
+ for element in soup.find_all(id=id_name):
59
+ element.extract()
60
+ for script in soup(["script", "noscript", "style", "head", "footer", "iframe"]):
61
+ script.extract()
62
+ return re.sub(' +', ' ', soup.get_text())
63
+
64
+
65
+ class AgentDescriptor:
66
+ # Dictionary to hold all agent strategies
67
+ _list: dict[str,AgentDescriptorStrategy] = {
68
+ "default": DefaultAgentDescriptor(),
69
+ "url2text": URL2TextAgentDescriptor(),
70
+ }
71
+
72
+ # Functions to manage strategies
73
+ @staticmethod
74
+ def add_strategy(name: str, strategy: AgentDescriptorStrategy):
75
+ """_summary_
76
+ add a new strategy to the dictionary
77
+ Args:
78
+ name (str): name of the strategy, in lowercase
79
+ strategy (AgentDescriptorStrategy): class implementing the strategy
80
+ Examples:
81
+ AgentDescriptor.add_strategy("custom_agent_descriptor", CustomAgentDescriptor())
82
+ """
83
+ AgentDescriptor._list[name.lower()] = strategy
84
+
85
+ @staticmethod
86
+ def get_strategy(name: str) -> AgentDescriptorStrategy:
87
+ return AgentDescriptor._list.get(name.lower(), DefaultAgentDescriptor())
88
+
89
+ def __init__(self, api_key: str, prompt: str, mode: str, rules: LlmRules = None):
90
+ self.__prompt = prompt
91
+ self.__llm = ChatOpenAI(model="gpt-4o", temperature=0, api_key=api_key) # type: ignore
92
+ self.api_key = api_key
93
+ self.rules= rules
94
+ self.strategy = self.get_strategy(mode) # Selects the strategy from the dictionary
95
+
96
+ async def __create_prompt(self, input_dict: dict):
97
+ input_data = json.loads(input_dict.get("input", {}))
98
+ system = self.strategy.enrich_prompt(self.__prompt, input_data)
99
+ if self.rules:
100
+ rule_input = self.strategy.rule_input(input_data)
101
+ rules_prompt = await get_rules(self.rules,self.api_key, rule_input)
102
+ system += rules_prompt
103
+ return ChatPromptTemplate.from_messages(
104
+ [
105
+ ("system", system),
106
+ ("user", input_data.get("content", ""))
107
+ ]
108
+ )
109
+
110
+ def __create_agent_descriptor(self, content) -> RunnableSerializable[Any, Any]:
111
+ content = json.loads(content)
112
+ agent = (
113
+ {
114
+ "input": lambda x: x["input"],
115
+ }
116
+ | RunnableLambda(self.__create_prompt)
117
+ | self.__llm
118
+ )
119
+ return agent
120
+
121
+ async def run_agent(self, content) -> Any:
122
+ agent_descriptor = self.__create_agent_descriptor(content)
123
+ response: AIMessage = await agent_descriptor.ainvoke({"input": content})
124
+ return response
@@ -1,167 +1,167 @@
1
- from asyncio import Queue
2
- from langchain_core.agents import AgentFinish
3
- from langchain_core.outputs import ChatGenerationChunk, GenerationChunk
4
- from langchain.callbacks.base import AsyncCallbackHandler
5
- from ws_bom_robot_app.llm.utils.print import printJson, printString
6
- from typing import Any, Dict, List, Optional, Union
7
- from uuid import UUID
8
- import ws_bom_robot_app.llm.settings as settings
9
- from langchain_core.callbacks.base import AsyncCallbackHandler
10
- from langchain_core.outputs import ChatGenerationChunk, GenerationChunk
11
- from langchain_core.messages import BaseMessage, HumanMessage, AIMessage
12
- import json
13
-
14
- # Here is a custom handler that will print the tokens to stdout.
15
- # Instead of printing to stdout you can send the data elsewhere; e.g., to a streaming API response
16
-
17
-
18
- class AgentHandler(AsyncCallbackHandler):
19
-
20
- def __init__(self, queue: Queue, threadId: str = None) -> None:
21
- super().__init__()
22
- self._threadId = threadId
23
- self.json_block = ""
24
- self.is_json_block = False
25
- self.backtick_count = 0 # Conteggio dei backticks per il controllo accurato
26
- self.queue = queue
27
-
28
- async def on_llm_start(
29
- self,
30
- serialized: Dict[str, Any],
31
- prompts: List[str],
32
- *,
33
- run_id: UUID,
34
- parent_run_id: UUID = None,
35
- tags: List[str] = None,
36
- metadata: Dict[str, Any] = None,
37
- **kwargs: Any,
38
- ) -> None:
39
- firstChunk = {
40
- "type": "info",
41
- "threadId": self._threadId,
42
- }
43
- await self.queue.put(printString(firstChunk))
44
-
45
- """async def on_chat_model_start(self, serialized: Dict[str, Any], messages: List[List[BaseMessage]], *, run_id: UUID = None, parent_run_id = None, tags = None, metadata = None, **kwargs: Any) -> Any:
46
- pass"""
47
-
48
- async def on_tool_end(self, output: Any, *, run_id: UUID, parent_run_id: UUID = None, tags: List[str] = None, **kwargs: Any) -> None:
49
- pass
50
-
51
- async def on_llm_new_token(
52
- self,
53
- token: str,
54
- *,
55
- chunk: Optional[Union[GenerationChunk, ChatGenerationChunk]] = None,
56
- run_id: UUID,
57
- parent_run_id: Optional[UUID] = None,
58
- tags: Optional[List[str]] = None,
59
- **kwargs: Any,
60
- ) -> None:
61
- """Gestisce i nuovi token durante lo streaming."""
62
-
63
- if token != "":
64
- self.backtick_count += token.count("`")
65
-
66
- if self.backtick_count >= 3:
67
- if not self.is_json_block:
68
- self.is_json_block = True
69
- self.json_block = ""
70
- else:
71
- self.is_json_block = False
72
- self.json_block += token.replace("```json", '')
73
- await self.process_json_block(self.json_block)
74
- self.json_block = ""
75
- self.backtick_count = 0
76
- elif self.is_json_block:
77
- self.json_block += token
78
- else:
79
- await self.queue.put(printString(token))
80
- pass
81
-
82
- async def on_agent_finish(
83
- self,
84
- finish: AgentFinish,
85
- *,
86
- run_id: UUID,
87
- parent_run_id: UUID = None,
88
- tags: List[str] = None,
89
- **kwargs: Any,
90
- ) -> None:
91
- settings.chat_history.extend(
92
- [
93
- AIMessage(content=finish.return_values["output"]),
94
- ]
95
- )
96
- finalChunk = {"type": "end"}
97
- await self.queue.put(printJson(finalChunk))
98
- await self.queue.put(None)
99
-
100
- async def process_json_block(self, json_block: str):
101
- """Processa il blocco JSON completo."""
102
- # Rimuove il delimitatore iniziale '```json' se presente, e spazi vuoti
103
- json_block_clean = json_block.replace('```', '').replace('json', '').strip()
104
- # Verifica che il blocco non sia vuoto prima di tentare il parsing
105
- if json_block_clean:
106
- try:
107
- # Prova a fare il parsing del JSON
108
- parsed_json = json.loads(json_block_clean)
109
- await self.queue.put(printJson(parsed_json))
110
- except json.JSONDecodeError as e:
111
- # Se il JSON è malformato, logga l'errore
112
- raise e
113
-
114
- class RawAgentHandler(AsyncCallbackHandler):
115
-
116
- def __init__(self,queue: Queue) -> None:
117
- super().__init__()
118
- self.queue = queue
119
-
120
- async def on_llm_start(
121
- self,
122
- serialized: Dict[str, Any],
123
- prompts: List[str],
124
- *,
125
- run_id: UUID,
126
- parent_run_id: UUID = None,
127
- tags: List[str] = None,
128
- metadata: Dict[str, Any] = None,
129
- **kwargs: Any,
130
- ) -> None:
131
- pass
132
-
133
- """async def on_chat_model_start(self, serialized: Dict[str, Any], messages: List[List[BaseMessage]], *, run_id: UUID = None, parent_run_id = None, tags = None, metadata = None, **kwargs: Any) -> Any:
134
- pass"""
135
-
136
- async def on_tool_end(self, output: Any, *, run_id: UUID, parent_run_id: UUID = None, tags: List[str] = None, **kwargs: Any) -> None:
137
- pass
138
-
139
- async def on_llm_new_token(
140
- self,
141
- token: str,
142
- *,
143
- chunk: Optional[Union[GenerationChunk, ChatGenerationChunk]] = None,
144
- run_id: UUID,
145
- parent_run_id: Optional[UUID] = None,
146
- tags: Optional[List[str]] = None,
147
- **kwargs: Any,
148
- ) -> None:
149
- """Handles new tokens during streaming."""
150
- if token: # Only process non-empty tokens
151
- await self.queue.put(token)
152
-
153
- async def on_agent_finish(
154
- self,
155
- finish: AgentFinish,
156
- *,
157
- run_id: UUID,
158
- parent_run_id: UUID = None,
159
- tags: List[str] = None,
160
- **kwargs: Any,
161
- ) -> None:
162
- settings.chat_history.extend(
163
- [
164
- AIMessage(content=finish.return_values["output"]),
165
- ]
166
- )
167
- await self.queue.put(None)
1
+ from asyncio import Queue
2
+ from langchain_core.agents import AgentFinish
3
+ from langchain_core.outputs import ChatGenerationChunk, GenerationChunk
4
+ from langchain.callbacks.base import AsyncCallbackHandler
5
+ from ws_bom_robot_app.llm.utils.print import printJson, printString
6
+ from typing import Any, Dict, List, Optional, Union
7
+ from uuid import UUID
8
+ import ws_bom_robot_app.llm.settings as settings
9
+ from langchain_core.callbacks.base import AsyncCallbackHandler
10
+ from langchain_core.outputs import ChatGenerationChunk, GenerationChunk
11
+ from langchain_core.messages import BaseMessage, HumanMessage, AIMessage
12
+ import json
13
+
14
+ # Here is a custom handler that will print the tokens to stdout.
15
+ # Instead of printing to stdout you can send the data elsewhere; e.g., to a streaming API response
16
+
17
+
18
+ class AgentHandler(AsyncCallbackHandler):
19
+
20
+ def __init__(self, queue: Queue, threadId: str = None) -> None:
21
+ super().__init__()
22
+ self._threadId = threadId
23
+ self.json_block = ""
24
+ self.is_json_block = False
25
+ self.backtick_count = 0 # Conteggio dei backticks per il controllo accurato
26
+ self.queue = queue
27
+
28
+ async def on_llm_start(
29
+ self,
30
+ serialized: Dict[str, Any],
31
+ prompts: List[str],
32
+ *,
33
+ run_id: UUID,
34
+ parent_run_id: UUID = None,
35
+ tags: List[str] = None,
36
+ metadata: Dict[str, Any] = None,
37
+ **kwargs: Any,
38
+ ) -> None:
39
+ firstChunk = {
40
+ "type": "info",
41
+ "threadId": self._threadId,
42
+ }
43
+ await self.queue.put(printString(firstChunk))
44
+
45
+ """async def on_chat_model_start(self, serialized: Dict[str, Any], messages: List[List[BaseMessage]], *, run_id: UUID = None, parent_run_id = None, tags = None, metadata = None, **kwargs: Any) -> Any:
46
+ pass"""
47
+
48
+ async def on_tool_end(self, output: Any, *, run_id: UUID, parent_run_id: UUID = None, tags: List[str] = None, **kwargs: Any) -> None:
49
+ pass
50
+
51
+ async def on_llm_new_token(
52
+ self,
53
+ token: str,
54
+ *,
55
+ chunk: Optional[Union[GenerationChunk, ChatGenerationChunk]] = None,
56
+ run_id: UUID,
57
+ parent_run_id: Optional[UUID] = None,
58
+ tags: Optional[List[str]] = None,
59
+ **kwargs: Any,
60
+ ) -> None:
61
+ """Gestisce i nuovi token durante lo streaming."""
62
+
63
+ if token != "":
64
+ self.backtick_count += token.count("`")
65
+
66
+ if self.backtick_count >= 3:
67
+ if not self.is_json_block:
68
+ self.is_json_block = True
69
+ self.json_block = ""
70
+ else:
71
+ self.is_json_block = False
72
+ self.json_block += token.replace("```json", '')
73
+ await self.process_json_block(self.json_block)
74
+ self.json_block = ""
75
+ self.backtick_count = 0
76
+ elif self.is_json_block:
77
+ self.json_block += token
78
+ else:
79
+ await self.queue.put(printString(token))
80
+ pass
81
+
82
+ async def on_agent_finish(
83
+ self,
84
+ finish: AgentFinish,
85
+ *,
86
+ run_id: UUID,
87
+ parent_run_id: UUID = None,
88
+ tags: List[str] = None,
89
+ **kwargs: Any,
90
+ ) -> None:
91
+ settings.chat_history.extend(
92
+ [
93
+ AIMessage(content=finish.return_values["output"]),
94
+ ]
95
+ )
96
+ finalChunk = {"type": "end"}
97
+ await self.queue.put(printJson(finalChunk))
98
+ await self.queue.put(None)
99
+
100
+ async def process_json_block(self, json_block: str):
101
+ """Processa il blocco JSON completo."""
102
+ # Rimuove il delimitatore iniziale '```json' se presente, e spazi vuoti
103
+ json_block_clean = json_block.replace('```', '').replace('json', '').strip()
104
+ # Verifica che il blocco non sia vuoto prima di tentare il parsing
105
+ if json_block_clean:
106
+ try:
107
+ # Prova a fare il parsing del JSON
108
+ parsed_json = json.loads(json_block_clean)
109
+ await self.queue.put(printJson(parsed_json))
110
+ except json.JSONDecodeError as e:
111
+ # Se il JSON è malformato, logga l'errore
112
+ raise e
113
+
114
+ class RawAgentHandler(AsyncCallbackHandler):
115
+
116
+ def __init__(self,queue: Queue) -> None:
117
+ super().__init__()
118
+ self.queue = queue
119
+
120
+ async def on_llm_start(
121
+ self,
122
+ serialized: Dict[str, Any],
123
+ prompts: List[str],
124
+ *,
125
+ run_id: UUID,
126
+ parent_run_id: UUID = None,
127
+ tags: List[str] = None,
128
+ metadata: Dict[str, Any] = None,
129
+ **kwargs: Any,
130
+ ) -> None:
131
+ pass
132
+
133
+ """async def on_chat_model_start(self, serialized: Dict[str, Any], messages: List[List[BaseMessage]], *, run_id: UUID = None, parent_run_id = None, tags = None, metadata = None, **kwargs: Any) -> Any:
134
+ pass"""
135
+
136
+ async def on_tool_end(self, output: Any, *, run_id: UUID, parent_run_id: UUID = None, tags: List[str] = None, **kwargs: Any) -> None:
137
+ pass
138
+
139
+ async def on_llm_new_token(
140
+ self,
141
+ token: str,
142
+ *,
143
+ chunk: Optional[Union[GenerationChunk, ChatGenerationChunk]] = None,
144
+ run_id: UUID,
145
+ parent_run_id: Optional[UUID] = None,
146
+ tags: Optional[List[str]] = None,
147
+ **kwargs: Any,
148
+ ) -> None:
149
+ """Handles new tokens during streaming."""
150
+ if token: # Only process non-empty tokens
151
+ await self.queue.put(token)
152
+
153
+ async def on_agent_finish(
154
+ self,
155
+ finish: AgentFinish,
156
+ *,
157
+ run_id: UUID,
158
+ parent_run_id: UUID = None,
159
+ tags: List[str] = None,
160
+ **kwargs: Any,
161
+ ) -> None:
162
+ settings.chat_history.extend(
163
+ [
164
+ AIMessage(content=finish.return_values["output"]),
165
+ ]
166
+ )
167
+ await self.queue.put(None)