agentframe-py 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.
Files changed (46) hide show
  1. agentframe/__init__.py +170 -0
  2. agentframe/authoring/__init__.py +1 -0
  3. agentframe/authoring/agent.py +75 -0
  4. agentframe/authoring/context.py +123 -0
  5. agentframe/authoring/decorators.py +202 -0
  6. agentframe/authoring/definitions.py +372 -0
  7. agentframe/authoring/services.py +176 -0
  8. agentframe/cli.py +293 -0
  9. agentframe/errors.py +194 -0
  10. agentframe/hosting/__init__.py +1 -0
  11. agentframe/hosting/a2a_executor.py +569 -0
  12. agentframe/hosting/admission.py +69 -0
  13. agentframe/hosting/app.py +617 -0
  14. agentframe/hosting/card.py +138 -0
  15. agentframe/hosting/dedup.py +193 -0
  16. agentframe/hosting/draining_server.py +47 -0
  17. agentframe/hosting/host.py +143 -0
  18. agentframe/hosting/lifecycle.py +81 -0
  19. agentframe/hosting/model_router.py +407 -0
  20. agentframe/hosting/request_size.py +52 -0
  21. agentframe/hosting/routing.py +349 -0
  22. agentframe/models/__init__.py +1 -0
  23. agentframe/models/base.py +264 -0
  24. agentframe/models/foundry.py +570 -0
  25. agentframe/models/ollama.py +320 -0
  26. agentframe/models/strict_schema.py +211 -0
  27. agentframe/py.typed +0 -0
  28. agentframe/runtime/__init__.py +1 -0
  29. agentframe/runtime/generation.py +725 -0
  30. agentframe/runtime/limits.py +124 -0
  31. agentframe/runtime/options.py +50 -0
  32. agentframe/runtime/runtime.py +449 -0
  33. agentframe/runtime/tools.py +216 -0
  34. agentframe/runtime/usage.py +40 -0
  35. agentframe/security/__init__.py +1 -0
  36. agentframe/security/authentication.py +265 -0
  37. agentframe/security/authorization.py +66 -0
  38. agentframe/security/entra.py +260 -0
  39. agentframe/security/execution_policy.py +241 -0
  40. agentframe/security/principal.py +16 -0
  41. agentframe/testing.py +135 -0
  42. agentframe_py-0.1.0.dist-info/METADATA +570 -0
  43. agentframe_py-0.1.0.dist-info/RECORD +46 -0
  44. agentframe_py-0.1.0.dist-info/WHEEL +4 -0
  45. agentframe_py-0.1.0.dist-info/entry_points.txt +2 -0
  46. agentframe_py-0.1.0.dist-info/licenses/LICENSE +201 -0
