メインコンテンツへスキップ

API Overview


Source

class Agent

Pydantic フィールド:
  • 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]
Source

method step

step(state: AgentState) → AgentState
エージェントのステップを実行します。 引数:
  • state: 環境の現在の状態。
  • action: 実行するアクション。 戻り値: 環境の新しい状態。

Source

class AgentState

Pydantic フィールド:
  • name: str | None
  • description: str | None
  • ref: trace.refs.ObjectRef | None
  • history: list[typing.Any]

Source

class AnnotationSpec

Pydantic フィールド:
  • name: str | None
  • description: str | None
  • field_schema: dict[str, typing.Any]
  • unique_among_creators: <class 'bool'>
  • op_scope: list[str] | None
Source

classmethod preprocess_field_schema

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

Source

classmethod validate_field_schema

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

Source

method value_is_valid

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

Source

class Audio

サポートされている形式(wav または mp3)のオーディオデータを表すクラス。 このクラスはオーディオデータの保存を処理し、異なるソースからの読み込みやファイルへのエクスポート用メソッドを提供します。 属性:
  • format: オーディオ形式(現在は ‘wav’ または ‘mp3’ をサポート)
  • data: バイト列としての生のオーディオデータ
引数:
  • data: オーディオデータ(バイト列または base64 エンコードされた文字列)
  • format: オーディオ形式(‘wav’ または ‘mp3’)
  • validate_base64: 入力データに対して base64 デコードを試みるかどうか 例外:
  • ValueError: オーディオデータが空、または形式がサポートされていない場合
Source

method __init__

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

Source

method export

export(path: 'str | bytes | Path | PathLike') → None
オーディオデータをファイルにエクスポートします。 引数:
Source

classmethod from_data

from_data(data: 'str | bytes', format: 'str') → Self
生のデータと指定された形式から Audio オブジェクトを作成します。
  • path: オーディオファイルが書き込まれるパス 引数:
  • data: バイト列または base64 エンコードされた文字列としてのオーディオデータ
  • format: オーディオ形式(‘wav’ または ‘mp3’) 戻り値:
  • Audio: 新しい Audio インスタンス
例外:
  • ValueError: 形式がサポートされていない場合

Source

classmethod from_path

from_path(path: 'str | bytes | Path | PathLike') → Self
ファイルパスから Audio オブジェクトを作成します。 引数:
  • path: オーディオファイルへのパス(拡張子が .wav または .mp3 である必要があります) 戻り値:
  • Audio: ファイルから読み込まれた新しい Audio インスタンス
例外:
  • ValueError: ファイルが存在しないか、サポートされていない拡張子の場合

Source

class Content

さまざまなソースからのコンテンツを表現し、関連するメタデータと共に統一されたバイト指向の表現に解決するクラス。 このクラスは、以下のクラスメソッドのいずれかを使用してインスタンス化する必要があります:
  • from_path()
  • from_bytes()
  • from_text()
  • from_url()
  • from_base64()
  • from_data_url()
Source

method __init__

__init__(*args: 'Any', **kwargs: 'Any') → None
直接の初期化は無効化されています。インスタンスを作成するには、Content.from_path() のようなクラスメソッドを使用してください。 Pydantic フィールド:
  • 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


Source

method as_string

as_string() → str
データを文字列として表示します。バイト列は encoding 属性を使用してデコードされます。base64 の場合、データは一度 base64 バイトに再エンコードされた後、ASCII 文字列にデコードされます。 戻り値: str.
Source

classmethod from_base64

from_base64(
    b64_data: 'str | bytes',
    extension: 'str | None' = None,
    mimetype: 'str | None' = None,
    metadata: 'dict[str, Any] | None' = None
) → Self
base64 エンコードされた文字列またはバイト列から Content を初期化します。
Source

classmethod from_bytes

from_bytes(
    data: 'bytes',
    extension: 'str | None' = None,
    mimetype: 'str | None' = None,
    metadata: 'dict[str, Any] | None' = None,
    encoding: 'str' = 'utf-8'
) → Self
生のバイト列から Content を初期化します。
Source

classmethod from_data_url

from_data_url(url: 'str', metadata: 'dict[str, Any] | None' = None) → Self
データ URL から Content を初期化します。
Source

classmethod from_path

from_path(
    path: 'str | Path',
    encoding: 'str' = 'utf-8',
    mimetype: 'str | None' = None,
    metadata: 'dict[str, Any] | None' = None
) → Self
ローカルのファイルパスから Content を初期化します。
Source

classmethod from_text

from_text(
    text: 'str',
    extension: 'str | None' = None,
    mimetype: 'str | None' = None,
    metadata: 'dict[str, Any] | None' = None,
    encoding: 'str' = 'utf-8'
) → Self
テキスト文字列から Content を初期化します。
Source

classmethod from_url

from_url(
    url: 'str',
    headers: 'dict[str, Any] | None' = None,
    timeout: 'int | None' = 30,
    metadata: 'dict[str, Any] | None' = None
) → Self
HTTP(S) URL からバイト列を取得して Content を初期化します。 コンテンツをダウンロードし、ヘッダー、URL パス、およびデータから mimetype / 拡張子を推論し、得られたバイト列から Content オブジェクトを構築します。
Source

classmethod model_validate

model_validate(
    obj: 'Any',
    strict: 'bool | None' = None,
    from_attributes: 'bool | None' = None,
    context: 'dict[str, Any] | None' = None
) → Self
辞書からの Content 再構築を処理するために model_validate をオーバーライドします。
Source

classmethod model_validate_json

model_validate_json(
    json_data: 'str | bytes | bytearray',
    strict: 'bool | None' = None,
    context: 'dict[str, Any] | None' = None
) → Self
JSON からの Content 再構築を処理するために model_validate_json をオーバーライドします。
Source

method open

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

Source

method save

save(dest: 'str | Path') → None
指定された保存先パスにファイルをコピーします。最後に保存されたコピーを反映するように、コンテンツのファイル名とパスを更新します。 引数:
Source

