> ## Documentation Index
> Fetch the complete documentation index at: https://cndoc-langchain.site/llms.txt
> Use this file to discover all available pages before exploring further.

# 追踪 Instructor 应用

LangSmith 提供了与 [Instructor](https://python.useinstructor.com/) 的便捷集成，这是一个流行的开源库，用于通过 LLM 生成结构化输出。

要使用此功能，您首先需要设置您的 LangSmith API 密钥。

```shell theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
export LANGSMITH_API_KEY=<your-api-key>
# 对于链接到多个工作区的 LangSmith API 密钥，请设置 LANGSMITH_WORKSPACE_ID 环境变量以指定要使用的工作区。
export LANGSMITH_WORKSPACE_ID=<your-workspace-id>
```

接下来，您需要安装 LangSmith SDK：

<CodeGroup>
  ```bash pip theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  pip install -U langsmith
  ```

  ```bash uv theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  uv add langsmith
  ```
</CodeGroup>

使用 `langsmith.wrappers.wrap_openai` 包装您的 OpenAI 客户端。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from openai import OpenAI
from langsmith import wrappers

client = wrappers.wrap_openai(OpenAI())
```

之后，您可以使用 `instructor` 来修补包装后的 OpenAI 客户端：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import instructor

client = instructor.patch(client)
```

现在，您可以像往常一样使用 `instructor`，但现在所有内容都会被记录到 LangSmith 中！

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from pydantic import BaseModel


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


user = client.chat.completions.create(
    model="gpt-5.4-mini",
    response_model=UserDetail,
    messages=[
        {"role": "user", "content": "Extract Jason is 25 years old"},
    ]
)
```

通常，您会在其他函数内部使用 `instructor`。
您可以通过使用这个包装后的客户端并用 `@traceable` 装饰这些函数来获取嵌套的追踪。
有关如何使用 `@traceable` 装饰器为追踪注解代码的更多信息，请参阅[自定义检测](/langsmith/annotate-code)。

```python {highlight={2}} theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
# 您可以使用 `name` 关键字参数自定义运行名称
@traceable(name="Extract User Details")
def my_function(text: str) -> UserDetail:
    return client.chat.completions.create(
        model="gpt-5.4-mini",
        response_model=UserDetail,
        messages=[
            {"role": "user", "content": f"Extract {text}"},
        ]
    )

my_function("Jason is 25 years old")
```

***

<div className="source-links">
  <Callout icon="terminal-2">
    [将这些文档](/use-these-docs)通过 MCP 连接到 Claude、VSCode 等，以获取实时答案。
  </Callout>

  <Callout icon="edit">
    [在 GitHub 上编辑此页面](https://github.com/langchain-ai/docs/edit/main/src/langsmith/trace-with-instructor.mdx) 或 [提交问题](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