agentframe/cli.py ADDED
@@ -0,0 +1,293 @@
1
+ """The ``agentframe`` command line: ``agentframe run`` serves one agent.
2
+
3
+ Usage::
4
+
5
+ agentframe run myapp.hosting:create_app --host 127.0.0.1 --port 8000
6
+ agentframe run myapp.agents:Echo --dev
7
+
8
+ The first form calls the application's own ``create_app()`` function, which
9
+ returns a fully configured ``AgentApp``; secrets belong in environment
10
+ variables read inside it, never in command-line flags. The second form is for
11
+ local development only: it serves an agent class anonymously on localhost.
12
+
13
+ On SIGTERM or Ctrl+C the app stops being ready and refuses new messages at
14
+ once, waits up to its ``HostConfig.shutdown_grace_seconds`` for running work,
15
+ then cancels the rest and exits. With ``--reload`` that shutdown starts only
16
+ after Uvicorn has waited for open requests, bounded by the same grace period.
17
+ """
18
+
19
+ import argparse
20
+ import contextlib
21
+ import importlib
22
+ import ipaddress
23
+ import json
24
+ import logging
25
+ import math
26
+ import os
27
+ import sys
28
+ from collections.abc import Sequence
29
+ from dataclasses import asdict, dataclass
30
+ from types import ModuleType
31
+
32
+ from agentframe.authoring.agent import Agent
33
+ from agentframe.errors import AgentFrameError
34
+ from agentframe.hosting.app import AgentApp
35
+ from agentframe.hosting.host import HostConfig
36
+ from agentframe.security.authentication import AllowAnonymous
37
+
38
+ logger = logging.getLogger("agentframe")
39
+
40
+ # Uvicorn's --reload runs the server in a fresh worker process that rebuilds
41
+ # the app through an import string, so the parent passes its settings here.
42
+ _RELOAD_SETTINGS_VARIABLE = "AGENTFRAME_RUN_SETTINGS"
43
+
44
+
45
+ class CommandError(Exception):
46
+ """A problem the command reports as a one-line message instead of a traceback."""
47
+
48
+
49
+ @dataclass(frozen=True)
50
+ class RunSettings:
51
+ """What ``agentframe run`` serves, and where.
52
+
53
+ Args:
54
+ target: ``module:function`` (an app factory) or, with ``dev``,
55
+ ``module:AgentClass``.
56
+ host: The address the server binds to.
57
+ port: The port the server binds to.
58
+ dev: Serve an agent class anonymously on localhost for development.
59
+ """
60
+
61
+ target: str
62
+ host: str
63
+ port: int
64
+ dev: bool
65
+
66
+
67
+ def main(argv: Sequence[str] | None = None) -> int:
68
+ """Run the ``agentframe`` command.
69
+
70
+ Args:
71
+ argv: Command-line arguments without the program name. Defaults to
72
+ ``sys.argv[1:]``.
73
+
74
+ Returns:
75
+ The process exit code: 0 after a clean shutdown, 1 on a reported error.
76
+ """
77
+ arguments = _parser().parse_args(argv)
78
+ settings = RunSettings(
79
+ target=arguments.target,
80
+ host=arguments.host,
81
+ port=arguments.port,
82
+ dev=arguments.dev,
83
+ )
84
+ _configure_logging()
85
+ try:
86
+ serve(settings, reload=arguments.reload)
87
+ except (CommandError, AgentFrameError) as error:
88
+ print(f"agentframe: error: {error}", file=sys.stderr)
89
+ return 1
90
+ return 0
91
+
92
+
93
+ def _parser() -> argparse.ArgumentParser:
94
+ parser = argparse.ArgumentParser(prog="agentframe")
95
+ commands = parser.add_subparsers(dest="command", required=True)
96
+ run = commands.add_parser(
97
+ "run",
98
+ help="serve one agent over A2A",
99
+ description="Serve one agent over A2A with uvicorn.",
100
+ )
101
+ run.add_argument(
102
+ "target",
103
+ help="module:function returning an AgentApp, or module:AgentClass with --dev",
104
+ )
105
+ run.add_argument("--host", default="127.0.0.1", help="bind address")
106
+ run.add_argument("--port", type=int, default=8000, help="bind port")
107
+ run.add_argument(
108
+ "--reload", action="store_true", help="restart when source files change"
109
+ )
110
+ run.add_argument(
111
+ "--dev",
112
+ action="store_true",
113
+ help="serve an agent class anonymously on localhost, for development only",
114
+ )
115
+ return parser
116
+
117
+
118
+ def serve(settings: RunSettings, *, reload: bool = False) -> None:
119
+ """Build the app described by ``settings`` and serve it until stopped.
120
+
121
+ The app is built before the server starts, so configuration errors are
122
+ reported up front, also when reloading. Shutdown is graceful, bounded by
123
+ the app's ``HostConfig.shutdown_grace_seconds``.
124
+
125
+ Args:
126
+ settings: What to serve and where.
127
+ reload: Restart the server when source files change.
128
+
129
+ Raises:
130
+ CommandError: The target cannot be loaded or is not usable, ``--dev``
131
+ was asked to bind a non-localhost address, Uvicorn is missing, or
132
+ the server failed to start.
133
+ AgentFrameError: The application's configuration is invalid.
134
+ """
135
+ uvicorn = _import_uvicorn()
136
+ # A console script's import path starts at the script's directory, not the
137
+ # working directory the application's modules live in.
138
+ if os.getcwd() not in sys.path:
139
+ sys.path.insert(0, os.getcwd())
140
+ app = build_app(settings)
141
+ if not reload:
142
+ _serve_draining(app, settings)
143
+ return
144
+ os.environ[_RELOAD_SETTINGS_VARIABLE] = json.dumps(asdict(settings))
145
+ # noinspection PyProtectedMember
146
+ grace_seconds = app._host.shutdown_grace_seconds
147
+ uvicorn.run(
148
+ f"{__name__}:{_app_for_reload.__name__}",
149
+ factory=True,
150
+ reload=True,
151
+ host=settings.host,
152
+ port=settings.port,
153
+ timeout_graceful_shutdown=math.ceil(grace_seconds),
154
+ )
155
+
156
+
157
+ def _serve_draining(app: AgentApp, settings: RunSettings) -> None:
158
+ """Serve ``app`` until a signal, starting its shutdown on the signal."""
159
+ # Imported here because it needs Uvicorn, an optional dependency.
160
+ from agentframe.hosting.draining_server import DrainingServer
161
+
162
+ server = DrainingServer(app, host=settings.host, port=settings.port)
163
+ # Uvicorn re-raises the signal it handled once it has shut down.
164
+ with contextlib.suppress(KeyboardInterrupt):
165
+ server.run()
166
+ if not server.started:
167
+ raise CommandError("The server did not start; see the log above.")
168
+
169
+
170
+ def build_app(settings: RunSettings) -> AgentApp:
171
+ """Build the ``AgentApp`` that ``settings`` describes, without serving it.
172
+
173
+ Args:
174
+ settings: What to serve and where.
175
+
176
+ Returns:
177
+ The application's own app, or a development app with ``dev``.
178
+
179
+ Raises:
180
+ CommandError: The target cannot be loaded or is not usable, or
181
+ ``--dev`` was asked to bind a non-localhost address.
182
+ AgentFrameError: The application's configuration is invalid.
183
+ """
184
+ target = _load(settings.target)
185
+ if settings.dev:
186
+ return _development_app(target, settings)
187
+ return _app_from_factory(target, settings.target)
188
+
189
+
190
+ def _app_for_reload() -> AgentApp:
191
+ """Rebuild the app in Uvicorn's reload worker from the parent's settings."""
192
+ _configure_logging()
193
+ settings = RunSettings(**json.loads(os.environ[_RELOAD_SETTINGS_VARIABLE]))
194
+ return build_app(settings)
195
+
196
+
197
+ def _configure_logging() -> None:
198
+ # Match Uvicorn's own log lines so AgentFrame's warnings read the same way.
199
+ logging.basicConfig(format="%(levelname)s: %(message)s")
200
+
201
+
202
+ def _load(target: str) -> object:
203
+ module_name, separator, attribute = target.partition(":")
204
+ if not separator or not module_name or not attribute:
205
+ raise CommandError(
206
+ f"'{target}' is not an import path; use module:name, for example "
207
+ "myapp.hosting:create_app."
208
+ )
209
+ try:
210
+ module = importlib.import_module(module_name)
211
+ except ModuleNotFoundError as error:
212
+ # Only the target module itself is "not found"; a missing dependency
213
+ # inside it is the application's bug and keeps its traceback.
214
+ if error.name != module_name and not module_name.startswith(f"{error.name}."):
215
+ raise
216
+ raise CommandError(f"Cannot import module '{module_name}'.") from error
217
+ try:
218
+ return getattr(module, attribute)
219
+ except AttributeError:
220
+ raise CommandError(
221
+ f"Module '{module_name}' has no attribute '{attribute}'."
222
+ ) from None
223
+
224
+
225
+ def _app_from_factory(factory: object, target: str) -> AgentApp:
226
+ if not callable(factory):
227
+ raise CommandError(f"'{target}' is not a function that returns an AgentApp.")
228
+ app = factory()
229
+ if isinstance(app, AgentApp):
230
+ return app
231
+ hint = (
232
+ " To serve an agent class for local development, add --dev."
233
+ if isinstance(factory, type) and issubclass(factory, Agent)
234
+ else ""
235
+ )
236
+ raise CommandError(
237
+ f"'{target}' returned {type(app).__name__}, not an AgentApp.{hint}"
238
+ )
239
+
240
+
241
+ def _development_app(agent_class: object, settings: RunSettings) -> AgentApp:
242
+ if not (isinstance(agent_class, type) and issubclass(agent_class, Agent)):
243
+ raise CommandError(f"--dev needs an Agent class; '{settings.target}' is not.")
244
+ if not _is_localhost(settings.host):
245
+ raise CommandError(
246
+ f"--dev serves anonymously, so it only binds to localhost, not "
247
+ f"'{settings.host}'. Use a create_app() factory with real "
248
+ "authentication for other hosts."
249
+ )
250
+ try:
251
+ agent = agent_class()
252
+ except TypeError as error:
253
+ raise CommandError(
254
+ f"--dev cannot construct {agent_class.__name__}() without arguments "
255
+ f"({error}). Use a create_app() factory instead."
256
+ ) from error
257
+ app = AgentApp(
258
+ agent=agent,
259
+ host=HostConfig(
260
+ public_url=f"http://{_url_host(settings.host)}:{settings.port}",
261
+ auth=AllowAnonymous(),
262
+ ),
263
+ )
264
+ logger.warning(
265
+ "Development mode: serving %s with AllowAnonymous, so any local process "
266
+ "can call it without credentials. Never use --dev in production.",
267
+ agent_class.__name__,
268
+ )
269
+ return app
270
+
271
+
272
+ def _is_localhost(host: str) -> bool:
273
+ if host == "localhost":
274
+ return True
275
+ try:
276
+ return ipaddress.ip_address(host).is_loopback
277
+ except ValueError:
278
+ return False
279
+
280
+
281
+ def _url_host(host: str) -> str:
282
+ return f"[{host}]" if ":" in host else host
283
+
284
+
285
+ def _import_uvicorn() -> ModuleType:
286
+ try:
287
+ import uvicorn
288
+ except ImportError:
289
+ raise CommandError(
290
+ "agentframe run needs the uvicorn ASGI server; install it with "
291
+ "pip install 'agentframe-py[server]'."
292
+ ) from None
293
+ return uvicorn
agentframe/errors.py ADDED
@@ -0,0 +1,194 @@
1
+ """Errors raised by AgentFrame."""
2
+
3
+ from collections.abc import Collection
4
+
5
+ from pydantic import ValidationError
6
+
7
+ from agentframe.runtime.usage import Usage
8
+
9
+
10
+ class AgentFrameError(Exception):
11
+ """Base class for all AgentFrame errors.
12
+
13
+ The message is always safe to show to callers: no secrets, raw input,
14
+ provider payloads, or stack traces.
15
+
16
+ Args:
17
+ message: Safe, human-readable description of the failure.
18
+ invocation_id: Identifier of the run that failed. ``None`` only for
19
+ definition errors raised while a class is being defined.
20
+ """
21
+
22
+ def __init__(self, message: str, *, invocation_id: str | None = None) -> None:
23
+ super().__init__(message)
24
+ self.message = message
25
+ self.invocation_id = invocation_id
26
+
27
+
28
+ class DefinitionError(AgentFrameError):
29
+ """An agent, skill, service registration or limit is defined incorrectly."""
30
+
31
+
32
+ class InputValidationError(AgentFrameError):
33
+ """The requested skill does not exist or its arguments are invalid."""
34
+
35
+
36
+ class OutputValidationError(AgentFrameError):
37
+ """A skill returned a value that does not match its return annotation."""
38
+
39
+
40
+ class AuthenticationError(AgentFrameError):
41
+ """A remote caller's credentials are missing or invalid."""
42
+
43
+
44
+ class PermissionDeniedError(AgentFrameError):
45
+ """The caller lacks a required permission or the policy denied the run."""
46
+
47
+
48
+ class PolicyUnavailableError(AgentFrameError):
49
+ """A required policy failed or did not answer in time, so the run failed closed."""
50
+
51
+
52
+ class ModelError(AgentFrameError):
53
+ """Base class for model failures: capability, refusal, truncation, provider.
54
+
55
+ Args:
56
+ message: Safe, human-readable description of the failure.
57
+ usage: Tokens the failed call consumed, when known. Model adapters set
58
+ it so the run's accounting counts what the call actually used.
59
+ invocation_id: Identifier of the run that failed, when known.
60
+ """
61
+
62
+ def __init__(
63
+ self,
64
+ message: str,
65
+ *,
66
+ usage: Usage | None = None,
67
+ invocation_id: str | None = None,
68
+ ) -> None:
69
+ super().__init__(message, invocation_id=invocation_id)
70
+ self.usage = usage
71
+
72
+
73
+ class UnsupportedCapabilityError(ModelError):
74
+ """The model lacks a requested capability; raised before anything is sent."""
75
+
76
+
77
+ class ModelRefusalError(ModelError):
78
+ """The model refused the request. Refusal is never returned as text."""
79
+
80
+
81
+ class IncompleteOutputError(ModelError):
82
+ """The model's output was cut short, for example at its output token limit.
83
+
84
+ A skill that prefers a partial answer to a failure can catch this error
85
+ and use ``partial_text``. The message never contains the partial text.
86
+
87
+ Args:
88
+ message: Safe, human-readable description of the failure.
89
+ partial_text: The text received before a text generation stopped at
90
+ its output token limit. ``None`` for structured output, empty
91
+ output and every other reason output was incomplete.
92
+ usage: Tokens the failed call consumed, when known.
93
+ invocation_id: Identifier of the run that failed, when known.
94
+ """
95
+
96
+ def __init__(
97
+ self,
98
+ message: str,
99
+ *,
100
+ partial_text: str | None = None,
101
+ usage: Usage | None = None,
102
+ invocation_id: str | None = None,
103
+ ) -> None:
104
+ super().__init__(message, usage=usage, invocation_id=invocation_id)
105
+ self.partial_text = partial_text
106
+
107
+
108
+ class ProviderError(ModelError):
109
+ """A model provider call failed, translated without provider details.
110
+
111
+ Args:
112
+ message: Safe, human-readable description of the failure.
113
+ transient: Whether retrying may succeed (rate limit, timeout, server
114
+ error). Only transient errors are retried.
115
+ retry_after: Seconds the provider asked callers to wait before
116
+ retrying, when it gave a hint.
117
+ usage: Tokens the failed call consumed, when the provider reported any.
118
+ invocation_id: Identifier of the run that failed, when known.
119
+ """
120
+
121
+ def __init__(
122
+ self,
123
+ message: str,
124
+ *,
125
+ transient: bool,
126
+ retry_after: float | None = None,
127
+ usage: Usage | None = None,
128
+ invocation_id: str | None = None,
129
+ ) -> None:
130
+ super().__init__(message, usage=usage, invocation_id=invocation_id)
131
+ self.transient = transient
132
+ self.retry_after = retry_after
133
+
134
+
135
+ class LimitExceededError(AgentFrameError):
136
+ """A run exceeded one of its execution limits; subclasses name which one."""
137
+
138
+
139
+ class TokenLimitExceededError(LimitExceededError):
140
+ """A model call's input or token reservation does not fit the run's limits.
141
+
142
+ Raised before the call is sent: when the input is larger than
143
+ ``max_input_tokens``, input plus output does not fit the model's context
144
+ window, or the call's reservation does not fit what is left of
145
+ ``max_total_tokens``.
146
+ """
147
+
148
+
149
+ class ModelCallLimitExceededError(LimitExceededError):
150
+ """A model call would exceed the run's ``max_model_calls``; it is not sent."""
151
+
152
+
153
+ class ToolCallLimitExceededError(LimitExceededError):
154
+ """A tool call would exceed the run's ``max_tool_calls``; it does not run."""
155
+
156
+
157
+ class TimeoutLimitExceededError(LimitExceededError):
158
+ """The run's ``timeout_seconds`` expired."""
159
+
160
+
161
+ class CancelledError(AgentFrameError):
162
+ """A run was cancelled before it finished.
163
+
164
+ Distinct from ``asyncio.CancelledError``: this reports a cancelled run to
165
+ callers and does not cancel anything itself.
166
+ """
167
+
168
+
169
+ def describe_validation_error(
170
+ error: ValidationError, field_names: Collection[str] | None = None
171
+ ) -> str:
172
+ """List field locations and problems without the submitted values.
173
+
174
+ Used for safe error messages: the invalid input itself, which may be
175
+ caller or model text, is never included.
176
+
177
+ Args:
178
+ error: The Pydantic validation error.
179
+ field_names: When given, location parts that are not one of these
180
+ names (such as dictionary keys chosen by a model) are shown as
181
+ ``<key>``, so the input cannot leak through its keys.
182
+ """
183
+ problems = []
184
+ for item in error.errors(include_input=False, include_url=False):
185
+ parts = [_location_part(part, field_names) for part in item["loc"]]
186
+ location = ".".join(parts) or "value"
187
+ problems.append(f"{location}: {item['msg']}")
188
+ return "; ".join(problems)
189
+
190
+
191
+ def _location_part(part: str | int, field_names: Collection[str] | None) -> str:
192
+ if field_names is None or isinstance(part, int) or part in field_names:
193
+ return str(part)
194
+ return "<key>"
@@ -0,0 +1 @@
1
+ """Hosting: the A2A AgentApp, host configuration, Agent Card and routing."""