Claude与工具调用:结构化JSON数据提取实战

摘要

本文系统介绍如何利用Claude大模型的工具调用能力,实现高效、灵活的结构化JSON数据提取。通过五大典型实战案例,帮助中国AI开发者掌握从文本到结构化数据的全流程,提升AI应用开发效率。


目录

  1. 结构化数据提取的意义与应用场景
  2. Claude工具调用机制简介
  3. 五大实战案例详解
    1. 文章摘要结构化
    2. 命名实体识别(NER)
    3. 情感分析
    4. 文本分类
    5. 开放属性抽取
  4. 整体流程图与架构图
  5. 注意事项与最佳实践
  6. 常见问题与扩展阅读
  7. 总结与参考资料

结构化数据提取的意义与应用场景

  • 数据驱动AI:结构化JSON数据是AI自动化、知识管理、数据分析的基础。
  • 典型场景:舆情监测、智能客服、自动摘要、知识图谱、信息抽取、数据标注等。
  • Claude优势:支持复杂文本理解与结构化输出,极大简化开发流程。

Claude工具调用机制简介

Claude支持通过自定义工具(Tool Use)实现结构化数据输出。开发者可定义输入输出Schema,Claude根据Schema自动生成JSON结果。

  • 核心流程
    1. 定义工具及输入Schema
    2. 构造Prompt引导Claude调用工具
    3. 获取结构化JSON结果

五大实战案例详解

1. 文章摘要结构化

场景:自动提取文章作者、主题、摘要、条理性、说服力等结构化信息。

# 安装依赖
# %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"

# 定义工具Schema
tools = [
    {
        "name": "print_summary",
        "description": "Prints a summary of the article.",
        "input_schema": {
            "type": "object",
            "properties": {
                "author": {"type": "string", "description": "文章作者"},
                "topics": {"type": "array", "items": {"type": "string"}, "description": "主题列表"},
                "summary": {"type": "string", "description": "摘要"},
                "coherence": {"type": "integer", "description": "条理性评分,0-100"},
                "persuasion": {"type": "number", "description": "说服力评分,0.0-1.0"},
                "counterpoint": {"type": "string", "description": "反方观点"}
            },
            "required": ['author', 'topics', 'summary', 'coherence', 'persuasion', 'counterpoint']
        }
    }
]

# 获取文章内容
url = "https://www.anthropic.com/news/third-party-testing"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
article = " ".join([p.text for p in soup.find_all("p")])

query = f"""
<article>
{article}
</article>

Use the `print_summary` tool.
"""

response = client.messages.create(
    model=MODEL_NAME,
    max_tokens=4096,
    tools=tools,
    messages=[{"role": "user", "content": query}]
)
json_summary = None
for content in response.content:
    if content.type == "tool_use" and content.name == "print_summary":
        json_summary = content.input
        break

if json_summary:
    print("JSON Summary:")
    print(json.dumps(json_summary, indent=2, ensure_ascii=False))
else:
    print("未提取到结构化摘要。")

2. 命名实体识别(NER)

场景:自动识别文本中的人名、机构、地点等实体,并结构化输出。

# 定义工具Schema
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": "实体名称"},
                            "type": {"type": "string", "description": "实体类型(如PERSON, ORGANIZATION, LOCATION)"},
                            "context": {"type": "string", "description": "实体出现上下文"}
                        },
                        "required": ["name", "type", "context"]
                    }
                }
            },
            "required": ["entities"]
        }
    }
]

text = "John works at Google in New York. He met with Sarah, the CEO of Acme Inc., last week in San Francisco."

query = f"""
<document>
{text}
</document>

Use the print_entities tool.
"""

response = client.messages.create(
    model=MODEL_NAME,
    max_tokens=4096,
    tools=tools,
    messages=[{"role": "user", "content": query}]
)

json_entities = None
for content in response.content:
    if content.type == "tool_use" and content.name == "print_entities":
        json_entities = content.input
        break

if json_entities:
    print("Extracted Entities (JSON):")
    print(json.dumps(json_entities, indent=2, ensure_ascii=False))
