> ## Documentation Index
> Fetch the complete documentation index at: https://docs.impact.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Python runtime and application API

> Use the Python API for logical requests, manual operations and scoped context.

## Runtime API

| API | Purpose |
| - | - |
| `init(...)` | Starts capture. Equivalent settings return the existing runtime. Conflicting settings raise. |
| `init_async(...)` | Returns an `AsyncRuntime` sharing the same resources. Await its lifecycle and capability methods. |
| `interaction(work, ...)` | Owns one logical request and its observed result, exception, cancellation or supported stream ending. |
| `continue_interaction(carrier, work, ...)` | Takes completion ownership after a confirmed handoff. |
| `context(...)` | Applies validated task-scoped Product context. |
| `span(name, ...)` | Captures an application boundary and preserves native output, exception and cancellation. |
| `operation(name, role=..., capture=...)` | Decorates sync or async functions and generators. Optionally captures named arguments. |
| `inject_context(carrier)` / `extract_context(carrier)` | Propagates W3C parentage and bounded contributor context. Apply extraction with `context(propagated=...)`. |
| `feedback(...)` | Records [Feedback](https://docs.impact.ai/sdk/feedback.md) with a stable occurrence identity. |
| `runtime.attach_realtime(connection, ...)` | Observes an [application-owned OpenAI Realtime connection](https://docs.impact.ai/sdk/python/integrations.md#openai-realtime-attachment). |
| `runtime.status()` | Reports provider ownership, integration activation, limitations, delivery and cleanup. |
| `runtime.flush(timeout_ms=...)` | Makes a bounded attempt to export finished telemetry. Product readback is a separate observation. |
| `runtime.shutdown(timeout_ms=...)` | Flushes and stops SDK-owned work. A retry skips completed cleanup phases. |

Manual capture never changes application exceptions or cancellation identity. Serialization loss leaves an
explicit partial or omission marker. Stream output records consumed chunks in a JSON array. A capturable
non-`None` sync generator return uses a single `output.value` JSON object containing `chunks` and `return`,
identified by `impact.capture.output.format="stream-chunks-and-return"`. The output follows the boundary's
content controls. Context identifiers allow 1,024 UTF-8 bytes and purpose allows 65,536. Empty strings, NUL,
malformed Unicode and unknown fields reject before capture.

## Record a logical request

Initialize Impact to observe ordinary provider calls in the [integration catalogue](https://docs.impact.ai/sdk/python/integrations.md).
Wrap an application request with `interaction()` to connect its native model, tool and service calls to its
outcome. Use the configuration and dependencies from the [quickstart](https://docs.impact.ai/quickstart.md#python-example) to run this
example. It makes one billable provider call.

```python theme={null}
import os

import impact

runtime = impact.init()
try:
    from openai import OpenAI

    with OpenAI(max_retries=0) as client:
        def answer_request(request):
            result = client.responses.create(
                model=os.getenv("OPENAI_MODEL", "gpt-6.1-sol"),
                max_output_tokens=512,
                reasoning={"effort": "low"},
                input="Explain how a customer can find their order status.",
            )
            return result.output_text

        answer = impact.interaction(
            answer_request,
            session_id="conversation-1",
            interaction_id="request-42",
            user_id="customer-17",
            name="answer",
            input={"question": "Where is my order?"},
        )
        print(answer)
finally:
    runtime.shutdown()
```

`interaction()` preserves the callback's native value or awaitable and invokes it once. Omit `interaction_id`
to create one UUID at that explicit request boundary. Several requests can share an optional Session. A User
ID is an opaque application key, not an authenticated person. Plain `context`, `span` and `operation` scopes
never create an Interaction or independently finish their parent request. Set stable deployment defaults with
`init(context=impact.ImpactContext(...))` using `environment`, `version_id`, `component_id`, `build_id` and
`deployment_id` when those values are known. `environment` is a reported environment name. `version_id` is a
reported deployed-version reference. `build_id` and `deployment_id` are external CI, build and deployment
references. Builder Version and Deploy UUIDs are separate identities. Use real configured values or omit them.
`component_id`, `agent_id` and `agent_version_id` are reported application keys. Native `gen_ai.agent.*`
facts, provider model names and Part relationships have their own sources.

Route credentials establish Workspace and Product tenancy. Context values are correlation claims. Keep
Environment, reported deployed-version reference, component/build/deployment, Session, Interaction, purpose,
User and `DomainRun(kind, id)` distinct. Business identities emit `impact.session.id`, `impact.interaction.id`
and `impact.user.id`. Native provider conversation, response, Trace and Span IDs remain separate. A Simulation
run or invocation ID is not a Session or Interaction ID.

## Manual tool capture

Use an explicit tool span inside the owning Interaction when the application calls the tool itself. Call the
real tool once and set its result on the span. Here `lookup_order` is the application's normal tool.

```python theme={null}
def answer_request(request):
    with impact.span("lookup_order", role="tool", input={"order_id": "order-42"}) as tool:
        result = lookup_order("order-42")
        tool.set_output(result)
    return result

answer = impact.interaction(answer_request, name="answer", session_id="conversation-1")
```

## Typed content and lazy results

Manual spans and Interactions record a successfully captured input or output as one JSON document with
`application/json` MIME. Decode the value once. JSON null, false, zero and empty text have distinct values,
and a string that looks like JSON stays a string. A missing value or MIME declaration leaves typed content
unavailable. The capture state explains whether a policy or native limit omitted it.

Supported Python iterator and async-iterator results remain lazy and observe actual exhaustion, explicit
close, error or cancellation. Never-consumed or opaque framework/HTTP results do not imply successful
completion. Drain or close such work at the application's actual observable boundary. Stopping telemetry does
not end a business Session.

## Propagate native context and correlation

`inject_context()` combines initialized context defaults with the current scope's overrides. It fills and
returns the supplied carrier with standard W3C `traceparent`/`tracestate` plus one bounded `impact-context`
value. That value is canonical compact UTF-8 JSON encoded as unpadded base64url: version 2, optional
Interaction/Session and `domainRun`. User attribution is not automatically propagated. A conflicting or stale
owned value raises `ValueError` without changing any carrier field. Use a fresh carrier for each request.
Successful shutdown removes initialized defaults.

`extract_context()` returns `context`, `native_context`, content-free `issues` and an optional explicit
`transfer`. Inspect issues before applying received correlation through `context(propagated=...)`. Conflicting
Interaction, Session or Domain Run IDs from that carrier cause `ValueError` before the active local
correlation or native context changes. Existing application-owned native parentage is preserved. Contributor
propagation never grants completion ownership or authorizes a Product route. JavaScript uses the same
versioned wire contract. Use the version 2 headers for cross-language propagation.

Create the gateway carrier inside each actual request's active span and pass it through the application's
existing per-request header option. For an application-owned `http.client` connection, use
`connection.request("POST", path, body=body, headers=impact.inject_context(request_headers))`. Keep native
credentials and other request options under application control. Do not cache an injected `traceparent` on a
shared client: concurrent requests need their own active parent. Injection preserves existing equal values and
does not install an HTTP patcher.

## Hand off completion ownership

For longer work, confirm handoff when the application receives its durable publication acknowledgement. The
sender and worker below use the application's queue and request handlers.

```python theme={null}
async def enqueue(request):
    async def publish(transfer):
        await queue.publish_confirmed(question=question, context=transfer.carrier)
        transfer.confirm()  # Only after the application's actual durable acknowledgment.

    await request.handoff(publish)
    return accepted_response()

await impact.interaction(enqueue, session_id=session_id, name="answer", input=question)
await impact.continue_interaction(job.context, lambda request: agent.answer(job.question))
```

The queue, acknowledgment and job above belong to the application. `confirm()` is valid only within the active
publisher callback. Returning or raising without confirmation leaves transfer unconfirmed. A later error after
confirmation cannot reclaim completion ownership. The SDK never republishes business work.
`continue_interaction` requires an actual transfer carrier and defaults to preserving active native parentage.
Supply `new_trace=True` to start a new technical root linked to the valid received context while retaining
logical identity. An ordinary nested `interaction()` with the active Interaction ID raises before invoking the
inner callback. Use `context()` or `span()` for contributor work, and await the actual join inside the
application's completion owner.

## Typed context and Session ending

Optional typed context fields `channel`, `locale`, `plan`, `user_type` and `journey_step` emit the
corresponding `impact.correlation.channel`, `.locale`, `.plan`, `.user_type` and `.journey_step` attributes.
They use the context string bounds above and do not prescribe a vocabulary or infer values. Stable defaults
may be supplied through `init(context=impact.ImpactContext(...))`. Within one context, a typed field wins over
its exact canonical `correlation` key. An inner scope wins over outer/default values, including an inner
correlation value. Existing correlation-only values keep their validation and omission behavior.
`agent_version_id` continues to emit `impact.agent.version.id` separately from the Product's `version_id`.

Supply a known terminal Session fact on the actual terminal operation, before its span or automatic owner
starts:

```python theme={null}
with impact.context(session_id="conversation-1", journey_step="complete", session_ending="resolved"):
    with impact.span("finish-conversation", role="entry") as operation:
        operation.set_output(finish_conversation())
```

`session_ending` emits the raw `impact.session.ending` attribute and requires `session_id` in the same
submitted context. It is rejected in init defaults. Nested work inherits it for the same Session. Changing the
Session clears the inherited ending unless that scope supplies a new pair, and leaving the scope restores the
outer pair. Application-owned native trace parentage must still place the terminal operation under the
intended Session. An existing Trace keeps its native parentage if the context value changes. This field
records the supplied fact, does not close a Session or alter inferred Ending classification, and offers no
post-hoc ending API. Verify the terminal span's raw attribute through authenticated Trace readback under that
exact Session. These typed fields and the supplied ending are not added to propagation headers or baggage.

## Provenance and source references

Shared execution provenance uses `impact.execution.origin`, `impact.execution.input.reference` and distinct
`impact.<evaluation|dataset|case|experiment|replay>.id` attributes. Source references use `code.file.path`,
`code.function.name`, `code.line.number`, `impact.source.basis.id` and `impact.source.observed.at`.
Correlation values use `impact.correlation.*`, matching JavaScript's `custom` fields. These supplied claims do
not establish route authority or trigger source inspection. Native provider identity fields retain their own
meanings.

Automatic callsites require an explicit source root and deployment/source basis:

```python theme={null}
runtime = impact.init(
    callsites={"root": "/srv/my-application", "basis": "git:0123456789abcdef"}
)
```

Impact walks at most 32 active frames when an owned span starts, emits only a path relative to the supplied
root plus function and line, and retains no frames. It does not read source, discover a repository, resolve
symlinks or emit the host absolute root. Omit `callsites` when no trustworthy mapping is available, or set
`enabled=False` for a global opt-out. Explicit `ImpactContext(source=...)` facts remain authoritative.

[Startup and lifecycle](https://docs.impact.ai/sdk/python/setup.md) · [Privacy and streaming](https://docs.impact.ai/sdk/python/capture.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.