agentflight-sdk 0.1.0__tar.gz → 0.2.0__tar.gz

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 (89) hide show
  1. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/CHANGELOG.md +22 -1
  2. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/PKG-INFO +121 -10
  3. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/README.md +117 -9
  4. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/pyproject.toml +3 -1
  5. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/src/agentflight/__init__.py +1 -1
  6. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/src/agentflight/server/app.py +66 -4
  7. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/src/agentflight/server/auth.py +27 -19
  8. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/src/agentflight/server/limits.py +35 -28
  9. agentflight_sdk-0.2.0/src/agentflight/server/otlp.py +389 -0
  10. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/src/agentflight/server/service.py +14 -4
  11. agentflight_sdk-0.2.0/tests/test_otlp.py +734 -0
  12. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/.gitignore +0 -0
  13. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/LICENSE +0 -0
  14. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/alembic.ini +0 -0
  15. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/examples/langgraph_agent.py +0 -0
  16. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/examples/openai_agent.py +0 -0
  17. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/examples/replay_agent.py +0 -0
  18. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/examples/toy_agent.py +0 -0
  19. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/scripts/bench_overhead.py +0 -0
  20. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/scripts/compose_smoke.py +0 -0
  21. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/scripts/smoke_installed.py +0 -0
  22. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/src/agentflight/_queue.py +0 -0
  23. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/src/agentflight/_spool.py +0 -0
  24. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/src/agentflight/attributes.py +0 -0
  25. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/src/agentflight/exporter.py +0 -0
  26. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/src/agentflight/integrations/__init__.py +0 -0
  27. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/src/agentflight/integrations/langgraph.py +0 -0
  28. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/src/agentflight/integrations/openai.py +0 -0
  29. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/src/agentflight/py.typed +0 -0
  30. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/src/agentflight/replayer.py +0 -0
  31. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/src/agentflight/sdk.py +0 -0
  32. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/src/agentflight/server/__init__.py +0 -0
  33. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/src/agentflight/server/cli.py +0 -0
  34. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/src/agentflight/server/db.py +0 -0
  35. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/src/agentflight/server/main.py +0 -0
  36. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/src/agentflight/server/migrations/env.py +0 -0
  37. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/src/agentflight/server/migrations/script.py.mako +0 -0
  38. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/src/agentflight/server/migrations/versions/0001_initial.py +0 -0
  39. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/src/agentflight/server/migrations/versions/0002_event_columns_run_totals.py +0 -0
  40. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/src/agentflight/server/migrations/versions/0003_unset_status_unknown.py +0 -0
  41. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/src/agentflight/server/migrations/versions/0004_run_dropped_spans.py +0 -0
  42. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/src/agentflight/server/models.py +0 -0
  43. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/src/agentflight/server/schemas.py +0 -0
  44. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/src/agentflight/server/settings.py +0 -0
  45. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/src/agentflight/server/viewer/__init__.py +0 -0
  46. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/src/agentflight/server/viewer/format.py +0 -0
  47. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/src/agentflight/server/viewer/routes.py +0 -0
  48. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/src/agentflight/server/viewer/session.py +0 -0
  49. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/src/agentflight/server/viewer/static/VENDORED.md +0 -0
  50. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/src/agentflight/server/viewer/static/htmx-2.0.11.min.js +0 -0
  51. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/src/agentflight/server/viewer/static/viewer.css +0 -0
  52. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/src/agentflight/server/viewer/templates/_event.html +0 -0
  53. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/src/agentflight/server/viewer/templates/_runs_table.html +0 -0
  54. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/src/agentflight/server/viewer/templates/_timeline_rows.html +0 -0
  55. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/src/agentflight/server/viewer/templates/base.html +0 -0
  56. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/src/agentflight/server/viewer/templates/event.html +0 -0
  57. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/src/agentflight/server/viewer/templates/login.html +0 -0
  58. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/src/agentflight/server/viewer/templates/not_found.html +0 -0
  59. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/src/agentflight/server/viewer/templates/run.html +0 -0
  60. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/src/agentflight/server/viewer/templates/runs.html +0 -0
  61. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/tests/__init__.py +0 -0
  62. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/tests/conftest.py +0 -0
  63. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/tests/test_api.py +0 -0
  64. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/tests/test_auth.py +0 -0
  65. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/tests/test_bench_script.py +0 -0
  66. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/tests/test_dropped_spans_server.py +0 -0
  67. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/tests/test_error_redaction.py +0 -0
  68. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/tests/test_examples.py +0 -0
  69. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/tests/test_failure_isolation.py +0 -0
  70. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/tests/test_failures.py +0 -0
  71. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/tests/test_fork.py +0 -0
  72. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/tests/test_langgraph_integration.py +0 -0
  73. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/tests/test_migrations.py +0 -0
  74. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/tests/test_openai_integration.py +0 -0
  75. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/tests/test_payloads.py +0 -0
  76. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/tests/test_queries.py +0 -0
  77. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/tests/test_queue_and_drops.py +0 -0
  78. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/tests/test_replay.py +0 -0
  79. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/tests/test_retention.py +0 -0
  80. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/tests/test_run_span_lane.py +0 -0
  81. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/tests/test_scoped_keys.py +0 -0
  82. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/tests/test_sdk.py +0 -0
  83. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/tests/test_span_tree.py +0 -0
  84. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/tests/test_spool.py +0 -0
  85. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/tests/test_status_and_limits.py +0 -0
  86. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/tests/test_totals.py +0 -0
  87. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/tests/test_viewer_browser.py +0 -0
  88. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/tests/test_viewer_login.py +0 -0
  89. {agentflight_sdk-0.1.0 → agentflight_sdk-0.2.0}/tests/test_viewer_pages.py +0 -0
