主题
追踪 Instructor 应用
LangSmith 提供了与 Instructor 的便捷集成,这是一个流行的开源库,用于通过 LLM 生成结构化输出。
要使用它,首先需要设置你的 LangSmith API key。
shell
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:
bash
pip install -U langsmithbash
uv add langsmith使用 langsmith.wrappers.wrap_openai 包装你的 OpenAI 客户端
python
from openai import OpenAI
from langsmith import wrappers
client = wrappers.wrap_openai(OpenAI())之后,你可以使用 instructor 对包装后的 OpenAI 客户端进行 patch:
python
import instructor
client = instructor.patch(client)现在,你可以像往常一样使用 instructor,但所有内容都会记录到 LangSmith!
python
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 装饰器为代码添加追踪标注的更多信息,请参阅自定义埋点。
python
# 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-5.4-mini",
response_model=UserDetail,
messages=[
{"role": "user", "content": f"Extract {text}"},
]
)
my_function("Jason is 25 years old")