返回顶部
a

ai-integrationAI集成

Use when building AI-powered features with the Claude API or Anthropic SDK — structured outputs, tool calling, streaming, multi-provider routing, multi-agent orchestration, LLM evaluation, prompt engineering, agent memory, RAG pipelines, and production deployment. Covers single-agent, multi-agent, and agentic loop patterns for Next.js, Python, and TypeScript stacks.

作者: admin | 来源: ClawHub
源自
ClawHub
版本
V 1.0.0
安全检测
已通过
89
下载量
免费
免费
0
收藏
概述
安装方式
版本历史

ai-integration

AI集成技能

将Anthropic Claude API集成到生产系统中的全面模式——从基础API调用到具有状态管理、记忆和评估功能的完整多智能体编排。

何时使用此技能

在以下情况下激活:

  • - 构建Claude API集成或封装器
  • 实现结构化输出、工具调用或流式传输
  • 设置多提供商LLM路由(LiteLLM、回退机制)
  • 设计多智能体编排或智能体循环
  • 实现RAG或持久化智能体记忆
  • 评估LLM输出质量或构建评估系统
  • 将智能体部署到Next.js、Python FastAPI或Docker

不要将此技能用于:

  • - 与AI基础设施无关的Kubernetes/Terraform配置
  • 不涉及LLM调用的通用React/Next.js功能



核心原则

1. 单智能体 vs 多智能体

模式使用场景成本
单智能体线性任务、简单I/O、<5步
子智能体委派
并行任务、需要专业领域知识 | 中 | | 多智能体群体 | 复杂自主工作流、>10步 | 高——按团队预算 |

基础设施成本计算(2026年): 从单智能体转向编排群体时,多智能体计算成本约增加3倍。构建前先做好预算。

2. 智能体通信模式

中心辐射模式(最常见): 编排器将任务委派给专业智能体。

编排器
├── 研究智能体 (网络搜索、文档)
├── 编码智能体 (代码生成、测试)
└── 审查智能体 (质量、安全检查)

流水线模式: 一个智能体的输出是下一个智能体的输入(线性、可预测)。

群体模式: 共享记忆的智能体,无单一编排器。用于探索性任务。

3. 上下文窗口管理

python
import anthropic

client = anthropic.Anthropic()

