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

本文主要是介绍构建LangChain应用程序的示例代码:9、使用Anthropic API生成结构化输出的工具教程,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

使用Anthropic API生成结构化输出的工具

Anthropic API最近增加了工具使用功能。

这对于生成结构化输出非常有用。

! pip install -U langchain-anthropic

可选配置:

import osos.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 prints the string 'hello world' and tell me how it works in a sentence"
)

初始推理阶段:

code_output["raw"].content[0]

工具调用:

code_output["raw"].content[1]

JSON字符串:

code_output["raw"].content[1]["input"]

错误:

error = code_output["parsing_error"]
error

结果:

parsed_result = code_output["parsed"]

Python:

parsed_result.prefix

Python:

parsed_result.imports

Python:

parsed_result.code

更具挑战性的例子:

动机例子,用于工具使用/结构化输出。
在这里插入图片描述

这里是我们想要回答有关代码问题的一些文档。

from bs4 import BeautifulSoup as Soup
from langchain_community.document_loaders.recursive_url_loader import RecursiveUrlLoaderLCEL文档url = "https://python.langchain.com/docs/expression_language/"
loader = RecursiveUrlLoader(url=url, max_depth=20, extractor=lambda x: Soup(x, "html.parser").text
)
docs = loader.load()根据URL对列表进行排序并获取文本d_sorted = sorted(docs, key=lambda x: x.metadata["source"])
d_reversed = list(reversed(d_sorted))
concatenated_content = "\n\n\n --- \n\n\n".join([doc.page_content for doc in d_reversed]
)

问题:

如果我们想强制使用工具怎么办?

我们可以使用回退策略。

让我们选择一个代码生成提示,根据我的一些测试,它没有正确调用工具。

我们看看是否可以纠正这个问题。

# 此代码生成提示调用工具使用
code_gen_prompt_working = ChatPromptTemplate.from_messages([("system",""" You are a coding assistant with expertise in LCEL, LangChain expression language.
Here is the LCEL documentation:-------
{context}-------
Answer the user question based on the
above provided documentation. Ensure any code you provide can be executed with all required imports and variables
defined. Structure your answer: 1) a prefix describing the code solution, 2) the imports, 3) the functioning code block.
Invoke the code tool to structure the output correctly.Here is the user question:""",),("placeholder", "{messages}"),]
)# 此代码生成提示没有调用工具使用
code_gen_prompt_bad = ChatPromptTemplate.from_messages([("system","""You are a coding assistant with expertise in LCEL, LangChain expression language.
Here is a full set of LCEL documentation:-------
{context}-------
Answer the user question based on the above provided documentation. Ensure any code you provide can be executed
with all required imports and variables defined. Structure your answer with a description of the code solution.Then list the imports. And finally list the functioning code block. Here is the user question:""",),("placeholder", "{messages}"),]
)

数据模型:

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)

检查错误:

def check_claude_output(tool_output):"""检查解析错误或未能调用工具"""

带有输出检查的链:

code_chain = code_gen_prompt_bad | structured_llm | check_claude_output

让我们添加检查并重试。

def insert_errors(inputs):"""在消息中插入错误"""

这将作为回退链运行。

fallback_chain = insert_errors | code_chain
N = 3  # 最大重试次数
code_chain_re_try = code_chain.with_fallbacks(fallbacks=[fallback_chain] * N, exception_key="error"
)

测试:

messages = [("user", "How do I build a RAG chain in LCEL?")]
code_output_lcel = code_chain_re_try.invoke({"context": concatenated_content, "messages": messages}
)

Python:

parsed_result_lcel = code_output_lcel["parsed"]

Python:

parsed_result_lcel.prefix

Python:

parsed_result_lcel.imports

Python:

parsed_result_lcel.code

示例跟踪捕获错误并纠正:

跟踪链接


介绍了如何使用Anthropic API来生成结构化输出。它首先建议安装langchain-anthropic库,然后通过设置环境变量启用追踪和API密钥。文件中展示了如何定义数据模型,创建ChatAnthropic实例,并使用with_structured_output方法来生成符合特定模式的结构化输出。接着,通过示例代码演示了如何调用API、处理原始输出、捕获解析错误,并展示了如何通过回退机制和错误检查来增强工具调用的鲁棒性。最后,提供了一个测试用例,展示了如何使用构建的链来回答问题并获取结构化代码输出。

