### Full OpenFeature Initialization and Evaluation Example Source: https://pydantic.dev/docs/logfire/manage/client-side-feature-flags/index Initialize the OpenFeature SDK with the OFREPWebProvider, set user context, and evaluate flags. This example demonstrates a complete setup for a web application. ```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/ofrep/v1`, fetchImplementation: (input, init) => fetch(input, { ...init, headers: { ...Object.fromEntries(new Headers(init?.headers).entries()), Authorization: `Bearer ${apiKey}`, }, }), }) 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), } } ``` -------------------------------- ### Example: Querying BigQuery with Logfire Source: https://pydantic.dev/docs/logfire/integrations/databases/bigquery/index This example demonstrates how to use the BigQuery client library after configuring Logfire. Logfire automatically instruments the BigQuery client, so no explicit setup is needed for instrumentation itself. Ensure Logfire is configured before creating the client and executing queries. ```python from google.cloud import bigquery import logfire logfire.configure() client = bigquery.Client() query = """ SELECT name FROM `bigquery-public-data.usa_names.usa_1910_2013` WHERE state = "TX" LIMIT 100 """ query_job = client.query(query) print(list(query_job.result())) ``` -------------------------------- ### Install OpenFeature React SDK Source: https://pydantic.dev/docs/logfire/manage/client-side-feature-flags/index Install the OpenFeature React SDK using npm, pnpm, or yarn. ```bash npm install @openfeature/react-sdk ``` ```bash pnpm add @openfeature/react-sdk ``` ```bash yarn add @openfeature/react-sdk ``` -------------------------------- ### Configure Logfire SDK and Instrument OpenAI Source: https://pydantic.dev/docs/logfire/get-started/ai-observability/index Install the Logfire SDK and configure it for your application. This snippet shows basic setup and how to instrument the OpenAI client for observability. ```python import logfire logfire.configure() logfire.instrument_openai() # Or your framework of choice ``` -------------------------------- ### Go OpenTelemetry OTLP HTTP Exporter Setup Source: https://pydantic.dev/docs/logfire/guides/alternative-clients/index Set up an OpenTelemetry OTLP HTTP exporter in Go to send traces to Logfire. This example demonstrates initializing the exporter, processor, and tracer provider. ```go package main import ( "context" "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp" "go.opentelemetry.io/otel/sdk/trace" ) func main() { ctx := context.Background() traceExporter, _ := otlptracehttp.New(ctx) batchSpanProcessor := trace.NewBatchSpanProcessor(traceExporter) tracerProvider := trace.NewTracerProvider(trace.WithSpanProcessor(batchSpanProcessor)) tracer := tracerProvider.Tracer("my_tracer") ctx, span := tracer.Start(ctx, "Hello World") span.End() tracerProvider.Shutdown(ctx) } ``` -------------------------------- ### Basic Logfire Setup and Instrumentation Source: https://pydantic.dev/docs/logfire/get-started/faq/index Use these three lines of Python code for basic Logfire instrumentation. This setup is sufficient for most users to start sending data. ```python import logfire logfire.configure() logfire.instrument_pydantic_ai() # Or your framework of choice ``` -------------------------------- ### Install Dependencies Source: https://pydantic.dev/docs/logfire/integrations/llms/claude-agent-sdk/index Install the necessary packages for Logfire and the Claude Agent SDK. ```bash pip install logfire claude-agent-sdk ``` -------------------------------- ### Start MongoDB with Docker Source: https://pydantic.dev/docs/logfire/integrations/databases/pymongo/index Optional step to start a MongoDB instance using Docker if you don't have one running. ```bash docker run --name mongo -p 27017:27017 -d mongo:latest ``` -------------------------------- ### Install Logfire with Asyncpg Extra using uv Source: https://pydantic.dev/docs/logfire/integrations/databases/asyncpg/index Install the logfire package with the asyncpg extra dependency using uv. ```bash uv add 'logfire[asyncpg]' ``` -------------------------------- ### NodeJS: Setup and Basic Trace Export Source: https://pydantic.dev/docs/logfire/guides/alternative-clients/index Set up the OpenTelemetry NodeJS SDK to export traces to Logfire. This includes installing dependencies, configuring the SDK, and exporting a simple span. ```js import {NodeSDK} from "@opentelemetry/sdk-node"; import {OTLPTraceExporter} from "@opentelemetry/exporter-trace-otlp-proto"; import {BatchSpanProcessor} from "@opentelemetry/sdk-trace-node"; import {trace} from "@opentelemetry/api"; import {Resource} from "@opentelemetry/resources"; import {ATTR_SERVICE_NAME} from "@opentelemetry/semantic-conventions"; const traceExporter = new OTLPTraceExporter(); const spanProcessor = new BatchSpanProcessor(traceExporter); const resource = new Resource({[ATTR_SERVICE_NAME]: "my_service"}); const sdk = new NodeSDK({spanProcessor, resource}); sdk.start(); const tracer = trace.getTracer("my_tracer"); tracer.startSpan("Hello World").end(); sdk.shutdown().catch(console.error); ``` -------------------------------- ### Install Logfire with ASGI extra Source: https://pydantic.dev/docs/logfire/integrations/web-frameworks/asgi/index Install the logfire package with the 'asgi' extra to enable ASGI integration. ```bash pip install 'logfire[asgi]' ``` ```bash uv add 'logfire[asgi]' ``` -------------------------------- ### Install Logfire with AWS Lambda Extra using uv Source: https://pydantic.dev/docs/logfire/integrations/aws-lambda/index Install the logfire package with the aws-lambda extra using uv. ```bash uv add 'logfire[aws-lambda]' ``` -------------------------------- ### Install Logfire with Flask Extra using uv Source: https://pydantic.dev/docs/logfire/integrations/web-frameworks/flask/index Install the logfire package with the flask extra using uv. ```bash uv add 'logfire[flask]' ``` -------------------------------- ### Install LlamaIndex Instrumentation Source: https://pydantic.dev/docs/logfire/integrations/llms/llamaindex/index Install the necessary package for LlamaIndex instrumentation using pip. ```bash pip install opentelemetry-instrumentation-llamaindex ``` -------------------------------- ### Initial values.yaml for Logfire Helm Chart Source: https://pydantic.dev/docs/logfire/deploy/self-hosted-deployment/installation/index An example `values.yaml` file to start with for deploying Logfire. This configuration includes settings for admin email, image pull secrets, PostgreSQL databases, Dex identity provider, object storage, and ingress. ```yaml adminEmail: admin-email@my-company.dev # Configure the Image Pull Secrets imagePullSecrets: - logfire-image-key # Configure Logfire Postgres Databases postgresDsn: postgres://postgres:postgres@postgres.example.com:5432/crud postgresFFDsn: postgres://postgres:postgres@postgres.example.com:5432/ff # Configure Dex Postgres & Identity Provider logfire-dex: config: storage: type: postgres config: host: postgres.example.com port: 5432 user: postgres database: dex password: postgres ssl: mode: disable connectors: - type: "github" id: "github" name: "GitHub" config: clientID: client_id clientSecret: client_secret getUserInfo: true # Configure Object Storage objectStore: uri: s3://logfire-example-bucket env: AWS_ACCESS_KEY_ID: logfire-example AWS_SECRET_ACCESS_KEY: logfire-example # Configure Ingress ingress: enabled: true tls: true hostnames: - logfire.example.com ingressClassName: nginx ``` -------------------------------- ### Install Logfire with FastAPI and Run Uvicorn Source: https://pydantic.dev/docs/logfire/get-started/why/index Install necessary packages including `logfire` with the `fastapi` extra, FastAPI, and uvicorn. Then, run the FastAPI application using uvicorn. ```bash pip install 'logfire[fastapi]' fastapi uvicorn # (1) uvicorn main:app # (2) ``` -------------------------------- ### Install Logfire with Django Extra Source: https://pydantic.dev/docs/logfire/integrations/web-frameworks/django/index Install the logfire package with the django extra using pip or uv. ```bash pip install 'logfire[django]' ``` ```bash uv add 'logfire[django]' ``` -------------------------------- ### Install Logfire with HTTPX extra Source: https://pydantic.dev/docs/logfire/integrations/http-clients/httpx/index Install the logfire package with the httpx extra to enable HTTPX instrumentation. This command installs logfire and its dependencies for httpx. ```bash pip install 'logfire[httpx]' ``` -------------------------------- ### Install Logfire with SQLite3 Extra Source: https://pydantic.dev/docs/logfire/integrations/databases/sqlite3/index Install the logfire package with the sqlite3 extra to enable SQLite3 instrumentation. ```bash pip install 'logfire[sqlite3]' ``` -------------------------------- ### Install Logfire with MySQL extra Source: https://pydantic.dev/docs/logfire/integrations/databases/mysql/index Install the logfire package with the 'mysql' extra to enable MySQL instrumentation. ```bash pip install 'logfire[mysql]' ``` -------------------------------- ### Install logfire with WSGI extra Source: https://pydantic.dev/docs/logfire/integrations/web-frameworks/wsgi/index Install the logfire package with the `wsgi` extra to enable WSGI integration. ```bash pip install 'logfire[wsgi]' ``` -------------------------------- ### LangChain Example with Logfire Integration Source: https://pydantic.dev/docs/logfire/integrations/llms/langchain/index A complete example demonstrating how to integrate Logfire with LangChain. Ensure the necessary environment variables are set before importing and configuring Logfire. ```python import os import logfire # These environment variables need to be set before importing langchain or langgraph os.environ['LANGSMITH_OTEL_ENABLED'] = 'true' os.environ['LANGSMITH_OTEL_ONLY'] = 'true' os.environ['LANGSMITH_TRACING'] = 'true' from langchain.agents import create_agent logfire.configure() def add(a: float, b: float) -> float: """Add two numbers.""" return a + b math_agent = create_agent('openai:gpt-5-mini', tools=[add], name='math_agent') result = math_agent.invoke({'messages': [{'role': 'user', 'content': "what's 123 + 456?"}]}) print(result['messages'][-1].content) ``` -------------------------------- ### Install Logfire Node.js Package Source: https://pydantic.dev/docs/logfire/integrations/javascript/vercel-ai/index Install the necessary packages for standalone Node.js scripts. Replace `@ai-sdk/your-provider` with your specific AI provider. ```bash npm install @pydantic/logfire-node ai @ai-sdk/your-provider ``` -------------------------------- ### Install Logfire with Redis extra Source: https://pydantic.dev/docs/logfire/integrations/databases/redis/index Install the logfire package with the redis extra to enable Redis instrumentation. ```bash pip install 'logfire[redis]' ``` -------------------------------- ### Install Uvicorn for Running Starlette App Source: https://pydantic.dev/docs/logfire/integrations/web-frameworks/starlette/index Install Uvicorn, a high-performance ASGI server, to run your Starlette application. ```bash pip install uvicorn ``` -------------------------------- ### Install Logfire with System Metrics Extra Source: https://pydantic.dev/docs/logfire/integrations/system-metrics/index Install the logfire package with the system-metrics extra to enable system metric collection. This can be done using pip or uv. ```bash pip install 'logfire[system-metrics]' ``` ```bash uv add 'logfire[system-metrics]' ``` -------------------------------- ### Install Vercel OTEL for Next.js Source: https://pydantic.dev/docs/logfire/integrations/javascript/vercel-ai/index Install the Vercel OpenTelemetry package and AI SDK for Next.js applications. Adjust `@ai-sdk/your-provider` as needed. ```bash npm install @vercel/otel @opentelemetry/api ai @ai-sdk/your-provider ``` -------------------------------- ### Install OpenFeature Web SDK and OFREP Provider Source: https://pydantic.dev/docs/logfire/manage/client-side-feature-flags/index Install the necessary packages for using OpenFeature with the OFREP provider in your web application. ```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 ``` -------------------------------- ### Install Logfire with SQLite3 Extra using uv Source: https://pydantic.dev/docs/logfire/integrations/databases/sqlite3/index Install the logfire package with the sqlite3 extra using the uv package manager. ```bash uv add 'logfire[sqlite3]' ``` -------------------------------- ### Install Logfire with SQLAlchemy extra Source: https://pydantic.dev/docs/logfire/integrations/databases/sqlalchemy/index Install the logfire package with the sqlalchemy extra to enable SQLAlchemy instrumentation. ```bash pip install 'logfire[sqlalchemy]' ``` -------------------------------- ### Install Logfire with AIOHTTP Client Extra Source: https://pydantic.dev/docs/logfire/integrations/http-clients/aiohttp/index Install the logfire package with the 'aiohttp-client' extra to enable aiohttp client instrumentation. This can be done using pip or uv. ```bash pip install 'logfire[aiohttp-client]' ``` ```bash uv add 'logfire[aiohttp-client]' ``` -------------------------------- ### Install Logfire with Asyncpg Extra Source: https://pydantic.dev/docs/logfire/integrations/databases/asyncpg/index Install the logfire package with the asyncpg extra dependency using pip. ```bash pip install 'logfire[asyncpg]' ``` -------------------------------- ### Install Logfire with FastAPI extra using uv Source: https://pydantic.dev/docs/logfire/integrations/web-frameworks/fastapi/index Install the logfire package with the fastapi extra using the 'uv' package manager. ```bash uv add 'logfire[fastapi]' ``` -------------------------------- ### Install Logfire with Redis extra using uv Source: https://pydantic.dev/docs/logfire/integrations/databases/redis/index Install the logfire package with the redis extra using the uv package manager. ```bash uv add 'logfire[redis]' ``` -------------------------------- ### Install Logfire with PyMongo Extra Source: https://pydantic.dev/docs/logfire/integrations/databases/pymongo/index Install the logfire package with the 'pymongo' extra to enable PyMongo instrumentation. ```bash pip install 'logfire[pymongo]' ``` ```bash uv add 'logfire[pymongo]' ``` -------------------------------- ### NodeJS: Install Dependencies and Run Source: https://pydantic.dev/docs/logfire/guides/alternative-clients/index Commands to install necessary OpenTelemetry packages for NodeJS and run the main script. Ensure environment variables are set for export. ```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 ``` -------------------------------- ### Install Logfire with MySQL extra using uv Source: https://pydantic.dev/docs/logfire/integrations/databases/mysql/index Install the logfire package with the 'mysql' extra using the 'uv' package manager. ```bash uv add 'logfire[mysql]' ``` -------------------------------- ### Install Logfire SDK with Datasets Extra Source: https://pydantic.dev/docs/logfire/evaluate/datasets/sdk/index Install the Logfire SDK with the `datasets` extra to include `httpx` and `pydantic-evals` dependencies. Python 3.10+ is required. ```bash pip install 'logfire[datasets]' ``` -------------------------------- ### Install logfire with WSGI extra using uv Source: https://pydantic.dev/docs/logfire/integrations/web-frameworks/wsgi/index Install the logfire package with the `wsgi` extra using the `uv` package manager. ```bash uv add 'logfire[wsgi]' ``` -------------------------------- ### Install Logfire with Psycopg Extra Source: https://pydantic.dev/docs/logfire/integrations/databases/psycopg/index Install the 'logfire' package with the 'psycopg' extra to enable Psycopg 3 integration. ```bash pip install 'logfire[psycopg]' ``` -------------------------------- ### Install Logfire with SQLAlchemy extra using uv Source: https://pydantic.dev/docs/logfire/integrations/databases/sqlalchemy/index Install the logfire package with the sqlalchemy extra using the uv package manager. ```bash uv add 'logfire[sqlalchemy]' ``` -------------------------------- ### Install Logfire Node.js Package Source: https://pydantic.dev/docs/logfire/integrations/javascript/node/index Install the Logfire Node.js package and initialize an ES6 project. Ensure your package.json has `type: module` for ES6 support. ```sh mkdir test-logfire-js cd test-logfire-js npm init -y es6 npm install @pydantic/logfire-node ``` -------------------------------- ### Install Pydantic Skills CLI Source: https://pydantic.dev/docs/logfire/guides/skills/index Install the Pydantic skills and plugins using the `skills` CLI. This makes them available to Claude Code and other agents. ```bash npx skills install pydantic/skills ``` -------------------------------- ### Install Logfire with Starlette Extra using uv Source: https://pydantic.dev/docs/logfire/integrations/web-frameworks/starlette/index Install the logfire package with the starlette extra using the uv package manager. ```bash uv add 'logfire[starlette]' ``` -------------------------------- ### Install LiteLLM with uv Source: https://pydantic.dev/docs/logfire/integrations/llms/litellm/index Install the logfire package with the litellm extra using uv. This command adds logfire and its LiteLLM dependencies to your project. ```bash uv add 'logfire[litellm]' ``` -------------------------------- ### Stripe Client Initialization and Request Examples Source: https://pydantic.dev/docs/logfire/integrations/stripe/index Demonstrates initializing the StripeClient and making both synchronous and asynchronous requests. This serves as a baseline before applying Logfire instrumentation. ```python from stripe import StripeClient client = StripeClient(api_key='') # Synchronous request client.customers.list() # uses `requests` # Asynchronous request async def main(): await client.customers.list_async() # uses `httpx` if __name__ == '__main__': import asyncio asyncio.run(main()) ``` -------------------------------- ### Configure and Instrument DSPy with Logfire Source: https://pydantic.dev/docs/logfire/integrations/llms/dspy/index Configure Logfire and then instrument DSPy to start capturing telemetry. This setup involves initializing Logfire and then calling logfire.instrument_dspy(). ```python import dspy import logfire logfire.configure() logfire.instrument_dspy() lm = dspy.LM('openai/gpt-5-mini') dspy.configure(lm=lm) class ExtractInfo(dspy.Signature): """Extract structured information from text.""" text: str = dspy.InputField() title: str = dspy.OutputField() headings: list[str] = dspy.OutputField() entities: list[dict[str, str]] = dspy.OutputField(desc='a list of entities and their metadata') module = dspy.Predict(ExtractInfo) text = ( 'Apple Inc. announced its latest iPhone 14 today. ' 'The CEO, Tim Cook, highlighted its new features in a press release.' ) response = module(text=text) print(response.title) print(response.headings) print(response.entities) ``` -------------------------------- ### Start Tilt with Logfire Configuration Source: https://pydantic.dev/docs/logfire/deploy/self-hosted-deployment/local-quickstart/index Command to launch Tilt with the configured Logfire deployment. Ensure required environment variables are set before running. ```bash LOGFIRE_EMAIL= \ LOGFIRE_KEY_PATH="$(pwd)/key.json" \ LOGFIRE_ADMIN_EMAIL= \ tilt up ``` -------------------------------- ### Basic Usage of Requests Instrumentation Source: https://pydantic.dev/docs/logfire/integrations/http-clients/requests/index Configure Logfire and instrument the requests library. This example shows how to make a GET request after instrumentation, which will be logged by Logfire. ```python import requests import logfire logfire.configure() logfire.instrument_requests() requests.get('https://httpbin.org/get') ``` -------------------------------- ### Logfire Redis Integration Example Source: https://pydantic.dev/docs/logfire/integrations/databases/redis/index Demonstrates setting up Logfire and instrumenting Redis clients for both synchronous and asynchronous operations. Ensure the Redis server is running before executing. ```python import redis import logfire logfire.configure() logfire.instrument_redis() client = redis.StrictRedis(host='localhost', port=6379) client.set('my-key', 'my-value') async def main(): client = redis.asyncio.Redis(host='localhost', port=6379) await client.get('my-key') if __name__ == '__main__': import asyncio asyncio.run(main()) ``` -------------------------------- ### Trace Modules Not in Standard Library Source: https://pydantic.dev/docs/logfire/instrument/add-auto-tracing/index Use a custom function with `install_auto_tracing` to dynamically select modules. This example traces modules not part of the standard Python installation. ```python import pathlib import logfire PYTHON_LIB_ROOT = str(pathlib.Path(pathlib.__file__).parent) def should_trace(module: logfire.AutoTraceModule) -> bool: return not module.filename.startswith(PYTHON_LIB_ROOT) logfire.install_auto_tracing(should_trace, min_duration=0) ``` -------------------------------- ### Tool-Calling Scenario Example Source: https://pydantic.dev/docs/logfire/prompt-management/scenarios/index Demonstrates how to represent tool calls and their returns within a scenario. String fields within `args` and `content` are templated. ```text Role: assistant Tool call: tool_name = fetch_weather tool_call_id = call_001 args = { "city": "{{city}}" } Role: tool Tool return: tool_name = fetch_weather tool_call_id = call_001 content = { "temp_c": 19, "conditions": "{{weather_summary}}" } ``` -------------------------------- ### OpenFeature Client Default Value Handling Source: https://pydantic.dev/docs/logfire/manage/managed-variables/external/index Example using the OpenFeature Web SDK to get a string value, providing a default ('light') if the server returns null. ```typescript const client = OpenFeature.getClient(); // The second argument is used when the server returns value: null const theme = await client.getStringValue('ui_theme', 'light'); ``` -------------------------------- ### Rust: Project Setup and Environment Variables Source: https://pydantic.dev/docs/logfire/guides/alternative-clients/index Initializes a new Rust Cargo project and sets environment variables for OpenTelemetry OTLP export. Requires updating Cargo.toml and main.rs. ```sh cargo new --bin otel-example && cd otel-example export OTEL_EXPORTER_OTLP_ENDPOINT=https://logfire-us.pydantic.dev export OTEL_EXPORTER_OTLP_HEADERS='Authorization=your-write-token' ``` -------------------------------- ### Instrument FastAPI with Logfire and Configure Sampling Source: https://pydantic.dev/docs/logfire/instrument/sampling/index Instruments a FastAPI application with Logfire and configures tail sampling with a specific duration threshold. This example demonstrates how to handle background tasks that might start after the root span has ended. ```python import uvicorn from fastapi import BackgroundTasks, FastAPI import logfire app = FastAPI() logfire.configure( sampling=logfire.SamplingOptions.level_or_duration( duration_threshold=0.1, ), ) logfire.instrument_fastapi(app) async def background_task(): # This will be included even if the root span was excluded. logfire.info('background') @app.get('/') async def index(background_tasks: BackgroundTasks): # Uncomment to prevent request span from being sampled out. # await asyncio.sleep(0.2) background_tasks.add_task(background_task) return {} uvicorn.run(app) ``` -------------------------------- ### Install Logfire with LiteLLM Extra Source: https://pydantic.dev/docs/logfire/integrations/llms/litellm/index Install the logfire package with the litellm extra to enable LiteLLM integration. This command installs logfire and its dependencies for LiteLLM. ```bash pip install 'logfire[litellm]' ``` -------------------------------- ### Install Logfire with Conda Source: https://pydantic.dev/docs/logfire/integrations/pytest/index Install the logfire package from the conda-forge channel. ```bash conda install -c conda-forge logfire ``` -------------------------------- ### Start Gunicorn with Configuration Source: https://pydantic.dev/docs/logfire/integrations/web-frameworks/gunicorn/index Run Gunicorn with your WSGI application and specify the configuration file containing the `post_fork` hook. ```bash gunicorn myapp:app --config gunicorn_config.py ``` -------------------------------- ### Install Logfire with Pip Source: https://pydantic.dev/docs/logfire/integrations/pytest/index Install the logfire package using pip. This includes the pytest plugin. ```bash pip install logfire ``` -------------------------------- ### Instrument LiteLLM Calls with Logfire Source: https://pydantic.dev/docs/logfire/integrations/llms/litellm/index Configure Logfire and instrument LiteLLM calls. This example shows how to set up Logfire, enable LiteLLM instrumentation, and make a sample completion call. It's recommended to pass arguments as keyword arguments for best results. ```python import litellm import logfire logfire.configure() logfire.instrument_litellm() response = litellm.completion( model='gpt-5-mini', messages=[{'role': 'user', 'content': 'Hi'}], ) print(response.choices[0].message.content) #> Hello! How can I assist you today? ``` -------------------------------- ### Example API Response Source: https://pydantic.dev/docs/logfire/manage/use-api-keys/index A successful API request to list projects will return a JSON array containing project details. ```json [ { "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "project_name": "my-project", "created_at": "2024-05-24T11:18:22.704455Z", "description": null, "organization_name": "my-organization", "visibility": "public" } ] ``` -------------------------------- ### Install Logfire with Flask Extra Source: https://pydantic.dev/docs/logfire/integrations/web-frameworks/flask/index Install the logfire package with the flask extra using pip. ```bash pip install 'logfire[flask]' ``` -------------------------------- ### Install Logfire and Dotenv Source: https://pydantic.dev/docs/logfire/integrations/javascript/express/index Installs the necessary packages for Logfire integration and environment variable management. ```bash npm install logfire dotenv ``` -------------------------------- ### Install Logfire with Starlette Extra Source: https://pydantic.dev/docs/logfire/integrations/web-frameworks/starlette/index Install the logfire package with the starlette extra to enable Starlette integration. ```bash pip install 'logfire[starlette]' ``` -------------------------------- ### Tiltfile for Logfire Local Deployment Source: https://pydantic.dev/docs/logfire/deploy/self-hosted-deployment/local-quickstart/index Use this Tiltfile to automate the Logfire setup with Kubernetes. Configure Docker registry details and Helm chart parameters via environment variables. ```python load('ext://secret', 'secret_yaml_registry') load('ext://helm_resource', 'helm_resource', 'helm_repo') update_settings ( max_parallel_updates = 3 , k8s_upsert_timeout_secs = 600 , suppress_unused_image_warnings = None ) k8s_yaml(secret_yaml_registry("logfire-image-key", flags_dict = { 'docker-server': 'us-docker.pkg.dev', 'docker-username': '_json_key', 'docker-email': os.getenv('LOGFIRE_EMAIL'), 'docker-password': read_file(os.getenv('LOGFIRE_KEY_PATH')) })) helm_repo('pydantic', 'https://charts.pydantic.dev/') helm_resource('logfire', 'pydantic/logfire', flags=[ '--set=adminEmail=' + os.getenv('LOGFIRE_ADMIN_EMAIL'), '--set=imagePullSecrets[0]=logfire-image-key', '--set=dev.deployPostgres=true', '--set=dev.deployMinio=true', '--set=dev.deployMaildev=true', '--set=objectStore.uri=s3://logfire', '--set=objectStore.env.AWS_ACCESS_KEY_ID=logfire-minio', '--set=objectStore.env.AWS_SECRET_ACCESS_KEY=logfire-minio', '--set=objectStore.env.AWS_ENDPOINT=http://logfire-minio:9000', '--set=objectStore.env.AWS_ALLOW_HTTP=true', '--set="ingress.hostnames[0]=localhost:8080"', ], links=[link('http://localhost:1080', 'maildev')], ) k8s_resource( workload='logfire', port_forwards=[ port_forward(8080, 8080, name='logfire'), ], extra_pod_selectors=[ {'app.kubernetes.io/component': 'logfire-service'}, ], discovery_strategy='selectors-only', ) local_resource( 'maildev-portforward', serve_cmd='kubectl port-forward svc/logfire-maildev 1080:1080', deps=['logfire'], allow_parallel=True, ) ``` -------------------------------- ### Example: Text Generation with Tools and Telemetry Source: https://pydantic.dev/docs/logfire/integrations/javascript/vercel-ai/index A complete example demonstrating text generation with a tool, including enabling telemetry. This showcases how to define tools with input schemas and execution logic. ```typescript import { generateText, tool } from "ai"; import { yourProvider } from "@ai-sdk/your-provider"; import { z } from "zod"; const result = await generateText({ model: yourProvider("model-name"), experimental_telemetry: { isEnabled: true }, tools: { weather: tool({ description: "Get the weather in a location", inputSchema: z.object({ location: z.string().describe("The location to get the weather for"), }), execute: async ({ location }) => ({ location, temperature: 72 + Math.floor(Math.random() * 21) - 10, }), }), }, prompt: "What is the weather in San Francisco?", }); console.log(result.text); ``` -------------------------------- ### Install Logfire with AWS Lambda Extra Source: https://pydantic.dev/docs/logfire/integrations/aws-lambda/index Install the logfire package with the aws-lambda extra using pip. ```bash pip install 'logfire[aws-lambda]' ``` -------------------------------- ### Run Redis Server using Docker Source: https://pydantic.dev/docs/logfire/integrations/databases/redis/index Start a Redis server instance using Docker for local development and testing. ```bash docker run --name redis -p 6379:6379 -d redis:latest ```