构建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常用命令提示符使用方法详解

《Python常用命令提示符使用方法详解》在学习python的过程中,我们需要用到命令提示符(CMD)进行环境的配置,:本文主要介绍Python常用命令提示符使用方法的相关资料,文中通过代码介绍的... 目录一、python环境基础命令【Windows】1、检查Python是否安装2、 查看Python的安

OpenCV实现实时颜色检测的示例

《OpenCV实现实时颜色检测的示例》本文主要介绍了OpenCV实现实时颜色检测的示例,通过HSV色彩空间转换和色调范围判断实现红黄绿蓝颜色检测,包含视频捕捉、区域标记、颜色分析等功能,具有一定的参考... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间

Python并行处理实战之如何使用ProcessPoolExecutor加速计算

《Python并行处理实战之如何使用ProcessPoolExecutor加速计算》Python提供了多种并行处理的方式,其中concurrent.futures模块的ProcessPoolExecu... 目录简介完整代码示例代码解释1. 导入必要的模块2. 定义处理函数3. 主函数4. 生成数字列表5.

Python中help()和dir()函数的使用

《Python中help()和dir()函数的使用》我们经常需要查看某个对象(如模块、类、函数等)的属性和方法,Python提供了两个内置函数help()和dir(),它们可以帮助我们快速了解代... 目录1. 引言2. help() 函数2.1 作用2.2 使用方法2.3 示例(1) 查看内置函数的帮助(

Linux脚本(shell)的使用方式

《Linux脚本(shell)的使用方式》:本文主要介绍Linux脚本(shell)的使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录概述语法详解数学运算表达式Shell变量变量分类环境变量Shell内部变量自定义变量:定义、赋值自定义变量:引用、修改、删

Python实例题之pygame开发打飞机游戏实例代码

《Python实例题之pygame开发打飞机游戏实例代码》对于python的学习者,能够写出一个飞机大战的程序代码,是不是感觉到非常的开心,:本文主要介绍Python实例题之pygame开发打飞机... 目录题目pygame-aircraft-game使用 Pygame 开发的打飞机游戏脚本代码解释初始化部

基于Python实现一个Windows Tree命令工具

《基于Python实现一个WindowsTree命令工具》今天想要在Windows平台的CMD命令终端窗口中使用像Linux下的tree命令,打印一下目录结构层级树,然而还真有tree命令,但是发现... 目录引言实现代码使用说明可用选项示例用法功能特点添加到环境变量方法一:创建批处理文件并添加到PATH1

Java使用HttpClient实现图片下载与本地保存功能

《Java使用HttpClient实现图片下载与本地保存功能》在当今数字化时代,网络资源的获取与处理已成为软件开发中的常见需求,其中,图片作为网络上最常见的资源之一,其下载与保存功能在许多应用场景中都... 目录引言一、Apache HttpClient简介二、技术栈与环境准备三、实现图片下载与保存功能1.

Python中使用uv创建环境及原理举例详解

《Python中使用uv创建环境及原理举例详解》uv是Astral团队开发的高性能Python工具,整合包管理、虚拟环境、Python版本控制等功能,:本文主要介绍Python中使用uv创建环境及... 目录一、uv工具简介核心特点:二、安装uv1. 通过pip安装2. 通过脚本安装验证安装:配置镜像源(可

C++ 函数 strftime 和时间格式示例详解

《C++函数strftime和时间格式示例详解》strftime是C/C++标准库中用于格式化日期和时间的函数,定义在ctime头文件中,它将tm结构体中的时间信息转换为指定格式的字符串,是处理... 目录C++ 函数 strftipythonme 详解一、函数原型二、功能描述三、格式字符串说明四、返回值五