def slidingwindow(messages: list[dict], maxtokens: int = 150_000) -> list[dict]:
丢弃最早的消息以保持在token预算内。
# 粗略估计:1 token ≈ 4个字符
while len(messages) > 2:
total = sum(len(m[content]) // 4 for m in messages)
if total <= max_tokens:
break
messages = messages[1:] # 丢弃最早的非系统消息
return messages

def summarize_history(messages: list[dict]) -> list[dict]:
将旧轮次压缩为摘要以回收上下文预算。
if len(messages) <= 4:
return messages
history = \n.join(f{m[role]}: {m[content]} for m in messages[:-2])
summary = client.messages.create(
model=claude-haiku-4-5, max_tokens=512,
messages=[{role: user, content: f简洁地总结:\n{history}}],
).content[0].text
return [{role: user, content: f[先前上下文]\n{summary}}] + messages[-2:]



结构化输出

使用instructor的Pydantic绑定(推荐)

python
import anthropic
import instructor
from pydantic import BaseModel

class Entity(BaseModel):
name: str
type: str # person | org | location | concept
description: str

class ExtractionResult(BaseModel):
entities: list[Entity]
summary: str

instructor修补客户端——返回经过验证的Pydantic模型

client = instructor.from_anthropic(anthropic.Anthropic())

result: ExtractionResult = client.messages.create(
model=claude-sonnet-4-6,
max_tokens=1024,
messages=[{role: user, content: f从以下文本中提取所有实体:\n{text}}],
response_model=ExtractionResult,
)
print(result.entities[0].name) # 完全类型化、已验证

不使用instructor的Schema强制(TypeScript)

typescript
import Anthropic from @anthropic-ai/sdk;
import { z } from zod;

const client = new Anthropic();

const EntitySchema = z.object({
entities: z.array(z.object({ name: z.string(), type: z.string() })),
summary: z.string(),
});

const response = await client.messages.create({
model: claude-sonnet-4-6,
max_tokens: 1024,
messages: [{
role: user,
content: 提取实体。仅使用与此schema匹配的有效JSON响应:
{entities: [{name: string, type: string}], summary: string}

文本:${inputText},
}],
});

const parsed = EntitySchema.parse(JSON.parse(response.content[0].text));



工具调用(函数调用)

并行工具调用 + 智能体循环(TypeScript)

typescript
import Anthropic from @anthropic-ai/sdk;

const client = new Anthropic();

const tools: Anthropic.Tool[] = [
{ name: search_web, description: 搜索网络,
input_schema: { type: object as const, properties: { query: { type: string } }, required: [query] } },
{ name: read_file, description: 读取本地文件,
input_schema: { type: object as const, properties: { path: { type: string } }, required: [path] } },
];

async function runAgentLoop(userMessage: string): Promise {
const messages: Anthropic.MessageParam[] = [{ role: user, content: userMessage }];

while (true) {
const response = await client.messages.create({
model: claude-sonnet-4-6, max_tokens: 4096,
tools, toolchoice: { type: auto }, // 或 { type: tool, name: searchweb }
messages,
});

if (response.stopreason === endturn) {
return response.content.filter((b) => b.type === text).map((b) => b.text).join();
}

// Claude可能并行调用多个工具——一次性处理所有
const toolUses = response.content.filter((b) => b.type === tool_use);
const toolResults = await Promise.all(
toolUses.map(async (tu) => ({
type: tool_result as const,
tooluseid: (tu as Anthropic.ToolUseBlock).id,
content: await executeTool((tu as Anthropic.ToolUseBlock).name, (tu as Anthropic.ToolUseBlock).input),
}))
);

messages.push({ role: assistant, content: response.content });
messages.push({ role: user, content: toolResults });
}
}



流式响应

Python流式传输

python import anthropic

client = anthropic.Anthropic()

流式文本

with client.messages.stream( model=claude-sonnet-4-6, max_tokens=1024, messages=[{role: user, content: prompt}], ) as stream: for text in stream.text_stream: print(text, end=, flush=True) final = stream.getfinalmessage() print(f\n[{final.usage.inputtokens} 输入 / {final.usage.outputtokens} 输出 tokens])

TypeScript流式传输

typescript import Anthropic from @anthropic-ai/sdk;

const client = new Anthropic();

const stream = await client.messages.create({
model: claude-opus-4-6,
max_tokens: 4096,
stream: true,
messages: [{ role: user, content: prompt }],
});

for await (const chunk of stream) {
if (chunk.type === contentblockdelta && chunk.delta.type === text_delta) {
process.stdout.write(chunk.delta.text);
}
}

Next.js SSE流式路由

typescript // app/api/chat/route.ts import Anthropic from @anthropic-ai/sdk; import { NextRequest } from next/server;

const client = new Anthropic();

export async function POST(req: NextRequest) {
const { messages } = await req.json();
const stream = await client.messages.create({
model: claude-sonnet-4-6,
max_tokens: 2048,
stream: true,
messages,
});

const encoder = new TextEncoder();
const readable = new ReadableStream({
async start(controller) {
for await (const chunk of stream) {
if (chunk.type

标签

skill ai

通过对话安装

该技能支持在以下平台通过对话安装:

OpenClaw WorkBuddy QClaw Kimi Claude

方式一:安装 SkillHub 和技能

帮我安装 SkillHub 和 ai-integration-1775959261 技能

方式二:设置 SkillHub 为优先技能安装源

设置 SkillHub 为我的优先技能安装源,然后帮我安装 ai-integration-1775959261 技能

通过命令行安装

skillhub install ai-integration-1775959261

下载

⬇ 下载 ai-integration v1.0.0(免费)

文件大小: 6.52 KB | 发布时间: 2026-4-13 09:14

v1.0.0 最新 2026-4-13 09:14
ai-integration v1.0.0

- Initial release offering patterns and best practices for integrating the Claude API and Anthropic SDK.
- Covers single-agent, subagent, and multi-agent orchestration for Next.js, Python, and TypeScript stacks.
- Provides guidance for structured outputs (Pydantic, Zod), tool/function calling, streaming, agent memory, context management, and RAG pipelines.
- Includes practical code examples for API integration, tool calling, streaming responses, schema enforcement, and agentic loops.
- Highlights multi-provider LLM routing, evaluation techniques, and production deployment scenarios.

Archiver·手机版·闲社网·闲社论坛·羊毛社区· 多链控股集团有限公司 · 苏ICP备2025199260号-1

Powered by Discuz! X5.0   © 2024-2025 闲社网·线报更新论坛·羊毛分享社区·http://xianshe.com

p2p_official_large
返回顶部