ws-bom-robot-app 0.0.37__py3-none-any.whl → 0.0.103__py3-none-any.whl
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.
- ws_bom_robot_app/config.py +35 -7
- ws_bom_robot_app/cron_manager.py +15 -14
- ws_bom_robot_app/llm/agent_context.py +26 -0
- ws_bom_robot_app/llm/agent_description.py +123 -123
- ws_bom_robot_app/llm/agent_handler.py +176 -180
- ws_bom_robot_app/llm/agent_lcel.py +107 -54
- ws_bom_robot_app/llm/api.py +100 -7
- ws_bom_robot_app/llm/defaut_prompt.py +15 -15
- ws_bom_robot_app/llm/evaluator.py +319 -0
- ws_bom_robot_app/llm/feedbacks/__init__.py +0 -0
- ws_bom_robot_app/llm/feedbacks/feedback_manager.py +66 -0
- ws_bom_robot_app/llm/main.py +159 -110
- ws_bom_robot_app/llm/models/api.py +70 -5
- ws_bom_robot_app/llm/models/feedback.py +30 -0
- ws_bom_robot_app/llm/nebuly_handler.py +185 -0
- ws_bom_robot_app/llm/providers/llm_manager.py +244 -80
- ws_bom_robot_app/llm/tools/models/main.py +8 -0
- ws_bom_robot_app/llm/tools/tool_builder.py +68 -23
- ws_bom_robot_app/llm/tools/tool_manager.py +343 -133
- ws_bom_robot_app/llm/tools/utils.py +41 -25
- ws_bom_robot_app/llm/utils/agent.py +34 -0
- ws_bom_robot_app/llm/utils/chunker.py +6 -1
- ws_bom_robot_app/llm/utils/cleanup.py +81 -0
- ws_bom_robot_app/llm/utils/cms.py +123 -0
- ws_bom_robot_app/llm/utils/download.py +183 -79
- ws_bom_robot_app/llm/utils/print.py +29 -29
- ws_bom_robot_app/llm/vector_store/db/__init__.py +0 -0
- ws_bom_robot_app/llm/vector_store/db/base.py +193 -0
- ws_bom_robot_app/llm/vector_store/db/chroma.py +97 -0
- ws_bom_robot_app/llm/vector_store/db/faiss.py +91 -0
- ws_bom_robot_app/llm/vector_store/db/manager.py +15 -0
- ws_bom_robot_app/llm/vector_store/db/qdrant.py +73 -0
- ws_bom_robot_app/llm/vector_store/generator.py +137 -137
- ws_bom_robot_app/llm/vector_store/integration/api.py +216 -0
- ws_bom_robot_app/llm/vector_store/integration/azure.py +1 -1
- ws_bom_robot_app/llm/vector_store/integration/base.py +58 -15
- ws_bom_robot_app/llm/vector_store/integration/confluence.py +41 -11
- ws_bom_robot_app/llm/vector_store/integration/dropbox.py +1 -1
- ws_bom_robot_app/llm/vector_store/integration/gcs.py +1 -1
- ws_bom_robot_app/llm/vector_store/integration/github.py +22 -22
- ws_bom_robot_app/llm/vector_store/integration/googledrive.py +46 -17
- ws_bom_robot_app/llm/vector_store/integration/jira.py +112 -75
- ws_bom_robot_app/llm/vector_store/integration/manager.py +6 -2
- ws_bom_robot_app/llm/vector_store/integration/s3.py +1 -1
- ws_bom_robot_app/llm/vector_store/integration/sftp.py +1 -1
- ws_bom_robot_app/llm/vector_store/integration/sharepoint.py +7 -14
- ws_bom_robot_app/llm/vector_store/integration/shopify.py +143 -0
- ws_bom_robot_app/llm/vector_store/integration/sitemap.py +9 -1
- ws_bom_robot_app/llm/vector_store/integration/slack.py +3 -2
- ws_bom_robot_app/llm/vector_store/integration/thron.py +236 -0
- ws_bom_robot_app/llm/vector_store/loader/base.py +52 -8
- ws_bom_robot_app/llm/vector_store/loader/docling.py +71 -33
- ws_bom_robot_app/llm/vector_store/loader/json_loader.py +25 -25
- ws_bom_robot_app/main.py +148 -146
- ws_bom_robot_app/subprocess_runner.py +106 -0
- ws_bom_robot_app/task_manager.py +207 -54
- ws_bom_robot_app/util.py +65 -20
- ws_bom_robot_app-0.0.103.dist-info/METADATA +364 -0
- ws_bom_robot_app-0.0.103.dist-info/RECORD +76 -0
- {ws_bom_robot_app-0.0.37.dist-info → ws_bom_robot_app-0.0.103.dist-info}/WHEEL +1 -1
- ws_bom_robot_app/llm/settings.py +0 -4
- ws_bom_robot_app/llm/utils/agent_utils.py +0 -17
- ws_bom_robot_app/llm/utils/kb.py +0 -34
- ws_bom_robot_app-0.0.37.dist-info/METADATA +0 -277
- ws_bom_robot_app-0.0.37.dist-info/RECORD +0 -60
- {ws_bom_robot_app-0.0.37.dist-info → ws_bom_robot_app-0.0.103.dist-info}/top_level.txt +0 -0
|
@@ -1,180 +1,176 @@
|
|
|
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
|
|
6
|
-
from typing import Any, Dict, List, Optional, Union
|
|
7
|
-
from uuid import UUID
|
|
8
|
-
|
|
9
|
-
from langchain_core.
|
|
10
|
-
from langchain_core.
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
#
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
""
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
self.
|
|
34
|
-
self.
|
|
35
|
-
self.
|
|
36
|
-
|
|
37
|
-
self.
|
|
38
|
-
self.
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
self,
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
async def
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
self
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
async def
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
AIMessage(content=_parse_token(self.llm,finish.return_values["output"]))
|
|
178
|
-
]
|
|
179
|
-
)
|
|
180
|
-
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 print_json, print_string
|
|
6
|
+
from typing import Any, Dict, List, Optional, Union
|
|
7
|
+
from uuid import UUID
|
|
8
|
+
from langchain_core.callbacks.base import AsyncCallbackHandler
|
|
9
|
+
from langchain_core.outputs import ChatGenerationChunk, GenerationChunk
|
|
10
|
+
from langchain_core.messages import BaseMessage, AIMessage
|
|
11
|
+
import json, logging, re
|
|
12
|
+
|
|
13
|
+
# Here is a custom handler that will print the tokens to stdout.
|
|
14
|
+
# Instead of printing to stdout you can send the data elsewhere; e.g., to a streaming API response
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _parse_token(llm:str,token: str) -> str:
|
|
18
|
+
"""Parses the token based on the LLM provider."""
|
|
19
|
+
if llm == "anthropic" and isinstance(token, list):
|
|
20
|
+
first = token[0]
|
|
21
|
+
if 'text' in first:
|
|
22
|
+
token = first['text']
|
|
23
|
+
else:
|
|
24
|
+
#[{'id': 'toolu_01GGLwJcrQ8PvFMUkQPGu8n7', 'input': {}, 'name': 'document_retriever_xxx', 'type': 'tool_use', 'index': 1}]
|
|
25
|
+
token = ""
|
|
26
|
+
return token
|
|
27
|
+
|
|
28
|
+
class AgentHandler(AsyncCallbackHandler):
|
|
29
|
+
|
|
30
|
+
def __init__(self, queue: Queue, llm:str, threadId: str = None) -> None:
|
|
31
|
+
super().__init__()
|
|
32
|
+
self._threadId = threadId
|
|
33
|
+
self.queue = queue
|
|
34
|
+
self.llm = llm
|
|
35
|
+
self.__started: bool = False
|
|
36
|
+
# on new token event
|
|
37
|
+
self.stream_buffer = "" # accumulates text that hasn't been processed yet
|
|
38
|
+
self.in_json_block = False
|
|
39
|
+
self.json_buffer = ""
|
|
40
|
+
self.json_start_regex = re.compile(r'(`{1,3}\s*json\b)') # detect a potential json start fence.
|
|
41
|
+
self.json_end_regex = re.compile(r'(`{1,3})') # an end fence (one to three backticks).
|
|
42
|
+
self.stream_cut_last_output_chunk_size = 16 # safe cut last chunk size to output if no markers are found
|
|
43
|
+
async def on_chat_model_start(self, serialized, messages, *, run_id, parent_run_id = None, tags = None, metadata = None, **kwargs):
|
|
44
|
+
if not self.__started:
|
|
45
|
+
self.__started = True
|
|
46
|
+
firstChunk = {
|
|
47
|
+
"type": "info",
|
|
48
|
+
"threadId": self._threadId,
|
|
49
|
+
}
|
|
50
|
+
await self.queue.put(print_json(firstChunk))
|
|
51
|
+
|
|
52
|
+
async def on_llm_new_token(
|
|
53
|
+
self,
|
|
54
|
+
token: str,
|
|
55
|
+
*,
|
|
56
|
+
chunk: Optional[Union[GenerationChunk, ChatGenerationChunk]] = None,
|
|
57
|
+
run_id: UUID,
|
|
58
|
+
parent_run_id: Optional[UUID] = None,
|
|
59
|
+
tags: Optional[List[str]] = None,
|
|
60
|
+
**kwargs: Any,
|
|
61
|
+
) -> None:
|
|
62
|
+
if token and "llm_chain" not in (tags or []):
|
|
63
|
+
token = _parse_token(self.llm,token)
|
|
64
|
+
if token:
|
|
65
|
+
self.stream_buffer += token # append new data to pending buffer
|
|
66
|
+
if not self.in_json_block:
|
|
67
|
+
# search for the start of a json block.
|
|
68
|
+
start_match = self.json_start_regex.search(self.stream_buffer)
|
|
69
|
+
if start_match:
|
|
70
|
+
start_index = start_match.start()
|
|
71
|
+
# everything before the start marker is normal content.
|
|
72
|
+
if start_index > 0:
|
|
73
|
+
_before = self.stream_buffer[:start_index].replace('`','').strip() # remove eventual preceding backticks.
|
|
74
|
+
if _before:
|
|
75
|
+
await self.queue.put(print_string(_before))
|
|
76
|
+
# remove the start marker from pending.
|
|
77
|
+
self.stream_buffer = self.stream_buffer[start_match.end():]
|
|
78
|
+
# switch into json mode.
|
|
79
|
+
self.in_json_block = True
|
|
80
|
+
self.json_buffer = ""
|
|
81
|
+
else:
|
|
82
|
+
# no json start marker found. It might be because the marker is split between chunks.
|
|
83
|
+
# to avoid losing potential marker fragments, output what we can safely process:
|
|
84
|
+
# if the pending text is long, we output most of it except the last few characters.
|
|
85
|
+
if len(self.stream_buffer) > self.stream_cut_last_output_chunk_size:
|
|
86
|
+
safe_cut = self.stream_buffer[:-3]
|
|
87
|
+
if safe_cut.startswith('`'):
|
|
88
|
+
safe_cut = safe_cut[1:]
|
|
89
|
+
await self.queue.put(print_string(safe_cut))
|
|
90
|
+
self.stream_buffer = self.stream_buffer[-3:]
|
|
91
|
+
else:
|
|
92
|
+
# in json block: look for an end fence.
|
|
93
|
+
end_match = self.json_end_regex.search(self.stream_buffer)
|
|
94
|
+
if end_match:
|
|
95
|
+
end_index = end_match.start()
|
|
96
|
+
self.json_buffer += self.stream_buffer[:end_index]
|
|
97
|
+
try:
|
|
98
|
+
data = json.loads(self.json_buffer.replace('`',''))
|
|
99
|
+
await self.queue.put(print_json(data))
|
|
100
|
+
except json.JSONDecodeError as e:
|
|
101
|
+
logging.error(f"on_token: invalid json: {e} | {self.json_buffer}")
|
|
102
|
+
finally:
|
|
103
|
+
self.json_buffer = ""
|
|
104
|
+
# remove the end fence from pending.
|
|
105
|
+
self.stream_buffer = self.stream_buffer[end_match.end():].strip()
|
|
106
|
+
self.in_json_block = False
|
|
107
|
+
else:
|
|
108
|
+
# no end marker found
|
|
109
|
+
# accumulate everything and break to wait for more data.
|
|
110
|
+
self.json_buffer += self.stream_buffer
|
|
111
|
+
self.stream_buffer = ""
|
|
112
|
+
|
|
113
|
+
async def on_tool_end(self, output, *, run_id, parent_run_id = None, tags = None, **kwargs):
|
|
114
|
+
if "stream" in (tags or []):
|
|
115
|
+
await self.queue.put(print_json(output))
|
|
116
|
+
|
|
117
|
+
async def on_agent_finish(
|
|
118
|
+
self,
|
|
119
|
+
finish: AgentFinish,
|
|
120
|
+
*,
|
|
121
|
+
run_id: UUID,
|
|
122
|
+
parent_run_id: UUID = None,
|
|
123
|
+
tags: List[str] = None,
|
|
124
|
+
**kwargs: Any,
|
|
125
|
+
) -> None:
|
|
126
|
+
# end-of-stream: flush any remaining text
|
|
127
|
+
if self.in_json_block:
|
|
128
|
+
try:
|
|
129
|
+
data = json.loads(self.json_buffer)
|
|
130
|
+
await self.queue.put(print_json(data))
|
|
131
|
+
except json.JSONDecodeError as e :
|
|
132
|
+
logging.error(f"on_agent_finish: invalid json: {e} | {self.json_buffer}")
|
|
133
|
+
#await self.queue.put(print_string(self.json_buffer))
|
|
134
|
+
elif self.stream_buffer:
|
|
135
|
+
await self.queue.put(print_string(self.stream_buffer))
|
|
136
|
+
|
|
137
|
+
finalChunk = {"type": "end"}
|
|
138
|
+
await self.queue.put(print_json(finalChunk))
|
|
139
|
+
await self.queue.put(None)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
class RawAgentHandler(AsyncCallbackHandler):
|
|
143
|
+
|
|
144
|
+
def __init__(self,queue: Queue, llm: str) -> None:
|
|
145
|
+
super().__init__()
|
|
146
|
+
self.queue = queue
|
|
147
|
+
self.llm = llm
|
|
148
|
+
|
|
149
|
+
async def on_llm_new_token(
|
|
150
|
+
self,
|
|
151
|
+
token: str,
|
|
152
|
+
*,
|
|
153
|
+
chunk: Optional[Union[GenerationChunk, ChatGenerationChunk]] = None,
|
|
154
|
+
run_id: UUID,
|
|
155
|
+
parent_run_id: Optional[UUID] = None,
|
|
156
|
+
tags: Optional[List[str]] = None,
|
|
157
|
+
**kwargs: Any,
|
|
158
|
+
) -> None:
|
|
159
|
+
"""Handles new tokens during streaming."""
|
|
160
|
+
if token: # only process non-empty tokens
|
|
161
|
+
await self.queue.put(_parse_token(self.llm,token))
|
|
162
|
+
|
|
163
|
+
async def on_tool_end(self, output, *, run_id, parent_run_id = None, tags = None, **kwargs):
|
|
164
|
+
if "stream" in (tags or []):
|
|
165
|
+
await self.queue.put(print_json(output))
|
|
166
|
+
|
|
167
|
+
async def on_agent_finish(
|
|
168
|
+
self,
|
|
169
|
+
finish: AgentFinish,
|
|
170
|
+
*,
|
|
171
|
+
run_id: UUID,
|
|
172
|
+
parent_run_id: UUID = None,
|
|
173
|
+
tags: List[str] = None,
|
|
174
|
+
**kwargs: Any,
|
|
175
|
+
) -> None:
|
|
176
|
+
await self.queue.put(None)
|
|
@@ -1,54 +1,107 @@
|
|
|
1
|
-
from typing import Any
|
|
2
|
-
from langchain.agents import AgentExecutor, create_tool_calling_agent
|
|
3
|
-
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
|
|
4
|
-
from langchain_core.runnables import RunnableLambda
|
|
5
|
-
from langchain_core.tools import render_text_description
|
|
6
|
-
from
|
|
7
|
-
|
|
8
|
-
from ws_bom_robot_app.llm.
|
|
9
|
-
from ws_bom_robot_app.llm.
|
|
10
|
-
from ws_bom_robot_app.llm.
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
self.
|
|
20
|
-
self.
|
|
21
|
-
self.
|
|
22
|
-
self.embeddings = llm.get_embeddings()
|
|
23
|
-
self.memory_key = "chat_history"
|
|
24
|
-
self.__llm_with_tools = llm.get_llm().bind_tools(self.__tools) if len(self.__tools) > 0 else llm.get_llm()
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
"
|
|
47
|
-
"
|
|
48
|
-
"
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
1
|
+
from typing import Any, Optional
|
|
2
|
+
from langchain.agents import AgentExecutor, create_tool_calling_agent
|
|
3
|
+
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
|
|
4
|
+
from langchain_core.runnables import RunnableLambda
|
|
5
|
+
from langchain_core.tools import render_text_description
|
|
6
|
+
from pydantic import create_model, BaseModel
|
|
7
|
+
import chevron
|
|
8
|
+
from ws_bom_robot_app.llm.agent_context import AgentContext
|
|
9
|
+
from ws_bom_robot_app.llm.providers.llm_manager import LlmInterface
|
|
10
|
+
from ws_bom_robot_app.llm.models.api import LlmMessage, LlmRules
|
|
11
|
+
from ws_bom_robot_app.llm.utils.agent import get_rules
|
|
12
|
+
from ws_bom_robot_app.llm.defaut_prompt import default_prompt, tool_prompt
|
|
13
|
+
|
|
14
|
+
class AgentLcel:
|
|
15
|
+
|
|
16
|
+
def __init__(self, llm: LlmInterface, sys_message: str, sys_context: AgentContext, tools: list, rules: LlmRules = None, json_schema: Optional[dict] = None):
|
|
17
|
+
self.sys_message = chevron.render(template=sys_message,data=sys_context)
|
|
18
|
+
self.__llm = llm
|
|
19
|
+
self.__tools = tools
|
|
20
|
+
self.rules = rules
|
|
21
|
+
self.json_schema = json_schema
|
|
22
|
+
self.embeddings = llm.get_embeddings()
|
|
23
|
+
self.memory_key: str = "chat_history"
|
|
24
|
+
self.__llm_with_tools = llm.get_llm().bind_tools(self.__tools) if len(self.__tools) > 0 else llm.get_llm()
|
|
25
|
+
if self.json_schema:
|
|
26
|
+
self.__pydantic_schema = self.__create_pydantic_schema()
|
|
27
|
+
else:
|
|
28
|
+
self.__pydantic_schema = None
|
|
29
|
+
|
|
30
|
+
self.executor = self.__create_agent()
|
|
31
|
+
|
|
32
|
+
def __create_pydantic_schema(self) -> type[BaseModel]:
|
|
33
|
+
"""Crea un Pydantic model dinamico dallo schema JSON."""
|
|
34
|
+
if not self.json_schema:
|
|
35
|
+
return None
|
|
36
|
+
|
|
37
|
+
type_map = {
|
|
38
|
+
"string": str,
|
|
39
|
+
"text": str,
|
|
40
|
+
"number": float,
|
|
41
|
+
"float": float,
|
|
42
|
+
"int": int,
|
|
43
|
+
"integer": int,
|
|
44
|
+
"bool": bool,
|
|
45
|
+
"boolean": bool,
|
|
46
|
+
"list": list,
|
|
47
|
+
"array": list,
|
|
48
|
+
"dict": dict,
|
|
49
|
+
"object": dict,
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
fields: dict[str, tuple[Any, Any]] = {}
|
|
53
|
+
for k, v in self.json_schema.items():
|
|
54
|
+
if isinstance(v, str):
|
|
55
|
+
py_type = type_map.get(v.lower(), str)
|
|
56
|
+
fields[k] = (py_type, ...)
|
|
57
|
+
elif isinstance(v, dict):
|
|
58
|
+
fields[k] = (dict, ...)
|
|
59
|
+
elif isinstance(v, list):
|
|
60
|
+
fields[k] = (list, ...)
|
|
61
|
+
else:
|
|
62
|
+
fields[k] = (type(v), ...)
|
|
63
|
+
|
|
64
|
+
return create_model('JsonSchema', **fields)
|
|
65
|
+
|
|
66
|
+
def __get_output_parser(self):
|
|
67
|
+
return self.__llm.get_parser()
|
|
68
|
+
|
|
69
|
+
async def __create_prompt(self, input: dict) -> ChatPromptTemplate:
|
|
70
|
+
from langchain_core.messages import SystemMessage
|
|
71
|
+
message : LlmMessage = input[self.memory_key][-1]
|
|
72
|
+
rules_prompt = await get_rules(self.embeddings, self.rules, message.content) if self.rules else ""
|
|
73
|
+
system = default_prompt + (tool_prompt(render_text_description(self.__tools)) if len(self.__tools)>0 else "") + self.sys_message + rules_prompt
|
|
74
|
+
|
|
75
|
+
# Aggiungi istruzioni per output JSON strutturato se necessario
|
|
76
|
+
if self.json_schema and self.__pydantic_schema:
|
|
77
|
+
json_instructions = f"\n\nIMPORTANT: You must format your final response as a JSON object with the following structure:\n"
|
|
78
|
+
for field_name, field_info in self.__pydantic_schema.model_fields.items():
|
|
79
|
+
field_type = field_info.annotation.__name__ if hasattr(field_info.annotation, '__name__') else str(field_info.annotation)
|
|
80
|
+
json_instructions += f"- {field_name}: {field_type}\n"
|
|
81
|
+
json_instructions += "\nProvide ONLY the JSON object in your response, no additional text."
|
|
82
|
+
system += json_instructions
|
|
83
|
+
|
|
84
|
+
messages = [
|
|
85
|
+
SystemMessage(content=system),
|
|
86
|
+
MessagesPlaceholder(variable_name=self.memory_key),
|
|
87
|
+
MessagesPlaceholder(variable_name="agent_scratchpad"),
|
|
88
|
+
]
|
|
89
|
+
|
|
90
|
+
prompt = ChatPromptTemplate.from_messages(
|
|
91
|
+
messages=messages,
|
|
92
|
+
template_format=None,
|
|
93
|
+
)
|
|
94
|
+
return prompt
|
|
95
|
+
|
|
96
|
+
def __create_agent(self):
|
|
97
|
+
# Un solo AgentExecutor per entrambe le modalità
|
|
98
|
+
agent = (
|
|
99
|
+
{
|
|
100
|
+
"agent_scratchpad": lambda x: self.__llm.get_formatter(x["intermediate_steps"]),
|
|
101
|
+
self.memory_key: lambda x: x[self.memory_key],
|
|
102
|
+
}
|
|
103
|
+
| RunnableLambda(self.__create_prompt)
|
|
104
|
+
| self.__llm_with_tools
|
|
105
|
+
| self.__get_output_parser()
|
|
106
|
+
)
|
|
107
|
+
return AgentExecutor(agent=agent, tools=self.__tools, verbose=False)
|