> ## Documentation Index
> Fetch the complete documentation index at: https://wb-21fd5541-feature-automate-reference-docs-generation.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Tracing

![Weave Calls Screenshot](https://mintlify.s3.us-west-1.amazonaws.com/wb-21fd5541-feature-automate-reference-docs-generation/images/screenshots/calls_macro.png)

![Weave Calls Screenshot](https://mintlify.s3.us-west-1.amazonaws.com/wb-21fd5541-feature-automate-reference-docs-generation/images/screenshots/basic_call.png)

![Weave Calls Screenshot](https://mintlify.s3.us-west-1.amazonaws.com/wb-21fd5541-feature-automate-reference-docs-generation/images/screenshots/calls_filter.png)

<Info>
  **Calls**
  CallsはWeaveの基本的な構成要素です。関数の単一の実行を表し、以下を含みます：

  * 入力（引数）
  * 出力（戻り値）
  * メタデータ（実行時間、例外、LLM使用状況など）

  Callsは[OpenTelemetry](https://opentelemetry.io)データモデルのスパンに似ています。Callは以下のことができます：

  * Trace（同じ実行コンテキスト内のCallのコレクション）に属する
  * 親子関係のCallを持ち、ツリー構造を形成する
</Info>

## Callsの作成

Weaveでのcallの作成には主に3つの方法があります：

### 1. LLMライブラリの自動トラッキング

<Tabs>
  <Tab title="Python">
    Weaveは自動的に[一般的なLLMライブラリへの呼び出し](../integrations/index.mdx)を追跡します。例えば`openai`、`anthropic`、`cohere`、そして`mistral`などです。プログラムの開始時に単に[`weave.init('project_name')`](../../reference/python-sdk/weave/index.md#function-init)を呼び出すだけです：

    <Tip>
      Weaveのデフォルトのトラッキング動作は[の`autopatch_settings`引数を使用して`weave.init`](#configure-autopatching)制御できます。
    </Tip>

    ```python showLineNumbers
    import weave

    from openai import OpenAI
    client = OpenAI()

    # Initialize Weave Tracing
    weave.init('intro-example')

    response = client.chat.completions.create(
        model="gpt-4",
        messages=[
            {
                "role": "user",
                "content": "How are you?"
            }
        ],
        temperature=0.8,
        max_tokens=64,
        top_p=1,
    )
    ```
  </Tab>

  <Tab title="TypeScript">
    Weaveは自動的に[一般的なLLMライブラリへの呼び出し](../integrations/index.mdx)を追跡します。例えば`openai`などです。

    ```typescript showLineNumbers
    import OpenAI from 'openai'
    import * as weave from 'weave'

    const client = new OpenAI()

    // Initialize Weave Tracing
    await weave.init('intro-example')

    const response = await client.chat.completions.create({
      model: 'gpt-4',
      messages: [
        {
          role: 'user',
          content: 'How are you?',
        },
      ],
      temperature: 0.8,
      max_tokens: 64,
      top_p: 1,
    });
    ```

    JS / TSプロジェクトの完全なセットアップガイドについては、[TypeScript SDK: サードパーティ統合ガイド](../integrations/js.mdx)を参照してください。
  </Tab>
</Tabs>

#### サマリー

メトリクスやその他の呼び出し後の値をCallの`summary`summary
辞書に保存できます。実行中に`call.summary`summaryを変更すると、追加した値は呼び出しが終了したときにWeaveの計算されたサマリーデータとマージされます。

### 2. 関数の装飾とラッピング

しかし、LLMアプリケーションには、追跡したい追加のロジック（前処理/後処理、プロンプトなど）がある場合が多いです。

<Tabs>
  <Tab title="Python">
    Weaveでは[`@weave.op`](../../reference/python-sdk/weave/index.md#function-op)デコレータを使用してこれらの呼び出しを手動で追跡できます。例えば：

    ```python showLineNumbers
    import weave

    # Initialize Weave Tracing
    weave.init('intro-example')

    # Decorate your function
    @weave.op
    def my_function(name: str):
        return f"Hello, {name}!"

    # Call your function -- Weave will automatically track inputs and outputs
    print(my_function("World"))
    ```

    また、[クラスのメソッド](#4-track-class-and-object-methods)も追跡できます。

    #### 同期および非同期ジェネレータ関数のトレース

    Weaveは同期および非同期ジェネレータ関数の両方をトレースすることをサポートしており、深くネストされたパターンも含まれます。

    <Warning>
      ジェネレータは値を遅延的に生成するため、出力はジェネレータが完全に消費された場合（例えば、リストに変換することによって）にのみログに記録されます。
      トレースに出力が確実に記録されるようにするには、ジェネレータを完全に消費してください（例えば、`list()`を使用するなど）。
    </Warning>

    ```python showLineNumbers
    from typing import Generator
    import weave

    weave.init("my-project")

    # This function uses a simple sync generator.
    # Weave will trace the call and its input (`x`), 
    # but output values are only captured once the generator is consumed (e.g., via `list()`).
    @weave.op
    def basic_gen(x: int) -> Generator[int, None, None]:
        yield from range(x)

    # A normal sync function used within the generator pipeline.
    # Its calls are also traced independently by Weave.
    @weave.op
    def inner(x: int) -> int:
        return x + 1

    # A sync generator that calls another traced function (`inner`).
    # Each yielded value comes from a separate traced call to `inner`.
    @weave.op
    def nested_generator(x: int) -> Generator[int, None, None]:
        for i in range(x):
            yield inner(i)

    # A more complex generator that composes the above generator.
    # Tracing here produces a hierarchical call tree:
    # - `deeply_nested_generator` (parent)
    #   - `nested_generator` (child)
    #     - `inner` (grandchild)
    @weave.op
    def deeply_nested_generator(x: int) -> Generator[int, None, None]:
        for i in range(x):
            for j in nested_generator(i):
                yield j

    # The generator must be *consumed* for Weave to capture outputs.
    # This is true for both sync and async generators.
    res = deeply_nested_generator(4)
    list(res)  # Triggers tracing of all nested calls and yields
    ```

    ![Tracing generator functions in Weave.](https://mintlify.s3.us-west-1.amazonaws.com/wb-21fd5541-feature-automate-reference-docs-generation/ja/guides/tracking/imgs/generators.png)
  </Tab>

  <Tab title="TypeScript">
    Weaveでは[`weave.op`](../../reference/typescript-sdk/weave/functions/op.mdx)で関数をラップすることで、これらの呼び出しを手動で追跡できます。例えば：

    ```typescript showLineNumbers
    import * as weave from 'weave'

    await weave.init('intro-example')

    function myFunction(name: string) {
        return `Hello, ${name}!`
    }

    const myFunctionOp = weave.op(myFunction)
    ```

    インラインでラッピングを定義することもできます：

    ```typescript
    const myFunctionOp = weave.op((name: string) => `Hello, ${name}!`)
    ```

    これは関数だけでなく、クラスのメソッドにも機能します：

    ```typescript
    class MyClass {
        constructor() {
            this.myMethod = weave.op(this.myMethod)
        }

        myMethod(name: string) {
            return `Hello, ${name}!`
        }
    }
    ```
  </Tab>
</Tabs>

#### 実行中にcallオブジェクトのハンドルを取得する

<Tabs>
  <Tab title="Python">
    時には`Call`Call`op.call`with\_result`Call`Call

    ```python showLineNumbers
    result, call = my_function.call("World")
    ```

    その後、`call`callオブジェクト

    <Note>
      opがクラスのメソッドである場合は、インスタンスを最初の引数としてopに渡す必要があります（以下の例を参照）。
    </Note>

    ```python showLineNumbers
    # Notice that we pass the `instance` as the first argument.
    print(instance.my_method.call(instance, "World"))
    ```

    ```python showLineNumbers
    import weave

    # Initialize Weave Tracing
    weave.init("intro-example")

    class MyClass:
        # Decorate your method
        @weave.op
        def my_method(self, name: str):
            return f"Hello, {name}!"

    instance = MyClass()

    # Call your method -- Weave will automatically track inputs and outputs
    instance.my_method.call(instance, "World")
    ```
  </Tab>

  <Tab title="TypeScript">
    ```plaintext
    This feature is not available in TypeScript yet.  Stay tuned!
    ```
  </Tab>
</Tabs>

#### Call表示名

<Tabs>
  <Tab title="Python">
    場合によっては、callの表示名を上書きしたいことがあります。これは次の4つの方法のいずれかで実現できます：

    1. opを呼び出す時に表示名を変更する：

    ```python showLineNumbers
    result = my_function("World", __weave={"display_name": "My Custom Display Name"})
    ```

    <Note>
      この`__weave`metadata
    </Note>

    2. call単位で表示名を変更します。これは[`Op.call`](../../reference/python-sdk/weave/trace/weave.trace.op.md#function-call)with\_result`Call`Call[`Call.set_display_name`](../../reference/python-sdk/weave/trace/weave.trace.weave_client.md#method-set_display_name)set\_display\_name

    ```python showLineNumbers
    result, call = my_function.call("World")
    call.set_display_name("My Custom Display Name")
    ```

    3. 特定のOpのすべてのCallの表示名を変更する：

    ```python showLineNumbers
    @weave.op(call_display_name="My Custom Display Name")
    def my_function(name: str):
        return f"Hello, {name}!"
    ```

    4. この`call_display_name`display\_name`Call`Call`Call`Call

    5. 一般的なユースケースの1つは、関数名にタイムスタンプを追加するだけです。

       ```py
       from datetime import datetime

       @weave.op(call_display_name=lambda call: f"{call.func_name}__{datetime.now()}")
       def func():
           return ...
       ```

    6. また、`.attributes`

       ```py
       def custom_attribute_name(call):
           model = call.attributes["model"]
           revision = call.attributes["revision"]
           now = call.attributes["date"]

           return f"{model}__{revision}__{now}"

       @weave.op(call_display_name=custom_attribute_name)
       def func():
           return ...

       with weave.attributes(
           {
               "model": "finetuned-llama-3.1-8b",
               "revision": "v0.1.2",
               "date": "2024-08-01",
           }
       ):
           func()  # the display name will be "finetuned-llama-3.1-8b__v0.1.2__2024-08-01"

           with weave.attributes(
               {
                   "model": "finetuned-gpt-4o",
                   "revision": "v0.1.3",
                   "date": "2024-08-02",
               }
           ):
               func()  # the display name will be "finetuned-gpt-4o__v0.1.3__2024-08-02"
       ```

    **技術的注意：**「Calls」は「Ops」によって生成されます。Opは`@weave.op`weave.opでデコレートされた関数またはメソッドです。
    デフォルトでは、Opの名前は関数名であり、関連するcallも同じ表示名を持ちます。上記の例は、特定のOpのすべてのCallの表示名を上書きする方法を示しています。時々、ユーザーはOp自体の名前を上書きしたいと思うことがあります。これは次の2つの方法のいずれかで実現できます：

    1. 任意のcallがログに記録される前に、Opの`name`name

    ```python showLineNumbers
    my_function.name = "My Custom Op Name"
    ```

    2. opデコレータで`name`name

    ```python showLineNumbers
    @weave.op(name="My Custom Op Name)
    ```
  </Tab>

  <Tab title="TypeScript">
    ```plaintext
    This feature is not available in TypeScript yet.  Stay tuned!
    ```
  </Tab>
</Tabs>

#### 属性

<Tabs>
  <Tab title="Python">
    追跡された関数を呼び出す際、[`weave.attributes`](../../reference/python-sdk/weave/index.md#function-attributes)weave.attributes`env`example`'production'`value

    ```python showLineNumbers
    # ... continued from above ...

    # Add additional attributes to the call
    with weave.attributes({'env': 'production'}):
        print(my_function.call("World"))
    ```

    <Tip>
      `call.attributes`attributesはcallが開始されると変更できません。このコンテキストマネージャを使用して、opを呼び出す前に任意のメタデータを設定してください。
    </Tip>
  </Tab>

  <Tab title="TypeScript">
    ```plaintext
    This feature is not available in TypeScript yet.  Stay tuned!
    ```
  </Tab>
</Tabs>

#### 並列（マルチスレッド）関数呼び出しのトレース

<Tabs>
  <Tab title="Python">
    デフォルトでは、並列呼び出しはすべてWeaveで別々のルート呼び出しとして表示されます。同じ親`op`Call[`ThreadPoolExecutor`](../../reference/python-sdk/weave/trace/weave.trace.util/#class-contextawarethreadpoolexecutor)weave.trace\_context

    以下のコードサンプルは`ThreadPoolExecutor`weave.trace\_contextの使用方法を示しています。
    最初の関数`func`increment`op`weave.op`x`x`x+1`x + 1`outer`increment\_all`op`weave.op`outer`increment\_all`ThreadPoolExecutor`weave.trace\_context`exc.map(func, inputs)`concurrent.futures`func`increment

    ```python
    import weave

    @weave.op
    def func(x):
        return x+1

    @weave.op
    def outer(inputs):
        with weave.ThreadPoolExecutor() as exc:
            exc.map(func, inputs)

    # Update your Weave project name  
    client = weave.init('my-weave-project')
    outer([1,2,3,4,5])
    ```

    Weave UIでは、これにより5つのネストされた子呼び出しを持つ単一の親呼び出しが生成されるため、インクリメントが並列で実行されていても完全に階層的なトレースが得られます。

    ![The Trace UI, showing a single parent call for outer, with five nested child calls.](https://mintlify.s3.us-west-1.amazonaws.com/wb-21fd5541-feature-automate-reference-docs-generation/ja/guides/tracking/imgs/threadpoolexecutor.png)
  </Tab>
</Tabs>

### 3. 手動Call追跡

APIを直接使用してCallを手動で作成することもできます。

<Tabs>
  <Tab title="Python">
    ```python showLineNumbers
    import weave

    # Initialize Weave Tracing
    client = weave.init('intro-example')

    def my_function(name: str):
        # Start a call
        call = client.create_call(op="my_function", inputs={"name": name})

        # ... your function code ...

        # End a call
        client.finish_call(call, output="Hello, World!")

    # Call your function
    print(my_function("World"))
    ```
  </Tab>

  <Tab title="TypeScript">
    ```plaintext
    This feature is not available in TypeScript yet.  Stay tuned!
    ```
  </Tab>

  <Tab title="HTTP API">
    * コールを開始する：[POST `/call/start`](../../reference/service-api/call-start-call-start-post.api.mdx)
    * コールを終了する：[POST `/call/end`](../../reference/service-api/call-end-call-end-post.api.mdx)

    ```bash
    curl -L 'https://trace.wandb.ai/call/start' \
    -H 'Content-Type: application/json' \
    -H 'Accept: application/json' \
    -d '{
        "start": {
            "project_id": "string",
            "id": "string",
            "op_name": "string",
            "display_name": "string",
            "trace_id": "string",
            "parent_id": "string",
            "started_at": "2024-09-08T20:07:34.849Z",
            "attributes": {},
            "inputs": {},
            "wb_run_id": "string"
        }
    }
    ```
  </Tab>
</Tabs>

### 4. クラスとオブジェクトメソッドを追跡する

クラスとオブジェクトメソッドも追跡できます。

<Tabs>
  <Tab title="Python">
    クラス上の任意のメソッドを追跡するには `weave.op`.

    ```python showLineNumbers
    import weave

    # Initialize Weave Tracing
    weave.init("intro-example")

    class MyClass:
        # Decorate your method
        @weave.op
        def my_method(self, name: str):
            return f"Hello, {name}!"

    instance = MyClass()

    # Call your method -- Weave will automatically track inputs and outputs
    print(instance.my_method("World"))
    ```
  </Tab>

  <Tab title="TypeScript">
    <Important>
      **TypeScriptでデコレータを使用する**

      TypeScriptコードで `@weave.op` デコレータを使用するには、環境が適切に構成されていることを確認してください：

      * **TypeScript v5.0以降**：デコレータはそのままサポートされており、追加の設定は必要ありません。
      * **TypeScript v5.0より前のバージョン**：デコレータの実験的サポートを有効にしてください。詳細については、[デコレータに関する公式TypeScriptドキュメント](https://www.typescriptlang.org/docs/handbook/decorators.html)を参照してください。
    </Important>

    #### クラスメソッドをデコレートする

    インスタンスメソッドをトレースするには `@weave.op` を使用します。

    ```typescript
    class Foo {
        @weave.op
        async predict(prompt: string) {
            return "bar"
        }
    }
    ```

    #### 静的クラスメソッドをデコレートする

    クラス内のユーティリティ関数を監視するには、静的メソッドに `@weave.op` を適用します。

    ```typescript
    class MathOps {
        @weave.op
        static square(n: number): number {
            return n * n;
        }
    }
    ```
  </Tab>
</Tabs>

## コールの表示

<Tabs>
  <Tab title="Webアプリ">
    Webアプリでコールを表示するには：

    1. プロジェクトの「Traces」タブに移動します
    2. リストから表示したいコールを見つけます
    3. コールをクリックして詳細ページを開きます

    詳細ページには、コールの入力、出力、実行時間、およびその他のメタデータが表示されます。

    ![View Call in Web App](https://mintlify.s3.us-west-1.amazonaws.com/wb-21fd5541-feature-automate-reference-docs-generation/ja/images/screenshots/basic_call.png)
  </Tab>

  <Tab title="Python">
    Python APIを使用してコールを表示するには、[`get_call`](../../reference/python-sdk/weave/trace/weave.trace.weave_client#method-get_call) method:

    ```python
    import weave

    # Initialize the client
    client = weave.init("your-project-name")

    # Get a specific call by its ID
    call = client.get_call("call-uuid-here")

    print(call)
    ```

    ### カスタマイズされたトレースのレンダリングには `weave.Markdown`

    Weaveを使用すると、元のデータを失うことなく、トレースされた操作の表示方法を簡単に調整できます。
    `weave.Markdown` を使用すると、入力と出力をきれいで読みやすいフォーマットされたコンテンツブロックとしてレンダリングしながら、プログラムによるアクセスのために基礎となる構造化データを保持できます。
    トレースの読みやすさを向上させるには、`postprocess_inputs` と `postprocess_output` を `@weave.op` デコレータで使用します。

    次のコードサンプルでは、ポストプロセッサを使用して、絵文字と見やすいフォーマットでWeaveにコールをレンダリングしています：

    <pre>
      ```python
      import weave

      def postprocess_inputs(query) -> weave.Markdown:
          search_box = f"""
      **Search Query:**
      ``+`
      {query}
      ``+`
      """
          return {"search_box": weave.Markdown(search_box),
                  "query": query}

      def postprocess_output(docs) -> weave.Markdown:
          formatted_docs = f"""
      # {docs[0]["title"]}

      {docs[0]["content"]}

      [Read more]({docs[0]["url"]})

      ---

      # {docs[1]["title"]}

      {docs[1]["content"]}

      [Read more]({docs[1]["url"]})
      """
          return weave.Markdown(formatted_docs)

      @weave.op(
          postprocess_inputs=postprocess_inputs,
          postprocess_output=postprocess_output,
      )
      def rag_step(query):
          # example newspaper articles of the companies on the S&P 500 
          docs = [
              {
                  "title": "OpenAI",
                  "content": "OpenAI is a company that makes AI models.",
                  "url": "https://www.openai.com",
              },
              {
                  "title": "Google",
                  "content": "Google is a company that makes search engines.",
                  "url": "https://www.google.com",
              },
          ]
          return docs

      if __name__ == "__main__":
          weave.init('markdown_renderers')
          rag_step("Tell me about OpenAI")
      ```
    </pre>

    ![A call rendered in the Weave UI using the code sample.](https://mintlify.s3.us-west-1.amazonaws.com/wb-21fd5541-feature-automate-reference-docs-generation/ja/guides/tracking/imgs/md-call-render.png)
  </Tab>

  <Tab title="TypeScript">
    ```typescript showLineNumbers
    import * as weave from 'weave'

    // Initialize the client
    const client = await weave.init('intro-example')

    // Get a specific call by its ID
    const call = await client.getCall('call-uuid-here')

    console.log(call)
    ```
  </Tab>

  <Tab title="HTTP API">
    Service APIを使用してコールを表示するには、[`/call/read`](../../reference/service-api/call-read-call-read-post.api.mdx) エンドポイントにリクエストを送信できます。

    ```bash
    curl -L 'https://trace.wandb.ai/call/read' \
    -H 'Content-Type: application/json' \
    -H 'Accept: application/json' \
    -d '{
        "project_id": "string",
        "id": "string",
    }'
    ```
  </Tab>
</Tabs>

## コールの更新

コールは作成後はほとんど不変ですが、いくつかの変更がサポートされています：

* [表示名の設定](#set-display-name)
* [フィードバックの追加](#add-feedback)
* [コールの削除](#delete-a-call)

これらの変更はすべて、コール詳細ページに移動してUIから実行できます：

![Update Call in Web App](https://mintlify.s3.us-west-1.amazonaws.com/wb-21fd5541-feature-automate-reference-docs-generation/ja/images/call_edit_screenshot.png)

### 表示名の設定

<Tabs>
  <Tab title="Python">
    コールの表示名を設定するには、[`Call.set_display_name`](../../reference/python-sdk/weave/trace/weave.trace.weave_client.md#method-set_display_name) メソッドを使用できます。

    ```python showLineNumbers
    import weave

    # Initialize the client
    client = weave.init("your-project-name")

    # Get a specific call by its ID
    call = client.get_call("call-uuid-here")

    # Set the display name of the call
    call.set_display_name("My Custom Display Name")
    ```
  </Tab>

  <Tab title="TypeScript">
    ```plaintext
    This feature is not available in TypeScript yet.  Stay tuned!
    ```
  </Tab>

  <Tab title="HTTP API">
    Service APIを使用してコールの表示名を設定するには、[`/call/update`](../../reference/service-api/call-update-call-update-post.api.mdx) エンドポイントにリクエストを送信できます。

    ```bash
    curl -L 'https://trace.wandb.ai/call/update' \
    -H 'Content-Type: application/json' \
    -H 'Accept: application/json' \
    -d '{
        "project_id": "string",
        "call_id": "string",
        "display_name": "string",
    }'
    ```
  </Tab>
</Tabs>

### フィードバックの追加

詳細については、[フィードバックドキュメント](./feedback.mdx)を参照してください。

### コールの削除

<Tabs>
  <Tab title="Python">
    Python APIを使用してコールを削除するには、[`Call.delete`](../../reference/python-sdk/weave/trace/weave.trace.weave_client.md#method-delete) メソッドを使用できます。

    ```python showLineNumbers
    import weave

    # Initialize the client
    client = weave.init("your-project-name")

    # Get a specific call by its ID
    call = client.get_call("call-uuid-here")

    # Delete the call
    call.delete()
    ```
  </Tab>

  <Tab title="TypeScript">
    ```plaintext
    This feature is not available in TypeScript yet.  Stay tuned!
    ```
  </Tab>

  <Tab title="HTTP API">
    Service APIを使用してコールを削除するには、[`/calls/delete`](../../reference/service-api/calls-delete-calls-delete-post.api.mdx) エンドポイントにリクエストを送信できます。

    ```bash
    curl -L 'https://trace.wandb.ai/calls/delete' \
    -H 'Content-Type: application/json' \
    -H 'Accept: application/json' \
    -d '{
        "project_id": "string",
        "call_ids": [
            "string"
        ],
    }'
    ```
  </Tab>
</Tabs>

### 複数のコールの削除

<Tabs>
  <Tab title="Python">
    Python APIを使用してコールのバッチを削除するには、コールIDのリストを `delete_calls()`に渡します。

    <Important>
      * 削除できるコールの最大数は `1000`です。
      * コールを削除すると、そのすべての子も削除されます。
    </Important>

    ```python showLineNumbers
    import weave

    # Initialize the client
    client = weave.init("my-project")

    # Get all calls from client 
    all_calls = client.get_calls()

    # Get list of first 1000 Call objects
    first_1000_calls = all_calls[:1000]

    # Get list of first 1000 Call IDs
    first_1000_calls_ids = [c.id for c in first_1000_calls]

    # Delete first 1000 Call objects by ID
    client.delete_calls(call_ids=first_1000_calls_ids)
    ```
  </Tab>

  <Tab title="TypeScript">
    ```plaintext
    This feature is not available in TypeScript yet.  Stay tuned!
    ```
  </Tab>
</Tabs>

## コールのクエリとエクスポート

![Screenshot of many calls](https://mintlify.s3.us-west-1.amazonaws.com/wb-21fd5541-feature-automate-reference-docs-generation/images/screenshots/calls_filter.png)

プロジェクトの `/calls` ページ（「Traces」タブ）には、プロジェクト内のすべてのコールのテーブルビューが含まれています。そこから、以下のことができます：

* ソート
* フィルタリング
* エクスポート

![Calls Table View](https://mintlify.s3.us-west-1.amazonaws.com/wb-21fd5541-feature-automate-reference-docs-generation/images/export_modal.png)

エクスポートモーダル（上図）では、データを様々な形式でエクスポートできるだけでなく、選択したコールのPythonとCURLの同等のコードも表示されます！
始めるには、UIでビューを構築し、生成されたコードスニペットからエクスポートAPIについて詳しく学ぶのが最も簡単な方法です。

<Tabs>
  <Tab title="Python">
    Python APIを使用してコールを取得するには、[`client.get_calls`](../../reference/python-sdk/weave/trace/weave.trace.weave_client.md#method-get_calls) method:

    ```python
    import weave

    # Initialize the client
    client = weave.init("your-project-name")

    # Fetch calls
    calls = client.get_calls(filter=...)
    ```
  </Tab>

  <Tab title="TypeScript">
    TypeScript APIを使用してコールを取得するには、[`client.getCalls`](../../reference/typescript-sdk/weave/classes/WeaveClient#getcalls) メソッドを使用できます。

    ```typescript
    import * as weave from 'weave'

    // Initialize the client
    const client = await weave.init('intro-example')

    // Fetch calls
    const calls = await client.getCalls(filter=...)
    ```
  </Tab>

  <Tab title="HTTP API">
    最も強力なクエリレイヤーはService APIにあります。Service APIを使用してコールを取得するには、[`/calls/stream_query`](../../reference/service-api/calls-query-stream-calls-stream-query-post.api.mdx) エンドポイントにリクエストを送信できます。

    ```bash
    curl -L 'https://trace.wandb.ai/calls/stream_query' \
    -H 'Content-Type: application/json' \
    -H 'Accept: application/json' \
    -d '{
    "project_id": "string",
    "filter": {
        "op_names": [
            "string"
        ],
        "input_refs": [
            "string"
        ],
        "output_refs": [
            "string"
        ],
        "parent_ids": [
            "string"
        ],
        "trace_ids": [
            "string"
        ],
        "call_ids": [
            "string"
        ],
        "trace_roots_only": true,
        "wb_user_ids": [
            "string"
        ],
        "wb_run_ids": [
            "string"
        ]
    },
    "limit": 100,
    "offset": 0,
    "sort_by": [
        {
        "field": "string",
        "direction": "asc"
        }
    ],
    "query": {
        "$expr": {}
    },
    "include_costs": true,
    "include_feedback": true,
    "columns": [
        "string"
    ],
    "expand_columns": [
        "string"
    ]
    }'
    ```
  </Tab>
</Tabs>

### コールスキーマ

フィールドの完全なリストについては、[スキーマ](../../reference/python-sdk/weave/trace_server/weave.trace_server.trace_server_interface#class-callschema)を参照してください。

| プロパティ         | 型                     | 説明                                    |
| ------------- | --------------------- | ------------------------------------- |
| id            | string (uuid)         | コールの一意の識別子                            |
| project\_id   | string (オプション)        | 関連するプロジェクト識別子                         |
| op\_name      | string                | 操作の名前（参照の場合あり）                        |
| display\_name | string (オプション)        | コールのユーザーフレンドリーな名前                     |
| trace\_id     | string (uuid)         | このコールが属するトレースの識別子                     |
| parent\_id    | string (uuid)         | 親コールの識別子                              |
| started\_at   | datetime              | コールが開始されたタイムスタンプ                      |
| attributes    | Dict\[str, Any]       | コールに関するユーザー定義のメタデータ *(実行中は読み取り専用)*    |
| inputs        | Dict\[str, Any]       | コールの入力パラメータ                           |
| ended\_at     | datetime (オプション)      | コールが終了したタイムスタンプ                       |
| exception     | string (オプション)        | コールが失敗した場合のエラーメッセージ                   |
| output        | Any (オプション)           | コールの結果                                |
| summary       | Optional\[SummaryMap] | 実行後の要約情報。実行中にこれを変更してカスタムメトリクスを記録できます。 |
| wb\_user\_id  | Optional\[str]        | 関連する Weights & Biases ユーザーID          |
| wb\_run\_id   | Optional\[str]        | 関連する Weights & Biases 実行ID            |
| deleted\_at   | datetime (optional)   | 該当する場合、コール削除のタイムスタンプ                  |

上記の表はWeaveにおけるCallの主要なプロパティを概説しています。各プロパティは関数呼び出しの追跡と管理において重要な役割を果たします：

* The `id`, `trace_id`, and `parent_id` フィールドは、システム内でコールを整理し関連付けるのに役立ちます。
* タイミング情報（`started_at`, `ended_at`）はパフォーマンス分析を可能にします。
* The `attributes` and `inputs` フィールドはコールのコンテキストを提供します。属性はコールが開始されると固定されるため、`weave.attributes` で呼び出し前に設定してください。`output` and `summary` は結果をキャプチャし、`summary` は実行中に更新して追加のメトリクスを記録できます。
* Weights & Biasesとの統合は `wb_user_id` and `wb_run_id` を通じて実現されます。

このプロパティの包括的なセットにより、プロジェクト全体を通じて関数呼び出しの詳細な追跡と分析が可能になります。

計算フィールド：

* コスト
* 所要時間
* ステータス

## 保存されたビュー

トレーステーブルの構成、フィルター、並べ替えを *saved views* として保存し、お好みの設定に素早くアクセスできます。UIとPython SDKを通じて保存されたビューを設定およびアクセスできます。詳細については、[Saved Views](/ja/guides/tools/saved-views) をご覧ください。

## トレーステーブルでW\&B実行を表示する

Weaveを使用すると、コード内の関数呼び出しを追跡し、それらを実行された [W\&B runs](https://docs.wandb.ai/guides/runs/) に直接リンクできます。
@weave.op()で関数をトレースし、wandb.init()コンテキスト内で呼び出すと、WeaveはトレースをW\&B実行に自動的に関連付けます。
関連する実行へのリンクはトレーステーブルに表示されます。

### Python例

以下のPythonコードは、トレースされた操作が `wandb.init()` コンテキスト内で実行されるとW\&B実行にリンクされる方法を示しています。これらのトレースはWeave UIに表示され、対応する実行に関連付けられます。

```python
import wandb
import weave

def example_wandb(projname):
    # Split projname into entity and project
    entity, project = projname.split("/", 1)

    # Initialize Weave context for tracing
    weave.init(projname)

    # Define a traceable operation
    @weave.op()
    def say(message: str) -> str:
        return f"I said: {message}"

    # First W&B run
    with wandb.init(
        entity=entity,
        project=project,
        notes="Experiment 1",
        tags=["baseline", "paper1"],
    ) as run:
        say("Hello, world!")
        say("How are you!")
        run.log({"messages": 2})

    # Second W&B run
    with wandb.init(
        entity=entity,
        project=project,
        notes="Experiment 2",
        tags=["baseline", "paper1"],
    ) as run:
        say("Hello, world from experiment 2!")
        say("How are you!")
        run.log({"messages": 2})

if __name__ == "__main__":
    # Replace this with your actual W&B username/project
    example_wandb("your-username/your-project")
```

コードサンプルを使用するには：

1. ターミナルで依存関係をインストールします：

   ```bash
   pip install wandb weave
   ```

2. W\&Bにログインします：

   ```bash
   wandb login
   ```

3. スクリプトで、`your-username/your-project` を実際のW\&Bエンティティ/プロジェクトに置き換えます。

4. スクリプトを実行します：

   ```bash
   python weave_trace_with_wandb.py
   ```

5. Visit [https://weave.wandb.ai](https://weave.wandb.ai) にアクセスしてプロジェクトを選択します。

6. **Traces** タブで、トレース出力を表示します。関連する実行へのリンクはトレーステーブルに表示されます。

## 自動パッチの設定

デフォルトでは、Weaveは `openai`, `anthropic`, `cohere`, and `mistral` などの一般的なLLMライブラリへの呼び出しを自動的にパッチし追跡します。
この動作は `autopatch_settings` 引数を `weave.init` で使用して制御できます。

### すべての自動パッチを無効にする

```python showLineNumbers
weave.init(..., autopatch_settings={"disable_autopatch": True})
```

### 特定の統合を無効にする

```python showLineNumbers
weave.init(..., autopatch_settings={"openai": {"enabled": False}})
```

### 入力と出力の後処理

自動パッチング中に入力と出力（例：PII データ）を後処理する方法をカスタマイズすることもできます：

```python showLineNumbers
def redact_inputs(inputs: dict) -> dict:
    if "email" in inputs:
        inputs["email"] = "[REDACTED]"
    return inputs

weave.init(
    ...,
    autopatch_settings={
        "openai": {
            "op_settings": {
                "postprocess_inputs": redact_inputs,
            }
        }
    }
)
```

詳細については、[How to use Weave with PII data](../../cookbooks/pii.mdx) をご覧ください。

## よくある質問

### 大きなトレースが切り捨てられないようにするにはどうすればよいですか？

詳細については、[Trace data is truncated](../troubleshooting.md#trace-data-is-truncated) を [Troubleshooting guide](../troubleshooting.mdx) でご覧ください。

### トレースを無効にするにはどうすればよいですか？

#### 環境変数

プログラム全体のトレースを無条件に無効にしたい場合は、環境変数 `WEAVE_DISABLED=true` を設定できます。

#### クライアント初期化

特定の条件に基づいて特定の初期化のトレースを条件付きで有効にしたい場合があります。この場合、初期設定で `disabled` フラグを使用してクライアントを初期化できます。

```python
import weave

# Initialize the client
client = weave.init(..., settings={"disabled": True})
```

#### コンテキストマネージャー

最後に、アプリケーションロジックに基づいて単一の関数のトレースを条件付きで無効にしたい場合があります。この場合、コンテキストマネージャー `with set_tracing_enabled(False)` を使用できます。これは `weave.trace.context.call_context` からインポートできます。

```python
import weave
from weave.trace.context.call_context import set_tracing_enabled

client = weave.init(...)

@weave.op
def my_op():
    ...

with set_tracing_enabled(False):
    my_op()
```

### Callに関する情報をキャプチャするにはどうすればよいですか？

通常、opを直接呼び出します：

```python
@weave.op
def my_op():
    ...

my_op()
```

ただし、opの `call` メソッドを呼び出すことで、コールオブジェクトに直接アクセスすることもできます：

```python
@weave.op
def my_op():
    ...

output, call = my_op.call()
```

ここから、`call` オブジェクトには、入力、出力、その他のメタデータを含むコールに関するすべての情報が含まれます。
