API Overview
class Agent
Pydantic Fields:
name: str | None
description: str | None
ref: trace.refs.ObjectRef | None
model_name: <class 'str'>
temperature: <class 'float'>
system_message: <class 'str'>
tools: list[typing.Any]
method step
Run a step of the agent.
Args:
state: The current state of the environment.
action: The action to take.
Returns:
The new state of the environment.
class AgentState
Pydantic Fields:
name: str | None
description: str | None
ref: trace.refs.ObjectRef | None
history: list[typing.Any]
class AnnotationSpec
Pydantic Fields:
name: str | None
description: str | None
field_schema: dict[str, typing.Any]
unique_among_creators: <class 'bool'>
op_scope: list[str] | None
classmethod preprocess_field_schema
classmethod validate_field_schema
method value_is_valid
Validates a payload against this annotation spec’s schema.
Args:
payload: The data to validate against the schema
Returns:
bool: True if validation succeeds, False otherwise
class Audio
A class representing audio data in a supported format (wav or mp3).
This class handles audio data storage and provides methods for loading from different sources and exporting to files.
Attributes:
format: The audio format (currently supports ‘wav’ or ‘mp3’)
data: The raw audio data as bytes
Args:
data: The audio data (bytes or base64 encoded string)
format: The audio format (‘wav’ or ‘mp3’)
validate_base64: Whether to attempt base64 decoding of the input data
Raises:
ValueError: If audio data is empty or format is not supported
method __init__
method export
Export audio data to a file.
Args:
classmethod from_data
Create an Audio object from raw data and specified format.
path: Path where the audio file should be written
Args:
data: Audio data as bytes or base64 encoded string
format: Audio format (‘wav’ or ‘mp3’)
Returns:
Audio: A new Audio instance
Raises:
ValueError: If format is not supported
classmethod from_path
Create an Audio object from a file path.
Args:
path: Path to an audio file (must have .wav or .mp3 extension)
Returns:
Audio: A new Audio instance loaded from the file
Raises:
ValueError: If file doesn’t exist or has unsupported extension
class ClassifierMonitor
A monitor that merges multiple scorers into a single classifier.
Classifier monitors combine prompts from multiple LLMAsAJudgeScorers targeting the same model into a single scoring call.
Pydantic Fields:
name: str | None
description: str | None
ref: trace.refs.ObjectRef | None
sampling_rate: <class 'float'>
scorers: list[flow.scorer.Scorer]
op_names: list[typing.Union[typing.Literal['genai.turn_ended'], str]]
query: trace_server.interface.query.Query | None
is_traced: <class 'bool'>
active: <class 'bool'>
scorer_debounce_config: flow.monitor.ScorerDebounceConfig | None
prompt_header: str | None
prompt_footer: str | None
method activate
Activates the monitor.
Returns:
The ref to the monitor.
method deactivate
Deactivates the monitor.
Returns:
The ref to the monitor.
classmethod from_obj
Text to append after the merged classifier prompts.
Text to prepend before the merged classifier prompts.
method model_post_init
Normalize op_names at construction when a client is available.
Publishing has no per-object hook, so to also cover a bare weave.publish(monitor) (no activate()), expand short names here: anyone who will publish has typically called weave.init, so the client is set when the monitor is constructed.
Several use cases perform construction without a client, such as unit tests, inspection, deserializing a stored monitor in a worker. The guard on get_weave_client() allows construction without a client. Normalization won’t occur in this case, but that should be ok because stored monitors already hold full refs.
There is an edge case where a monitor can be created using the SDK without normalizing: if the user constructs the monitor, then calls weave.init, and then publishes it. Calling activate() or deactivate() could be a workaround for this use-case.
class Content
A class to represent content from various sources, resolving them to a unified byte-oriented representation with associated metadata.
This class must be instantiated using one of its classmethods:
- from_path()
- from_bytes()
- from_text()
- from_url()
- from_base64()
- from_data_url()
method __init__
Direct initialization is disabled. Please use a classmethod like Content.from_path() to create an instance.
Pydantic Fields:
data: <class 'bytes'>
size: <class 'int'>
mimetype: <class 'str'>
digest: <class 'str'>
filename: <class 'str'>
content_type: typing.Literal['bytes', 'text', 'base64', 'file', 'url', 'data_url', 'data_url:base64', 'data_url:encoding', 'data_url:encoding:base64']
input_type: <class 'str'>
encoding: <class 'str'>
metadata: dict[str, typing.Any] | None
extension: str | None
property art
property ref
method as_string
Display the data as a string. Bytes are decoded using the encoding attribute If base64, the data will be re-encoded to base64 bytes then decoded to an ASCII string
Returns:
str.
classmethod from_base64
Initializes Content from a base64 encoded string or bytes.
classmethod from_bytes
Initializes Content from raw bytes.
classmethod from_data_url
Initializes Content from a data URL.
classmethod from_path
Initializes Content from a local file path.
classmethod from_text
Initializes Content from a string of text.
classmethod from_url
Initializes Content by fetching bytes from an HTTP(S) URL.
Downloads the content, infers mimetype/extension from headers, URL path, and data, and constructs a Content object from the resulting bytes.
classmethod model_validate
Override model_validate to handle Content reconstruction from dict.
classmethod model_validate_json
Override model_validate_json to handle Content reconstruction from JSON.
method open
Open the file using the operating system’s default application.
This method uses the platform-specific mechanism to open the file with the default application associated with the file’s type.
Returns:
bool: True if the file was successfully opened, False otherwise.
method save
Copy the file to the specified destination path. Updates the filename and the path of the content to reflect the last saved copy.
Args:
method serialize_data
When dumping model in json mode
method to_data_url
Constructs a data URL from the content.
dest: Destination path where the file will be copied to (string or pathlib.Path) The destination path can be a file or a directory. If dest has no file extension (e.g. .txt), destination will be considered a directory.
Args:
use_base64: If True, the data will be base64 encoded. Otherwise, it will be percent-encoded. Defaults to True.
Returns:
A data URL string.
class Conversation
A conversation. Groups turns by conversation_id (no span).
continue_parent_trace controls trace isolation for the turns this conversation creates. Default False means each turn starts its own OTel trace (the right choice for the standalone Agents tab view). Set True when the application has an outer trace (e.g. a fastapi-instrumented request) that should contain the agent invocation.
Pydantic Fields:
conversation_id: <class 'str'>
conversation_name: <class 'str'>
agent_name: <class 'str'>
model: <class 'str'>
agent_id: <class 'str'>
agent_description: <class 'str'>
agent_version: <class 'str'>
include_content: <class 'bool'>
continue_parent_trace: <class 'bool'>
attributes: dict[str, typing.Any]
method end
method model_post_init
method start_turn
Create a new turn. Auto-ends the previous turn if still open.
Sets the _current_turn contextvar so the turn is visible via get_current_turn() regardless of whether a context manager is used. Each of agent_name / model / agent_id / agent_description / agent_version falls back to the conversation’s default when left empty; continue_parent_trace is inherited. Override any of them later via turn.record(...).
system_instructions (the agent’s system prompt) is carried on the turn’s invoke_agent span; it can also be set later via attribute assignment on the returned Turn, mirroring start_llm.
class Dataset
Dataset object with easy saving and automatic versioning.
Examples:
Pydantic Fields:
name: str | None
description: str | None
ref: trace.refs.ObjectRef | None
rows: trace.table.Table | trace.vals.WeaveTable
method add_rows
Create a new dataset version by appending rows to the existing dataset.
This is useful for adding examples to large datasets without having to load the entire dataset into memory.
Args:
rows: The rows to add to the dataset.
Returns:
The updated dataset.
classmethod convert_to_table
classmethod from_calls
classmethod from_hf
classmethod from_obj
classmethod from_pandas
method select
Select rows from the dataset based on the provided indices.
Args:
indices: An iterable of integer indices specifying which rows to select.
Returns:
A new Dataset object containing only the selected rows.
method to_hf
method to_pandas
class EasyPrompt
method __init__
Pydantic Fields:
name: str | None
description: str | None
ref: trace.refs.ObjectRef | None
data: <class 'list'>
config: <class 'dict'>
requirements: <class 'dict'>
property as_str
Join all messages into a single string.
property is_bound
property messages
property placeholders
property system_message
Join all messages into a system prompt message.
property system_prompt
Join all messages into a system prompt object.
property unbound_placeholders
method append
method as_dict
method as_pydantic_dict
method bind
method bind_rows
method config_table
method dump
method dump_file
classmethod from_obj
classmethod load
classmethod load_file
method messages_table
method print
method publish
method require
method run
method validate_requirement
method validate_requirements
method values_table
class Evaluation
Sets up an evaluation which includes a set of scorers and a dataset.
Calling evaluation.evaluate(model) will pass in rows from a dataset into a model matching the names of the columns of the dataset to the argument names in model.predict.
Then it will call all of the scorers and save the results in weave.
If you want to preprocess the rows from the dataset you can pass in a function to preprocess_model_input.
Examples:
Pydantic Fields:
name: str | None
description: str | None
ref: trace.refs.ObjectRef | None
dataset: <class 'dataset.dataset.Dataset'>
scorers: list[typing.Annotated[trace.op_protocol.Op | flow.scorer.Scorer, BeforeValidator(func=<function cast_to_scorer at 0x7f136d430d60>, json_schema_input_type=PydanticUndefined)]] | None
preprocess_model_input: collections.abc.Callable[[dict], dict] | None
trials: <class 'int'>
metadata: dict[str, typing.Any] | None
evaluation_name: str | collections.abc.Callable[trace.call.Call, str] | None
method evaluate
classmethod from_obj
method get_eval_results
method get_evaluate_calls
Retrieve all evaluation calls that used this Evaluation object.
Note that this returns a CallsIter instead of a single call because it’s possible to have multiple evaluation calls for a single evaluation (e.g. if you run the same evaluation multiple times).
Returns:
CallsIter: An iterator over Call objects representing evaluation runs.
Raises:
ValueError: If the evaluation has no ref (hasn’t been saved/run yet).
Examples:
method get_score_calls
Retrieve scorer calls for each evaluation run, grouped by trace ID.
Returns:
dict[str, list[Call]]: A dictionary mapping trace IDs to lists of scorer Call objects. Each trace ID represents one evaluation run, and the list contains all scorer calls executed during that run.
Examples:
method get_scores
Extract and organize scorer outputs from evaluation runs.
Returns:
dict[str, dict[str, list[Any]]]: A nested dictionary structure where:
- First level keys are trace IDs (evaluation runs)
- Second level keys are scorer names
- Values are lists of scorer outputs for that run and scorer
Examples:
Expected output:
method model_post_init
method predict_and_score
method summarize
class EvaluationLogger
This class provides an imperative interface for logging evaluations.
An evaluation is started automatically when the first prediction is logged using the log_prediction method, and finished when the log_summary method is called.
Each time you log a prediction, you will get back a ScoreLogger object. You can use this object to log scores and metadata for that specific prediction. For more information, see the ScoreLogger class.
Basic usage - log predictions with inputs and outputs directly:
Advanced usage - use context manager for dynamic outputs and nested operations:
method __init__
property attributes
property ui_url
method fail
Convenience method to fail the evaluation with an exception.
method finish
Clean up the evaluation resources explicitly without logging a summary.
Ensures all prediction calls and the main evaluation call are finalized. This is automatically called if the logger is used as a context manager.
method log_example
Log a complete example with inputs, output, and scores.
This is a convenience method that combines log_prediction and log_score for when you have all the data upfront.
Args:
inputs: The input data for the prediction
output: The output value
scores: Dictionary mapping scorer names to score values
Example:
method log_prediction
Log a prediction to the Evaluation.
Returns a ScoreLogger that can be used directly or as a context manager.
Args:
inputs: The input data for the prediction
output: The output value. Defaults to None. Can be set later using pred.output.
Returns:
ScoreLogger for logging scores and optionally finishing the prediction.
Example (direct):
pred = ev.log_prediction({'q': ’…’}, output=“answer”) pred.log_score(“correctness”, 0.9) pred.finish()
Example (context manager):
with ev.log_prediction({'q': ’…’}) as pred: response = model(…) pred.output = response pred.log_score(“correctness”, 0.9) # Automatically calls finish() on exit
method log_summary
Log a summary dict to the Evaluation.
This will calculate the summary, call the summarize op, and then finalize the evaluation, meaning no more predictions or scores can be logged.
method set_view
Attach a view to the evaluation’s main call summary under weave.views.
Saves the provided content as an object in the project and writes its reference URI under summary.weave.views.<name> for the evaluation’s evaluate call. String inputs are wrapped as text content using Content.from_text with the provided extension or mimetype.
Args:
name: The view name to display, used as the key under summary.weave.views.
content: A weave.Content instance or string to serialize.
extension: Optional file extension for string content inputs.
mimetype: Optional MIME type for string content inputs.
metadata: Optional metadata attached to newly created Content.
encoding: Text encoding for string content inputs.
Returns:
None
Examples:
class File
A class representing a file with path, mimetype, and size information.
method __init__
Initialize a File object.
Args:
property filename
Get the filename of the file.
path: Path to the file (string or pathlib.Path)
mimetype: Optional MIME type of the file - will be inferred from extension if not provided
Returns:
str: The name of the file without the directory path.
method open
Open the file using the operating system’s default application.
This method uses the platform-specific mechanism to open the file with the default application associated with the file’s type.
Returns:
bool: True if the file was successfully opened, False otherwise.
method save
Copy the file to the specified destination path.
Args:
class LLM
One LLM API call. Maps to a chat OTel span.
dest: Destination path where the file will be copied to (string or pathlib.Path) The destination path can be a file or a directory.
Pydantic Fields:
model: <class 'str'>
provider_name: <class 'str'>
response_id: <class 'str'>
response_model: <class 'str'>
output_type: <class 'str'>
system_instructions: list[str]
usage: <class 'conversation.types.Usage'>
reasoning: <class 'conversation.types.Reasoning'>
finish_reasons: list[str]
input_messages: list[conversation.types.Message]
output_messages: list[conversation.types.Message]
media_attachments: list[conversation.types.MediaAttachment]
request_temperature: float | None
request_max_tokens: int | None
request_top_p: float | None
request_frequency_penalty: float | None
request_presence_penalty: float | None
request_seed: int | None
request_stop_sequences: list[str]
request_choice_count: int | None
started_at: datetime.datetime | None
ended_at: datetime.datetime | None
method add_event
Record an OTel span event at a point in time within this span.
Use for marker / lifecycle data — permission prompts (e.g. weave.permission_request), lifecycle transitions (e.g. spawned / streaming / finished), or any custom milestone that happens at a point in time within the span’s lifetime (vs an attribute, which is a property of the span as a whole).
Must be called between span start and span end (inside with). Outside that window the call is a no-op and logs a warning.
Attach media to this LLM call.
Creates a Content object from the provided data, publishes it to get a weave:// ref, and stores only that ref. Exactly one of content, uri, or file_id must be provided.
The publish (which uploads the media) runs on a dedicated background thread so the call returns immediately without blocking the caller; one thread is dispatched per attachment so multiple uploads proceed in parallel. The placeholder MediaAttachment is appended synchronously and its ref is filled in once the upload completes. Refs are guaranteed populated before the span is emitted (the build path waits on the in-flight uploads via _await_uploads).
Attach a media URL to this LLM call.
Convenience over attach_media for the common case where the caller has a URL string from an upstream message. data: URLs are parsed into bytes and published; plain URIs are fetched and published. Empty URLs are ignored. Returns self for chaining.
method end
method model_post_init
method output
Append an assistant message to output_messages.
method record
Set multiple LLM-call fields in one call.
Manually-instrumented agents typically build up a chat span by assigning eight or more individual fields at the end of an LLM call (input_messages, output_messages, usage, response_id, etc.). record(...) collapses those into a single keyword call so the recording site stays compact.
Only fields explicitly passed (non-None) are applied — existing values are preserved. reasoning accepts either a Reasoning instance or a plain string (wrapped automatically). Returns self for chaining.
method set_attributes
Stamp arbitrary OTel attributes on this span.
Pass a dict whether you have one key or many — single-key callers use span.set_attributes({"weave.tag": "value"}). Mirrors OTel’s Span.set_attributes.
Must be called between span start and span end — i.e. inside a with block. Outside that window the call is a no-op and logs a warning. For batch ingest, populate the object’s declared fields directly and pass it to log_turn / log_conversation.
method think
Set reasoning/chain-of-thought content.
class LogResult
Result of a batch log_* call.
Pydantic Fields:
conversation_id: <class 'str'>
trace_ids: list[str]
root_span_ids: list[str]
span_count: <class 'int'>
class Markdown
A Markdown renderable.
Args:
markup (str): A string containing markdown.
code_theme (str, optional): Pygments theme for code blocks. Defaults to “monokai”. See https://pygments.org/styles/ for code themes.
justify (JustifyMethod, optional): Justify value for paragraphs. Defaults to None.
style (Union[str, Style], optional): Optional style to apply to markdown.
hyperlinks (bool, optional): Enable hyperlinks. Defaults to True.
method __init__
A media attachment on an LLM call.
Always holds a weave:// content ref URI. Raw bytes, data-URLs, and plain HTTP URIs are converted to a published Content object by LLM.attach_media before being stored here.
inline_code_lexer: (str, optional): Lexer to use if inline code highlighting is enabled. Defaults to None.
inline_code_theme: (Optional[str], optional): Pygments theme for inline code highlighting, or None for no highlighting. Defaults to None.
Pydantic Fields:
ref: <class 'str'>
modality: <class 'str'>
mime_type: <class 'str'>
class Message
A single message in a conversation.
Two construction styles are supported:
-
Flat (back-compat, ergonomic for plain text):
Message(role="assistant", content="Hi there")
-
Explicit parts (richer — supports tool calls, mixed reasoning+text, inline media):
Message(role="assistant", parts=[TextPart(content="Let me check"), ToolCallPart(id="c1", name="get_weather", arguments='{...}')])
When parts is non-empty it is the canonical representation. When empty, the serializer synthesizes a single TextPart (or ToolCallResponsePart for role="tool") from the flat fields.
Pydantic Fields:
role: typing.Literal['user', 'assistant', 'system', 'tool']
content: <class 'str'>
tool_call_id: <class 'str'>
tool_name: <class 'str'>
parts: list[typing.Annotated[conversation.types.TextPart | conversation.types.ReasoningPart | conversation.types.ToolCallPart | conversation.types.ToolCallResponsePart | conversation.types.BlobPart | conversation.types.UriPart | conversation.types.FilePart, FieldInfo(annotation=NoneType, required=True, discriminator='type')]]
classmethod assistant
Build an assistant message with optional text and tool calls.
Use plain text for simple replies; pass tool_calls when the assistant requests one or more tools. When both are present the text is emitted as a leading TextPart followed by each ToolCallPart so the chat view renders them inline.
classmethod system
Build a system message from plain text.
Build a tool-result message for a previously-requested tool call.
output may be a string, dict, list, scalar, or None — the underlying ToolCallResponsePart JSON-encodes non-strings.
classmethod user
Build a user message from plain text.
class MessagesPrompt
method __init__
Pydantic Fields:
name: str | None
description: str | None
ref: trace.refs.ObjectRef | None
messages: list[dict]
Format a single message by replacing template variables.
This method delegates to the standalone format_message_with_template_vars function for the actual formatting logic.
classmethod from_obj
class Model
Intended to capture a combination of code and data the operates on an input. For example it might call an LLM with a prompt to make a prediction or generate text.
When you change the attributes or the code that defines your model, these changes will be logged and the version will be updated. This ensures that you can compare the predictions across different versions of your model. Use this to iterate on prompts or to try the latest LLM and compare predictions across different settings
Examples:
Pydantic Fields:
name: str | None
description: str | None
ref: trace.refs.ObjectRef | None
method get_infer_method
class Monitor
Sets up a monitor to score incoming calls automatically.
Note that the op name will be converted to a weave ref using the entity and project from the Weave client. If you’re operating on multiple entities and projects with the same client, you’ll need to specify a fully-qualified weave ref. See _normalized_op_names for more details.
Examples:
Pydantic Fields:
name: str | None
description: str | None
ref: trace.refs.ObjectRef | None
sampling_rate: <class 'float'>
scorers: list[flow.scorer.Scorer]
op_names: list[typing.Union[typing.Literal['genai.turn_ended'], str]]
query: trace_server.interface.query.Query | None
is_traced: <class 'bool'>
active: <class 'bool'>
scorer_debounce_config: flow.monitor.ScorerDebounceConfig | None
method activate
Activates the monitor.
Returns:
The ref to the monitor.
method deactivate
Deactivates the monitor.
Returns:
The ref to the monitor.
classmethod from_obj
method model_post_init
Normalize op_names at construction when a client is available.
Publishing has no per-object hook, so to also cover a bare weave.publish(monitor) (no activate()), expand short names here: anyone who will publish has typically called weave.init, so the client is set when the monitor is constructed.
Several use cases perform construction without a client, such as unit tests, inspection, deserializing a stored monitor in a worker. The guard on get_weave_client() allows construction without a client. Normalization won’t occur in this case, but that should be ok because stored monitors already hold full refs.
There is an edge case where a monitor can be created using the SDK without normalizing: if the user constructs the monitor, then calls weave.init, and then publishes it. Calling activate() or deactivate() could be a workaround for this use-case.
class Object
Base class for Weave objects that can be tracked and versioned.
This class extends Pydantic’s BaseModel to provide Weave-specific functionality for object tracking, referencing, and serialization. Objects can have names, descriptions, and references that allow them to be stored and retrieved from the Weave system.
Attributes:
name (str | None): A human-readable name for the object.
description (str | None): A description of what the object represents.
ref (ObjectRef | None): A reference to the object in the Weave system.
Examples:
Pydantic Fields:
name: str | None
description: str | None
ref: trace.refs.ObjectRef | None
classmethod from_uri
Create an object instance from a Weave URI.
Args:
uri (str): The Weave URI pointing to the object.
objectify (bool): Whether to objectify the result. Defaults to True.
Returns:
Self: An instance of the class created from the URI.
Raises:
NotImplementedError: If the class doesn’t implement the required methods for deserialization.
Examples:
classmethod handle_relocatable_object
Handle validation of relocatable objects including ObjectRef and WeaveObject.
This validator handles special cases where the input is an ObjectRef or WeaveObject that needs to be properly converted to a standard Object instance. It ensures that references are preserved and that ignored types are handled correctly during the validation process.
Args:
v (Any): The value to validate.
handler (ValidatorFunctionWrapHandler): The standard pydantic validation handler.
info (ValidationInfo): Validation context information.
Returns:
Any: The validated object instance.
Examples:
This method is called automatically during object creation and validation. It handles cases like:
Strip weave serialization metadata from dict inputs.
Weave’s serialization adds _type, _class_name, and _bases to dicts for type reconstruction. These are not real model fields and must be removed before Pydantic validation, which uses extra=“forbid”.
class ObjectRef
ObjectRef(entity: ‘str’, project: ‘str’, name: ‘str’, _digest: ‘str | Future[str]’, _extra: ‘tuple[str | Future[str], …]’ = ())
method __init__
property digest
property is_digest_resolved
method as_param_dict
method delete
method get
method is_descended_from
method maybe_parse_uri
method parse_uri
method with_attr
method with_index
method with_item
method with_key
class Prompt
Pydantic Fields:
name: str | None
description: str | None
ref: trace.refs.ObjectRef | None
class SavedView
A fluent-style class for working with SavedView objects.
method __init__
property entity
property label
property project
property view_type
method add_column
method add_columns
Convenience method for adding multiple columns to the grid.
method add_filter
method add_sort
method column_index
method filter_op
method get_calls
Get calls matching this saved view’s filters and settings.
method get_known_columns
Get the set of columns that are known to exist.
method get_table_columns
method hide_column
method insert_column
classmethod load
method page_size
method pin_column_left
method pin_column_right
method remove_column
method remove_columns
Remove columns from the saved view.
method remove_filter
method remove_filters
Remove all filters from the saved view.
method rename
method rename_column
method save
Publish the saved view to the server.
method set_columns
Set the columns to be displayed in the grid.
method show_column
method sort_by
method to_grid
method to_rich_table_str
method ui_url
URL to show this saved view in the UI.
Note this is the “result” page with traces etc, not the URL for the view object.
method unpin_column
class Scorer
Pydantic Fields:
name: str | None
description: str | None
ref: trace.refs.ObjectRef | None
column_map: dict[str, str] | None
property display_name
classmethod from_obj
method model_post_init
method score
method summarize
class Session
Deprecated alias of :class:weave.Conversation.
Accepts the old session_id / session_name constructor fields and also exposes them as read/write properties that proxy to conversation_id / conversation_name. The original Session had these as model fields, so old code that reads or assigns s.session_id keeps working.
method __init__
Pydantic Fields:
conversation_id: <class 'str'>
conversation_name: <class 'str'>
agent_name: <class 'str'>
model: <class 'str'>
agent_id: <class 'str'>
agent_description: <class 'str'>
agent_version: <class 'str'>
include_content: <class 'bool'>
continue_parent_trace: <class 'bool'>
attributes: dict[str, typing.Any]
property session_id
Deprecated alias of :attr:conversation_id.
property session_name
Deprecated alias of :attr:conversation_name.
class StringPrompt
method __init__
Pydantic Fields:
name: str | None
description: str | None
ref: trace.refs.ObjectRef | None
content: <class 'str'>
classmethod from_obj
class SubAgent
A delegated agent invocation within a turn.
Maps to a nested invoke_agent OTel span in the same trace.
Pydantic Fields:
name: <class 'str'>
model: <class 'str'>
agent_id: <class 'str'>
agent_description: <class 'str'>
agent_version: <class 'str'>
system_instructions: list[str]
started_at: datetime.datetime | None
ended_at: datetime.datetime | None
method add_event
Record an OTel span event at a point in time within this span.
Use for marker / lifecycle data — permission prompts (e.g. weave.permission_request), lifecycle transitions (e.g. spawned / streaming / finished), or any custom milestone that happens at a point in time within the span’s lifetime (vs an attribute, which is a property of the span as a whole).
Must be called between span start and span end (inside with). Outside that window the call is a no-op and logs a warning.
method end
method llm
Start an LLM call within this sub-agent.
Sets the _current_llm contextvar so the LLM is visible via get_current_llm() regardless of whether a context manager is used.
method record
Set multiple sub-agent fields in one call.
Collapses the per-field assignments a manually-instrumented agent otherwise makes on a sub-agent (system_instructions, agent_id, …) into a single keyword call. Only fields explicitly passed (non-None) are applied — existing values are preserved. Returns self for chaining. Mirrors Turn.record / LLM.record.
Note: on the streaming (with) path the sub-agent span is named from name at __enter__, so set name via start_subagent / turn.subagent rather than record if you need the span name to reflect it; record still updates the gen_ai.agent.name attribute.
method set_attributes
Stamp arbitrary OTel attributes on this span.
Pass a dict whether you have one key or many — single-key callers use span.set_attributes({"weave.tag": "value"}). Mirrors OTel’s Span.set_attributes.
Must be called between span start and span end — i.e. inside a with block. Outside that window the call is a no-op and logs a warning. For batch ingest, populate the object’s declared fields directly and pass it to log_turn / log_conversation.
Start a tool execution within this sub-agent.
class Table
method __init__
property rows
method append
Add a row to the table.
method pop
Remove a row at the given index from the table.
class ContextAwareThread
A Thread that runs functions with the context of the caller.
This is a drop-in replacement for threading.Thread that ensures calls behave as expected inside the thread. Weave requires certain contextvars to be set (see call_context.py), but new threads do not automatically copy context from the parent, which can cause the call context to be lost — not good! This class automates contextvar copying so using this thread “just works” as the user probably expects.
You can achieve the same effect without this class by instead writing:
method __init__
property daemon
A boolean value indicating whether this thread is a daemon thread.
This must be set before start() is called, otherwise RuntimeError is raised. Its initial value is inherited from the creating thread; the main thread is not a daemon thread and therefore all threads created in the main thread default to daemon = False.
The entire Python program exits when only daemon threads are left.
property ident
Thread identifier of this thread or None if it has not been started.
This is a nonzero integer. See the get_ident() function. Thread identifiers may be recycled when a thread exits and another thread is created. The identifier is available even after the thread has exited.
property name
A string used for identification purposes only.
It has no semantics. Multiple threads may be given the same name. The initial name is set by the constructor.
property native_id
Native integral thread ID of this thread, or None if it has not been started.
This is a non-negative integer. See the get_native_id() function. This represents the Thread ID as reported by the kernel.
method run
class ThreadContext
Context object providing access to current thread and turn information.
method __init__
Initialize ThreadContext with the specified thread_id.
Args:
property thread_id
Get the thread_id for this context.
thread_id: The thread identifier for this context, or None if disabled.
Returns:
The thread identifier, or None if thread tracking is disabled.
property turn_id
Get the current turn_id from the active context.
Returns:
The current turn_id if set, None otherwise.
class ContextAwareThreadPoolExecutor
A ThreadPoolExecutor that runs functions with the context of the caller.
This is a drop-in replacement for concurrent.futures.ThreadPoolExecutor that ensures weave calls behave as expected inside the executor. Weave requires certain contextvars to be set (see call_context.py), but new threads do not automatically copy context from the parent, which can cause the call context to be lost — not good! This class automates contextvar copying so using this executor “just works” as the user probably expects.
You can achieve the same effect without this class by instead writing:
method __init__
method map
method submit
One tool execution. Maps to an execute_tool OTel span.
arguments and result use the JSONString annotation: callers can assign a dict / list / scalar and the SDK JSON-encodes it at construction or assignment. The stored value is always a string, matching the wire format per GenAI semconv.
Pydantic Fields:
name: <class 'str'>
arguments: <class 'str'>
result: <class 'str'>
tool_call_id: <class 'str'>
tool_type: <class 'str'>
tool_description: <class 'str'>
tool_definitions: <class 'str'>
duration_ms: <class 'int'>
started_at: datetime.datetime | None
ended_at: datetime.datetime | None
method add_event
Record an OTel span event at a point in time within this span.
Use for marker / lifecycle data — permission prompts (e.g. weave.permission_request), lifecycle transitions (e.g. spawned / streaming / finished), or any custom milestone that happens at a point in time within the span’s lifetime (vs an attribute, which is a property of the span as a whole).
Must be called between span start and span end (inside with). Outside that window the call is a no-op and logs a warning.
method end
method set_attributes
Stamp arbitrary OTel attributes on this span.
Pass a dict whether you have one key or many — single-key callers use span.set_attributes({"weave.tag": "value"}). Mirrors OTel’s Span.set_attributes.
Must be called between span start and span end — i.e. inside a with block. Outside that window the call is a no-op and logs a warning. For batch ingest, populate the object’s declared fields directly and pass it to log_turn / log_conversation.
class Turn
One user-agent exchange. Maps to an invoke_agent OTel span.
By default each turn starts its own OTel trace (continue_parent_trace=False) so the Agents tab shows one trace per turn. Set continue_parent_trace=True on the Conversation (or directly on the Turn) when an outer trace is already active and you want the agent invocation to nest inside it — e.g. inside a fastapi-instrumented request.
Pydantic Fields:
agent_name: <class 'str'>
model: <class 'str'>
agent_id: <class 'str'>
agent_description: <class 'str'>
agent_version: <class 'str'>
system_instructions: list[str]
messages: list[conversation.types.Message]
spans: list[conversation.conversation.LLM | conversation.conversation.Tool | conversation.conversation.SubAgent]
continue_parent_trace: <class 'bool'>
started_at: datetime.datetime | None
ended_at: datetime.datetime | None
method add_event
Record an OTel span event at a point in time within this span.
Use for marker / lifecycle data — permission prompts (e.g. weave.permission_request), lifecycle transitions (e.g. spawned / streaming / finished), or any custom milestone that happens at a point in time within the span’s lifetime (vs an attribute, which is a property of the span as a whole).
Must be called between span start and span end (inside with). Outside that window the call is a no-op and logs a warning.
method end
method llm
Start an LLM call (chat span, child of this turn).
Sets the _current_llm contextvar so the LLM is visible via get_current_llm() regardless of whether a context manager is used.
method model_post_init
method record
Set multiple turn fields in one call.
Collapses the per-field assignments a manually-instrumented agent otherwise makes on a turn (system_instructions, agent_id, …) into a single keyword call. Only fields explicitly passed (non-None) are applied — existing values are preserved. messages replaces the turn’s existing messages (unlike Turn.user(...), which appends a single message). Returns self for chaining. Mirrors LLM.record.
Note: on the streaming (with) path the turn span is named from agent_name at __enter__, so set agent_name via start_turn rather than record if you need the span name to reflect it; record still updates the gen_ai.agent.name attribute.
method set_attributes
Stamp arbitrary OTel attributes on this span.
Pass a dict whether you have one key or many — single-key callers use span.set_attributes({"weave.tag": "value"}). Mirrors OTel’s Span.set_attributes.
Must be called between span start and span end — i.e. inside a with block. Outside that window the call is a no-op and logs a warning. For batch ingest, populate the object’s declared fields directly and pass it to log_turn / log_conversation.
method subagent
Start a sub-agent invocation (nested invoke_agent span, same trace).
Start a tool execution (execute_tool span, child of this turn).
method user
Append a user message mid-turn.
class Usage
Token usage for an LLM call.
Pydantic Fields:
input_tokens: <class 'int'>
output_tokens: <class 'int'>
reasoning_tokens: <class 'int'>
cache_creation_input_tokens: <class 'int'>
cache_read_input_tokens: <class 'int'>
Add tags to an object version.
Args:
function as_op
Given a @weave.op decorated function, return its Op.
@weave.op decorated functions are instances of Op already, so this function should be a no-op at runtime. But you can use it to satisfy type checkers if you need to access OpDef attributes in a typesafe way.
obj_ref: Reference to the object version, either an ObjectRef (returned by weave.publish()) or a weave /// URI string.
tags: List of tag strings to add.
Args:
fn: A weave.op decorated function.
Returns:
The Op of the function.
function attributes
Context manager for setting attributes on a call.
Example:
function end_conversation
End the current conversation (from contextvar).
function end_llm
End the current LLM call (from contextvar).
function end_session
Deprecated alias of :func:weave.end_conversation.
function end_turn
End the current turn (from contextvar).
function finish
Stops logging to weave.
Following finish, calls of weave.op decorated functions will no longer be logged. You will need to run weave.init() again to resume logging.
function get
A convenience function for getting an object from a URI.
Many objects logged by Weave are automatically registered with the Weave server. This function allows you to retrieve those objects by their URI.
Args:
uri: A fully-qualified weave ref URI.
Returns:
The object.
Example:
function get_aliases
Get aliases for an object version.
Args:
obj_ref: Reference to the object version, either an ObjectRef or a weave /// URI string.
Returns:
List of alias strings.
function get_client
function get_current_call
Get the Call object for the currently executing Op, within that Op.
Returns:
The Call object for the currently executing Op, or None if tracking has not been initialized or this method is invoked outside an Op.
Note:
The returned Call’s attributes dictionary becomes immutable once the call starts. Use :func:weave.attributes to set call metadata before invoking an Op. The summary field may be updated while the Op executes and will be merged with computed summary information when the call finishes.
function get_current_conversation
Return the active conversation from contextvar, or None.
function get_current_llm
Return the active LLM call from contextvar, or None.
function get_current_session
Deprecated alias of :func:weave.get_current_conversation.
function get_current_turn
Return the active turn from contextvar, or None.
Get tags for an object version.
Args:
obj_ref: Reference to the object version, either an ObjectRef or a weave /// URI string.
Returns:
List of tag strings.
Get both tags and aliases for an object version in a single call.
Args:
obj_ref: Reference to the object version, either an ObjectRef or a weave /// URI string.
Returns:
A tuple of (tags, aliases). Each is a list of strings.
function init
Initialize weave tracking, logging to a wandb project.
Logging is initialized globally, so you do not need to keep a reference to the return value of init.
Following init, calls of weave.op decorated functions will be logged to the specified project.
Args:
NOTE: Client-level postprocessing runs after each op’s own postprocessing. The order is always: 1. Op-specific postprocessing 2. Client-level postprocessing
project_name: The name of the Weights & Biases team and project to log to. If you don’t specify a team, your default entity is used. To find or update your default entity, refer to User Settings in the W&B documentation.
settings: Configuration for the Weave client generally. Can be a UserSettings instance or a dict with any of the following keys (all optional). All settings can also be configured via environment variables using the prefix WEAVE_ (e.g., WEAVE_DISABLED=true). Available settings: - disabled (bool): Disables traces on all functions. Default: False - print_call_link (bool): Prints links in terminal to Weave UI for ops. Default: True - log_level (str): Sets what type of information to log (DEBUG, INFO, WARNING, ERROR, CRITICAL). Default: INFO - display_viewer (str): Controls how Weave displays objects in the console (auto, rich, print). Default: auto - capture_code (bool): Captures code of traced ops to your Weave project. Default: True - implicitly_patch_integrations (bool): Auto-patches supported libraries. Default: True - redact_pii (bool): Scans all trace data for sensitive information, like emails, phone numbers, and credit cards, and replaces them with placeholder values before sending to the server. Requires presidio-analyzer and presidio-anonymizer packages.
Default: False - redact_pii_fields (list[str]): Specifies which PII entity types to redact when redact_pii is True. If empty, uses Presidio’s default set. Examples [‘EMAIL’,‘PHONE_NUMBER’,‘CREDIT_CARD’,‘US_SSN’]. See full list at https://microsoft.github.io/presidio/supported_entities/
Default: [] - redact_pii_exclude_fields (list[str]): PII entity types to exclude. Default: [] - capture_client_info (bool): Captures Python/SDK version info. Default: True - capture_system_info (bool): Captures OS information. Default: True - client_parallelism (int): Number of workers for background ops. Default: auto - use_server_cache (bool): Enables local disk caching of server responses. - server_cache_size_limit (int): Cache size limit in bytes. Default: 1_000_000_000 - server_cache_dir (str): Directory for server cache. Default: temporary - scorers_dir (str): Directory for scorer model checkpoints. Default: ~/.cache/wandb/weave-scorers - max_calls_queue_size (int): Maximum queue size (0 = unbounded). Default: 100_000 - retry_max_interval (float): Maximum retry interval in seconds. Default: 300 - retry_max_attempts (int): Maximum number of retries. Default: 3 - enable_disk_fallback (bool): Writes dropped items to disk. Default: True - use_parallel_table_upload (bool): Enables parallel chunked upload for large tables. If False, tables are uploaded sequentially in smaller chunks.
Default: True - http_timeout (float): Maximum time in seconds to wait for HTTP requests to complete. This includes connection time, data transfer, and server processing. Increase for slow networks or when working with large payloads.
Default: 30.0 - use_stainless_server (bool): Uses the Stainless-generated HTTP client which provides better type safety, automatic retries, and improved error handling. This is experimental and may become the default in future versions.
Default: False - use_calls_complete (bool): Uses an optimized write path that batches complete call data (start and end) into a single request instead of separate start/end requests. This reduces server load and improves performance, especially for short-lived ops.
Default: True - use_otel_v2: (bool): Routes OTel-capable integrations through their OTel variant.
Default: True
autopatch_settings: (Deprecated) Configuration for autopatch integrations. Use explicit patching instead.
postprocess_inputs: A function applied to the inputs of every op traced by this client.
postprocess_output: A function applied to the output of every op traced by this client.
attributes: A dictionary of attributes applied to every trace produced by this client.
Returns:
A Weave client.
function link_prompt_to_registry
Link a published prompt version into the registry.
Args:
prompt: A published prompt, an ObjectRef, or a fully qualified weave ///… URI string.
target_path: Registry destination path in the format <registry_project>/<portfolio_name>, for example wandb-registry-prompts/my-prompt-collection.
aliases: Optional aliases to attach to the created registry version.
Returns:
LinkAssetToRegistryRes: Parsed response from the registry-link endpoint.
function list_aliases
List all distinct aliases in the project.
Returns:
Sorted list of all alias strings in the project.
List all distinct tags in the project.
Returns:
Sorted list of all tag strings in the project.
function log_call
Log a call directly to Weave without using the decorator pattern.
This function provides an imperative API for logging operations to Weave, useful when you want to log calls after they’ve already been executed or when the decorator pattern isn’t suitable for your use case.
Args:
op (str): The operation name to log. This will be used as the op_name for the call. Anonymous operations (strings not referring to published ops) are supported.
inputs (dict[str, Any]): A dictionary of input parameters for the operation.
output (Any): The output/result of the operation.
parent (Call | None): Optional parent call to nest this call under. If not provided, the call will be a root-level call (or nested under the current call context if one exists). Defaults to None.
attributes (dict[str, Any] | None): Optional metadata to attach to the call. These are frozen once the call is created. Defaults to None.
display_name (str | Callable[[Call], str] | None): Optional display name for the call in the UI. Can be a string or a callable that takes the call and returns a string. Defaults to None.
use_stack (bool): Whether to push the call onto the runtime stack. When True, the call will be available in the call context and can be accessed via weave.require_current_call(). When False, the call is logged but not added to the call stack. Defaults to True.
exception (BaseException | None): Optional exception to log if the operation failed. Defaults to None.
Returns:
Call: The created and finished Call object with full trace information.
Examples:
Basic usage:
function log_conversation
Imperatively emit a complete conversation.
Each Turn’s .spans attribute provides its children. Auto-generates conversation_id if empty. By default each turn gets its own OTel trace. agent_name / model / agent_id / agent_description / agent_version are conversation-level defaults — a Turn’s own value wins; the conversation value only fills in when the Turn leaves it empty. The conversation’s continue_parent_trace applies to every turn (a per-Turn continue_parent_trace is intentionally superseded here).
attributes are stamped on every emitted span. Use custom, non-semconv keys: a key that collides with a span’s own gen_ai.* / weave.* attribute is unsupported (which value wins is path-dependent).
function log_session
Deprecated alias of :func:weave.log_conversation.
session_id / session_name map to conversation_id / conversation_name.
function log_turn
Imperatively emit one turn and its child spans to OTel.
Use when context managers aren’t viable (stateless containers, callbacks, queue workers). Each child span passed in should have started_at / ended_at set; the emitted OTel span timestamps come from those fields. Falls back to the earliest/latest child timestamp, then now(), when the turn doesn’t supply its own. agent_id / agent_description / agent_version mirror the streaming path.
attributes are stamped on every emitted span; the streaming path reads these from the active conversation instead. Use custom, non-semconv keys: a key that collides with a span’s own gen_ai.* / weave.* attribute is unsupported (which value wins is path-dependent).
function op
A decorator to weave op-ify a function or method. Works for both sync and async. Automatically detects iterator functions and applies appropriate behavior.
Args:
function otel_traces_endpoint
Return the full OTLP HTTP endpoint URL for Weave GenAI trace ingestion.
External callers (e.g. boot-time probes that want to verify the ingest endpoint is reachable before relying on the BatchSpanProcessor to silently drop exports) should call this rather than constructing the URL by hand. The path is owned by the SDK and may move.
func: The function to decorate.
name: Custom name for the op. Defaults to the function name.
call_display_name: Display name for calls, can be a string or callable.
postprocess_inputs: Function to transform inputs before logging.
postprocess_output: Function to transform output before logging.
tracing_sample_rate: Fraction of calls to trace (0.0 to 1.0).
enable_code_capture: Whether to capture source code for this op.
accumulator: Function to accumulate results for streaming ops.
attributes: Default attributes merged into every call this op creates, at the lowest precedence. A weave.attributes() context and explicit per-call attributes override them on key collision. The reserved “weave” key may not be set here.
eager_call_start: If True, call starts are sent immediately rather than batched. Useful for long-running operations like evaluations that should be visible in the UI immediately.
Args:
function publish
Save and version a Python object.
Weave creates a new version of the object if the object’s name already exists and its content hash does not match the latest version of that object.
base_url: Trace server base URL. Defaults to weave_trace_server_url().
Args:
obj: The object to save and version.
name: The name to save the object under.
tags: Optional list of tags to add to the published object version.
aliases: Optional list of aliases to set on the published object version.
Returns:
A Weave Ref to the saved object.
function ref
Creates a Ref to an existing Weave object. This does not directly retrieve the object but allows you to pass it to other Weave API functions.
Args:
location: A Weave Ref URI, or if weave.init() has been called, name:version or name. If no version is provided, latest is used.
Returns:
A Weave Ref to the object.
function remove_aliases
Remove one or more aliases from an object.
Args:
Remove tags from an object version.
obj_ref: Reference to the object, either an ObjectRef or a weave /// URI string.
alias: An alias name or list of alias names to remove.
Args:
function require_current_call
Get the Call object for the currently executing Op, within that Op.
This allows you to access attributes of the Call such as its id or feedback while it is running.
It is also possible to access a Call after the Op has returned.
If you have the Call’s id, perhaps from the UI, you can use the get_call method on the WeaveClient returned from weave.init to retrieve the Call object.
Alternately, after defining your Op you can use its call method. For example:
obj_ref: Reference to the object version, either an ObjectRef or a weave /// URI string.
tags: List of tag strings to remove.
Returns:
The Call object for the currently executing Op
Raises:
NoCurrentCallError: If tracking has not been initialized or this method is invoked outside an Op.
function set_aliases
Set one or more aliases for an object version.
Args:
function set_view
Attach a custom view to the current call summary at _weave.views.<name>.
obj_ref: Reference to the object version, either an ObjectRef or a weave /// URI string.
alias: An alias name or list of alias names to set (e.g., “production”).
Args:
name: The view name (key under summary._weave.views).
content: A weave.Content instance or raw string. Strings are wrapped via Content.from_text using the supplied extension or mimetype.
extension: Optional file extension to use when content is a string.
mimetype: Optional MIME type to use when content is a string.
metadata: Optional metadata to attach when creating Content from text.
encoding: Text encoding to apply when creating Content from text.
Returns:
None
Examples:
function start_conversation
Create and activate a conversation. Sets the contextvar for cross-module access.
attributes are stamped on every span this conversation emits (e.g. an integration identity like weave.integration.*). Use custom, non-semconv keys: set semantic-convention fields via the typed params (conversation_name, model, …). A key that collides with a span’s own gen_ai.* / weave.* attribute is unsupported; which value wins is path-dependent (streaming vs log_turn).
function start_llm
Create and activate an LLM call. Uses the current turn if available.
If no turn is active, returns a disconnected LLM (no contextvar set).
Pass provider_name explicitly. The SDK does not infer it from the model identifier: prefix-based guessing misattributes user fine-tunes (e.g. a model named text-...) and bakes assumptions about future model names into telemetry that’s expensive to correct after the fact.
function start_session
Deprecated alias of :func:weave.start_conversation.
session_id / session_name map to conversation_id / conversation_name.
function start_subagent
Create a sub-agent invocation span.
The SubAgent’s OTel span automatically becomes a child of whatever span is current in OTel context — typically a Turn span if one is active. Mirrors start_tool in shape; OTel context handles parent-child propagation, no explicit delegation is needed.
Create a tool execution span.
The Tool’s OTel span automatically becomes a child of whatever span is current in OTel context — typically a Turn span if one is active. No explicit turn delegation is needed: parent-child propagation happens via OTel context, not via the Conversation SDK contextvars.
function start_turn
Create and activate a turn. Uses the current conversation if available.
If no conversation is active, returns a disconnected Turn that is NOT set in the contextvar. This means get_current_turn() will return None. Use conversation.start_turn() instead if you need contextvar-based cross-module access.
function thread
Context manager for setting thread_id on calls within the context.
Examples:
Args:
thread_id: The thread identifier to associate with calls in this context. If not provided, a UUID v7 will be auto-generated. If None, thread tracking will be disabled.
Yields:
ThreadContext: An object providing access to thread_id and current turn_id.
function wandb_init_hook
Last modified on October 12, 2026