> ## 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.

# Instructor

> Weave의 Instructor 인테그레이션으로 LLM의 구조화된 데이터 추출을 트레이스하고, Pydantic 검증과 재시도 로직을 포착합니다.

<a target="_blank" href="https://colab.research.google.com/github/wandb/examples/blob/master/weave/docs/quickstart_instructor.ipynb" aria-label="Google Colab에서 열기">
  <img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Colab에서 열기" />
</a>

[Instructor](https://python.useinstructor.com/)는 LLM에서 JSON과 같은 구조화된 데이터를 쉽게 얻을 수 있게 해주는 경량 라이브러리입니다. 이 가이드에서는 Weave로 Instructor 호출을 트레이스하여 구조화된 추출을 디버그하고, Pydantic 검증을 캡처하고, 재시도 로직을 검사하는 방법을 보여줍니다.

<div id="tracing">
  ## 트레이싱
</div>

개발 중이든 프로덕션이든, 언어 모델 애플리케이션의 트레이스를 한곳에 중앙 집중식으로 저장하는 것이 중요합니다. 이러한 트레이스는 디버깅에 유용할 뿐 아니라, 애플리케이션 개선에 도움이 되는 데이터셋으로도 활용할 수 있습니다.

Weave는 [Instructor](https://python.useinstructor.com/)의 트레이스를 자동으로 캡처합니다. 추적을 시작하려면 `weave.init(project_name="[YOUR-WANDB-PROJECT-NAME]")`를 호출한 다음, 평소처럼 라이브러리를 사용하세요.

```python lines theme={null}
import instructor
import weave
from pydantic import BaseModel
from openai import OpenAI


# 원하는 출력 구조 정의
class UserInfo(BaseModel):
    user_name: str
    age: int

# Weave 초기화
weave.init(project_name="instructor-test")

# OpenAI 클라이언트 패치
client = instructor.from_openai(OpenAI())

# 자연어에서 구조화된 데이터 추출
user_info = client.chat.completions.create(
    model="gpt-3.5-turbo",
    response_model=UserInfo,
    messages=[{"role": "user", "content": "John Doe is 30 years old."}],
)
```

| <img src="https://mintcdn.com/wb-21fd5541/S0cRiDzxeODX77LU/weave/guides/integrations/imgs/instructor/instructor_lm_trace.gif?s=d827147d688205eeafb140b59c2df5b2" alt="구조화된 출력 추출 워크플로가 포함된 Weave의 Instructor LM 트레이스" width="2880" height="1512" data-path="weave/guides/integrations/imgs/instructor/instructor_lm_trace.gif" /> |
| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Weave는 Instructor를 사용해 이루어지는 모든 LLM Call을 추적하고 로깅합니다. Weave 웹 인터페이스에서 해당 트레이스를 확인할 수 있습니다.                                                                                                                                                                                                                                                                                                                     |

<div id="track-your-own-ops">
  ## 직접 만든 ops 추적하기
</div>

함수를 `@weave.op`로 감싸면 입력, 출력, 앱 로직 캡처가 시작되어 앱에서 데이터가 어떻게 흐르는지 디버그할 수 있습니다. ops를 깊게 중첩해 추적하려는 함수들의 트리를 구성할 수 있습니다. 또한 실험하는 동안 코드 버전 관리도 자동으로 시작되어 Git에 커밋되지 않은 임시 세부 정보까지 캡처합니다.

[`@weave.op`](/ko/weave/guides/tracking/ops)으로 데코레이트된 함수를 만드세요.

다음 예시에서 `extract_person` 함수는 `@weave.op`로 감싼 metric 함수입니다. 이를 통해 OpenAI chat completion call과 같은 중간 step를 확인할 수 있습니다.

```python lines theme={null}
import instructor
import weave
from openai import OpenAI
from pydantic import BaseModel


# 원하는 출력 구조 정의
class Person(BaseModel):
    person_name: str
    age: int


# Weave 초기화
weave.init(project_name="instructor-test")

# OpenAI 클라이언트 패치
lm_client = instructor.from_openai(OpenAI())


# 자연어에서 구조화된 데이터 추출
@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")
```

| <img src="https://mintcdn.com/wb-21fd5541/S0cRiDzxeODX77LU/weave/guides/integrations/imgs/instructor/instructor_op_trace.png?fit=max&auto=format&n=S0cRiDzxeODX77LU&q=85&s=09552c82f59e6d2276702950a8beef37" alt="구조화된 객체, 함수 입력, 출력, 그리고 Pydantic 모델 검증이 포함된 Instructor op 트레이스" width="2880" height="1514" data-path="weave/guides/integrations/imgs/instructor/instructor_op_trace.png" /> |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `extract_person` 함수에 `@weave.op` 데코레이터를 적용하면 함수의 입력, 출력와 함수 내부에서 발생하는 모든 LM Call이 트레이스됩니다. Weave는 또한 Instructor가 생성한 구조화된 객체를 자동으로 추적하고 버전 관리합니다.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |

<div id="create-a-model-for-easier-experimentation">
  ## `Model`로 더 쉽게 실험하기
</div>

구성 요소가 많아질수록 실험을 체계적으로 정리하기가 어렵습니다. [`Model`](../core-types/models) 클래스를 사용하면 system 프롬프트나 사용 중인 모델처럼 앱 실험의 세부 사항을 캡처하고 정리할 수 있습니다. 이렇게 하면 앱의 여러 반복 버전을 더 쉽게 정리하고 비교할 수 있습니다.

코드를 버전 관리하고 입력과 출력을 캡처하는 것에 더해, [`Model`](../core-types/models)은 애플리케이션의 동작을 제어하는 구조화된 파라미터도 캡처하므로 어떤 파라미터가 가장 잘 작동했는지 찾을 수 있습니다. 또한 Weave Models를 [`서빙`](#serve-a-weave-model) 및 [`평가`](../core-types/evaluations)와 함께 사용할 수도 있습니다.

다음 예시에서는 `PersonExtractor`를 실험해 볼 수 있습니다. 이 항목들 중 하나를 변경할 때마다 `PersonExtractor`의 새 *version*이 생성됩니다.

```python lines theme={null}
import asyncio
from typing import List, Iterable

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


# 원하는 출력 구조 정의
class Person(BaseModel):
    person_name: str
    age: int


# Weave 초기화
weave.init(project_name="instructor-test")

# OpenAI 클라이언트 패치
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"))
```

| <img src="https://mintcdn.com/wb-21fd5541/S0cRiDzxeODX77LU/weave/guides/integrations/imgs/instructor/instructor_weave_model.png?fit=max&auto=format&n=S0cRiDzxeODX77LU&q=85&s=3a0ef6045c7dc9796cb7cd04cc713cd7" alt="모델 버전과 트레이스 이력이 표시된 Instructor Weave Model 트레이싱 및 버전 관리 인터페이스" width="1490" height="1422" data-path="weave/guides/integrations/imgs/instructor/instructor_weave_model.png" /> |
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`Model`](../core-types/models)을 사용해 Call 트레이싱 및 버전 관리                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |

<div id="serve-a-weave-model">
  ## Weave Model 서빙하기
</div>

`weave.Model`을 저장한 후에는 이를 FastAPI 엔드포인트로 서빙하여 노트북 외부에서 테스트하거나 다른 애플리케이션과 통합할 수 있습니다. `weave.Model` 객체를 가리키는 weave 레퍼런스가 있으면 FastAPI 서버를 실행하고 [`서빙`](https://docs.wandb.ai/weave/guides/tools/serve)할 수 있습니다.

| [<img src="https://mintcdn.com/wb-21fd5541/S0cRiDzxeODX77LU/weave/guides/integrations/imgs/instructor/instructor_serve.png?fit=max&auto=format&n=S0cRiDzxeODX77LU&q=85&s=d41e3c4dea4f295e1a581c44a3b68167" alt="FastAPI 서버 설정 및 모델 서빙 옵션이 포함된 Instructor 서빙 인터페이스" width="2880" height="1514" data-path="weave/guides/integrations/imgs/instructor/instructor_serve.png" />](https://wandb.ai/geekyrakshit/instructor-test/weave/objects/PersonExtractor/versions/xXpMsJvaiTOjKafz1TnHC8wMgH5ZAAwYOaBMvHuLArI) |
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 모델로 이동한 뒤 UI에서 복사하면 모든 `weave.Model`의 weave 레퍼런스를 찾을 수 있습니다.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |

모델을 서빙하려면 터미널에서 다음 명령어를 실행하세요:

```bash theme={null}
weave serve weave://your_entity/project-name/YourModel:[HASH]
```