else:
    print("未提取到实体信息。")

3. 情感分析

场景:自动分析文本情感倾向,输出正面、负面、中性分数。

# 定义工具Schema
tools = [
    {
        "name": "print_sentiment_scores",
        "description": "Prints the sentiment scores of a given text.",
        "input_schema": {
            "type": "object",
            "properties": {
                "positive_score": {"type": "number", "description": "正面分数,0.0-1.0"},
                "negative_score": {"type": "number", "description": "负面分数,0.0-1.0"},
                "neutral_score": {"type": "number", "description": "中性分数,0.0-1.0"}
            },
            "required": ["positive_score", "negative_score", "neutral_score"]
        }
    }
]

text = "The product was okay, but the customer service was terrible. I probably won't buy from them again."

query = f"""
<text>
{text}
</text>

Use the print_sentiment_scores tool.
"""

response = client.messages.create(
    model=MODEL_NAME,
    max_tokens=4096,
    tools=tools,
    messages=[{"role": "user", "content": query}]
)

json_sentiment = None
for content in response.content:
    if content.type == "tool_use" and content.name == "print_sentiment_scores":
        json_sentiment = content.input
        break

if json_sentiment:
    print("Sentiment Analysis (JSON):")
    print(json.dumps(json_sentiment, indent=2, ensure_ascii=False))
else:
    print("未提取到情感分析结果。")

4. 文本分类

场景:将文本自动归类到多个预设类别,并输出置信分数。

# 定义工具Schema
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": "类别名称"},
                            "score": {"type": "number", "description": "置信分数,0.0-1.0"}
                        },
                        "required": ["name", "score"]
                    }
                }
            },
            "required": ["categories"]
        }
    }
]

text = "The new quantum computing breakthrough could revolutionize the tech industry."

query = f"""
<document>
{text}
</document>

Use the print_classification tool. The categories can be Politics, Sports, Technology, Entertainment, Business.
"""

response = client.messages.create(
    model=MODEL_NAME,
    max_tokens=4096,
    tools=tools,
    messages=[{"role": "user", "content": query}]
)

json_classification = None
for content in response.content:
    if content.type == "tool_use" and content.name == "print_classification":
        json_classification = content.input
        break

if json_classification:
    print("Text Classification (JSON):")
    print(json.dumps(json_classification, indent=2, ensure_ascii=False))
else:
    print("未提取到分类结果。")

5. 开放属性抽取

场景:针对描述性文本,自动抽取所有可识别属性,支持开放Schema。

# 定义开放Schema工具
tools = [
    {
        "name": "print_all_characteristics",
        "description": "Prints all characteristics which are provided.",
        "input_schema": {
            "type": "object",
            "additionalProperties": True
        }
    }
]

query = f"""Given a description of a character, your task is to extract all the characteristics of the character and print them using the print_all_characteristics tool.

The print_all_characteristics tool takes an arbitrary number of inputs where the key is the characteristic name and the value is the characteristic value (age: 28 or eye_color: green).

<description>
The man is tall, with a beard and a scar on his left cheek. He has a deep voice and wears a black leather jacket.
</description>

Now use the print_all_characteristics tool."""

response = client.messages.create(
    model=MODEL_NAME,
    max_tokens=4096,
    tools=tools,
    tool_choice={"type": "tool", "name": "print_all_characteristics"},
    messages=[{"role": "user", "content": query}]
)

tool_output = None
for content in response.content:
    if content.type == "tool_use" and content.name == "print_all_characteristics":
        tool_output = content.input
        break

if tool_output:
    print("Characteristics (JSON):")
    print(json.dumps(tool_output, indent=2, ensure_ascii=False))
else:
    print("未提取到属性信息。")

整体流程图与架构图

原始文本输入
定义工具Schema
构造Prompt
Claude调用工具
输出结构化JSON
下游AI/数据系统

图1:Claude结构化JSON提取流程图


注意事项与最佳实践

  • Schema设计要详细:字段描述越清晰,Claude输出越准确。
  • 异常处理:需判断返回内容类型,防止解析失败。
  • Token限制:长文本需分段处理,避免超限。
  • 开放Schema需加强Prompt约束
  • 调试建议:多用print输出中间结果,便于排查问题。

