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

# チュートリアル: アプリのバージョン管理

> Weave Model を使用して、アプリケーションとそのパラメーターをトラッキングし、バージョン管理する方法を学びます

[入力、出力、メタデータ](/ja/weave/quickstart)や[アプリ内を流れるデータ](/ja/weave/tutorial-tracing_2)をトラッキングすることは、システムのパフォーマンスを理解するうえで非常に重要です。一方で、**時間の経過に沿ってアプリをバージョン管理すること**も、コードやアプリケーションのパラメーターの変更によって出力がどう変わるかを理解するために重要です。Weave の `Model` クラスを使うことで、これらの変更を Weave でトラッキングできます。

このチュートリアルでは、次のことを学びます。

* Weave `Model` を使用して、アプリケーションとそのパラメーターをトラッキングし、バージョン管理する方法
* すでにログした Weave `Model` をエクスポートし、変更して再利用する方法

<div id="using-weavemodel">
  ## `weave.Model` の使用
</div>

<Warning>
  `weave.Model` クラスは現在、Python でのみサポートされています。
</Warning>

Weave `モデル` を使用すると、モデルベンダー ID、プロンプト、temperature などのパラメーターが、変更時に保存されてバージョン管理されます。

Weave で `Model` を作成するには、次のものが必要です。

* `weave.Model` を継承するクラス
* すべてのクラスフィールドの型定義
* `@weave.op()` デコレーターが付いた、型付きの `invoke` 関数

クラスフィールドやモデルを定義するコードを変更すると、**それらの変更はログされ、バージョンが更新されます**。これにより、アプリの異なるバージョン間で生成結果を比較できます。

以下の例では、**モデル名、temperature、system prompt がトラッキングされ、バージョン管理されます**。

<Tabs>
  <Tab title="Python">
    ```python lines {26,33-34} theme={null}
    import json
    from openai import OpenAI

    import weave

    @weave.op()
    def extract_dinos(wmodel: weave.Model, sentence: str) -> dict:
        response = wmodel.client.chat.completions.create(
            model=wmodel.model_name,
            temperature=wmodel.temperature,
            messages=[
                {
                    "role": "system",
                    "content": wmodel.system_prompt
                },
                {
                    "role": "user",
                    "content": sentence
                }
                ],
                response_format={ "type": "json_object" }
            )
        return response.choices[0].message.content

    # weave.Model を使ったサブクラス
    class ExtractDinos(weave.Model):
        client: OpenAI = None
        model_name: str
        temperature: float
        system_prompt: str

        # 関数名は `invoke` または `predict` にしてください
        @weave.op()
        def invoke(self, sentence: str) -> dict:
            dino_data  = extract_dinos(self, sentence)
            return json.loads(dino_data)
    ```
  </Tab>

  <Tab title="TypeScript">
    ```plaintext theme={null}
    この機能はまだ TypeScript では利用できません。続報をお待ちください！
    ```
  </Tab>
</Tabs>

これで、`invoke` を使ってモデルをインスタンス化し、呼び出せます。

<Tabs>
  <Tab title="Python">
    ```python lines {7,18} theme={null}
    weave.init('jurassic-park')
    client = OpenAI()

    system_prompt = """Extract any dinosaur `name`, their `common_name`, \
    names and whether its `diet` is a herbivore or carnivore, in JSON format."""

    dinos = ExtractDinos(
        client=client,
        model_name='gpt-4o',
        temperature=0.4,
        system_prompt=system_prompt
    )

    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 = dinos.invoke(sentence)
    print(result)
    ```
  </Tab>

  <Tab title="TypeScript">
    ```plaintext theme={null}
    この機能はまだ TypeScript では利用できません。続報をお待ちください！
    ```
  </Tab>
</Tabs>

`.invoke()` を呼び出すと、Weave のトレースで、`weave.op()` でデコレートされたモデル関数のコードに加えて、モデルパラメーターもトラッキングされていることを確認できます。モデル自体も、この場合は「v21」としてバージョン管理されており、モデルをクリックすると、そのバージョンのモデルを使用した **すべての Call** を確認できます。

<img src="https://mintcdn.com/wb-21fd5541-mintlify-bbaa8558/Kt-aSqqWFo2jJ9iu/images/tutorial-model_invoke3.png?fit=max&auto=format&n=Kt-aSqqWFo2jJ9iu&q=85&s=5db716f4bacbaca9db57fc65c2a0b16d" alt="weave model の再利用" width="1664" height="1292" data-path="images/tutorial-model_invoke3.png" />

**`weave.Model` の使用に関する注意:**

* 必要に応じて、Weave `Model` 内の関数名には `invoke` の代わりに `predict` を使用できます。
* 他のクラスメソッドも weave でトラッキングしたい場合は、`weave.op()` でラップする必要があります
* アンダースコアで始まるパラメーターは weave によって無視され、ログに記録されません

<div id="exporting-and-re-using-a-logged-weavemodel">
  ## ログした `weave.Model` のエクスポートと再利用
</div>

Weave は呼び出された モデル を保存し、バージョン管理するため、これらのモデルをエクスポートして再利用できます。

**モデル ref を取得する**
Weave UI では、特定のバージョンの モデル ref を取得できます。

**モデル を使用する**
モデル object の URI を取得したら、それをエクスポートして再利用できます。なお、エクスポートされたモデルはすでに初期化されており、すぐに使用できます。

<Tabs>
  <Tab title="Python">
    ```python lines {2} theme={null}
    # エクスポートした weave model はすでに初期化されており、すぐに呼び出せます
    new_dinos = weave.ref("weave://morgan/jurassic-park/object/ExtractDinos:ey4udBU2MU23heQFJenkVxLBX4bmDsFk7vsGcOWPjY4").get()

    # client を再び openai client に設定します
    new_dinos.client = client

    new_sentence = """I also saw an Ankylosaurus grazing on giant ferns"""
    new_result = new_dinos.invoke(new_sentence)
    print(new_result)
    ```
  </Tab>

  <Tab title="TypeScript">
    ```plaintext theme={null}
    この機能はまだ TypeScript では利用できません。続報をお待ちください
    ```
  </Tab>
</Tabs>

ここで、モデル バージョン (v21) が新しい入力で使用されたことを確認できます。

<img src="https://mintcdn.com/wb-21fd5541-mintlify-bbaa8558/Kt-aSqqWFo2jJ9iu/images/tutorial-model_re-use.png?fit=max&auto=format&n=Kt-aSqqWFo2jJ9iu&q=85&s=fee2cc78b46477366838ccd55f3650b9" alt="weave モデルの再利用" width="1260" height="1120" data-path="images/tutorial-model_re-use.png" />

<div id="whats-next">
  ## 次のステップ
</div>

* [評価パイプラインを構築するチュートリアル](/ja/weave/tutorial-eval)に沿って、アプリケーションを反復的に改善していきましょう。
