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

# Tutorial tracing 2

In the [LLMの入力と出力を追跡する](/ja/quickstart) チュートリアルでは、LLMの入力と出力を追跡する基本について説明しました。

このチュートリアルでは、以下の方法を学びます：

* **データを追跡する** アプリケーション全体を通じて
* **メタデータを追跡する** 呼び出し時に

## ネストされた関数呼び出しの追跡

LLMを活用したアプリケーションには、複数のLLM呼び出しや、監視が重要な追加のデータ処理および検証ロジックが含まれることがあります。多くのアプリで一般的な深くネストされた呼び出し構造であっても、Weaveは`weave.op()` が追跡したいすべての関数に追加されている限り、ネストされた関数の親子関係を追跡し続けます。

私たちの[基本的なトレース例](/ja/quickstart)に基づいて、LLMから返されるアイテムをカウントする追加ロジックを追加し、それらをすべて上位レベルの関数でラップします。次に`weave.op()` を追加して、すべての関数、その呼び出し順序、および親子関係をトレースします：

<Tabs>
  <Tab title="Python">
    ```python
    import weave
    import json
    from openai import OpenAI

    client = OpenAI()

    # highlight-next-line
    @weave.op()
    def extract_dinos(sentence: str) -> dict:
        response = client.chat.completions.create(
            model="gpt-4o",
            messages=[
                {
                    "role": "system",
                    "content": """Extract any dinosaur `name`, their `common_name`, \
    names and whether its `diet` is a herbivore or carnivore, in JSON format."""
                },
                {
                    "role": "user",
                    "content": sentence
                }
                ],
                response_format={ "type": "json_object" }
            )
        return response.choices[0].message.content

    # highlight-next-line
    @weave.op()
    def count_dinos(dino_data: dict) -> int:
        # count the number of items in the returned list
        k = list(dino_data.keys())[0]
        return len(dino_data[k])

    # highlight-next-line
    @weave.op()
    def dino_tracker(sentence: str) -> dict:
        # extract dinosaurs using a LLM
        dino_data = extract_dinos(sentence)

        # count the number of dinosaurs returned
        dino_data = json.loads(dino_data)
        n_dinos = count_dinos(dino_data)
        return {"n_dinosaurs": n_dinos, "dinosaurs": dino_data}

    # highlight-next-line
    weave.init('jurassic-park')

    sentence = """I watched as a Tyrannosaurus rex (T. rex) chased after a Triceratops (Trike), \
    both carnivore and herbivore locked in an ancient dance. Meanwhile, a gentle giant \
    Brachiosaurus (Brachi) calmly munched on treetops, blissfully unaware of the chaos below."""

    result = dino_tracker(sentence)
    print(result)
    ```

    **ネストされた関数**

    上記のコードを実行すると、2つのネストされた関数（`extract_dinos` と`count_dinos`）からの入力と出力、および自動的に記録されたOpenAIトレースが表示されます。

    ![Nested Weave Trace](https://mintlify.s3.us-west-1.amazonaws.com/wb-21fd5541-feature-automate-reference-docs-generation/ja/images/tutorial_tracing_2_nested_dinos.png)
  </Tab>

  <Tab title="TypeScript">
    ```typescript
    import OpenAI from 'openai';
    import * as weave from 'weave';

    const openai = new OpenAI();

    const extractDinos = weave.op(async (sentence: string) => {
      const response = await openai.chat.completions.create({
        model: 'gpt-4o',
        messages: [
          {
            role: 'system',
            content:
              'Extract any dinosaur `name`, their `common_name`, names and whether its `diet` is a herbivore or carnivore, in JSON format.',
          },
          {role: 'user', content: sentence},
        ],
        response_format: {type: 'json_object'},
      });
      return response.choices[0].message.content;
    });

    const countDinos = weave.op(async (dinoData: string) => {
      const parsed = JSON.parse(dinoData);
      return Object.keys(parsed).length;
    });

    const dinoTracker = weave.op(async (sentence: string) => {
      const dinoData = await extractDinos(sentence);
      const nDinos = await countDinos(dinoData);
      return {nDinos, dinoData};
    });

    async function main() {
      await weave.init('jurassic-park');

      const sentence = `I watched as a Tyrannosaurus rex (T. rex) chased after a Triceratops (Trike),
            both carnivore and herbivore locked in an ancient dance. Meanwhile, a gentle giant
            Brachiosaurus (Brachi) calmly munched on treetops, blissfully unaware of the chaos below.`;

      const result = await dinoTracker(sentence);
      console.log(result);
    }

    main();

    ```

    **ネストされた関数**

    上記のコードを実行すると、2つのネストされた関数（`extractDinos` と`countDinos`）からの入力と出力、および自動的に記録されたOpenAIトレースが表示されます。

    {/* TODO: Update to TS screenshot */}

    ![Nested Weave Trace](https://mintlify.s3.us-west-1.amazonaws.com/wb-21fd5541-feature-automate-reference-docs-generation/ja/images/tutorial_tracing_2_nested_dinos.png)
  </Tab>
</Tabs>

## メタデータの追跡

メタデータの追跡は、`weave.attributes` コンテキストマネージャーを使用し、呼び出し時に追跡するメタデータの辞書を渡すことで簡単に行えます。

上記の例を続けます：

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

    weave.init('jurassic-park')

    sentence = """I watched as a Tyrannosaurus rex (T. rex) chased after a Triceratops (Trike), \
    both carnivore and herbivore locked in an ancient dance. Meanwhile, a gentle giant \
    Brachiosaurus (Brachi) calmly munched on treetops, blissfully unaware of the chaos below."""

    # track metadata alongside our previously defined function
    # highlight-next-line
    with weave.attributes({'user_id': 'lukas', 'env': 'production'}):
        result = dino_tracker(sentence)
    ```
  </Tab>

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

<Note>
  実行時にメタデータを追跡するには、メタデータ追跡を使用することをお勧めします。例えば、ユーザーIDや、呼び出しが開発プロセスの一部であるか本番環境であるかなどです。

  システムプロンプトなどのシステム設定を追跡するには、[weave Models](guides/core-types/models)
</Note>

## 次のステップ

* 以下の[アプリケーションのバージョン管理チュートリアル](/ja/tutorial-weave_models) に従って、アドホックなプロンプト、モデル、およびアプリケーションの変更をキャプチャ、バージョン管理、整理します。
