> ## Documentation Index
> Fetch the complete documentation index at: https://docs.coreweave.com/llms.txt
> Use this file to discover all available pages before exploring further.

# OpenAI

> OpenAI を Weave と統合して、トレース、評価、モニタリングを行います

<a target="_blank" href="https://colab.research.google.com/github/wandb/examples/blob/master/weave/docs/quickstart_openai.ipynb" aria-label="Google Colab で開く">
  <img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab" />
</a>

このガイドでは、OpenAI の Python および TypeScript ライブラリを Weave と統合し、LLM アプリケーションのトレース、評価、監視を行う方法を説明します。対象は、すでに OpenAI の SDK を使用しており、開発時や本番環境での Call を可視化したい開発者です。

<Note>
  [LLM プレイグラウンド](/ja/products/wandb/weave/guides/tools/playground)を使用すると、セットアップ不要で Weave 上の OpenAI モデルを試せます。
</Note>

<h2 id="tracing">
  トレース
</h2>

LLM アプリケーションのトレースを一元的なデータベースに保存しておくと、開発時にも本番環境でも役立ちます。トレースはデバッグに使用できるほか、アプリケーションの改善時に評価に使う、難しい事例を集めたデータセットの構築にも役立ちます。

Weave は [`openai` Python ライブラリ](https://developers.openai.com/api/docs/libraries)のトレースを自動的に取得できます。

取得を開始するには、任意のプロジェクト名を指定して `weave.init("[PROJECT_NAME]")` を呼び出します。Weave は OpenAI をインポートするタイミングにかかわらず自動的にパッチを適用するため、以降の OpenAI の Call はすべてトレースされます。

`weave.init()` の呼び出し時に CoreWeave Forge のチームを指定しない場合、Weave はデフォルトの entity を使用します。デフォルトの entity を確認または変更するには、Weights & Biases Models ドキュメントの [User Settings](/ja/products/wandb/platform/app/settings-page/user-settings#default-team) を参照してください。

<h3 id="automatic-patching">
  自動パッチ適用
</h3>

Weave は、OpenAI を `weave.init()` の前後どちらでインポートしても、自動的に OpenAI にパッチを適用します。次の例は、Call のトレースを開始するために必要な最小限のセットアップです。

<CodeGroup>
  ```python Python lines {4} theme={"system"}
  from openai import OpenAI
  import weave

  weave.init('emoji-bot')  # OpenAI に自動的にパッチが適用されます！

  client = OpenAI()
  response = client.chat.completions.create(
    model="gpt-4",
    messages=[
      {
        "role": "system",
        "content": "You are AGI. You will be provided with a message, and your task is to respond using emojis only."
      },
      {
        "role": "user",
        "content": "How are you?"
      }
    ]
  )
  ```

  ```typescript twoslash TypeScript theme={"system"}
  // @noErrors
  import { OpenAI } from 'openai';
  import { wrapOpenAI } from '@wandb/weave';

  const openai = wrapOpenAI(new OpenAI());

  // これで OpenAI へのすべての Call がトレースされます
  openai.chat.completions.create(
    {
      model: "gpt-4",
      messages: [
        {
          role: "system",
          content: "You are AGI. You will be provided with a message, and your task is to respond using emojis only."
        },
        {
          role: "user",
          content: "How are you?"
        }
      ]
    }
  );
  ```
</CodeGroup>

<h3 id="optional-explicit-patching">
  オプション: 明示的なパッチ適用
</h3>

パッチを適用するタイミングを細かく制御したい場合は、自動の動作に任せず、OpenAI に明示的にパッチを適用します。

```python lines {3,4} theme={"system"}
import weave

weave.init('emoji-bot')
weave.integrations.patch_openai()  # OpenAI のトレースを有効にします

from openai import OpenAI
client = OpenAI()
response = client.chat.completions.create(
  model="gpt-4",
  messages=[
    {"role": "user", "content": "Make me a emoji"}
  ]
)
```

[ライブトレースを表示する](https://forge.coreweave.com/wandb/capecape/emoji-bot/weave/calls/01928a78-6d8a-7e20-9b8c-0cbc8318a0c8)

<Tip>
  Weave は、[OpenAI Functions](https://platform.openai.com/docs/guides/function-calling) と [OpenAI Assistants](https://platform.openai.com/docs/assistants/overview) の関数呼び出しツールも取得します。
</Tip>

<h2 id="structured-outputs">
  Structured outputs
</h2>

Weave は OpenAI の structured outputs のトレースをサポートしています。structured outputs は、LLM の応答を特定の形式に確実に従わせたい場合に便利です。次の例では、ユーザーメッセージから型付きの `UserDetail` オブジェクトを抽出する Call をトレースします。

<CodeGroup>
  ```python Python theme={"system"}
  from openai import OpenAI
  from pydantic import BaseModel
  import weave

  class UserDetail(BaseModel):
      name: str
      age: int

  client = OpenAI()
  weave.init('extract-user-details')

  completion = client.beta.chat.completions.parse(
      model="gpt-4o-2024-08-06",
      messages=[
          {"role": "system", "content": "Extract the user details from the message."},
          {"role": "user", "content": "My name is David and I am 30 years old."},
      ],
      response_format=UserDetail,
  )

  user_detail = completion.choices[0].message.parsed
  print(user_detail)
  ```
</CodeGroup>

<h2 id="async-support">
  Async のサポート
</h2>

Weave は非同期の OpenAI Call のトレースをサポートしています。そのため、`AsyncOpenAI` を使用するアプリケーションでも、同期アプリケーションと同様の可観測性が得られます。

<CodeGroup>
  ```python Python theme={"system"}
  from openai import AsyncOpenAI
  import weave

  client = AsyncOpenAI()
  weave.init('async-emoji-bot')

  async def call_openai():
      response = await client.chat.completions.create(
          model="gpt-4",
          messages=[
              {
                  "role": "system", 
                  "content": "You are AGI. You will be provided with a message, and your task is to respond using emojis only."
              },
              {
                  "role": "user",
                  "content": "How are you?"
              }
          ]
      )
      return response

  # 非同期関数を呼び出す
  result = await call_openai()
  ```
</CodeGroup>

<h2 id="streaming-support">
  ストリーミングのサポート
</h2>

Weave は、OpenAI からのストリーミング応答のトレースをサポートしています。取得されたトレースにはストリーミングされた完了内容の全体が反映されるため、最終的な出力をリクエストパラメーターと並べて確認できます。

<CodeGroup>
  ```python Python theme={"system"}
  from openai import OpenAI
  import weave

  client = OpenAI()
  weave.init('streaming-emoji-bot')

  response = client.chat.completions.create(
      model="gpt-4",
      messages=[
          {
              "role": "system", 
              "content": "You are AGI. You will be provided with a message, and your task is to respond using emojis only."
          },
          {
              "role": "user",
              "content": "How are you?"
          }
      ],
      stream=True
  )

  for chunk in response:
      print(chunk.choices[0].delta.content or "", end="")
  ```
</CodeGroup>

<h2 id="tracing-function-calls">
  関数の Call のトレース
</h2>

ツールを使用すると、OpenAI による関数の Call が Weave によってトレースされます。これにより、モデルが各ツールをどのように呼び出し、どのような引数を渡したかを把握できます。

<CodeGroup>
  ```python Python theme={"system"}
  from openai import OpenAI
  import weave

  client = OpenAI()
  weave.init('function-calling-bot')

  tools = [
      {
          "type": "function",
          "function": {
              "name": "get_weather",
              "description": "Get the weather in a given location",
              "parameters": {
                  "type": "object",
                  "properties": {
                      "location": {
                          "type": "string",
                          "description": "The location to get the weather for"
                      },
                      "unit": {
                          "type": "string",
                          "enum": ["celsius", "fahrenheit"],
                          "description": "The unit to return the temperature in"
                      }
                  },
                  "required": ["location"]
              }
          }
      }
  ]

  response = client.chat.completions.create(
      model="gpt-4",
      messages=[
          {
              "role": "user",
              "content": "What's the weather like in New York?"
          }
      ],
      tools=tools
  )

  print(response.choices[0].message.tool_calls)
  ```
</CodeGroup>

<h2 id="batch-api">
  Batch API
</h2>

Weave は OpenAI Batch API をサポートしています。Batch API を使用すると複数のリクエストを非同期で処理でき、その場合も Weave は各リクエストをトレースに取得します。

<CodeGroup>
  ```python Python theme={"system"}
  from openai import OpenAI
  import weave

  client = OpenAI()
  weave.init('batch-processing')

  # バッチファイルを作成する
  batch_input = [
      {
          "custom_id": "request-1",
          "method": "POST",
          "url": "/v1/chat/completions",
          "body": {
              "model": "gpt-4",
              "messages": [{"role": "user", "content": "Hello, how are you?"}]
          }
      },
      {
          "custom_id": "request-2", 
          "method": "POST",
          "url": "/v1/chat/completions",
          "body": {
              "model": "gpt-4",
              "messages": [{"role": "user", "content": "What's the weather like?"}]
          }
      }
  ]

  # バッチを送信する
  batch = client.batches.create(
      input_file_id="your-file-id",
      endpoint="/v1/chat/completions",
      completion_window="24h"
  )

  # バッチの結果を取得する
  completed_batch = client.batches.retrieve(batch.id)
  ```
</CodeGroup>

<h2 id="assistants-api">
  Assistants API
</h2>

Weave は OpenAI Assistants API をサポートしているため、アシスタント、スレッド、run を中心に構築した対話型 AI アプリケーションをトレースできます。

<CodeGroup>
  ```python Python theme={"system"}
  from openai import OpenAI
  import weave

  client = OpenAI()
  weave.init('assistant-bot')

  # アシスタントを作成する
  assistant = client.beta.assistants.create(
      name="Math Assistant",
      instructions="You are a personal math tutor. Answer questions about math.",
      model="gpt-4"
  )

  # スレッドを作成する
  thread = client.beta.threads.create()

  # スレッドにメッセージを追加する
  message = client.beta.threads.messages.create(
      thread_id=thread.id,
      role="user",
      content="What is 2+2?"
  )

  # アシスタントを実行する
  run = client.beta.threads.runs.create(
      thread_id=thread.id,
      assistant_id=assistant.id
  )

  # アシスタントの応答を取得する
  messages = client.beta.threads.messages.list(thread_id=thread.id)
  ```
</CodeGroup>

<h2 id="cost-tracking">
  コストのトラッキング
</h2>

Weave は OpenAI API の呼び出しにかかるコストを自動的にトラッキングするため、パフォーマンスとあわせて支出を監視できます。コストの内訳は Weights & Biases の UI で確認できます。

<Note>
  コストのトラッキングはすべての OpenAI モデルで利用できます。Weave は OpenAI が公開している料金に基づいてコストを算出します。
</Note>

<h2 id="tracing-custom-functions">
  カスタム関数のトレース
</h2>

OpenAI の Call を独自のアプリケーションロジック単位でまとめるには、OpenAI を使用するカスタム関数に `@weave.op` デコレーターを適用してトレースします。これにより、その関数の親トレースが生成され、内部で実行される OpenAI の Call がその中にネストされます。

<CodeGroup>
  ```python Python theme={"system"}
  from openai import OpenAI
  import weave

  client = OpenAI()
  weave.init('custom-function-bot')

  @weave.op
  def generate_response(prompt: str) -> str:
      response = client.chat.completions.create(
          model="gpt-4",
          messages=[
              {
                  "role": "user",
                  "content": prompt
              }
          ]
      )
      return response.choices[0].message.content

  # この関数呼び出しはトレースされます
  result = generate_response("Hello, how are you?")
  ```
</CodeGroup>

<h2 id="next-steps">
  次のステップ
</h2>

OpenAI のトレースを設定したので、アプリケーションの Call を Weave で確認できるようになりました。次に、以下のことを行えます。

* **Weights & Biases UI でトレースを表示する**: Weave プロジェクトに移動して、OpenAI の Call のトレースを確認します。
* **評価を作成する**: トレースを使用して評価用のデータセットを構築します。
* **パフォーマンスを監視する**: レイテンシー、コスト、その他のメトリクスをトラッキングします。
* **問題をデバッグする**: トレースを使用して、LLM アプリケーション内で何が起きているかを把握します。

これらのトピックの詳細については、[評価ガイド](/ja/products/wandb/weave/guides/evaluation/scorers)および[モニタリングガイド](../tracking)を参照してください。