常见问题与扩展阅读

常见问题:

  • Claude未返回结构化内容?检查Prompt和Schema定义。
  • 字段缺失或类型不符?优化Schema和示例。
  • 超长文本报错?分段处理或调整max_tokens。

扩展阅读:


总结与参考资料

本文详细介绍了Claude结合工具调用实现结构化JSON数据提取的全流程与实战案例。建议开发者结合自身业务场景,灵活设计Schema与Prompt,持续优化提取效果。

参考资料:

<think>好的,我现在需要帮助用户了解如何使用深度求索(DeepSeek)等AI工具通过API完成工作任务。首先,我需要明确用户的需求。他们可能是一个开发者或者项目经理,想要将AI集成到现有的工作流程中,以提高效率或者自动化某些任务。用户可能对API的使用有一定了解,但具体如何操作还不清楚,特别是如何结合AI工具。 接下来,我需要考虑用户可能关心的几个方面。首先是API的基本使用流程,包括如何获取API密钥,如何调用接口。然后是具体的应用场景,比如数据分析、文档处理、代码生成等,用户可能希望看到实际例子。此外,错误处理和安全性也是需要考虑的因素,用户可能担心API调用的稳定性和数据隐私问题。 用户可能没有提到的深层需求包括如何选择合适的AI工具,不同工具之间的比较,以及如何将API集成到现有的系统中。例如,他们可能想知道如何处理API返回的数据,如何优化请求频率,或者如何评估不同AI模型的性能。 我需要组织回答的结构,先介绍通用流程,再举几个具体例子,比如数据分析、文档处理、代码生成,每个例子给出步骤和代码示例。然后讨论注意事项,比如错误处理、安全性和成本控制。最后可以比较不同工具的特点,帮助用户选择适合的解决方案。 在准备回答时,需要确保技术细节的准确性,比如API端点的URL、请求头的设置、参数的正确使用。同时,语言要简洁明了,避免使用过于专业的术语,让不同技术背景的用户都能理解。可能需要提醒用户替换示例中的API密钥,避免泄露敏感信息。 另外,用户可能对免费资源和测试方法感兴趣,可以推荐一些提供免费层级的AI服务,比如OpenAI、DeepSeek的免费试用,或者Hugging Face的模型库。同时,演示如何通过Postman或curl测试API调用,帮助用户快速上手。 最后,需要总结使用AI工具API的优势,比如提升效率、自动化任务,以及需要注意的潜在问题,如数据隐私和模型偏差。这样用户能全面了解如何有效利用AI工具API来完成工作任务。</think>以下是使用DeepSeek等AI工具通过API提升工作效率的完整指南,包含具体场景、技术实现和最佳实践: --- ### 一、API调用基础流程 ```python # 通用请求模板 import requests API_KEY = "your_api_key_here" ENDPOINT = "https://api.deepseek.com/v1/chat/completions" headers = { "Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json" } payload = { "model": "deepseek-chat", "messages": [ {"role": "user", "content": "将这篇会议纪要提炼为待办事项..."} ], "temperature": 0.7 } response = requests.post(ENDPOINT, headers=headers, json=payload) print(response.json()['choices'][0]['message']['content']) ``` --- ### 二、典型工作场景应用 #### 1. 数据分析自动化 ```python # 自动生成SQL查询 prompt = '''基于以下数据结构: 员工表(employee_id, name, department, salary) 请生成查询市场部薪资前10的SQL语句''' # 解析返回结果并执行 generated_sql = call_ai_api(prompt) execute_sql(generated_sql) ``` #### 2. 文档处理流水线 ```python # 自动生成周报 template = { "本周工作": ["完成项目A原型设计", "客户会议3次"], "下周计划": ["推进项目B开发", "技术方案评审"] } prompt = f'''将以下要点扩展为正式周报: {template} 要求:使用商务用语,包含数据支撑''' ``` #### 3. 代码辅助开发 ```python # 自动生成测试用例 prompt = '''为以下Python函数生成单元测试: def calculate_discount(price, is_member): if is_member and price > 100: return price * 0.9 return price 要求使用pytest格式''' ``` --- ### 三、进阶开发技巧 #### 1. 流式响应处理(适合长文本) ```python response = requests.post(ENDPOINT, headers=headers, json=payload, stream=True) for chunk in response.iter_lines(): if chunk: decoded = chunk.decode('utf-8') print(json.loads(decoded[6:])['choices'][0]['delta'].get('content', '')) ``` #### 2. 函数调用模式(结构化输出) ```json { "functions": [{ "name": "format_meeting_summary", "parameters": { "type": "object", "properties": { "key_points": {"type": "array"}, "action_items": {"type": "array"} } } }], "function_call": {"name": "format_meeting_summary"} } ``` --- ### 四、工具链整合方案 #### 1. 企业微信集成 ```python from wechatwork import WeChatAPI def wechat_callback(msg): ai_response = call_ai_api(msg.content) WeChatAPI.send_text(msg.sender, ai_response) ``` #### 2. Notion数据库联动 ```python import notion page_id = "notion_page_id" content = notion.get_page_content(page_id) summary = call_ai_api(f"摘要以下内容:{content}") notion.update_page(page_id, summary) ``` --- ### 五、成本优化策略 1. **分级缓存系统** ```python from redis import Redis cache = Redis() def get_cached_response(prompt): key = hash(prompt) if cache.exists(key): return cache.get(key) response = call_ai_api(prompt) cache.setex(key, 3600, response) return response ``` 2. **请求批处理** ```python batch_payload = { "requests": [ {"text": "文档1内容...", "task": "摘要"}, {"text": "文档2内容...", "task": "关键词提取"} ] } ``` --- ### 六、安全合规实践 1. 数据脱敏处理 ```python def sanitize_input(text): patterns = [ r'\d{3}-\d{4}-\d{4}', # 电话号码 r'\d{18}|\d{17}X' # 身份证号 ] for pattern in patterns: text = re.sub(pattern, '[REDACTED]', text) return text ``` 2. 审计日志记录 ```python import logging from datetime import datetime logging.basicConfig(filename='api_audit.log', level=INFO) def audit_log(prompt, response): log_entry = { "timestamp": datetime.now().isoformat(), "user": current_user, "prompt_hash": hash(prompt), "response_length": len(response) } logging.info(json.dumps(log_entry)) ``` --- ### 七、主流AI工具对比 | 工具 | 免费额度 | 特色功能 | 最佳场景 | |---------------|-------------|--------------------------|----------------------| | DeepSeek | 5,000次/月 | 中文优化/代码生成 | 本地化需求/开发辅助 | | OpenAI GPT-4 | 无 | 多模态支持 | 复杂推理/创新设计 | | Claude | 100次/天 | 长文本处理(100K tokens) | 文档分析/法律合同 | | 文心一言 | 2,000次/日 | 中文知识图谱 | 市场分析/舆情监测 | --- ### 八、调试测试工具 1. **Postman测试集** ```json { "info": { "name": "DeepSeek API测试集" }, "item": [{ "name": "会议纪要处理", "request": { "method": "POST", "header": [ {"key": "Authorization", "value": "Bearer {{API_KEY}}"} ], "body": { "mode": "json", "raw": { "model": "deepseek-chat", "messages": [{ "role": "user", "content": "将以下会议记录转换为待办事项..." }] } } } }] } ``` 2. **监控仪表盘配置(Grafana)** ```yaml panels: - title: API使用情况 metrics: - sum(api_calls_total) by (status_code) - rate(api_duration_seconds_sum[5m]) alerts: - expr: rate(api_errors_total[5m]) > 0.1 severity: critical ``` --- 通过合理设计工作流,AI API可帮助实现: - 文档处理效率提升5-10倍 - 代码开发时间减少30%-50% - 数据分析流程自动化程度达80% - 会议记录到任务分发的端到端自动化
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

CarlowZJ

我的文章对你有用的话,可以支持

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

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

打赏作者

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

抵扣说明:

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

余额充值