Skip to content

Commit 60f124b

Browse files
committed
add type checing isntructions
1 parent dc5e199 commit 60f124b

7 files changed

Lines changed: 208 additions & 2466 deletions

File tree

.vscode/settings.json

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,9 @@
1414
"prettier.documentSelectors": [
1515
"**/*.{cjs,mjs,ts,tsx,astro,md,mdx,json,yaml,yml}"
1616
],
17-
"python.testing.pytestArgs": ["tests"],
17+
"python.testing.pytestArgs": [
18+
"tests"
19+
],
1820
"python.testing.unittestEnabled": false,
1921
"python.testing.pytestEnabled": true
2022
}

CLAUDE.md

Lines changed: 132 additions & 72 deletions
Original file line numberDiff line numberDiff line change
@@ -4,115 +4,175 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
44

55
## Project Overview
66

7-
This is the Langfuse Python SDK, a client library for accessing the Langfuse observability platform. The SDK provides integration with OpenTelemetry (OTel) for tracing, automatic instrumentation for popular LLM frameworks (OpenAI, Langchain, etc.), and direct API access to Langfuse's features.
7+
This is the **Langfuse Python SDK**, an observability and analytics platform for AI applications. It provides tracing, evaluation, and analytics for LLM applications through multiple interfaces: decorators, low-level SDK, and integrations with popular AI libraries.
88

99
## Development Commands
1010

11-
### Setup
11+
### Environment Setup
1212
```bash
13-
# Install Poetry plugins (one-time setup)
14-
poetry self add poetry-dotenv-plugin
15-
poetry self add poetry-bumpversion
13+
# Using UV (preferred)
14+
uv venv --python 3.12
15+
source .venv/bin/activate
16+
uv sync
1617

17-
# Install all dependencies including optional extras
18+
# Using Poetry (legacy)
1819
poetry install --all-extras
19-
20-
# Setup pre-commit hooks
2120
poetry run pre-commit install
2221
```
2322

2423
### Testing
2524
```bash
26-
# Run all tests with verbose output
25+
# Run all tests
2726
poetry run pytest -s -v --log-cli-level=INFO
2827

29-
# Run a specific test
28+
# Run specific test
3029
poetry run pytest -s -v --log-cli-level=INFO tests/test_core_sdk.py::test_flush
3130

32-
# Run tests in parallel (faster)
33-
poetry run pytest -s -v --log-cli-level=INFO -n auto
31+
# Run with UV
32+
uv run pytest -s -v --log-cli-level=INFO
3433
```
3534

35+
### Memory for Running Unit Tests
36+
- To run unit tests you must always use the env file, use: `UV_ENV_FILE=.env uv run pytest -s -v --log-cli-level=INFO tests/TESTFILE::TEST_NAME`
37+
3638
### Code Quality
3739
```bash
38-
# Format code with Ruff
39-
poetry run ruff format .
40-
41-
# Run linting (development config)
42-
poetry run ruff check .
40+
# Format code
41+
ruff format .
4342

44-
# Run type checking
45-
poetry run mypy .
43+
# Run linter (development config)
44+
ruff check .
4645

47-
# Run pre-commit hooks manually
48-
poetry run pre-commit run --all-files
46+
# Run linter (CI config)
47+
ruff check --config ci.ruff.toml .
4948
```
5049

51-
### Building and Releasing
50+
### Documentation
5251
```bash
53-
# Build the package
54-
poetry build
55-
56-
# Run release script (handles versioning, building, tagging, and publishing)
57-
poetry run release
58-
59-
# Generate documentation
52+
# Generate SDK reference docs
6053
poetry run pdoc -o docs/ --docformat google --logo "https://langfuse.com/langfuse_logo.svg" langfuse
54+
55+
# Serve docs locally
56+
poetry run pdoc --docformat google --logo "https://langfuse.com/langfuse_logo.svg" langfuse
6157
```
6258

63-
## Architecture
59+
## Architecture Overview
6460

6561
### Core Components
6662

