|
| 1 | +--- |
| 2 | +integration: logfire |
| 3 | +--- |
| 4 | + |
| 5 | +## Introduction |
| 6 | + |
| 7 | +Logfire supports instrumenting [PydanticAI](https://ai.pydantic.dev/). |
| 8 | + |
| 9 | +```python hl_lines="5" |
| 10 | +import logfire |
| 11 | +from pydantic_ai import Agent, RunContext |
| 12 | + |
| 13 | +logfire.configure() |
| 14 | +Agent.instrument_all() |
| 15 | +``` |
| 16 | + |
| 17 | +!!! note |
| 18 | + You will need to provide your `LOGFIRE_TOKEN` and LLM-appropriate API key environment variables. |
| 19 | + |
| 20 | +With that you get: |
| 21 | + |
| 22 | +* A span around all LLM calls your agent makes which records duration and captures any exceptions that might occur |
| 23 | +* Human-readable display of the conversation with the agent |
| 24 | +* Details of the request/response, including the number of tokens used |
| 25 | + |
| 26 | +You can also instrument **specific** agents with this approach: |
| 27 | + |
| 28 | +```python hl_lines="15" |
| 29 | +import logfire |
| 30 | +from pydantic_ai import Agent, RunContext |
| 31 | + |
| 32 | +logfire.configure() |
| 33 | + |
| 34 | + |
| 35 | +roulette_agent = Agent( |
| 36 | + 'openai:gpt-4o', |
| 37 | + deps_type=int, |
| 38 | + result_type=bool, |
| 39 | + system_prompt=( |
| 40 | + 'Use the `roulette_wheel` function to see if the ' |
| 41 | + 'customer has won based on the number they provide.' |
| 42 | + ), |
| 43 | + instrument=True |
| 44 | +) |
| 45 | + |
| 46 | + |
| 47 | +@roulette_agent.tool |
| 48 | +async def roulette_wheel(ctx: RunContext[int], square: int) -> str: |
| 49 | + """check if the square is a winner""" |
| 50 | + return 'winner' if square == ctx.deps else 'loser' |
| 51 | + |
| 52 | + |
| 53 | +# Run the agent |
| 54 | +success_number = 18 |
| 55 | +result = roulette_agent.run_sync('Put my money on square eighteen', deps=success_number) |
| 56 | +print(result.data) |
| 57 | +#> True |
| 58 | + |
| 59 | +result = roulette_agent.run_sync('I bet five is the winner', deps=success_number) |
| 60 | +print(result.data) |
| 61 | +#> False |
| 62 | +``` |
| 63 | + |
| 64 | +The above example displays like this in Logfire: |
| 65 | + |
| 66 | +<figure markdown="span"> |
| 67 | +  |
| 69 | + <figcaption>PydanticAI instrumented and displayed in Logfire</figcaption> |
| 70 | +</figure> |
| 71 | + |
| 72 | +You can use PydanticAI with a [large variety of LLMs](https://ai.pydantic.dev/api/models/base/#pydantic_ai.models.KnownModelName), the example |
| 73 | +just happens to show `gpt-4o`. |
| 74 | + |
| 75 | +For more information, see the [PydanticAI docs on instrumenting](https://ai.pydantic.dev/#instrumentation-with-pydantic-logfire) with Logfire. |
0 commit comments