method serialize_data

serialize_data(data: 'bytes') → str
JSON モードでモデルをダンプする際に使用されます。
Source

method to_data_url

to_data_url(use_base64: 'bool' = True) → str
コンテンツからデータ URL を構築します。
  • dest: ファイルがコピーされる保存先パス(文字列または pathlib.Path)。保存先パスはファイルまたはディレクトリーのいずれかです。dest にファイル拡張子(例:.txt)がない場合、保存先はディレクトリーとみなされます。 引数:
  • use_base64: True の場合、データは base64 エンコードされます。それ以外の場合は、パーセントエンコーディングされます。デフォルトは True です。 戻り値: データ URL 文字列。

Source

class Dataset

簡単な保存と自動バージョン管理を備えた Dataset オブジェクト。 例:
# データセットを作成する
dataset = 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."}
])

# データセットをパブリッシュ(公開)する
weave.publish(dataset)

# データセットを取得する
dataset_ref = weave.ref('grammar').get()

# 特定の例にアクセスする
example_label = dataset_ref.rows[2]['sentence']
Pydantic フィールド:
  • name: str | None
  • description: str | None
  • ref: trace.refs.ObjectRef | None
  • rows: trace.table.Table | trace.vals.WeaveTable
Source

method add_rows

add_rows(rows: Iterable[dict]) → Dataset
既存のデータセットに行を追加して、新しいデータセットバージョンを作成します。 これは、データセット全体をメモリーに読み込むことなく、大規模なデータセットに例を追加する場合に便利です。 引数:
  • rows: データセットに追加する行。 戻り値: 更新されたデータセット。

Source

classmethod convert_to_table

convert_to_table(rows: Any) → Table | WeaveTable

Source

classmethod from_calls

from_calls(calls: Iterable[Call]) → Self

Source

classmethod from_hf

from_hf(
    hf_dataset: Union[ForwardRef('HFDataset'), ForwardRef('HFDatasetDict')]
) → Self

Source

classmethod from_obj

from_obj(obj: WeaveObject) → Self

Source

classmethod from_pandas

from_pandas(df: 'DataFrame') → Self

Source

method select

select(indices: Iterable[int]) → Self
指定されたインデックスに基づいてデータセットから行を選択します。 引数:
  • indices: 選択する行を指定する整数インデックスのイテラブル。 戻り値: 選択された行のみを含む新しい Dataset オブジェクト。

Source

method to_hf

to_hf() → HFDataset

Source

method to_pandas

to_pandas() → DataFrame

Source

class EasyPrompt

Source

method __init__

__init__(
    content: str | dict | list | None = None,
    role: str | None = None,
    dedent: bool = False,
    **kwargs: Any
) → None
Pydantic フィールド:
  • name: str | None
  • description: str | None
  • ref: trace.refs.ObjectRef | None
  • data: <class 'list'>
  • config: <class 'dict'>
  • requirements: <class 'dict'>

property as_str

すべてのメッセージを単一の文字列に結合します。

property is_bound


property messages

property placeholders


property system_message

すべてのメッセージをシステムプロンプトメッセージに結合します。

property system_prompt

すべてのメッセージをシステムプロンプトオブジェクトに結合します。

property unbound_placeholders


Source

method append

append(item: Any, role: str | None = None, dedent: bool = False) → None

Source

method as_dict

as_dict() → dict[str, Any]

Source

method as_pydantic_dict

as_pydantic_dict() → dict[str, Any]

Source

method bind

bind(*args: Any, **kwargs: Any) → Prompt

Source

method bind_rows

bind_rows(dataset: list[dict] | Any) → list['Prompt']

Source

method config_table

config_table(title: str | None = None) → Table

Source

method configure

configure(config: dict | None = None, **kwargs: Any) → Prompt

Source

method dump

dump(fp: <class 'IO'>) → None

Source

method dump_file

dump_file(filepath: str | Path) → None

Source

method format

format(**kwargs: Any) → Any

Source

classmethod from_obj

from_obj(obj: WeaveObject) → Self

Source

classmethod load

load(fp: <class 'IO'>) → Self

Source

classmethod load_file

load_file(filepath: str | Path) → Self

Source

method messages_table

messages_table(title: str | None = None) → Table

Source

method print

print() → str

Source

method publish

publish(name: str | None = None) → ObjectRef

Source

method require

require(param_name: str, **kwargs: Any) → Prompt

Source

method run

run() → Any

Source

method validate_requirement

validate_requirement(key: str, value: Any) → list

Source

method validate_requirements

validate_requirements(values: dict[str, Any]) → list

Source

method values_table

values_table(title: str | None = None) → Table

Source

class Evaluation

一連のスコアラーとデータセットを含む評価をセットアップします。 evaluation.evaluate(model) を呼び出すと、データセットの列名と model.predict の引数名を一致させて、データセットの行をモデルに渡します。 その後、すべてのスコアラーを呼び出し、結果を weave に保存します。 データセットの行を前処理したい場合は、preprocess_model_input に関数を渡すことができます。 例:
# 例を収集する
examples = [
     {"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"},
]

# カスタムスコアリング関数を定義する
@weave.op
def match_score1(expected: str, model_output: dict) -> dict:
     # ここにモデルの出力をスコアリングするロジックを定義します
     return {'match': expected == model_output['generated_text']}

@weave.op
def function_to_evaluate(question: str):
     # ここに LLM の呼び出しを追加し、出力を返します
     return  {'generated_text': 'Paris'}

# スコアリング関数を使用して例を評価する
evaluation = Evaluation(
     dataset=examples, scorers=[match_score1]
)

# 評価のトラッキングを開始する
weave.init('intro-example')
# 評価を実行する
asyncio.run(evaluation.evaluate(function_to_evaluate))
Pydantic フィールド:
  • 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 0x7fd95dcf47c0>, 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