67-
- **`langfuse/_client/`**: Main SDK implementation built on OpenTelemetry
68-
- `client.py`: Core Langfuse client with OTel integration
69-
- `span.py`: LangfuseSpan, LangfuseGeneration, LangfuseEvent classes
70-
- `observe.py`: Decorator for automatic instrumentation
71-
- `datasets.py`: Dataset management functionality
72-
73-
- **`langfuse/api/`**: Auto-generated Fern API client
74-
- Contains all API resources and types
75-
- Generated from OpenAPI spec - do not manually edit these files
76-
77-
- **`langfuse/_task_manager/`**: Background processing
78-
- Media upload handling and queue management
79-
- Score ingestion consumer
80-
81-
- **Integration modules**:
82-
- `langfuse/openai.py`: OpenAI instrumentation
83-
- `langfuse/langchain/`: Langchain integration via CallbackHandler
84-
85-
### Key Design Patterns
86-
87-
The SDK is built on OpenTelemetry for observability, using:
88-
- Spans for tracing LLM operations
89-
- Attributes for metadata (see `LangfuseOtelSpanAttributes`)
90-
- Resource management for efficient batching and flushing
91-
92-
The client follows an async-first design with automatic batching of events and background flushing to the Langfuse API.
63+
**Main SDK Client** (`langfuse/_client/client.py`)
64+
- Built on OpenTelemetry foundations
65+
- Provides span management for tracing (LangfuseSpan, LangfuseGeneration, LangfuseEvent)
66+
- Thread-safe singleton pattern with multi-project support
67+
- Handles both sync and async operations
68+
69+
**Resource Manager** (`langfuse/_client/resource_manager.py`)
70+
- Central coordination hub implementing thread-safe singleton
71+
- Manages OpenTelemetry setup, API clients, background workers
72+
- Handles media upload and score ingestion queues
73+
- Provides graceful shutdown and resource cleanup
74+
75+
**API Layer** (`langfuse/api/`)
76+
- Auto-generated from OpenAPI spec using Fern
77+
- Provides complete typed client for Langfuse API
78+
- Organized by resources (prompts, datasets, observations, etc.)
79+
80+
### SDK Interfaces
81+
82+
**Three primary interaction patterns:**
83+
84+
1. **Decorator Pattern** (`@observe`)
85+
```python
86+
@observe(as_type="generation")
87+
def my_llm_function():
88+
# Automatically traced
89+
```
90+
91+
2. **Low-level Client API**
92+
```python
93+
langfuse = Langfuse()
94+
span = langfuse.start_span(name="operation")
95+
```
96+
97+
3. **Integration Libraries**
98+
```python
99+
from langfuse.openai import openai # Drop-in replacement
100+
```
101+
102+
### Integration Architecture
103+
104+
**OpenAI Integration** (`langfuse/openai.py`)
105+
- Drop-in replacement supporting both v0.x and v1.x
106+
- Wraps all completion methods (chat, completions, streaming, async)
107+
- Automatic metrics collection (tokens, cost, latency)
108+
109+
**LangChain Integration** (`langfuse/langchain/`)
110+
- CallbackHandler pattern for chain tracing
111+
- Automatic span creation for chains, tools, and agents
112+
- UUID mapping between LangChain runs and Langfuse spans
113+
114+
### Background Processing
115+
116+
**Task Manager** (`langfuse/_task_manager/`)
117+
- Media upload processing with configurable workers
118+
- Score ingestion with batching and retry logic
119+
- Queue-based architecture with backpressure handling
120+
121+
## Key Development Patterns
122+
123+
### Multi-Project Safety
124+
- Thread-safe singleton per public key prevents data leakage
125+
- Project-scoped span processor filters ensure data isolation
126+
- Disabled clients returned when project context is ambiguous
127+
128+
### OpenTelemetry Foundation
129+
- All tracing built on OTel primitives for standards compliance
130+
- Custom span processor for Langfuse-specific export
131+
- Proper context propagation across async boundaries
132+
133+
### Testing Approach
134+
- Comprehensive unit and integration tests
135+
- API mocking through test wrappers
136+
- Concurrency testing with ThreadPoolExecutor
137+
- Proper resource cleanup in test teardown
138+
139+
## File Structure Notes
140+
141+
- `langfuse/_client/` - Core client implementation and tracing logic
142+
- `langfuse/api/` - Auto-generated API client (excluded from linting)
143+
- `langfuse/_utils/` - Utility functions for serialization, error handling, etc.
144+
- `langfuse/_task_manager/` - Background processing workers
145+
- `tests/` - Comprehensive test suite with integration tests
146+
- `static/` - Test assets and sample files
93147

94148
## Configuration
95149

96-
Environment variables (defined in `_client/environment_variables.py`):
97-
- `LANGFUSE_PUBLIC_KEY` / `LANGFUSE_SECRET_KEY`: API credentials
98-
- `LANGFUSE_HOST`: API endpoint (defaults to https://cloud.langfuse.com)
99-
- `LANGFUSE_DEBUG`: Enable debug logging
100-
- `LANGFUSE_TRACING_ENABLED`: Enable/disable tracing
101-
- `LANGFUSE_SAMPLE_RATE`: Sampling rate for traces
150+
### Environment Variables
151+
Key environment variables for development:
152+
- `LANGFUSE_PUBLIC_KEY` / `LANGFUSE_SECRET_KEY` - API credentials
153+
- `LANGFUSE_HOST` - Langfuse instance URL
154+
- `LANGFUSE_DEBUG` - Enable debug logging
155+
- `LANGFUSE_TRACING_ENABLED` - Enable/disable tracing
102156

103-
## Testing Notes
157+
### Test Configuration
158+
- Tests require `.env` file based on `.env.template`
159+
- Some E2E tests are skipped by default (remove decorators to run)
160+
- CI uses different ruff config (`ci.ruff.toml`)
104161

105-
- Create `.env` file based on `.env.template` for integration tests
106-
- E2E tests with external APIs (OpenAI, SERP) are typically skipped in CI
107-
- Remove `@pytest.mark.skip` decorators in test files to run external API tests
108-
- Tests use `respx` for HTTP mocking and `pytest-httpserver` for test servers
162+
## Release Process
109163

110-
## Important Files
164+
```bash
165+
# Automated release
166+
poetry run release
111167

112-
- `pyproject.toml`: Poetry configuration, dependencies, and tool settings
113-
- `ruff.toml`: Local development linting config (stricter)
114-
- `ci.ruff.toml`: CI linting config (more permissive)
115-
- `langfuse/version.py`: Version string (updated by release script)
168+
# Manual release steps
169+
poetry version patch
170+
poetry build
171+
git commit -am "chore: release v{version}"
172+
git tag v{version}
173+
git push --tags
174+
poetry publish
175+
```
116176

117177
## API Generation
118178

CONTRIBUTING.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,13 @@ poetry install --all-extras
2121
poetry run pre-commit install
2222
```
2323

24+
### Type Checking
25+
26+
To run type checking on the langfuse package, run:
27+
```sh
28+
poetry run mypy langfuse --no-error-summary
29+
```
30+
2431
### Tests
2532

2633
#### Setup

langfuse/langchain/CallbackHandler.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -458,6 +458,7 @@ def on_tool_start(
458458
input=input_str,
459459
metadata=meta,
460460
level="DEBUG" if tags and LANGSMITH_TAG_HIDDEN in tags else None,
461+
as_type="tool",
461462
)
462463

463464
except Exception as e:

0 commit comments

Comments
 (0)