> ## Documentation Index
> Fetch the complete documentation index at: https://wb-21fd5541-feature-automate-reference-docs-generation.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Instructor

# Instructor

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

[Instructor](https://python.useinstructor.com/) は、LLMからJSONなどの構造化データを簡単に取得できる軽量ライブラリです。

## トレーシング

開発中および本番環境の両方で、言語モデルアプリケーションのトレースを中央の場所に保存することが重要です。これらのトレースはデバッグに役立ち、アプリケーションの改善に役立つデータセットとしても機能します。

Weaveは[Instructor](https://python.useinstructor.com/)のトレースを自動的にキャプチャします。追跡を開始するには、`weave.init(project_name="<YOUR-WANDB-PROJECT-NAME>")` を呼び出し、通常通りライブラリを使用します。

```python
import instructor
import weave
from pydantic import BaseModel
from openai import OpenAI


# Define your desired output structure
class UserInfo(BaseModel):
    user_name: str
    age: int

# Initialize Weave
weave.init(project_name="instructor-test")

# Patch the OpenAI client
client = instructor.from_openai(OpenAI())

# Extract structured data from natural language
user_info = client.chat.completions.create(
    model="gpt-3.5-turbo",
    response_model=UserInfo,
    messages=[{"role": "user", "content": "John Doe is 30 years old."}],
)
```

| ![](https://mintlify.s3.us-west-1.amazonaws.com/wb-21fd5541-feature-automate-reference-docs-generation/ja/guides/integrations/imgs/instructor/instructor_lm_trace.gif) |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| WeaveはInstructorを使用して行われたすべてのLLM呼び出しを追跡し、記録します。Weaveウェブインターフェースでトレースを表示できます。                                                                                           |

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

関数を`@weave.op` でラップすると、入力、出力、およびアプリケーションロジックのキャプチャが開始され、データがアプリケーションをどのように流れるかをデバッグできます。オペレーションを深くネストし、追跡したい関数のツリーを構築できます。これにより、実験時にコードの自動バージョン管理も開始され、gitにコミットされていないアドホックな詳細がキャプチャされます。

単に[`@weave.op`](/ja/guides/tracking/ops)でデコレートされた関数を作成します。

以下の例では、`extract_person` 関数は`@weave.op`でラップされたメトリック関数です。これにより、OpenAIチャット完了呼び出しなどの中間ステップを確認できます。

```python
import instructor
import weave
from openai import OpenAI
from pydantic import BaseModel


# Define your desired output structure
class Person(BaseModel):
    person_name: str
    age: int


# Initialize Weave
weave.init(project_name="instructor-test")

# Patch the OpenAI client
lm_client = instructor.from_openai(OpenAI())


# Extract structured data from natural language
@weave.op()
def extract_person(text: str) -> Person:
    return lm_client.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=[
            {"role": "user", "content": text},
        ],
        response_model=Person,
    )


person = extract_person("My name is John and I am 20 years old")
```

| ![](https://mintlify.s3.us-west-1.amazonaws.com/wb-21fd5541-feature-automate-reference-docs-generation/ja/guides/integrations/imgs/instructor/instructor_op_trace.png) |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `extract_person` 関数を`@weave.op` でデコレートすると、その入力、出力、および関数内で行われるすべての内部LM呼び出しがトレースされます。Weaveはまた、Instructorによって生成された構造化オブジェクトを自動的に追跡し、バージョン管理します。                           |

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

多くの要素が動いている場合、実験の整理は困難です。[`Model`](../core-types/models) クラスを使用することで、システムプロンプトや使用しているモデルなど、アプリの実験的な詳細をキャプチャして整理できます。これにより、アプリのさまざまな反復を整理して比較するのに役立ちます。

コードのバージョン管理と入出力のキャプチャに加えて、[`Model`](../core-types/models) はアプリケーションの動作を制御する構造化パラメータをキャプチャし、どのパラメータが最適に機能したかを簡単に見つけることができます。Weave Modelsを`serve` （以下を参照）、および[`Evaluation`](../core-types/evaluations.mdx) と一緒に使用することもできます。

以下の例では、`PersonExtractor` で実験できます。これらのいずれかを変更するたびに、新しい*version* の`PersonExtractor`が得られます。

```python
import asyncio
from typing import List, Iterable

import instructor
import weave
from openai import AsyncOpenAI
from pydantic import BaseModel


# Define your desired output structure
class Person(BaseModel):
    person_name: str
    age: int


# Initialize Weave
weave.init(project_name="instructor-test")

# Patch the OpenAI client
lm_client = instructor.from_openai(AsyncOpenAI())


class PersonExtractor(weave.Model):
    openai_model: str
    max_retries: int

    @weave.op()
    async def predict(self, text: str) -> List[Person]:
        model = await lm_client.chat.completions.create(
            model=self.openai_model,
            response_model=Iterable[Person],
            max_retries=self.max_retries,
            stream=True,
            messages=[
                {
                    "role": "system",
                    "content": "You are a perfect entity extraction system",
                },
                {
                    "role": "user",
                    "content": f"Extract `{text}`",
                },
            ],
        )
        return [m async for m in model]


model = PersonExtractor(openai_model="gpt-4", max_retries=2)
asyncio.run(model.predict("John is 30 years old"))
```

| ![](https://mintlify.s3.us-west-1.amazonaws.com/wb-21fd5541-feature-automate-reference-docs-generation/ja/guides/integrations/imgs/instructor/instructor_weave_model.png) |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| を使用した呼び出しのトレースとバージョン管理[`Model`](../core-types/models)                                                                                                                     |

## Weave Modelの提供

weaveリファレンスである`weave.Model` オブジェクトを使用して、fastapiサーバーをスピンアップして[`serve`](https://wandb.github.io/weave/guides/tools/serve) することができます。

| [![](https://mintlify.s3.us-west-1.amazonaws.com/wb-21fd5541-feature-automate-reference-docs-generation/ja/guides/integrations/imgs/instructor/instructor_serve.png)](https://wandb.ai/geekyrakshit/instructor-test/weave/objects/PersonExtractor/versions/xXpMsJvaiTOjKafz1TnHC8wMgH5ZAAwYOaBMvHuLArI) |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 任意の`weave.Model` のweaveリファレンスは、モデルに移動してUIからコピーすることで見つけることができます。                                                                                                                                                                                                                                         |

ターミナルで次のコマンドを使用してモデルを提供できます：

```shell
weave serve weave:///your_entity/project-name/YourModel:<hash>
```