Source

method evaluate

evaluate(model: Op | Model) → dict

Source

classmethod from_obj

from_obj(obj: WeaveObject) → Self

Source

method get_eval_results

get_eval_results(model: Op | Model) → EvaluationResults

Source

method get_evaluate_calls

get_evaluate_calls() → PaginatedIterator[CallSchema, WeaveObject]
この Evaluation オブジェクトを使用したすべての評価コールを取得します。 単一の評価に対して複数の評価コールが存在する可能性があるため(例:同じ評価を複数回実行した場合)、単一のコールではなく CallsIter が返されることに注意してください。 戻り値:
  • CallsIter: 評価の run を表す Call オブジェクトのイテレーター。
例外:
  • ValueError: 評価に ref がない場合(まだ保存/実行されていない場合)。
例:
evaluation = Evaluation(dataset=examples, scorers=[scorer])
await evaluation.evaluate(model)  # まず評価を実行する
calls = evaluation.get_evaluate_calls()
for call in calls:
     print(f"Evaluation run: {call.id} at {call.started_at}")

Source

method get_score_calls

get_score_calls() → dict[str, list[Call]]
評価の各 run ごとにスコアラーコールを取得し、トレース ID でグループ化します。 戻り値:
  • dict[str, list[Call]]: トレース ID をスコアラー Call オブジェクトのリストにマッピングする辞書。各トレース ID は 1 回の評価 run を表し、リストにはその run 中に実行されたすべてのスコアラーコールが含まれます。
例:
evaluation = Evaluation(dataset=examples, scorers=[accuracy_scorer, f1_scorer])
await evaluation.evaluate(model)
score_calls = evaluation.get_score_calls()
for trace_id, calls in score_calls.items():
     print(f"Trace {trace_id}: {len(calls)} scorer calls")
     for call in calls:
         scorer_name = call.summary.get("weave", {}).get("trace_name")
         print(f"  Scorer: {scorer_name}, Output: {call.output}")

Source

method get_scores

get_scores() → dict[str, dict[str, list[Any]]]
評価 run からスコアラーの出力を抽出して整理します。 戻り値:
  • dict[str, dict[str, list[Any]]]: 以下の構造を持つネストされた辞書:
    • 第 1 レベルのキー:トレース ID(評価 run)
    • 第 2 レベルのキー:スコアラー名
    • 値:その run とスコアラーに対するスコアラー出力のリスト
例:
evaluation = Evaluation(dataset=examples, scorers=[accuracy_scorer, f1_scorer])
await evaluation.evaluate(model)
scores = evaluation.get_scores()
# トレースとスコアラー別にスコアにアクセスする
for trace_id, trace_scores in scores.items():
         print(f"Evaluation run {trace_id}:")
         for scorer_name, outputs in trace_scores.items():
             print(f"  {scorer_name}: {outputs}")
期待される出力:
{
     "trace_123": {
     "accuracy_scorer": [{"accuracy": 0.85}],
     "f1_scorer": [{"f1": 0.78}]
     }
}

Source

method model_post_init

model_post_init(_Evaluation__context: Any) → None

Source

method predict_and_score

predict_and_score(model: Op | Model, example: dict) → dict

Source

method summarize

summarize(eval_table: EvaluationResults) → dict

Source

class EvaluationLogger

このクラスは、評価をログに記録するための命令的なインターフェースを提供します。 log_prediction メソッドを使用して最初の予測がログに記録されると、評価が自動的に開始され、log_summary メソッドが呼び出されると終了します。 予測をログに記録するたびに、ScoreLogger オブジェクトが返されます。このオブジェクトを使用して、その特定の予測に対するスコアとメタデータをログに記録できます。詳細については、ScoreLogger クラスを参照してください。 基本的な使用法 - 入力と出力を直接指定して予測をログに記録する:
ev = EvaluationLogger()

# 既知の入力/出力を使用して予測をログに記録する
pred = ev.log_prediction(inputs={'q': 'Hello'}, outputs={'a': 'Hi there!'})
pred.log_score("correctness", 0.9)

# 評価を終了する
ev.log_summary({"avg_score": 0.9})
高度な使用法 - 動的な出力とネストされた操作のためにコンテキストマネージャーを使用する:
ev = EvaluationLogger()

# ネストされた操作をキャプチャする必要がある場合はコンテキストマネージャーを使用する
with ev.log_prediction(inputs={'q': 'Hello'}) as pred:
     # ここでのあらゆる操作(LLM 呼び出しなど)は自動的に
     # predict コールの子になります
     response = your_llm_call(...)
     pred.output = response.content
     pred.log_score("correctness", 0.9)

# 評価を終了する
ev.log_summary({"avg_score": 0.9})
Source

method __init__

__init__(
    name: 'str | None' = None,
    model: 'Model | dict | str | None' = None,
    dataset: 'Dataset | list[dict] | str | None' = None,
    eval_attributes: 'dict[str, Any] | None' = None,
    scorers: 'list[str] | None' = None
) → None

property attributes


property ui_url


Source

method fail

fail(exception: 'BaseException') → None
例外を発生させて評価を失敗させる便利なメソッド。
Source

method finish

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

method log_example

log_example(
    inputs: 'dict[str, Any]',
    output: 'Any',
    scores: 'dict[str, ScoreType]'
) → None
入力、出力、スコアを含む完全な例をログに記録します。 これは、すべてのデータが事前に揃っている場合に、log_prediction と log_score を組み合わせる便利なメソッドです。 引数:
  • inputs: 予測の入力データ。
  • output: 出力値。
  • scores: スコアラー名をスコア値にマッピングする辞書。 例:
ev = EvaluationLogger()
ev.log_example(
    inputs={'q': 'What is 2+2?'},
    output='4',
    scores={'correctness': 1.0, 'fluency': 0.9}
)

Source

method log_prediction

