メインコンテンツへスキップ
Colab で開く Weave は、MistralAI Python library 経由で行われる LLM 呼び出しを自動的にトラッキングし、ログします。
新しい Mistral v1.0 SDK をサポートしています。詳しくは移行ガイドを参照してください。

トレース

開発時だけでなく本番環境でも、LLM アプリケーションのトレースを一元的なデータベースに保存しておくことが重要です。これらのトレースは、デバッグに使うだけでなく、アプリケーションの改善に役立つデータセットとしても活用できます。 Weave は mistralai のトレースを自動的に取得します。ライブラリは通常どおり使用でき、まず weave.init() を呼び出します。
import weave
weave.init("cheese_recommender")

# 通常通りmistralaiライブラリを使用する
import os
from mistralai import Mistral

api_key = os.environ["MISTRAL_API_KEY"]
model = "mistral-large-latest"

client = Mistral(api_key=api_key)

messages = [
    {
        "role": "user",
        "content": "What is the best French cheese?",
    },
]

chat_response = client.chat.complete(
    model=model,
    messages=messages,
)
これで、Weave は MistralAI ライブラリ経由のすべての LLM 呼び出しをトラッキングしてログします。トレースは Weave の Web インターフェースで確認できます。 mistral_trace.png

独自の ops でラップする

Weave ops を使うと、実験を進めながらコードを自動でバージョン管理し、入力と出力も記録することで、結果を再現可能にできます。@weave.op() でデコレートした関数を作成し、その中で mistralai.client.MistralClient.chat() を呼び出すだけで、Weave が入力と出力をトラッキングしてくれます。では、これをチーズ推薦ツールでどのように行うか見ていきましょう。
@weave.op()
def cheese_recommender(region:str, model:str) -> str:
    "Recommend the best cheese in a given region"
    
    messages = [
        {
            "role": "user",
            "content": f"What is the best cheese in {region}?",
        },
    ]

    chat_response = client.chat.complete(
        model=model,
        messages=messages,
    )
    return chat_response.choices[0].message.content

cheese_recommender(region="France", model="mistral-large-latest")
cheese_recommender(region="Spain", model="mistral-large-latest")
cheese_recommender(region="Netherlands", model="mistral-large-latest")
mistral_ops.png

実験をしやすくするために Model を作成する

構成要素が多いと、実験を整理するのは難しくなります。Model クラスを使用すると、system prompt や使用しているモデルなど、アプリの実験に関する詳細を記録して整理できます。これにより、アプリのさまざまなイテレーションを整理して比較しやすくなります。 Model は、コードのバージョン管理や入出力の記録に加えて、アプリケーションの挙動を制御する構造化されたパラメーターも記録するため、どのパラメーターが最も効果的だったかを簡単に検索できます。また、Weave Models は serve評価 でも使用できます。 以下の例では、modelcountry を試せます。これらのいずれかを変更するたびに、CheeseRecommender の新しい version が作成されます。
import weave
from mistralai import Mistral

weave.init("mistralai_project")

class CheeseRecommender(weave.Model): # `weave.Model` に変更
    model: str
    temperature: float

    @weave.op()
    def predict(self, region:str) -> str: # `predict` に変更
        "指定された地域で最高のチーズを推薦する"
        
        client = Mistral(api_key=api_key)

        messages = [
            {
                "role": "user",
                "content": f"What is the best cheese in {region}?",
            },
        ]

        chat_response = client.chat.complete(
            model=model,
            messages=messages,
            temperature=self.temperature
        )
        return chat_response.choices[0].message.content

cheese_model = CheeseRecommender(
    model="mistral-medium-latest",
    temperature=0.0
    )
result = cheese_model.predict(region="France")
print(result)
mistral_model.png