@@ -4,7 +4,28 @@ All notable changes to AgentFlight. The HTTP API is versioned by its `/v1` prefi
4
4
  "HTTP API versioning" under 0.1.0); every change that can break a client is listed under
5
5
  **Behaviour changes**.
6
6
 
7
- ## 0.1.0 (not yet released; dated when it is tagged)
7
+ ## 0.2.0 (2026-11-28)
8
+
9
+ ### Added
10
+
11
+ - **OTLP ingest:** `POST /v1/traces` accepts OTLP/HTTP trace exports
12
+ (`application/x-protobuf` or `application/json`, optionally `Content-Encoding: gzip`), so
13
+ any OpenTelemetry-instrumented agent or Collector can record runs without the SDK. Same
14
+ `ingest` key auth and ingest limits as `POST /v1/spans`; the 16 MiB body cap applies to the
15
+ decompressed body too. Responses follow the OTLP spec: `partial_success` for spans that
16
+ can't be stored, `google.rpc.Status` errors with `400`/`401`/`403`/`413`/`415`, and a
17
+ retryable `503` only when the database is unavailable. Spans with a name or span event
18
+ name over 255 characters are rejected that way, as on `/v1/spans`.
19
+ - OTLP spans map onto runs: the trace is the run and its parentless span closes it;
20
+ `gen_ai.*` operations, models, tokens and tool names become `llm` and `tool` events that
21
+ count in run totals and filters; `service.*` and `deployment.environment` become run
22
+ metadata; every other attribute (resource attributes as `otel.resource.*`) is kept.
23
+ Spans with `agentflight.*` attributes are read as on `/v1/spans`. Re-sent batches are
24
+ idempotent. See "OTLP ingest" in the README for limitations (no replay or cost for
25
+ OTLP-only runs).
26
+ - The server depends on `opentelemetry-proto`.
27
+
28
+ ## 0.1.0 (2026-11-27)
8
29
 
9
30
  The first release on PyPI, as **`agentflight-sdk`** (the name `agentflight` is too close
10
31
  to an existing PyPI project): `pip install agentflight-sdk` for the SDK,
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: agentflight-sdk
3
- Version: 0.1.0
3
+ Version: 0.2.0
4
4
  Summary: Black box recorder for AI agents: record, replay and debug agent runs
5
5
  Project-URL: Homepage, https://github.com/shupandee/agentflight
6
6
  Project-URL: Repository, https://github.com/shupandee/agentflight
@@ -33,6 +33,8 @@ Requires-Dist: jinja2>=3.1; extra == 'dev'
33
33
  Requires-Dist: langgraph>=1.0; extra == 'dev'
34
34
  Requires-Dist: mypy>=1.10; extra == 'dev'
35
35
  Requires-Dist: openai>=1.0; extra == 'dev'
36
+ Requires-Dist: opentelemetry-exporter-otlp-proto-http>=1.24; extra == 'dev'
37
+ Requires-Dist: opentelemetry-proto>=1.24; extra == 'dev'
36
38
  Requires-Dist: psycopg[binary]>=3.1; extra == 'dev'
37
39
  Requires-Dist: pytest>=8.0; extra == 'dev'
38
40
  Requires-Dist: ruff>=0.5; extra == 'dev'
@@ -46,6 +48,7 @@ Provides-Extra: server
46
48
  Requires-Dist: alembic>=1.13; extra == 'server'
47
49
  Requires-Dist: fastapi>=0.110; extra == 'server'
48
50
  Requires-Dist: jinja2>=3.1; extra == 'server'
51
+ Requires-Dist: opentelemetry-proto>=1.24; extra == 'server'
49
52
  Requires-Dist: psycopg[binary]>=3.1; extra == 'server'
50
53
  Requires-Dist: sqlalchemy>=2.0; extra == 'server'
51
54
  Requires-Dist: uvicorn>=0.29; extra == 'server'
@@ -88,6 +91,7 @@ flowchart LR
88
91
  OTel --> EXP[AgentFlightExporter<br/>batched HTTP JSON]
89
92
  end
90
93
  EXP -->|POST /v1/spans| API[FastAPI ingest server]
94
+ O[Any OpenTelemetry agent<br/>or Collector] -->|POST /v1/traces<br/>OTLP/HTTP| API
91
95
  API --> DB[(PostgreSQL<br/>runs + events)]
92
96
  C[curl / scripts] -->|GET /v1/runs, /v1/runs/:id| API
93
97
  V[Browser] -->|/ui viewer| API
@@ -115,14 +119,14 @@ export AGENTFLIGHT_API_KEY=$(openssl rand -hex 32)
115
119
  # 1. Server + Postgres + retention job (applies Alembic migrations on start)
116
120
  docker compose up --build
117
121
 
118
- # or without Docker, using SQLite (from a checkout; once 0.1.0 is on PyPI,
119
- # `pip install "agentflight-sdk[server]"` works too):
122
+ # or without Docker, using SQLite (from a checkout; elsewhere,
123
+ # `pip install "agentflight-sdk[server]"`):
120
124
  pip install -e ".[server]"
121
125
  agentflight-server migrate # uses AGENTFLIGHT_DATABASE_URL, default sqlite:///./agentflight.db
122
126
  agentflight-server serve # http://127.0.0.1:8000
123
127
 
124
128
  # 2. Record the toy agent (the SDK reads AGENTFLIGHT_API_KEY)
125
- pip install -e . # or, once 0.1.0 is on PyPI: pip install agentflight-sdk
129
+ pip install -e . # elsewhere: pip install agentflight-sdk
126
130
  # (the package is agentflight-sdk; you import agentflight)
127
131
  python examples/toy_agent.py
128
132
 
