panel-agents 0.1.0b0__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.
- panel_agents/__init__.py +54 -0
- panel_agents/__version.py +46 -0
- panel_agents/actions.py +261 -0
- panel_agents/adapters/__init__.py +7 -0
- panel_agents/adapters/pydantic_ai.py +634 -0
- panel_agents/artifacts/__init__.py +39 -0
- panel_agents/artifacts/diff.py +386 -0
- panel_agents/artifacts/model.py +171 -0
- panel_agents/audit.py +110 -0
- panel_agents/components/__init__.py +19 -0
- panel_agents/components/_diff.py +266 -0
- panel_agents/components/_schema_form.py +634 -0
- panel_agents/components/_toggle.py +114 -0
- panel_agents/components/approval.py +574 -0
- panel_agents/components/artifacts.py +712 -0
- panel_agents/components/chat.py +381 -0
- panel_agents/components/drawer.py +369 -0
- panel_agents/components/renderers.py +225 -0
- panel_agents/components/tool_call.py +431 -0
- panel_agents/events.py +284 -0
- panel_agents/mcp.py +387 -0
- panel_agents/policy.py +134 -0
- panel_agents/recording.py +205 -0
- panel_agents/security.py +205 -0
- panel_agents/state.py +558 -0
- panel_agents-0.1.0b0.dist-info/METADATA +104 -0
- panel_agents-0.1.0b0.dist-info/RECORD +29 -0
- panel_agents-0.1.0b0.dist-info/WHEEL +4 -0
- panel_agents-0.1.0b0.dist-info/licenses/LICENSE.txt +30 -0
panel_agents/__init__.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
from . import events
|
|
2
|
+
from .__version import __version__ # noqa
|
|
3
|
+
from .actions import Action, ActionRegistry
|
|
4
|
+
from .artifacts import Artifact, ArtifactStore, ArtifactVersion, register_diff
|
|
5
|
+
from .audit import AuditLog
|
|
6
|
+
from .components import (
|
|
7
|
+
AgentChat,
|
|
8
|
+
AgentDrawer,
|
|
9
|
+
ApprovalCard,
|
|
10
|
+
ApprovalQueue,
|
|
11
|
+
ArtifactPane,
|
|
12
|
+
ArtifactView,
|
|
13
|
+
ToolCallCard,
|
|
14
|
+
register_renderer,
|
|
15
|
+
)
|
|
16
|
+
from .policy import ApprovalPolicy, ApprovalRule
|
|
17
|
+
from .recording import Recorder, dump_events, load_events, load_state
|
|
18
|
+
from .state import (
|
|
19
|
+
ApprovalRequest,
|
|
20
|
+
MessageState,
|
|
21
|
+
RunInfo,
|
|
22
|
+
RunState,
|
|
23
|
+
ToolCallState,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
__all__ = [
|
|
27
|
+
"Action",
|
|
28
|
+
"ActionRegistry",
|
|
29
|
+
"AgentChat",
|
|
30
|
+
"AgentDrawer",
|
|
31
|
+
"ApprovalCard",
|
|
32
|
+
"ApprovalPolicy",
|
|
33
|
+
"ApprovalQueue",
|
|
34
|
+
"ApprovalRequest",
|
|
35
|
+
"ApprovalRule",
|
|
36
|
+
"Artifact",
|
|
37
|
+
"ArtifactPane",
|
|
38
|
+
"ArtifactStore",
|
|
39
|
+
"ArtifactVersion",
|
|
40
|
+
"ArtifactView",
|
|
41
|
+
"AuditLog",
|
|
42
|
+
"MessageState",
|
|
43
|
+
"Recorder",
|
|
44
|
+
"RunInfo",
|
|
45
|
+
"RunState",
|
|
46
|
+
"ToolCallCard",
|
|
47
|
+
"ToolCallState",
|
|
48
|
+
"dump_events",
|
|
49
|
+
"events",
|
|
50
|
+
"load_events",
|
|
51
|
+
"load_state",
|
|
52
|
+
"register_diff",
|
|
53
|
+
"register_renderer",
|
|
54
|
+
]
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""Define the package version.
|
|
2
|
+
|
|
3
|
+
Called __version.py as setuptools_scm will create a _version.py
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import pathlib
|
|
7
|
+
|
|
8
|
+
PACKAGE = "panel_agents"
|
|
9
|
+
|
|
10
|
+
try:
|
|
11
|
+
# For performance reasons on imports, avoid importing setuptools_scm
|
|
12
|
+
# if not in a .git folder
|
|
13
|
+
if (pathlib.Path(__file__).parent.parent.parent / ".git").is_dir():
|
|
14
|
+
# If setuptools_scm is installed (e.g. in a development environment with
|
|
15
|
+
# an editable install), then use it to determine the version dynamically.
|
|
16
|
+
from setuptools_scm import get_version
|
|
17
|
+
|
|
18
|
+
# This will fail with LookupError if the package is not installed in
|
|
19
|
+
# editable mode or if Git is not installed.
|
|
20
|
+
__version__ = get_version(
|
|
21
|
+
root="../..", relative_to=__file__, version_scheme="post-release"
|
|
22
|
+
)
|
|
23
|
+
else:
|
|
24
|
+
raise FileNotFoundError
|
|
25
|
+
except (ImportError, LookupError, FileNotFoundError):
|
|
26
|
+
# As a fallback, use the version that is hard-coded in the file.
|
|
27
|
+
try:
|
|
28
|
+
# __version__ was added in _version in setuptools-scm 7.0.0, we rely on
|
|
29
|
+
# the hopefully stable version variable.
|
|
30
|
+
from ._version import version as __version__ # type: ignore
|
|
31
|
+
except (ModuleNotFoundError, ImportError):
|
|
32
|
+
# Either _version doesn't exist (ModuleNotFoundError) or version isn't
|
|
33
|
+
# in _version (ImportError). ModuleNotFoundError is a subclass of
|
|
34
|
+
# ImportError, let's be explicit anyway.
|
|
35
|
+
|
|
36
|
+
# Try something else:
|
|
37
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
38
|
+
|
|
39
|
+
try:
|
|
40
|
+
__version__ = version(PACKAGE)
|
|
41
|
+
except PackageNotFoundError:
|
|
42
|
+
# The user is probably trying to run this without having installed
|
|
43
|
+
# the package.
|
|
44
|
+
__version__ = "0.0.0+unknown"
|
|
45
|
+
|
|
46
|
+
__all__ = ("__version__",)
|
panel_agents/actions.py
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Actions on the user interface that an agent can take on the user's behalf.
|
|
3
|
+
|
|
4
|
+
A host app registers the things a user can do in it, such as navigating,
|
|
5
|
+
selecting or filtering, as typed functions on an ``ActionRegistry``. The
|
|
6
|
+
registry derives a JSON schema from each signature, so the same actions
|
|
7
|
+
can be listed in a command palette, exposed to an agent as tools or
|
|
8
|
+
served over MCP without the descriptions drifting apart. Actions always
|
|
9
|
+
run in the Panel session that created the registry.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import asyncio
|
|
15
|
+
import concurrent.futures
|
|
16
|
+
import contextlib
|
|
17
|
+
import inspect
|
|
18
|
+
import re
|
|
19
|
+
from collections.abc import Callable, Iterator
|
|
20
|
+
from dataclasses import dataclass, field
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
import param
|
|
24
|
+
from pydantic import BaseModel, ConfigDict, Field, create_model
|
|
25
|
+
from pydantic.fields import FieldInfo
|
|
26
|
+
|
|
27
|
+
_SECTION = re.compile(r"^(\w[\w ]*):\s*$")
|
|
28
|
+
_ARG = re.compile(r"^\*{0,2}(\w+)\s*(\([^)]*\))?\s*:\s*(.*)$")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _parse_docstring(doc: str | None) -> tuple[str, dict[str, str]]:
|
|
32
|
+
"""
|
|
33
|
+
Split a Google style docstring into its description and the
|
|
34
|
+
descriptions of the arguments listed under ``Args:``.
|
|
35
|
+
"""
|
|
36
|
+
description: list[str] = []
|
|
37
|
+
args: dict[str, str] = {}
|
|
38
|
+
section = None
|
|
39
|
+
current = None
|
|
40
|
+
args_indent = 0
|
|
41
|
+
for line in inspect.cleandoc(doc or "").splitlines():
|
|
42
|
+
if (header := _SECTION.match(line)) is not None:
|
|
43
|
+
section, current = header.group(1).lower(), None
|
|
44
|
+
continue
|
|
45
|
+
if section is None:
|
|
46
|
+
description.append(line)
|
|
47
|
+
elif section in ("args", "arguments", "parameters") and line.strip():
|
|
48
|
+
stripped = line.strip()
|
|
49
|
+
match = _ARG.match(stripped)
|
|
50
|
+
if match and (current is None or len(line) - len(line.lstrip()) <= args_indent):
|
|
51
|
+
current, args_indent = match.group(1), len(line) - len(line.lstrip())
|
|
52
|
+
args[current] = match.group(3).strip()
|
|
53
|
+
elif current is not None:
|
|
54
|
+
args[current] = f"{args[current]} {stripped}".strip()
|
|
55
|
+
return "\n".join(description).strip(), args
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@dataclass
|
|
59
|
+
class Action:
|
|
60
|
+
"""
|
|
61
|
+
A named, typed function the user, a command palette or an agent can
|
|
62
|
+
invoke. ``parameters`` is the JSON schema of its arguments, derived
|
|
63
|
+
from the function's signature and docstring.
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
name: str
|
|
67
|
+
description: str
|
|
68
|
+
function: Callable[..., Any]
|
|
69
|
+
parameters: dict[str, Any] = field(init=False, repr=False)
|
|
70
|
+
_model: type[BaseModel] = field(init=False, repr=False, compare=False)
|
|
71
|
+
|
|
72
|
+
def __post_init__(self):
|
|
73
|
+
_, arg_docs = _parse_docstring(self.function.__doc__)
|
|
74
|
+
signature = inspect.signature(self.function)
|
|
75
|
+
hints = _type_hints(self.function)
|
|
76
|
+
fields: dict[str, Any] = {}
|
|
77
|
+
for pname, p in signature.parameters.items():
|
|
78
|
+
if p.kind in (p.VAR_POSITIONAL, p.VAR_KEYWORD):
|
|
79
|
+
raise TypeError(f"Action {self.name!r} cannot take *{pname}; declare each argument.")
|
|
80
|
+
annotation = hints.get(pname, Any)
|
|
81
|
+
default = ... if p.default is p.empty else p.default
|
|
82
|
+
fields[pname] = (annotation, _with_description(default, arg_docs.get(pname)))
|
|
83
|
+
model_name = "".join(part.title() for part in self.name.split("_")) or "Action"
|
|
84
|
+
self._model = create_model(model_name, __config__=ConfigDict(extra="forbid", arbitrary_types_allowed=True), **fields)
|
|
85
|
+
schema = self._model.model_json_schema()
|
|
86
|
+
schema.pop("title", None)
|
|
87
|
+
for prop in schema.get("properties", {}).values():
|
|
88
|
+
prop.pop("title", None)
|
|
89
|
+
self.parameters = schema
|
|
90
|
+
|
|
91
|
+
@classmethod
|
|
92
|
+
def from_function(cls, function: Callable[..., Any], name: str | None = None, description: str | None = None) -> Action:
|
|
93
|
+
"""An action named after ``function`` and described by its docstring unless given."""
|
|
94
|
+
doc_description, _ = _parse_docstring(function.__doc__)
|
|
95
|
+
return cls(
|
|
96
|
+
name=name or function.__name__,
|
|
97
|
+
description=description if description is not None else doc_description,
|
|
98
|
+
function=function,
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
def validate(self, args: dict[str, Any] | None = None) -> dict[str, Any]:
|
|
102
|
+
"""Validate ``args`` against the signature, returning the keyword arguments to call with."""
|
|
103
|
+
instance = self._model.model_validate(args or {})
|
|
104
|
+
return {name: getattr(instance, name) for name in type(instance).model_fields}
|
|
105
|
+
|
|
106
|
+
def validate_json(self, data: str | bytes) -> dict[str, Any]:
|
|
107
|
+
instance = self._model.model_validate_json(data or "{}")
|
|
108
|
+
return {name: getattr(instance, name) for name in type(instance).model_fields}
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _type_hints(function) -> dict[str, Any]:
|
|
112
|
+
try:
|
|
113
|
+
return inspect.get_annotations(function, eval_str=True)
|
|
114
|
+
except Exception:
|
|
115
|
+
return {k: v for k, v in getattr(function, "__annotations__", {}).items() if not isinstance(v, str)}
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _with_description(default: Any, description: str | None):
|
|
119
|
+
if not description or isinstance(default, FieldInfo):
|
|
120
|
+
return default
|
|
121
|
+
return Field(default, description=description)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _server_loop(doc) -> asyncio.AbstractEventLoop | None:
|
|
125
|
+
try:
|
|
126
|
+
return doc.session_context.server_context.application_context.io_loop.asyncio_loop
|
|
127
|
+
except AttributeError:
|
|
128
|
+
return None
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _session_loop() -> asyncio.AbstractEventLoop | None:
|
|
132
|
+
try:
|
|
133
|
+
return asyncio.get_running_loop()
|
|
134
|
+
except RuntimeError:
|
|
135
|
+
return None
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
class ActionRegistry(param.Parameterized):
|
|
139
|
+
"""
|
|
140
|
+
The actions a host app offers in one user session.
|
|
141
|
+
|
|
142
|
+
Create it inside the session, e.g. while building the page, so
|
|
143
|
+
actions invoked from elsewhere (a tool running in another thread, an
|
|
144
|
+
MCP request) still run in the user's session and update the page
|
|
145
|
+
they are looking at. Calls from outside the session's event loop are
|
|
146
|
+
handed to it through the document's next-tick callback, which also
|
|
147
|
+
holds the document lock, so sync actions block that session while
|
|
148
|
+
they run. Once the session is destroyed, invoking raises.
|
|
149
|
+
|
|
150
|
+
>>> actions = ActionRegistry()
|
|
151
|
+
>>> @actions.action
|
|
152
|
+
... def open_page(path: str) -> str:
|
|
153
|
+
... '''Navigate to a page of the app.'''
|
|
154
|
+
... return f"Opened {path}"
|
|
155
|
+
"""
|
|
156
|
+
|
|
157
|
+
actions = param.Dict(default={}, constant=True, doc="""
|
|
158
|
+
Mapping of action name to Action, in registration order.""")
|
|
159
|
+
|
|
160
|
+
def __init__(self, **params):
|
|
161
|
+
super().__init__(**params)
|
|
162
|
+
import panel as pn
|
|
163
|
+
|
|
164
|
+
self._doc = pn.state.curdoc
|
|
165
|
+
self._loop = _session_loop()
|
|
166
|
+
self._closed = False
|
|
167
|
+
self._pending: set[concurrent.futures.Future] = set()
|
|
168
|
+
if self._doc is not None and self._doc.session_context is not None:
|
|
169
|
+
pn.state.on_session_destroyed(self._on_session_destroyed)
|
|
170
|
+
|
|
171
|
+
def _on_session_destroyed(self, session_context):
|
|
172
|
+
self._closed = True
|
|
173
|
+
# Calls handed to the session that will now never run must not leave their callers waiting.
|
|
174
|
+
for future in list(self._pending):
|
|
175
|
+
if not future.done():
|
|
176
|
+
future.set_exception(RuntimeError("The session these actions belong to has ended."))
|
|
177
|
+
self._pending.clear()
|
|
178
|
+
|
|
179
|
+
def __iter__(self) -> Iterator[Action]:
|
|
180
|
+
return iter(self.actions.values())
|
|
181
|
+
|
|
182
|
+
def __len__(self) -> int:
|
|
183
|
+
return len(self.actions)
|
|
184
|
+
|
|
185
|
+
def __contains__(self, name: str) -> bool:
|
|
186
|
+
return name in self.actions
|
|
187
|
+
|
|
188
|
+
def __getitem__(self, name: str) -> Action:
|
|
189
|
+
return self.actions[name]
|
|
190
|
+
|
|
191
|
+
def add(self, function: Callable[..., Any], *, name: str | None = None, description: str | None = None) -> Action:
|
|
192
|
+
"""Register ``function`` as an action, replacing any action of the same name."""
|
|
193
|
+
action = Action.from_function(function, name=name, description=description)
|
|
194
|
+
with param.edit_constant(self):
|
|
195
|
+
self.actions = {**self.actions, action.name: action}
|
|
196
|
+
return action
|
|
197
|
+
|
|
198
|
+
def action(self, function: Callable[..., Any] | None = None, *, name: str | None = None, description: str | None = None):
|
|
199
|
+
"""Decorator registering a function as an action, with or without arguments."""
|
|
200
|
+
def register(f):
|
|
201
|
+
self.add(f, name=name, description=description)
|
|
202
|
+
return f
|
|
203
|
+
return register if function is None else register(function)
|
|
204
|
+
|
|
205
|
+
def remove(self, name: str):
|
|
206
|
+
"""Unregister an action."""
|
|
207
|
+
with param.edit_constant(self):
|
|
208
|
+
self.actions = {k: v for k, v in self.actions.items() if k != name}
|
|
209
|
+
|
|
210
|
+
async def invoke(self, name: str, args: dict[str, Any] | None = None) -> Any:
|
|
211
|
+
"""
|
|
212
|
+
Validate ``args`` and run the action in the registry's session,
|
|
213
|
+
returning its result. Coroutine functions are awaited.
|
|
214
|
+
"""
|
|
215
|
+
action = self.actions.get(name)
|
|
216
|
+
if action is None:
|
|
217
|
+
raise KeyError(f"Unknown action {name!r}; available: {', '.join(self.actions) or 'none'}.")
|
|
218
|
+
return await self._invoke_validated(action, action.validate(args))
|
|
219
|
+
|
|
220
|
+
async def _invoke_validated(self, action: Action, kwargs: dict[str, Any]) -> Any:
|
|
221
|
+
if self._closed:
|
|
222
|
+
raise RuntimeError(f"The session the {action.name!r} action belongs to has ended.")
|
|
223
|
+
doc = self._doc
|
|
224
|
+
# Resolved now rather than at construction, which may have happened on a worker thread.
|
|
225
|
+
loop = _server_loop(doc) or self._loop
|
|
226
|
+
if loop is None or not loop.is_running() or loop is _session_loop():
|
|
227
|
+
return await self._call(action, kwargs)
|
|
228
|
+
result: concurrent.futures.Future = concurrent.futures.Future()
|
|
229
|
+
self._pending.add(result)
|
|
230
|
+
result.add_done_callback(self._pending.discard)
|
|
231
|
+
|
|
232
|
+
async def run():
|
|
233
|
+
if result.done():
|
|
234
|
+
return
|
|
235
|
+
try:
|
|
236
|
+
value = await self._call(action, kwargs)
|
|
237
|
+
except BaseException as e:
|
|
238
|
+
if not result.done():
|
|
239
|
+
result.set_exception(e)
|
|
240
|
+
else:
|
|
241
|
+
if not result.done():
|
|
242
|
+
result.set_result(value)
|
|
243
|
+
|
|
244
|
+
if doc is not None and doc.session_context is not None:
|
|
245
|
+
doc.add_next_tick_callback(run)
|
|
246
|
+
else:
|
|
247
|
+
asyncio.run_coroutine_threadsafe(run(), loop)
|
|
248
|
+
return await asyncio.wrap_future(result)
|
|
249
|
+
|
|
250
|
+
async def _call(self, action: Action, kwargs: dict[str, Any]) -> Any:
|
|
251
|
+
from panel.io.state import set_curdoc
|
|
252
|
+
|
|
253
|
+
context = set_curdoc(self._doc) if self._doc is not None else contextlib.nullcontext()
|
|
254
|
+
with context:
|
|
255
|
+
result = action.function(**kwargs)
|
|
256
|
+
if inspect.isawaitable(result):
|
|
257
|
+
result = await result
|
|
258
|
+
return result
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
__all__ = ["Action", "ActionRegistry"]
|