log_prediction(inputs: 'dict[str, Any]', output: 'Any' = None) → ScoreLogger
評価に予測をログとして記録します。 直接使用することも、コンテキストマネージャーとして使用することもできる ScoreLogger を返します。 引数:
  • inputs: 予測のための入力データ。
  • output: 出力値。デフォルトは None です。後で pred.output を使用して設定できます。 戻り値: スコアをログに記録し、オプションで予測を完了させるための ScoreLogger。
例(直接使用):
  • 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) # 終了時に自動的に finish() を呼び出します

Source

method log_summary

log_summary(summary: 'dict | None' = None, auto_summarize: 'bool' = True) → None
評価にサマリー辞書をログとして記録します。 これによりサマリーが計算され、summarize op が呼び出され、評価が完了します。これ以降、予測やスコアをログに記録することはできなくなります。
Source

method set_view

set_view(
    name: 'str',
    content: 'Content | str',
    extension: 'str | None' = None,
    mimetype: 'str | None' = None,
    metadata: 'dict[str, Any] | None' = None,
    encoding: 'str' = 'utf-8'
) → None
評価のメインコールサマリーの weave.views 下にビューをアタッチします。 提供されたコンテンツをプロジェクト内のオブジェクトとして保存し、評価の evaluate コールの summary.weave.views.<name> 下にその参照 URI を書き込みます。文字列入力は、提供された拡張子または mimetype を使用して Content.from_text でテキストコンテンツとしてラップされます。 引数:
  • name: 表示されるビュー名。summary.weave.views 下のキーとして使用されます。
  • content: シリアライズする weave.Content インスタンスまたは文字列。
  • extension: 文字列コンテンツ入力に対するオプションのファイル拡張子。
  • mimetype: 文字列コンテンツ入力に対するオプションの MIME タイプ。
  • metadata: 新しく作成された Content にアタッチされるオプションのメタデータ。
  • encoding: 文字列コンテンツ入力に対するテキストエンコーディング。 戻り値: None