@@ -272,6 +276,106 @@ python examples/openai_agent.py # uses the real API if OPENAI_API_KEY is se
272
276
  python examples/langgraph_agent.py
273
277
  ```
274
278
 
279
+ ## OTLP ingest (any OpenTelemetry agent)
280
+
281
+ Agents that are already instrumented with OpenTelemetry (OpenLLMetry, OpenInference,
282
+ framework auto-instrumentation or your own spans) can send traces to AgentFlight over
283
+ standard **OTLP/HTTP**, without the AgentFlight SDK: `POST /v1/traces` accepts
284
+ `application/x-protobuf` and `application/json`, optionally with
285
+ `Content-Encoding: gzip`. OTLP over gRPC is not supported.
286
+
287
+ Use an `ingest` key, sent as `Authorization: Bearer <key>` (or `X-AgentFlight-Key`).
288
+ With the stock environment variables (the exporter appends `/v1/traces` to
289
+ `OTEL_EXPORTER_OTLP_ENDPOINT`; the space in the header value is written `%20`):
290
+
291
+ ```bash
292
+ export OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
293
+ export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:8000
294
+ export OTEL_EXPORTER_OTLP_HEADERS="authorization=Bearer%20${AGENTFLIGHT_INGEST_KEY}"
295
+ export OTEL_EXPORTER_OTLP_COMPRESSION=gzip
296
+ ```
297
+
298
+ Or in Python (`pip install opentelemetry-exporter-otlp-proto-http`):
299
+
300
+ ```python
301
+ from opentelemetry.exporter.otlp.proto.http import Compression
302
+ from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
303
+ from opentelemetry.sdk.trace import TracerProvider
304
+ from opentelemetry.sdk.trace.export import BatchSpanProcessor
305
+
306
+ exporter = OTLPSpanExporter(
307
+ endpoint="http://localhost:8000/v1/traces",
308
+ headers={"Authorization": f"Bearer {ingest_key}"},
309
+ compression=Compression.Gzip,
310
+ )
311
+ provider = TracerProvider()
312
+ provider.add_span_processor(BatchSpanProcessor(exporter))
313
+ ```
314
+
315
+ Or from an OpenTelemetry Collector, next to whatever else it exports to:
316
+
317
+ ```yaml
318
+ exporters:
319
+ otlphttp/agentflight:
320
+ endpoint: http://agentflight:8000 # the exporter appends /v1/traces
321
+ headers:
322
+ authorization: "Bearer ${env:AGENTFLIGHT_INGEST_KEY}"
323
+ compression: gzip
324
+ service:
325
+ pipelines:
326
+ traces:
327
+ receivers: [otlp]
328
+ exporters: [otlphttp/agentflight]
329
+ ```
330
+
331
+ **How spans become runs.** One trace is one run (the run id is the trace id), as with
332
+ the SDK:
333
+
334
+ | OTLP | AgentFlight |
335
+ | --- | --- |
336
+ | Span without a parent | Closes the run: its name is the run name, its status the run status (`unset` counts as `ok`, OpenTelemetry's convention). Until it arrives the run is `running`. |
337
+ | `gen_ai.operation.name` `chat`, `text_completion`, `generate_content` or `embeddings` (or a `gen_ai.request.model` / `gen_ai.system` / `gen_ai.provider.name` without an operation) | An `llm` event: model from `gen_ai.response.model`, else `gen_ai.request.model`; tokens from `gen_ai.usage.input_tokens` / `output_tokens` (or the older `prompt_tokens` / `completion_tokens`). These count in the run's call and token totals and the `model` filter. |
338
+ | `gen_ai.operation.name` `execute_tool` (or a `gen_ai.tool.name` without an operation) | A `tool` event named by `gen_ai.tool.name` (the `tool` filter) |
339
+ | Any other span | A `span` event |
340
+ | Resource `service.name`, `service.namespace`, `service.version`, `deployment.environment(.name)` | Run metadata of the root span (the `meta=` filter) |
341
+ | Every other attribute | Kept on the event as is. Resource attributes are copied to every span as `otel.resource.*`, plus `otel.scope.name` / `otel.scope.version`, `otel.span_kind` and `otel.links`. Span events are kept. |
342
+
343
+ Spans that carry `agentflight.*` attributes (the SDK's own spans, sent through an OTLP
344
+ exporter or a Collector) are read exactly as on `POST /v1/spans`; `gen_ai.*` attributes are
345
+ not applied to them. Re-sending a batch is idempotent (spans are upserted by span id and
346
+ totals recomputed in SQL), so exporter and Collector retries can't double-count.
347
+
348
+ **Responses** follow the OTLP/HTTP spec, encoded like the request (protobuf or JSON):
349
+
350
+ | Status | When | Retried by OTLP exporters |
351
+ | --- | --- | --- |
352
+ | `200` | Stored. Spans that can't be stored (an invalid trace or span id, a name over 255 characters, an attribute over a [limit](#ingest-limits)) are left out and counted in `partial_success` (`rejected_spans`, `error_message` naming the first few); the rest of the batch is stored. | no |
353
+ | `400` | The body isn't valid OTLP protobuf/JSON, or isn't valid gzip | no |
354
+ | `401` / `403` | Missing or wrong key / a key without `ingest` | no |
355
+ | `413` | Body over `AGENTFLIGHT_MAX_BODY_BYTES`, compressed **or decompressed** (decompression stops at the cap, so a gzip bomb can't use more memory than that), or more than `AGENTFLIGHT_MAX_SPANS_PER_BATCH` spans | no |
356
+ | `415` | Another `Content-Type`, or a `Content-Encoding` other than `gzip` / `identity` | no |
357
+ | `503` | The database is unavailable (with `Retry-After`) | yes |
358
+
359
+ Errors carry a `google.rpc.Status` body. The server never answers `429` (it has no rate
360
+ limit). Unlike the SDK's exporter, stock OTLP exporters don't split a batch on `413`; the
361
+ default batch processor sends at most 512 spans per request, so keep payloads well under
362
+ 16 MiB per batch or raise the cap.
363
+
364
+ **Limitations**
365
+
366
+ - **No replay for OTLP-only runs.** Replay and fork need the recorded outputs the SDK
367
+ stores (`agentflight.llm.response`, `agentflight.tool.result`...). `gen_ai` prompts,
368
+ completions and tool arguments stay under their own attribute names, and the viewer shows
369
+ them, but `Recording` doesn't read them. SDK spans sent over OTLP stay replayable.
370
+ - **No cost.** The `gen_ai` conventions have no cost attribute, so `cost_usd` is only set
371
+ from `agentflight.llm.cost_usd`.
372
+ - **Distributed traces:** a trace whose root span lives in a service that doesn't export
373
+ to AgentFlight never closes, and shows as `abandoned` after the stale threshold. A trace
374
+ with several parentless spans takes its name and status from the last one received.
375
+ - A span whose name, or one of whose span event names, is over 255 characters is
376
+ rejected (counted in `partial_success`), as `POST /v1/spans` rejects it with `422`.
377
+ - The pre-1.0 `instrumentationLibrarySpans` field is ignored; send `scopeSpans`.
378
+
275
379
  ## Replay and fork
276
380
 
277
381
  Re-run an agent against a recorded run. Recorded model and tool outputs are served instead of
@@ -695,12 +799,14 @@ works too) and then keeps a **signed session** in a cookie:
695
799
 
696
800
  Every ingest request is bounded. The defaults are deliberately generous, so they shouldn't
697
801
  reject anything the SDK sends with its default settings; they will be tuned once real
698
- batch sizes are measured. A request over a limit gets `413` and nothing from it is stored.
802
+ batch sizes are measured. A request over a limit gets `413` and nothing from it is stored. On `POST /v1/traces` the body
803
+ cap also applies to the decompressed body, and a span over a per-span limit is rejected on
804
+ its own (see [OTLP ingest](#otlp-ingest-any-opentelemetry-agent)).
699
805
 
700
806
  | Setting | Default | Limit |
701
807
  | --- | --- | --- |
702
808
  | `AGENTFLIGHT_MAX_BODY_BYTES` | `16777216` (16 MiB) | Request body size, checked from `Content-Length` and while reading chunked bodies |
703
- | `AGENTFLIGHT_MAX_SPANS_PER_BATCH` | `2048` | Spans in one `POST /v1/spans` (the SDK's batch processor sends at most 512 by default) |
809
+ | `AGENTFLIGHT_MAX_SPANS_PER_BATCH` | `2048` | Spans in one `POST /v1/spans` or `POST /v1/traces` (the SDK's batch processor sends at most 512 by default) |
704
810
  | `AGENTFLIGHT_MAX_ATTRIBUTE_CHARS` | `262144` | Characters in one attribute value, span event attribute value or status message (the SDK caps payloads at 32,000 by default) |
705
811
  | `AGENTFLIGHT_MAX_ATTRIBUTES_PER_SPAN` | `1024` | Attributes on one span or span event (OpenTelemetry's SDK keeps 128 by default) |
706
812
  | `AGENTFLIGHT_MAX_EVENTS_PER_SPAN` | `1024` | Events on one span (OpenTelemetry's SDK keeps 128 by default) |
@@ -760,6 +866,7 @@ should ignore fields they don't know); a breaking change would mean `/v2`, serve
760
866
  | Method | Path | Permission | Description |
761
867
  | --- | --- | --- | --- |
762
868
  | `POST` | `/v1/spans` | ingest | Ingest a batch of spans (`{"spans": [...]}`) |
869
+ | `POST` | `/v1/traces` | ingest | [OTLP/HTTP](#otlp-ingest-any-opentelemetry-agent) trace export (protobuf or JSON, optionally gzip) |
763
870
  | `GET` | `/v1/runs` | read | List runs, newest first, with token/cost/error totals. Paging: `limit` (1-500, default 50), `offset`. Filters (all must match): `status` (`running`, `ok`, `error`, `unknown`, `abandoned`), `name` (case-insensitive substring), `since_ns`/`until_ns` (run start, Unix ns), `has_errors`, `model`, `tool` (exact), `meta=key:value` (string metadata values, exact; up to 5) |
764
871
  | `GET` | `/v1/runs/{run_id}` | read | One run with its events ordered by start time. Every event with payloads by default (what replay uses). `events_limit` (1-1000) and `events_offset` page the events; `payloads=false` leaves recorded payloads (messages, outputs, args, stack traces) out and lists them in each event's `omitted` |
765
872
  | `GET` | `/v1/runs/{run_id}/events/{span_id}` | read | One event with all of its payloads |
@@ -824,12 +931,16 @@ docker compose down --volumes
824
931
  and shown as incomplete recordings in the viewer and replay; a configurable queue size;
825
932
  split retries stop at the first non-413 failure; bounded `flush()` and `shutdown()`;
826
933
  benchmark repeats and the server's ingest rate.
827
- - **0.1.0** (this branch): run spans on their own lane, so runs with drops still close;
934
+ - **0.1.0** (released): run spans on their own lane, so runs with drops still close;
828
935
  release packaging (migrations in the package, `agentflight-server migrate`, a Trusted
829
936
  Publishing release workflow) and the `/v1` stability policy; an opt-in on-disk spool
830
- for failed exports. Next: OTLP ingest, `parent_run_id`, server-side redaction, run
831
- diff. Deferred: a demo, overhead on real (non-synthetic) agent runs, and a rate limit
832
- on failed keys.
937
+ for failed exports.
938
+ - **0.2.0** (released): OTLP ingest: `POST /v1/traces` takes OTLP/HTTP (protobuf or JSON,
939
+ gzip) from any OpenTelemetry-instrumented agent or Collector, with `gen_ai.*` mapped to
940
+ models, tokens and tools. Deferred: OTLP over gRPC, replay from `gen_ai` content,
941
+ cost from a price table.
942
+ - **Next:** `parent_run_id`, server-side redaction, run diff. Deferred: a demo, overhead
943
+ on real (non-synthetic) agent runs, and a rate limit on failed keys.
833
944
 
834
945
  ## License
835
946
 
@@ -35,6 +35,7 @@ flowchart LR
35
35
  OTel --> EXP[AgentFlightExporter<br/>batched HTTP JSON]
36
36
  end
37
37
  EXP -->|POST /v1/spans| API[FastAPI ingest server]
38
+ O[Any OpenTelemetry agent<br/>or Collector] -->|POST /v1/traces<br/>OTLP/HTTP| API
38
39
  API --> DB[(PostgreSQL<br/>runs + events)]
39
40
  C[curl / scripts] -->|GET /v1/runs, /v1/runs/:id| API
40
41
  V[Browser] -->|/ui viewer| API
@@ -62,14 +63,14 @@ export AGENTFLIGHT_API_KEY=$(openssl rand -hex 32)
62
63
  # 1. Server + Postgres + retention job (applies Alembic migrations on start)
63
64
  docker compose up --build
64
65
 
65
- # or without Docker, using SQLite (from a checkout; once 0.1.0 is on PyPI,
66
- # `pip install "agentflight-sdk[server]"` works too):
66
+ # or without Docker, using SQLite (from a checkout; elsewhere,
67
+ # `pip install "agentflight-sdk[server]"`):
67
68
  pip install -e ".[server]"
68
69
  agentflight-server migrate # uses AGENTFLIGHT_DATABASE_URL, default sqlite:///./agentflight.db
69
70
  agentflight-server serve # http://127.0.0.1:8000
70
71
 
71
72
  # 2. Record the toy agent (the SDK reads AGENTFLIGHT_API_KEY)
72
- pip install -e . # or, once 0.1.0 is on PyPI: pip install agentflight-sdk
73
+ pip install -e . # elsewhere: pip install agentflight-sdk
73
74
  # (the package is agentflight-sdk; you import agentflight)
74
75
  python examples/toy_agent.py
75
76
 
@@ -219,6 +220,106 @@ python examples/openai_agent.py # uses the real API if OPENAI_API_KEY is se
219
220
  python examples/langgraph_agent.py
220
221
  ```
