LangWatch Python SDK
LangWatch is a Python SDK for monitoring, evaluating, and testing LLM-powered applications and AI agents. It provides end-to-end observability by capturing traces and spans for LLM calls, RAG retrievals, and other pipeline steps, helping developers debug, prevent regressions, and optimize their AI systems. The current version is 0.18.0, and the library undergoes active development with regular releases.
Common errors
-
No traces appearing in LangWatch dashboard.
cause The `LANGWATCH_API_KEY` environment variable is likely not set, or the API key passed to `langwatch.setup()` is incorrect or missing.fixSet your LangWatch API key as an environment variable: `export LANGWATCH_API_KEY="your_api_key"` (Linux/macOS) or `$Env:LANGWATCH_API_KEY="your_api_key"` (PowerShell), or pass it directly: `langwatch.setup(api_key="your_api_key")`. -
ImportError: cannot import name 'OpenAIInstrumentor' from 'langwatch'
cause Specific modules like instrumentors are located within subpackages, not directly under the top-level `langwatch` package.fixImport the symbol from its correct submodule path, e.g., `from langwatch.instrumentors import OpenAIInstrumentor`. -
Error: Trace not found for current context.
cause Attempting to call `langwatch.get_current_trace().error()` or similar trace-specific methods outside of an active trace context (i.e., not within a `@langwatch.trace()` or `@langwatch.span()` decorated function/context block).fixEnsure all operations that interact with the current trace are performed within a function or block that is decorated with `@langwatch.trace()` or `@langwatch.span()`.
Warnings
- gotcha Traces might not appear in the LangWatch dashboard if the `LANGWATCH_API_KEY` environment variable is not set or passed explicitly during `langwatch.setup()`.
- gotcha In applications that exit quickly (e.g., short scripts), traces might not be fully sent to the LangWatch backend before termination.
- gotcha LangWatch uses OpenTelemetry under the hood. Incorrect or conflicting OpenTelemetry configurations can interfere with LangWatch's tracing.
- gotcha The `langwatch` Python SDK is distinct from the `langwatch-scenario` library, which focuses on agent simulations.
Install
-
pip install langwatch
Imports
- langwatch
import langwatch
- setup
langwatch.setup()
- trace
@langwatch.trace()
- span
@langwatch.span()
- OpenAIInstrumentor
from langwatch import OpenAIInstrumentor
from langwatch.instrumentors import OpenAIInstrumentor
- LangChainTracer
from langwatch import LangChainTracer
import langwatch.langchain langWatchCallback = langwatch.langchain.LangChainTracer()
Quickstart
import os
import langwatch
from langwatch.instrumentors import OpenAIInstrumentor
from openai import OpenAI
# Ensure your API key is set as an environment variable or pass it directly
# os.environ["LANGWATCH_API_KEY"] = "YOUR_LANGWATCH_API_KEY"
api_key = os.environ.get("LANGWATCH_API_KEY", "")
if not api_key:
print("Warning: LANGWATCH_API_KEY environment variable not set. Traces will not be sent.")
# For demonstration, we'll proceed but you should set your key.
# In a real application, you might raise an error or configure LangWatch to only log locally.
# Initialize LangWatch early in your application
# Automatically instruments OpenAI calls within the decorated functions
langwatch.setup(
api_key=api_key,
instrumentors=[OpenAIInstrumentor()]
)
client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY", "")) # Assume OpenAI API key is also set
@langwatch.trace(name="UserInteraction")
async def handle_user_query(query: str):
print(f"Processing query: {query}")
try:
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": query}
]
)
result = response.choices[0].message.content
print(f"Assistant's response: {result}")
return result
except Exception as e:
langwatch.get_current_trace().error(str(e)) # Record error if something goes wrong
print(f"An error occurred: {e}")
raise
async def main():
await handle_user_query("Tell me a fun fact about Python.")
# Ensure traces are flushed before the application exits
await langwatch.shutdown()
import asyncio
asyncio.run(main())