Skip to main content

Python SDK

The Foil Python SDK provides automatic OpenAI instrumentation, tracing, logging, and feedback collection for Python applications.
Full examples: Browse runnable examples at github.com/getfoil/foil-examples.

Installation

Requirements: Python 3.8 or higher
Or with poetry:

Configuration

Get your API key from the Foil Dashboard under Settings > API Keys.
Never hardcode API keys in your source code. Use environment variables instead.

Configuration Options

Quick Start: OpenAI Wrapper

The easiest way to get started is with the OpenAI wrapper, which automatically traces all your API calls:
Every call through wrapped_client is automatically logged to Foil with model name, input messages, output response, token usage, latency, and errors (if any).

Streaming

Streaming responses work seamlessly:

Tool Calls

Function/tool calls are automatically tracked:

Using Traces

For structured tracing with full span hierarchy, use Foil with agent_name and the trace() method:
This creates a trace with nested spans:

Available Span Methods

Fire-and-Forget Logging

For manual logging without the OpenAI wrapper:
This is non-blocking and doesn’t wait for a response.

Complete Example

Error Handling

Errors are automatically captured:

Advanced Patterns

The wrapper works with the async OpenAI client:
Each call through the wrapped client is logged separately:
When one agent delegates to another, use span.create_child_context() to create nested agent spans:
Trace input and output guardrail checks as separate spans: