API概要

クラス

関数

  • api.init: wandbプロジェクトへのログ記録を行うweaveトラッキングを初期化します。
  • api.publish: Pythonオブジェクトを保存してバージョン管理します。
  • api.ref: Weaveオブジェクトへの参照(Ref)を構築します。
  • api.get: URIからオブジェクトを取得するための便利な関数。
  • call_context.require_current_call: 現在実行中のOp内で、そのOpのCallオブジェクトを取得します。
  • call_context.get_current_call: 現在実行中のOp内で、そのOpのCallオブジェクトを取得します。
  • api.finish: weaveへのログ記録を停止します。
  • op.op: 関数またはメソッドをweave op化するデコレータ。同期と非同期の両方で動作します。
  • api.attributes: 呼び出しに属性を設定するためのコンテキストマネージャ。

function init

init( project_name: 'str', settings: 'UserSettings | dict[str, Any] | None' = None, autopatch_settings: 'AutopatchSettings | None' = None, global_postprocess_inputs: 'PostprocessInputsFunc | None' = None, global_postprocess_output: 'PostprocessOutputFunc | None' = None, global_attributes: 'dict[str, Any] | None' = None) → WeaveClient
wandbプロジェクトへのログ記録を行うweaveトラッキングを初期化します。 ログ記録はグローバルに初期化されるため、initの戻り値への参照を保持する必要はありません。 init後、weave.op()でデコレートされた関数の呼び出しは指定されたプロジェクトにログ記録されます。 Args:
  • project_name**: ログを記録するWeights & Biasesプロジェクトの名前。
  • settings: Weaveクライアント全般の設定。
  • autopatch_settings: openaiなどの自動パッチ統合の設定
  • global_postprocess_inputs: すべてのopのすべての入力に適用される関数。
  • global_postprocess_output: すべてのopのすべての出力に適用される関数。
  • global_attributes: すべてのトレースに適用される属性の辞書。
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 Returns:Weaveクライアント。

function publish

publish(obj: 'Any', name: 'str | None' = None) → ObjectRef
Pythonオブジェクトを保存してバージョン管理します。 nameという名前のオブジェクトが既に存在し、objのコンテンツハッシュがそのオブジェクトの最新バージョンと一致しない場合、新しいバージョンが作成されます。 TODO: Need to document how name works with this change. Args:
  • obj**: 保存してバージョン管理するオブジェクト。
  • name: オブジェクトを保存する名前。
Returns:保存されたオブジェクトへのweave Ref。

function ref

ref(location: 'str') → ObjectRef
Weaveオブジェクトへの参照(Ref)を構築します。 TODO: what happens if obj does not exist Args:
  • location**: 完全修飾されたweave参照URI、またはweave.init()が呼び出されている場合は「name:version」または単に「name」(この場合、バージョンには「latest」が使用されます)。
Returns:オブジェクトへのweave Ref。

function get

get(uri: 'str | ObjectRef') → Any
URIからオブジェクトを取得するための便利な関数。 Weaveによってログ記録されたオブジェクトの多くは、自動的にWeaveサーバーに登録されます。この関数を使用すると、URIでそれらのオブジェクトを取得できます。 Args:
  • uri**: 完全修飾されたweave参照URI。
Returns:オブジェクト。 Example:
weave.init("weave_get_example")dataset = weave.Dataset(rows=[{"a": 1, "b": 2}])ref = weave.publish(dataset)dataset2 = weave.get(ref) # same as dataset!

function require_current_call

require_current_call() → Call
現在実行中のOp内で、そのOpのCallオブジェクトを取得します。 これにより、実行中のCallのIDやフィードバックなどの属性にアクセスできます。
@weave.opdef hello(name: str) -> None: print(f"Hello {name}!") current_call = weave.require_current_call() print(current_call.id)
Opが戻った後にCallにアクセスすることも可能です。 CallのID(おそらくUIから)がある場合は、get_callメソッドをWeaveClientから返されたweave.initで使用してCallオブジェクトを取得できます。
client = weave.init("
")mycall = client.get_call("")
あるいは、Opを定義した後、そのcallメソッドを使用できます。例えば:
@weave.opdef add(a: int, b: int) -> int: return a + bresult, call = add.call(1, 2)print(call.id)
Returns:現在実行中のOpのCallオブジェクト Raises:
  • NoCurrentCallError**: トラッキングが初期化されていない場合、またはこのメソッドがOp外で呼び出された場合。

function get_current_call

get_current_call() → Call | None
現在実行中のOp内で、そのOpのCallオブジェクトを取得します。 Returns:現在実行中のOpのCallオブジェクト、またはトラッキングが初期化されていない場合やこのメソッドがOp外で呼び出された場合はNone。

function finish

finish() → None
weaveへのログ記録を停止します。 finish後、weave.op()でデコレートされた関数の呼び出しはログに記録されなくなります。ログ記録を再開するには、weave.init()を再度実行する必要があります。

function op

op( func: 'Callable[P, R] | None' = None, name: 'str | None' = None, call_display_name: 'str | CallDisplayNameFunc | None' = None, postprocess_inputs: 'PostprocessInputsFunc | None' = None, postprocess_output: 'PostprocessOutputFunc | None' = None, tracing_sample_rate: 'float' = 1.0, enable_code_capture: 'bool' = True, accumulator: 'Callable[[Any | None, Any], Any] | None' = None) → Callable[[Callable[P, R]], Op[P, R]] | Op[P, R]
関数またはメソッドをweave op化するデコレータ。同期と非同期の両方で動作します。イテレータ関数を自動的に検出し、適切な動作を適用します。

function attributes

attributes(attributes: 'dict[str, Any]') → Iterator
呼び出しに属性を設定するためのコンテキストマネージャ。 属性は呼び出しの実行が開始されると不変になります。このコンテキストマネージャを使用して、呼び出しが開始される前にメタデータを提供します。 Example:
with weave.attributes({'env': 'production'}): print(my_function.call("World"))

class Object

Pydanticフィールド:
  • name: typing.Optional[str]
  • description: typing.Optional[str]
  • ref: typing.Optional[trace.refs.ObjectRef]

classmethod from_uri

from_uri(uri: str, objectify: bool = True) → Self

classmethod handle_relocatable_object

handle_relocatable_object( v: Any, handler: ValidatorFunctionWrapHandler, info: ValidationInfo) → Any

class Dataset

簡単な保存と自動バージョン管理機能を持つDatasetオブジェクト Examples:
# Create a datasetdataset = Dataset(name='grammar', rows=[ {'id': '0', 'sentence': "He no likes ice cream.", 'correction': "He doesn't like ice cream."}, {'id': '1', 'sentence': "She goed to the store.", 'correction': "She went to the store."}, {'id': '2', 'sentence': "They plays video games all day.", 'correction': "They play video games all day."}])# Publish the datasetweave.publish(dataset)# Retrieve the datasetdataset_ref = weave.ref('grammar').get()# Access a specific exampleexample_label = dataset_ref.rows[2]['sentence']
Pydanticフィールド:
  • 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

add_rows(rows: Iterable[dict]) → Dataset
既存のデータセットに行を追加して新しいデータセットバージョンを作成します。 これは、データセット全体をメモリにロードすることなく、大規模なデータセットに例を追加するのに役立ちます。 Args:
  • rows**: データセットに追加する行。
Returns:更新されたデータセット。

classmethod convert_to_table

convert_to_table(rows: Any) → Union[Table, WeaveTable]

classmethod from_calls

from_calls(calls: Iterable[Call]) → Self

classmethod from_obj

from_obj(obj: WeaveObject) → Self

classmethod from_pandas

from_pandas(df: 'DataFrame') → Self

method select

select(indices: Iterable[int]) → Self
提供されたインデックスに基づいてデータセットから行を選択します。 Args:
  • indices**: 選択する行を指定する整数インデックスの反復可能オブジェクト。
Returns:選択された行のみを含む新しいDatasetオブジェクト。

method to_pandas

to_pandas() → DataFrame

class Model

入力に対して動作するコードとデータの組み合わせをキャプチャすることを目的としています。例えば、予測やテキスト生成を行うためにプロンプトを使用してLLMを呼び出すことがあります。 モデルの属性や定義するコードを変更すると、これらの変更がログに記録され、バージョンが更新されます。これにより、異なるバージョンのモデル間で予測を比較することができます。これを使用してプロンプトを反復的に改善したり、最新のLLMを試して異なる設定間で予測を比較したりすることができます Examples:
class YourModel(Model): attribute1: str attribute2: int @weave.op() def predict(self, input_data: str) -> dict: # Model logic goes here prediction = self.attribute1 + ' ' + input_data return {'pred': prediction}
Pydantic Fields:
  • name: typing.Optional[str]
  • description: typing.Optional[str]
  • ref: typing.Optional[trace.refs.ObjectRef]

method get_infer_method

get_infer_method() → Callable

class Prompt

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

method format

format(**kwargs: Any) → Any

class StringPrompt

method __init__

__init__(content: str)
Pydantic Fields:
  • name: typing.Optional[str]
  • description: typing.Optional[str]
  • ref: typing.Optional[trace.refs.ObjectRef]
  • content: “

method format

format(**kwargs: Any) → str

classmethod from_obj

from_obj(obj: WeaveObject) → Self

class MessagesPrompt

method __init__

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

method format

format(**kwargs: Any) → list

method format_message

format_message(message: dict, **kwargs: Any) → dict

classmethod from_obj

from_obj(obj: WeaveObject) → Self

class Evaluation

スコアラーとデータセットのセットを含む評価をセットアップします。 evaluation.evaluate(model)を呼び出すと、データセットの列の名前をmodel.predictの引数名に一致させてデータセットから行をモデルに渡します。 その後、すべてのスコアラーを呼び出し、結果をweaveに保存します。 データセットからの行を前処理したい場合は、preprocess_model_inputに関数を渡すことができます。 Examples:
# Collect your examplesexamples = [ {"question": "What is the capital of France?", "expected": "Paris"}, {"question": "Who wrote 'To Kill a Mockingbird'?", "expected": "Harper Lee"}, {"question": "What is the square root of 64?", "expected": "8"},]# Define any custom scoring function@weave.op()def match_score1(expected: str, model_output: dict) -> dict: # Here is where you'd define the logic to score the model output return {'match': expected == model_output['generated_text']}@weave.op()def function_to_evaluate(question: str): # here's where you would add your LLM call and return the output return {'generated_text': 'Paris'}# Score your examples using scoring functionsevaluation = Evaluation( dataset=examples, scorers=[match_score1])# Start tracking the evaluationweave.init('intro-example')# Run the evaluationasyncio.run(evaluation.evaluate(function_to_evaluate))
Pydantic Fields:
  • name: typing.Optional[str]
  • description: typing.Optional[str]
  • ref: typing.Optional[trace.refs.ObjectRef]
  • dataset: “
  • scorers: typing.Optional[list[typing.Annotated[typing.Union[trace.op.Op, flow.scorer.Scorer], BeforeValidator(func=)]]]
  • preprocess_model_input: typing.Optional[typing.Callable[[dict], dict]]
  • trials: “
  • evaluation_name: typing.Union[str, typing.Callable[[trace.weave_client.Call], str], NoneType]

method evaluate

evaluate(model: Union[Op, Model]) → dict

classmethod from_obj

from_obj(obj: WeaveObject) → Self

method get_eval_results

get_eval_results(model: Union[Op, Model]) → EvaluationResults

method predict_and_score

predict_and_score(model: Union[Op, Model], example: dict) → dict

method summarize

summarize(eval_table: EvaluationResults) → dict

class EvaluationLogger

このクラスは評価をログに記録するための命令型インターフェースを提供します。 評価は、最初の予測がlog_predictionメソッドを使用してログに記録されると自動的に開始され、log_summaryメソッドが呼び出されると終了します。 予測をログに記録するたびに、ScoreLoggerオブジェクトが返されます。このオブジェクトを使用して、その特定の予測のスコアとメタデータをログに記録できます。詳細については、ScoreLoggerクラスを参照してください。 Example:
 ev = EvaluationLogger() pred = ev.log_prediction(inputs, output) pred.log_score(scorer_name, score) ev.log_summary(summary)
Pydantic Fields:
  • name: str | None
  • model: flow.model.Model | dict | str
  • dataset: flow.dataset.Dataset | list[dict] | str

property ui_url

method finish

finish() → None
サマリーをログに記録せずに評価リソースを明示的にクリーンアップします。 すべての予測呼び出しとメイン評価呼び出しが確実に終了します。これはロガーがコンテキストマネージャーとして使用される場合に自動的に呼び出されます。

method log_prediction

log_prediction(inputs: 'dict', output: 'Any') → ScoreLogger
予測を評価にログに記録し、参照を返します。 この参照を使用して、特定の予測インスタンスに添付されるスコアをログに記録できます。

method log_summary

log_summary(summary: 'dict | None' = None, auto_summarize: 'bool' = True) → None
サマリー辞書を評価にログに記録します。 これはサマリーを計算し、summarize操作を呼び出し、その後評価を終了します。つまり、これ以上の予測やスコアをログに記録することはできません。

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

method model_post_init

model_post_init(_Scorer__context: Any) → None

method score

score(output: Any, **kwargs: Any) → Any

method summarize

summarize(score_rows: list) → Optional[dict]

class AnnotationSpec

Pydantic Fields:
  • name: typing.Optional[str]
  • description: typing.Optional[str]
  • field_schema: dict[str, typing.Any]
  • unique_among_creators: “
  • op_scope: typing.Optional[list[str]]

classmethod preprocess_field_schema

preprocess_field_schema(data: dict[str, Any]) → dict[str, Any]

classmethod validate_field_schema

validate_field_schema(schema: dict[str, Any]) → dict[str, Any]

method value_is_valid

value_is_valid(payload: Any) → bool
ペイロードをこのアノテーション仕様のスキーマに対して検証します。 Args:
  • payload**: スキーマに対して検証するデータ
Returns:
  • bool: 検証が成功した場合はTrue、そうでない場合はFalse

class File

パス、MIMEタイプ、サイズ情報を持つファイルを表すクラス。

method __init__

__init__(path: 'str | Path', mimetype: 'str | None' = None)
Fileオブジェクトを初期化します。 Args:
  • path**: ファイルへのパス(文字列またはpathlib.Path)
  • mimetype: ファイルのオプションのMIMEタイプ - 提供されない場合は拡張子から推測されます

property filename

ファイルのファイル名を取得します。 Returns:
  • str: ディレクトリパスを除いたファイルの名前。

method open

open() → bool
オペレーティングシステムのデフォルトアプリケーションを使用してファイルを開きます。 このメソッドは、プラットフォーム固有のメカニズムを使用して、ファイルの種類に関連付けられたデフォルトアプリケーションでファイルを開きます。 Returns:
  • bool**: ファイルが正常に開かれた場合はTrue、そうでない場合はFalse。

method save

save(dest: 'str | Path') → None
ファイルを指定された宛先パスにコピーします。 Args:
  • dest**: ファイルがコピーされる宛先パス(文字列またはpathlib.Path)。宛先パスはファイルまたはディレクトリにすることができます。

class Markdown

Markdownレンダリング可能。 Args:
  • markup (str): マークダウンを含む文字列。
  • code_theme (str, optional): コードブロック用のPygmentsテーマ。デフォルトは「monokai」。
  • justify (JustifyMethod, optional): 段落の揃え値。デフォルトはNone。
  • style (Union[str, Style], optional): マークダウンに適用するオプションのスタイル。
  • hyperlinks (bool, optional): ハイパーリンクを有効にします。デフォルトはTrue
  • inline_code_lexer: (str, optional): インラインコードハイライトが有効な場合に使用するレクサー。デフォルトはNone。
  • inline_code_theme: (Optional[str], optional): インラインコードのハイライト表示用のPygmentsテーマ、またはハイライト表示なしの場合はNone。デフォルトはNone。

method __init__

__init__( markup: 'str', code_theme: 'str' = 'monokai', justify: 'Optional[JustifyMethod]' = None, style: 'Union[str, Style]' = 'none', hyperlinks: 'bool' = True, inline_code_lexer: 'Optional[str]' = None, inline_code_theme: 'Optional[str]' = None) → None

class Monitor

着信コールを自動的にスコアリングするモニターをセットアップします。 Examples:
import weavefrom weave.scorers import ValidJSONScorerjson_scorer = ValidJSONScorer()my_monitor = weave.Monitor( name="my-monitor", description="This is a test monitor", sampling_rate=0.5, op_names=["my_op"], query={ "$expr": { "$gt": [ { "$getField": "started_at" }, { "$literal": 1742540400 } ] } } }, scorers=[json_scorer],)my_monitor.activate()
Pydantic Fields:
  • name: typing.Optional[str]
  • description: typing.Optional[str]
  • ref: typing.Optional[trace.refs.ObjectRef]
  • sampling_rate: “
  • scorers: list[flow.scorer.Scorer]
  • op_names: list[str]
  • query: typing.Optional[trace_server.interface.query.Query]
  • active: “

method activate

activate() → ObjectRef
モニターをアクティブにします。 Returns: モニターへの参照。

method deactivate

deactivate() → ObjectRef
モニターを非アクティブにします。 Returns: モニターへの参照。

classmethod from_obj

from_obj(obj: WeaveObject) → Self

class SavedView

SavedViewオブジェクトを操作するためのフルエントスタイルのクラス。

method __init__

__init__(view_type: 'str' = 'traces', label: 'str' = 'SavedView') → None

property entity

property label

property project

property view_type

method add_column

add_column(path: 'str | ObjectPath', label: 'str | None' = None) → SavedView

method add_columns

add_columns(*columns: 'str') → SavedView
グリッドに複数の列を追加するための便利なメソッド。

method add_filter

add_filter( field: 'str', operator: 'str', value: 'Any | None' = None) → SavedView

method add_sort

add_sort(field: 'str', direction: 'SortDirection') → SavedView

method column_index

column_index(path: 'int | str | ObjectPath') → int

method filter_op

filter_op(op_name: 'str | None') → SavedView

method get_calls

get_calls( limit: 'int | None' = None, offset: 'int | None' = None, include_costs: 'bool' = False, include_feedback: 'bool' = False, all_columns: 'bool' = False) → CallsIter
この保存されたビューのフィルターと設定に一致するコールを取得します。

method get_known_columns

get_known_columns(num_calls_to_query: 'int | None' = None) → list[str]
存在することが分かっている列のセットを取得します。

method get_table_columns

get_table_columns() → list[TableColumn]

method hide_column

hide_column(col_name: 'str') → SavedView

method insert_column

insert_column( idx: 'int', path: 'str | ObjectPath', label: 'str | None' = None) → SavedView

classmethod load

load(ref: 'str') → SavedView

method page_size

page_size(page_size: 'int') → SavedView

method pin_column_left

pin_column_left(col_name: 'str') → SavedView

method pin_column_right

pin_column_right(col_name: 'str') → SavedView

method remove_column

remove_column(path: 'int | str | ObjectPath') → SavedView

method remove_columns

remove_columns(*columns: 'str') → SavedView
保存されたビューから列を削除します。

method remove_filter

remove_filter(index_or_field: 'int | str') → SavedView

method remove_filters

remove_filters() → SavedView
保存されたビューからすべてのフィルターを削除します。

method rename

rename(label: 'str') → SavedView

method rename_column

rename_column(path: 'int | str | ObjectPath', label: 'str') → SavedView

method save

save() → SavedView
保存されたビューをサーバーに公開します。

method set_columns

set_columns(*columns: 'str') → SavedView
グリッドに表示する列を設定します。

