> ## Documentation Index
> Fetch the complete documentation index at: https://pype-db52d533.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Agensight Tracing

> How to initialize Agensight tracing, define main operations with @trace, and add granular details with @span.

# Core Concepts

This guide covers the essentials for instrumenting your Python application with Agensight:

1. *Initializing* the tracing system using init().
2. Defining top-level operations or requests as *traces* using the @trace decorator.
3. Instrumenting specific units of work within a trace as *spans* using the @span decorator.

## Initializing Agensight Tracing

Before any traces or spans can be created, you must initialize the Agensight tracing system using init() — typically once at the beginning of your application.
*Purpose*:
Sets up the tracing backend (local or cloud), trace/session ID handling, and optional auto-instrumentation of LLM providers.
*Parameters*:

* name (str): Name of your app/service for trace attribution.
* mode (str): One of local, dev, or prod. Determines if data is stored locally (SQLite) or sent to cloud.
* token (str): Required for cloud mode to associate records in Supabase.
* session (str | dict | None): Optional session ID or metadata. If provided, it associates all traces/spans with this session.
  *Usage Example:*

```python theme={null}
import agensight
agensight.init(
    name="chatbot-with-tools",
    mode="prod",
    token="abc12345",
    session="user_123"  # Can be just a session ID
)
```

***

## Defining Traces with @trace

Use @trace to define a *top-level operation* (e.g. API handler, main pipeline, or user workflow). This starts a trace and includes session + metadata.

```python theme={null}
@trace(name="multi_agent_chat", session={"id": "xyz123", "name": "multi agent chat", "user_id": "123"})
def main():
    ...
```

* Automatically generates a unique trace\_id
* Associates any child spans
* Ties to provided session metadata (if any)

***

## Instrumenting with @span

Use @span to annotate *specific operations* like LLM calls, tool invocations, or data steps.

```python theme={null}
@span(name="llm")
def call_llm(messages):
    return client.chat.completions.create(...)
```

* Captures input, output, execution time
* Extracts LLM usage if present
* Handles tool call spans automatically when tool\_choice=auto

***

## Session Behavior

> :information\_source: *Note on Sessions*:
>
> * If both init() and @trace() specify a session, the @trace() value takes precedence for that specific trace.
> * If you pass only a string (e.g. session="user\_123"), it is treated as a session\_id.
> * To improve traceability, you can pass a full dictionary: id, name, user\_id.
>
> *Example*:
>
> ```python theme={null}
> @trace(name="do_task", session="user_123")  # Overrides session from init()
> def do_task():
>     ...
> ```
>
> Supplying a full dict `{id, name, user_id}` improves tracking and grouping but is optional.
> Before any traces or spans can be created, you must initialize the Agensight tracing system using `init()` — typically once at the beginning of your application.

***

## Example: Multi-Agent Chat with Tools

```python theme={null}
import agensight
from agensight.tracing.decorators import trace, span
agensight.init(name="chat-service", mode="prod", token="abc12345", session="user_456")
@span(name="llm")
def call_llm(messages):
    # Simulate an LLM call with tool use
    return {"content": "Mock response", "tool_used": "get_weather"}
@trace(name="multi_agent_chat", session="user_789")
def main():
    plan = call_llm([{"role": "user", "content": "Weather in Paris?"}])
    summary = call_llm([{"role": "user", "content": f"Summarize: {plan['content']}"}])
    print("Final Output:", summary["content"])
main()
```

This simplified example demonstrates how multiple LLM calls, each wrapped with @span, are grouped under a trace using @trace. Session IDs ensure all trace data is linked and queryable in your observability dashboard.

## Cloud Export

In prod or dev mode, Agensight automatically sends observability data to your configured cloud setup (e.g. via AWS Lambda and Supabase).
To enable this, ensure:

* You've set mode="prod" or mode="dev" in init()
* A valid token is provided
* Your backend infrastructure (e.g. Lambda, database) is correctly configured to receive logs
  Agensight will capture and transmit structured data for:
* traces: top-level operations
* spans: fine-grained steps and LLM/tool calls
* prompts and completions: LLM input/output and token usage
* tools: invoked tool functions
* sessions: grouped user journeys or workflows
  All of this data becomes accessible via your observability dashboard for inspection, debugging, or analytics -**traces, spans, prompts, completions, tools, sessions**

***

For more, see the /examples folder or cloud setup guide.
