API Overview
class Agent
Pydantic Fields:
name:str | Nonedescription:str | Noneref:trace.refs.ObjectRef | Nonemodel_name:<class 'str'>temperature:<class 'float'>system_message:<class 'str'>tools:list[typing.Any]
method step
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 | Nonedescription:str | Noneref:trace.refs.ObjectRef | Nonehistory:list[typing.Any]
class AnnotationSpec
Pydantic Fields:
name:str | Nonedescription:str | Nonefield_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
-
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
-
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
classmethod from_data
-
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
ValueError: If format is not supported
classmethod from_path
-
path: Path to an audio file (must have .wav or .mp3 extension) Returns: -
Audio: A new Audio instance loaded from the file
ValueError: If file doesn’t exist or has unsupported extension
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__
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] | Noneextension:str | None
property art
property ref
method as_string
encoding attribute If base64, the data will be re-encoded to base64 bytes then decoded to an ASCII string
Returns:
str.
classmethod from_base64
classmethod from_bytes
classmethod from_data_url
classmethod from_path
classmethod from_text
classmethod from_url
classmethod model_validate
classmethod model_validate_json
method open
bool: True if the file was successfully opened, False otherwise.
method save
method serialize_data
method to_data_url
-
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 Dataset
Dataset object with easy saving and automatic versioning.
Examples:
name:str | Nonedescription:str | Noneref:trace.refs.ObjectRef | Nonerows:trace.table.Table | trace.vals.WeaveTable
method add_rows
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
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__
name:str | Nonedescription:str | Noneref:trace.refs.ObjectRef | Nonedata:<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 configure
method dump
method dump_file
method format
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:
name:str | Nonedescription:str | Noneref:trace.refs.ObjectRef | Nonedataset:<class 'dataset.dataset.Dataset'>scorers:list[typing.Annotated[trace.op_protocol.Op | flow.scorer.Scorer, BeforeValidator(func=<function cast_to_scorer at 0x7fa9722cf880>, json_schema_input_type=PydanticUndefined)]] | Nonepreprocess_model_input:collections.abc.Callable[[dict], dict] | Nonetrials:<class 'int'>metadata:dict[str, typing.Any] | Noneevaluation_name:str | collections.abc.Callable[trace.call.Call, str] | None
method evaluate
classmethod from_obj
method get_eval_results
method get_evaluate_calls
CallsIter: An iterator over Call objects representing evaluation runs.
ValueError: If the evaluation has no ref (hasn’t been saved/run yet).
method get_score_calls
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.
method get_scores
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
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:
name:str | Nonemodel:flow.model.Model | dict | strdataset:dataset.dataset.Dataset | list[dict] | streval_attributes:dict[str, typing.Any]scorers:list[str] | None
property attributes
property ui_url
method fail
method finish
method log_example
inputs: The input data for the predictionoutput: The output valuescores: Dictionary mapping scorer names to score values Example:
method log_prediction
inputs: The input data for the predictionoutput: The output value. Defaults to None. Can be set later using pred.output. Returns: ScoreLogger for logging scores and optionally finishing the prediction.
pred = ev.log_prediction({'q': ’…’}, output=“answer”) pred.log_score(“correctness”, 0.9) pred.finish()
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
method model_post_init
method set_view
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 undersummary.weave.views.content: Aweave.Contentinstance 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 createdContent.encoding: Text encoding for string content inputs. Returns: None
import weave
ev = weave.EvaluationLogger() ev.set_view(“report”, ”# Report”, extension=“md”)
class File
A class representing a file with path, mimetype, and size information.
method __init__
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
bool: True if the file was successfully opened, False otherwise.
method save
class Markdown
A Markdown renderable.
-
dest: Destination path where the file will be copied to (string or pathlib.Path) The destination path can be a file or a directory. 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 toTrue.
method __init__
class MessagesPrompt
method __init__
-
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: -
name:str | None -
description:str | None -
ref:trace.refs.ObjectRef | None -
messages:list[dict]
method format
method format_message
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:
name:str | Nonedescription:str | Noneref:trace.refs.ObjectRef | None
method get_infer_method
class Monitor
Sets up a monitor to score incoming calls automatically.
Examples:
name:str | Nonedescription:str | Noneref:trace.refs.ObjectRef | Nonesampling_rate:<class 'float'>scorers:list[flow.scorer.Scorer]op_names:list[str]query:trace_server.interface.query.Query | Noneactive:<class 'bool'>
method activate
method deactivate
classmethod from_obj
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(Optional[str]): A human-readable name for the object.description(Optional[str]): A description of what the object represents.ref(Optional[ObjectRef]): A reference to the object in the Weave system.
name:str | Nonedescription:str | Noneref:trace.refs.ObjectRef | None
classmethod from_uri
uri(str): The Weave URI pointing to the object.objectify(bool): Whether to objectify the result. Defaults to True.
Self: An instance of the class created from the URI.
NotImplementedError: If the class doesn’t implement the required methods for deserialization.
classmethod handle_relocatable_object
v(Any): The value to validate.handler(ValidatorFunctionWrapHandler): The standard pydantic validation handler.info(ValidationInfo): Validation context information.
Any: The validated object instance.
When an ObjectRef is passed
obj = MyObject(some_object_ref)When a WeaveObject is passed
obj = MyObject(some_weave_object)property digest
property extra
method as_param_dict
method delete
method get
method is_descended_from
method maybe_parse_uri
method parse_uri
method uri
method with_attr
method with_extra
method with_index
method with_item
method with_key
class EasyPrompt
method __init__
name:str | Nonedescription:str | Noneref:trace.refs.ObjectRef | Nonedata:<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 configure
method dump
method dump_file
method format
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 Prompt
Pydantic Fields:
name:str | Nonedescription:str | Noneref:trace.refs.ObjectRef | None
method format
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
method add_filter
method add_sort
method column_index
method filter_op
method get_calls
method get_known_columns
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
method remove_filter
method remove_filters
method rename
method rename_column
method save
method set_columns
method show_column
method sort_by
method to_grid
method to_rich_table_str
method ui_url
method unpin_column
class Scorer
Pydantic Fields:
name:str | Nonedescription:str | Noneref:trace.refs.ObjectRef | Nonecolumn_map:dict[str, str] | None
classmethod from_obj
method model_post_init
method score
method summarize
class StringPrompt
method __init__
name:str | Nonedescription:str | Noneref:trace.refs.ObjectRef | Nonecontent:<class 'str'>
method format
classmethod from_obj
class Table
method __init__
property rows
method append
method pop
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__
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
function as_op
fn: A weave.op decorated function. Returns: The Op of the function.
function attributes
function finish
function get
uri: A fully-qualified weave ref URI. Returns: The object.
function get_client
function get_current_call
The returned Call’sattributesdictionary becomes immutable once the call starts. Use :func:weave.attributesto set call metadata before invoking an Op. Thesummaryfield may be updated while the Op executes and will be merged with computed summary information when the call finishes.
function init
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 Models documentation.settings: Configuration for the Weave client generally.autopatch_settings: (Deprecated) Configuration for autopatch integrations. Use explicit patching instead.global_postprocess_inputs: A function that will be applied to all inputs of all ops.global_postprocess_output: A function that will be applied to all outputs of all ops.global_attributes: A dictionary of attributes that will be applied to all traces. Returns: A Weave client.
function log_call
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.
Call: The created and finished Call object with full trace information.
function publish
obj: The object to save and version.name: The name to save the object under. Returns: A Weave Ref to the saved object.
function ref
location: A Weave Ref URI, or ifweave.init()has been called,name:versionorname. If no version is provided,latestis used. Returns: A Weave Ref to the object.
function require_current_call
get_call method on the WeaveClient returned from weave.init to retrieve the Call object.
call method. For example:
NoCurrentCallError: If tracking has not been initialized or this method is invoked outside an Op.
function set_view
_weave.views.<name>.
Args:
name: The view name (key undersummary._weave.views).content: Aweave.Contentinstance or raw string. Strings are wrapped viaContent.from_textusing the supplied extension or mimetype.extension: Optional file extension to use whencontentis a string.mimetype: Optional MIME type to use whencontentis a string.metadata: Optional metadata to attach when creatingContentfrom text.encoding: Text encoding to apply when creatingContentfrom text. Returns: None
import weave
weave.init(“proj”) @weave.op … def foo(): … weave.set_view(“readme”, ”# Hello”, extension=“md”) … return 1 foo()
function thread
-
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.