agent-snr 0.1.1__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.
- agent_snr/__init__.py +60 -0
- agent_snr/adapters/__init__.py +12 -0
- agent_snr/adapters/crewai.py +147 -0
- agent_snr/adapters/langgraph.py +293 -0
- agent_snr/adapters/openai.py +241 -0
- agent_snr/cli.py +282 -0
- agent_snr/core/__init__.py +39 -0
- agent_snr/core/embedder.py +224 -0
- agent_snr/core/firewall.py +234 -0
- agent_snr/core/frames.py +231 -0
- agent_snr/core/telemetry.py +490 -0
- agent_snr/modules/__init__.py +14 -0
- agent_snr/modules/budgeter.py +118 -0
- agent_snr/modules/compactor.py +226 -0
- agent_snr/modules/entropy.py +141 -0
- agent_snr/modules/router.py +101 -0
- agent_snr/py.typed +0 -0
- agent_snr-0.1.1.dist-info/METADATA +288 -0
- agent_snr-0.1.1.dist-info/RECORD +23 -0
- agent_snr-0.1.1.dist-info/WHEEL +5 -0
- agent_snr-0.1.1.dist-info/entry_points.txt +2 -0
- agent_snr-0.1.1.dist-info/licenses/LICENSE +17 -0
- agent_snr-0.1.1.dist-info/top_level.txt +1 -0
agent_snr/__init__.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""Agent SNR: An open-source, lightweight, framework-agnostic Agent Signal Firewall."""
|
|
2
|
+
|
|
3
|
+
from agent_snr.adapters.crewai import CrewAISNRHook
|
|
4
|
+
from agent_snr.adapters.langgraph import LangGraphSNRAdapter
|
|
5
|
+
from agent_snr.adapters.openai import AsyncSNRWrappedOpenAI, SNRWrappedOpenAI
|
|
6
|
+
from agent_snr.core.embedder import (
|
|
7
|
+
BaseEmbedder,
|
|
8
|
+
FastEmbedAdapter,
|
|
9
|
+
HashNgramEmbedder,
|
|
10
|
+
cosine_similarity,
|
|
11
|
+
)
|
|
12
|
+
from agent_snr.core.firewall import (
|
|
13
|
+
AgentSNRFirewall,
|
|
14
|
+
SNRCircuitBreakError,
|
|
15
|
+
)
|
|
16
|
+
from agent_snr.core.frames import (
|
|
17
|
+
FirewallAction,
|
|
18
|
+
FrameRole,
|
|
19
|
+
SignalFrame,
|
|
20
|
+
TraceLedger,
|
|
21
|
+
)
|
|
22
|
+
from agent_snr.core.telemetry import (
|
|
23
|
+
StepTelemetry,
|
|
24
|
+
TelemetryProfiler,
|
|
25
|
+
attach_to_otel_span,
|
|
26
|
+
profile_step,
|
|
27
|
+
)
|
|
28
|
+
from agent_snr.modules.budgeter import DynamicAttentionBudgeter
|
|
29
|
+
from agent_snr.modules.compactor import StateCompactor
|
|
30
|
+
from agent_snr.modules.entropy import LoopEntropyDetector
|
|
31
|
+
from agent_snr.modules.router import SkipLevelRouter, SkipRule
|
|
32
|
+
|
|
33
|
+
__version__ = "0.1.1"
|
|
34
|
+
|
|
35
|
+
__all__ = [
|
|
36
|
+
"AgentSNRFirewall",
|
|
37
|
+
"AsyncSNRWrappedOpenAI",
|
|
38
|
+
"BaseEmbedder",
|
|
39
|
+
"CrewAISNRHook",
|
|
40
|
+
"DynamicAttentionBudgeter",
|
|
41
|
+
"FastEmbedAdapter",
|
|
42
|
+
"FirewallAction",
|
|
43
|
+
"FrameRole",
|
|
44
|
+
"HashNgramEmbedder",
|
|
45
|
+
"LangGraphSNRAdapter",
|
|
46
|
+
"LoopEntropyDetector",
|
|
47
|
+
"SNRCircuitBreakError",
|
|
48
|
+
"SNRWrappedOpenAI",
|
|
49
|
+
"SignalFrame",
|
|
50
|
+
"SkipLevelRouter",
|
|
51
|
+
"SkipRule",
|
|
52
|
+
"StateCompactor",
|
|
53
|
+
"StepTelemetry",
|
|
54
|
+
"TelemetryProfiler",
|
|
55
|
+
"TraceLedger",
|
|
56
|
+
"__version__",
|
|
57
|
+
"attach_to_otel_span",
|
|
58
|
+
"cosine_similarity",
|
|
59
|
+
"profile_step",
|
|
60
|
+
]
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""Zero-lock-in ecosystem adapters for OpenAI, LiteLLM, LangGraph, and CrewAI."""
|
|
2
|
+
|
|
3
|
+
from agent_snr.adapters.crewai import CrewAISNRHook
|
|
4
|
+
from agent_snr.adapters.langgraph import LangGraphSNRAdapter
|
|
5
|
+
from agent_snr.adapters.openai import AsyncSNRWrappedOpenAI, SNRWrappedOpenAI
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"AsyncSNRWrappedOpenAI",
|
|
9
|
+
"CrewAISNRHook",
|
|
10
|
+
"LangGraphSNRAdapter",
|
|
11
|
+
"SNRWrappedOpenAI",
|
|
12
|
+
]
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
"""CrewAI step callback hook adapter for the Agent Signal Firewall."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from agent_snr.core.firewall import AgentSNRFirewall
|
|
9
|
+
from agent_snr.core.telemetry import TelemetryProfiler
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class CrewAISNRHook:
|
|
13
|
+
"""Callback hook integrating AgentSNRFirewall into CrewAI step_callback execution."""
|
|
14
|
+
|
|
15
|
+
def __init__(
|
|
16
|
+
self,
|
|
17
|
+
firewall: AgentSNRFirewall | None = None,
|
|
18
|
+
session_id: str = "crew_session",
|
|
19
|
+
) -> None:
|
|
20
|
+
"""Initialize CrewAISNRHook.
|
|
21
|
+
|
|
22
|
+
Args:
|
|
23
|
+
firewall: AgentSNRFirewall instance (created if None).
|
|
24
|
+
session_id: Session identifier used for telemetry and trajectory ledger.
|
|
25
|
+
"""
|
|
26
|
+
self._firewall = firewall if firewall is not None else AgentSNRFirewall()
|
|
27
|
+
self.session_id = session_id
|
|
28
|
+
self._histories: dict[str, list[dict[str, Any]]] = {}
|
|
29
|
+
|
|
30
|
+
@property
|
|
31
|
+
def firewall(self) -> AgentSNRFirewall:
|
|
32
|
+
"""Access the underlying AgentSNRFirewall."""
|
|
33
|
+
return self._firewall
|
|
34
|
+
|
|
35
|
+
@property
|
|
36
|
+
def profiler(self) -> TelemetryProfiler:
|
|
37
|
+
"""Access the firewall's TelemetryProfiler."""
|
|
38
|
+
return self._firewall.profiler
|
|
39
|
+
|
|
40
|
+
def reset(self, session_id: str | None = None) -> None:
|
|
41
|
+
"""Reset step message history for a session."""
|
|
42
|
+
target = session_id or self.session_id
|
|
43
|
+
self._histories.pop(target, None)
|
|
44
|
+
|
|
45
|
+
def _extract_step_info(
|
|
46
|
+
self, step_output: Any
|
|
47
|
+
) -> tuple[str, str | None, dict[str, Any] | None, str]:
|
|
48
|
+
"""Extract node_id, tool_name, tool_args, and content from arbitrary CrewAI outputs."""
|
|
49
|
+
# 1. Agent / Node identifier
|
|
50
|
+
node_id = "crew_agent"
|
|
51
|
+
if hasattr(step_output, "agent"):
|
|
52
|
+
agent_obj = step_output.agent
|
|
53
|
+
node_id = str(
|
|
54
|
+
getattr(agent_obj, "role", getattr(agent_obj, "name", str(agent_obj)))
|
|
55
|
+
)
|
|
56
|
+
elif isinstance(step_output, dict) and "agent" in step_output:
|
|
57
|
+
node_id = str(step_output["agent"])
|
|
58
|
+
elif hasattr(step_output, "role"):
|
|
59
|
+
node_id = str(step_output.role)
|
|
60
|
+
|
|
61
|
+
# 2. Tool information
|
|
62
|
+
tool_name: str | None = None
|
|
63
|
+
tool_args: dict[str, Any] | None = None
|
|
64
|
+
|
|
65
|
+
action_obj = getattr(step_output, "action", None)
|
|
66
|
+
if action_obj is not None:
|
|
67
|
+
tool_name = getattr(action_obj, "tool", None)
|
|
68
|
+
raw_input = getattr(action_obj, "tool_input", None)
|
|
69
|
+
tool_args = raw_input if isinstance(raw_input, dict) else {"input": str(raw_input)}
|
|
70
|
+
elif isinstance(step_output, dict):
|
|
71
|
+
tool_name = step_output.get("tool")
|
|
72
|
+
raw_input = step_output.get("tool_input")
|
|
73
|
+
tool_args = raw_input if isinstance(raw_input, dict) else {"input": str(raw_input)}
|
|
74
|
+
elif isinstance(step_output, (tuple, list)) and len(step_output) > 1:
|
|
75
|
+
action_part = step_output[0]
|
|
76
|
+
tool_name = str(getattr(action_part, "tool", str(action_part)))
|
|
77
|
+
raw_input = getattr(action_part, "tool_input", None)
|
|
78
|
+
tool_args = raw_input if isinstance(raw_input, dict) else {"input": str(raw_input)}
|
|
79
|
+
|
|
80
|
+
# 3. Observation / Content
|
|
81
|
+
if hasattr(step_output, "observation"):
|
|
82
|
+
content = str(step_output.observation)
|
|
83
|
+
elif hasattr(step_output, "result"):
|
|
84
|
+
content = str(step_output.result)
|
|
85
|
+
elif hasattr(step_output, "output"):
|
|
86
|
+
content = str(step_output.output)
|
|
87
|
+
elif isinstance(step_output, dict):
|
|
88
|
+
content = str(
|
|
89
|
+
step_output.get(
|
|
90
|
+
"output",
|
|
91
|
+
step_output.get(
|
|
92
|
+
"result", step_output.get("observation", str(step_output))
|
|
93
|
+
),
|
|
94
|
+
)
|
|
95
|
+
)
|
|
96
|
+
elif isinstance(step_output, (tuple, list)) and len(step_output) > 1:
|
|
97
|
+
content = str(step_output[1])
|
|
98
|
+
else:
|
|
99
|
+
content = str(step_output)
|
|
100
|
+
|
|
101
|
+
return node_id, tool_name, tool_args, content
|
|
102
|
+
|
|
103
|
+
def __call__(self, step_output: Any) -> None:
|
|
104
|
+
"""Execute firewall telemetry and loop detection on each CrewAI step."""
|
|
105
|
+
node_id, tool_name, tool_args, content = self._extract_step_info(step_output)
|
|
106
|
+
|
|
107
|
+
messages: list[dict[str, Any]] = []
|
|
108
|
+
if tool_name:
|
|
109
|
+
messages.append(
|
|
110
|
+
{
|
|
111
|
+
"role": "tool_call",
|
|
112
|
+
"name": tool_name,
|
|
113
|
+
"tool_args": tool_args,
|
|
114
|
+
"content": f"Calling tool {tool_name}",
|
|
115
|
+
}
|
|
116
|
+
)
|
|
117
|
+
messages.append(
|
|
118
|
+
{
|
|
119
|
+
"role": "tool_result",
|
|
120
|
+
"name": tool_name,
|
|
121
|
+
"tool_args": tool_args,
|
|
122
|
+
"content": content,
|
|
123
|
+
}
|
|
124
|
+
)
|
|
125
|
+
else:
|
|
126
|
+
messages.append(
|
|
127
|
+
{
|
|
128
|
+
"role": "assistant",
|
|
129
|
+
"content": content,
|
|
130
|
+
}
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
# Accumulate in step history for the session so incremental frames are ingested
|
|
134
|
+
if self.session_id not in self._histories:
|
|
135
|
+
self._histories[self.session_id] = []
|
|
136
|
+
self._histories[self.session_id].extend(messages)
|
|
137
|
+
|
|
138
|
+
# Process through firewall (raises SNRCircuitBreakError if threshold exceeded)
|
|
139
|
+
self.firewall.process_outbound(
|
|
140
|
+
session_id=self.session_id,
|
|
141
|
+
node_id=node_id,
|
|
142
|
+
messages=self._histories[self.session_id],
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
def as_callback(self) -> Callable[[Any], None]:
|
|
146
|
+
"""Return a callable reference for CrewAI step_callback."""
|
|
147
|
+
return self.__call__
|
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
"""LangGraph node and conditional edge interceptor adapter for the Agent Signal Firewall."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import copy
|
|
6
|
+
import functools
|
|
7
|
+
import inspect
|
|
8
|
+
from collections.abc import Callable, Sequence
|
|
9
|
+
from typing import Any, TypeVar
|
|
10
|
+
|
|
11
|
+
from agent_snr.core.firewall import AgentSNRFirewall
|
|
12
|
+
from agent_snr.core.telemetry import TelemetryProfiler
|
|
13
|
+
|
|
14
|
+
F = TypeVar("F", bound=Callable[..., Any])
|
|
15
|
+
|
|
16
|
+
ROLE_MAP = {
|
|
17
|
+
"human": "user",
|
|
18
|
+
"user": "user",
|
|
19
|
+
"ai": "assistant",
|
|
20
|
+
"assistant": "assistant",
|
|
21
|
+
"tool": "tool_result",
|
|
22
|
+
"tool_result": "tool_result",
|
|
23
|
+
"function": "tool_result",
|
|
24
|
+
"system": "system",
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
INVERSE_ROLE_MAP = {
|
|
28
|
+
"user": "human",
|
|
29
|
+
"assistant": "ai",
|
|
30
|
+
"tool_result": "tool",
|
|
31
|
+
"system": "system",
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class LangGraphSNRAdapter:
|
|
36
|
+
"""Zero-lock-in interceptor for LangGraph node functions and conditional edge routers."""
|
|
37
|
+
|
|
38
|
+
def __init__(
|
|
39
|
+
self,
|
|
40
|
+
firewall: AgentSNRFirewall | None = None,
|
|
41
|
+
session_key: str = "thread_id",
|
|
42
|
+
messages_key: str = "messages",
|
|
43
|
+
) -> None:
|
|
44
|
+
"""Initialize LangGraphSNRAdapter.
|
|
45
|
+
|
|
46
|
+
Args:
|
|
47
|
+
firewall: AgentSNRFirewall instance (created if None).
|
|
48
|
+
session_key: Configurable key used to extract session ID (default: 'thread_id').
|
|
49
|
+
messages_key: State dictionary key containing messages (default: 'messages').
|
|
50
|
+
"""
|
|
51
|
+
self._firewall = firewall if firewall is not None else AgentSNRFirewall()
|
|
52
|
+
self.session_key = session_key
|
|
53
|
+
self.messages_key = messages_key
|
|
54
|
+
|
|
55
|
+
@property
|
|
56
|
+
def firewall(self) -> AgentSNRFirewall:
|
|
57
|
+
"""Access the underlying AgentSNRFirewall instance."""
|
|
58
|
+
return self._firewall
|
|
59
|
+
|
|
60
|
+
@property
|
|
61
|
+
def profiler(self) -> TelemetryProfiler:
|
|
62
|
+
"""Access the firewall's TelemetryProfiler."""
|
|
63
|
+
return self._firewall.profiler
|
|
64
|
+
|
|
65
|
+
def _normalize_messages(self, raw_messages: Sequence[Any]) -> list[dict[str, Any]]:
|
|
66
|
+
"""Normalize both LangChain BaseMessage duck-types and dicts into canonical dicts."""
|
|
67
|
+
normalized: list[dict[str, Any]] = []
|
|
68
|
+
for item in raw_messages:
|
|
69
|
+
if isinstance(item, dict):
|
|
70
|
+
normalized.append(
|
|
71
|
+
{
|
|
72
|
+
"role": str(item.get("role", "user")),
|
|
73
|
+
"content": str(item.get("content", "")),
|
|
74
|
+
"name": item.get("name"),
|
|
75
|
+
"tool_args": item.get("tool_args"),
|
|
76
|
+
}
|
|
77
|
+
)
|
|
78
|
+
else:
|
|
79
|
+
# Duck-type LangChain BaseMessage (has .content and .type/.role)
|
|
80
|
+
raw_type = getattr(item, "type", getattr(item, "role", "user"))
|
|
81
|
+
mapped_role = ROLE_MAP.get(str(raw_type).lower(), "user")
|
|
82
|
+
normalized.append(
|
|
83
|
+
{
|
|
84
|
+
"role": mapped_role,
|
|
85
|
+
"content": str(getattr(item, "content", "")),
|
|
86
|
+
"name": getattr(item, "name", None),
|
|
87
|
+
"tool_args": getattr(
|
|
88
|
+
item,
|
|
89
|
+
"tool_args",
|
|
90
|
+
getattr(item, "additional_kwargs", None),
|
|
91
|
+
),
|
|
92
|
+
}
|
|
93
|
+
)
|
|
94
|
+
return normalized
|
|
95
|
+
|
|
96
|
+
def _reconstruct_messages(
|
|
97
|
+
self,
|
|
98
|
+
original_raw: Sequence[Any],
|
|
99
|
+
optimized_dicts: list[dict[str, Any]],
|
|
100
|
+
) -> list[Any]:
|
|
101
|
+
"""Restore messages into the original format (dicts or BaseMessage duck types)."""
|
|
102
|
+
if not original_raw or isinstance(original_raw[0], dict):
|
|
103
|
+
return optimized_dicts
|
|
104
|
+
|
|
105
|
+
# Attempt to preserve or reconstruct objects matching original type
|
|
106
|
+
first_obj = original_raw[0]
|
|
107
|
+
reconstructed: list[Any] = []
|
|
108
|
+
|
|
109
|
+
for d in optimized_dicts:
|
|
110
|
+
role = d["role"]
|
|
111
|
+
content = d["content"]
|
|
112
|
+
# Look for an existing message in original_raw to clone
|
|
113
|
+
matched_orig = None
|
|
114
|
+
for orig in original_raw:
|
|
115
|
+
orig_type = getattr(orig, "type", getattr(orig, "role", "user"))
|
|
116
|
+
if ROLE_MAP.get(str(orig_type).lower(), "user") == role:
|
|
117
|
+
matched_orig = orig
|
|
118
|
+
break
|
|
119
|
+
|
|
120
|
+
if matched_orig is not None:
|
|
121
|
+
try:
|
|
122
|
+
cloned = copy.copy(matched_orig)
|
|
123
|
+
cloned.content = content
|
|
124
|
+
if d.get("name"):
|
|
125
|
+
cloned.name = d["name"]
|
|
126
|
+
reconstructed.append(cloned)
|
|
127
|
+
continue
|
|
128
|
+
except Exception:
|
|
129
|
+
pass
|
|
130
|
+
|
|
131
|
+
# Fallback to duck-type instantiation or dict
|
|
132
|
+
try:
|
|
133
|
+
msg_cls = type(first_obj)
|
|
134
|
+
new_msg = msg_cls(content=content)
|
|
135
|
+
if hasattr(new_msg, "type"):
|
|
136
|
+
new_msg.type = INVERSE_ROLE_MAP.get(role, role)
|
|
137
|
+
reconstructed.append(new_msg)
|
|
138
|
+
except Exception:
|
|
139
|
+
reconstructed.append(d)
|
|
140
|
+
|
|
141
|
+
return reconstructed
|
|
142
|
+
|
|
143
|
+
def _extract_session_id(self, *args: Any, **kwargs: Any) -> str:
|
|
144
|
+
"""Extract session_id from LangGraph config dictionary."""
|
|
145
|
+
config = None
|
|
146
|
+
if len(args) > 1 and isinstance(args[1], dict):
|
|
147
|
+
config = args[1]
|
|
148
|
+
elif "config" in kwargs and isinstance(kwargs["config"], dict):
|
|
149
|
+
config = kwargs["config"]
|
|
150
|
+
|
|
151
|
+
if config and isinstance(config, dict):
|
|
152
|
+
configurable = config.get("configurable", {})
|
|
153
|
+
if isinstance(configurable, dict) and self.session_key in configurable:
|
|
154
|
+
return str(configurable[self.session_key])
|
|
155
|
+
|
|
156
|
+
return "default"
|
|
157
|
+
|
|
158
|
+
def guard_node(self, node_id: str) -> Callable[[F], F]:
|
|
159
|
+
"""Decorate a LangGraph node function (sync or async) with firewall protection."""
|
|
160
|
+
|
|
161
|
+
def decorator(fn: F) -> F:
|
|
162
|
+
is_async = inspect.iscoroutinefunction(fn)
|
|
163
|
+
sig = inspect.signature(fn)
|
|
164
|
+
params = sig.parameters
|
|
165
|
+
accepts_var_kwargs = any(
|
|
166
|
+
p.kind == inspect.Parameter.VAR_KEYWORD for p in params.values()
|
|
167
|
+
)
|
|
168
|
+
accepts_multiple_pos = len(params) > 1 or any(
|
|
169
|
+
p.kind == inspect.Parameter.VAR_POSITIONAL for p in params.values()
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
def _prepare_guarded_state(args: tuple[Any, ...]) -> tuple[dict[str, Any], Any]:
|
|
173
|
+
state = args[0]
|
|
174
|
+
state_copy = copy.copy(state) if isinstance(state, dict) else dict(state)
|
|
175
|
+
raw_msgs = state_copy.get(self.messages_key, [])
|
|
176
|
+
return state_copy, raw_msgs
|
|
177
|
+
|
|
178
|
+
def _filter_kwargs(kwargs: dict[str, Any]) -> dict[str, Any]:
|
|
179
|
+
if accepts_var_kwargs:
|
|
180
|
+
return kwargs
|
|
181
|
+
return {k: v for k, v in kwargs.items() if k in params}
|
|
182
|
+
|
|
183
|
+
if is_async:
|
|
184
|
+
|
|
185
|
+
@functools.wraps(fn)
|
|
186
|
+
async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
187
|
+
if not args:
|
|
188
|
+
return await fn(*args, **kwargs)
|
|
189
|
+
|
|
190
|
+
session_id = self._extract_session_id(*args, **kwargs)
|
|
191
|
+
state_copy, raw_msgs = _prepare_guarded_state(args)
|
|
192
|
+
|
|
193
|
+
if raw_msgs:
|
|
194
|
+
norm_msgs = self._normalize_messages(raw_msgs)
|
|
195
|
+
opt_msgs, _action, _metrics = self.firewall.process_outbound(
|
|
196
|
+
session_id=session_id,
|
|
197
|
+
node_id=node_id,
|
|
198
|
+
messages=norm_msgs,
|
|
199
|
+
)
|
|
200
|
+
state_copy[self.messages_key] = self._reconstruct_messages(
|
|
201
|
+
raw_msgs, opt_msgs
|
|
202
|
+
)
|
|
203
|
+
|
|
204
|
+
filtered_kw = _filter_kwargs(kwargs)
|
|
205
|
+
if accepts_multiple_pos and len(args) > 1:
|
|
206
|
+
return await fn(state_copy, *args[1:], **filtered_kw)
|
|
207
|
+
return await fn(state_copy, **filtered_kw)
|
|
208
|
+
|
|
209
|
+
return async_wrapper # type: ignore[return-value]
|
|
210
|
+
|
|
211
|
+
@functools.wraps(fn)
|
|
212
|
+
def sync_wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
213
|
+
if not args:
|
|
214
|
+
return fn(*args, **kwargs)
|
|
215
|
+
|
|
216
|
+
session_id = self._extract_session_id(*args, **kwargs)
|
|
217
|
+
state_copy, raw_msgs = _prepare_guarded_state(args)
|
|
218
|
+
|
|
219
|
+
if raw_msgs:
|
|
220
|
+
norm_msgs = self._normalize_messages(raw_msgs)
|
|
221
|
+
opt_msgs, _action, _metrics = self.firewall.process_outbound(
|
|
222
|
+
session_id=session_id,
|
|
223
|
+
node_id=node_id,
|
|
224
|
+
messages=norm_msgs,
|
|
225
|
+
)
|
|
226
|
+
state_copy[self.messages_key] = self._reconstruct_messages(
|
|
227
|
+
raw_msgs, opt_msgs
|
|
228
|
+
)
|
|
229
|
+
|
|
230
|
+
filtered_kw = _filter_kwargs(kwargs)
|
|
231
|
+
if accepts_multiple_pos and len(args) > 1:
|
|
232
|
+
return fn(state_copy, *args[1:], **filtered_kw)
|
|
233
|
+
return fn(state_copy, **filtered_kw)
|
|
234
|
+
|
|
235
|
+
return sync_wrapper # type: ignore[return-value]
|
|
236
|
+
|
|
237
|
+
return decorator
|
|
238
|
+
|
|
239
|
+
def skip_router(
|
|
240
|
+
self,
|
|
241
|
+
current_node: str,
|
|
242
|
+
default_router: Callable[..., str],
|
|
243
|
+
) -> Callable[..., Any]:
|
|
244
|
+
"""Wrap a LangGraph conditional edge routing function with skip-level bypasses."""
|
|
245
|
+
is_async = inspect.iscoroutinefunction(default_router)
|
|
246
|
+
sig = inspect.signature(default_router)
|
|
247
|
+
params = sig.parameters
|
|
248
|
+
accepts_var_kwargs = any(
|
|
249
|
+
p.kind == inspect.Parameter.VAR_KEYWORD for p in params.values()
|
|
250
|
+
)
|
|
251
|
+
accepts_multiple_pos = len(params) > 1 or any(
|
|
252
|
+
p.kind == inspect.Parameter.VAR_POSITIONAL for p in params.values()
|
|
253
|
+
)
|
|
254
|
+
|
|
255
|
+
def _call_router(args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any:
|
|
256
|
+
filtered_kw = (
|
|
257
|
+
kwargs
|
|
258
|
+
if accepts_var_kwargs
|
|
259
|
+
else {k: v for k, v in kwargs.items() if k in params}
|
|
260
|
+
)
|
|
261
|
+
if accepts_multiple_pos and len(args) > 1:
|
|
262
|
+
return default_router(*args, **filtered_kw)
|
|
263
|
+
if args:
|
|
264
|
+
return default_router(args[0], **filtered_kw)
|
|
265
|
+
return default_router(**filtered_kw)
|
|
266
|
+
|
|
267
|
+
if is_async:
|
|
268
|
+
|
|
269
|
+
@functools.wraps(default_router)
|
|
270
|
+
async def async_router_wrapper(*args: Any, **kwargs: Any) -> str:
|
|
271
|
+
default_next = await _call_router(args, kwargs)
|
|
272
|
+
session_id = self._extract_session_id(*args, **kwargs)
|
|
273
|
+
next_node, _skipped = self.firewall.resolve_route(
|
|
274
|
+
session_id=session_id,
|
|
275
|
+
current_node=current_node,
|
|
276
|
+
default_next_node=default_next,
|
|
277
|
+
)
|
|
278
|
+
return next_node
|
|
279
|
+
|
|
280
|
+
return async_router_wrapper
|
|
281
|
+
|
|
282
|
+
@functools.wraps(default_router)
|
|
283
|
+
def sync_router_wrapper(*args: Any, **kwargs: Any) -> str:
|
|
284
|
+
default_next = _call_router(args, kwargs)
|
|
285
|
+
session_id = self._extract_session_id(*args, **kwargs)
|
|
286
|
+
next_node, _skipped = self.firewall.resolve_route(
|
|
287
|
+
session_id=session_id,
|
|
288
|
+
current_node=current_node,
|
|
289
|
+
default_next_node=default_next,
|
|
290
|
+
)
|
|
291
|
+
return next_node
|
|
292
|
+
|
|
293
|
+
return sync_router_wrapper
|