这篇关于构建LangChain应用程序的示例代码:9、使用Anthropic API生成结构化输出的工具教程的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1029950

相关文章

Java中流式并行操作parallelStream的原理和使用方法

《Java中流式并行操作parallelStream的原理和使用方法》本文详细介绍了Java中的并行流(parallelStream)的原理、正确使用方法以及在实际业务中的应用案例,并指出在使用并行流... 目录Java中流式并行操作parallelStream0. 问题的产生1. 什么是parallelS

Linux join命令的使用及说明

《Linuxjoin命令的使用及说明》`join`命令用于在Linux中按字段将两个文件进行连接,类似于SQL的JOIN,它需要两个文件按用于匹配的字段排序,并且第一个文件的换行符必须是LF,`jo... 目录一. 基本语法二. 数据准备三. 指定文件的连接key四.-a输出指定文件的所有行五.-o指定输出

Linux jq命令的使用解读

《Linuxjq命令的使用解读》jq是一个强大的命令行工具,用于处理JSON数据,它可以用来查看、过滤、修改、格式化JSON数据,通过使用各种选项和过滤器,可以实现复杂的JSON处理任务... 目录一. 简介二. 选项2.1.2.2-c2.3-r2.4-R三. 字段提取3.1 普通字段3.2 数组字段四.

Linux kill正在执行的后台任务 kill进程组使用详解

《Linuxkill正在执行的后台任务kill进程组使用详解》文章介绍了两个脚本的功能和区别,以及执行这些脚本时遇到的进程管理问题,通过查看进程树、使用`kill`命令和`lsof`命令,分析了子... 目录零. 用到的命令一. 待执行的脚本二. 执行含子进程的脚本,并kill2.1 进程查看2.2 遇到的

详解SpringBoot+Ehcache使用示例

《详解SpringBoot+Ehcache使用示例》本文介绍了SpringBoot中配置Ehcache、自定义get/set方式,并实际使用缓存的过程,文中通过示例代码介绍的非常详细,对大家的学习或者... 目录摘要概念内存与磁盘持久化存储:配置灵活性:编码示例引入依赖:配置ehcache.XML文件:配置

Java 虚拟线程的创建与使用深度解析

《Java虚拟线程的创建与使用深度解析》虚拟线程是Java19中以预览特性形式引入,Java21起正式发布的轻量级线程,本文给大家介绍Java虚拟线程的创建与使用,感兴趣的朋友一起看看吧... 目录一、虚拟线程简介1.1 什么是虚拟线程?1.2 为什么需要虚拟线程?二、虚拟线程与平台线程对比代码对比示例:三

k8s按需创建PV和使用PVC详解

《k8s按需创建PV和使用PVC详解》Kubernetes中,PV和PVC用于管理持久存储,StorageClass实现动态PV分配,PVC声明存储需求并绑定PV,通过kubectl验证状态,注意回收... 目录1.按需创建 PV(使用 StorageClass)创建 StorageClass2.创建 PV

Redis 基本数据类型和使用详解

《Redis基本数据类型和使用详解》String是Redis最基本的数据类型,一个键对应一个值,它的功能十分强大,可以存储字符串、整数、浮点数等多种数据格式,本文给大家介绍Redis基本数据类型和... 目录一、Redis 入门介绍二、Redis 的五大基本数据类型2.1 String 类型2.2 Hash

Redis中Hash从使用过程到原理说明

《Redis中Hash从使用过程到原理说明》RedisHash结构用于存储字段-值对,适合对象数据,支持HSET、HGET等命令,采用ziplist或hashtable编码,通过渐进式rehash优化... 目录一、开篇:Hash就像超市的货架二、Hash的基本使用1. 常用命令示例2. Java操作示例三

Linux创建服务使用systemctl管理详解

《Linux创建服务使用systemctl管理详解》文章指导在Linux中创建systemd服务,设置文件权限为所有者读写、其他只读,重新加载配置,启动服务并检查状态,确保服务正常运行,关键步骤包括权... 目录创建服务 /usr/lib/systemd/system/设置服务文件权限:所有者读写js,其他