### Install Uvicorn and start the app Source: https://pydantic.dev/docs/logfire/integrations/web-frameworks/litestar Install Uvicorn, the server used by the example, and start the app with `python main.py`. ```bash pip install uvicorn python main.py ``` -------------------------------- ### OpenCode: Interactive setup command Source: https://pydantic.dev/docs/logfire/guides/mcp-server Run this command to start the interactive setup for adding the MCP server. Answer the prompts as described in the guide. ```bash opencode mcp add ``` -------------------------------- ### Install Uvicorn server Source: https://pydantic.dev/docs/logfire/integrations/web-frameworks/asgi Install Uvicorn, the ASGI server, required to run the example application. ```bash pip install uvicorn ``` -------------------------------- ### Set up environment and run Node.js OpenTelemetry example Source: https://pydantic.dev/docs/logfire/guides/alternative-clients Terminal commands to set the OTLP endpoint and authorization header, initialize a package.json with type module, install the @opentelemetry/sdk-node package, and run main.js. ```sh export OTEL_EXPORTER_OTLP_ENDPOINT=https://logfire-us.pydantic.dev export OTEL_EXPORTER_OTLP_HEADERS='Authorization=your-write-token' npm init es6 -y # creates package.json with type module npm install @opentelemetry/sdk-node node main.js ``` -------------------------------- ### Start local PostgreSQL with Docker for asyncpg example Source: https://pydantic.dev/docs/logfire/integrations/databases/asyncpg Start a local PostgreSQL container for testing. Creates a database reachable at postgres://user:secret@127.0.0.1:5432/database. ```bash docker run --name postgres \ -e POSTGRES_USER=user \ -e POSTGRES_PASSWORD=secret \ -e POSTGRES_DB=database \ -p 5432:5432 \ -d postgres ``` -------------------------------- ### Install requests for admin automation Source: https://pydantic.dev/docs/logfire/deploy/self-hosted-deployment/examples Install the requests library if it is not already available. Required for the instance admin automation example. ```bash python -m pip install requests ``` -------------------------------- ### Start local MongoDB with Docker Source: https://pydantic.dev/docs/logfire/integrations/databases/pymongo Start a local MongoDB instance using Docker, which is required for the usage example. ```bash docker run --name mongo -p 127.0.0.1:27017:27017 -d mongo:latest ``` -------------------------------- ### Start Redis broker with Docker Source: https://pydantic.dev/docs/logfire/integrations/event-streams/celery Start a Redis broker for the Celery integration example using Docker. ```bash docker run --rm -d -p 127.0.0.1:6379:6379 redis ``` -------------------------------- ### Install and run FastAPI app with Logfire (Terminal) Source: https://pydantic.dev/docs/logfire/get-started/why These commands install the required packages and run the FastAPI app. The first command installs `logfire[fastapi]`, `fastapi`, and `uvicorn`. The second command runs the app with uvicorn. This setup is necessary to run the instrumented app. ```bash pip install 'logfire[fastapi]' fastapi uvicorn # (1) uvicorn main:app # (2) ``` -------------------------------- ### Python: Add Logfire to your app (hello.py) Source: https://pydantic.dev/docs/logfire/get-started/first-trace Python example that configures Logfire, starts a span named 'greeting', and logs an info message inside it. `configure()` connects your app to Logfire, `span()` records one operation, and `info()` writes a log inside it, together forming your first trace. ```py import logfire logfire.configure() with logfire.span('greeting'): logfire.info('Hello, {name}!', name='world') ``` -------------------------------- ### Full example: initialize OFREP provider, set context, and evaluate flags Source: https://pydantic.dev/docs/logfire/manage/client-side-feature-flags Complete setup combining initialization, context, and evaluation. Initializes the OFREP web provider with a custom fetch implementation that adds Authorization and Content-Type headers, sets user context with a targeting key, and evaluates boolean, string, and number flags. ```typescript import { OFREPWebProvider } from '@openfeature/ofrep-web-provider' import { OpenFeature } from '@openfeature/web-sdk' // Initialize once at app startup function initFeatureFlags(apiKey: string, apiHost: string) { const provider = new OFREPWebProvider({ baseUrl: `https://${apiHost}/v1`, fetchImplementation: (input, init) => { const headers = new Headers(input instanceof Request ? input.headers : undefined) new Headers(init?.headers).forEach((value, key) => headers.set(key, value)) headers.set('Authorization', `Bearer ${apiKey}`) headers.set('Content-Type', 'application/json') return fetch(input, { ...init, headers }) }, }) OpenFeature.setProvider(provider) } // Set context when user authenticates async function setUserContext(userId: string, attributes: Record = {}) { await OpenFeature.setContext({ targetingKey: userId, ...attributes, }) } // Evaluate flags anywhere in your app function getFeatureFlags() { const client = OpenFeature.getClient() return { showNewDashboard: client.getBooleanValue('show_new_dashboard', false), pricingTier: client.getStringValue('pricing_tier_config', 'standard'), maxUploadSize: client.getNumberValue('max_upload_size_mb', 10), } } ``` -------------------------------- ### Install Letta and letta-client Source: https://pydantic.dev/docs/logfire/integrations/llms/letta Install the Letta server and client packages via pip. ```bash pip install letta letta-client ``` -------------------------------- ### logfire projects use backend example Source: https://pydantic.dev/docs/logfire/reference/cli Example that uses the `backend` project. ```bash logfire projects use backend ``` -------------------------------- ### Install LlamaIndex instrumentation and dependencies Source: https://pydantic.dev/docs/logfire/integrations/llms/llamaindex Installs the OpenTelemetry LlamaIndex instrumentation and required LlamaIndex packages for the example, including OpenAI LLM and web reader support. ```bash pip install opentelemetry-instrumentation-llamaindex \ llama-index-core llama-index-llms-openai llama-index-readers-web html2text ``` -------------------------------- ### Run Python example Source: https://pydantic.dev/docs/logfire/get-started/first-trace Run the Python example. The first run asks you to pick or create a Logfire project, then sends your trace. ```bash uv run hello.py ``` -------------------------------- ### Install and configure OpenAI instrumentation Source: https://pydantic.dev/docs/logfire/observe/llms Install the required packages and set the LOGFIRE_TOKEN environment variable. This is the first step to get your first LLM row to appear. ```bash pip install logfire openai export LOGFIRE_TOKEN= ``` -------------------------------- ### main.rs: create tracer and export span Source: https://pydantic.dev/docs/logfire/guides/alternative-clients Sets up an OTLP HTTP exporter, installs a simple tracer provider, and creates a span named "Hello World". Includes commented-out code for programmatic endpoint and header configuration. ```rust use opentelemetry::{ global::ObjectSafeSpan, trace::{Tracer, TracerProvider}, }; fn main() -> Result<(), Box> { let otlp_exporter = opentelemetry_otlp::new_exporter() .http() .with_protocol(opentelemetry_otlp::Protocol::HttpBinary) // If you don't want to export environment variables, you can also configure // programmatically like so: // // (You'll need to add `use opentelemetry_otlp::WithExportConfig;` to the top of the // file to access the `.with_endpoint` method.) // // .with_endpoint("https://logfire-us.pydantic.dev/v1/traces") // .with_headers({ // let mut headers = std::collections::HashMap::new(); // headers.insert( // "Authorization".into(), // "your-write-token".into(), // ); // headers // }) ; let tracer_provider = opentelemetry_otlp::new_pipeline() .tracing() .with_exporter(otlp_exporter) .install_simple()?; let tracer = tracer_provider.tracer("my_tracer"); tracer.span_builder("Hello World").start(&tracer).end(); Ok(()) } ``` -------------------------------- ### Initialize and run the Go module Source: https://pydantic.dev/docs/logfire/instrument/go Commands to initialize the Go module, fetch dependencies, and run the program. This is the final step to send the trace to Logfire. ```sh go mod init hello-go go mod tidy go run . ``` -------------------------------- ### Example response for GET /proxy/models Source: https://pydantic.dev/docs/logfire/manage/ai-gateway/embeddings Example JSON response showing chat models under 'models' and embedding models under 'embedding_models'. The response is one entry per route. ```json [ { "route": "openai", "provider": "openai", "models": [{ "id": "gpt-5.2", "name": "gpt-5.2", "context_window": 400000 }], "embedding_models": [ { "id": "text-embedding-3-small", "name": "text-embedding-3-small", "context_window": 8192 }, { "id": "text-embedding-3-large", "name": "text-embedding-3-large", "context_window": 8192 } ] } ] ``` -------------------------------- ### Install and configure OpenInference LangChain instrumentor Source: https://pydantic.dev/docs/logfire/integrations/llms/langchain Install the OpenInference LangChain instrumentation package and configure it with Logfire. This setup marks agent root spans so agents appear on the Agents page, unlike the LangSmith export which only lands traces in the Live view. ```bash pip install openinference-instrumentation-langchain ``` ```python from openinference.instrumentation.langchain import LangChainInstrumentor import logfire logfire.configure() LangChainInstrumentor().instrument() ``` -------------------------------- ### Install OpenFeature Web SDK and OFREP provider Source: https://pydantic.dev/docs/logfire/manage/client-side-feature-flags Install the OpenFeature Web SDK and OFREP provider using npm, pnpm, or yarn. Choose the command that matches your package manager. ```bash npm install @openfeature/web-sdk @openfeature/ofrep-web-provider ``` ```bash pnpm add @openfeature/web-sdk @openfeature/ofrep-web-provider ``` ```bash yarn add @openfeature/web-sdk @openfeature/ofrep-web-provider ``` -------------------------------- ### Refresh token with curl Source: https://pydantic.dev/docs/logfire/manage/oauth-apps Uses curl to POST to the token endpoint with refresh_token grant, authenticating with client credentials. Requires the environment variables from the setup example. ```bash curl --fail-with-body --silent --show-error \ --user "$CLIENT_ID:$CLIENT_SECRET" \ --data-urlencode 'grant_type=refresh_token' \ --data-urlencode "refresh_token=$REFRESH_TOKEN" \ "$LOGFIRE_BASE_URL/api/oauth/token" ``` -------------------------------- ### Example console output Source: https://pydantic.dev/docs/logfire/instrument/python/add-manual-tracing Example output when running the span and log example, showing the project URL and the log lines with timestamps and indentation. ```text Logfire project URL: https://logfire.pydantic.dev/my_username/my_project_name 21:02:55.078 This is a span 21:02:56.084 This is an info log ``` -------------------------------- ### Install logfire variables extra and fetch a managed prompt for a CrewAI agent Source: https://pydantic.dev/docs/logfire/integrations/llms/crewai Install the variables extra for the Logfire SDK, then fetch a versioned prompt and pass it into a CrewAI agent. The Python example defines a BackstoryInputs model, retrieves the prompt with logfire.template_var, and uses the resolved value as the agent's backstory. ```bash pip install 'logfire[variables]' ``` ```python from crewai import Agent from pydantic import BaseModel import logfire logfire.configure() class BackstoryInputs(BaseModel): domain: str backstory_var = logfire.template_var( name='prompt__researcher_backstory', type=str, default='You are a knowledgeable analyst who values brevity.', inputs_type=BackstoryInputs, ) with backstory_var.get(BackstoryInputs(domain='observability'), label='production') as resolved: backstory = resolved.value researcher = Agent( role='Researcher', goal='Explain a topic clearly and concisely', backstory=backstory, llm='openai/gpt-4o-mini', ) ``` -------------------------------- ### Capture specific HTTP request headers Source: https://pydantic.dev/docs/logfire/integrations/web-frameworks Set `OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST` to a comma-separated list of regexes to capture only matching headers. This example captures the `content-type` header and any header starting with `X-`. ```bash OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST="content-type,X-.*" ``` -------------------------------- ### Environment Setup for Verification Source: https://pydantic.dev/docs/logfire/manage/oauth-apps Set the API base URL and access token environment variables before listing projects. ```bash export LOGFIRE_API_BASE_URL='https://api-us.pydantic.dev/api/v1' export ACCESS_TOKEN='ACCESS_TOKEN_FROM_THE_TOKEN_RESPONSE' ``` -------------------------------- ### Add tracing code to hello.php Source: https://pydantic.dev/docs/logfire/instrument/php Initialize the tracer and create a manual span named 'Hello World'. ```php getTracer('hello-php') ->spanBuilder('Hello World') ->startSpan() ->end(); ``` -------------------------------- ### Basic auto-tracing setup with main.py Source: https://pydantic.dev/docs/logfire/instrument/python/add-auto-tracing Call logfire.install_auto_tracing() before importing the modules to trace. This example traces all functions in the 'app' package that take longer than 0.01 seconds. Generator functions are not traced. ```python import logfire logfire.configure() logfire.install_auto_tracing(modules=['app'], min_duration=0.01) from app.main import main main() ``` -------------------------------- ### Start Gunicorn with configuration file Source: https://pydantic.dev/docs/logfire/integrations/web-frameworks/gunicorn Start Gunicorn using the configuration file that sets up Logfire. Replace myapp:app with your WSGI application. ```bash gunicorn myapp:app --config gunicorn_config.py ``` -------------------------------- ### Sync Logfire Query Client Usage Source: https://pydantic.dev/docs/logfire/manage/query-api Example of using the LogfireQueryClient to query data in JSON, Arrow, and CSV formats, and to get read token info. Requires pyarrow for Arrow format. ```python from datetime import UTC, datetime, timedelta from io import StringIO import polars as pl from logfire.query_client import LogfireQueryClient def main(): query = """ SELECT start_timestamp FROM records LIMIT 1 """ min_timestamp = datetime.now(tz=UTC) - timedelta(hours=2) with LogfireQueryClient(read_token='') as client: # Load data as JSON json_rows = client.query_json_rows(sql=query, min_timestamp=min_timestamp) print(json_rows) """ { "columns": [{'name': 'start_timestamp', 'datatype': {'Timestamp': ['Microsecond', 'UTC']}, 'nullable': False}], "rows": [{'start_timestamp': '2026-05-27T13:16:36.517321Z'}] } """ # Retrieve data in arrow format, and load into a polars DataFrame # Note that JSON columns such as `attributes` will be returned as # JSON-serialized strings df_from_arrow = pl.from_arrow(client.query_arrow(sql=query, min_timestamp=min_timestamp)) print(df_from_arrow) # Retrieve data in CSV format, and load into a polars DataFrame # Note that JSON columns such as `attributes` will be returned as # JSON-serialized strings df_from_csv = pl.read_csv(StringIO(client.query_csv(sql=query, min_timestamp=min_timestamp))) print(df_from_csv) # Get read token info read_token_info = client.info() print(read_token_info) if __name__ == '__main__': main() ``` -------------------------------- ### Async Logfire Query Client Usage Source: https://pydantic.dev/docs/logfire/manage/query-api Example of using the AsyncLogfireQueryClient to query data in JSON, Arrow, and CSV formats, and to get read token info. Requires pyarrow for Arrow format. ```python from datetime import UTC, datetime, timedelta from io import StringIO import polars as pl from logfire.query_client import AsyncLogfireQueryClient async def main(): query = """ SELECT start_timestamp FROM records LIMIT 1 """ min_timestamp = datetime.now(tz=UTC) - timedelta(hours=2) async with AsyncLogfireQueryClient(read_token='') as client: # Load data as JSON json_rows = await client.query_json_rows(sql=query, min_timestamp=min_timestamp) print(json_rows) """ { "columns": [{'name': 'start_timestamp', 'datatype': {'Timestamp': ['Microsecond', 'UTC']}, 'nullable': False}], "rows": [{'start_timestamp': '2026-05-27T13:16:36.517321Z'}] } """ # Retrieve data in arrow format, and load into a polars DataFrame # Note that JSON columns such as `attributes` will be returned as # JSON-serialized strings df_from_arrow = pl.from_arrow(await client.query_arrow(sql=query, min_timestamp=min_timestamp)) print(df_from_arrow) # Retrieve data in CSV format, and load into a polars DataFrame # Note that JSON columns such as `attributes` will be returned as # JSON-serialized strings df_from_csv = pl.read_csv(StringIO(await client.query_csv(sql=query, min_timestamp=min_timestamp))) print(df_from_csv) # Get read token info read_token_info = await client.info() print(read_token_info) if __name__ == '__main__': import asyncio asyncio.run(main()) ``` -------------------------------- ### Switch to pydantic-skills marketplace for Claude Code Source: https://pydantic.dev/docs/logfire/guides/mcp-server Removes the official plugin and installs from the pydantic/skills marketplace to get a version tracking the latest commit. Run `/reload-plugins` or restart Claude Code after switching. ```bash claude plugin remove logfire@claude-plugins-official claude plugin marketplace add pydantic/skills claude plugin install logfire@pydantic-skills ``` -------------------------------- ### Instrument requests library in main.py Source: https://pydantic.dev/docs/logfire/integrations/http-clients/requests Add `logfire.configure()` and `logfire.instrument_requests()` to your app to record every outgoing request. The example makes a GET request to `https://httpbin.org/get` and the span appears in the Logfire Live view. ```python import requests import logfire logfire.configure() logfire.instrument_requests() requests.get('https://httpbin.org/get') ``` -------------------------------- ### Set up local project credentials with CLI Source: https://pydantic.dev/docs/logfire/instrument/typescript/configuration Use these commands to authenticate and select a project, which writes local credentials to `.logfire/logfire_credentials.json` for Node.js development. ```bash npx logfire auth npx logfire projects use my-project ```