例: import weave
ev = weave.EvaluationLogger() ev.set_view(“report”, ”# Report”, extension=“md”)

Source

class File

パス、mimetype、およびサイズ情報を持つファイルを表すクラス。 Source

method __init__

__init__(path: 'str | Path', mimetype: 'str | None' = None)
File オブジェクトを初期化します。 引数:

property filename

ファイルのファイル名を取得します。
  • path: ファイルへのパス(文字列または pathlib.Path)
  • mimetype: ファイルのオプションの MIME タイプ - 指定されない場合は拡張子から推論されます 戻り値:
  • str: ディレクトリーパスを含まないファイル名。

Source

method open

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

Source

method save

save(dest: 'str | Path') → None
指定された保存先パスにファイルをコピーします。 引数:
Source

class Markdown

Markdown レンダリング可能オブジェクト。
  • dest: ファイルがコピーされる保存先パス(文字列または pathlib.Path)。保存先パスはファイルまたはディレクトリーのいずれかです。 引数:
  • markup (str): Markdown を含む文字列。
  • code_theme (str, optional): コードブロック用の Pygments テーマ。デフォルトは “monokai”。コードテーマについては https://pygments.org/styles/ を参照してください。
  • justify (JustifyMethod, optional): 段落の配置(ジャスティファイ)方法。デフォルトは None。
  • style (Union[str, Style], optional): Markdown に適用するオプションのスタイル。
  • hyperlinks (bool, optional): ハイパーリンクを有効にします。デフォルトは True
Source

method __init__

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

Source

class MessagesPrompt

Source

method __init__

__init__(messages: list[dict])
  • inline_code_lexer: (str, optional): インラインコードのハイライトが有効な場合に使用するレクサー。デフォルトは None です。
  • inline_code_theme: (Optional[str], optional): インラインコードのハイライト用の Pygments テーマ、またはハイライトなしの場合は None。デフォルトは None です。 Pydantic フィールド:
  • name: str | None
  • description: str | None
  • ref: trace.refs.ObjectRef | None
  • messages: list[dict]
Source

method format

format(**kwargs: Any) → list

Source

method format_message

format_message(message: dict, **kwargs: Any) → dict
テンプレート変数を置換して単一のメッセージをフォーマットします。 このメソッドは、実際のフォーマットロジックについて、スタンドアロンの format_message_with_template_vars 関数に委譲します。
Source

classmethod from_obj

from_obj(obj: WeaveObject) → Self

Source

class Model

入力に対して動作するコードとデータの組み合わせをキャプチャすることを目的としています。例えば、プロンプトを使用して LLM を呼び出し、予測を行ったりテキストを生成したりすることが考えられます。 モデルを定義する属性やコードを変更すると、それらの変更がログに記録され、バージョンが更新されます。これにより、モデルの異なるバージョン間で予測結果を比較できるようになります。これを使用して、プロンプトの調整を繰り返したり、最新の LLM を試して異なる設定間で予測結果を比較したりしてください。 例:
class YourModel(Model):
     attribute1: str
     attribute2: int

     @weave.op
     def predict(self, input_data: str) -> dict:
         # モデルのロジックをここに記述します
         prediction = self.attribute1 + ' ' + input_data
         return {'pred': prediction}
Pydantic フィールド:
  • name: str | None
  • description: str | None
  • ref: trace.refs.ObjectRef | None
Source

method get_infer_method

get_infer_method() → Callable

Source

class Monitor

受信したコールを自動的にスコアリングするためのモニターをセットアップします。 例:
import weave
from weave.scorers import ValidJSONScorer

json_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 フィールド:
  • name: str | None
  • description: str | None
  • ref: trace.refs.ObjectRef | None
  • sampling_rate: <class 'float'>
  • scorers: list[flow.scorer.Scorer]
  • op_names: list[str]
  • query: trace_server.interface.query.Query | None
  • active: <class 'bool'>
Source

method activate

activate() → ObjectRef
モニターをアクティブにします。 戻り値: モニターへの ref。
Source

method deactivate

deactivate() → ObjectRef
モニターを非アクティブにします。 戻り値: モニターへの ref。
Source

classmethod from_obj

from_obj(obj: WeaveObject) → Self

Source

class Object

追跡およびバージョン管理が可能な Weave オブジェクトのベースクラス。 このクラスは Pydantic の BaseModel を拡張し、オブジェクトの追跡、参照、およびシリアライズのための Weave 固有の機能を提供します。オブジェクトは名前、説明、および参照を持つことができ、これらによって Weave システムに保存および取得できます。 属性:
  • name (Optional[str]): オブジェクトの人間が読みやすい名前。
  • description (Optional[str]): オブジェクトが何を表すかの説明。
  • ref (Optional[ObjectRef]): Weave システム内のオブジェクトへの参照。
例:
# シンプルなオブジェクトを作成する
obj = Object(name="my_object", description="A test object")

# URI からオブジェクトを作成する
obj = Object.from_uri("weave:///entity/project/object:digest")
Pydantic フィールド:
  • name: str | None
  • description: str | None
  • ref: trace.refs.ObjectRef | None
Source

classmethod from_uri

from_uri(uri: str, objectify: bool = True) → Self
Weave URI からオブジェクトインスタンスを作成します。 引数:
  • uri (str): オブジェクトを指す Weave URI。
  • objectify (bool): 結果をオブジェクト化するかどうか。デフォルトは True。
戻り値:
  • Self: URI から作成されたクラスのインスタンス。
例外:
  • NotImplementedError: クラスがデシリアライズに必要なメソッドを実装していない場合。
例:
obj = MyObject.from_uri("weave:///entity/project/object:digest")

Source

classmethod handle_relocatable_object

handle_relocatable_object(
    v: Any,
    handler: ValidatorFunctionWrapHandler,
    info: ValidationInfo
) → Any
ObjectRef および WeaveObject を含む再配置可能なオブジェクトの検証を処理します。 このバリデーターは、入力が標準の Object インスタンスに適切に変換される必要がある ObjectRef または WeaveObject である特殊なケースを処理します。検証プロセス中に参照が保持され、無視されたタイプが正しく処理されるようにします。 引数:
  • v (Any): 検証する値。
  • handler (ValidatorFunctionWrapHandler): 標準的な Pydantic 検証ハンドラー。
  • info (ValidationInfo): 検証コンテキスト情報。
戻り値:
  • Any: 検証されたオブジェクトインスタンス。
例: このメソッドは、オブジェクトの作成および検証中に自動的に呼び出されます。次のようなケースを処理します: ```python

ObjectRef が渡されたとき

obj = MyObject(some_object_ref)

WeaveObject が渡されたとき

obj = MyObject(some_weave_object)

---

<SourceLink url="https://github.com/wandb/weave/blob/v0.52.24/weave/trace/refs.py#L159" />

## <kbd>class</kbd> `ObjectRef`
ObjectRef(entity: 'str', project: 'str', name: 'str', _digest: 'str | Future[str]', _extra: 'tuple[str | Future[str], ...]' = ()) 

<SourceLink url="https://github.com/wandb/weave/blob/v0.52.24/../../../../weave/trace/refs/__init__" />

### <kbd>method</kbd> `__init__`

```python
__init__(
entity: 'str',
project: 'str',
name: 'str',
_digest: 'str | Future[str]',
_extra: 'tuple[str | Future[str], ]' = ()
) → None

property digest


property extra


Source

method as_param_dict

as_param_dict() → dict

Source

method delete

delete() → None

Source

method get

get(objectify: 'bool' = True) → Any

Source

method is_descended_from

is_descended_from(potential_ancestor: 'ObjectRef') → bool

Source

method maybe_parse_uri

maybe_parse_uri(s: 'str') → AnyRef | None

Source

method parse_uri

parse_uri(uri: 'str') → ObjectRef

Source

method uri

uri() → str

Source

method with_attr

with_attr(attr: 'str') → Self

Source

method with_extra

with_extra(extra: 'tuple[str | Future[str], ]') → Self

Source

method with_index

with_index(index: 'int') → Self

Source

method with_item

with_item(item_digest: 'str | Future[str]') → Self

Source

method with_key

with_key(key: 'str') → Self

Source

class EasyPrompt

Source

method __init__

__init__(
    content: str | dict | list | None = None,
    role: str | None = None,
    dedent: bool = False,
    **kwargs: Any
) → None
Pydantic フィールド:
  • name: str | None
  • description: str | None
  • ref: trace.refs.ObjectRef | None
  • data: <class 'list'>
  • config: <class 'dict'>
  • requirements: <class 'dict'>

property as_str

すべてのメッセージを単一の文字列に結合します。

property is_bound


property messages

property placeholders


property system_message

すべてのメッセージをシステムプロンプトメッセージに結合します。

property system_prompt

すべてのメッセージをシステムプロンプトオブジェクトに結合します。

property unbound_placeholders


Source

method append

append(item: Any, role: str | None = None, dedent: bool = False) → None

Source

method as_dict

as_dict() → dict[str, Any]

Source

method as_pydantic_dict

as_pydantic_dict() → dict[str, Any]

Source

method bind

bind(*args: Any, **kwargs: Any) → Prompt

Source

method bind_rows

bind_rows(dataset: list[dict] | Any) → list['Prompt']

Source

method config_table

config_table(title: str | None = None) → Table

Source

method configure

configure(config: dict | None = None, **kwargs: Any) → Prompt

Source

method dump

dump(fp: <class 'IO'>) → None

Source

method dump_file

dump_file(filepath: str | Path) → None

Source

method format

format(**kwargs: Any) → Any

Source

classmethod from_obj

from_obj(obj: WeaveObject) → Self

Source

classmethod load

load(fp: <class 'IO'>) → Self

Source

classmethod load_file

load_file(filepath: str | Path) → Self

Source

method messages_table

messages_table(title: str | None = None) → Table

Source

method print

print() → str

Source

method publish

publish(name: str | None = None) → ObjectRef

Source

method require

require(param_name: str, **kwargs: Any) → Prompt

Source

method run

run() → Any

Source

method validate_requirement

validate_requirement(key: str, value: Any) → list

Source

method validate_requirements

validate_requirements(values: dict[str, Any]) → list

Source

method values_table

values_table(title: str | None = None) → Table

Source

class Prompt

Pydantic フィールド:
  • name: str | None
  • description: str | None
  • ref: trace.refs.ObjectRef | None
Source

method format

format(**kwargs: Any) → Any

Source

class SavedView

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

method __init__

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

property entity


property label


property project


property view_type


Source

method add_column

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

Source

method add_columns

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

method add_filter

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

Source

method add_sort

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

Source

method column_index

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

Source

method filter_op

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

Source

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
この保存されたビューのフィルターと設定に一致するコールを取得します。
Source

method get_known_columns

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

method get_table_columns

get_table_columns() → list[TableColumn]

Source

method hide_column

hide_column(col_name: 'str') → SavedView

Source

method insert_column

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

Source

classmethod load

load(ref: 'str') → Self

Source

method page_size

page_size(page_size: 'int') → SavedView

Source

method pin_column_left

pin_column_left(col_name: 'str') → SavedView

Source

method pin_column_right

pin_column_right(col_name: 'str') → SavedView

Source

method remove_column

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

Source

method remove_columns

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

method remove_filter

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

Source

method remove_filters

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

method rename

rename(label: 'str') → SavedView

Source

method rename_column

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

Source

method save

save() → SavedView
保存されたビューをサーバーにパブリッシュします。
Source

method set_columns

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

method show_column

show_column(col_name: 'str') → SavedView

Source

method sort_by

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

Source

method to_grid

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

Source

method to_rich_table_str

to_rich_table_str() → str

Source

method ui_url

ui_url() → str | None
UI でこの保存されたビューを表示するための URL。 これは、トレースなどが表示される「結果」ページの URL であり、ビューオブジェクト自体の URL ではないことに注意してください。
Source

method unpin_column

unpin_column(col_name: 'str') → SavedView

Source

class Scorer

Pydantic フィールド:
  • name: str | None
  • description: str | None
  • ref: trace.refs.ObjectRef | None
  • column_map: dict[str, str] | None
Source

classmethod from_obj

from_obj(obj: WeaveObject) → Self

Source

method model_post_init

model_post_init(_Scorer__context: Any) → None

Source

method score

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

Source

method summarize

summarize(score_rows: list) → dict | None

Source

class StringPrompt

Source

method __init__

__init__(content: str)
Pydantic フィールド:
  • name: str | None
  • description: str | None
  • ref: trace.refs.ObjectRef | None
  • content: <class 'str'>
Source

method format

format(**kwargs: Any) → str

Source

classmethod from_obj

from_obj(obj: WeaveObject) → Self

Source

class Table

Source

method __init__

__init__(rows: 'list[dict]') → None

property rows


Source

method append

append(row: 'dict') → None
テーブルに行を追加します。
Source

method pop

pop(index: 'int') → None
テーブルの指定されたインデックスにある行を削除します。
Source

class ContextAwareThread

呼び出し元のコンテキストで関数を実行するスレッド。 これは threading.Thread のドロップインリプレースメントであり、スレッド内での呼び出しが期待通りに動作することを保証します。Weave は特定の contextvars が設定されている必要がありますが(call_context.py を参照)、新しいスレッドは親からコンテキストを自動的にコピーしないため、コールコンテキストが失われる可能性があります。このクラスは contextvar のコピーを自動化するため、このスレッドを使用すればユーザーが期待する通りに「ただ動作」します。 このクラスを使わずに、次のように記述することで同じ効果を得ることもできます:
def run_with_context(func, *args, **kwargs):
     context = copy_context()
     def wrapper():
         context.run(func, *args, **kwargs)
     return wrapper

thread = threading.Thread(target=run_with_context(your_func, *args, **kwargs))
thread.start()
Source

method __init__

__init__(*args: 'Any', **kwargs: 'Any') → None

property daemon

このスレッドがデーモンスレッドかどうかを示すブール値。 これは start() が呼び出される前に設定する必要があり、そうでない場合は RuntimeError が発生します。初期値は作成元のスレッドから継承されます。メインスレッドはデーモンスレッドではないため、メインスレッドで作成されたすべてのスレッドはデフォルトで daemon = False になります。 デーモンスレッドのみが残ると、Python プログラム全体が終了します。

property ident

このスレッドのスレッド識別子。まだ開始されていない場合は None。 これは 0 以外の整数です。get_ident() 関数を参照してください。スレッド識別子は、スレッドが終了して別のスレッドが作成されたときに再利用される可能性があります。識別子はスレッドが終了した後でも利用可能です。

property name

識別目的のみに使用される文字列。 セマンティクスはありません。複数のスレッドに同じ名前を付けることができます。初期名はコンストラクターによって設定されます。

property native_id

このスレッドのネイティブ整数スレッド ID。まだ開始されていない場合は None。 これは非負の整数です。get_native_id() 関数を参照してください。これはカーネルによって報告されるスレッド ID を表します。
Source

method run

run() → None

Source

class ThreadContext

現在のスレッドおよびターンの情報へのアクセスを提供するコンテキストオブジェクト。 Source

method __init__

__init__(thread_id: 'str | None')
指定された thread_id で ThreadContext を初期化します。 引数:

property thread_id

このコンテキストの thread_id を取得します。
  • thread_id: このコンテキストのスレッド識別子。無効な場合は None。 戻り値: スレッド識別子。スレッドトラッキングが無効な場合は None。

property turn_id

アクティブなコンテキストから現在の turn_id を取得します。 戻り値: 設定されている場合は現在の turn_id、そうでない場合は None。
Source

class ContextAwareThreadPoolExecutor

呼び出し元のコンテキストで関数を実行する ThreadPoolExecutor。 これは concurrent.futures.ThreadPoolExecutor のドロップインリプレースメントであり、エグゼキューター内での weave の呼び出しが期待通りに動作することを保証します。Weave は特定の contextvars が設定されている必要がありますが(call_context.py を参照)、新しいスレッドは親からコンテキストを自動的にコピーしないため、コールコンテキストが失われる可能性があります。このクラスは contextvar のコピーを自動化するため、このエグゼキューターを使用すればユーザーが期待する通りに「ただ動作」します。 このクラスを使わずに、次のように記述することで同じ効果を得ることもできます:
with concurrent.futures.ThreadPoolExecutor() as executor:
     contexts = [copy_context() for _ in range(len(vals))]

     def _wrapped_fn(*args):
         return contexts.pop().run(fn, *args)

     executor.map(_wrapped_fn, vals)
Source

method __init__

__init__(*args: 'Any', **kwargs: 'Any') → None

Source

method map

map(
    fn: 'Callable',
    *iterables: 'Iterable[Any]',
    timeout: 'float | None' = None,
    chunksize: 'int' = 1
) → Iterator

Source

method submit

submit(fn: 'Callable', *args: 'Any', **kwargs: 'Any') → Any

Source

function as_op

as_op(fn: 'Callable[P, R]') → Op[P, R]
@weave.op デコレートされた関数が与えられたとき、その Op を返します。 @weave.op デコレートされた関数はすでに Op のインスタンスであるため、この関数は実行時には no-op(何もしない)であるはずです。しかし、タイプセーフな方法で OpDef 属性にアクセスする必要がある場合に、型チェッカーを満足させるために使用できます。 引数:
  • fn: weave.op デコレートされた関数。 戻り値: 関数の Op。

Source

function attributes

attributes(attributes: 'dict[str, Any]') → Iterator
コールに属性を設定するためのコンテキストマネージャー。 例:
with weave.attributes({'env': 'production'}):
     print(my_function.call("World"))

Source

function finish

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

function get

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

dataset2 = weave.get(ref)  # dataset と同じです!

Source

function get_client

get_client() → WeaveClient | None

Source

function get_current_call

get_current_call() → Call | None
現在実行中の Op 内で、その Op の Call オブジェクトを取得します。 戻り値: 現在実行中の Op の Call オブジェクト。トラッキングが初期化されていない場合や、このメソッドが Op 外で呼び出された場合は None。 注:
返された Call の attributes 辞書は、コールが開始されると不変(immutable)になります。Op を呼び出す前にコールのメタデータを設定するには、:func:weave.attributes を使用してください。summary フィールドは Op の実行中に更新される可能性があり、コール終了時に計算されたサマリー情報とマージされます。

Source

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
weave トラッキングを初期化し、wandb プロジェクトにログを記録します。 ログ記録はグローバルに初期化されるため、init の戻り値を保持しておく必要はありません。 init の後、weave.op デコレートされた関数の呼び出しは指定されたプロジェクトにログとして記録されます。 引数: 注意:グローバルな後処理設定は、各 op 独自の後処理の後に、すべての op に適用されます。順序は常に次の通りです: 1. Op 固有の後処理 2. グローバルな後処理
  • project_name: ログを記録する Weights & Biases の Team 名と Project 名。Team を指定しない場合、デフォルトの Entity が使用されます。デフォルトの Entity を確認または更新するには、W&B Models ドキュメントの User Settings を参照してください。
  • settings: Weave クライアント全般の設定。
  • autopatch_settings: (非推奨) オートパッチインテグレーションの設定。代わりに明示的なパッチ適用を使用してください。
  • global_postprocess_inputs: すべての op のすべての入力に適用される関数。
  • global_postprocess_output: すべての op のすべての出力に適用される関数。
  • global_attributes: すべてのトレースに適用される属性の辞書。 戻り値: Weave クライアント。

Source

function log_call

log_call(
    op: 'str',
    inputs: 'dict[str, Any]',
    output: 'Any',
    parent: 'Call | None' = None,
    attributes: 'dict[str, Any] | None' = None,
    display_name: 'str | Callable[[Call], str] | None' = None,
    use_stack: 'bool' = True,
    exception: 'BaseException | None' = None
) → Call
デコレーターパターンを使用せずに、Weave に直接コールをログ記録します。 この関数は、すでに実行された後にコールを記録したい場合や、デコレーターパターンがユースケースに適さない場合に便利な、Weave への操作ログ記録用命令型 API を提供します。 引数:
  • op (str): ログに記録する操作名。これはコールの op_name として使用されます。匿名操作(公開された op を参照しない文字列)もサポートされています。
  • inputs (dict[str, Any]): 操作の入力パラメータの辞書。
  • output (Any): 操作の出力/結果。
  • parent (Call | None): このコールをネストさせるオプションの親コール。指定されない場合、コールはルートレベルのコールになります(または、存在する場合は現在のコールコンテキストの下にネストされます)。デフォルトは None。
  • attributes (dict[str, Any] | None): コールにアタッチするオプションのメタデータ。これらはコール作成時に固定(凍結)されます。デフォルトは None。
  • display_name (str | Callable[[Call], str] | None): UI でのコールのオプションの表示名。文字列、またはコールを受け取って文字列を返す呼び出し可能オブジェクトを指定できます。デフォルトは None。
  • use_stack (bool): コールを実行時スタックにプッシュするかどうか。True の場合、コールはコールコンテキストで利用可能になり、weave.require_current_call() を介してアクセスできます。False の場合、コールはログに記録されますが、コールスタックには追加されません。デフォルトは True。
  • exception (BaseException | None): 操作が失敗した場合にログに記録するオプションの例外。デフォルトは None。
戻り値:
  • Call: 完全なトレース情報を持つ、作成および完了済みの Call オブジェクト。
例: 基本的な使用法:
import weave
    >>> weave.init('my-project')
    >>> call = weave.log_call(
    ...     op="my_function",
    ...     inputs={"x": 5, "y": 10},
    ...     output=15
    ... )

    属性と表示名を使用したログ記録:
    >>> call = weave.log_call(
    ...     op="process_data",
    ...     inputs={"data": [1, 2, 3]},
    ...     output={"mean": 2.0},
    ...     attributes={"version": "1.0", "env": "prod"},
    ...     display_name="Data Processing"
    ... )

    失敗した操作のログ記録:
    >>> try:
    ...     result = risky_operation()
    ... except Exception as e:
    ...     call = weave.log_call(
    ...         op="risky_operation",
    ...         inputs={},
    ...         output=None,
    ...         exception=e
    ...     )

    コールのネスト:
    >>> parent_call = weave.log_call("parent", {"input": 1}, 2)
    >>> child_call = weave.log_call(
    ...     "child",
    ...     {"input": 2},
    ...     4,
    ...     parent=parent_call
    ... )

    コールスタックに追加せずにログ記録:
    >>> call = weave.log_call(
    ...     op="background_task",
    ...     inputs={"task_id": 123},
    ...     output="completed",
    ...     use_stack=False  # コールスタックにプッシュしない
    ... )

---

<SourceLink url="https://github.com/wandb/weave/blob/v0.52.24/weave/trace/op.py#L1202" />

### <kbd>function</kbd> `op`

```python
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,
    kind: 'OpKind | None' = None,
    color: 'OpColor | None' = None
) → Callable[[Callable[P, R]], Op[P, R]] | Op[P, R]
関数またはメソッドを weave op 化するためのデコレーター。同期と非同期の両方で動作します。イテレーター関数を自動的に検出し、適切な振る舞いを適用します。
Source

function publish

publish(obj: 'Any', name: 'str | None' = None) → ObjectRef
Python オブジェクトを保存し、バージョン管理します。 オブジェクトの名前がすでに存在し、そのコンテンツのハッシュが最新バージョンのオブジェクトと一致しない場合、Weave はオブジェクトの新しいバージョンを作成します。 引数:
  • obj: 保存およびバージョン管理するオブジェクト。
  • name: オブジェクトを保存する名前。 戻り値: 保存されたオブジェクトへの Weave Ref。

Source

function ref

ref(location: 'str') → ObjectRef
既存の Weave オブジェクトへの Ref を作成します。これは直接オブジェクトを取得するのではなく、他の Weave API 関数に渡すことができるようにします。 引数:
  • location: Weave Ref URI、または weave.init() が呼び出されている場合は name:version または name。バージョンが提供されない場合は latest が使用されます。 戻り値: オブジェクトへの Weave Ref。

Source

function require_current_call

require_current_call() → Call
現在実行中の Op 内で、その Op の Call オブジェクトを取得します。 これにより、実行中にその ID やフィードバックなどの Call 属性にアクセスできます。
@weave.op
def hello(name: str) -> None:
     print(f"Hello {name}!")
     current_call = weave.require_current_call()
     print(current_call.id)
Op が戻った後に Call にアクセスすることも可能です。 UI などから得られた Call の ID がある場合は、weave.init から返された WeaveClientget_call メソッドを使用して Call オブジェクトを取得できます。
client = weave.init("<project>")
mycall = client.get_call("<call_id>")
あるいは、Op を定義した後、その call メソッドを使用することもできます。例:
@weave.op
def add(a: int, b: int) -> int:
     return a + b

result, call = add.call(1, 2)
print(call.id)
戻り値: 現在実行中の Op の Call オブジェクト。 例外:
  • NoCurrentCallError: トラッキングが初期化されていない場合や、このメソッドが Op 外で呼び出された場合。

Source

function set_view

set_view(
    name: 'str',
    content: 'Content | str',
    extension: 'str | None' = None,
    mimetype: 'str | None' = None,
    metadata: 'dict[str, Any] | None' = None,
    encoding: 'str' = 'utf-8'
) → None
現在のコールのサマリーの _weave.views.<name> にカスタムビューをアタッチします。 引数:
  • name: ビュー名(summary._weave.views 下のキー)。
  • content: weave.Content インスタンスまたは生の文字列。文字列は、提供された拡張子または mimetype を使用して Content.from_text 経由でラップされます。
  • extension: content が文字列の場合に使用するオプションのファイル拡張子。
  • mimetype: content が文字列の場合に使用するオプションの MIME タイプ。
  • metadata: テキストから Content を作成する際にアタッチするオプションのメタデータ。
  • encoding: テキストから Content を作成する際に適用するテキストエンコーディング。 戻り値: None
例: import weave
weave.init(“proj”) @weave.op … def foo(): … weave.set_view(“readme”, ”# Hello”, extension=“md”) … return 1 foo()

Source

function thread

thread(
    thread_id: 'str | None | object' = <object object at 0x7fd95e3cc980>
) → Iterator[ThreadContext]
コンテキスト内のコールに thread_id を設定するためのコンテキストマネージャー。 例:
# thread_id を自動生成する
with weave.thread() as t:
     print(f"Thread ID: {t.thread_id}")
     result = my_function("input")  # このコールは自動生成された thread_id を持ちます
     print(f"Current turn: {t.turn_id}")

# thread_id を明示的に指定する
with weave.thread("custom_thread") as t:
     result = my_function("input")  # このコールは thread_id="custom_thread" を持ちます

# スレッディングを無効にする
with weave.thread(None) as t:
     result = my_function("input")  # このコールは thread_id=None を持ちます
引数:
  • thread_id: このコンテキスト内のコールに関連付けるスレッド識別子。指定されない場合、UUID v7 が自動生成されます。None の場合、スレッドトラッキングは無効になります。 Yields:
  • ThreadContext: thread_id および現在の turn_id へのアクセスを提供するオブジェクト。

Source

function wandb_init_hook

wandb_init_hook() → None