使用Anthropic API生成结构化输出的工具
Anthropic API最近增加了工具使用功能。
这对于生成结构化输出非常有用。
! pip install -U langchain-anthropic
可选配置:
import os
os.environ['LANGCHAIN_TRACING_V2'] = 'true' # 启用追踪
os.environ['LANGCHAIN_API_KEY'] = # 设置你的API密钥
我们如何使用工具来产生结构化输出?
函数调用/工具使用仅生成有效载荷。
有效载荷通常是JSON字符串,可以传递给API,或者在本例中,传递给解析器以产生结构化输出。
LangChain提供了llm.with_structured_output(schema)
,使得生成符合模式的结构化输出变得非常容易。
from langchain_anthropic import ChatAnthropic
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.pydantic_v1 import BaseModel, Field
# 数据模型
class Code(BaseModel):
"""代码输出"""
# LLM
llm = ChatAnthropic(
model="claude-3-opus-20240229",
default_headers={
"anthropic-beta": "tools-2024-04-04"},
)
# 结构化输出,包括原始内容将捕获原始输出和解析器错误
structured_llm = llm.with_structured_output(Code, include_raw=True)
code_output = structured_llm.invoke(
"Write a python program that print