haystack-experimental 0.15.2__py3-none-any.whl → 0.17.0__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.
- haystack_experimental/chat_message_stores/in_memory.py +3 -3
- haystack_experimental/chat_message_stores/types.py +2 -2
- haystack_experimental/components/agents/agent.py +264 -124
- haystack_experimental/components/agents/human_in_the_loop/dataclasses.py +6 -6
- haystack_experimental/components/agents/human_in_the_loop/errors.py +1 -5
- haystack_experimental/components/agents/human_in_the_loop/strategies.py +10 -10
- haystack_experimental/components/agents/human_in_the_loop/types.py +5 -5
- haystack_experimental/components/agents/human_in_the_loop/user_interfaces.py +2 -2
- haystack_experimental/components/generators/chat/openai.py +11 -11
- haystack_experimental/components/preprocessors/__init__.py +1 -3
- haystack_experimental/components/retrievers/chat_message_retriever.py +4 -4
- haystack_experimental/components/retrievers/types/protocol.py +3 -3
- haystack_experimental/components/summarizers/llm_summarizer.py +7 -7
- haystack_experimental/core/pipeline/breakpoint.py +6 -6
- haystack_experimental/dataclasses/breakpoints.py +2 -2
- haystack_experimental/memory_stores/__init__.py +7 -0
- haystack_experimental/memory_stores/mem0/__init__.py +16 -0
- haystack_experimental/memory_stores/mem0/memory_store.py +323 -0
- haystack_experimental/memory_stores/types/__init__.py +7 -0
- haystack_experimental/memory_stores/types/protocol.py +94 -0
- haystack_experimental/utils/hallucination_risk_calculator/dataclasses.py +9 -9
- haystack_experimental/utils/hallucination_risk_calculator/openai_planner.py +4 -4
- haystack_experimental/utils/hallucination_risk_calculator/skeletonization.py +5 -5
- {haystack_experimental-0.15.2.dist-info → haystack_experimental-0.17.0.dist-info}/METADATA +8 -11
- {haystack_experimental-0.15.2.dist-info → haystack_experimental-0.17.0.dist-info}/RECORD +28 -24
- haystack_experimental/components/preprocessors/embedding_based_document_splitter.py +0 -430
- {haystack_experimental-0.15.2.dist-info → haystack_experimental-0.17.0.dist-info}/WHEEL +0 -0
- {haystack_experimental-0.15.2.dist-info → haystack_experimental-0.17.0.dist-info}/licenses/LICENSE +0 -0
- {haystack_experimental-0.15.2.dist-info → haystack_experimental-0.17.0.dist-info}/licenses/LICENSE-MIT.txt +0 -0
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
|
|
8
8
|
import inspect
|
|
9
9
|
from dataclasses import dataclass
|
|
10
|
-
from typing import Any
|
|
10
|
+
from typing import Any
|
|
11
11
|
|
|
12
12
|
# Monkey patch Haystack's AgentSnapshot with our extended version
|
|
13
13
|
import haystack.dataclasses.breakpoints as hdb
|
|
@@ -28,11 +28,13 @@ from haystack.components.agents.agent import _ExecutionContext as Haystack_Execu
|
|
|
28
28
|
from haystack.components.agents.agent import _schema_from_dict
|
|
29
29
|
from haystack.components.agents.state import replace_values, State
|
|
30
30
|
from haystack.components.generators.chat.types import ChatGenerator
|
|
31
|
-
from haystack.core.errors import PipelineRuntimeError
|
|
31
|
+
from haystack.core.errors import BreakpointException, PipelineRuntimeError
|
|
32
32
|
from haystack.core.pipeline import AsyncPipeline, Pipeline
|
|
33
33
|
from haystack.core.pipeline.breakpoint import (
|
|
34
34
|
_create_pipeline_snapshot_from_chat_generator,
|
|
35
35
|
_create_pipeline_snapshot_from_tool_invoker,
|
|
36
|
+
_save_pipeline_snapshot,
|
|
37
|
+
_should_trigger_tool_invoker_breakpoint,
|
|
36
38
|
)
|
|
37
39
|
from haystack.core.pipeline.utils import _deepcopy_with_exceptions
|
|
38
40
|
from haystack.core.serialization import default_from_dict, import_class_by_name
|
|
@@ -55,6 +57,7 @@ from haystack_experimental.components.agents.human_in_the_loop.strategies import
|
|
|
55
57
|
)
|
|
56
58
|
from haystack_experimental.components.retrievers import ChatMessageRetriever
|
|
57
59
|
from haystack_experimental.components.writers import ChatMessageWriter
|
|
60
|
+
from haystack_experimental.memory_stores.types import MemoryStore
|
|
58
61
|
|
|
59
62
|
logger = logging.getLogger(__name__)
|
|
60
63
|
|
|
@@ -75,8 +78,8 @@ class _ExecutionContext(Haystack_ExecutionContext):
|
|
|
75
78
|
parameter in their `run()` and `run_async()` methods.
|
|
76
79
|
"""
|
|
77
80
|
|
|
78
|
-
tool_execution_decisions:
|
|
79
|
-
confirmation_strategy_context:
|
|
81
|
+
tool_execution_decisions: list[ToolExecutionDecision] | None = None
|
|
82
|
+
confirmation_strategy_context: dict[str, Any] | None = None
|
|
80
83
|
|
|
81
84
|
|
|
82
85
|
class Agent(HaystackAgent):
|
|
@@ -134,16 +137,17 @@ class Agent(HaystackAgent):
|
|
|
134
137
|
self,
|
|
135
138
|
*,
|
|
136
139
|
chat_generator: ChatGenerator,
|
|
137
|
-
tools:
|
|
138
|
-
system_prompt:
|
|
139
|
-
exit_conditions:
|
|
140
|
-
state_schema:
|
|
140
|
+
tools: ToolsType | None = None,
|
|
141
|
+
system_prompt: str | None = None,
|
|
142
|
+
exit_conditions: list[str] | None = None,
|
|
143
|
+
state_schema: dict[str, Any] | None = None,
|
|
141
144
|
max_agent_steps: int = 100,
|
|
142
|
-
streaming_callback:
|
|
145
|
+
streaming_callback: StreamingCallbackT | None = None,
|
|
143
146
|
raise_on_tool_invocation_failure: bool = False,
|
|
144
|
-
confirmation_strategies:
|
|
145
|
-
tool_invoker_kwargs:
|
|
146
|
-
chat_message_store:
|
|
147
|
+
confirmation_strategies: dict[str, ConfirmationStrategy] | None = None,
|
|
148
|
+
tool_invoker_kwargs: dict[str, Any] | None = None,
|
|
149
|
+
chat_message_store: ChatMessageStore | None = None,
|
|
150
|
+
memory_store: MemoryStore | None = None,
|
|
147
151
|
) -> None:
|
|
148
152
|
"""
|
|
149
153
|
Initialize the agent component.
|
|
@@ -162,6 +166,9 @@ class Agent(HaystackAgent):
|
|
|
162
166
|
:param raise_on_tool_invocation_failure: Should the agent raise an exception when a tool invocation fails?
|
|
163
167
|
If set to False, the exception will be turned into a chat message and passed to the LLM.
|
|
164
168
|
:param tool_invoker_kwargs: Additional keyword arguments to pass to the ToolInvoker.
|
|
169
|
+
:param chat_message_store: The ChatMessageStore that the agent can use to store
|
|
170
|
+
and retrieve chat messages history.
|
|
171
|
+
:param memory_store: The memory store that the agent can use to store and retrieve memories.
|
|
165
172
|
:raises TypeError: If the chat_generator does not support tools parameter in its run method.
|
|
166
173
|
:raises ValueError: If the exit_conditions are not valid.
|
|
167
174
|
"""
|
|
@@ -184,18 +191,20 @@ class Agent(HaystackAgent):
|
|
|
184
191
|
self._chat_message_writer = (
|
|
185
192
|
ChatMessageWriter(chat_message_store=chat_message_store) if chat_message_store else None
|
|
186
193
|
)
|
|
194
|
+
self._memory_store = memory_store
|
|
187
195
|
|
|
188
196
|
def _initialize_fresh_execution(
|
|
189
197
|
self,
|
|
190
198
|
messages: list[ChatMessage],
|
|
191
|
-
streaming_callback:
|
|
199
|
+
streaming_callback: StreamingCallbackT | None,
|
|
192
200
|
requires_async: bool,
|
|
193
201
|
*,
|
|
194
|
-
system_prompt:
|
|
195
|
-
generation_kwargs:
|
|
196
|
-
tools:
|
|
197
|
-
confirmation_strategy_context:
|
|
198
|
-
chat_message_store_kwargs:
|
|
202
|
+
system_prompt: str | None = None,
|
|
203
|
+
generation_kwargs: dict[str, Any] | None = None,
|
|
204
|
+
tools: ToolsType | list[str] | None = None,
|
|
205
|
+
confirmation_strategy_context: dict[str, Any] | None = None,
|
|
206
|
+
chat_message_store_kwargs: dict[str, Any] | None = None,
|
|
207
|
+
memory_store_kwargs: dict[str, Any] | None = None,
|
|
199
208
|
**kwargs: dict[str, Any],
|
|
200
209
|
) -> _ExecutionContext:
|
|
201
210
|
"""
|
|
@@ -207,29 +216,62 @@ class Agent(HaystackAgent):
|
|
|
207
216
|
:param system_prompt: System prompt for the agent. If provided, it overrides the default system prompt.
|
|
208
217
|
:param tools: Optional list of Tool objects, a Toolset, or list of tool names to use for this run.
|
|
209
218
|
When passing tool names, tools are selected from the Agent's originally configured tools.
|
|
219
|
+
|
|
220
|
+
:param memory_store_kwargs: Optional dictionary of keyword arguments to pass to the MemoryStore.
|
|
221
|
+
For example, it can include the `user_id`, `run_id`, and `agent_id` parameters
|
|
222
|
+
for storing and retrieving memories.
|
|
210
223
|
:param confirmation_strategy_context: Optional dictionary for passing request-scoped resources
|
|
211
224
|
to confirmation strategies.
|
|
212
225
|
:param chat_message_store_kwargs: Optional dictionary of keyword arguments to pass to the ChatMessageStore.
|
|
226
|
+
For example, it can include the `chat_history_id` and `last_k` parameters for retrieving chat history.
|
|
213
227
|
:param kwargs: Additional data to pass to the State used by the Agent.
|
|
214
228
|
"""
|
|
215
229
|
system_prompt = system_prompt or self.system_prompt
|
|
216
|
-
|
|
217
|
-
|
|
230
|
+
retrieved_memory = None
|
|
231
|
+
updated_system_prompt = system_prompt
|
|
232
|
+
|
|
233
|
+
# Retrieve memories from the memory store
|
|
234
|
+
if self._memory_store:
|
|
235
|
+
retrieved_memories = self._memory_store.search_memories(query=messages[-1].text, **memory_store_kwargs) # type: ignore[arg-type]
|
|
236
|
+
|
|
237
|
+
# we combine the memories into a single string
|
|
238
|
+
combined_memory = "\n".join(
|
|
239
|
+
f"- MEMORY #{idx + 1}: {memory.text}" for idx, memory in enumerate(retrieved_memories)
|
|
240
|
+
)
|
|
241
|
+
retrieved_memory = ChatMessage.from_system(text=combined_memory)
|
|
242
|
+
|
|
243
|
+
if retrieved_memory:
|
|
244
|
+
memory_instruction = (
|
|
245
|
+
"\n\nWhen messages start with `[MEMORY]`, treat them as long-term "
|
|
246
|
+
"context and use them to guide the response if relevant."
|
|
247
|
+
)
|
|
248
|
+
updated_system_prompt = f"{system_prompt}{memory_instruction}"
|
|
249
|
+
|
|
250
|
+
memory_text = f"Here are the relevant memories for the user's query: {retrieved_memory.text}"
|
|
251
|
+
print(memory_text)
|
|
252
|
+
updated_memory = ChatMessage.from_system(text=memory_text)
|
|
253
|
+
else:
|
|
254
|
+
updated_memory = None
|
|
255
|
+
|
|
256
|
+
combined_messages = messages + [updated_memory] if updated_memory else messages
|
|
257
|
+
if updated_system_prompt is not None:
|
|
258
|
+
combined_messages = [ChatMessage.from_system(updated_system_prompt)] + combined_messages
|
|
218
259
|
|
|
219
260
|
# NOTE: difference with parent method to add chat message retrieval
|
|
220
261
|
if self._chat_message_retriever:
|
|
221
262
|
retriever_kwargs = _select_kwargs(self._chat_message_retriever, chat_message_store_kwargs or {})
|
|
222
263
|
if "chat_history_id" in retriever_kwargs:
|
|
223
264
|
messages = self._chat_message_retriever.run(
|
|
224
|
-
current_messages=
|
|
265
|
+
current_messages=combined_messages,
|
|
225
266
|
**retriever_kwargs,
|
|
226
267
|
)["messages"]
|
|
268
|
+
combined_messages = messages
|
|
227
269
|
|
|
228
|
-
if all(m.is_from(ChatRole.SYSTEM) for m in
|
|
270
|
+
if all(m.is_from(ChatRole.SYSTEM) for m in combined_messages):
|
|
229
271
|
logger.warning("All messages provided to the Agent component are system messages. This is not recommended.")
|
|
230
272
|
|
|
231
273
|
state = State(schema=self.state_schema, data=kwargs)
|
|
232
|
-
state.set("messages",
|
|
274
|
+
state.set("messages", combined_messages)
|
|
233
275
|
|
|
234
276
|
streaming_callback = select_streaming_callback( # type: ignore[call-overload]
|
|
235
277
|
init_callback=self.streaming_callback, runtime_callback=streaming_callback, requires_async=requires_async
|
|
@@ -262,12 +304,12 @@ class Agent(HaystackAgent):
|
|
|
262
304
|
def _initialize_from_snapshot( # type: ignore[override]
|
|
263
305
|
self,
|
|
264
306
|
snapshot: AgentSnapshot,
|
|
265
|
-
streaming_callback:
|
|
307
|
+
streaming_callback: StreamingCallbackT | None,
|
|
266
308
|
requires_async: bool,
|
|
267
309
|
*,
|
|
268
|
-
generation_kwargs:
|
|
269
|
-
tools:
|
|
270
|
-
confirmation_strategy_context:
|
|
310
|
+
generation_kwargs: dict[str, Any] | None = None,
|
|
311
|
+
tools: ToolsType | list[str] | None = None,
|
|
312
|
+
confirmation_strategy_context: dict[str, Any] | None = None,
|
|
271
313
|
) -> _ExecutionContext:
|
|
272
314
|
"""
|
|
273
315
|
Initialize execution context from an AgentSnapshot.
|
|
@@ -315,18 +357,19 @@ class Agent(HaystackAgent):
|
|
|
315
357
|
confirmation_strategy_context=confirmation_strategy_context,
|
|
316
358
|
)
|
|
317
359
|
|
|
318
|
-
def run( # type: ignore[override] # noqa: PLR0915
|
|
360
|
+
def run( # type: ignore[override] # noqa: PLR0915 PLR0912
|
|
319
361
|
self,
|
|
320
362
|
messages: list[ChatMessage],
|
|
321
|
-
streaming_callback:
|
|
363
|
+
streaming_callback: StreamingCallbackT | None = None,
|
|
322
364
|
*,
|
|
323
|
-
generation_kwargs:
|
|
324
|
-
break_point:
|
|
325
|
-
snapshot:
|
|
326
|
-
system_prompt:
|
|
327
|
-
tools:
|
|
328
|
-
confirmation_strategy_context:
|
|
329
|
-
chat_message_store_kwargs:
|
|
365
|
+
generation_kwargs: dict[str, Any] | None = None,
|
|
366
|
+
break_point: AgentBreakpoint | None = None,
|
|
367
|
+
snapshot: AgentSnapshot | None = None,
|
|
368
|
+
system_prompt: str | None = None,
|
|
369
|
+
tools: ToolsType | list[str] | None = None,
|
|
370
|
+
confirmation_strategy_context: dict[str, Any] | None = None,
|
|
371
|
+
chat_message_store_kwargs: dict[str, Any] | None = None,
|
|
372
|
+
memory_store_kwargs: dict[str, Any] | None = None,
|
|
330
373
|
**kwargs: Any,
|
|
331
374
|
) -> dict[str, Any]:
|
|
332
375
|
"""
|
|
@@ -350,6 +393,19 @@ class Agent(HaystackAgent):
|
|
|
350
393
|
can use for non-blocking user interaction.
|
|
351
394
|
:param chat_message_store_kwargs: Optional dictionary of keyword arguments to pass to the ChatMessageStore.
|
|
352
395
|
For example, it can include the `chat_history_id` and `last_k` parameters for retrieving chat history.
|
|
396
|
+
:param memory_store_kwargs: Optional dictionary of keyword arguments to pass to the MemoryStore.
|
|
397
|
+
It can include:
|
|
398
|
+
- `user_id`: The user ID to search and add memories from.
|
|
399
|
+
- `run_id`: The run ID to search and add memories from.
|
|
400
|
+
- `agent_id`: The agent ID to search and add memories from.
|
|
401
|
+
- `search_criteria`: A dictionary of containing kwargs for the `search_memories` method.
|
|
402
|
+
This can include:
|
|
403
|
+
- `filters`: A dictionary of filters to search for memories.
|
|
404
|
+
- `query`: The query to search for memories.
|
|
405
|
+
Note: If you pass this, the user query passed to the agent will be
|
|
406
|
+
ignored for memory retrieval.
|
|
407
|
+
- `top_k`: The number of memories to return.
|
|
408
|
+
- `include_memory_metadata`: Whether to include the memory metadata in the ChatMessage.
|
|
353
409
|
:param kwargs: Additional data to pass to the State schema used by the Agent.
|
|
354
410
|
The keys must match the schema defined in the Agent's `state_schema`.
|
|
355
411
|
:returns:
|
|
@@ -360,8 +416,8 @@ class Agent(HaystackAgent):
|
|
|
360
416
|
:raises RuntimeError: If the Agent component wasn't warmed up before calling `run()`.
|
|
361
417
|
:raises BreakpointException: If an agent breakpoint is triggered.
|
|
362
418
|
"""
|
|
363
|
-
|
|
364
|
-
|
|
419
|
+
memory_store_kwargs = memory_store_kwargs or {}
|
|
420
|
+
|
|
365
421
|
agent_inputs = {
|
|
366
422
|
"messages": messages,
|
|
367
423
|
"streaming_callback": streaming_callback,
|
|
@@ -369,13 +425,9 @@ class Agent(HaystackAgent):
|
|
|
369
425
|
"snapshot": snapshot,
|
|
370
426
|
**kwargs,
|
|
371
427
|
}
|
|
372
|
-
#
|
|
373
|
-
#
|
|
374
|
-
|
|
375
|
-
if len(inspect.signature(self._runtime_checks).parameters) == 2:
|
|
376
|
-
self._runtime_checks(break_point, snapshot) # type: ignore[call-arg] # pylint: disable=too-many-function-args
|
|
377
|
-
else:
|
|
378
|
-
self._runtime_checks(break_point) # type: ignore[call-arg] # pylint: disable=no-value-for-parameter
|
|
428
|
+
# TODO Probably good to add a warning in runtime checks that BreakpointConfirmationStrategy will take
|
|
429
|
+
# precedence over passing a ToolBreakpoint
|
|
430
|
+
self._runtime_checks(break_point)
|
|
379
431
|
|
|
380
432
|
if snapshot:
|
|
381
433
|
exe_context = self._initialize_from_snapshot(
|
|
@@ -396,6 +448,7 @@ class Agent(HaystackAgent):
|
|
|
396
448
|
tools=tools,
|
|
397
449
|
confirmation_strategy_context=confirmation_strategy_context,
|
|
398
450
|
chat_message_store_kwargs=chat_message_store_kwargs,
|
|
451
|
+
memory_store_kwargs=memory_store_kwargs,
|
|
399
452
|
**kwargs,
|
|
400
453
|
)
|
|
401
454
|
|
|
@@ -403,10 +456,6 @@ class Agent(HaystackAgent):
|
|
|
403
456
|
span.set_content_tag("haystack.agent.input", _deepcopy_with_exceptions(agent_inputs))
|
|
404
457
|
|
|
405
458
|
while exe_context.counter < self.max_agent_steps:
|
|
406
|
-
# Handle breakpoint and ChatGenerator call
|
|
407
|
-
Agent._check_chat_generator_breakpoint(
|
|
408
|
-
execution_context=exe_context, break_point=break_point, parent_snapshot=parent_snapshot
|
|
409
|
-
)
|
|
410
459
|
# We skip the chat generator when restarting from a snapshot from a ToolBreakpoint
|
|
411
460
|
if exe_context.skip_chat_generator:
|
|
412
461
|
llm_messages = exe_context.state.get("messages", [])[-1:]
|
|
@@ -423,14 +472,26 @@ class Agent(HaystackAgent):
|
|
|
423
472
|
},
|
|
424
473
|
component_visits=exe_context.component_visits,
|
|
425
474
|
parent_span=span,
|
|
475
|
+
break_point=break_point.break_point if isinstance(break_point, AgentBreakpoint) else None,
|
|
426
476
|
)
|
|
427
|
-
except PipelineRuntimeError as e:
|
|
428
|
-
|
|
429
|
-
agent_name=
|
|
430
|
-
|
|
431
|
-
|
|
477
|
+
except (BreakpointException, PipelineRuntimeError) as e:
|
|
478
|
+
if isinstance(e, BreakpointException):
|
|
479
|
+
agent_name = break_point.agent_name if break_point else None
|
|
480
|
+
saved_bp = break_point
|
|
481
|
+
else:
|
|
482
|
+
agent_name = getattr(self, "__component_name__", None)
|
|
483
|
+
saved_bp = None
|
|
484
|
+
|
|
485
|
+
e.pipeline_snapshot = _create_pipeline_snapshot_from_chat_generator(
|
|
486
|
+
agent_name=agent_name, execution_context=exe_context, break_point=saved_bp
|
|
432
487
|
)
|
|
433
|
-
e
|
|
488
|
+
if isinstance(e, BreakpointException):
|
|
489
|
+
e._break_point = e.pipeline_snapshot.break_point
|
|
490
|
+
# If Agent is not in a pipeline, we save the snapshot to a file.
|
|
491
|
+
# Checked by __component_name__ not being set.
|
|
492
|
+
if getattr(self, "__component_name__", None) is None:
|
|
493
|
+
full_file_path = _save_pipeline_snapshot(pipeline_snapshot=e.pipeline_snapshot)
|
|
494
|
+
e.pipeline_snapshot_file_path = full_file_path
|
|
434
495
|
raise e
|
|
435
496
|
|
|
436
497
|
llm_messages = result["replies"]
|
|
@@ -441,6 +502,19 @@ class Agent(HaystackAgent):
|
|
|
441
502
|
exe_context.counter += 1
|
|
442
503
|
break
|
|
443
504
|
|
|
505
|
+
# We only pass down the breakpoint if the tool name matches the tool call in the LLM messages
|
|
506
|
+
resolved_break_point = None
|
|
507
|
+
break_point_to_pass = None
|
|
508
|
+
if (
|
|
509
|
+
break_point
|
|
510
|
+
and isinstance(break_point.break_point, ToolBreakpoint)
|
|
511
|
+
and _should_trigger_tool_invoker_breakpoint(
|
|
512
|
+
break_point=break_point.break_point, llm_messages=llm_messages
|
|
513
|
+
)
|
|
514
|
+
):
|
|
515
|
+
resolved_break_point = break_point
|
|
516
|
+
break_point_to_pass = resolved_break_point.break_point
|
|
517
|
+
|
|
444
518
|
# Apply confirmation strategies and update State and messages sent to ToolInvoker
|
|
445
519
|
try:
|
|
446
520
|
# Run confirmation strategies to get updated tool call messages and modified chat history
|
|
@@ -452,8 +526,8 @@ class Agent(HaystackAgent):
|
|
|
452
526
|
# Replace the chat history in state with the modified one
|
|
453
527
|
exe_context.state.set(key="messages", value=new_chat_history, handler_override=replace_values)
|
|
454
528
|
except HITLBreakpointException as tbp_error:
|
|
455
|
-
# We create a break_point to pass
|
|
456
|
-
|
|
529
|
+
# We create a break_point to pass to Pipeline._run_component
|
|
530
|
+
resolved_break_point = AgentBreakpoint(
|
|
457
531
|
agent_name=getattr(self, "__component_name__", ""),
|
|
458
532
|
break_point=ToolBreakpoint(
|
|
459
533
|
component_name="tool_invoker",
|
|
@@ -462,11 +536,9 @@ class Agent(HaystackAgent):
|
|
|
462
536
|
snapshot_file_path=tbp_error.snapshot_file_path,
|
|
463
537
|
),
|
|
464
538
|
)
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
execution_context=exe_context, break_point=break_point, parent_snapshot=parent_snapshot
|
|
469
|
-
)
|
|
539
|
+
break_point_to_pass = resolved_break_point.break_point
|
|
540
|
+
# If we hit a HITL breakpoint, we skip passing modified messages to ToolInvoker
|
|
541
|
+
modified_tool_call_messages = llm_messages
|
|
470
542
|
|
|
471
543
|
# Run ToolInvoker
|
|
472
544
|
try:
|
|
@@ -481,19 +553,28 @@ class Agent(HaystackAgent):
|
|
|
481
553
|
},
|
|
482
554
|
component_visits=exe_context.component_visits,
|
|
483
555
|
parent_span=span,
|
|
556
|
+
break_point=break_point_to_pass,
|
|
484
557
|
)
|
|
485
|
-
except PipelineRuntimeError as e:
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
558
|
+
except (BreakpointException, PipelineRuntimeError) as e:
|
|
559
|
+
if isinstance(e, BreakpointException):
|
|
560
|
+
agent_name = resolved_break_point.agent_name if resolved_break_point else None
|
|
561
|
+
tool_name = e.break_point.tool_name if isinstance(e.break_point, ToolBreakpoint) else None
|
|
562
|
+
saved_bp = resolved_break_point
|
|
563
|
+
else:
|
|
564
|
+
agent_name = getattr(self, "__component_name__", None)
|
|
565
|
+
tool_name = getattr(e.__cause__, "tool_name", None)
|
|
566
|
+
saved_bp = None
|
|
567
|
+
|
|
568
|
+
e.pipeline_snapshot = _create_pipeline_snapshot_from_tool_invoker(
|
|
569
|
+
tool_name=tool_name, agent_name=agent_name, execution_context=exe_context, break_point=saved_bp
|
|
495
570
|
)
|
|
496
|
-
e
|
|
571
|
+
if isinstance(e, BreakpointException):
|
|
572
|
+
e._break_point = e.pipeline_snapshot.break_point
|
|
573
|
+
# If Agent is not in a pipeline, we save the snapshot to a file.
|
|
574
|
+
# Checked by __component_name__ not being set.
|
|
575
|
+
if getattr(self, "__component_name__", None) is None:
|
|
576
|
+
full_file_path = _save_pipeline_snapshot(pipeline_snapshot=e.pipeline_snapshot)
|
|
577
|
+
e.pipeline_snapshot_file_path = full_file_path
|
|
497
578
|
raise e
|
|
498
579
|
|
|
499
580
|
# Set execution context tool execution decisions to empty after applying them b/c they should only
|
|
@@ -523,6 +604,11 @@ class Agent(HaystackAgent):
|
|
|
523
604
|
if msgs := result.get("messages"):
|
|
524
605
|
result["last_message"] = msgs[-1]
|
|
525
606
|
|
|
607
|
+
# Add the new conversation as memories to the memory store
|
|
608
|
+
if self._memory_store:
|
|
609
|
+
new_memories = [message for message in msgs if message.role.value != "system"]
|
|
610
|
+
self._memory_store.add_memories(messages=new_memories, **memory_store_kwargs)
|
|
611
|
+
|
|
526
612
|
# Write messages to ChatMessageStore if configured
|
|
527
613
|
if self._chat_message_writer:
|
|
528
614
|
writer_kwargs = _select_kwargs(self._chat_message_writer, chat_message_store_kwargs or {})
|
|
@@ -531,18 +617,19 @@ class Agent(HaystackAgent):
|
|
|
531
617
|
|
|
532
618
|
return result
|
|
533
619
|
|
|
534
|
-
async def run_async( # type: ignore[override]
|
|
620
|
+
async def run_async( # type: ignore[override] # noqa: PLR0915
|
|
535
621
|
self,
|
|
536
622
|
messages: list[ChatMessage],
|
|
537
|
-
streaming_callback:
|
|
623
|
+
streaming_callback: StreamingCallbackT | None = None,
|
|
538
624
|
*,
|
|
539
|
-
generation_kwargs:
|
|
540
|
-
break_point:
|
|
541
|
-
snapshot:
|
|
542
|
-
system_prompt:
|
|
543
|
-
tools:
|
|
544
|
-
confirmation_strategy_context:
|
|
545
|
-
chat_message_store_kwargs:
|
|
625
|
+
generation_kwargs: dict[str, Any] | None = None,
|
|
626
|
+
break_point: AgentBreakpoint | None = None,
|
|
627
|
+
snapshot: AgentSnapshot | None = None,
|
|
628
|
+
system_prompt: str | None = None,
|
|
629
|
+
tools: ToolsType | list[str] | None = None,
|
|
630
|
+
confirmation_strategy_context: dict[str, Any] | None = None,
|
|
631
|
+
chat_message_store_kwargs: dict[str, Any] | None = None,
|
|
632
|
+
memory_store_kwargs: dict[str, Any] | None = None,
|
|
546
633
|
**kwargs: Any,
|
|
547
634
|
) -> dict[str, Any]:
|
|
548
635
|
"""
|
|
@@ -569,6 +656,20 @@ class Agent(HaystackAgent):
|
|
|
569
656
|
can use for non-blocking user interaction.
|
|
570
657
|
:param chat_message_store_kwargs: Optional dictionary of keyword arguments to pass to the ChatMessageStore.
|
|
571
658
|
For example, it can include the `chat_history_id` and `last_k` parameters for retrieving chat history.
|
|
659
|
+
:param kwargs: Additional data to pass to the State schema used by the Agent.
|
|
660
|
+
:param memory_store_kwargs: Optional dictionary of keyword arguments to pass to the MemoryStore.
|
|
661
|
+
It can include:
|
|
662
|
+
- `user_id`: The user ID to search and add memories from.
|
|
663
|
+
- `run_id`: The run ID to search and add memories from.
|
|
664
|
+
- `agent_id`: The agent ID to search and add memories from.
|
|
665
|
+
- `search_criteria`: A dictionary of containing kwargs for the `search_memories` method.
|
|
666
|
+
This can include:
|
|
667
|
+
- `filters`: A dictionary of filters to search for memories.
|
|
668
|
+
- `query`: The query to search for memories.
|
|
669
|
+
Note: If you pass this, the user query passed to the agent will be
|
|
670
|
+
ignored for memory retrieval.
|
|
671
|
+
- `top_k`: The number of memories to return.
|
|
672
|
+
- `include_memory_metadata`: Whether to include the memory metadata in the ChatMessage.
|
|
572
673
|
:param kwargs: Additional data to pass to the State schema used by the Agent.
|
|
573
674
|
The keys must match the schema defined in the Agent's `state_schema`.
|
|
574
675
|
:returns:
|
|
@@ -579,8 +680,8 @@ class Agent(HaystackAgent):
|
|
|
579
680
|
:raises RuntimeError: If the Agent component wasn't warmed up before calling `run_async()`.
|
|
580
681
|
:raises BreakpointException: If an agent breakpoint is triggered.
|
|
581
682
|
"""
|
|
582
|
-
|
|
583
|
-
|
|
683
|
+
memory_store_kwargs = memory_store_kwargs or {}
|
|
684
|
+
|
|
584
685
|
agent_inputs = {
|
|
585
686
|
"messages": messages,
|
|
586
687
|
"streaming_callback": streaming_callback,
|
|
@@ -588,13 +689,7 @@ class Agent(HaystackAgent):
|
|
|
588
689
|
"snapshot": snapshot,
|
|
589
690
|
**kwargs,
|
|
590
691
|
}
|
|
591
|
-
|
|
592
|
-
# _runtime_checks. This change will be released in Haystack 2.20.0.
|
|
593
|
-
# To maintain compatibility with Haystack 2.19 we check the number of parameters and call accordingly.
|
|
594
|
-
if len(inspect.signature(self._runtime_checks).parameters) == 2:
|
|
595
|
-
self._runtime_checks(break_point, snapshot) # type: ignore[call-arg] # pylint: disable=too-many-function-args
|
|
596
|
-
else:
|
|
597
|
-
self._runtime_checks(break_point) # type: ignore[call-arg] # pylint: disable=no-value-for-parameter
|
|
692
|
+
self._runtime_checks(break_point)
|
|
598
693
|
|
|
599
694
|
if snapshot:
|
|
600
695
|
exe_context = self._initialize_from_snapshot(
|
|
@@ -615,6 +710,7 @@ class Agent(HaystackAgent):
|
|
|
615
710
|
tools=tools,
|
|
616
711
|
confirmation_strategy_context=confirmation_strategy_context,
|
|
617
712
|
chat_message_store_kwargs=chat_message_store_kwargs,
|
|
713
|
+
memory_store_kwargs=memory_store_kwargs,
|
|
618
714
|
**kwargs,
|
|
619
715
|
)
|
|
620
716
|
|
|
@@ -622,26 +718,39 @@ class Agent(HaystackAgent):
|
|
|
622
718
|
span.set_content_tag("haystack.agent.input", _deepcopy_with_exceptions(agent_inputs))
|
|
623
719
|
|
|
624
720
|
while exe_context.counter < self.max_agent_steps:
|
|
625
|
-
# Handle breakpoint and ChatGenerator call
|
|
626
|
-
self._check_chat_generator_breakpoint(
|
|
627
|
-
execution_context=exe_context, break_point=break_point, parent_snapshot=parent_snapshot
|
|
628
|
-
)
|
|
629
721
|
# We skip the chat generator when restarting from a snapshot from a ToolBreakpoint
|
|
630
722
|
if exe_context.skip_chat_generator:
|
|
631
723
|
llm_messages = exe_context.state.get("messages", [])[-1:]
|
|
632
724
|
# Set to False so the next iteration will call the chat generator
|
|
633
725
|
exe_context.skip_chat_generator = False
|
|
634
726
|
else:
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
727
|
+
try:
|
|
728
|
+
result = await AsyncPipeline._run_component_async(
|
|
729
|
+
component_name="chat_generator",
|
|
730
|
+
component={"instance": self.chat_generator},
|
|
731
|
+
component_inputs={
|
|
732
|
+
"messages": exe_context.state.data["messages"],
|
|
733
|
+
**exe_context.chat_generator_inputs,
|
|
734
|
+
},
|
|
735
|
+
component_visits=exe_context.component_visits,
|
|
736
|
+
parent_span=span,
|
|
737
|
+
break_point=break_point.break_point if isinstance(break_point, AgentBreakpoint) else None,
|
|
738
|
+
)
|
|
739
|
+
except BreakpointException as e:
|
|
740
|
+
e.pipeline_snapshot = _create_pipeline_snapshot_from_chat_generator(
|
|
741
|
+
agent_name=break_point.agent_name if break_point else None,
|
|
742
|
+
execution_context=exe_context,
|
|
743
|
+
break_point=break_point,
|
|
744
|
+
)
|
|
745
|
+
e._break_point = e.pipeline_snapshot.break_point
|
|
746
|
+
# We check if the agent is part of a pipeline by checking for __component_name__
|
|
747
|
+
# If it is not in a pipeline, we save the snapshot to a file.
|
|
748
|
+
in_pipeline = getattr(self, "__component_name__", None) is not None
|
|
749
|
+
if not in_pipeline:
|
|
750
|
+
full_file_path = _save_pipeline_snapshot(pipeline_snapshot=e.pipeline_snapshot)
|
|
751
|
+
e.pipeline_snapshot_file_path = full_file_path
|
|
752
|
+
raise e
|
|
753
|
+
|
|
645
754
|
llm_messages = result["replies"]
|
|
646
755
|
exe_context.state.set("messages", llm_messages)
|
|
647
756
|
|
|
@@ -650,6 +759,19 @@ class Agent(HaystackAgent):
|
|
|
650
759
|
exe_context.counter += 1
|
|
651
760
|
break
|
|
652
761
|
|
|
762
|
+
# We only pass down the breakpoint if the tool name matches the tool call in the LLM messages
|
|
763
|
+
resolved_break_point = None
|
|
764
|
+
break_point_to_pass = None
|
|
765
|
+
if (
|
|
766
|
+
break_point
|
|
767
|
+
and isinstance(break_point.break_point, ToolBreakpoint)
|
|
768
|
+
and _should_trigger_tool_invoker_breakpoint(
|
|
769
|
+
break_point=break_point.break_point, llm_messages=llm_messages
|
|
770
|
+
)
|
|
771
|
+
):
|
|
772
|
+
resolved_break_point = break_point
|
|
773
|
+
break_point_to_pass = resolved_break_point.break_point
|
|
774
|
+
|
|
653
775
|
# Apply confirmation strategies and update State and messages sent to ToolInvoker
|
|
654
776
|
try:
|
|
655
777
|
# Run confirmation strategies to get updated tool call messages and modified chat history (async)
|
|
@@ -662,7 +784,7 @@ class Agent(HaystackAgent):
|
|
|
662
784
|
exe_context.state.set(key="messages", value=new_chat_history, handler_override=replace_values)
|
|
663
785
|
except HITLBreakpointException as tbp_error:
|
|
664
786
|
# We create a break_point to pass into _check_tool_invoker_breakpoint
|
|
665
|
-
|
|
787
|
+
resolved_break_point = AgentBreakpoint(
|
|
666
788
|
agent_name=getattr(self, "__component_name__", ""),
|
|
667
789
|
break_point=ToolBreakpoint(
|
|
668
790
|
component_name="tool_invoker",
|
|
@@ -671,25 +793,38 @@ class Agent(HaystackAgent):
|
|
|
671
793
|
snapshot_file_path=tbp_error.snapshot_file_path,
|
|
672
794
|
),
|
|
673
795
|
)
|
|
796
|
+
break_point_to_pass = resolved_break_point.break_point
|
|
797
|
+
# If we hit a HITL breakpoint, we skip passing modified messages to ToolInvoker
|
|
798
|
+
modified_tool_call_messages = llm_messages
|
|
674
799
|
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
800
|
+
try:
|
|
801
|
+
# We only send the messages from the LLM to the tool invoker
|
|
802
|
+
tool_invoker_result = await AsyncPipeline._run_component_async(
|
|
803
|
+
component_name="tool_invoker",
|
|
804
|
+
component={"instance": self._tool_invoker},
|
|
805
|
+
component_inputs={
|
|
806
|
+
"messages": modified_tool_call_messages,
|
|
807
|
+
"state": exe_context.state,
|
|
808
|
+
**exe_context.tool_invoker_inputs,
|
|
809
|
+
},
|
|
810
|
+
component_visits=exe_context.component_visits,
|
|
811
|
+
parent_span=span,
|
|
812
|
+
break_point=break_point_to_pass,
|
|
813
|
+
)
|
|
814
|
+
except BreakpointException as e:
|
|
815
|
+
e.pipeline_snapshot = _create_pipeline_snapshot_from_tool_invoker(
|
|
816
|
+
tool_name=e.break_point.tool_name if isinstance(e.break_point, ToolBreakpoint) else None,
|
|
817
|
+
agent_name=resolved_break_point.agent_name if resolved_break_point else None,
|
|
818
|
+
execution_context=exe_context,
|
|
819
|
+
break_point=resolved_break_point,
|
|
820
|
+
)
|
|
821
|
+
e._break_point = e.pipeline_snapshot.break_point
|
|
822
|
+
# If Agent is not in a pipeline, we save the snapshot to a file.
|
|
823
|
+
# Checked by __component_name__ not being set.
|
|
824
|
+
if getattr(self, "__component_name__", None) is None:
|
|
825
|
+
full_file_path = _save_pipeline_snapshot(pipeline_snapshot=e.pipeline_snapshot)
|
|
826
|
+
e.pipeline_snapshot_file_path = full_file_path
|
|
827
|
+
raise e
|
|
693
828
|
|
|
694
829
|
# Set execution context tool execution decisions to empty after applying them b/c they should only
|
|
695
830
|
# be used once for the current tool calls
|
|
@@ -718,6 +853,11 @@ class Agent(HaystackAgent):
|
|
|
718
853
|
if msgs := result.get("messages"):
|
|
719
854
|
result["last_message"] = msgs[-1]
|
|
720
855
|
|
|
856
|
+
# Add the new conversation as memories to the memory store
|
|
857
|
+
if self._memory_store:
|
|
858
|
+
new_memories = [message for message in msgs if message.role.value != "system"]
|
|
859
|
+
self._memory_store.add_memories(messages=new_memories, **memory_store_kwargs)
|
|
860
|
+
|
|
721
861
|
# Write messages to ChatMessageStore if configured
|
|
722
862
|
if self._chat_message_writer:
|
|
723
863
|
writer_kwargs = _select_kwargs(self._chat_message_writer, chat_message_store_kwargs or {})
|