### Minimal AIOHTTP Server with Logfire Instrumentation Source: https://github.com/pydantic/logfire/blob/main/docs/integrations/web-frameworks/aiohttp.md This example demonstrates a basic AIOHTTP server setup instrumented with Logfire. Ensure logfire is configured and aiohttp server instrumentation is enabled before defining routes. ```python from aiohttp import web import logfire logfire.configure() logfire.instrument_aiohttp_server() async def hello(request): return web.Response(text='Hello, World!') async def user_handler(request): user_id = request.match_info['user_id'] return web.json_response({'user_id': user_id, 'message': 'User profile'}) app = web.Application() app.router.add_get('/', hello) app.router.add_get('/users/{user_id}', user_handler) if __name__ == '__main__': web.run_app(app, host='localhost', port=8080) ``` -------------------------------- ### Install React SDK Source: https://github.com/pydantic/logfire/blob/main/docs/how-to-guides/client-side-feature-flags.md 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 ``` -------------------------------- ### Python: Install and Configure OTLP Exporter Source: https://github.com/pydantic/logfire/blob/main/docs/how-to-guides/alternative-clients.md Installs the OTLP exporter and sets environment variables for the Logfire endpoint and authorization token. This is the initial setup for exporting Python traces. ```sh pip install opentelemetry-exporter-otlp export OTEL_EXPORTER_OTLP_ENDPOINT=https://logfire-us.pydantic.dev export OTEL_EXPORTER_OTLP_HEADERS='Authorization=your-write-token' ``` -------------------------------- ### Install Python Requests Library Source: https://github.com/pydantic/logfire/blob/main/docs/reference/self-hosted/examples.md Install the 'requests' library using pip. This is a prerequisite for the Python example that interacts with the Logfire API. ```bash python -m pip install requests ``` -------------------------------- ### Install Uvicorn Source: https://github.com/pydantic/logfire/blob/main/docs/integrations/web-frameworks/starlette.md Install Uvicorn, a necessary ASGI server to run the Starlette application. ```bash pip install uvicorn ``` -------------------------------- ### Example CHANGELOG.md Entry Source: https://github.com/pydantic/logfire/blob/main/release/README.md An example of how to format a version tag and comparison link in the CHANGELOG.md file. ```markdown [v1.0.1]: https://github.com/pydantic/logfire/compare/v1.0.0...v1.0.1 ``` -------------------------------- ### Install LlamaIndex Instrumentation Source: https://github.com/pydantic/logfire/blob/main/docs/integrations/llms/llamaindex.md Install the opentelemetry-instrumentation-llamaindex package using pip. ```bash pip install opentelemetry-instrumentation-llamaindex ``` -------------------------------- ### LangGraph Example with Logfire Integration Source: https://github.com/pydantic/logfire/blob/main/docs/integrations/llms/langchain.md A complete example demonstrating how to configure Logfire and use LangGraph with OpenTelemetry tracing enabled. This setup allows Logfire to capture traces from LangChain agents. ```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 with WSGI extra Source: https://github.com/pydantic/logfire/blob/main/docs/integrations/web-frameworks/wsgi.md Install logfire with the 'wsgi' extra to enable WSGI instrumentation. ```bash pip install "logfire[wsgi]" ``` -------------------------------- ### NodeJS: Install Dependencies and Run Source: https://github.com/pydantic/logfire/blob/main/docs/how-to-guides/alternative-clients.md Commands to set environment variables for OTLP export, initialize a package.json for module support, install the OpenTelemetry SDK, and run the main JavaScript file. ```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 and Send First Span Source: https://github.com/pydantic/logfire/blob/main/docs/guides/web-ui/services.md Install the Logfire Python SDK, set the necessary environment variables, and send an initial info log to see your service appear in the Logfire UI. Ensure OTEL_SERVICE_NAME is set. ```bash pip install logfire export LOGFIRE_TOKEN= export OTEL_SERVICE_NAME=cart python -c "import logfire; logfire.configure(); logfire.info('hi')" ``` -------------------------------- ### Install Logfire with Asyncpg Extra Source: https://github.com/pydantic/logfire/blob/main/docs/integrations/databases/asyncpg.md Install the logfire package with the asyncpg extra to enable asyncpg instrumentation. ```bash pip install logfire[asyncpg] ``` -------------------------------- ### Install Logfire with System Metrics Extra Source: https://github.com/pydantic/logfire/blob/main/docs/integrations/system-metrics.md Install the logfire package with the 'system-metrics' extra to enable system metric collection. ```bash pip install logfire[system-metrics] ``` -------------------------------- ### Example Backing Managed Variable Source: https://github.com/pydantic/logfire/blob/main/docs/reference/advanced/prompt-management/concepts.md An example illustrating the backing variable name for a prompt with the slug 'welcome-email'. This variable is used for managing labels and rollout rules. ```text prompt__welcome_email ``` -------------------------------- ### Logfire Basic Configuration and OpenAI Instrumentation Source: https://github.com/pydantic/logfire/blob/main/docs/comparisons/arize-phoenix.md This snippet shows the minimal setup required to start observing AI calls with full application context using Logfire. It configures Logfire and instruments OpenAI calls. ```python import logfire logfire.configure() logfire.instrument_openai() ``` -------------------------------- ### Install OpenFeature SDK and OFREP Provider Source: https://github.com/pydantic/logfire/blob/main/docs/how-to-guides/client-side-feature-flags.md Install the necessary Python packages for the OpenFeature SDK and the OFREP provider using pip. ```bash pip install openfeature-sdk openfeature-provider-ofrep ``` -------------------------------- ### Install Logfire with FastAPI and Run Uvicorn Source: https://github.com/pydantic/logfire/blob/main/docs/why.md Install the 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)! ``` -------------------------------- ### Start Gunicorn with Configuration Source: https://github.com/pydantic/logfire/blob/main/docs/integrations/web-frameworks/gunicorn.md Command to start Gunicorn with a specified configuration file. Replace 'myapp:app' with your WSGI application and 'gunicorn_config.py' with your config file name. ```bash gunicorn myapp:app --config gunicorn_config.py ``` -------------------------------- ### Install Dependencies Source: https://github.com/pydantic/logfire/blob/main/docs/integrations/llms/mcp.md Install the necessary Python packages for MCP and Pydantic AI with OpenAI support. ```bash pip install mcp 'pydantic-ai-slim[openai]' ``` -------------------------------- ### Install Logfire and Claude Agent SDK Source: https://github.com/pydantic/logfire/blob/main/docs/integrations/llms/claude-agent-sdk.md Install the necessary packages for Logfire and the Claude Agent SDK. ```bash pip install logfire claude-agent-sdk ``` -------------------------------- ### Install logfire with Psycopg extra Source: https://github.com/pydantic/logfire/blob/main/docs/integrations/databases/psycopg.md Install logfire with the 'psycopg' extra to include Psycopg support. ```bash pip install logfire[psycopg] ``` -------------------------------- ### Install Logfire SDK Source: https://github.com/pydantic/logfire/blob/main/README.md Install the Logfire Python SDK using pip. This is the first step to using Logfire in your project. ```bash pip install logfire ``` -------------------------------- ### Install OpenFeature SDK and OFREP Provider with npm Source: https://github.com/pydantic/logfire/blob/main/docs/how-to-guides/client-side-feature-flags.md Use npm to install the necessary packages for the OpenFeature Web SDK and the OFREP provider in your project. ```bash npm install @openfeature/web-sdk @openfeature/ofrep-web-provider ``` -------------------------------- ### Install Logfire with Redis Extra Source: https://github.com/pydantic/logfire/blob/main/docs/integrations/databases/redis.md Install the logfire package with the 'redis' extra to enable Redis instrumentation. ```bash pip install logfire[redis] ``` -------------------------------- ### Install Logfire SDK with Datasets Extra Source: https://github.com/pydantic/logfire/blob/main/docs/evaluate/datasets/sdk.md Install the Logfire SDK with the `datasets` extra to include `httpx` and `pydantic-evals` dependencies. ```bash pip install 'logfire[datasets]' ``` -------------------------------- ### Install Logfire Gateway and Launch AI Tool Source: https://github.com/pydantic/logfire/blob/main/docs/reference/advanced/gateway/index.md Install the gateway package and launch a supported AI coding tool like Claude. Alternatively, run the proxy with `logfire gateway serve` and configure tools manually. ```bash pip install "logfire[gateway]" logfire gateway launch claude ``` -------------------------------- ### Install logfire with Psycopg2 extra Source: https://github.com/pydantic/logfire/blob/main/docs/integrations/databases/psycopg.md Install logfire with the 'psycopg2' extra to include Psycopg2 support. ```bash pip install logfire[psycopg2] ``` -------------------------------- ### Install Logfire with OpenAI Source: https://github.com/pydantic/logfire/blob/main/docs/guides/web-ui/llms.md Install the Logfire package with OpenAI support and set the necessary environment variable for authentication. ```bash pip install 'logfire[openai]' export LOGFIRE_TOKEN= ``` -------------------------------- ### Install Logfire with MySQL extra Source: https://github.com/pydantic/logfire/blob/main/docs/integrations/databases/mysql.md Install the logfire package with the necessary extras for MySQL integration. ```bash pip install "logfire[mysql]" ``` -------------------------------- ### Install Logfire Helm Chart Source: https://github.com/pydantic/logfire/blob/main/docs/reference/self-hosted/local-quickstart.md Installs the Logfire Helm chart using development values and updates Helm repositories. ```bash helm repo add pydantic https://charts.pydantic.dev/ helm repo update helm pull pydantic/logfire --untar helm upgrade --install logfire ./logfire \ -f ./logfire/values.dev.yaml \ --namespace logfire ``` -------------------------------- ### Install Logfire and Configure Token Source: https://github.com/pydantic/logfire/blob/main/docs/guides/web-ui/metrics-explorer.md Install the Logfire Python SDK and set the LOGFIRE_TOKEN environment variable to your write token. This is necessary to send metrics to your project. ```bash pip install logfire export LOGFIRE_TOKEN= ``` -------------------------------- ### Install Logfire with DSPy Extra Source: https://github.com/pydantic/logfire/blob/main/docs/integrations/llms/dspy.md Install the logfire package with the 'dspy' extra and the dspy package itself. This is a prerequisite for instrumenting DSPy. ```bash pip install dspy-ai ``` -------------------------------- ### Install Logfire with FastAPI Extra Source: https://github.com/pydantic/logfire/blob/main/docs/integrations/web-frameworks/fastapi.md Install the logfire package with the 'fastapi' extra to include necessary dependencies for FastAPI integration. ```bash pip install logfire[fastapi] ``` -------------------------------- ### Install OpenFeature SDK and OFREP Provider with pnpm Source: https://github.com/pydantic/logfire/blob/main/docs/how-to-guides/client-side-feature-flags.md Use pnpm to install the necessary packages for the OpenFeature Web SDK and the OFREP provider in your project. ```bash pnpm add @openfeature/web-sdk @openfeature/ofrep-web-provider ``` -------------------------------- ### Install Logfire with AIOHTTP Server Extra Source: https://github.com/pydantic/logfire/blob/main/docs/integrations/web-frameworks/aiohttp.md Install the logfire package with the 'aiohttp-server' extra to include necessary dependencies for AIOHTTP server instrumentation. ```bash pip install logfire[aiohttp-server] ``` -------------------------------- ### Install OpenFeature SDK and OFREP Provider with yarn Source: https://github.com/pydantic/logfire/blob/main/docs/how-to-guides/client-side-feature-flags.md Use yarn to install the necessary packages for the OpenFeature Web SDK and the OFREP provider in your project. ```bash yarn add @openfeature/web-sdk @openfeature/ofrep-web-provider ``` -------------------------------- ### Run MongoDB on Docker Source: https://github.com/pydantic/logfire/blob/main/docs/integrations/databases/pymongo.md Start a MongoDB instance using Docker for local development or testing. ```bash docker run --name mongo -p 27017:27017 -d mongo:latest ``` -------------------------------- ### Install Logfire Skill using Skills CLI Source: https://github.com/pydantic/logfire/blob/main/docs/how-to-guides/skills.md Install the Logfire skill using the skills CLI, which allows picking individual skills like 'logfire-instrumentation' or 'logfire-query'. This works with multiple agents via the agentskills.io standard. ```bash npx skills add pydantic/skills ``` -------------------------------- ### Full Example: Initialization, Context, and Evaluation Source: https://github.com/pydantic/logfire/blob/main/docs/how-to-guides/client-side-feature-flags.md Demonstrates how to initialize the OpenFeature SDK with a provider, set user context, and evaluate feature flags within your 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`, 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), } } ``` -------------------------------- ### Basic FastAPI App with Logfire Source: https://github.com/pydantic/logfire/blob/main/docs/integrations/web-frameworks/fastapi.md A minimal FastAPI application instrumented with Logfire. Ensure Uvicorn is installed to run this example. ```python from fastapi import FastAPI import logfire app = FastAPI() logfire.configure() logfire.instrument_fastapi(app) @app.get('/hello') async def hello(name: str): return {'message': f'hello {name}'} if __name__ == '__main__': import uvicorn uvicorn.run(app) ``` -------------------------------- ### NodeJS: Setup and Trace Export Source: https://github.com/pydantic/logfire/blob/main/docs/how-to-guides/alternative-clients.md Sets up the OpenTelemetry Node.js SDK with an OTLPTraceExporter and BatchSpanProcessor to export a 'Hello World' trace. Requires environment variables to be set separately. ```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); ``` -------------------------------- ### Logfire Psycopg Integration & Setup Guide Source: https://github.com/pydantic/logfire/blob/main/docs/integrations/databases/psycopg.md Instrument Psycopg and Psycopg2 operations with OpenTelemetry Psycopg. Capture queries, duration, and context with logfire.instrument_psycopg(). ```APIDOC ## Psycopg Integration ### Description The `logfire.instrument_psycopg()` function instruments the Psycopg PostgreSQL driver (both `psycopg2` and `psycopg` v3) with Logfire, enabling the capture of queries, duration, and context. ### Method `logfire.instrument_psycopg()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import psycopg import logfire logfire.configure() # Instrument the whole module (psycopg and/or psycopg2) logfire.instrument_psycopg() # Or instrument a specific connection connection = psycopg.connect('dbname=database user=user password=secret host=0.0.0.0 port=5432') logfire.instrument_psycopg(connection) with logfire.span('Create table and insert data'), connection.cursor() as cursor: cursor.execute('CREATE TABLE IF NOT EXISTS test (id serial PRIMARY KEY, num integer, data varchar);') cursor.execute('INSERT INTO test (num, data) VALUES (%s, %s)', (100, 'abc')) cursor.execute('SELECT * FROM test') ``` ### Response #### Success Response (200) No direct response body for this instrumentation function. Successful instrumentation leads to captured telemetry data. #### Response Example None ``` -------------------------------- ### Capture Specific Server Request Headers Source: https://github.com/pydantic/logfire/blob/main/docs/integrations/web-frameworks/index.md Configure environment variables to capture specific request headers by name or pattern. This example captures 'content-type' and any header starting with 'X-'. ```shell OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST="content-type,X-.*" ``` -------------------------------- ### Rust: Project Setup and Environment Variables Source: https://github.com/pydantic/logfire/blob/main/docs/how-to-guides/alternative-clients.md Commands to create a new Rust binary project, navigate into it, and set environment variables for the OpenTelemetry OTLP exporter endpoint and authorization headers. ```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' ``` -------------------------------- ### Query Records with pandas Source: https://github.com/pydantic/logfire/blob/main/docs/how-to-guides/query-api.md Integrate Logfire's DB API with pandas to read query results directly into a DataFrame. This example assumes pandas is installed and requires your read token. ```python import pandas as pd import logfire.db_api conn = logfire.db_api.connect(read_token='') df = pd.read_sql('SELECT start_timestamp, message FROM records LIMIT 100', conn) print(df) conn.close() ``` -------------------------------- ### Install Logfire with LiteLLM Extra Source: https://github.com/pydantic/logfire/blob/main/docs/integrations/llms/litellm.md Install the logfire package with the 'litellm' extra to enable LiteLLM instrumentation. This command installs logfire and its dependencies for LiteLLM. ```bash pip install "logfire[litellm]" ``` -------------------------------- ### Setup PostgreSQL Database Using Docker Source: https://github.com/pydantic/logfire/blob/main/docs/integrations/databases/asyncpg.md This command initializes a PostgreSQL database using Docker. It sets the user, password, and database name, and maps the default PostgreSQL port. ```bash docker run --name postgres \ -e POSTGRES_USER=user \ -e POSTGRES_PASSWORD=secret \ -e POSTGRES_DB=database \ -p 5432:5432 \ -d postgres ``` -------------------------------- ### Install Logfire with Starlette Extra Source: https://github.com/pydantic/logfire/blob/main/docs/integrations/web-frameworks/starlette.md Install logfire with the starlette extra to enable Starlette integration. ```bash pip install "logfire[starlette]" ``` -------------------------------- ### Install Logfire with Celery Extra Source: https://github.com/pydantic/logfire/blob/main/docs/integrations/event-streams/celery.md Install logfire with the celery extra to enable Celery integration. ```bash pip install logfire[celery] ``` -------------------------------- ### Instrument OpenAI Agents with Function Tools Source: https://github.com/pydantic/logfire/blob/main/docs/integrations/llms/openai.md This example demonstrates instrumenting OpenAI agents that utilize function tools. It also shows how to instrument httpx clients used within the agent's context. ```python from agents import Agent, RunContextWrapper, Runner, function_tool from httpx import AsyncClient from typing_extensions import TypedDict import logfire logfire.configure() logfire.instrument_openai_agents() class Location(TypedDict): lat: float long: float @function_tool async def fetch_weather(ctx: RunContextWrapper[AsyncClient], location: Location) -> str: """Fetch the weather for a given location. Args: ctx: Run context object. location: The location to fetch the weather for. """ r = await ctx.context.get('https://httpbin.org/get', params=location) return 'sunny' if r.status_code == 200 else 'rainy' agent = Agent(name='weather agent', tools=[fetch_weather]) async def main(): async with AsyncClient() as client: logfire.instrument_httpx(client) result = await Runner.run(agent, 'Get the weather at lat=51 lng=0.2', context=client) print(result.final_output) if __name__ == '__main__': import asyncio asyncio.run(main()) ``` -------------------------------- ### Install Logfire with PyMongo Extra Source: https://github.com/pydantic/logfire/blob/main/docs/integrations/databases/pymongo.md Install the logfire package with the necessary extra for PyMongo integration. ```bash pip install logfire[pymongo] ``` -------------------------------- ### Create and Read Project Token Source: https://github.com/pydantic/logfire/blob/main/docs/reference/cli.md This command creates a read token for a specified project and prints it to standard output. It composes well with other tools for configuration. ```bash logfire read-tokens --project / create ``` ```bash claude mcp add logfire -e LOGFIRE_READ_TOKEN=$(logfire read-tokens --project / create) -- uvx logfire-mcp@latest ``` -------------------------------- ### Set Current Project Source: https://github.com/pydantic/logfire/blob/main/docs/reference/cli.md Use this command to switch to an already created project. Replace `` with the name of the project you want to use. ```bash logfire projects use ``` ```bash logfire projects use backend ``` -------------------------------- ### Logfire PyMongo Usage Example (Sync) Source: https://github.com/pydantic/logfire/blob/main/docs/integrations/databases/pymongo.md Example of how to use Logfire with a synchronous PyMongo client. ```APIDOC ```python skip-run="true" skip-reason="external-connection" from pymongo import MongoClient import logfire logfire.configure() logfire.instrument_pymongo() client = MongoClient() db = client['database'] collection = db['collection'] collection.insert_one({'name': 'MongoDB'}) collection.find_one() ``` ``` -------------------------------- ### Configure Managed Variables with Aliases Source: https://github.com/pydantic/logfire/blob/main/docs/reference/advanced/managed-variables/configuration-reference.md Example of defining managed variables locally using VariableConfig and VariablesConfig. Demonstrates how to set up aliases for zero-downtime variable migrations. ```python from logfire.variables.config import VariableConfig, VariablesConfig config = VariablesConfig( variables={ 'support_agent_config': VariableConfig( name='support_agent_config', labels={...}, latest_version=LatestVersion(...), rollout=Rollout(labels={...}), overrides=[], # Old name resolves to this variable aliases=['agent_config'], ), } ) ``` -------------------------------- ### Install Logfire with SQLAlchemy Extra Source: https://github.com/pydantic/logfire/blob/main/docs/integrations/databases/sqlalchemy.md Install the logfire package with the sqlalchemy extra to enable SQLAlchemy integration. ```bash pip install logfire[sqlalchemy] ``` -------------------------------- ### Tool-Calling Scenario Example Source: https://github.com/pydantic/logfire/blob/main/docs/reference/advanced/prompt-management/scenarios.md Demonstrates how to represent tool-calling exchanges within a scenario using 'assistant' and 'tool' roles with 'tool-call' and 'tool-return' parts. String fields within JSON values 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}}" } ``` -------------------------------- ### Example Safety Rules Text Source: https://github.com/pydantic/logfire/blob/main/docs/reference/advanced/prompt-management/composition-walkthrough.md This is an example of safety rules text that can be managed and reused within prompts. ```text Never reveal private account data. Confirm the customer's identity before discussing billing. Ask for missing operational details before taking any irreversible action. ``` -------------------------------- ### Logfire PyMongo Usage Example (Async with Motor) Source: https://github.com/pydantic/logfire/blob/main/docs/integrations/databases/pymongo.md Example of how to use Logfire with an asynchronous Motor client. ```APIDOC ```python skip-run="true" skip-reason="external-connection" import asyncio from motor.motor_asyncio import AsyncIOMotorClient import logfire logfire.configure() logfire.instrument_pymongo() async def main(): client = AsyncIOMotorClient() db = client['database'] collection = db['collection'] await collection.insert_one({'name': 'MongoDB'}) await collection.find_one() asyncio.run(main()) ``` ``` -------------------------------- ### Detailed System Metrics Configuration (Equivalent to base='full') Source: https://github.com/pydantic/logfire/blob/main/docs/integrations/system-metrics.md Specifies a detailed list of all system and process metrics to collect, equivalent to using `base='full'`. This provides granular data but can be resource-intensive. ```python logfire.instrument_system_metrics({ 'system.cpu.simple_utilization': None, 'system.cpu.time': ['idle', 'user', 'system', 'irq', 'softirq', 'nice', 'iowait', 'steal', 'interrupt', 'dpc'], 'system.cpu.utilization': ['idle', 'user', 'system', 'irq', 'softirq', 'nice', 'iowait', 'steal', 'interrupt', 'dpc'], 'system.memory.usage': ['available', 'used', 'free', 'active', 'inactive', 'buffers', 'cached', 'shared', 'wired', 'slab', 'total'], 'system.memory.utilization': ['available', 'used', 'free', 'active', 'inactive', 'buffers', 'cached', 'shared', 'wired', 'slab'], 'system.swap.usage': ['used', 'free'], 'system.swap.utilization': ['used'], 'system.disk.io': ['read', 'write'], 'system.disk.operations': ['read', 'write'], 'system.disk.time': ['read', 'write'], 'system.network.dropped.packets': ['transmit', 'receive'], 'system.network.packets': ['transmit', 'receive'], 'system.network.errors': ['transmit', 'receive'], 'system.network.io': ['transmit', 'receive'], 'system.thread_count': None, 'process.context_switches': ['involuntary', 'voluntary'], 'process.runtime.gc_count': None, 'process.open_file_descriptor.count': None, 'process.cpu.time': ['user', 'system'], 'process.cpu.utilization': None, 'process.cpu.core_utilization': None, 'process.disk.io': ['read', 'write'], 'process.memory.usage': None, 'process.memory.virtual': None, 'process.thread.count': None, 'cpython.gc.collected_objects': None, 'cpython.gc.collections': None, 'cpython.gc.uncollectable_objects': None, }) ``` -------------------------------- ### Configure and Instrument Logfire SDK Source: https://github.com/pydantic/logfire/blob/main/docs/ai-observability.md Import the Logfire SDK and call `configure()` to set up logging. Use `instrument_openai()` or a similar function to integrate with your chosen AI framework. ```python import logfire logfire.configure() logfire.instrument_openai() # Or your framework of choice ```