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

# DSPy Instrumentation

> Learn how to instrument DSPy programs with the LangWatch Python SDK to trace RAG pipelines, optimize prompts, and improve AI agent evaluations.

LangWatch integrates with DSPy to automatically capture detailed information about your DSPy program executions, including module calls and language model interactions.

## Installation

<CodeGroup>
  ```bash pip theme={null}
  pip install langwatch dspy
  ```

  ```bash uv theme={null}
  uv add langwatch dspy
  ```
</CodeGroup>

## Usage

<Info>
  The LangWatch API key is configured by default via the `LANGWATCH_API_KEY` environment variable.
</Info>

Use `autotrack_dspy()` to automatically capture all DSPy operations within a trace.

```python theme={null}
import langwatch
import dspy
import os

langwatch.setup()

# Initialize your DSPy LM (Language Model)
lm = dspy.LM(
    "openai/gpt-5",
    api_key=os.environ.get("OPENAI_API_KEY"),
    temperature=1.0,
    max_tokens=16000,
)
dspy.settings.configure(lm=lm)


@langwatch.trace(name="DSPy RAG Execution")
def run_dspy_program(user_query: str):
    langwatch.get_current_trace().autotrack_dspy()

    module = dspy.Predict("question -> answer")
    prediction = module(question=user_query)
    return prediction.answer


def main():
    user_question = "What is the capital of France?"
    response = run_dspy_program(user_question)
    print(f"Question: {user_question}")
    print(f"Answer: {response}")


if __name__ == "__main__":
    main()
```

The `@langwatch.trace()` decorator creates a parent trace, and `autotrack_dspy()` enables automatic tracking of all DSPy operations, including module calls and underlying LM interactions, for the duration of that trace.

## Related

* [Capturing RAG](/integration/python/tutorials/capturing-rag) - Learn how to capture RAG data from retrievers and tools
* [Capturing Metadata and Attributes](/integration/python/tutorials/capturing-metadata) - Add custom metadata and attributes to your traces and spans
* [Capturing Evaluations & Guardrails](/integration/python/tutorials/capturing-evaluations-guardrails) - Log evaluations and implement guardrails in your DSPy applications