method show_column

show_column(col_name: 'str') → SavedView

method sort_by

sort_by(field: 'str', direction: 'SortDirection') → SavedView

method to_grid

to_grid(limit: 'int | None' = None) → Grid

method to_rich_table_str

to_rich_table_str() → str

method ui_url

ui_url() → str | None
UIでこの保存されたビューを表示するURL。 これはトレースなどを含む「結果」ページであり、ビューオブジェクト自体のURLではありません。

method unpin_column

unpin_column(col_name: 'str') → SavedView

class Audio

サポートされている形式(wavまたはmp3)のオーディオデータを表すクラス。 このクラスはオーディオデータの保存を処理し、さまざまなソースからの読み込みやファイルへのエクスポートのためのメソッドを提供します。 Attributes:
  • format**: オーディオ形式(現在は「wav」または「mp3」をサポート)
  • data: 生のオーディオデータ(バイト形式)
Args:
  • data: オーディオデータ(バイトまたはbase64エンコードされた文字列)
  • format: オーディオ形式(「wav」または「mp3」)
  • validate_base64: 入力データのbase64デコードを試みるかどうか
Raises:
  • ValueError: オーディオデータが空または形式がサポートされていない場合

method __init__

__init__( data: 'bytes', format: 'SUPPORTED_FORMATS_TYPE', validate_base64: 'bool' = True) → None

method export

export(path: 'str | bytes | Path | PathLike') → None
オーディオデータをファイルにエクスポートします。 Args:
  • path**: オーディオファイルを書き込むパス

classmethod from_data

from_data(data: 'str | bytes', format: 'str') → Audio
生データと指定された形式からAudioオブジェクトを作成します。 Args:
  • data**: バイトまたはbase64エンコードされた文字列としてのオーディオデータ
  • format: オーディオ形式(「wav」または「mp3」)
Returns:
  • Audio: 新しいAudioインスタンス
Raises:
  • ValueError: 形式がサポートされていない場合

classmethod from_path

from_path(path: 'str | bytes | Path | PathLike') → Audio
ファイルパスからAudioオブジェクトを作成します。 Args:
  • path**: オーディオファイルへのパス(.wavまたは.mp3拡張子が必要)
Returns:
  • Audio: ファイルから読み込まれた新しいAudioインスタンス
Raises:
  • ValueError: ファイルが存在しないか、サポートされていない拡張子を持つ場合
このページを編集最終更新日: Jul 14, 2025