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

# プロンプトオブジェクトを作成する

> LLM アプリケーション向けのプロンプトオブジェクトを作成、公開、使用する

プロンプトの作成、評価、改良は、AI エンジニアにとって中核となる作業です。
プロンプトの小さな変更が、アプリケーションの挙動に大きな影響を与えることがあります。
W\&B Weave を使うと、プロンプトを作成して公開し、継続的に改善していくことができます。

このページは、Weave で再利用可能なプロンプトオブジェクトを作成し、アプリケーションコードから参照できるように公開したい AI エンジニア向けです。このガイドに従うことで、単一文字列のプロンプトやマルチターンのプロンプトを作成し、実行時の値でパラメーター化して、Weave プロジェクトに公開する方法を学べます。公開済みプロンプトの参照、取得、バージョン管理については、[プロンプトのバージョンの保存と追跡](/ja/weave/guides/core-types/prompts-version.mdx) を参照してください。

プロンプトの要件がシンプルな場合は、組み込みの `weave.StringPrompt` または `weave.MessagesPrompt` クラスを使用できます。より複雑な要件がある場合は、それらのクラス、または基底クラス `weave.Prompt` をサブクラス化し、`format` method をオーバーライドできます。

`weave.publish` でプロンプトを公開すると、Weave プロジェクトの [Prompts ページ](/ja/weave/guides/core-types/prompts-version.mdx#view-prompts) に表示され、あなたや共同作業者が参照して再利用できます。

<div id="stringprompt">
  ## StringPrompt
</div>

`StringPrompt` は、システムメッセージ、ユーザーのクエリ、または LLM への単独のテキスト入力として使用できる単一文字列のプロンプトをログします。複数メッセージの会話のような複雑さが不要な個別のプロンプト文字列を管理するには、`StringPrompt` を使用してください。

<Tabs>
  <Tab title="Python">
    ```python lines {4,5,15} theme={null}
    import weave
    weave.init('intro-example')

    system_prompt = weave.StringPrompt("You speak like a pirate")
    weave.publish(system_prompt, name="pirate_prompt")

    from openai import OpenAI
    client = OpenAI()

    response = client.chat.completions.create(
      model="gpt-4o",
      messages=[
        {
          "role": "system",
          "content": system_prompt.format()
        },
        {
          "role": "user",
          "content": "Explain general relativity in one paragraph."
        }
      ],
    )
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript twoslash lines theme={null}
    // @noErrors
    import * as weave from 'weave';
    import OpenAI from 'openai';

    async function main() {
      // weave.init はクライアントインスタンスを返します
      const weaveClient = await weave.init('wandb/prompt-examples');

      const systemPrompt = new weave.StringPrompt({
        content: 'You speak like a pirate',
        name: 'your-prompt',
        description: 'A helpful description of your prompt',
      });
      
      // init から返されたクライアントを使用します
      await weaveClient.publish(systemPrompt, 'pirate_prompt');

      // OpenAI クライアントをラップして Weave で Call をトラッキングします
      const client = weave.wrapOpenAI(new OpenAI());

      const response = await client.chat.completions.create({
        model: "gpt-4o",
        messages: [
          {
            role: "system",
            content: systemPrompt.content
          },
          {
            role: "user",
            content: "Explain general relativity in one paragraph."
          }
        ],
      });
    }

    main();
    ```
  </Tab>
</Tabs>

<div id="messagesprompt">
  ## MessagesPrompt
</div>

`MessagesPrompt` を使うと、マルチターンの会話やチャットベースのプロンプトをログできます。これは、会話全体の流れを表すメッセージオブジェクトの配列 (`system`、`user`、`assistant` などのロールを含む) を保存します。複数のメッセージにまたがってコンテキストを維持する必要があるチャットベースの LLM、特定の会話パターンを定義したい場合、または再利用可能な会話テンプレートを作成したい場合は、`MessagesPrompt` を使用してください。

<Tabs>
  <Tab title="Python">
    ```python lines {4,21} theme={null}
    import weave
    weave.init('intro-example')

    prompt = weave.MessagesPrompt([
        {
            "role": "system",
            "content": "You are a stegosaurus, but don't be too obvious about it."
        },
        {
            "role": "user",
            "content": "What's good to eat around here?"
        }
    ])
    weave.publish(prompt, name="dino_prompt")

    from openai import OpenAI
    client = OpenAI()

    response = client.chat.completions.create(
      model="gpt-4o",
      messages=prompt.format(),
    )
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript twoslash lines theme={null}
    // @noErrors
    import * as weave from 'weave';
    import OpenAI from 'openai';

    async function main() {
      // weave.init はクライアント インスタンスを返します
      const weaveClient = await weave.init('wandb/prompt-examples');

      const prompt = new weave.MessagesPrompt({
        messages: [
          {
            "role": "system",
            "content": "You are a stegosaurus, but don't be too obvious about it."
          },
          {
            "role": "user",
            "content": "What's good to eat around here?"
          }
        ],
      });
      
      // init から返されたクライアントを使用します
      await weaveClient.publish(prompt, 'dino_prompt');

      // OpenAI クライアントをラップして Weave で Call をトラッキングします
      const client = weave.wrapOpenAI(new OpenAI());

      const response = await client.chat.completions.create({
        model: "gpt-4o",
        messages: prompt.messages,
      });
    }

    main();
    ```
  </Tab>
</Tabs>

<div id="parameterize-prompts">
  ## プロンプトをパラメーター化する
</div>

静的なプロンプトを作成できるようになったら、次のステップは、それらをさまざまな入力に対して再利用できるようにすることです。`StringPrompt` と `MessagesPrompt` はどちらも、パラメーター化によって動的なコンテンツをサポートしています。これにより、プレースホルダー (`{variable}` 構文を使用) を含む再利用可能なプロンプトテンプレートを作成し、実行時に異なる値を埋め込めます。パラメーター化は、一貫した構造を保ちながら、プロンプトをさまざまな入力、ユーザーデータ、またはコンテキストに応じて変える必要がある場合に便利です。`format()` メソッドは、これらのプレースホルダーを実際の値に置き換えるためのキーと値のペアを受け入れます。

<Tabs>
  <Tab title="Python">
    ```python lines {4,15} theme={null}
    import weave
    weave.init('intro-example')

    prompt = weave.StringPrompt("Solve the equation {equation}")
    weave.publish(prompt, name="calculator_prompt")

    from openai import OpenAI
    client = OpenAI()

    response = client.chat.completions.create(
      model="gpt-4o",
      messages=[
        {
          "role": "user",
          "content": prompt.format(equation="1 + 1 = ?")
        }
      ],
    )
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript twoslash lines {8,23} theme={null}
    // @noErrors
    import * as weave from 'weave';
    import OpenAI from 'openai';

    async function main() {
      // weave.init はクライアントインスタンスを返します
      const weaveClient = await weave.init('wandb/prompt-examples');

      const prompt = new weave.StringPrompt({
        content: 'Solve the equation {equation}',
      });
      
      // init から返されたクライアントを使用します
      await weaveClient.publish(prompt, 'calculator_prompt');

      // Weave で Call をトラッキングするために OpenAI クライアントをラップします
      const client = weave.wrapOpenAI(new OpenAI());

      const response = await client.chat.completions.create({
        model: "gpt-4o",
        messages: [
          {
            role: "user",
            content: prompt.format({ equation: "1 + 1 = ?" })
          }
        ],
      });
    }

    main();
    ```
  </Tab>
</Tabs>

同じパラメーター化のパターンは、マルチターン会話内でプレースホルダーが必要な場合にも `MessagesPrompt` で使用できます。

<Tabs>
  <Tab title="Python">
    ```python lines {4,21} theme={null}
    import weave
    weave.init('intro-example')

    prompt = weave.MessagesPrompt([
    {
        "role": "system",
        "content": "You will be provided with a description of a scene and your task is to provide a single word that best describes an associated emotion."
    },
    {
        "role": "user",
        "content": "{scene}"
    }
    ])
    weave.publish(prompt, name="emotion_prompt")

    from openai import OpenAI
    client = OpenAI()

    response = client.chat.completions.create(
      model="gpt-4o",
      messages=prompt.format(scene="A dog is lying on a dock next to a fisherman."),
    )
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript twoslash lines {8,29} theme={null}
    // @noErrors
    import * as weave from 'weave';
    import OpenAI from 'openai';

    async function main() {
      // weave.init はクライアントインスタンスを返します
      const weaveClient = await weave.init('wandb/prompt-examples');

      const prompt = new weave.MessagesPrompt({
        messages: [
          {
            "role": "system",
            "content": "You will be provided with a description of a scene and your task is to provide a single word that best describes an associated emotion."
          },
          {
            "role": "user",
            "content": "{scene}"
          }
        ]
      });
      
      // init から返されたクライアントを使用します
      await weaveClient.publish(prompt, 'emotion_prompt');

      // Weave で Call をトラッキングするために OpenAI クライアントをラップします
      const client = weave.wrapOpenAI(new OpenAI());

      const response = await client.chat.completions.create({
        model: "gpt-4o",
        messages: prompt.format({ scene: "A dog is lying on a dock next to a fisherman." }),
      });
    }

    main();
    ```
  </Tab>
</Tabs>
