loopgrid-haystack 0.1.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.
- loopgrid_haystack/__init__.py +15 -0
- loopgrid_haystack/integration.py +778 -0
- loopgrid_haystack-0.1.0.dist-info/METADATA +241 -0
- loopgrid_haystack-0.1.0.dist-info/RECORD +7 -0
- loopgrid_haystack-0.1.0.dist-info/WHEEL +5 -0
- loopgrid_haystack-0.1.0.dist-info/licenses/LICENSE +202 -0
- loopgrid_haystack-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
from .integration import (
|
|
2
|
+
HAYSTACK_TARGET_VERSION,
|
|
3
|
+
LOOPGRID_HAYSTACK_VERSION,
|
|
4
|
+
LoopGridHaystack,
|
|
5
|
+
LoopGridSpan,
|
|
6
|
+
LoopGridTracer,
|
|
7
|
+
)
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
"HAYSTACK_TARGET_VERSION",
|
|
11
|
+
"LOOPGRID_HAYSTACK_VERSION",
|
|
12
|
+
"LoopGridHaystack",
|
|
13
|
+
"LoopGridSpan",
|
|
14
|
+
"LoopGridTracer",
|
|
15
|
+
]
|
|
@@ -0,0 +1,778 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import contextlib
|
|
4
|
+
import contextvars
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import queue
|
|
8
|
+
import threading
|
|
9
|
+
from collections.abc import Iterator, Mapping, Sequence
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from haystack import tracing
|
|
14
|
+
from haystack.tracing import Span, Tracer
|
|
15
|
+
from loopgrid import LoopGrid
|
|
16
|
+
|
|
17
|
+
LOOPGRID_HAYSTACK_VERSION = "0.1.0"
|
|
18
|
+
HAYSTACK_TARGET_VERSION = "3.3.0"
|
|
19
|
+
_FRAMEWORK = "haystack"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _require_nonempty(name: str, value: Any) -> None:
|
|
23
|
+
if value is None or value == "" or value == {} or value == []:
|
|
24
|
+
raise ValueError(f"{name} is required")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _canonical_bytes(value: Any) -> bytes:
|
|
28
|
+
try:
|
|
29
|
+
return json.dumps(
|
|
30
|
+
value,
|
|
31
|
+
sort_keys=True,
|
|
32
|
+
separators=(",", ":"),
|
|
33
|
+
ensure_ascii=False,
|
|
34
|
+
default=str,
|
|
35
|
+
).encode("utf-8")
|
|
36
|
+
except Exception:
|
|
37
|
+
return repr(value).encode("utf-8", errors="replace")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _commitment(value: Any) -> dict[str, Any]:
|
|
41
|
+
raw = _canonical_bytes(value)
|
|
42
|
+
return {
|
|
43
|
+
"algorithm": "sha256",
|
|
44
|
+
"sha256": hashlib.sha256(raw).hexdigest(),
|
|
45
|
+
"bytes": len(raw),
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _idempotency(*parts: Any) -> str:
|
|
50
|
+
raw = "|".join("" if p is None else str(p) for p in parts).encode("utf-8")
|
|
51
|
+
return "lg-haystack-" + hashlib.sha256(raw).hexdigest()
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _call_identity(tool_call: Any) -> str:
|
|
55
|
+
call_id = getattr(tool_call, "id", None)
|
|
56
|
+
name = getattr(tool_call, "tool_name", None) or "tool"
|
|
57
|
+
arguments = getattr(tool_call, "arguments", None)
|
|
58
|
+
arguments_hash = _commitment(arguments)["sha256"]
|
|
59
|
+
if call_id:
|
|
60
|
+
# Tool-call IDs are provider/framework supplied and are not guaranteed to be unique
|
|
61
|
+
# across an entire Agent decision. Include the surviving tool name/arguments so a
|
|
62
|
+
# reused ID with modified parameters cannot collapse correlation within one step.
|
|
63
|
+
return f"id-{call_id}-{name}-{arguments_hash}"
|
|
64
|
+
return f"local-{name}-{arguments_hash}"
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _tool_step_identity(state: Any) -> str:
|
|
68
|
+
"""Return a stable identity for the current Agent tool step.
|
|
69
|
+
|
|
70
|
+
Haystack 3.x exposes ``step_count`` in Agent state. For direct hook/unit usage where a
|
|
71
|
+
synthetic ``State`` may omit that field, the current conversation length is a deterministic
|
|
72
|
+
fallback: retrying the same hook against the same pending message keeps the same identity,
|
|
73
|
+
while a later tool step has additional messages and therefore a different identity.
|
|
74
|
+
"""
|
|
75
|
+
|
|
76
|
+
step_count = state.data.get("step_count")
|
|
77
|
+
if step_count is not None:
|
|
78
|
+
return f"step-{step_count}"
|
|
79
|
+
messages = state.data.get("messages") or []
|
|
80
|
+
return f"messages-{len(messages)}"
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _tool_calls_from_state(state: Any) -> list[Any]:
|
|
84
|
+
messages = state.data.get("messages") or []
|
|
85
|
+
if not messages:
|
|
86
|
+
return []
|
|
87
|
+
calls = getattr(messages[-1], "tool_calls", None)
|
|
88
|
+
return list(calls or [])
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _tool_results_from_state(state: Any) -> list[Any]:
|
|
92
|
+
results: list[Any] = []
|
|
93
|
+
for message in state.data.get("messages") or []:
|
|
94
|
+
result = getattr(message, "tool_call_result", None)
|
|
95
|
+
if result is not None:
|
|
96
|
+
results.append(result)
|
|
97
|
+
return results
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _safe_tags(tags: Mapping[str, Any] | None) -> dict[str, Any]:
|
|
101
|
+
return dict(tags or {})
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _model_name_from_tags(tags: Mapping[str, Any], fallback: str | None) -> str | None:
|
|
105
|
+
preferred = (
|
|
106
|
+
"haystack.chat_generator.model",
|
|
107
|
+
"haystack.component.model",
|
|
108
|
+
"gen_ai.request.model",
|
|
109
|
+
"model",
|
|
110
|
+
)
|
|
111
|
+
for key in preferred:
|
|
112
|
+
value = tags.get(key)
|
|
113
|
+
if isinstance(value, (str, int, float)) and value != "":
|
|
114
|
+
return str(value)
|
|
115
|
+
for key, value in tags.items():
|
|
116
|
+
if "model" in str(key).lower() and isinstance(value, (str, int, float)) and value != "":
|
|
117
|
+
return str(value)
|
|
118
|
+
return fallback
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
@dataclass(frozen=True)
|
|
122
|
+
class _QueuedEvent:
|
|
123
|
+
decision_id: str
|
|
124
|
+
event_type: str
|
|
125
|
+
payload: dict[str, Any]
|
|
126
|
+
actor_type: str
|
|
127
|
+
actor_id: str
|
|
128
|
+
idempotency_key: str
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
@dataclass(frozen=True)
|
|
132
|
+
class _PendingToolCall:
|
|
133
|
+
call: Any
|
|
134
|
+
call_identity: str
|
|
135
|
+
occurrence_identity: str
|
|
136
|
+
step_identity: str
|
|
137
|
+
ordinal: int
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
@dataclass(frozen=True)
|
|
141
|
+
class _PendingToolBatch:
|
|
142
|
+
decision_id: str
|
|
143
|
+
calls: tuple[_PendingToolCall, ...]
|
|
144
|
+
result_offset: int
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
class _EventTransport:
|
|
148
|
+
"""Single FIFO worker so hook/tracer callbacks do not block Haystack execution."""
|
|
149
|
+
|
|
150
|
+
def __init__(self, owner: "LoopGridHaystack") -> None:
|
|
151
|
+
self._owner = owner
|
|
152
|
+
self._queue: queue.Queue[_QueuedEvent | object] = queue.Queue()
|
|
153
|
+
self._stop = object()
|
|
154
|
+
self._worker: threading.Thread | None = None
|
|
155
|
+
self._worker_lock = threading.Lock()
|
|
156
|
+
|
|
157
|
+
def _ensure_worker(self) -> None:
|
|
158
|
+
with self._worker_lock:
|
|
159
|
+
if self._worker is not None and self._worker.is_alive():
|
|
160
|
+
return
|
|
161
|
+
self._worker = threading.Thread(
|
|
162
|
+
target=self._worker_main,
|
|
163
|
+
name="loopgrid-haystack",
|
|
164
|
+
daemon=True,
|
|
165
|
+
)
|
|
166
|
+
self._worker.start()
|
|
167
|
+
|
|
168
|
+
def _worker_main(self) -> None:
|
|
169
|
+
while True:
|
|
170
|
+
item = self._queue.get()
|
|
171
|
+
try:
|
|
172
|
+
if item is self._stop:
|
|
173
|
+
return
|
|
174
|
+
assert isinstance(item, _QueuedEvent)
|
|
175
|
+
try:
|
|
176
|
+
self._owner.client.add_event(
|
|
177
|
+
item.decision_id,
|
|
178
|
+
item.event_type,
|
|
179
|
+
item.payload,
|
|
180
|
+
actor_type=item.actor_type,
|
|
181
|
+
actor_id=item.actor_id,
|
|
182
|
+
idempotency_key=item.idempotency_key,
|
|
183
|
+
)
|
|
184
|
+
except Exception as exc: # observability/evidence must not break the Agent
|
|
185
|
+
self._owner._record_error(item.event_type, item.decision_id, exc)
|
|
186
|
+
finally:
|
|
187
|
+
self._queue.task_done()
|
|
188
|
+
|
|
189
|
+
def enqueue(
|
|
190
|
+
self,
|
|
191
|
+
decision_id: str,
|
|
192
|
+
event_type: str,
|
|
193
|
+
payload: dict[str, Any],
|
|
194
|
+
*,
|
|
195
|
+
actor_type: str,
|
|
196
|
+
actor_id: str,
|
|
197
|
+
identity: Sequence[Any],
|
|
198
|
+
) -> None:
|
|
199
|
+
self._ensure_worker()
|
|
200
|
+
self._queue.put(
|
|
201
|
+
_QueuedEvent(
|
|
202
|
+
decision_id=decision_id,
|
|
203
|
+
event_type=event_type,
|
|
204
|
+
payload=payload,
|
|
205
|
+
actor_type=actor_type,
|
|
206
|
+
actor_id=actor_id,
|
|
207
|
+
idempotency_key=_idempotency(decision_id, event_type, *identity),
|
|
208
|
+
)
|
|
209
|
+
)
|
|
210
|
+
|
|
211
|
+
def flush(self) -> None:
|
|
212
|
+
self._ensure_worker()
|
|
213
|
+
self._queue.join()
|
|
214
|
+
|
|
215
|
+
def shutdown(self) -> None:
|
|
216
|
+
self.flush()
|
|
217
|
+
worker = self._worker
|
|
218
|
+
if worker is not None and worker.is_alive():
|
|
219
|
+
self._queue.put(self._stop)
|
|
220
|
+
self._queue.join()
|
|
221
|
+
worker.join(timeout=5)
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
@dataclass
|
|
225
|
+
class LoopGridSpan(Span):
|
|
226
|
+
"""Haystack Span implementation used by :class:`LoopGridTracer`."""
|
|
227
|
+
|
|
228
|
+
owner: "LoopGridHaystack"
|
|
229
|
+
operation_name: str
|
|
230
|
+
decision_id: str | None
|
|
231
|
+
parent_operation: str | None = None
|
|
232
|
+
tags: dict[str, Any] = field(default_factory=dict)
|
|
233
|
+
delegate_span: Span | None = None
|
|
234
|
+
sequence: int | None = None
|
|
235
|
+
|
|
236
|
+
def set_tag(self, key: str, value: Any) -> None:
|
|
237
|
+
self.tags[key] = value
|
|
238
|
+
if self.delegate_span is not None:
|
|
239
|
+
try:
|
|
240
|
+
self.delegate_span.set_tag(key, value)
|
|
241
|
+
except Exception as exc:
|
|
242
|
+
self.owner._record_error("delegate_set_tag", self.decision_id, exc)
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
class LoopGridTracer(Tracer):
|
|
246
|
+
"""Native Haystack tracer that records LLM-completion evidence.
|
|
247
|
+
|
|
248
|
+
Tool request/execution evidence is intentionally *not* inferred from tracing spans. It is
|
|
249
|
+
recorded by Agent hooks around Haystack's actual tool execution boundary so approval-gated
|
|
250
|
+
or rejected calls are not misreported as executed actions.
|
|
251
|
+
|
|
252
|
+
A delegate tracer may be supplied so LoopGrid can coexist with an existing Haystack tracer.
|
|
253
|
+
"""
|
|
254
|
+
|
|
255
|
+
def __init__(self, owner: "LoopGridHaystack", delegate: Tracer | None = None) -> None:
|
|
256
|
+
self._owner = owner
|
|
257
|
+
self._delegate = delegate
|
|
258
|
+
self._current: contextvars.ContextVar[LoopGridSpan | None] = contextvars.ContextVar(
|
|
259
|
+
"loopgrid_haystack_current_span", default=None
|
|
260
|
+
)
|
|
261
|
+
|
|
262
|
+
@contextlib.contextmanager
|
|
263
|
+
def trace(
|
|
264
|
+
self,
|
|
265
|
+
operation_name: str,
|
|
266
|
+
tags: dict[str, Any] | None = None,
|
|
267
|
+
parent_span: Span | None = None,
|
|
268
|
+
) -> Iterator[Span]:
|
|
269
|
+
delegate_parent = parent_span.delegate_span if isinstance(parent_span, LoopGridSpan) else None
|
|
270
|
+
delegate_span: Span | None = None
|
|
271
|
+
error: BaseException | None = None
|
|
272
|
+
|
|
273
|
+
with contextlib.ExitStack() as stack:
|
|
274
|
+
if self._delegate is not None:
|
|
275
|
+
try:
|
|
276
|
+
delegate_span = stack.enter_context(
|
|
277
|
+
self._delegate.trace(operation_name, tags=tags, parent_span=delegate_parent)
|
|
278
|
+
)
|
|
279
|
+
except Exception as exc:
|
|
280
|
+
self._owner._record_error("delegate_trace_start", self._owner.current_decision_id, exc)
|
|
281
|
+
delegate_span = None
|
|
282
|
+
|
|
283
|
+
parent_operation = parent_span.operation_name if isinstance(parent_span, LoopGridSpan) else None
|
|
284
|
+
decision_id = self._owner.current_decision_id
|
|
285
|
+
span = LoopGridSpan(
|
|
286
|
+
owner=self._owner,
|
|
287
|
+
operation_name=operation_name,
|
|
288
|
+
decision_id=decision_id,
|
|
289
|
+
parent_operation=parent_operation,
|
|
290
|
+
tags=_safe_tags(tags),
|
|
291
|
+
delegate_span=delegate_span,
|
|
292
|
+
sequence=self._owner._next_span_sequence(decision_id) if decision_id else None,
|
|
293
|
+
)
|
|
294
|
+
token = self._current.set(span)
|
|
295
|
+
try:
|
|
296
|
+
yield span
|
|
297
|
+
except BaseException as exc: # preserve application exception behavior
|
|
298
|
+
error = exc
|
|
299
|
+
raise
|
|
300
|
+
finally:
|
|
301
|
+
self._current.reset(token)
|
|
302
|
+
try:
|
|
303
|
+
self._owner._finish_span(span, error)
|
|
304
|
+
except Exception as exc:
|
|
305
|
+
self._owner._record_error("trace_finish", span.decision_id, exc)
|
|
306
|
+
|
|
307
|
+
def current_span(self) -> Span | None:
|
|
308
|
+
return self._current.get()
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
class _BeforeRunHook:
|
|
312
|
+
allowed_hook_points = frozenset({"before_run"})
|
|
313
|
+
|
|
314
|
+
def __init__(self, owner: "LoopGridHaystack", decision_id: str) -> None:
|
|
315
|
+
self._owner = owner
|
|
316
|
+
self._decision_id = decision_id
|
|
317
|
+
|
|
318
|
+
def run(self, state: Any) -> None:
|
|
319
|
+
self._owner._enter_run(state, self._decision_id)
|
|
320
|
+
|
|
321
|
+
async def run_async(self, state: Any) -> None:
|
|
322
|
+
self.run(state)
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
class _BeforeToolHook:
|
|
326
|
+
allowed_hook_points = frozenset({"before_tool"})
|
|
327
|
+
|
|
328
|
+
def __init__(self, owner: "LoopGridHaystack", decision_id: str) -> None:
|
|
329
|
+
self._owner = owner
|
|
330
|
+
self._decision_id = decision_id
|
|
331
|
+
|
|
332
|
+
def run(self, state: Any) -> None:
|
|
333
|
+
# This hook MUST be registered after ConfirmationHook (or any other hook that can
|
|
334
|
+
# remove/modify tool calls). We record only calls that survive those controls.
|
|
335
|
+
calls = _tool_calls_from_state(state)
|
|
336
|
+
step_identity = _tool_step_identity(state)
|
|
337
|
+
pending_calls = [
|
|
338
|
+
_PendingToolCall(
|
|
339
|
+
call=call,
|
|
340
|
+
call_identity=_call_identity(call),
|
|
341
|
+
occurrence_identity=f"{step_identity}:{ordinal}:{_call_identity(call)}",
|
|
342
|
+
step_identity=step_identity,
|
|
343
|
+
ordinal=ordinal,
|
|
344
|
+
)
|
|
345
|
+
for ordinal, call in enumerate(calls)
|
|
346
|
+
]
|
|
347
|
+
self._owner._set_pending(state, self._decision_id, pending_calls)
|
|
348
|
+
for pending in pending_calls:
|
|
349
|
+
call = pending.call
|
|
350
|
+
name = str(getattr(call, "tool_name", None) or "tool")
|
|
351
|
+
arguments = getattr(call, "arguments", None)
|
|
352
|
+
payload: dict[str, Any] = {
|
|
353
|
+
"framework": _FRAMEWORK,
|
|
354
|
+
"haystack_target": HAYSTACK_TARGET_VERSION,
|
|
355
|
+
"tool": name,
|
|
356
|
+
"call_id": getattr(call, "id", None),
|
|
357
|
+
"agent_step": pending.step_identity,
|
|
358
|
+
"tool_ordinal": pending.ordinal,
|
|
359
|
+
"input_commitment": _commitment(arguments),
|
|
360
|
+
"source": "agent.before_tool",
|
|
361
|
+
}
|
|
362
|
+
if self._owner.capture_content:
|
|
363
|
+
payload["input"] = arguments
|
|
364
|
+
self._owner._transport.enqueue(
|
|
365
|
+
self._decision_id,
|
|
366
|
+
"tool_requested",
|
|
367
|
+
payload,
|
|
368
|
+
actor_type="tool",
|
|
369
|
+
actor_id=name,
|
|
370
|
+
identity=("before_tool", pending.occurrence_identity),
|
|
371
|
+
)
|
|
372
|
+
|
|
373
|
+
async def run_async(self, state: Any) -> None:
|
|
374
|
+
self.run(state)
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
class _AfterToolHook:
|
|
378
|
+
allowed_hook_points = frozenset({"after_tool"})
|
|
379
|
+
|
|
380
|
+
def __init__(self, owner: "LoopGridHaystack", decision_id: str) -> None:
|
|
381
|
+
self._owner = owner
|
|
382
|
+
self._decision_id = decision_id
|
|
383
|
+
|
|
384
|
+
def run(self, state: Any) -> None:
|
|
385
|
+
pending_batch = self._owner._take_pending(state, self._decision_id)
|
|
386
|
+
if pending_batch is None or not pending_batch.calls:
|
|
387
|
+
return
|
|
388
|
+
|
|
389
|
+
# Only consider results produced by this tool step. This prevents a legitimate later
|
|
390
|
+
# invocation that reuses the same tool-call ID/arguments from binding to an older result.
|
|
391
|
+
results = _tool_results_from_state(state)[pending_batch.result_offset :]
|
|
392
|
+
by_identity: dict[str, list[Any]] = {}
|
|
393
|
+
for result in results:
|
|
394
|
+
origin = getattr(result, "origin", None)
|
|
395
|
+
if origin is not None:
|
|
396
|
+
by_identity.setdefault(_call_identity(origin), []).append(result)
|
|
397
|
+
|
|
398
|
+
for pending in pending_batch.calls:
|
|
399
|
+
call = pending.call
|
|
400
|
+
matching_results = by_identity.get(pending.call_identity) or []
|
|
401
|
+
result = matching_results.pop(0) if matching_results else None
|
|
402
|
+
if result is None:
|
|
403
|
+
self._owner._record_error(
|
|
404
|
+
"after_tool_missing_result",
|
|
405
|
+
self._decision_id,
|
|
406
|
+
RuntimeError(f"No Haystack tool result found for {pending.call_identity}"),
|
|
407
|
+
)
|
|
408
|
+
continue
|
|
409
|
+
|
|
410
|
+
origin = getattr(result, "origin", None) or call
|
|
411
|
+
name = str(getattr(origin, "tool_name", None) or getattr(call, "tool_name", None) or "tool")
|
|
412
|
+
raw_result = getattr(result, "result", None)
|
|
413
|
+
failed = bool(getattr(result, "error", False))
|
|
414
|
+
payload: dict[str, Any] = {
|
|
415
|
+
"framework": _FRAMEWORK,
|
|
416
|
+
"haystack_target": HAYSTACK_TARGET_VERSION,
|
|
417
|
+
"tool": name,
|
|
418
|
+
"call_id": getattr(origin, "id", None),
|
|
419
|
+
"agent_step": pending.step_identity,
|
|
420
|
+
"tool_ordinal": pending.ordinal,
|
|
421
|
+
"status": "failed" if failed else "completed",
|
|
422
|
+
"error": failed,
|
|
423
|
+
"output_commitment": _commitment(raw_result),
|
|
424
|
+
"source": "agent.after_tool",
|
|
425
|
+
}
|
|
426
|
+
if self._owner.capture_content:
|
|
427
|
+
payload["output"] = raw_result
|
|
428
|
+
self._owner._transport.enqueue(
|
|
429
|
+
self._decision_id,
|
|
430
|
+
"tool_executed",
|
|
431
|
+
payload,
|
|
432
|
+
actor_type="tool",
|
|
433
|
+
actor_id=name,
|
|
434
|
+
identity=("after_tool", pending.occurrence_identity),
|
|
435
|
+
)
|
|
436
|
+
|
|
437
|
+
async def run_async(self, state: Any) -> None:
|
|
438
|
+
self.run(state)
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
class _AfterRunHook:
|
|
442
|
+
allowed_hook_points = frozenset({"after_run"})
|
|
443
|
+
|
|
444
|
+
def __init__(self, owner: "LoopGridHaystack", decision_id: str) -> None:
|
|
445
|
+
self._owner = owner
|
|
446
|
+
self._decision_id = decision_id
|
|
447
|
+
|
|
448
|
+
def run(self, state: Any) -> None:
|
|
449
|
+
self._owner._leave_run(state, self._decision_id)
|
|
450
|
+
|
|
451
|
+
async def run_async(self, state: Any) -> None:
|
|
452
|
+
self.run(state)
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
class LoopGridHaystack:
|
|
456
|
+
"""LoopGrid evidence integration for Haystack 3.3 Agents.
|
|
457
|
+
|
|
458
|
+
Native surfaces:
|
|
459
|
+
* Haystack ``Tracer`` / ``Span`` for model-completion evidence.
|
|
460
|
+
* Agent ``before_tool`` / ``after_tool`` hooks for actual tool execution boundaries.
|
|
461
|
+
* Explicit application calls for policy, human review, and observed downstream outcome.
|
|
462
|
+
"""
|
|
463
|
+
|
|
464
|
+
def __init__(
|
|
465
|
+
self,
|
|
466
|
+
*,
|
|
467
|
+
client: LoopGrid | None = None,
|
|
468
|
+
base_url: str = "http://127.0.0.1:8000",
|
|
469
|
+
api_key: str | None = None,
|
|
470
|
+
workspace_id: str = "default",
|
|
471
|
+
agent_id: str = "haystack-agent",
|
|
472
|
+
capture_content: bool = False,
|
|
473
|
+
default_model_name: str | None = None,
|
|
474
|
+
default_model_provider: str | None = None,
|
|
475
|
+
) -> None:
|
|
476
|
+
_require_nonempty("agent_id", agent_id)
|
|
477
|
+
self.client = client or LoopGrid(base_url=base_url, api_key=api_key, workspace_id=workspace_id)
|
|
478
|
+
self.workspace_id = workspace_id
|
|
479
|
+
self.agent_id = agent_id
|
|
480
|
+
self.capture_content = bool(capture_content)
|
|
481
|
+
self.default_model_name = default_model_name
|
|
482
|
+
self.default_model_provider = default_model_provider
|
|
483
|
+
|
|
484
|
+
self._transport = _EventTransport(self)
|
|
485
|
+
self._errors: list[dict[str, Any]] = []
|
|
486
|
+
self._errors_lock = threading.Lock()
|
|
487
|
+
self._state_lock = threading.RLock()
|
|
488
|
+
self._pending_by_state: dict[int, _PendingToolBatch] = {}
|
|
489
|
+
self._previous_context_by_state: dict[int, tuple[str, ...]] = {}
|
|
490
|
+
self._decision_models: dict[str, dict[str, Any]] = {}
|
|
491
|
+
self._span_seq: dict[str, int] = {}
|
|
492
|
+
self._span_seq_lock = threading.Lock()
|
|
493
|
+
self._decision_stack: contextvars.ContextVar[tuple[str, ...]] = contextvars.ContextVar(
|
|
494
|
+
"loopgrid_haystack_decision_stack", default=()
|
|
495
|
+
)
|
|
496
|
+
self._installed_tracer: LoopGridTracer | None = None
|
|
497
|
+
|
|
498
|
+
@property
|
|
499
|
+
def current_decision_id(self) -> str | None:
|
|
500
|
+
stack = self._decision_stack.get()
|
|
501
|
+
return stack[-1] if stack else None
|
|
502
|
+
|
|
503
|
+
def _next_span_sequence(self, decision_id: str | None) -> int | None:
|
|
504
|
+
if not decision_id:
|
|
505
|
+
return None
|
|
506
|
+
with self._span_seq_lock:
|
|
507
|
+
next_value = self._span_seq.get(decision_id, 0) + 1
|
|
508
|
+
self._span_seq[decision_id] = next_value
|
|
509
|
+
return next_value
|
|
510
|
+
|
|
511
|
+
def make_tracer(self, *, delegate: Tracer | None = None) -> LoopGridTracer:
|
|
512
|
+
return LoopGridTracer(self, delegate=delegate)
|
|
513
|
+
|
|
514
|
+
def enable_tracing(self, *, delegate: Tracer | None = None) -> LoopGridTracer:
|
|
515
|
+
"""Explicitly enable LoopGrid as Haystack's process-level tracer.
|
|
516
|
+
|
|
517
|
+
Haystack exposes a process-level tracing facade. The public ``haystack.tracing.tracer``
|
|
518
|
+
object must not be captured and then used as a delegate: that facade routes to whichever
|
|
519
|
+
tracer is currently enabled, so delegating to it after installing LoopGrid can recurse
|
|
520
|
+
back into LoopGrid.
|
|
521
|
+
|
|
522
|
+
To compose LoopGrid with another tracing backend, keep the concrete backend tracer
|
|
523
|
+
instance and pass it explicitly as ``delegate``. Constructing ``LoopGridHaystack`` alone
|
|
524
|
+
never changes global Haystack tracing.
|
|
525
|
+
"""
|
|
526
|
+
|
|
527
|
+
if delegate is not None and (delegate is self._installed_tracer or isinstance(delegate, LoopGridTracer)):
|
|
528
|
+
raise ValueError("delegate must be a concrete non-LoopGrid Haystack tracer")
|
|
529
|
+
tracer = self.make_tracer(delegate=delegate)
|
|
530
|
+
tracing.enable_tracing(tracer)
|
|
531
|
+
self._installed_tracer = tracer
|
|
532
|
+
return tracer
|
|
533
|
+
|
|
534
|
+
def agent_hooks(
|
|
535
|
+
self,
|
|
536
|
+
decision_id: str,
|
|
537
|
+
*,
|
|
538
|
+
before_tool_prefix: Sequence[Any] = (),
|
|
539
|
+
after_tool_suffix: Sequence[Any] = (),
|
|
540
|
+
) -> dict[str, list[Any]]:
|
|
541
|
+
"""Return decision-scoped native Haystack Agent hooks.
|
|
542
|
+
|
|
543
|
+
Put ``ConfirmationHook`` (and any other hook that may remove/modify tool calls) in
|
|
544
|
+
``before_tool_prefix``. LoopGrid's request hook is appended after those controls and
|
|
545
|
+
therefore records only the calls that will actually proceed to Haystack execution.
|
|
546
|
+
"""
|
|
547
|
+
|
|
548
|
+
_require_nonempty("decision_id", decision_id)
|
|
549
|
+
return {
|
|
550
|
+
"before_run": [_BeforeRunHook(self, decision_id)],
|
|
551
|
+
"before_tool": [*list(before_tool_prefix), _BeforeToolHook(self, decision_id)],
|
|
552
|
+
"after_tool": [_AfterToolHook(self, decision_id), *list(after_tool_suffix)],
|
|
553
|
+
"after_run": [_AfterRunHook(self, decision_id)],
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
@contextlib.contextmanager
|
|
557
|
+
def decision_context(self, decision_id: str) -> Iterator[None]:
|
|
558
|
+
"""Exception-safe explicit correlation scope for advanced/custom run loops.
|
|
559
|
+
|
|
560
|
+
Normal ``Agent`` usage gets correlation from ``before_run``/``after_run`` hooks. This
|
|
561
|
+
context manager is useful when application code needs a guaranteed cleanup boundary even
|
|
562
|
+
if a generator/tool raises before ``after_run`` can execute.
|
|
563
|
+
"""
|
|
564
|
+
|
|
565
|
+
_require_nonempty("decision_id", decision_id)
|
|
566
|
+
previous = self._decision_stack.get()
|
|
567
|
+
token = self._decision_stack.set((*previous, decision_id))
|
|
568
|
+
try:
|
|
569
|
+
yield
|
|
570
|
+
finally:
|
|
571
|
+
self._decision_stack.reset(token)
|
|
572
|
+
|
|
573
|
+
def start_decision(
|
|
574
|
+
self,
|
|
575
|
+
*,
|
|
576
|
+
decision_type: str,
|
|
577
|
+
agent: Mapping[str, Any],
|
|
578
|
+
authority: Mapping[str, Any],
|
|
579
|
+
model: Mapping[str, Any],
|
|
580
|
+
context: Mapping[str, Any],
|
|
581
|
+
proposed_action: Mapping[str, Any],
|
|
582
|
+
policy: Mapping[str, Any] | None = None,
|
|
583
|
+
metadata: Mapping[str, Any] | None = None,
|
|
584
|
+
privacy_mode: str = "redacted",
|
|
585
|
+
idempotency_key: str | None = None,
|
|
586
|
+
) -> dict[str, Any]:
|
|
587
|
+
_require_nonempty("decision_type", decision_type)
|
|
588
|
+
_require_nonempty("agent.id", dict(agent).get("id"))
|
|
589
|
+
_require_nonempty("authority", authority)
|
|
590
|
+
_require_nonempty("model.name", dict(model).get("name"))
|
|
591
|
+
_require_nonempty("context", context)
|
|
592
|
+
_require_nonempty("proposed_action", proposed_action)
|
|
593
|
+
|
|
594
|
+
md = dict(metadata or {})
|
|
595
|
+
md.update(
|
|
596
|
+
{
|
|
597
|
+
"framework": _FRAMEWORK,
|
|
598
|
+
"integration": "loopgrid-haystack",
|
|
599
|
+
"integration_version": LOOPGRID_HAYSTACK_VERSION,
|
|
600
|
+
"haystack_target": HAYSTACK_TARGET_VERSION,
|
|
601
|
+
}
|
|
602
|
+
)
|
|
603
|
+
result = self.client.record_decision(
|
|
604
|
+
decision_type=decision_type,
|
|
605
|
+
agent=dict(agent),
|
|
606
|
+
authority=dict(authority),
|
|
607
|
+
model=dict(model),
|
|
608
|
+
context=dict(context),
|
|
609
|
+
proposed_action=dict(proposed_action),
|
|
610
|
+
metadata=md,
|
|
611
|
+
privacy_mode=privacy_mode,
|
|
612
|
+
idempotency_key=idempotency_key,
|
|
613
|
+
)
|
|
614
|
+
decision_id = result["decision_id"]
|
|
615
|
+
with self._state_lock:
|
|
616
|
+
self._decision_models[decision_id] = dict(model)
|
|
617
|
+
if policy is not None:
|
|
618
|
+
self.record_policy(decision_id, policy)
|
|
619
|
+
return result
|
|
620
|
+
|
|
621
|
+
def record_policy(self, decision_id: str, policy: Mapping[str, Any]) -> Any:
|
|
622
|
+
p = dict(policy)
|
|
623
|
+
decision = p.get("decision")
|
|
624
|
+
if decision not in {"auto_allowed", "human_approval_required", "blocked", "block"}:
|
|
625
|
+
raise ValueError(
|
|
626
|
+
"policy.decision must be auto_allowed, human_approval_required, blocked, or block"
|
|
627
|
+
)
|
|
628
|
+
if not (p.get("policy_id") or p.get("version")):
|
|
629
|
+
raise ValueError("policy provenance requires policy_id or version")
|
|
630
|
+
return self.client.policy_evaluated(
|
|
631
|
+
decision_id,
|
|
632
|
+
p,
|
|
633
|
+
actor_id=str(p.get("policy_id") or "application-policy"),
|
|
634
|
+
)
|
|
635
|
+
|
|
636
|
+
def record_human_review(
|
|
637
|
+
self,
|
|
638
|
+
decision_id: str,
|
|
639
|
+
*,
|
|
640
|
+
reviewer: str,
|
|
641
|
+
approved: bool,
|
|
642
|
+
reason: str = "",
|
|
643
|
+
) -> Any:
|
|
644
|
+
_require_nonempty("reviewer", reviewer)
|
|
645
|
+
# Explicit application facts are written synchronously by the LoopGrid SDK. Drain
|
|
646
|
+
# framework-generated evidence first so a slow transport cannot invert the real lifecycle
|
|
647
|
+
# (for example model_completed arriving after human_approved).
|
|
648
|
+
self.flush()
|
|
649
|
+
if approved:
|
|
650
|
+
return self.client.human_approved(decision_id, reviewer, reason)
|
|
651
|
+
return self.client.human_rejected(decision_id, reviewer, reason)
|
|
652
|
+
|
|
653
|
+
def record_outcome(
|
|
654
|
+
self,
|
|
655
|
+
decision_id: str,
|
|
656
|
+
outcome: Mapping[str, Any],
|
|
657
|
+
*,
|
|
658
|
+
observer: str = "application",
|
|
659
|
+
) -> Any:
|
|
660
|
+
_require_nonempty("outcome", outcome)
|
|
661
|
+
# Preserve ordering with queued model/tool evidence before recording the authoritative
|
|
662
|
+
# downstream observation.
|
|
663
|
+
self.flush()
|
|
664
|
+
return self.client.outcome_observed(decision_id, dict(outcome), actor_id=observer)
|
|
665
|
+
|
|
666
|
+
def flush(self) -> None:
|
|
667
|
+
self._transport.flush()
|
|
668
|
+
|
|
669
|
+
def shutdown(self) -> None:
|
|
670
|
+
self._transport.shutdown()
|
|
671
|
+
|
|
672
|
+
def _enter_run(self, state: Any, decision_id: str) -> None:
|
|
673
|
+
state_id = id(state)
|
|
674
|
+
previous = self._decision_stack.get()
|
|
675
|
+
with self._state_lock:
|
|
676
|
+
self._previous_context_by_state[state_id] = previous
|
|
677
|
+
self._decision_stack.set((*previous, decision_id))
|
|
678
|
+
|
|
679
|
+
def _leave_run(self, state: Any, decision_id: str) -> None:
|
|
680
|
+
state_id = id(state)
|
|
681
|
+
with self._state_lock:
|
|
682
|
+
previous = self._previous_context_by_state.pop(state_id, None)
|
|
683
|
+
self._pending_by_state.pop(state_id, None)
|
|
684
|
+
if previous is not None:
|
|
685
|
+
self._decision_stack.set(previous)
|
|
686
|
+
else:
|
|
687
|
+
# Fail closed on correlation rather than retaining a stale decision.
|
|
688
|
+
self._decision_stack.set(())
|
|
689
|
+
|
|
690
|
+
def _set_pending(
|
|
691
|
+
self,
|
|
692
|
+
state: Any,
|
|
693
|
+
decision_id: str,
|
|
694
|
+
calls: list[_PendingToolCall],
|
|
695
|
+
) -> None:
|
|
696
|
+
with self._state_lock:
|
|
697
|
+
self._pending_by_state[id(state)] = _PendingToolBatch(
|
|
698
|
+
decision_id=decision_id,
|
|
699
|
+
calls=tuple(calls),
|
|
700
|
+
result_offset=len(_tool_results_from_state(state)),
|
|
701
|
+
)
|
|
702
|
+
|
|
703
|
+
def _take_pending(self, state: Any, decision_id: str) -> _PendingToolBatch | None:
|
|
704
|
+
with self._state_lock:
|
|
705
|
+
stored = self._pending_by_state.pop(id(state), None)
|
|
706
|
+
if stored is None:
|
|
707
|
+
return None
|
|
708
|
+
if stored.decision_id != decision_id:
|
|
709
|
+
self._record_error(
|
|
710
|
+
"pending_decision_mismatch",
|
|
711
|
+
decision_id,
|
|
712
|
+
RuntimeError(f"pending tool calls belong to {stored.decision_id}"),
|
|
713
|
+
)
|
|
714
|
+
return None
|
|
715
|
+
return stored
|
|
716
|
+
|
|
717
|
+
def _finish_span(self, span: LoopGridSpan, error: BaseException | None) -> None:
|
|
718
|
+
# Haystack 3.x emits one LLM child span per Agent step. We intentionally ignore
|
|
719
|
+
# tool spans because hook ordering is the authoritative execution boundary.
|
|
720
|
+
if span.decision_id is None:
|
|
721
|
+
return
|
|
722
|
+
if span.operation_name != "haystack.agent.step.llm":
|
|
723
|
+
return
|
|
724
|
+
|
|
725
|
+
with self._state_lock:
|
|
726
|
+
model = dict(self._decision_models.get(span.decision_id, {}))
|
|
727
|
+
model_name = _model_name_from_tags(span.tags, model.get("name") or self.default_model_name)
|
|
728
|
+
provider = model.get("provider") or self.default_model_provider
|
|
729
|
+
payload: dict[str, Any] = {
|
|
730
|
+
"framework": _FRAMEWORK,
|
|
731
|
+
"haystack_target": HAYSTACK_TARGET_VERSION,
|
|
732
|
+
"operation": span.operation_name,
|
|
733
|
+
"parent_operation": span.parent_operation,
|
|
734
|
+
"provider": provider,
|
|
735
|
+
"model": model_name,
|
|
736
|
+
"status": "failed" if error is not None else "completed",
|
|
737
|
+
"trace_tags_commitment": _commitment(span.tags),
|
|
738
|
+
"source": "haystack.tracer",
|
|
739
|
+
}
|
|
740
|
+
if error is not None:
|
|
741
|
+
payload["error_type"] = type(error).__name__
|
|
742
|
+
if self.capture_content:
|
|
743
|
+
payload["trace_tags"] = span.tags
|
|
744
|
+
|
|
745
|
+
self._transport.enqueue(
|
|
746
|
+
span.decision_id,
|
|
747
|
+
"model_completed",
|
|
748
|
+
payload,
|
|
749
|
+
actor_type="agent",
|
|
750
|
+
actor_id=self.agent_id,
|
|
751
|
+
identity=("llm_span", span.sequence, _commitment(span.tags)["sha256"]),
|
|
752
|
+
)
|
|
753
|
+
|
|
754
|
+
def _record_error(self, stage: str, decision_id: str | None, exc: BaseException) -> None:
|
|
755
|
+
with self._errors_lock:
|
|
756
|
+
self._errors.append(
|
|
757
|
+
{
|
|
758
|
+
"stage": stage,
|
|
759
|
+
"decision_id": decision_id,
|
|
760
|
+
"error_type": type(exc).__name__,
|
|
761
|
+
# Do not retain arbitrary exception text; it can contain user data/secrets.
|
|
762
|
+
"message": "LoopGrid Haystack integration error",
|
|
763
|
+
}
|
|
764
|
+
)
|
|
765
|
+
|
|
766
|
+
@property
|
|
767
|
+
def errors(self) -> tuple[dict[str, Any], ...]:
|
|
768
|
+
with self._errors_lock:
|
|
769
|
+
return tuple(dict(x) for x in self._errors)
|
|
770
|
+
|
|
771
|
+
def assert_healthy(self) -> None:
|
|
772
|
+
errors = self.errors
|
|
773
|
+
if errors:
|
|
774
|
+
first = errors[0]
|
|
775
|
+
raise RuntimeError(
|
|
776
|
+
f"LoopGrid Haystack transport/integration failed ({len(errors)} error(s)); "
|
|
777
|
+
f"first={first['stage']}:{first['error_type']}"
|
|
778
|
+
)
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: loopgrid-haystack
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Signed, tamper-evident decision evidence for Haystack Agents using LoopGrid
|
|
5
|
+
Author: LoopGrid
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://loopgrid.io/integrations/haystack/
|
|
8
|
+
Project-URL: Repository, https://github.com/loopgridio/loopgrid-haystack
|
|
9
|
+
Project-URL: Issues, https://github.com/loopgridio/loopgrid-haystack/issues
|
|
10
|
+
Keywords: haystack,haystack-ai,ai-agents,agent-governance,decision-evidence,audit-trail,provenance,tamper-evident,loopgrid
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
18
|
+
Requires-Python: >=3.10
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
License-File: LICENSE
|
|
21
|
+
Requires-Dist: loopgrid<0.9,>=0.8.0
|
|
22
|
+
Requires-Dist: haystack-ai<3.4,>=3.3.0
|
|
23
|
+
Provides-Extra: dev
|
|
24
|
+
Requires-Dist: pytest>=8; extra == "dev"
|
|
25
|
+
Requires-Dist: pytest-asyncio>=0.24; extra == "dev"
|
|
26
|
+
Requires-Dist: build>=1.2; extra == "dev"
|
|
27
|
+
Requires-Dist: twine>=6; extra == "dev"
|
|
28
|
+
Dynamic: license-file
|
|
29
|
+
|
|
30
|
+
# LoopGrid for Haystack
|
|
31
|
+
|
|
32
|
+
Native Haystack 3.3 Agent hooks + tracing integration for LoopGrid, the evidence plane for AI agents.
|
|
33
|
+
|
|
34
|
+
`loopgrid-haystack` maps Haystack's real Agent lifecycle into LoopGrid decision evidence without changing the LoopGrid Core contract.
|
|
35
|
+
|
|
36
|
+
## Evidence contract
|
|
37
|
+
|
|
38
|
+
```text
|
|
39
|
+
application starts consequential decision
|
|
40
|
+
↓
|
|
41
|
+
Haystack Agent LLM span completes
|
|
42
|
+
↓
|
|
43
|
+
LoopGrid model_completed
|
|
44
|
+
↓
|
|
45
|
+
explicit application policy / human review
|
|
46
|
+
↓
|
|
47
|
+
Haystack ConfirmationHook / other controls
|
|
48
|
+
↓
|
|
49
|
+
LoopGrid before_tool observes the surviving tool call
|
|
50
|
+
↓
|
|
51
|
+
LoopGrid tool_requested
|
|
52
|
+
↓
|
|
53
|
+
actual Haystack tool execution
|
|
54
|
+
↓
|
|
55
|
+
Haystack after_tool
|
|
56
|
+
↓
|
|
57
|
+
LoopGrid tool_executed
|
|
58
|
+
↓
|
|
59
|
+
application explicitly observes downstream outcome
|
|
60
|
+
↓
|
|
61
|
+
LoopGrid outcome_observed
|
|
62
|
+
↓
|
|
63
|
+
evidence_complete → cryptographic verification
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
LoopGrid **does not** execute tools, invent delegated authority, invent policy, infer a reviewer, treat confirmation as authorization by itself, or infer a real-world outcome from a tool return.
|
|
67
|
+
|
|
68
|
+
## Compatibility
|
|
69
|
+
|
|
70
|
+
- Python 3.10–3.14
|
|
71
|
+
- `haystack-ai` 3.3.x
|
|
72
|
+
- `loopgrid` 0.8.x
|
|
73
|
+
- LoopGrid Core validation target: `0.8.1-design-partner`
|
|
74
|
+
|
|
75
|
+
## Install
|
|
76
|
+
|
|
77
|
+
```bash
|
|
78
|
+
pip install loopgrid-haystack
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
## Quickstart
|
|
82
|
+
|
|
83
|
+
```python
|
|
84
|
+
from haystack.components.agents import Agent
|
|
85
|
+
from haystack.dataclasses import ChatMessage
|
|
86
|
+
from loopgrid_haystack import LoopGridHaystack
|
|
87
|
+
|
|
88
|
+
loopgrid = LoopGridHaystack(
|
|
89
|
+
base_url="http://127.0.0.1:8000",
|
|
90
|
+
workspace_id="default",
|
|
91
|
+
agent_id="support-agent",
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
# Explicit: Haystack never enables tracing automatically. If the application already owns
|
|
95
|
+
# a concrete Haystack tracer backend, pass that backend explicitly as delegate=...
|
|
96
|
+
loopgrid.enable_tracing()
|
|
97
|
+
|
|
98
|
+
decision = loopgrid.start_decision(
|
|
99
|
+
decision_type="customer_refund",
|
|
100
|
+
agent={"id": "support-agent", "version": "1"},
|
|
101
|
+
authority={"acting_for": "Example Store", "scope": ["refund:create"], "limit_usd": 100},
|
|
102
|
+
model={"provider": "openai", "name": "gpt-5"},
|
|
103
|
+
context={"prompt_version": "support-v1"},
|
|
104
|
+
proposed_action={"tool": "refund.create", "amount": 25, "currency": "USD"},
|
|
105
|
+
policy={
|
|
106
|
+
"policy_id": "refund-policy",
|
|
107
|
+
"version": "1",
|
|
108
|
+
"decision": "auto_allowed",
|
|
109
|
+
"reason": "Within delegated threshold",
|
|
110
|
+
},
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
agent = Agent(
|
|
114
|
+
chat_generator=...,
|
|
115
|
+
tools=[...],
|
|
116
|
+
hooks=loopgrid.agent_hooks(decision["decision_id"]),
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
result = agent.run(messages=[ChatMessage.from_user("Handle this duplicate charge.")])
|
|
120
|
+
loopgrid.flush()
|
|
121
|
+
loopgrid.assert_healthy()
|
|
122
|
+
|
|
123
|
+
# Only after the application observes the authoritative downstream business result:
|
|
124
|
+
loopgrid.record_outcome(
|
|
125
|
+
decision["decision_id"],
|
|
126
|
+
{"status": "succeeded", "external_reference": "refund_123"},
|
|
127
|
+
observer="billing-webhook",
|
|
128
|
+
)
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
## Human approval / ConfirmationHook
|
|
132
|
+
|
|
133
|
+
Haystack's `ConfirmationHook` remains the execution-control mechanism. LoopGrid records evidence about an application-authenticated reviewer; it does not replace Haystack confirmation or application authorization.
|
|
134
|
+
|
|
135
|
+
**Ordering is critical:** pass confirmation/modification hooks through `before_tool_prefix`. LoopGrid's request hook is appended after them, so a rejected call cannot become `tool_requested` evidence and a modified call is recorded with the final model-visible parameters that survive confirmation.
|
|
136
|
+
|
|
137
|
+
```python
|
|
138
|
+
confirmation_hook = ConfirmationHook(confirmation_strategies={...})
|
|
139
|
+
|
|
140
|
+
agent = Agent(
|
|
141
|
+
chat_generator=...,
|
|
142
|
+
tools=[...],
|
|
143
|
+
hooks=loopgrid.agent_hooks(
|
|
144
|
+
decision_id,
|
|
145
|
+
before_tool_prefix=[confirmation_hook],
|
|
146
|
+
),
|
|
147
|
+
)
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
Your authenticated approval UI/strategy should explicitly record the reviewer when the human makes the decision:
|
|
151
|
+
|
|
152
|
+
```python
|
|
153
|
+
loopgrid.record_human_review(
|
|
154
|
+
decision_id,
|
|
155
|
+
reviewer="reviewer@example.com",
|
|
156
|
+
approved=True,
|
|
157
|
+
reason="Reviewed refund evidence",
|
|
158
|
+
)
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
LoopGrid never derives reviewer identity merely from the fact that a Haystack tool call survived `ConfirmationHook`.
|
|
162
|
+
|
|
163
|
+
`record_human_review()` drains earlier queued framework evidence before writing the explicit
|
|
164
|
+
review event. This preserves the real lifecycle ordering even when the LoopGrid transport is
|
|
165
|
+
temporarily slower than the application thread.
|
|
166
|
+
|
|
167
|
+
## Native integration surfaces
|
|
168
|
+
|
|
169
|
+
The integration uses two different Haystack-native boundaries for two different facts:
|
|
170
|
+
|
|
171
|
+
- `Tracer` / `Span`: `haystack.agent.step.llm` completion → `model_completed`.
|
|
172
|
+
- Agent `before_tool` / `after_tool`: actual surviving tool request and resulting tool message → `tool_requested` / `tool_executed`.
|
|
173
|
+
|
|
174
|
+
Haystack tool spans are deliberately ignored for action evidence. The hooks are authoritative because they run after confirmation/modification and around actual Agent-owned tool execution.
|
|
175
|
+
|
|
176
|
+
## Existing Haystack tracing backends
|
|
177
|
+
|
|
178
|
+
Haystack exposes one process-level tracing facade. `enable_tracing()` is explicit:
|
|
179
|
+
|
|
180
|
+
```python
|
|
181
|
+
loopgrid.enable_tracing()
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
Do **not** capture `haystack.tracing.tracer` and pass that facade back as a delegate. The facade routes to the currently enabled tracer; after LoopGrid is installed that would route back into LoopGrid and recurse.
|
|
185
|
+
|
|
186
|
+
If your application already owns a concrete Haystack tracer instance, compose it explicitly:
|
|
187
|
+
|
|
188
|
+
```python
|
|
189
|
+
existing_backend = MyConcreteHaystackTracer(...)
|
|
190
|
+
loopgrid.enable_tracing(delegate=existing_backend)
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
LoopGrid delegates spans directly to that concrete backend while recording its own evidence. Constructing `LoopGridHaystack` by itself never changes global Haystack tracing.
|
|
194
|
+
|
|
195
|
+
## Privacy
|
|
196
|
+
|
|
197
|
+
LoopGrid defaults to `capture_content=False`.
|
|
198
|
+
|
|
199
|
+
Model span tags and tool inputs/outputs are represented by SHA-256 commitments rather than raw content. Haystack itself also disables content tracing by default. Do not enable `HAYSTACK_CONTENT_TRACING_ENABLED=true` unless your application intentionally permits content export.
|
|
200
|
+
|
|
201
|
+
If you explicitly set `capture_content=True`, LoopGrid will include the tool input/result and captured Haystack trace tags in evidence payloads.
|
|
202
|
+
|
|
203
|
+
## Failure behavior
|
|
204
|
+
|
|
205
|
+
Tracer/hook transport is queued and does not raise into the Haystack Agent execution path. Failures are retained and surfaced explicitly:
|
|
206
|
+
|
|
207
|
+
```python
|
|
208
|
+
loopgrid.flush()
|
|
209
|
+
loopgrid.assert_healthy()
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
A successful Agent run is not evidence that LoopGrid transport succeeded unless `assert_healthy()` passes.
|
|
213
|
+
|
|
214
|
+
## Pre-release validation gates
|
|
215
|
+
|
|
216
|
+
The release candidate is **not a public release**. Required before `v0.1.0`:
|
|
217
|
+
|
|
218
|
+
- exact `haystack-ai==3.3.0` runtime install
|
|
219
|
+
- semantic/unit tests
|
|
220
|
+
- real deterministic Haystack Agent runtime test
|
|
221
|
+
- real LoopGrid Core E2E
|
|
222
|
+
- real native `ConfirmationHook` approval ordering E2E
|
|
223
|
+
- rejection and modification regression tests
|
|
224
|
+
- parallel tool-call correlation test
|
|
225
|
+
- repeated-call idempotency across later Agent steps, including missing/reused call IDs
|
|
226
|
+
- queued-event ordering before explicit human review/outcome writes
|
|
227
|
+
- real `Agent.run_async()` runtime regression
|
|
228
|
+
- privacy regression
|
|
229
|
+
- concurrency isolation
|
|
230
|
+
- transport-failure observability
|
|
231
|
+
- `evidence_complete`, applicable coverage 100%, `verify.valid=true`, failures `[]`
|
|
232
|
+
- wheel/sdist build + `twine check`
|
|
233
|
+
- fresh wheel install/import test
|
|
234
|
+
- GitHub CI, exact tested commit tag/release
|
|
235
|
+
- PyPI Trusted Publishing + fresh public install
|
|
236
|
+
- website/docs after public install
|
|
237
|
+
- official Haystack Integrations PR after all release gates pass
|
|
238
|
+
|
|
239
|
+
## License
|
|
240
|
+
|
|
241
|
+
Apache-2.0.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
loopgrid_haystack/__init__.py,sha256=DxYy48Ug7PAXamgW1hZhREBDpayyKKq7jP2Bm8S4hxk,294
|
|
2
|
+
loopgrid_haystack/integration.py,sha256=xlch-WvIYCb75bD7L2YAgCzxEqoPWEDbp3XoTr-HfNA,29116
|
|
3
|
+
loopgrid_haystack-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
4
|
+
loopgrid_haystack-0.1.0.dist-info/METADATA,sha256=5-Dg63JONlkoSmCu6PRO43CsvQ4oKoEMik0uIrHZjT0,8671
|
|
5
|
+
loopgrid_haystack-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
|
|
6
|
+
loopgrid_haystack-0.1.0.dist-info/top_level.txt,sha256=qqcKNwZgBH-9Y1Swx6HyaV7tDQvdfPh1OGF8xg3u1dI,18
|
|
7
|
+
loopgrid_haystack-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
loopgrid_haystack
|