构建LangChain应用程序的示例代码:9、使用Anthropic API生成结构化输出的工具教程

使用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
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Hugo_Hoo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值