Run Helpers
run_helpers
¶
Decorator for creating a run tree from functions.
| FUNCTION | DESCRIPTION |
|---|---|
get_current_run_tree |
Get the current run tree. |
set_run_metadata |
Update metadata on the current run tree. |
get_tracing_context |
Get the current tracing context. |
tracing_context |
Set the tracing context for a block of code. |
is_traceable_function |
Check if a function is |
ensure_traceable |
Ensure that a function is traceable. |
is_async |
Inspect function or wrapped function to see if it is async. |
traceable |
Trace a function with langsmith. |
as_runnable |
Convert a function wrapped by the LangSmith |
LangSmithExtra
¶
SupportsLangsmithExtra
¶
Bases: Protocol, Generic[P, R]
Implementations of this Protocol accept an optional langsmith_extra parameter.
| METHOD | DESCRIPTION |
|---|---|
__call__ |
Call the instance when it is called as a function. |
__call__
¶
__call__(
*args: args, langsmith_extra: LangSmithExtra | None = None, **kwargs: kwargs
) -> R
Call the instance when it is called as a function.
| PARAMETER | DESCRIPTION |
|---|---|
*args
|
Variable length argument list.
TYPE:
|
langsmith_extra
|
Optional dictionary containing additional parameters specific to Langsmith.
TYPE:
|
**kwargs
|
Arbitrary keyword arguments.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
R
|
The return value of the method.
TYPE:
|
trace
¶
Manage a LangSmith run in context.
This class can be used as both a synchronous and asynchronous context manager.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
Name of the run.
TYPE:
|
run_type
|
Type of run (e.g.,
TYPE:
|
inputs
|
Initial input data for the run.
TYPE:
|
project_name
|
Project name to associate the run with.
TYPE:
|
parent
|
Parent run. Can be a
TYPE:
|
tags
|
List of tags for the run. |
metadata
|
Additional metadata for the run. |
client
|
LangSmith client for custom settings.
TYPE:
|
run_id
|
Preset identifier for the run.
TYPE:
|
reference_example_id
|
Associates run with a dataset example. Only for root runs in evaluation.
TYPE:
|
exceptions_to_handle
|
Exception types to ignore.
TYPE:
|
extra
|
Extra data to send to LangSmith. Use 'metadata' instead.
TYPE:
|
Examples:
Synchronous usage:
with trace("My Operation", run_type="tool", tags=["important"]) as run:
result = "foo" # Perform operation
run.metadata["some-key"] = "some-value"
run.end(outputs={"result": result})
Asynchronous usage:
async def main():
async with trace("Async Operation", run_type="tool", tags=["async"]) as run:
result = "foo" # Await async operation
run.metadata["some-key"] = "some-value"
# "end" just adds the outputs and sets error to None
# The actual patching of the run happens when the context exits
run.end(outputs={"result": result})
asyncio.run(main())
Handling specific exceptions:
import pytest
import sys
with trace("Test", exceptions_to_handle=(pytest.skip.Exception,)):
if sys.platform == "win32": # Just an example
pytest.skip("Skipping test for windows")
result = "foo" # Perform test operation
| METHOD | DESCRIPTION |
|---|---|
__init__ |
Initialize the trace context manager. |
__enter__ |
Enter the context manager synchronously. |
__exit__ |
Exit the context manager synchronously. |
__aenter__ |
Enter the context manager asynchronously. |
__aexit__ |
Exit the context manager asynchronously. |
__init__
¶
__init__(
name: str,
run_type: RUN_TYPE_T = "chain",
*,
inputs: dict | None = None,
extra: dict | None = None,
project_name: str | None = None,
parent: RunTree | str | Mapping | Literal["ignore"] | None = None,
tags: list[str] | None = None,
metadata: Mapping[str, Any] | None = None,
client: Client | None = None,
run_id: ID_TYPE | None = None,
reference_example_id: ID_TYPE | None = None,
exceptions_to_handle: tuple[type[BaseException], ...] | None = None,
attachments: Attachments | None = None,
**kwargs: Any,
)
Initialize the trace context manager.
Warns if unsupported kwargs are passed.
__enter__
¶
__enter__() -> RunTree
Enter the context manager synchronously.
| RETURNS | DESCRIPTION |
|---|---|
RunTree
|
run_trees.RunTree: The newly created run. |
__exit__
¶
__exit__(
exc_type: type[BaseException] | None = None,
exc_value: BaseException | None = None,
traceback: TracebackType | None = None,
) -> None
Exit the context manager synchronously.
| PARAMETER | DESCRIPTION |
|---|---|
exc_type
|
The type of the exception that occurred, if any.
TYPE:
|
exc_value
|
The exception instance that occurred, if any.
TYPE:
|
traceback
|
The traceback object associated with the exception, if any.
TYPE:
|
__aenter__
async
¶
__aenter__() -> RunTree
Enter the context manager asynchronously.
| RETURNS | DESCRIPTION |
|---|---|
RunTree
|
run_trees.RunTree: The newly created run. |
__aexit__
async
¶
__aexit__(
exc_type: type[BaseException] | None = None,
exc_value: BaseException | None = None,
traceback: TracebackType | None = None,
) -> None
Exit the context manager asynchronously.
| PARAMETER | DESCRIPTION |
|---|---|
exc_type
|
The type of the exception that occurred, if any.
TYPE:
|
exc_value
|
The exception instance that occurred, if any.
TYPE:
|
traceback
|
The traceback object associated with the exception, if any.
TYPE:
|
set_run_metadata
¶
set_run_metadata(**metadata: Any) -> None
Update metadata on the current run tree.
get_tracing_context
¶
Get the current tracing context.
tracing_context
¶
tracing_context(
*,
project_name: str | None = None,
tags: list[str] | None = None,
metadata: dict[str, Any] | None = None,
parent: RunTree | Mapping | str | Literal[False] | None = None,
enabled: bool | Literal["local"] | None = None,
client: Client | None = None,
replicas: Sequence[WriteReplica] | None = None,
distributed_parent_id: str | None = None,
**kwargs: Any,
) -> Generator[None, None, None]
Set the tracing context for a block of code.
| PARAMETER | DESCRIPTION |
|---|---|
project_name
|
The name of the project to log the run to.
TYPE:
|
tags
|
The tags to add to the run. |
metadata
|
The metadata to add to the run. |
parent
|
The parent run to use for the context. Can be a Run/
TYPE:
|
client
|
The client to use for logging the run to LangSmith.
TYPE:
|
enabled
|
Whether tracing is enabled. Defaults to |
replicas
|
A sequence of Example:
TYPE:
|
distributed_parent_id
|
The distributed parent ID for distributed tracing. Defaults to None.
TYPE:
|
is_traceable_function
¶
is_traceable_function(func: Any) -> TypeGuard[SupportsLangsmithExtra[P, R]]
Check if a function is @traceable decorated.
ensure_traceable
¶
ensure_traceable(
func: Callable[P, R],
*,
name: str | None = None,
metadata: Mapping[str, Any] | None = None,
tags: list[str] | None = None,
client: Client | None = None,
reduce_fn: Callable[[Sequence], dict | str] | None = None,
project_name: str | None = None,
process_inputs: Callable[[dict], dict] | None = None,
process_outputs: Callable[..., dict] | None = None,
process_chunk: Callable | None = None,
) -> SupportsLangsmithExtra[P, R]
Ensure that a function is traceable.
is_async
¶
Inspect function or wrapped function to see if it is async.
traceable
¶
Trace a function with langsmith.
| PARAMETER | DESCRIPTION |
|---|---|
run_type
|
The type of run (span) to create. Examples: Defaults to "chain".
|
name
|
The name of the run. Defaults to the function name.
|
metadata
|
The metadata to add to the run. Defaults to
|
tags
|
The tags to add to the run. Defaults to
|
client
|
The client to use for logging the run to LangSmith. Defaults to
|
reduce_fn
|
A function to reduce the output of the function if the function returns a generator. Defaults to Note If the iterator is never exhausted (e.g. the function returns an infinite generator), this will never be called, and the run itself will be stuck in a pending state.
|
project_name
|
The name of the project to log the run to. Defaults to
|
process_inputs
|
Custom serialization / processing function for inputs. Defaults to
|
process_outputs
|
Custom serialization / processing function for outputs. Defaults to
|
dangerously_allow_filesystem
|
Whether to allow filesystem access for attachments. Defaults to Traces that reference local filepaths will be uploaded to LangSmith. In general, network-hosted applications should not be using this because referenced files are usually on the user's machine, not the host machine.
|
| RETURNS | DESCRIPTION |
|---|---|
Callable | Callable[[Callable], Callable]
|
The decorated function. |
Note
Requires that LANGSMITH_TRACING_V2 be set to 'true' in the environment.
Examples:
Basic usage
@traceable
def my_function(x: float, y: float) -> float:
return x + y
my_function(5, 6)
@traceable
async def my_async_function(query_params: dict) -> dict:
async with httpx.AsyncClient() as http_client:
response = await http_client.get(
"https://api.example.com/data",
params=query_params,
)
return response.json()
asyncio.run(my_async_function({"param": "value"}))
Streaming data with a generator
Async streaming data
@traceable
async def my_async_generator(query_params: dict) -> Iterable:
async with httpx.AsyncClient() as http_client:
response = await http_client.get(
"https://api.example.com/data",
params=query_params,
)
for item in response.json():
yield item
async def async_code():
async for item in my_async_generator({"param": "value"}):
print(item)
asyncio.run(async_code())
Specifying a run type and name
Logging with custom metadata and tags
Specifying a custom client and project name
as_runnable
¶
Convert a function wrapped by the LangSmith @traceable decorator to a Runnable.
| PARAMETER | DESCRIPTION |
|---|---|
traceable_fn
|
The function wrapped by the
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Runnable
|
A
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ImportError
|
If |
ValueError
|
If the provided function is not wrapped by the |
Example
@traceable ... def my_function(input_data): ... # Function implementation ... pass runnable = as_runnable(my_function)