In the LLMの入力と出力を追跡する チュートリアルでは、LLMの入力と出力を追跡する基本について説明しました。 このチュートリアルでは、以下の方法を学びます:
  • データを追跡する アプリケーション全体を通じて
  • メタデータを追跡する 呼び出し時に

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

LLMを活用したアプリケーションには、複数のLLM呼び出しや、監視が重要な追加のデータ処理および検証ロジックが含まれることがあります。多くのアプリで一般的な深くネストされた呼び出し構造であっても、Weaveはweave.op() が追跡したいすべての関数に追加されている限り、ネストされた関数の親子関係を追跡し続けます。 私たちの基本的なトレース例に基づいて、LLMから返されるアイテムをカウントする追加ロジックを追加し、それらをすべて上位レベルの関数でラップします。次にweave.op() を追加して、すべての関数、その呼び出し順序、および親子関係をトレースします:
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_dinoscount_dinos)からの入力と出力、および自動的に記録されたOpenAIトレースが表示されます。Nested Weave Trace

メタデータの追跡

メタデータの追跡は、weave.attributes コンテキストマネージャーを使用し、呼び出し時に追跡するメタデータの辞書を渡すことで簡単に行えます。 上記の例を続けます:
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)
実行時にメタデータを追跡するには、メタデータ追跡を使用することをお勧めします。例えば、ユーザーIDや、呼び出しが開発プロセスの一部であるか本番環境であるかなどです。システムプロンプトなどのシステム設定を追跡するには、weave Models

次のステップ