Skip to main content

API Overview


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: Global postprocessing settings are applied to all ops after each op’s own postprocessing. The order is always: 1. Op-specific postprocessing 2. Global 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 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 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. Args:
  • 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

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 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 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:
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 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 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 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.

function attributes

Context manager for setting attributes on a call. Example:

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.

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.
Examples:
Pydantic Fields:
  • name: typing.Optional[str]
  • description: typing.Optional[str]
  • ref: typing.Optional[trace.refs.ObjectRef]

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: ```python

When an ObjectRef is passed

obj = MyObject(some_object_ref)

When a WeaveObject is passed

obj = MyObject(some_weave_object)
Pydantic Fields:
  • name: typing.Optional[str]
  • description: typing.Optional[str]
  • ref: typing.Optional[trace.refs.ObjectRef]
  • rows: typing.Union[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 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: typing.Optional[str]
  • description: typing.Optional[str]
  • ref: typing.Optional[trace.refs.ObjectRef]

method get_infer_method


class Prompt

Pydantic Fields:
  • name: typing.Optional[str]
  • description: typing.Optional[str]
  • ref: typing.Optional[trace.refs.ObjectRef]

method format


class StringPrompt

method __init__

Pydantic Fields:
  • name: typing.Optional[str]
  • description: typing.Optional[str]
  • ref: typing.Optional[trace.refs.ObjectRef]
  • content: <class 'str'>

method format


classmethod from_obj


class MessagesPrompt

method __init__

Pydantic Fields:
  • name: typing.Optional[str]
  • description: typing.Optional[str]
  • ref: typing.Optional[trace.refs.ObjectRef]
  • messages: list[dict]

method format


method format_message


classmethod from_obj


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: typing.Optional[str]
  • description: typing.Optional[str]
  • ref: typing.Optional[trace.refs.ObjectRef]
  • dataset: <class 'dataset.dataset.Dataset'>
  • scorers: typing.Optional[list[typing.Annotated[typing.Union[trace.op_protocol.Op, flow.scorer.Scorer], BeforeValidator(func=<function cast_to_scorer at 0x7f126eaa0040>, json_schema_input_type=PydanticUndefined)]]]
  • preprocess_model_input: typing.Optional[typing.Callable[[dict], dict]]
  • trials: <class 'int'>
  • metadata: typing.Optional[dict[str, typing.Any]]
  • evaluation_name: typing.Union[str, typing.Callable[[trace.call.Call], str], NoneType]

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:
Pydantic Fields:
  • name: str | None
  • model: flow.model.Model | dict | str
  • dataset: dataset.dataset.Dataset | list[dict] | str
  • eval_attributes: dict[str, typing.Any]
  • scorers: list[str] | None

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_prediction

Log a prediction to the Evaluation. If output is provided, returns a ScoreLogger for direct use. If output is not provided, returns a PredictionContext for use as a context manager. Args:
  • inputs: The input data for the prediction
  • output: The output value. If not provided, use as context manager to set later. Returns: ScoreLogger if output provided, PredictionContext if not.
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)

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 model_post_init

Initialize the pseudo evaluation with the dataset from the model.

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: import weave
ev = weave.EvaluationLogger() ev.set_view(“report”, ”# Report”, extension=“md”)

class Scorer

Pydantic Fields:
  • name: typing.Optional[str]
  • description: typing.Optional[str]
  • ref: typing.Optional[trace.refs.ObjectRef]
  • column_map: typing.Optional[dict[str, str]]

classmethod from_obj


method model_post_init


method score


method summarize


class AnnotationSpec

Pydantic Fields:
  • name: typing.Optional[str]
  • description: typing.Optional[str]
  • field_schema: dict[str, typing.Any]
  • unique_among_creators: <class 'bool'>
  • op_scope: typing.Optional[list[str]]

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 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 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.
  • 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:
  • 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 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__


class Monitor

Sets up a monitor to score incoming calls automatically.
  • 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. Examples:
Pydantic Fields:
  • name: typing.Optional[str]
  • description: typing.Optional[str]
  • ref: typing.Optional[trace.refs.ObjectRef]
  • sampling_rate: <class 'float'>
  • scorers: list[flow.scorer.Scorer]
  • op_names: list[str]
  • query: typing.Optional[trace_server.interface.query.Query]
  • active: <class 'bool'>

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


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 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