构建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

相关文章

python使用try函数详解

《python使用try函数详解》Pythontry语句用于异常处理,支持捕获特定/多种异常、else/final子句确保资源释放,结合with语句自动清理,可自定义异常及嵌套结构,灵活应对错误场景... 目录try 函数的基本语法捕获特定异常捕获多个异常使用 else 子句使用 finally 子句捕获所

SpringBoot监控API请求耗时的6中解决解决方案

《SpringBoot监控API请求耗时的6中解决解决方案》本文介绍SpringBoot中记录API请求耗时的6种方案,包括手动埋点、AOP切面、拦截器、Filter、事件监听、Micrometer+... 目录1. 简介2.实战案例2.1 手动记录2.2 自定义AOP记录2.3 拦截器技术2.4 使用Fi

C++11右值引用与Lambda表达式的使用

《C++11右值引用与Lambda表达式的使用》C++11引入右值引用,实现移动语义提升性能,支持资源转移与完美转发;同时引入Lambda表达式,简化匿名函数定义,通过捕获列表和参数列表灵活处理变量... 目录C++11新特性右值引用和移动语义左值 / 右值常见的左值和右值移动语义移动构造函数移动复制运算符

Python对接支付宝支付之使用AliPay实现的详细操作指南

《Python对接支付宝支付之使用AliPay实现的详细操作指南》支付宝没有提供PythonSDK,但是强大的github就有提供python-alipay-sdk,封装里很多复杂操作,使用这个我们就... 目录一、引言二、准备工作2.1 支付宝开放平台入驻与应用创建2.2 密钥生成与配置2.3 安装ali

C#中lock关键字的使用小结

《C#中lock关键字的使用小结》在C#中,lock关键字用于确保当一个线程位于给定实例的代码块中时,其他线程无法访问同一实例的该代码块,下面就来介绍一下lock关键字的使用... 目录使用方式工作原理注意事项示例代码为什么不能lock值类型在C#中,lock关键字用于确保当一个线程位于给定实例的代码块中时

SQL Server 中的 WITH (NOLOCK) 示例详解

《SQLServer中的WITH(NOLOCK)示例详解》SQLServer中的WITH(NOLOCK)是一种表提示,等同于READUNCOMMITTED隔离级别,允许查询在不获取共享锁的情... 目录SQL Server 中的 WITH (NOLOCK) 详解一、WITH (NOLOCK) 的本质二、工作

MySQL 强制使用特定索引的操作

《MySQL强制使用特定索引的操作》MySQL可通过FORCEINDEX、USEINDEX等语法强制查询使用特定索引,但优化器可能不采纳,需结合EXPLAIN分析执行计划,避免性能下降,注意版本差异... 目录1. 使用FORCE INDEX语法2. 使用USE INDEX语法3. 使用IGNORE IND

C# $字符串插值的使用

《C#$字符串插值的使用》本文介绍了C#中的字符串插值功能,详细介绍了使用$符号的实现方式,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习吧... 目录$ 字符使用方式创建内插字符串包含不同的数据类型控制内插表达式的格式控制内插表达式的对齐方式内插表达式中使用转义序列内插表达式中使用

flask库中sessions.py的使用小结

《flask库中sessions.py的使用小结》在Flask中Session是一种用于在不同请求之间存储用户数据的机制,Session默认是基于客户端Cookie的,但数据会经过加密签名,防止篡改,... 目录1. Flask Session 的基本使用(1) 启用 Session(2) 存储和读取 Se

Java Thread中join方法使用举例详解

《JavaThread中join方法使用举例详解》JavaThread中join()方法主要是让调用改方法的thread完成run方法里面的东西后,在执行join()方法后面的代码,这篇文章主要介绍... 目录前言1.join()方法的定义和作用2.join()方法的三个重载版本3.join()方法的工作原