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

# start_span

> Context manager for creating spans with fine-grained control.

> [!WARNING]
>
> You are reading the docs of Galtea 5.16. [Read this page in the latest version](https://docs.galtea.ai/sdk/api/span/start-span.md).

## Returns

Yields a `GalteaSpan` object with helper methods for setting span data dynamically.

## Example

```python theme={"system"}
with start_span("manual_span", type="SPAN") as span:
    # Do work
    span.update(metadata={"status": "done"})
```

## Parameters

**name** `string` *required*

Name of the span.

**type** `string`

SpanType value: `SPAN`, `GENERATION`, `EVENT`, `AGENT`, `TOOL`, `CHAIN`, `RETRIEVER`, `EVALUATOR`, `EMBEDDING`, `GUARDRAIL`. See [Span Types](https://docs.galtea.ai/v5.16/concepts/product/version/session/span.md#span-types) for details. An unrecognized value emits a `UserWarning` and is sent as `SPAN`, so your original label is not stored. Pass the label to [`spans.create`](https://docs.galtea.ai/v5.16/sdk/api/span/create) instead when you need Galtea to keep it.

**description** `string`

Human-readable description of what this operation does. Useful for documentation and debugging. Maximum size: 1MB.

**input** `any`

Input data for the span. Accepts any value (non-serializable objects are converted to string). Maximum size: 10MB.

**metadata** `any`

Metadata for the span. Accepts any value (non-serializable objects are converted to string). Maximum size: 10MB.

**attributes** `dict`

Custom OpenTelemetry attributes to add to the span.

## GalteaSpan Methods

The yielded `GalteaSpan` object provides these methods:

**update(input, output, metadata, type)** `method`

Update span attributes. All parameters are optional and accept any value (non-serializable objects are converted to string).

**set\_attribute(key, value)** `method`

Set a custom attribute on the span.

**record\_exception(exception)** `method`

Manually record an exception on the span.

## When to Use

Use `start_span()` instead of `@traced` when you need:

1. **Fine-grained control** over specific code blocks rather than entire functions
2. **Dynamic attributes** that are only known at runtime
3. **Conditional tracing** based on runtime conditions
4. **Tracing third-party code** that you can't decorate

## Complete Example

```python theme={"system"}
def rag_pipeline(query: str, trace_id: str) -> str:
    token = set_context(trace_id=trace_id)

    try:
        # Retrieval step
        with start_span(
            "retrieve_documents",
            type="RETRIEVER",
            description="Searches vector store for relevant documents",
            input={"query": query},
        ) as span:
            # Simulated vector store search
            docs = [
                {"id": "doc1", "content": "Paris is the capital of France."},
                {"id": "doc2", "content": "France is in Western Europe."},
            ]
            span.update(output={"doc_count": len(docs), "docs": docs})

        # Generation step
        with start_span(
            "generate_response",
            type="GENERATION",
            description="Generates final response using retrieved context",
            input={"query": query},
        ) as span:
            # Simulated LLM response
            response_content = "Based on the documents, Paris is the capital of France."
            span.update(
                output={"response": response_content},
                metadata={"tokens_used": 42, "model": "gpt-4"},
            )

        return response_content
    finally:
        clear_context(token)


# Create a trace to associate spans with
trace_for_rag = galtea.traces.create(
    session_id=session_start_span.id,
    input="What is the capital of France?",
)
if trace_for_rag is None:
    raise ValueError("trace_for_rag is None")

result = rag_pipeline("What is the capital of France?", trace_for_rag.id)
```

## Nested Spans

Spans automatically form a parent-child hierarchy when nested:

```python theme={"system"}
def process_with_nested_spans(trace_id: str) -> dict:
    token = set_context(trace_id=trace_id)

    try:
        with start_span("parent_operation", type="CHAIN", input={"task": "process_all"}) as parent:
            # First child
            with start_span("child_step_1", type="TOOL") as span:
                step1_result = {"processed": True, "items": 5}
                span.update(output=step1_result)

            # Second child
            with start_span("child_step_2", type="TOOL") as span:
                step2_result = {"validated": True, "errors": 0}
                span.update(output=step2_result)

            parent.update(output={"total_steps": 2, "status": "completed"})

        return {"step1": step1_result, "step2": step2_result}
    finally:
        clear_context(token)


# Create another trace for nested span example
trace_for_nested = galtea.traces.create(
    session_id=session_start_span.id,
    input="Process all items",
)
if trace_for_nested is None:
    raise ValueError("trace_for_nested is None")

nested_result = process_with_nested_spans(trace_for_nested.id)
```

> [!NOTE]
>
> Like `@traced`, spans created with `start_span()` are automatically exported to Galtea API when `clear_context()` is called.


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