使用Anthropic Claude工具提取结构化JSON数据的技术实践

使用Anthropic Claude工具提取结构化JSON数据的技术实践

anthropic-cookbook A collection of notebooks/recipes showcasing some fun and effective ways of using Claude. anthropic-cookbook 项目地址: https://gitcode.com/gh_mirrors/an/anthropic-cookbook

概述

在现代自然语言处理应用中,将非结构化文本转换为结构化数据是一项关键任务。Anthropic的Claude模型通过其工具使用功能,提供了一种高效的方式来实现这一转换。本文将详细介绍如何利用Claude模型从各种文本输入中提取结构化JSON数据。

环境准备

在开始之前,我们需要设置开发环境:

%pip install anthropic requests beautifulsoup4

from anthropic import Anthropic
import requests
from bs4 import BeautifulSoup
import json

client = Anthropic()
MODEL_NAME = "claude-3-haiku-20240307"

这些依赖项包括Anthropic的Python客户端库、用于HTTP请求的requests库,以及用于HTML解析的BeautifulSoup库。

文章摘要提取

应用场景

文章摘要提取功能特别适用于内容聚合平台、新闻分析系统或研究辅助工具,能够快速获取文章的核心信息。

实现方法

我们定义一个print_summary工具,指定输出JSON的结构:

tools = [
    {
        "name": "print_summary",
        "description": "Prints a summary of the article.",
        "input_schema": {
            "type": "object",
            "properties": {
                "author": {"type": "string", "description": "Name of the article author"},
                "topics": {
                    "type": "array",
                    "items": {"type": "string"},
                    "description": 'Array of topics, e.g. ["tech", "current affairs"]. Should be as specific as possible, and can overlap.'
                },
                "summary": {"type": "string", "description": "Summary of the article. One or two paragraphs max."},
                "coherence": {"type": "integer", "description": "Coherence of the article's key points, 0-100 (inclusive)"},
                "persuasion": {"type": "number", "description": "Article's persuasion score, 0.0-1.0 (inclusive)"}
            },
            "required": ['author', 'topics', 'summary', 'coherence', 'persuasion', 'counterpoint']
        }
    }
]

技术要点

  1. 结构化输出设计:明确指定了作者、主题、摘要等字段及其数据类型
  2. 评分系统:包含连贯性和说服力评分,为内容分析提供量化指标
  3. 必填字段:通过required属性确保关键信息不会被遗漏

命名实体识别

应用场景

命名实体识别在信息提取、知识图谱构建、智能搜索等领域有广泛应用。

实现方法

tools = [
    {
        "name": "print_entities",
        "description": "Prints extract named entities.",
        "input_schema": {
            "type": "object",
            "properties": {
                "entities": {
                    "type": "array",
                    "items": {
                        "type": "object",
                        "properties": {
                            "name": {"type": "string", "description": "The extracted entity name."},
                            "type": {"type": "string", "description": "The entity type (e.g., PERSON, ORGANIZATION, LOCATION)."},
                            "context": {"type": "string", "description": "The context in which the entity appears in the text."}
                        },
                        "required": ["name", "type", "context"]
                    }
                }
            },
            "required": ["entities"]
        }
    }
]

技术要点

  1. 实体类型分类:支持人物、组织、地点等多种实体类型
  2. 上下文保留:记录实体出现的原始上下文,便于后续分析
  3. 数组结构:使用数组存储多个实体,适应文本中可能出现的多个实体

情感分析

应用场景

情感分析广泛应用于客户反馈分析、社交媒体监控、市场研究等领域。

实现方法

tools = [
    {
        "name": "print_sentiment_scores",
        "description": "Prints the sentiment scores of a given text.",
        "input_schema": {
            "type": "object",
            "properties": {
                "positive_score": {"type": "number", "description": "The positive sentiment score, ranging from 0.0 to 1.0."},
                "negative_score": {"type": "number", "description": "The negative sentiment score, ranging from 0.0 to 1.0."},
                "neutral_score": {"type": "number", "description": "The neutral sentiment score, ranging from 0.0 to 1.0."}
            },
            "required": ["positive_score", "negative_score", "neutral_score"]
        }
    }
]

技术要点

  1. 多维度评分:提供正面、负面和中性三个维度的情感评分
  2. 归一化数值:使用0-1范围的标准化分数,便于比较和分析
  3. 精确数值:采用浮点数而非整数,提高评分精度

文本分类

应用场景

文本分类在内容管理、信息过滤、主题建模等场景中非常有用。

实现方法