221
222
 
223
+ ## OTLP ingest (any OpenTelemetry agent)
224
+
225
+ Agents that are already instrumented with OpenTelemetry (OpenLLMetry, OpenInference,
226
+ framework auto-instrumentation or your own spans) can send traces to AgentFlight over
227
+ standard **OTLP/HTTP**, without the AgentFlight SDK: `POST /v1/traces` accepts
228
+ `application/x-protobuf` and `application/json`, optionally with
229
+ `Content-Encoding: gzip`. OTLP over gRPC is not supported.
230
+
231
+ Use an `ingest` key, sent as `Authorization: Bearer <key>` (or `X-AgentFlight-Key`).
232
+ With the stock environment variables (the exporter appends `/v1/traces` to
233
+ `OTEL_EXPORTER_OTLP_ENDPOINT`; the space in the header value is written `%20`):
234
+
235
+ ```bash
236
+ export OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
237
+ export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:8000
238
+ export OTEL_EXPORTER_OTLP_HEADERS="authorization=Bearer%20${AGENTFLIGHT_INGEST_KEY}"
239
+ export OTEL_EXPORTER_OTLP_COMPRESSION=gzip
240
+ ```
241
+
242
+ Or in Python (`pip install opentelemetry-exporter-otlp-proto-http`):
243
+
244
+ ```python
245
+ from opentelemetry.exporter.otlp.proto.http import Compression
246
+ from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
247
+ from opentelemetry.sdk.trace import TracerProvider
248
+ from opentelemetry.sdk.trace.export import BatchSpanProcessor
249
+
250
+ exporter = OTLPSpanExporter(
251
+ endpoint="http://localhost:8000/v1/traces",
252
+ headers={"Authorization": f"Bearer {ingest_key}"},
253
+ compression=Compression.Gzip,
254
+ )
255
+ provider = TracerProvider()
256
+ provider.add_span_processor(BatchSpanProcessor(exporter))
257
+ ```
258
+
259
+ Or from an OpenTelemetry Collector, next to whatever else it exports to:
260
+
261
+ ```yaml
262
+ exporters:
263
+ otlphttp/agentflight:
264
+ endpoint: http://agentflight:8000 # the exporter appends /v1/traces
265
+ headers:
266
+ authorization: "Bearer ${env:AGENTFLIGHT_INGEST_KEY}"
267
+ compression: gzip
268
+ service:
269
+ pipelines:
270
+ traces:
271
+ receivers: [otlp]
272
+ exporters: [otlphttp/agentflight]
273
+ ```
274
+
275
+ **How spans become runs.** One trace is one run (the run id is the trace id), as with
276
+ the SDK:
277
+
278
+ | OTLP | AgentFlight |
279
+ | --- | --- |
280
+ | Span without a parent | Closes the run: its name is the run name, its status the run status (`unset` counts as `ok`, OpenTelemetry's convention). Until it arrives the run is `running`. |
281
+ | `gen_ai.operation.name` `chat`, `text_completion`, `generate_content` or `embeddings` (or a `gen_ai.request.model` / `gen_ai.system` / `gen_ai.provider.name` without an operation) | An `llm` event: model from `gen_ai.response.model`, else `gen_ai.request.model`; tokens from `gen_ai.usage.input_tokens` / `output_tokens` (or the older `prompt_tokens` / `completion_tokens`). These count in the run's call and token totals and the `model` filter. |
282
+ | `gen_ai.operation.name` `execute_tool` (or a `gen_ai.tool.name` without an operation) | A `tool` event named by `gen_ai.tool.name` (the `tool` filter) |
283
+ | Any other span | A `span` event |
284
+ | Resource `service.name`, `service.namespace`, `service.version`, `deployment.environment(.name)` | Run metadata of the root span (the `meta=` filter) |
285
+ | Every other attribute | Kept on the event as is. Resource attributes are copied to every span as `otel.resource.*`, plus `otel.scope.name` / `otel.scope.version`, `otel.span_kind` and `otel.links`. Span events are kept. |
286
+
287
+ Spans that carry `agentflight.*` attributes (the SDK's own spans, sent through an OTLP
288
+ exporter or a Collector) are read exactly as on `POST /v1/spans`; `gen_ai.*` attributes are
289
+ not applied to them. Re-sending a batch is idempotent (spans are upserted by span id and
290
+ totals recomputed in SQL), so exporter and Collector retries can't double-count.
291
+
292
+ **Responses** follow the OTLP/HTTP spec, encoded like the request (protobuf or JSON):
293
+
294
+ | Status | When | Retried by OTLP exporters |
295
+ | --- | --- | --- |
296
+ | `200` | Stored. Spans that can't be stored (an invalid trace or span id, a name over 255 characters, an attribute over a [limit](#ingest-limits)) are left out and counted in `partial_success` (`rejected_spans`, `error_message` naming the first few); the rest of the batch is stored. | no |
297
+ | `400` | The body isn't valid OTLP protobuf/JSON, or isn't valid gzip | no |
298
+ | `401` / `403` | Missing or wrong key / a key without `ingest` | no |
299
+ | `413` | Body over `AGENTFLIGHT_MAX_BODY_BYTES`, compressed **or decompressed** (decompression stops at the cap, so a gzip bomb can't use more memory than that), or more than `AGENTFLIGHT_MAX_SPANS_PER_BATCH` spans | no |
300
+ | `415` | Another `Content-Type`, or a `Content-Encoding` other than `gzip` / `identity` | no |
301
+ | `503` | The database is unavailable (with `Retry-After`) | yes |
302
+
303
+ Errors carry a `google.rpc.Status` body. The server never answers `429` (it has no rate
304
+ limit). Unlike the SDK's exporter, stock OTLP exporters don't split a batch on `413`; the
305
+ default batch processor sends at most 512 spans per request, so keep payloads well under
306
+ 16 MiB per batch or raise the cap.
307
+
308
+ **Limitations**
309
+
310
+ - **No replay for OTLP-only runs.** Replay and fork need the recorded outputs the SDK
311
+ stores (`agentflight.llm.response`, `agentflight.tool.result`...). `gen_ai` prompts,
312
+ completions and tool arguments stay under their own attribute names, and the viewer shows
313
+ them, but `Recording` doesn't read them. SDK spans sent over OTLP stay replayable.
314
+ - **No cost.** The `gen_ai` conventions have no cost attribute, so `cost_usd` is only set
315
+ from `agentflight.llm.cost_usd`.
316
+ - **Distributed traces:** a trace whose root span lives in a service that doesn't export
317
+ to AgentFlight never closes, and shows as `abandoned` after the stale threshold. A trace
318
+ with several parentless spans takes its name and status from the last one received.
319
+ - A span whose name, or one of whose span event names, is over 255 characters is
320
+ rejected (counted in `partial_success`), as `POST /v1/spans` rejects it with `422`.
321
+ - The pre-1.0 `instrumentationLibrarySpans` field is ignored; send `scopeSpans`.
322
+
222
323
  ## Replay and fork
223
324
 
224
325
  Re-run an agent against a recorded run. Recorded model and tool outputs are served instead of
@@ -642,12 +743,14 @@ works too) and then keeps a **signed session** in a cookie:
642
743
 
643
744
  Every ingest request is bounded. The defaults are deliberately generous, so they shouldn't
644
745
  reject anything the SDK sends with its default settings; they will be tuned once real
645
- batch sizes are measured. A request over a limit gets `413` and nothing from it is stored.
746
+ batch sizes are measured. A request over a limit gets `413` and nothing from it is stored. On `POST /v1/traces` the body
747
+ cap also applies to the decompressed body, and a span over a per-span limit is rejected on
748
+ its own (see [OTLP ingest](#otlp-ingest-any-opentelemetry-agent)).
646
749
 
647
750
  | Setting | Default | Limit |
648
751
  | --- | --- | --- |
649
752
  | `AGENTFLIGHT_MAX_BODY_BYTES` | `16777216` (16 MiB) | Request body size, checked from `Content-Length` and while reading chunked bodies |
650
- | `AGENTFLIGHT_MAX_SPANS_PER_BATCH` | `2048` | Spans in one `POST /v1/spans` (the SDK's batch processor sends at most 512 by default) |
753
+ | `AGENTFLIGHT_MAX_SPANS_PER_BATCH` | `2048` | Spans in one `POST /v1/spans` or `POST /v1/traces` (the SDK's batch processor sends at most 512 by default) |
651
754
  | `AGENTFLIGHT_MAX_ATTRIBUTE_CHARS` | `262144` | Characters in one attribute value, span event attribute value or status message (the SDK caps payloads at 32,000 by default) |
652
755
  | `AGENTFLIGHT_MAX_ATTRIBUTES_PER_SPAN` | `1024` | Attributes on one span or span event (OpenTelemetry's SDK keeps 128 by default) |
653
756
  | `AGENTFLIGHT_MAX_EVENTS_PER_SPAN` | `1024` | Events on one span (OpenTelemetry's SDK keeps 128 by default) |
@@ -707,6 +810,7 @@ should ignore fields they don't know); a breaking change would mean `/v2`, serve
707
810
  | Method | Path | Permission | Description |
708
811
  | --- | --- | --- | --- |
709
812
  | `POST` | `/v1/spans` | ingest | Ingest a batch of spans (`{"spans": [...]}`) |
813
+ | `POST` | `/v1/traces` | ingest | [OTLP/HTTP](#otlp-ingest-any-opentelemetry-agent) trace export (protobuf or JSON, optionally gzip) |
710
814
  | `GET` | `/v1/runs` | read | List runs, newest first, with token/cost/error totals. Paging: `limit` (1-500, default 50), `offset`. Filters (all must match): `status` (`running`, `ok`, `error`, `unknown`, `abandoned`), `name` (case-insensitive substring), `since_ns`/`until_ns` (run start, Unix ns), `has_errors`, `model`, `tool` (exact), `meta=key:value` (string metadata values, exact; up to 5) |
711
815
  | `GET` | `/v1/runs/{run_id}` | read | One run with its events ordered by start time. Every event with payloads by default (what replay uses). `events_limit` (1-1000) and `events_offset` page the events; `payloads=false` leaves recorded payloads (messages, outputs, args, stack traces) out and lists them in each event's `omitted` |
712
816
  | `GET` | `/v1/runs/{run_id}/events/{span_id}` | read | One event with all of its payloads |
@@ -771,12 +875,16 @@ docker compose down --volumes
771
875
  and shown as incomplete recordings in the viewer and replay; a configurable queue size;
772
876
  split retries stop at the first non-413 failure; bounded `flush()` and `shutdown()`;
773
877
  benchmark repeats and the server's ingest rate.
774
- - **0.1.0** (this branch): run spans on their own lane, so runs with drops still close;
878
+ - **0.1.0** (released): run spans on their own lane, so runs with drops still close;
775
879
  release packaging (migrations in the package, `agentflight-server migrate`, a Trusted
776
880
  Publishing release workflow) and the `/v1` stability policy; an opt-in on-disk spool
777
- for failed exports. Next: OTLP ingest, `parent_run_id`, server-side redaction, run
778
- diff. Deferred: a demo, overhead on real (non-synthetic) agent runs, and a rate limit
779
- on failed keys.
881
+ for failed exports.
882
+ - **0.2.0** (released): OTLP ingest: `POST /v1/traces` takes OTLP/HTTP (protobuf or JSON,
883
+ gzip) from any OpenTelemetry-instrumented agent or Collector, with `gen_ai.*` mapped to
884
+ models, tokens and tools. Deferred: OTLP over gRPC, replay from `gen_ai` content,
885
+ cost from a price table.
886
+ - **Next:** `parent_run_id`, server-side redaction, run diff. Deferred: a demo, overhead
887
+ on real (non-synthetic) agent runs, and a rate limit on failed keys.
780
888
 
781
889
  ## License
782
890
 
@@ -49,12 +49,14 @@ server = [
49
49
  "alembic>=1.13",
50
50
  "psycopg[binary]>=3.1",
51
51
  "jinja2>=3.1",
52
+ "opentelemetry-proto>=1.24", # OTLP/HTTP ingest (/v1/traces)
52
53
  ]
53
54
  # Integrations: only needed for the frameworks you use.
54
55
  openai = ["openai>=1.0"]
55
56
  langgraph = ["langgraph>=1.0"]
56
57
  dev = [
57
58
  "agentflight-sdk[server,openai,langgraph]",
59
+ "opentelemetry-exporter-otlp-proto-http>=1.24", # OTLP ingest end-to-end test
58
60
  "pytest>=8.0",
59
61
  "ruff>=0.5",
60
62
  "mypy>=1.10",
@@ -97,5 +99,5 @@ exclude = ["src/agentflight/server/migrations/"]
97
99
  plugins = []
98
100
 
99
101
  [[tool.mypy.overrides]]
100
- module = ["opentelemetry.*"]
102
+ module = ["opentelemetry.*", "google.protobuf.*"]
101
103
  ignore_missing_imports = true
@@ -56,4 +56,4 @@ __all__ = [
56
56
  "tool",
57
57
  ]
58
58
 
59
- __version__ = "0.1.0"
59
+ __version__ = "0.2.0"
@@ -5,18 +5,20 @@ from __future__ import annotations
5
5
  import logging
6
6
  import re
7
7
  import time
8
- from collections.abc import Iterator
8
+ from collections.abc import Iterator, Mapping
9
9
  from typing import Annotated, Literal
10
10
 
11
11
  from fastapi import Depends, FastAPI, HTTPException, Query, Request, Response
12
12
  from sqlalchemy import Engine, text
13
+ from sqlalchemy.exc import IntegrityError, InterfaceError, OperationalError
13
14
  from sqlalchemy.orm import Session
15
+ from starlette.concurrency import run_in_threadpool
14
16
 
15
17
  from agentflight import __version__
16
- from agentflight.server import service
17
- from agentflight.server.auth import RedactingFilter, require
18
+ from agentflight.server import otlp, service
19
+ from agentflight.server.auth import RedactingFilter, authorize, require
18
20
  from agentflight.server.db import make_engine, session_factory
19
- from agentflight.server.limits import BodySizeLimit, check_spans
21
+ from agentflight.server.limits import BodySizeLimit, PayloadTooLarge, check_spans
20
22
  from agentflight.server.schemas import (
21
23
  EventOut,
22
24
  IngestRequest,
@@ -106,6 +108,66 @@ def create_app(engine: Engine | None = None, settings: Settings | None = None) -
106
108
  run_ids = service.ingest_spans(session, body.spans)
107
109
  return IngestResponse(accepted=len(body.spans), runs=run_ids)
108
110
 
111
+ def store_otlp(body: bytes, fmt: str, encoding: str | None) -> otlp.Converted:
112
+ raw = otlp.decompress(body, encoding, settings.max_body_bytes)
113
+ request = otlp.parse(raw, fmt)
114
+ count = otlp.span_count(request)
115
+ if count > settings.max_spans_per_batch:
116
+ raise otlp.OTLPError(
117
+ 413,
118
+ otlp.RESOURCE_EXHAUSTED,
119
+ f"{count} spans in one request; the limit is {settings.max_spans_per_batch}",
120
+ )
121
+ converted = otlp.convert(request, settings)
122
+ if converted.spans:
123
+ with app.state.sessions() as session:
124
+ service.ingest_spans(session, converted.spans, converted.roots)
125
+ return converted
126
+
127
+ @app.post(
128
+ "/v1/traces",
129
+ summary="OTLP/HTTP trace ingest (protobuf or JSON, optionally gzip)",
130
+ response_class=Response,
131
+ )
132
+ async def otlp_traces(request: Request) -> Response:
133
+ fmt = otlp.request_format(request.headers.get("content-type"))
134
+ reply = fmt or otlp.JSON
135
+
136
+ def error(
137
+ status: int, code: int, message: str, headers: Mapping[str, str] | None = None
138
+ ) -> Response:
139
+ body = otlp.encode_status(reply, code, message)
140
+ return Response(body, status_code=status, media_type=reply, headers=headers)
141
+
142
+ denied = authorize(request, Permission.INGEST)
143
+ if denied is not None:
144
+ code = otlp.UNAUTHENTICATED if denied.status_code == 401 else otlp.PERMISSION_DENIED
145
+ return error(denied.status_code, code, str(denied.detail), denied.headers)
146
+ if fmt is None:
147
+ return error(
148
+ 415,
149
+ otlp.INVALID_ARGUMENT,
150
+ f"Content-Type must be {otlp.PROTOBUF} or {otlp.JSON}",
151
+ )
152
+ body = bytearray()
153
+ try:
154
+ async for chunk in request.stream():
155
+ body += chunk
156
+ except PayloadTooLarge as exc:
157
+ return error(413, otlp.RESOURCE_EXHAUSTED, str(exc.detail))
158
+ encoding = request.headers.get("content-encoding")
159
+ try:
160
+ converted = await run_in_threadpool(store_otlp, bytes(body), fmt, encoding)
161
+ except otlp.OTLPError as exc:
162
+ return error(exc.status, exc.code, exc.message)
163
+ except (OperationalError, InterfaceError, IntegrityError):
164
+ # Transient (database down, or a concurrent insert of the same run): retryable.
165
+ logging.getLogger("agentflight").warning("OTLP ingest failed", exc_info=True)
166
+ return error(
167
+ 503, otlp.UNAVAILABLE, "database unavailable, retry later", {"Retry-After": "5"}
168
+ )
169
+ return Response(otlp.encode_response(fmt, converted), media_type=fmt)
170
+
109
171
  @app.get("/v1/runs", response_model=RunList, dependencies=[CanRead])
110
172
  def list_runs(
111
173
  session: SessionDep,
@@ -62,26 +62,34 @@ def permissions_for(key: str, keys: Mapping[str, frozenset[Permission]]) -> froz
62
62
  return _match(key, keys)
63
63
 
64
64
 
65
+ def authorize(request: Request, permission: Permission) -> HTTPException | None:
66
+ """The error to answer with if this request may not use ``permission`` (else None)."""
67
+ settings: Settings = request.app.state.settings
68
+ if settings.auth_disabled:
69
+ return None
70
+ key = presented_key(request)
71
+ if key is None:
72
+ return HTTPException(
73
+ status_code=401,
74
+ detail="missing API key",
75
+ headers={"WWW-Authenticate": "Bearer"},
76
+ )
77
+ perms = _match(key, settings.api_keys)
78
+ if not perms:
79
+ return HTTPException(
80
+ status_code=401,
81
+ detail="invalid API key",
82
+ headers={"WWW-Authenticate": "Bearer"},
83
+ )
84
+ if permission not in perms:
85
+ return HTTPException(status_code=403, detail=f"key lacks {permission} permission")
86
+ return None
87
+
88
+
65
89
  def require(permission: Permission) -> Callable[[Request], None]:
66
90
  def dependency(request: Request) -> None:
67
- settings: Settings = request.app.state.settings
68
- if settings.auth_disabled:
69
- return
70
- key = presented_key(request)
71
- if key is None:
72
- raise HTTPException(
73
- status_code=401,
74
- detail="missing API key",
75
- headers={"WWW-Authenticate": "Bearer"},
76
- )
77
- perms = _match(key, settings.api_keys)
78
- if not perms:
79
- raise HTTPException(
80
- status_code=401,
81
- detail="invalid API key",
82
- headers={"WWW-Authenticate": "Bearer"},
83
- )
84
- if permission not in perms:
85
- raise HTTPException(status_code=403, detail=f"key lacks {permission} permission")
91
+ error = authorize(request, permission)
92
+ if error is not None:
93
+ raise error
86
94
 
87
95
  return dependency