跳到主要内容
LangSmith 与 Instructor 提供了便捷的集成,这是一个流行的开源库,用于生成带有 LLM 的结构化输出。 要使用它,您首先需要设置您的 LangSmith API 密钥。
export LANGSMITH_API_KEY=<your-api-key>
# For LangSmith API keys linked to multiple workspaces, set the LANGSMITH_WORKSPACE_ID environment variable to specify which workspace to use.
export LANGSMITH_WORKSPACE_ID=<your-workspace-id>
接下来,您需要安装 LangSmith SDK。
pip install -U langsmith
使用 langsmith.wrappers.wrap_openai 封装您的 OpenAI 客户端。
from openai import OpenAI
from langsmith import wrappers

client = wrappers.wrap_openai(OpenAI())
之后,您可以使用 instructor 修补已封装的 OpenAI 客户端。
import instructor

client = instructor.patch(client)
现在,您可以像往常一样使用 instructor,但所有内容都将记录到 LangSmith!
from pydantic import BaseModel


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


user = client.chat.completions.create(
    model="gpt-4o-mini",
    response_model=UserDetail,
    messages=[
        {"role": "user", "content": "Extract Jason is 25 years old"},
    ]
)
通常,您会在其他函数内部使用 instructor。您可以通过使用此封装客户端并使用 @traceable 装饰器装饰这些函数来获取嵌套追踪。有关如何使用 @traceable 装饰器注释代码以进行追踪的更多信息,请参阅本指南
# You can customize the run name with the `name` keyword argument
@traceable(name="Extract User Details")
def my_function(text: str) -> UserDetail:
    return client.chat.completions.create(
        model="gpt-4o-mini",
        response_model=UserDetail,
        messages=[
            {"role": "user", "content": f"Extract {text}"},
        ]
    )

my_function("Jason is 25 years old")

以编程方式连接这些文档到 Claude、VSCode 等,通过 MCP 获取实时答案。
© . This site is unofficial and not affiliated with LangChain, Inc.