langsmith
Description
LangSmith Client SDK
This package contains the Python client for interacting with the LangSmith platform.
To install:
pip install -U langsmith
export LANGSMITH_TRACING=true
export LANGSMITH_API_KEY=ls_...
Then trace:
import openai
from langsmith.wrappers import wrap_openai
from langsmith import traceable
# Auto-trace LLM calls in-context
client = wrap_openai(openai.Client())
@traceable # Auto-trace this function
def pipeline(user_input: str):
result = client.chat.completions.create(messages=[{"role": "user", "content": user_input}], model="gpt-5.4")
return result.choices[0].message.content
pipeline("Hello, world!")
Every LLM call inside pipeline is nested under a single trace in the LangSmith UI.
LangSmith helps you and your team develop and evaluate language models and intelligent agents. It is compatible with any LLM application.
Cookbook: For tutorials on how to get more value out of LangSmith, check out the Langsmith Cookbook repo.
A typical workflow looks like:
- Set up an account with LangSmith.
- Log traces while debugging and prototyping.
- Run benchmark evaluations and continuously improve with the collected data.
We'll walk through these steps in more detail below.
Sandbox AWS Auth Proxy
When sandbox code needs to call AWS services, use the sandbox AWS auth proxy. The proxy keeps the real AWS credentials outside the sandbox and signs supported AWS HTTPS requests with SigV4, so code in the sandbox can use AWS SDKs normally without storing long-lived AWS keys in files, environment variables, shell history, or logs.
Store AWS credentials as LangSmith workspace secrets using names that make sense for your workspace. Then create the sandbox with an AWS auth proxy config:
from langsmith.sandbox import (
SandboxClient,
aws_auth,
proxy_config,
workspace_secret,
)
client = SandboxClient()
auth_config = proxy_config(
rules=[
aws_auth(
access_key_id=workspace_secret("SANDBOX_AWS_ACCESS_KEY_ID"),
secret_access_key=workspace_secret("SANDBOX_AWS_SECRET_ACCESS_KEY"),
)
],
)
with client.sandbox(
name="aws-sandbox",
proxy_config=auth_config,
) as sandbox:
result = sandbox.run("python your_aws_script.py")
print(result.stdout)
Use opaque_secret("...") instead of workspace_secret(...) when your
application needs to pass short-lived write-only AWS credentials at sandbox
creation time. Plaintext AWS credential values are not accepted directly; wrap
them as opaque_secret(...) values.
Sandbox GCP Auth Proxy
When sandbox code needs to call Google APIs, use the sandbox GCP auth proxy. The proxy keeps the service account JSON outside the sandbox and injects OAuth bearer tokens for Google API hosts matched automatically by the sandbox proxy.
Store the service account JSON as a LangSmith workspace secret. Then create the sandbox with a GCP auth proxy config:
from langsmith.sandbox import (
SandboxClient,
gcp_auth,
proxy_config,
workspace_secret,
)
client = SandboxClient()
auth_config = proxy_config(
rules=[
gcp_auth(
service_account_json=workspace_secret("SANDBOX_GCP_SERVICE_ACCOUNT_JSON"),
scopes=["https://www.googleapis.com/auth/devstorage.read_write"],
)
],
)
with client.sandbox(
name="gcp-sandbox",
proxy_config=auth_config,
) as sandbox:
result = sandbox.run("python your_gcp_script.py")
print(result.stdout)
Use opaque_secret("...") for short-lived write-only service account JSON.
Plaintext service account JSON is not accepted directly.
Sandbox Mounts
When you create a LangSmith sandbox that needs filesystem access to external
data such as object storage buckets or public Git repositories, pass a
mount_config on sandbox creation. Mount specs contain only the mount target.
Provider credentials stay in mount_config.auth; the backend expands them into
runtime proxy auth rules. You can also pass proxy_config for non-mount proxy
behavior such as custom headers, callbacks, access control, and generic egress
rules. Explicit AWS/GCP proxy auth rules conflict with mount_config auth for
the same provider.
S3 mounts require AWS auth:
from langsmith.sandbox import (
aws_auth,
mount_config,
s3_mount,
workspace_secret,
)
mount_cfg = mount_config(
auth=[
aws_auth(
access_key_id=workspace_secret("SANDBOX_AWS_ACCESS_KEY_ID"),
secret_access_key=workspace_secret("SANDBOX_AWS_SECRET_ACCESS_KEY"),
)
],
mounts=[
s3_mount(
id="customer_data",
mount_path="/mnt/mounts/customer-data",
bucket="example-bucket",
prefix="datasets/customer-data",
region="us-east-1",
endpoint_url="https://s3.amazonaws.com",
path_style=False,
read_only=False,
)
],
)
with client.sandbox(
name="s3-mount-sandbox",
mount_config=mount_cfg,
) as sandbox:
result = sandbox.run("ls /mnt/mounts/customer-data")
print(result.stdout)
GCS mounts require GCP auth:
from langsmith.sandbox import (
gcp_auth,
gcs_mount,
mount_config,
workspace_secret,
)
mount_cfg = mount_config(
auth=[gcp_auth(service_account_json=workspace_secret("SANDBOX_GCP_SERVICE_ACCOUNT_JSON"))],
mounts=[
gcs_mount(
id="customer_data",
mount_path="/mnt/mounts/customer-data",
bucket="example-bucket",
prefix="datasets/customer-data",
)
],
)
with client.sandbox(
name="gcs-mount-sandbox",
mount_config=mount_cfg,
) as sandbox:
result = sandbox.run("ls /mnt/mounts/customer-data")
print(result.stdout)
Public Git mounts do not require AWS or GCP auth:
from langsmith.sandbox import git_mount, mount_config
mount_cfg = mount_config(
mounts=[
git_mount(
id="repo",
mount_path="/mnt/repo",
remote_url="https://github.com/langchain-ai/langsmith-python.git",
ref={"type": "branch", "name": "main"},
refresh_interval_seconds=60,
)
],
)
with client.sandbox(
name="git-mount-sandbox",
mount_config=mount_cfg,
) as sandbox:
result = sandbox.run("ls /mnt/repo")
print(result.stdout)
Private Git repositories can use low-level proxy_config rules when the remote
requires proxy-managed auth. There is not yet a high-level private Git auth
helper.
1. Connect to LangSmith
Sign up for LangSmith using your GitHub, Discord accounts, or an email address and password. If you sign up with an email, make sure to verify your email address before logging in.
Then, create a unique API key on the Settings Page, which is found in the menu at the top right corner of the page.
[!NOTE] Save the API Key in a secure location. It will not be shown again.
2. Log Traces
You can log traces natively using the LangSmith SDK or within your LangChain application.
Logging Traces with LangChain
LangSmith seamlessly integrates with the Python LangChain library to record traces from your LLM applications.
- Copy the environment variables from the Settings Page and add them to your application.
Tracing can be activated by setting the following environment variables or by manually specifying the LangChainTracer.
import os
os.environ["LANGSMITH_TRACING"] = "true"
os.environ["LANGSMITH_ENDPOINT"] = "https://api.smith.langchain.com"
# os.environ["LANGSMITH_ENDPOINT"] = "https://eu.api.smith.langchain.com" # If signed up in the EU region
os.environ["LANGSMITH_API_KEY"] = "<YOUR-LANGSMITH-API-KEY>"
# os.environ["LANGSMITH_PROJECT"] = "My Project Name" # Optional: "default" is used if not set
# os.environ["LANGSMITH_WORKSPACE_ID"] = "<YOUR-WORKSPACE-ID>" # Required for org-scoped API keys
Tip: Projects are groups of traces. All runs are logged to a project. If not specified, the project is set to
default.
- Run an Agent, Chain, or Language Model in LangChain
If the environment variables are correctly set, your application will automatically connect to the LangSmith platform.
from langchain_core.runnables import chain
@chain
def add_val(x: dict) -> dict:
return {"val": x["val"] + 1}
add_val({"val": 1})
Logging Traces Outside LangChain
You can still use the LangSmith development platform without depending on any LangChain code.
- Copy the environment variables from the Settings Page and add them to your application.
import os
os.environ["LANGSMITH_ENDPOINT"] = "https://api.smith.langchain.com"
os.environ["LANGSMITH_API_KEY"] = "<YOUR-LANGSMITH-API-KEY>"
# os.environ["LANGSMITH_PROJECT"] = "My Project Name" # Optional: "default" is used if not set
- Log traces
The easiest way to log traces using the SDK is via the @traceable decorator. Below is an example.
from datetime import datetime
from typing import List, Optional, Tuple
import openai
from langsmith import traceable
from langsmith.wrappers import wrap_openai
client = wrap_openai(openai.Client())
@traceable
def argument_generator(query: str, additional_description: str = "") -> str:
return (
client.chat.completions.create(
model="gpt-5.4",
messages=[
{
"role": "system",
"content": "You are a debater making an argument on a topic."
f"{additional_description}"
f" The current time is {datetime.now()}",
},
{"role": "user", "content": f"The discussion topic is {query}"},
],
)
.choices[0]
.message.content
)
@traceable
def argument_chain(query: str, additional_description: str = "") -> str:
argument = argument_generator(query, additional_description)
# ... Do other processing or call other functions...
return argument
argument_chain("Why is blue better than orange?")
Alternatively, you can manually log events using the Client directly or using a RunTree, which is what the traceable decorator is meant to manage for you!
A RunTree tracks your application. Each RunTree object is required to have a name and run_type. These and other important attributes are as follows:
name:str- used to identify the component's purposerun_type:str- Currently one of "llm", "chain" or "tool"; more options will be added in the futureinputs:dict- the inputs to the componentoutputs:Optional[dict]- the (optional) returned values from the componenterror:Optional[str]- Any error messages that may have arisen during the call
from langsmith.run_trees import RunTree
parent_run = RunTree(
name="My Chat Bot",
run_type="chain",
inputs={"text": "Summarize this morning's meetings."},
# project_name= "Defaults to the LANGSMITH_PROJECT env var"
)
parent_run.post()
# .. My Chat Bot calls an LLM
child_llm_run = parent_run.create_child(
name="My Proprietary LLM",
run_type="llm",
inputs={"prompts": ["You are an AI Assistant. The time is XYZ. Summarize this morning's meetings."]},
)
child_llm_run.post()
child_llm_run.end(
outputs={"generations": ["I should use the transcript_loader tool to fetch meeting_transcripts from XYZ"]}
)
child_llm_run.patch()
# .. My Chat Bot takes the LLM output and calls
# a tool / function for fetching transcripts ..
child_tool_run = parent_run.create_child(
name="transcript_loader",
run_type="tool",
inputs={"date": "XYZ", "content_type": "meeting_transcripts"},
)
child_tool_run.post()
# The tool returns meeting notes to the chat bot
child_tool_run.end(outputs={"meetings": ["Meeting1 notes.."]})
child_tool_run.patch()
child_chain_run = parent_run.create_child(
name="Unreliable Component",
run_type="tool",
inputs={"input": "Summarize these notes..."},
)
child_chain_run.post()
try:
# .... the component does work
raise ValueError("Something went wrong")
child_chain_run.end(outputs={"output": "foo"})
child_chain_run.patch()
except Exception as e:
child_chain_run.end(error=f"I errored again {e}")
child_chain_run.patch()
pass
# .. The chat agent recovers
parent_run.end(outputs={"output": ["The meeting notes are as follows:..."]})
res = parent_run.patch()
res.result()
Create a Dataset from Existing Runs
Once your runs are stored in LangSmith, you can convert them into a dataset. For this example, we will do so using the Client, but you can also do this using the web interface, as explained in the LangSmith docs.
from langsmith import Client
client = Client()
dataset_name = "Example Dataset"
# We will only use examples from the top level AgentExecutor run here,
# and exclude runs that errored.
runs = client.list_runs(
project_name="my_project",
execution_order=1,
error=False,
)
dataset = client.create_dataset(dataset_name, description="An example dataset")
for run in runs:
client.create_example(
inputs=run.inputs,
outputs=run.outputs,
dataset_id=dataset.id,
)
Evaluating Runs
Check out the LangSmith Testing & Evaluation dos for up-to-date workflows.
For generating automated feedback on individual runs, you can run evaluations directly using the LangSmith client.
from typing import Optional
from langsmith.evaluation import StringEvaluator
def jaccard_chars(output: str, answer: str) -> float:
"""Naive Jaccard similarity between two strings."""
prediction_chars = set(output.strip().lower())
answer_chars = set(answer.strip().lower())
intersection = prediction_chars.intersection(answer_chars)
union = prediction_chars.union(answer_chars)
return len(intersection) / len(union)
def grader(run_input: str, run_output: str, answer: Optional[str]) -> dict:
"""Compute the score and/or label for this run."""
if answer is None:
value = "AMBIGUOUS"
score = 0.5
else:
score = jaccard_chars(run_output, answer)
value = "CORRECT" if score > 0.9 else "INCORRECT"
return dict(score=score, value=value)
evaluator = StringEvaluator(evaluation_name="Jaccard", grading_function=grader)
runs = client.list_runs(
project_name="my_project",
execution_order=1,
error=False,
)
for run in runs:
client.evaluate_run(run, evaluator)
Integrations
LangSmith easily integrates with your favorite LLM framework.
OpenAI SDK
We provide a convenient wrapper for the OpenAI SDK.
In order to use, you first need to set your LangSmith API key.
export LANGSMITH_API_KEY=<your-api-key>
Next, you will need to install the LangSmith SDK:
pip install -U langsmith
After that, you can wrap the OpenAI client:
from openai import OpenAI
from langsmith import wrappers
client = wrappers.wrap_openai(OpenAI())
Now, you can use the OpenAI client as you normally would, but now everything is logged to LangSmith!
client.chat.completions.create(
model="gpt-5.4",
messages=[{"role": "user", "content": "Say this is a test"}],
)
Oftentimes, you use the OpenAI client inside of other functions.
You can get nested traces by using this wrapped client and decorating those functions with @traceable.
See this documentation for more documentation how to use this decorator
from langsmith import traceable
@traceable(name="Call OpenAI")
def my_function(text: str):
return client.chat.completions.create(
model="gpt-5.4",
messages=[{"role": "user", "content": f"Say {text}"}],
)
my_function("hello world")
Instructor
We provide a convenient integration with Instructor, largely by virtue of it essentially just using the OpenAI SDK.
In order to use, you first need to set your LangSmith API key.
export LANGSMITH_API_KEY=<your-api-key>
Next, you will need to install the LangSmith SDK:
pip install -U langsmith
After that, you can wrap the OpenAI client:
from openai import OpenAI
from langsmith import wrappers
client = wrappers.wrap_openai(OpenAI())
After this, you can patch the OpenAI client using instructor:
import instructor
client = instructor.patch(OpenAI())
Now, you can use instructor as you normally would, but now everything is logged to LangSmith!
from pydantic import BaseModel
class UserDetail(BaseModel):
name: str
age: int
user = client.chat.completions.create(
model="gpt-5.4",
response_model=UserDetail,
messages=[
{"role": "user", "content": "Extract Jason is 25 years old"},
],
)
Oftentimes, you use instructor inside of other functions.
You can get nested traces by using this wrapped client and decorating those functions with @traceable.
See this documentation for more documentation how to use this decorator
@traceable()
def my_function(text: str) -> UserDetail:
return client.chat.completions.create(
model="gpt-5.4",
response_model=UserDetail,
messages=[
{"role": "user", "content": f"Extract {text}"},
],
)
my_function("Jason is 25 years old")
Pytest Plugin
The LangSmith pytest plugin lets Python developers define their datasets and evaluations as pytest test cases. See online docs for more information.
This plugin is installed as part of the LangSmith SDK, and is enabled by default. See also official pytest docs: How to install and use plugins
Additional Documentation
To learn more about the LangSmith platform, check out the docs.
License
The LangSmith SDK is licensed under the MIT License.
The copyright information for certain dependencies' are reproduced in their corresponding COPYRIGHT.txt files in this repo, including the following:
Generated REST client
The low-level, generated client (Langsmith / AsyncLangsmith) ships in the same package. Everything below is maintained by Stainless.
Documentation
The full API of this library can be found in api.md.
Installation
# install from the production repo
pip install git+ssh://git@github.com/langchain-ai/langsmith-python.git
[!NOTE] Once this package is published to PyPI, this will become:
pip install langsmith
Usage
The full API of this library can be found in api.md.
import os
from langsmith import Langsmith
client = Langsmith(
api_key=os.environ.get("LANGSMITH_API_KEY"), # This is the default and can be omitted
tenant_id=os.environ.get("LANGSMITH_TENANT_ID"), # This is the default and can be omitted
)
page = client.runs.query_v2(
project_ids=["00000000-0000-0000-0000-000000000000"],
)
print(page.items)
While you can provide an api_key keyword argument,
we recommend using python-dotenv
to add LANGSMITH_API_KEY="My API Key" to your .env file
so that your API Key is not stored in source control.
Async usage
Simply import AsyncLangsmith instead of Langsmith and use await with each API call:
import os
import asyncio
from langsmith import AsyncLangsmith
client = AsyncLangsmith(
api_key=os.environ.get("LANGSMITH_API_KEY"), # This is the default and can be omitted
tenant_id=os.environ.get("LANGSMITH_TENANT_ID"), # This is the default and can be omitted
)
async def main() -> None:
page = await client.runs.query_v2(
project_ids=["00000000-0000-0000-0000-000000000000"],
)
print(page.items)
asyncio.run(main())
Functionality between the synchronous and asynchronous clients is otherwise identical.
With aiohttp
By default, the async client uses httpx for HTTP requests. However, for improved concurrency performance you may also use aiohttp as the HTTP backend.
You can enable this by installing aiohttp:
# install from the production repo
pip install 'langsmith[aiohttp] @ git+ssh://git@github.com/langchain-ai/langsmith-python.git'
Then you can enable it by instantiating the client with http_client=DefaultAioHttpClient():
import os
import asyncio
from langsmith import DefaultAioHttpClient
from langsmith import AsyncLangsmith
async def main() -> None:
async with AsyncLangsmith(
api_key=os.environ.get("LANGSMITH_API_KEY"), # This is the default and can be omitted
tenant_id=os.environ.get("LANGSMITH_TENANT_ID"), # This is the default and can be omitted
http_client=DefaultAioHttpClient(),
) as client:
page = await client.runs.query_v2(
project_ids=["00000000-0000-0000-0000-000000000000"],
)
print(page.items)
asyncio.run(main())
Using types
Nested request parameters are TypedDicts. Responses are Pydantic models which also provide helper methods for things like:
- Serializing back into JSON,
model.to_json() - Converting to a dictionary,
model.to_dict()
Typed requests and responses provide autocomplete and documentation within your editor. If you would like to see type errors in VS Code to help catch bugs earlier, set python.analysis.typeCheckingMode to basic.
Pagination
List methods in the LangChain API are paginated.
This library provides auto-paginating iterators with each list response, so you do not have to request successive pages manually:
from langsmith import Langsmith
client = Langsmith()
all_runs = []
# Automatically fetches more pages as needed.
for run in client.runs.query_v2(
project_ids=["00000000-0000-0000-0000-000000000000"],
):
# Do something with run here
all_runs.append(run)
print(all_runs)
Or, asynchronously:
import asyncio
from langsmith import AsyncLangsmith
client = AsyncLangsmith()
async def main() -> None:
all_runs = []
# Iterate through items across all pages, issuing requests as needed.
async for run in client.runs.query_v2(
project_ids=["00000000-0000-0000-0000-000000000000"],
):
all_runs.append(run)
print(all_runs)
asyncio.run(main())
Alternatively, you can use the .has_next_page(), .next_page_info(), or .get_next_page() methods for more granular control working with pages:
first_page = await client.runs.query_v2(
project_ids=["00000000-0000-0000-0000-000000000000"],
)
if first_page.has_next_page():
print(f"will fetch next page using these details: {first_page.next_page_info()}")
next_page = await first_page.get_next_page()
print(f"number of items we just fetched: {len(next_page.items)}")
# Remove `await` for non-async usage.
Or just work directly with the returned data:
first_page = await client.runs.query_v2(
project_ids=["00000000-0000-0000-0000-000000000000"],
)
print(f"next page cursor: {first_page.next_cursor}") # => "next page cursor: ..."
for run in first_page.items:
print(run.id)
# Remove `await` for non-async usage.
Nested params
Nested parameters are dictionaries, typed using TypedDict, for example:
from langsmith import Langsmith
client = Langsmith()
product_feedback = client.product_feedback.create(
category="BUG",
message="x",
source="LANGSMITH_CLI",
client={},
)
print(product_feedback.client)
Handling errors
When the library is unable to connect to the API (for example, due to network connection problems or a timeout), a subclass of langsmith.APIConnectionError is raised.
When the API returns a non-success status code (that is, 4xx or 5xx
response), a subclass of langsmith.APIStatusError is raised, containing status_code and response properties.
All errors inherit from langsmith.APIError.
import langsmith
from langsmith import Langsmith
client = Langsmith()
try:
client.runs.query_v2(
project_ids=["00000000-0000-0000-0000-000000000000"],
)
except langsmith.APIConnectionError as e:
print("The server could not be reached")
print(e.__cause__) # an underlying Exception, likely raised within httpx.
except langsmith.RateLimitError as e:
print("A 429 status code was received; we should back off a bit.")
except langsmith.APIStatusError as e:
print("Another non-200-range status code was received")
print(e.status_code)
print(e.response)
Error codes are as follows:
Retries
Certain errors are automatically retried 2 times by default, with a short exponential backoff. Connection errors (for example, due to a network connectivity problem), 408 Request Timeout, 409 Conflict, 429 Rate Limit, and >=500 Internal errors are all retried by default.
You can use the max_retries option to configure or disable retry settings:
from langsmith import Langsmith
# Configure the default for all requests:
client = Langsmith(
# default is 2
max_retries=0,
)
# Or, configure per-request:
client.with_options(max_retries=5).runs.query_v2(
project_ids=["00000000-0000-0000-0000-000000000000"],
)
Timeouts
By default requests time out after 1.5 minutes. You can configure this with a timeout option,
which accepts a float or an httpx.Timeout object:
from langsmith import Langsmith
# Configure the default for all requests:
client = Langsmith(
# 20 seconds (default is 1.5 minutes)
timeout=20.0,
)
# More granular control:
client = Langsmith(
timeout=httpx.Timeout(60.0, read=5.0, write=10.0, connect=2.0),
)
# Override per-request:
client.with_options(timeout=5.0).runs.query_v2(
project_ids=["00000000-0000-0000-0000-000000000000"],
)
On timeout, an APITimeoutError is thrown.
Note that requests that time out are retried twice by default.
Advanced
Logging
We use the standard library logging module.
You can enable logging by setting the environment variable LANGCHAIN_LOG to info.
$ export LANGCHAIN_LOG=info
Or to debug for more verbose logging.
How to tell whether None means null or missing
In an API response, a field may be explicitly null, or missing entirely; in either case, its value is None in this library. You can differentiate the two cases with .model_fields_set:
if response.my_field is None:
if "my_field" not in response.model_fields_set:
print('Got json like {}, without a "my_field" key present at all.')
else:
print('Got json like {"my_field": null}.')
Accessing raw response data (e.g. headers)
The "raw" Response object can be accessed by prefixing .with_raw_response. to any HTTP method call, e.g.,
from langsmith import Langsmith
client = Langsmith()
response = client.runs.with_raw_response.query_v2(
project_ids=["00000000-0000-0000-0000-000000000000"],
)
print(response.headers.get("X-My-Header"))
run = response.parse() # get the object that `runs.query_v2()` would have returned
print(run.id)
These methods return an APIResponse object.
The async client returns an AsyncAPIResponse with the same structure, the only difference being awaitable methods for reading the response content.
.with_streaming_response
The above interface eagerly reads the full response body when you make the request, which may not always be what you want.
To stream the response body, use .with_streaming_response instead, which requires a context manager and only reads the response body once you call .read(), .text(), .json(), .iter_bytes(), .iter_text(), .iter_lines() or .parse(). In the async client, these are async methods.
with client.runs.with_streaming_response.query_v2(
project_ids=["00000000-0000-0000-0000-000000000000"],
) as response:
print(response.headers.get("X-My-Header"))
for line in response.iter_lines():
print(line)
The context manager is required so that the response will reliably be closed.
Making custom/undocumented requests
This library is typed for convenient access to the documented API.
If you need to access undocumented endpoints, params, or response properties, the library can still be used.
Undocumented endpoints
To make requests to undocumented endpoints, you can make requests using client.get, client.post, and other
http verbs. Options on the client will be respected (such as retries) when making this request.
import httpx
response = client.post(
"/foo",
cast_to=httpx.Response,
body={"my_param": True},
)
print(response.headers.get("x-foo"))
Undocumented request params
If you want to explicitly send an extra param, you can do so with the extra_query, extra_body, and extra_headers request
options.
Undocumented response properties
To access undocumented response properties, you can access the extra fields like response.unknown_prop. You
can also get all the extra fields on the Pydantic model as a dict with
response.model_extra.
Configuring the HTTP client
You can directly override the httpx client to customize it for your use case, including:
- Support for proxies
- Custom transports
- Additional advanced functionality
import httpx
from langsmith import Langsmith, DefaultHttpxClient
client = Langsmith(
# Or use the `LANGCHAIN_BASE_URL` env var
base_url="http://my.test.server.example.com:8083",
http_client=DefaultHttpxClient(
proxy="http://my.test.proxy.example.com",
transport=httpx.HTTPTransport(local_address="0.0.0.0"),
),
)
You can also customize the client on a per-request basis by using with_options():
client.with_options(http_client=DefaultHttpxClient(...))
Managing HTTP resources
By default the library closes underlying HTTP connections whenever the client is garbage collected. You can manually close the client using the .close() method if desired, or with a context manager that closes when exiting.
from langsmith import Langsmith
with Langsmith() as client:
# make requests here
...
# HTTP client is now closed
Versioning
This package generally follows SemVer conventions, though certain backwards-incompatible changes may be released as minor versions:
- Changes that only affect static types, without breaking runtime behavior.
- Changes to library internals which are technically public but not intended or documented for external use. (Please open a GitHub issue to let us know if you are relying on such internals.)
- Changes that we do not expect to impact the vast majority of users in practice.
We take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.
We are keen for your feedback; please open an issue with questions, bugs, or suggestions.
Determining the installed version
If you've upgraded to the latest version but aren't seeing any new features you were expecting then your python environment is likely still using an older version.
You can determine the version that is being used at runtime with:
import langsmith
print(langsmith.__version__)
Requirements
Python 3.10 or higher.
Contributing
Classes
Querystring
Options
ApiKeyAuth
API key authentication for write replicas.
ServiceAuth
Service-to-service JWT authentication for write replicas.
AuthHeaders
Custom authentication headers for write replicas.
WriteReplica
Configuration for a write replica endpoint.
address is in beta. It is enabled per workspace; a
workspace without it rejects the runs, so tracing is lost rather th
RunTree
Run Schema with back-references for posting runs.
TracingMiddleware
Middleware for propagating distributed tracing context using LangSmith.
This middleware checks for the 'langsmith-trace' header and propagates the
tracing context if present. It does not start new
StringNode
String node extracted from the data.
StringNodeProcessor
Processes a list of string nodes for masking.
ReplacerOptions
Configuration options for replacing sensitive data.
StringNodeRule
Declarative rule used for replacing sensitive data.
RuleNodeProcessor
String node processor that uses a list of rules to replace sensitive data.
CallableNodeProcessor
String node processor that uses a callable function to replace sensitive data.
Attachment
Annotated type that will be stored as an attachment if used.
BinaryIOLike
Protocol for binary IO-like objects.
ExampleBase
Example base model.
ExampleCreate
Example upload with attachments.
ExampleUpsertWithAttachments
Example create with attachments.
AttachmentInfo
Info for an attachment.
Example
Example model.
AttachmentsOperations
Operations to perform on attachments.
ExampleUpdate
Example update with attachments.
DataType
Enum for dataset data types.
DatasetBase
Dataset base model.
DatasetTransformation
Schema for dataset transformations.
Dataset
Dataset ORM model.
DatasetVersion
Class representing a dataset version.
RunBase
Base Run schema.
A Run is a span representing a single unit of work or operation within your LLM app. This could be a single call to an LLM or chain, to a prompt formatting call, to a runnable lambda
Run
Run schema when loading from the DB.
RunTypeEnum
(Deprecated) Enum for run types. Use string directly.
RunLikeDict
Run-like dictionary, for type-hinting.
RunWithAnnotationQueueInfo
Run schema with annotation queue info.
FeedbackSourceBase
Base class for feedback sources.
This represents whether feedback is submitted from the API, model, human labeler, etc.
APIFeedbackSource
API feedback source.
ModelFeedbackSource
Model feedback source.
FeedbackSourceType
Feedback source type.
FeedbackBase
Feedback schema.
FeedbackCategory
Specific value and label pair for feedback.
FeedbackConfig
Represents how a feedback value ought to be interpreted.
FeedbackCreate
Schema used for creating feedback.
Feedback
Schema for getting feedback.
TracerSession
TracerSession schema for the API.
Sessions are also referred to as "Projects" in the UI.
TracerSessionResult
A project, hydrated with additional information.
Sessions are also referred to as "Projects" in the UI.
BaseMessageLike
A protocol representing objects similar to BaseMessage.
DatasetShareSchema
Represents the schema for a dataset share.
AnnotationQueueRubricItem
Represents a rubric item assigned to an annotation queue.
Links a feedback config to a queue with optional per-queue customization.
AnnotationQueue
Represents an annotation queue.
AnnotationQueueWithDetails
Represents an annotation queue with details.
RunKey
A run identified by its full lookup key, for adding to an annotation queue.
Unlike a bare run ID, this carries the partition key (session_id and
start_time) so the run can be located directly
BatchIngestConfig
Configuration for batch ingestion.
LangSmithInfo
Information about the LangSmith server.
LangSmithSettings
Settings for the LangSmith tenant.
FeedbackIngestToken
Represents the schema for a feedback ingest token.
RunEvent
Run event schema.
TimeDeltaInput
Timedelta input schema.
DatasetDiffInfo
Represents the difference information between two datasets.
ComparativeExperiment
Represents a comparative experiment.
This information summarizes evaluation results comparing two or more models on a given dataset.
PromptCommit
Represents a Prompt with a manifest.
ListedPromptCommit
Represents a listed prompt commit with associated metadata.
Prompt
Represents a Prompt with metadata.
ListPromptsResponse
A list of prompts with metadata.
PromptSortField
Enum for sorting fields for prompts.
FileEntry
A file with inline content.
AgentEntry
A link to another agent repo.
SkillEntry
A link to a skill repo.
AgentContext
An agent pulled from hub.
SkillContext
A skill pulled from hub.
DirectoryCommitInfo
Commit details returned from a directory commit.
DirectoryCommitResponse
Response body for POST /directories/commits.
InputTokenDetails
Breakdown of input token counts.
Does not need to sum to full input token count. Does not need to have all keys.
OutputTokenDetails
Breakdown of output token counts.
Does not need to sum to full output token count. Does not need to have all keys.
InputCostDetails
Breakdown of input token costs.
Does not need to sum to full input cost. Does not need to have all keys.
OutputCostDetails
Breakdown of output token costs.
Does not need to sum to full output cost. Does not need to have all keys.
UsageMetadata
Usage metadata for a message, such as token counts.
This is a standard representation of token usage that is consistent across models.
ExtractedUsageMetadata
Usage metadata dictionary extracted from a run.
Should be the same as UsageMetadata, but does not require all keys to be present.
UpsertExamplesResponse
Response object returned from the upsert_examples_multipart method.
ExampleWithRuns
Example with runs.
ExperimentRunStats
Run statistics for an experiment.
ExperimentResults
Results container for experiment data with stats and examples.
Breaking change in v0.4.32: The 'stats' field has been split into 'feedback_stats' and 'run_stats'.
InsightsReport
An Insights Report created by the Insights Agent over a tracing project.
InsightsHighlightedTrace
A trace highlighted in an insights report summary.
InsightsSummaryReport
High-level summary of an insights job: key points and highlighted traces.
InsightsCluster
A single cluster of runs in an insights report.
InsightsReportResult
Full result of fetching an Insights report (job + clusters + summary + optional runs).
FeedbackFormulaWeightedVariable
A feedback key and weight used when calculating feedback formulas.
.. admonition:: Deprecated
Composite feedback formulas are no longer supported in the SDK.
Add composite feedback scores vi
FeedbackFormulaCreate
Schema used for creating a feedback formula.
.. admonition:: Deprecated
Composite feedback formulas are no longer supported in the SDK.
Add composite feedback scores via the LangSmith UI ins
FeedbackFormulaUpdate
Schema used for updating a feedback formula.
.. admonition:: Deprecated
Composite feedback formulas are no longer supported in the SDK.
Add composite feedback scores via the LangSmith UI ins
FeedbackFormula
Schema for getting feedback formulas.
.. admonition:: Deprecated
Composite feedback formulas are no longer supported in the SDK.
Add composite feedback scores via the LangSmith UI instead. T
FeedbackConfigSchema
Represents a feedback configuration for a tenant's feedback key.
Feedback configurations define how feedback with a given key should be interpreted, including its type (continuous, categorical, or fr
LangSmithError
An error occurred while communicating with the LangSmith API.
LangSmithAPIError
Internal server error while communicating with LangSmith.
LangSmithRequestTimeout
Client took too long to send request body.
LangSmithUserError
User error caused an exception when communicating with LangSmith.
LangSmithRateLimitError
You have exceeded the rate limit for the LangSmith API.
LangSmithAuthError
Couldn't authenticate with the LangSmith API.
LangSmithNotFoundError
Couldn't find the requested resource.
LangSmithConflictError
The resource already exists.
LangSmithConnectionError
Couldn't connect to the LangSmith API.
LangSmithExceptionGroup
Port of ExceptionGroup for Py < 3.11.
LangSmithWarning
Base class for warnings.
LangSmithMissingAPIKeyWarning
Warning for missing API key.
FilterPoolFullWarning
Filter urllib3 warnings logged when the connection pool isn't reused.
FilterLangSmithRetry
Filter for retries from this lib.
LangSmithRetry
Wrapper to filter logs with this name.
ContextThreadPoolExecutor
ThreadPoolExecutor that copies the context to the child thread.
SyncOffsetPaginationTopLevelArray
AsyncOffsetPaginationTopLevelArray
SyncOffsetPaginationIssues
AsyncOffsetPaginationIssues
SyncOffsetPaginationRepos
AsyncOffsetPaginationRepos
SyncOffsetPaginationCommits
AsyncOffsetPaginationCommits
SyncOffsetPaginationOnlineEvaluators
AsyncOffsetPaginationOnlineEvaluators
SyncOffsetPaginationInsightsClusteringJobs
AsyncOffsetPaginationInsightsClusteringJobs
CursorPaginationCursors
SyncCursorPagination
AsyncCursorPagination
SyncItemsCursorPostPagination
AsyncItemsCursorPostPagination
SyncItemsCursorGetPagination
AsyncItemsCursorGetPagination
RequestOptions
NotGiven
For parameters with a meaningful None value, we need to distinguish between the user explicitly passing None, and the user not passing the parameter at all.
User code shouldn't need to use not_given
Omit
To explicitly omit something from being sent in a request, use omit.
# as the default `Content-Type` header is `application/json` that will be sent
client.post("/upload/files", files={"file":
ModelBuilderProtocol
HeadersLikeProtocol
InheritsGeneric
Represents a type that has inherited from Generic
The __orig_bases__ property can be used to determine the resolved
type variable for a given base class.
HttpxSendArgs
SequenceNotStr
BaseModel
Config
CachedDiscriminatorType
DiscriminatorDetails
GenericModel
RootModel
Used as a placeholder to easily convert runtime types to a Pydantic format to provide validation.
For example:
validated = RootModel[int](__root__="5").__root__
# validated: 5FinalRequestOptionsInput
FinalRequestOptions
Config
CacheEntry
A single cache entry with metadata for TTL tracking.
CacheMetrics
Cache performance metrics.
PromptCache
Thread-safe LRU cache with background thread refresh.
For use with the synchronous Client.
Features:
- In-memory LRU cache with configurable max size
- Background thread for refreshing stale entries
AsyncPromptCache
Thread-safe LRU cache with asyncio task refresh.
For use with the asynchronous AsyncClient.
Features:
- In-memory LRU cache with configurable max size
- Asyncio task for refreshing stale entries
- S
Cache
Deprecated alias for PromptCache. Use PromptCache instead.
AsyncCache
Deprecated alias for AsyncPromptCache. Use AsyncPromptCache instead.
RuntimeOverrides
Overrides for LangSmith runtime behavior.
This class allows overriding default async implementations for environments that don't support certain asyncio features (e.g., Temporal doesn't support ``run
_NULL_SENTRY
A sentinel singleton class used to distinguish omitted keyword arguments from those passed in with the value None (which may have different behavior).
_Matcher
A class for making assertions on expectation values.
_Expect
A class for setting expectations on test results.
AgentAddress
(beta) An agent address. Use agent_address to validate and construct one.
The id is a DNS label of 1 to 63 lowercase ASCII letters, digits or hyphens, starting with a letter and ending with a lette
ExperimentAddress
(beta) An experiment address. Use experiment_address to construct one.
EvaluatorAddress
(beta) The address of the workspace's shared evaluators project.
EnvAddressError
(beta) The LANGSMITH_AGENT_* / project env vars can't address a run.
Raised for half an address, an invalid one, or an address beside a project.
Tracing entry points (@traceable, trace, `tracin
LangSmithExtra
Any additional info to be injected into the run dynamically.
SupportsLangsmithExtra
Implementations of this Protocol accept an optional langsmith_extra parameter.
trace
Manage a LangSmith run in context.
This class can be used as both a synchronous and asynchronous context manager.
address is in beta. It is enabled per workspace; a
Stream
Provides the core interface to iterate over a synchronous stream response.
AsyncStream
Provides the core interface to iterate over an asynchronous stream response.
ServerSentEvent
SSEDecoder
SSEBytesDecoder
BaseAPIResponse
APIResponse
AsyncAPIResponse
BinaryAPIResponse
Subclass of APIResponse providing helpers for dealing with binary data.
Note: If you want to stream the response data instead of eagerly reading it all at once then you should use `.with_streaming_re
AsyncBinaryAPIResponse
Subclass of APIResponse providing helpers for dealing with binary data.
Note: If you want to stream the response data instead of eagerly reading it all at once then you should use `.with_streaming_re
StreamedBinaryAPIResponse
AsyncStreamedBinaryAPIResponse
MissingStreamClassError
StreamAlreadyConsumed
Attempted to read or stream content, but the content has already been streamed.
This can happen if you use a method like .iter_lines() and then attempt
to read th entire response body afterwards, e
ResponseContextManager
Context manager for ensuring that a request is not made until it is entered and that the response will always be closed when the context manager exits
AsyncResponseContextManager
Context manager for ensuring that a request is not made until it is entered and that the response will always be closed when the context manager exits
LangSmithSecret
A string that LangSmith serializes as [LANGSMITH SECRET].
Wrap a credential once, where it is read, and LangSmith masks it wherever it appears in a trace, at any nesting depth::
@traceable
LangSmithPlugin
Plugin for rendering LangSmith results.
ZoneInfo
Introduced in python 3.9.
TracerProvider
Used for optional OTEL tracing.
ListThreadsItem
Item returned by :meth:Client.list_threads.
Client
Client for interacting with the LangSmith API.
ReplicaAuth
One write destination: a server plus the credentials to reach it.
SyncAPIResource
AsyncAPIResource
AsyncClient
Async Client for interacting with the LangSmith API.
Langsmith
AsyncLangsmith
LangsmithWithRawResponse
AsyncLangsmithWithRawResponse
LangsmithWithStreamedResponse
AsyncLangsmithWithStreamedResponse
LangsmithError
APIError
APIResponseValidationError
APIStatusError
Raised when an API response has a status code of 4xx or 5xx.
APIConnectionError
APITimeoutError
BadRequestError
AuthenticationError
PermissionDeniedError
NotFoundError
ConflictError
UnprocessableEntityError
RateLimitError
InternalServerError
PageInfo
Stores the necessary information to build the request to retrieve the next page.
Either url or params must be set.
BasePage
Defines the core interface for pagination.
BaseSyncPage
AsyncPaginator
BaseAsyncPage
BaseClient
SyncHttpxClientWrapper
SyncAPIClient
AsyncHttpxClientWrapper
AsyncAPIClient
ForceMultipartDict
OtherPlatform
OtherArch
GenericModel
typed_cached_property
GitInfo
MountCacheConfig
Optional per-mount cache configuration supported by bucket mounts.
MountEncryptionConfig
Customer-managed key that uploads through a mount are encrypted with.
For S3 mounts, kms_key is a KMS key ARN in the mount's region and uploads
use SSE-KMS with it.
BucketMountSpecBase
Optional fields applied per bucket-backed sandbox mount.
S3MountConfigRequired
Required S3 configuration for a sandbox mount.
S3MountConfig
S3 configuration for a sandbox mount.
S3MountSpecBase
Optional fields applied per S3 sandbox mount.
S3MountSpec
S3-backed sandbox mount specification.
GCSMountConfigRequired
Required GCS configuration for a sandbox mount.
GCSMountConfig
GCS configuration for a sandbox mount.
GCSMountSpec
GCS-backed sandbox mount specification.
GitMountRefSpec
Git ref selected for a sandbox mount.
GitMountConfigRequired
Required Git configuration for a sandbox mount.
GitMountConfig
Git configuration for a sandbox mount.
GitMountSpec
Git-backed sandbox mount specification.
ContextHubMountConfigRequired
Required Context Hub configuration for a sandbox mount.
ContextHubMountConfig
Context Hub configuration for a sandbox mount.
ContextHubMountSpec
Read-only Context Hub-backed sandbox mount specification.
AWSMountAuthConfig
AWS credentials used by the backend to authenticate S3 mounts.
AWSMountRoleAuthConfig
IAM role restricted by the backend to this sandbox's S3 mount scopes.
GCPMountAuthConfig
GCP credentials used by the backend to authenticate GCS mounts.
SandboxMountAuthConfig
Provider auth blocks for sandbox mounts.
SandboxMountConfig
Public mount config sent to the sandbox API.
StreamControl
What a command handle needs from its transport to steer a command.
A one-way transport supplies this too, and raises from the methods it cannot honor.
AsyncStreamControl
Async equivalent of :class:StreamControl.
ExecutionResult
Result of executing a command in a sandbox.
ResourceStatus
Lightweight provisioning status for any async-created resource.
RunConfig
The user, working directory and environment commands run with.
Mirrors docker run -u / -w / -e: user and work_dir replace the
layer below, env_vars merge into it key by key. It applie
FileInfo
One filesystem entry returned by :meth:Sandbox.glob.
GlobResult
Entries matching a glob pattern.
GrepMatch
One matching line found by :meth:Sandbox.grep.
GrepResult
Lines matching a literal search.
FileStat
What a HEAD on a sandbox file reports, without transferring it.
FileChunk
Bytes returned by a ranged read, and where they sit in the file.
Snapshot
Represents a sandbox snapshot.
Snapshots are built from Docker images or captured from running sandboxes. They are used to create new sandboxes.
SnapshotTag
One tag published under a snapshot name, and the snapshot it resolves to.
ServiceURL
Authenticated URL for accessing an HTTP service running in a sandbox.
Properties auto-refresh the token transparently when it nears expiry.
HTTP helper methods (.get, .post, etc.) inject the
AsyncServiceURL
Async variant of :class:ServiceURL with auto-refreshing token.
Properties and HTTP helpers are async. Use with
:meth:AsyncSandboxClient.service or :meth:AsyncSandbox.service.
Example::
sv
DownloadURL
A link that downloads one sandbox file with no LangSmith credential.
The link is pinned to the sandbox, the file path, and the response headers, so it cannot be repointed at another file. It is pinne
ServiceLoginURL
Service URL gated by LangSmith login rather than a token.
The grant is durable: there is no token to carry and no expiry, so the URL is only usable from a browser signed in to LangSmith. That is also
OutputChunk
A single chunk of streaming output from command execution.
CommandHandle
Handle to a running command with streaming output and auto-reconnect.
Iterable, yielding OutputChunk objects (stdout and stderr interleaved in arrival order). Access .result after iteration to get th
AsyncCommandHandle
Async handle to a running command with streaming output and auto-reconnect.
Async iterable, yielding OutputChunk objects (stdout and stderr interleaved in arrival order). Access .result after iterati
Sandbox
Represents an active sandbox for running commands and file operations.
This class is typically obtained from SandboxClient.sandbox() and supports the context manager protocol for automatic cleanup.
Tunnel
TCP tunnel to a port inside a sandbox.
Opens a local TCP listener and forwards each accepted connection through a yamux-multiplexed WebSocket to the daemon, which dials the target port inside the san
AsyncTunnel
Async wrapper around :class:Tunnel.
The underlying tunnel runs in background threads (TCP listener + bridges); async context-manager methods delegate to the sync tunnel via the event loop's executo
SandboxTokenVerificationError
Raised when a sandbox user token or callback signature fails verification.
SandboxUser
The LangSmith user a service URL request was made by.
SandboxCallbackIdentity
The sandbox whose outbound request triggered a proxy callback.
SandboxCallbackRequest
Snapshot of the outbound request, sent for full_request callbacks.
SandboxCallback
A verified proxy callback payload.
SandboxTokenVerifier
Verifies tokens LangSmith signs for code running in or behind a sandbox.
Keys are fetched from LangSmith's JWKS endpoint and cached.
YamuxStream
A single multiplexed stream within a yamux session.
Streams are created via :meth:YamuxSession.open_stream and provide
blocking read/write/close with per-stream flow control.
YamuxSession
Client-side yamux session over a byte-stream connection.
The connection must implement read(n) -> bytes, write(data) -> int,
and close() -> None. Typically this is a :class:_WSAdapter
AsyncSandbox
Represents an active sandbox for running commands and file operations async.
This class is typically obtained from AsyncSandboxClient.sandbox() and supports the async context manager protocol for aut
RetryTransport
Sync httpx transport that retries on transient errors.
Retries on:
- 502/503/504 with exponential backoff
- 429 with Retry-After header support
- Connection errors/timeouts with exponential backoff
AsyncRetryTransport
Async httpx transport that retries on transient errors.
Async equivalent of RetryTransport. See RetryTransport for details.
AsyncSandboxClient
Async client for interacting with the Sandbox Server API.
This client provides an async interface for managing sandboxes and snapshots.
SandboxClient
Client for interacting with the Sandbox Server API.
This client provides a simple interface for managing sandboxes and snapshots.
SandboxClientError
Base exception for sandbox client errors.
SandboxAPIError
Raised when the API endpoint returns an unexpected error.
For example, this is raised for wrong URL or path.
SandboxAuthenticationError
Raised when authentication fails (invalid or missing API key).
SandboxConnectionError
Raised when connection to the sandbox server fails.
SandboxRetryableConnectionError
Raised when a transient failure occurs before a command can start.
run() retries this error with the same command ID, so the server can
deduplicate an attempt whose outcome is unknown.
SandboxConnectTimeoutError
Raised when the socket fails or times out before the WebSocket handshake.
The execute frame was never sent, so re-issuing the same command ID cannot double-run a command.
SandboxServerReloadError
Raised when the server sends a 1001 Going Away close frame.
This indicates a server hot-reload, not a true connection failure. The command is still running on the server.
This is a subclass of Sandb
ResourceNotFoundError
Raised when a resource is not found.
ResourceTimeoutError
Raised when an operation times out.
ResourceInUseError
Raised when deleting a resource that is still in use.
ResourceAlreadyExistsError
Raised when creating a resource that already exists.
ResourceNameConflictError
Raised when updating a resource name to one that already exists.
ValidationError
Raised when request validation fails.
This includes:
- Resource values exceeding server-defined limits (CPU, memory, storage)
- Invalid resource units
- Invalid name formats
QuotaExceededError
Raised when organization quota limits are exceeded.
Users should contact technical support via our Support Portal (https://support.langchain.com) to increase quotas.
ResourceCreationError
Raised when resource provisioning fails.
DataplaneNotConfiguredError
Raised when dataplane_url is not available for the sandbox.
This occurs when the sandbox-router URL is not configured for the cluster.
SandboxNotReadyError
Raised when attempting to interact with a sandbox that is not ready.
SandboxOperationError
Raised when a sandbox operation fails (run, read, write).
CommandTimeoutError
Raised when a command exceeds its timeout.
TunnelError
Base exception for TCP tunnel errors.
TunnelPortNotAllowedError
The daemon rejected the port as not allowed.
TunnelConnectionRefusedError
Nothing is listening on the target port inside the sandbox.
TunnelUnsupportedVersionError
Protocol version mismatch between the tunnel client and the daemon.
SandboxProxySecret
A secret value that can be used by sandbox proxy rules.
AccessDelegation
Grant letting code inside a sandbox call the LangSmith API as the creator.
mode is "INHERIT" for everything the creator can do, or
"EXPLICIT" for the subset named in permissions. Perm
TracingExtra
TracingExtra
TracingExtra
LazyProxy
Implements data methods to pretend that an instance is another instance.
This includes forwarding attribute access and other methods.
ResourcesProxy
A proxy for the langsmith.resources module.
This is used so that we can lazily import langsmith.resources only when
needed and so that users can just import langsmith and reference `langsmith
PropertyInfo
Metadata class to be used in Annotated types to provide information about a given type.
For example:
class MyParams(TypedDict): account_holder_name: Annotated[str, PropertyInfo(alias='accountHol
ExperimentResultRow
ExperimentResults
Represents the results of an evaluate() call.
This class provides an iterator interface to iterate over the experiment results as they become available. It also provides methods to access the experim
ComparativeExperimentResults
Represents the results of an evaluate_comparative() call.
This class provides an iterator interface to iterate over the comparison results, indexed access by example ID, and properties to access the
AsyncExperimentResults
CategoricalScoreConfig
Configuration for a categorical score.
ContinuousScoreConfig
Configuration for a continuous score.
LLMEvaluator
A class for building LLM-as-a-judge evaluators.
.. deprecated:: 0.5.0
LLMEvaluator is deprecated. Use openevals instead: https://github.com/langchain-ai/openevals
Category
A category for categorical feedback.
FeedbackConfig
Configuration to define a type of feedback.
Applied on on the first creation of a feedback_key.
EvaluationResult
Evaluation result.
EvaluationResults
Batch evaluation results.
This makes it easy for your evaluator to return multiple metrics at once.
RunEvaluator
Evaluator interface class.
ComparisonEvaluationResult
Feedback scores for the results of comparative evaluations.
These are generated by functions that compare two or more runs, returning a ranking or other feedback.
DynamicRunEvaluator
A dynamic evaluator that wraps a function and transforms it into a RunEvaluator.
This class is designed to be used with the @run_evaluator decorator, allowing
functions that take a Run and an o
DynamicComparisonRunEvaluator
Compare predictions (as traces) from 2 or more runs.
StringEvaluator
Grades the run's string input, output, and optional answer.
.. deprecated:: 0.5.0
StringEvaluator is deprecated. Use openevals instead: https://github.com/langchain-ai/openevals
PromptWebhooksResource
AsyncPromptWebhooksResource
PromptWebhooksResourceWithRawResponse
AsyncPromptWebhooksResourceWithRawResponse
PromptWebhooksResourceWithStreamingResponse
AsyncPromptWebhooksResourceWithStreamingResponse
InfoResource
AsyncInfoResource
InfoResourceWithRawResponse
AsyncInfoResourceWithRawResponse
InfoResourceWithStreamingResponse
AsyncInfoResourceWithStreamingResponse
ProductFeedbackResource
AsyncProductFeedbackResource
ProductFeedbackResourceWithRawResponse
AsyncProductFeedbackResourceWithRawResponse
ProductFeedbackResourceWithStreamingResponse
AsyncProductFeedbackResourceWithStreamingResponse
OnlineEvaluatorsResource
AsyncOnlineEvaluatorsResource
OnlineEvaluatorsResourceWithRawResponse
AsyncOnlineEvaluatorsResourceWithRawResponse
OnlineEvaluatorsResourceWithStreamingResponse
AsyncOnlineEvaluatorsResourceWithStreamingResponse
TracesResource
AsyncTracesResource
TracesResourceWithRawResponse
AsyncTracesResourceWithRawResponse
TracesResourceWithStreamingResponse
AsyncTracesResourceWithStreamingResponse
IssuesResource
AsyncIssuesResource
IssuesResourceWithRawResponse
AsyncIssuesResourceWithRawResponse
IssuesResourceWithStreamingResponse
AsyncIssuesResourceWithStreamingResponse
SessionsResource
AsyncSessionsResource
Functions
Modules
Types
compute_run_id_for_secondary_replica
Compute the run ID used for a secondary tracing replica.
add_sandbox_metadata
Associate the active run with a known sandbox ID without creating a run.
