title: “NVIDIA NIM” description: “Use Weave to trace and log LLM calls made via the ChatNVIDIA library”

Weaveは、ChatNVIDIAライブラリを介して行われたLLM呼び出しを、weave.init()が呼び出された後、自動的に追跡およびログに記録します。
最新のチュートリアルについては、Weights & Biases on NVIDIAをご覧ください。

トレーシング

開発中および本番環境の両方で、LLMアプリケーションのトレースを中央データベースに保存することが重要です。これらのトレースはデバッグに使用し、アプリケーションを改善する際に評価するための難しい例のデータセットを構築するのに役立ちます。
WeaveはChatNVIDIA python libraryのトレースを自動的にキャプチャできます。キャプチャを開始するには、weave.init(<project-name>)を任意のプロジェクト名で呼び出します。
from langchain_nvidia_ai_endpoints import ChatNVIDIA
import weave
client = ChatNVIDIA(model="mistralai/mixtral-8x7b-instruct-v0.1", temperature=0.8, max_tokens=64, top_p=1)
# highlight-next-line
weave.init('emoji-bot')

messages=[
    {
      "role": "system",
      "content": "You are AGI. You will be provided with a message, and your task is to respond using emojis only."
    }]

response = client.invoke(messages)
chatnvidia_trace.png

独自のオペレーションを追跡する

関数を@weave.opでラップすると、入力、出力、およびアプリケーションロジックのキャプチャが開始され、データがアプリを通じてどのように流れるかをデバッグできます。オペレーションを深くネストして、追跡したい関数のツリーを構築できます。これにより、gitにコミットされていないアドホックな詳細をキャプチャするために、実験中にコードの自動バージョン管理も開始されます。単に@weave.opでデコレートされた関数を作成し、ChatNVIDIA python libraryを呼び出します。以下の例では、opでラップされた2つの関数があります。これにより、RAGアプリの検索ステップなどの中間ステップが、アプリの動作にどのように影響しているかを確認できます。
# highlight-next-line
import weave
from langchain_nvidia_ai_endpoints import ChatNVIDIA
import requests, random
PROMPT="""Emulate the Pokedex from early Pokémon episodes. State the name of the Pokemon and then describe it.
        Your tone is informative yet sassy, blending factual details with a touch of dry humor. Be concise, no more than 3 sentences. """
POKEMON = ['pikachu', 'charmander', 'squirtle', 'bulbasaur', 'jigglypuff', 'meowth', 'eevee']
client = ChatNVIDIA(model="mistralai/mixtral-8x7b-instruct-v0.1", temperature=0.7, max_tokens=100, top_p=1)

# highlight-next-line
@weave.op
def get_pokemon_data(pokemon_name):
    # highlight-next-line
    # This is a step within your application, like the retrieval step within a RAG app
    url = f"https://pokeapi.co/api/v2/pokemon/{pokemon_name}"
    response = requests.get(url)
    if response.status_code == 200:
        data = response.json()
        name = data["name"]
        types = [t["type"]["name"] for t in data["types"]]
        species_url = data["species"]["url"]
        species_response = requests.get(species_url)
        evolved_from = "Unknown"
        if species_response.status_code == 200:
            species_data = species_response.json()
            if species_data["evolves_from_species"]:
                evolved_from = species_data["evolves_from_species"]["name"]
        return {"name": name, "types": types, "evolved_from": evolved_from}
    else:
        return None

# highlight-next-line
@weave.op
def pokedex(name: str, prompt: str) -> str:
    # highlight-next-line
    # This is your root op that calls out to other ops
    # highlight-next-line
    data = get_pokemon_data(name)
    if not data: return "Error: Unable to fetch data"

    messages=[
            {"role": "system","content": prompt},
            {"role": "user", "content": str(data)}
        ]

    response = client.invoke(messages)
    return response.content

# highlight-next-line
weave.init('pokedex-nvidia')
# Get data for a specific Pokémon
pokemon_data = pokedex(random.choice(POKEMON), PROMPT)
Weaveに移動し、UIでget_pokemon_dataをクリックすると、そのステップの入力と出力を確認できます。
nvidia_pokedex.png

Modelを作成して実験を容易にする

多くの要素がある場合、実験の整理は困難です。Modelクラスを使用することで、システムプロンプトや使用しているモデルなど、アプリの実験的な詳細をキャプチャして整理できます。これにより、アプリのさまざまな反復を整理して比較するのに役立ちます。コードのバージョン管理と入出力のキャプチャに加えて、Modelはアプリケーションの動作を制御する構造化されたパラメータをキャプチャし、どのパラメータが最適に機能したかを簡単に見つけることができます。また、Weave Modelsをserve、およびEvaluationと一緒に使用することもできます。以下の例では、modelsystem_messageを試すことができます。これらのいずれかを変更するたびに、新しいversionGrammarCorrectorModelが得られます。
import weave
from langchain_nvidia_ai_endpoints import ChatNVIDIA

weave.init('grammar-nvidia')

class GrammarCorrectorModel(weave.Model): # Change to `weave.Model`
  system_message: str

  @weave.op()
  def predict(self, user_input): # Change to `predict`
    client = ChatNVIDIA(model="mistralai/mixtral-8x7b-instruct-v0.1", temperature=0, max_tokens=100, top_p=1)

    messages=[
          {
              "role": "system",
              "content": self.system_message
          },
          {
              "role": "user",
              "content": user_input
          }
          ]

    response = client.invoke(messages)
    return response.content

corrector = GrammarCorrectorModel(
    system_message = "You are a grammar checker, correct the following user input.")
result = corrector.predict("That was so easy, it was a piece of pie!")
print(result)
chatnvidia_model.png

使用情報

ChatNVIDIA統合はinvokestreamおよびそれらの非同期バリアントをサポートしています。また、ツールの使用もサポートしています。 ChatNVIDIAは多くのタイプのモデルで使用することを目的としているため、関数呼び出しのサポートはありません。