tools = [
    {
        "name": "print_classification",
        "description": "Prints the classification results.",
        "input_schema": {
            "type": "object",
            "properties": {
                "categories": {
                    "type": "array",
                    "items": {
                        "type": "object",
                        "properties": {
                            "name": {"type": "string", "description": "The category name."},
                            "score": {"type": "number", "description": "The classification score for the category, ranging from 0.0 to 1.0."}
                        },
                        "required": ["name", "score"]
                    }
                }
            },
            "required": ["categories"]
        }
    }
]

技术要点

  1. 多标签分类:支持一个文本属于多个类别的情况
  2. 置信度评分:为每个分类结果提供置信度分数
  3. 灵活扩展:可以轻松添加或修改分类类别

处理未知键名的JSON结构

应用场景

当需要提取的字段不固定或无法预先确定时,这种灵活的结构特别有用。

实现方法

tools = [
    {
        "name": "print_all_characteristics",
        "description": "Prints all characteristics which are provided.",
        "input_schema": {
            "type": "object",
            "additionalProperties": True
        }
    }
]

技术要点

  1. 动态属性:使用additionalProperties允许任意键值对
  2. 灵活提取:适用于描述性文本中特征提取的场景
  3. 提示工程:通过详细的提示语指导模型如何填充这些属性

最佳实践建议

  1. 模式设计:精心设计JSON Schema,确保它包含所有必要字段和适当的数据类型约束
  2. 错误处理:总是检查工具调用的响应,处理可能出现的缺失数据情况
  3. 性能考虑:对于大批量处理,考虑实现批处理机制
  4. 结果验证:建立验证机制确保提取的数据质量
  5. 提示优化:通过实验找到最有效的提示语,提高提取准确性

总结

通过Anthropic Claude的工具使用功能,开发者可以高效地从非结构化文本中提取结构化数据。本文介绍的五种模式涵盖了从文章摘要到特征提取的多种场景,展示了Claude在自然语言处理任务中的强大能力。合理设计JSON Schema和提示语是关键,开发者可以根据具体需求调整和扩展这些示例。

anthropic-cookbook A collection of notebooks/recipes showcasing some fun and effective ways of using Claude. anthropic-cookbook 项目地址: https://gitcode.com/gh_mirrors/an/anthropic-cookbook

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

### AWS中的Claude服务概述 Amazon Web Services (AWS) 提供了一系列强大的机器学习工具和服务,其中包括对第三方大型语言模型的支持。尽管AWS本身并未开发名为“Claude”的模型,但它通过 **Bedrock** 平台集成了由 Anthropic 开发的 Claude 系列模型[^1]。 #### 使用AWS Bedrock访问Claude模型 AWS Bedrock 是一项完全托管的服务,允许开发者轻松构建、定制和部署基础模型(Foundation Models, FM),而无需管理底层基础设施。通过该平台,用户可以无缝集成来自多个供应商的基础模型,例如 AnthropicClaude 和其他知名提供商的产品[^1]。 以下是关于如何在AWS环境中使用Claude的具体指导: 1. #### 创建IAM角色 需要创建具有适当权限的身份与访问管理(IAM)角色来授权应用程序调用Bedrock API。此过程涉及授予必要的策略以便于执行生成文本或其他操作所需的命令。 2. #### 初始化SDK客户端 利用Boto3库初始化一个针对`bedrock-runtime`端点的新客户端实例。这是实现程序化交互的第一步。 ```python import boto3 bedrock_runtime = boto3.client( service_name='bedrock-runtime', region_name='us-west-2' # 替换为您所在区域 ) ``` 3. #### 调用模型完成任务 接下来可以通过向指定URL发送JSON格式请求的方式调用选定版本的Claude模型。下面展示了一个简单的例子,演示怎样让模型响应一段问候消息。 ```python body = { "prompt": "\n\nHuman: Hello! How are you today?\n\nAssistant:", "max_tokens_to_sample": 60, "temperature": 0.5, "top_p": 0.9 } response = bedrock_runtime.invoke_model( body=json.dumps(body), modelId="anthropics.claude-v2", # 更改为实际使用的具体型号ID accept="application/json", contentType="application/json" ) result = json.loads(response['body'].read().decode()) print(result.get('completion')) ``` 4. #### 处理返回的数据结构 成功接收到来自服务器的消息之后,解析其中嵌套层次较深的结果字段即可获得最终答案字符串形式表示的内容。 以上步骤概括了整个工作流的关键环节,当然还有更多高级特性等待探索实践,比如调整参数设置以适应不同应用场景需求等。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

娄朋虎Imogene

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

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

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

打赏作者

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

抵扣说明:

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

余额充值