ai agent marketplace

AI Agent 市场:从 ClawHub 到 Hugging Face Spaces

引言 2025-2026 年,AI Agent 从技术概念走向产品化落地,催生了一批专门的 Agent 市场和分发平台。这些平台扮演着类似 App Store 的角色,让开发者发布、分享和变现 AI Agent,同时让非技术用户可以一键使用复杂的 AI 工作流。本文将全面梳理当前 AI Agent 市场生态,对比各平台的定位、能力和商业模式。 Agent 市场生态全景 ┌────────────────────────────────────────────────────────────┐ │ AI Agent 市场生态 │ ├────────────────┬────────────────┬───────────────────────────┤ │ 开源生态型 │ 平台型 │ 垂直场景型 │ ├────────────────┼────────────────┼───────────────────────────┤ │ Hugging Face │ Coze (字节) │ ClawHub (Agent分发) │ │ Spaces │ Dify Marketplace│ AutoGPT Store │ │ GitHub Topics │ FastGPT App库 │ AgentGPT │ │ CrewAI Hub │ 千帆 AppBuilder │ SuperAGI │ └────────────────┴────────────────┴───────────────────────────┘ 主要平台对比 平台 定位 Agent 类型 开源程度 商业化 用户量 Hugging Face Spaces 模型/应用托管 Demo 级 完全开源 免费+付费 2M+ ClawHub Agent 分发市场 生产级 开放生态 分成模式 增长中 Coze 低代码 Agent 平台 消费级 封闭 免费+付费 10M+ Dify Marketplace 应用模板市场 开发者级 开源 免费 500K+ CrewAI Hub 多Agent协作 开发者级 开源 免费 100K+ AutoGPT Store 自主Agent 实验级 开源 免费 300K+ Hugging Face Spaces Hugging Face Spaces 是目前最大的 AI 应用展示和托管平台。任何人都可以将 AI 应用部署到 Spaces,获得免费的 CPU/GPU 资源。 ...

2026-06-25 · 5 min · 911 words · AI 实战派
chatgpt agent mode 2026

ChatGPT Agent 模式 2026:从对话到全自动执行

引言:从聊天机器人到自主智能体 2026 年的 ChatGPT 已经不再是那个只会回答问题的对话框。随着 OpenAI 在 GPT-5 架构上全面引入 Agent 模式,ChatGPT 实现了从"被动回答"到"主动执行"的范式转变。Agent 模式允许 ChatGPT 自主规划任务步骤、调用工具链、浏览网页、执行代码,甚至在沙盒环境中操作软件——整个过程无需用户逐步指令。 Agent 模式的核心架构 ChatGPT Agent 模式的底层架构可以分为三个关键层: 1. 规划层(Planning Layer) Agent 模式首先将用户的高层意图分解为可执行的子任务序列。这一层基于 GPT-5 的推理能力,使用 Chain-of-Thought 和 Tree-of-Thought 混合策略。 # 伪代码示例:Agent 任务规划 from openai import OpenAI client = OpenAI() response = client.responses.create( model="gpt-5", instructions="You are an autonomous agent. Break down the user's request into actionable steps.", input="帮我调研当前主流的开源向量数据库,对比性能,生成报告", tools=[ {"type": "web_search_preview"}, {"type": "code_interpreter"}, {"type": "file_search"}, ], reasoning={"effort": "high"}, # Agent 模式核心参数 agent_config={ "max_steps": 20, "auto_execute": True, "require_approval": "on_sensitive_action", } ) for event in response: print(f"[{event.type}] {event.content}") 2. 执行层(Execution Layer) 执行层负责实际调用工具和 API。2026 版本的 Agent 模式支持以下工具类型: ...

2026-06-25 · 3 min · 514 words · AI 实战派
cursor agent coding

Cursor Agent 模式:AI 编程助手的进化

引言:从代码补全到自主编程 Cursor 在 2026 年将 Agent 模式推到了新的高度。不同于传统的代码补全或聊天式编程助手,Agent 模式能够自主理解项目结构、规划实现方案、编写代码、运行测试并修复错误——整个过程在 IDE 内完成,开发者只需描述需求。 Agent 模式核心机制 工作流程 需求理解 → 代码库探索 → 方案规划 → 代码实现 → 测试验证 → 迭代修复 1. 代码库语义理解 Cursor Agent 首先会对整个代码库建立语义索引: // Cursor 内部的代码库索引结构(简化) { "project": "my-web-app", "files_indexed": 847, "index_config": { "embedding_model": "cursor-code-embed-v2", "chunk_strategy": "ast-aware", // 基于语法树的智能分块 "chunk_size": "adaptive", // 函数/类边界对齐 "index_types": ["semantic", "symbol", "dependency"] }, "symbols": { "classes": 156, "functions": 1243, "components": 89, "api_endpoints": 34 } } 2. 上下文感知规划 Agent 模式的关键能力是理解项目约定和依赖关系: # Cursor Agent 内部规划流程(概念模型) class AgentPlanner: def plan(self, request: str, codebase: Codebase): # Step 1: 理解需求 intent = self.understand_intent(request) # Step 2: 定位相关代码 relevant_files = codebase.semantic_search(intent.keywords) dependencies = codebase.analyze_dependencies(relevant_files) # Step 3: 生成实现计划 plan = { "files_to_create": [], "files_to_modify": [], "files_to_read": [], "tests_to_write": [], "commands_to_run": [], } # Step 4: 验证计划可行性 validated_plan = self.validate(plan, codebase) return validated_plan 3. 代码实现与文件操作 // Cursor Agent 实际执行示例 // 用户请求:"给用户管理模块添加批量导入功能" // Agent 会: // 1. 读取现有用户管理代码 // 2. 创建 CSV 解析工具 // 3. 修改路由添加导入端点 // 4. 编写测试 // 5. 运行测试验证 // === Agent 创建的新文件 === // src/utils/csv-parser.ts import { parse } from 'csv-parse'; import { Readable } from 'stream'; export interface UserImportRow { name: string; email: string; department: string; role: string; } export async function parseUserCSV(buffer: Buffer): Promise<UserImportRow[]> { const records: UserImportRow[] = []; const parser = parse({ columns: true, skip_empty_lines: true, trim: true, delimiter: ',', }); Readable.from(buffer).pipe(parser); for await (const record of parser) { // 验证必填字段 if (!record.email || !record.name) { throw new Error(`缺少必填字段: 行 ${records.length + 2}`); } records.push({ name: record.name, email: record.email.toLowerCase(), department: record.department || '未分配', role: record.role || 'member', }); } return records; } // === Agent 修改的路由文件 === // src/routes/users.ts (修改部分) router.post('/users/import', upload.single('file'), requireRole('admin'), async (req, res) => { try { const users = await parseUserCSV(req.file.buffer); const result = await User.bulkCreate(users, { ignoreDuplicates: true, validate: true, }); res.json({ imported: result.length, total: users.length, skipped: users.length - result.length, }); } catch (error) { res.status(400).json({ error: error.message }); } } ); Agent 模式配置 配置文件 在项目根目录创建 .cursorrules 文件来定制 Agent 行为: ...

2026-06-25 · 4 min · 814 words · AI 实战派
event driven agent

事件驱动 Agent 架构:从 Webhook 到实时响应

1. 从轮询到事件驱动 传统 Agent 采用轮询模式:定期检查是否有新任务或状态变化。这种模式简单但低效——要么延迟高(轮询间隔长),要么浪费资源(轮询间隔短)。 事件驱动架构(EDA)将 Agent 从"主动检查"转变为"被动响应":当有意义的事件发生时,系统主动通知 Agent 处理。核心优势: 低延迟:事件发生即触发,无需等待轮询周期 低资源消耗:无事件时 Agent 处于休眠状态 天然解耦:事件生产者和消费者完全分离 弹性扩展:事件积压时可动态增加消费者 2. 事件驱动 Agent 整体架构 ┌──────────┐ ┌──────────┐ ┌──────────┐ │ GitHub │ │ Slack │ │ Sensor │ 事件源 │ Webhook │ │ Events │ │ Data │ └────┬─────┘ └────┬─────┘ └────┬─────┘ │ │ │ ▼ ▼ ▼ ┌────────────────────────────────────────┐ │ Event Ingestion Layer │ │ (API Gateway / Message Queue) │ └───────────────────┬────────────────────┘ │ ▼ ┌────────────────────────────────────────┐ │ Event Router / Filter │ └───────────────────┬────────────────────┘ │ ┌───────────┼───────────┐ ▼ ▼ ▼ ┌─────────┐ ┌─────────┐ ┌─────────┐ │ Agent A │ │ Agent B │ │ Agent C │ 事件消费者 │(Coder) │ │(Reviewer)│ │(Notifier)│ └────┬────┘ └────┬────┘ └────┬────┘ │ │ │ ▼ ▼ ▼ ┌─────────────────────────────────────┐ │ Action Executor │ │ (API calls, DB writes, etc.) │ └─────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────┐ │ Event Publisher (新事件) │ └─────────────────────────────────────┘ 3. 事件模型设计 3.1 事件 Schema from pydantic import BaseModel, Field from datetime import datetime from enum import Enum from typing import Any, Optional import uuid class EventSeverity(str, Enum): INFO = "info" WARNING = "warning" ERROR = "error" CRITICAL = "critical" class AgentEvent(BaseModel): """统一事件格式 - CloudEvents 兼容""" event_id: str = Field(default_factory=lambda: str(uuid.uuid4())) event_type: str # "github.pr.opened", "agent.task.completed" source: str # 事件来源标识 subject: str = "" # 事件主题(如 PR #123) data: dict[str, Any] # 事件负载 time: datetime = Field(default_factory=datetime.now) severity: EventSeverity = EventSeverity.INFO trace_id: str = "" # 分布式追踪 ID correlation_id: str = "" # 关联 ID(同一会话) # 事件版本控制 spec_version: str = "1.0" data_content_type: str = "application/json" class TaskCompletedEvent(AgentEvent): event_type: str = "agent.task.completed" data: dict[str, Any] = Field(description="包含 task_id, result, duration 等") class ErrorEvent(AgentEvent): event_type: str = "agent.error" severity: EventSeverity = EventSeverity.ERROR 3.2 事件注册表 class EventRegistry: """事件类型注册表 - 管理 Schema 和路由规则""" def __init__(self): self._schemas: dict[str, type[BaseModel]] = {} self._handlers: dict[str, list[callable]] = {} def register(self, event_type: str, schema: type[BaseModel]): self._schemas[event_type] = schema def subscribe(self, event_type: str, handler: callable): self._handlers.setdefault(event_type, []).append(handler) def get_handlers(self, event_type: str) -> list[callable]: # 支持通配符匹配: "github.pr.*" 匹配 "github.pr.opened" handlers = self._handlers.get(event_type, []) for pattern, h_list in self._handlers.items(): if "*" in pattern: prefix = pattern.replace("*", "") if event_type.startswith(prefix): handlers.extend(h_list) return handlers def validate(self, event: AgentEvent) -> bool: schema = self._schemas.get(event.event_type) if schema: schema(**event.model_dump()) return True 4. 事件总线实现 4.1 内存事件总线(单机) import asyncio from collections import defaultdict from concurrent.futures import ThreadPoolExecutor class InMemoryEventBus: def __init__(self, max_workers: int = 10): self._subscribers: dict[str, list] = defaultdict(list) self._executor = ThreadPoolExecutor(max_workers=max_workers) self._dead_letter_queue: list[tuple[AgentEvent, Exception]] = [] self._middleware: list[callable] = [] def use(self, middleware: callable): """注册中间件:日志、认证、限流等""" self._middleware.append(middleware) async def subscribe(self, event_type: str, handler: callable): self._subscribers[event_type].append(handler) async def publish(self, event: AgentEvent): # 执行中间件链 for mw in self._middleware: event = await mw(event) if event is None: return # 被中间件拦截 handlers = self._subscribers.get(event.event_type, []) # 匹配通配符订阅 for pattern, h_list in self._subscribers.items(): if "*" in pattern: prefix = pattern.replace("*", "") if event.event_type.startswith(prefix): handlers.extend(h_list) # 并行执行所有处理器 tasks = [self._safe_execute(h, event) for h in handlers] await asyncio.gather(*tasks, return_exceptions=True) async def _safe_execute(self, handler: callable, event: AgentEvent): try: if asyncio.iscoroutinefunction(handler): await handler(event) else: await asyncio.get_event_loop().run_in_executor( self._executor, handler, event ) except Exception as e: self._dead_letter_queue.append((event, e)) # 发布错误事件 error_event = ErrorEvent( source="event_bus", data={"original_event": event.event_id, "error": str(e)}, trace_id=event.trace_id, ) await self.publish(error_event) 4.2 Kafka 事件总线(分布式) from aiokafka import AIOKafkaProducer, AIOKafkaConsumer import json class KafkaEventBus: def __init__(self, bootstrap_servers: str = "localhost:9092"): self.bootstrap_servers = bootstrap_servers self._producer: AIOKafkaProducer = None self._consumers: list[AIOKafkaConsumer] = [] self._handlers: dict[str, callable] = {} async def start(self): self._producer = AIOKafkaProducer( bootstrap_servers=self.bootstrap_servers, value_serializer=lambda v: json.dumps(v.model_dump(mode="json")).encode(), key_serializer=lambda k: k.encode() if k else None, acks="all", # 等待所有副本确认 enable_idempotence=True, # 幂等生产者 compression_type="lz4", # 压缩 max_in_flight_requests_per_connection=5, ) await self._producer.start() async def publish(self, event: AgentEvent, topic: str = None): topic = topic or event.event_type.split(".")[0] # 按事件类型分 Topic partition_key = event.correlation_id or event.source await self._producer.send_and_wait( topic, event, key=partition_key ) async def subscribe(self, event_type: str, handler: callable, group_id: str = "agent-group"): topic = event_type.split(".")[0] consumer = AIOKafkaConsumer( topic, bootstrap_servers=self.bootstrap_servers, group_id=group_id, value_deserializer=lambda v: AgentEvent(**json.loads(v.decode())), auto_offset_reset="latest", enable_auto_commit=False, ) await consumer.start() self._consumers.append(consumer) self._handlers[event_type] = handler async for msg in consumer: event = msg.value if event.event_type == event_type or event_type.endswith("*"): try: await handler(event) await consumer.commit() except Exception as e: # 重试或进入死信队列 await self._handle_error(event, e) async def stop(self): await self._producer.stop() for c in self._consumers: await c.stop() 5. Agent 状态机 事件驱动 Agent 的核心是一个状态机:不同事件触发不同状态转换。 ...

2026-06-25 · 7 min · 1381 words · AI 实战派
agent memory architecture

Agent 记忆架构设计:短期/长期/情景记忆

为什么 Agent 需要记忆 没有记忆的 Agent 就像金鱼——每次对话都从零开始。你告诉它你的名字,下一轮它就忘了。你纠正过它的错误,它下次照犯。 记忆系统让 Agent 能够: 记住用户偏好和历史交互 从过去经验中学习 保持跨会话的上下文一致性 在长任务中不丢失关键信息 记忆类型体系 人类认知科学启发 记忆类型 持续时间 容量 Agent 对应 存储方案 工作记忆 秒-分钟 4±2 项 当前对话上下文 LLM Context Window 短期记忆 分钟-小时 有限 当前会话摘要 内存/Redis 长期记忆 天-永久 近无限 用户偏好、知识 向量库 + 关系库 情景记忆 事件级 大 具体交互记录 时序向量库 架构总览 ┌──────────────────────────────────────────────┐ │ Agent 主循环 │ │ │ │ ┌─────────┐ ┌─────────┐ ┌──────────────┐ │ │ │ 工作记忆 │ │ 短期记忆 │ │ 长期记忆 │ │ │ │ Context │←→│ Session │←→│ Persistent │ │ │ │ Window │ │ Summary │ │ Store │ │ │ └─────────┘ └─────────┘ └──────────────┘ │ │ │ │ │ │ │ │ │ ┌────────┼────────┐ │ │ │ │ │ │ │ │ │ │ │ ┌──┴──┐ ┌───┴───┐ ┌──┴──┐ │ │ │ │语义 │ │情景 │ │程序 │ │ │ │ │记忆 │ │记忆 │ │记忆 │ │ │ │ │向量 │ │时序 │ │图 │ │ │ │ └─────┘ └───────┘ └─────┘ │ │ │ │ ┌────┴────────────┴────────────────────────┐│ │ │ 记忆管理器 ││ │ │ 写入 → 压缩 → 检索 → 遗忘 → 巩固 ││ │ └────────────────────────────────────────────┘│ └──────────────────────────────────────────────┘ 工作记忆:上下文窗口管理 from dataclasses import dataclass, field from typing import List, Dict @dataclass class WorkingMemory: """工作记忆: 管理 LLM 上下文窗口""" max_tokens: int = 128000 reserved_for_response: int = 4096 messages: List[dict] = field(default_factory=list) def add(self, role: str, content: str): self.messages.append({"role": role, "content": content}) self._evict_if_needed() def add_system(self, content: str): """系统消息放在最前面,不被驱逐""" self.messages.insert(0, {"role": "system", "content": content}) def _evict_if_needed(self): """当超过 token 限制时,驱逐最旧的对话""" while self._count_tokens() > self.max_tokens - self.reserved_for_response: if len(self.messages) <= 1: break # 找到第一个非 system 消息并移除 for i, msg in enumerate(self.messages): if msg["role"] != "system": evicted = self.messages.pop(i) # 触发压缩: 被驱逐的消息需要被压缩到短期记忆 self._on_evict(evicted) break def _count_tokens(self) -> int: import tiktoken enc = tiktoken.encoding_for_model("gpt-4o") return sum(len(enc.encode(m["content"])) for m in self.messages) def _on_evict(self, evicted_msg: dict): """被驱逐的消息回调,交给短期记忆处理""" # 由 MemoryManager 注册 pass def get_context(self) -> List[dict]: """获取当前上下文""" return self.messages.copy() 短期记忆:会话级摘要 class ShortTermMemory: """短期记忆: 当前会话的压缩摘要""" def __init__(self): self.summary = "" self.key_points: List[str] = [] self.token_budget = 2000 # 摘要不超 2000 token async def compress(self, messages: List[dict]) -> str: """将多轮对话压缩为摘要""" conversation = "\n".join( f"{m['role']}: {m['content'][:200]}" for m in messages ) prompt = f"""请将以下对话压缩为简洁摘要,保留: 1. 用户的核心需求 2. 已确定的关键事实 3. 未解决的问题 4. 用户的明确偏好 对话: {conversation} 摘要:""" response = await llm_call(prompt, max_tokens=self.token_budget) self.summary = response return response async def extract_key_points(self, messages: List[dict]) -> List[str]: """提取关键信息点""" prompt = f"""从以下对话中提取关键信息点,每点一行: {chr(10).join(m['content'][:200] for m in messages)} 关键信息:""" response = await llm_call(prompt, max_tokens=500) self.key_points = response.strip().split('\n') return self.key_points def to_context(self) -> str: """转换为可注入上下文的文本""" parts = [] if self.summary: parts.append(f"之前的对话摘要:\n{self.summary}") if self.key_points: parts.append(f"关键信息:\n" + "\n".join(f"- {p}" for p in self.key_points)) return "\n\n".join(parts) 长期记忆:持久化存储 语义记忆(向量库) class SemanticMemory: """语义记忆: 存储事实和知识,向量检索""" def __init__(self, vector_store, embed_model): self.store = vector_store self.embed = embed_model async def remember(self, content: str, metadata: dict = None): """记住一条信息""" embedding = await self.embed(content) await self.store.upsert({ "id": self._generate_id(content), "values": embedding, "metadata": { "content": content, "type": "semantic", "created_at": datetime.now().isoformat(), **(metadata or {}) } }) async def recall(self, query: str, top_k: int = 5) -> List[dict]: """检索相关记忆""" query_embedding = await self.embed(query) results = await self.store.query( vector=query_embedding, top_k=top_k, filter={"type": {"$eq": "semantic"}} ) return [ { "content": r.metadata["content"], "score": r.score, "metadata": r.metadata } for r in results.matches ] async def forget(self, content_id: str): """主动遗忘""" await self.store.delete(ids=[content_id]) 情景记忆(时序事件) class EpisodicMemory: """情景记忆: 记录具体交互事件,支持时间检索""" def __init__(self, db): self.db = db # PostgreSQL + pgvector async def record(self, event: dict): """记录一个交互事件""" await self.db.execute( """ INSERT INTO episodic_memory (event_id, user_id, timestamp, input, output, outcome, context_snapshot, embedding) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) """, event["id"], event["user_id"], datetime.now(), event["input"], event["output"], event["outcome"], json.dumps(event.get("context", {})), event.get("embedding") ) async def recall_by_time(self, user_id: str, start: datetime, end: datetime) -> List[dict]: """按时间范围回忆""" rows = await self.db.fetch( """SELECT * FROM episodic_memory WHERE user_id = $1 AND timestamp BETWEEN $2 AND $3 ORDER BY timestamp DESC""", user_id, start, end ) return [dict(r) for r in rows] async def recall_similar(self, user_id: str, query_embedding: list, top_k: int = 5) -> List[dict]: """检索相似的历史事件""" rows = await self.db.fetch( """SELECT *, embedding <=> $1 as distance FROM episodic_memory WHERE user_id = $2 ORDER BY embedding <=> $1 LIMIT $3""", query_embedding, user_id, top_k ) return [dict(r) for r in rows] 程序记忆(知识图谱) class ProceduralMemory: """程序记忆: 存储技能、流程、因果关系(图结构)""" def __init__(self, graph_db): self.graph = graph_db # Neo4j async def learn_procedure(self, name: str, steps: List[str], triggers: List[str]): """学习一个新流程""" await self.graph.execute( """ CREATE (p:Procedure {name: $name}) WITH p UNWIND $steps as step_text CREATE (s:Step {text: step_text}) CREATE (p)-[:HAS_STEP]->(s) WITH p UNWIND $triggers as trigger CREATE (t:Trigger {text: trigger}) CREATE (t)-[:ACTIVATES]->(p) """, name=name, steps=steps, triggers=triggers ) async def recall_procedure(self, context: str) -> List[dict]: """根据上下文检索相关流程""" result = await self.graph.execute( """ MATCH (t:Trigger)-[:ACTIVATES]->(p:Procedure)-[:HAS_STEP]->(s:Step) WHERE $context CONTAINS t.text RETURN p.name as procedure, collect(s.text) as steps """, context=context ) return [dict(r) for r in result] 记忆管理器:统一调度 class MemoryManager: """统一记忆管理器""" def __init__(self): self.working = WorkingMemory() self.short_term = ShortTermMemory() self.semantic = SemanticMemory(...) self.episodic = EpisodicMemory(...) self.procedural = ProceduralMemory(...) self.recall_count = 0 async def think(self, user_input: str, user_id: str) -> str: """带记忆的思考过程""" # 1. 从长期记忆检索相关信息 semantic_results = await self.semantic.recall(user_input, top_k=3) episodic_results = await self.episodic.recall_similar( user_id, await self.embed(user_input), top_k=3 ) procedures = await self.procedural.recall_procedure(user_input) # 2. 组装上下文 context_parts = [] if self.short_term.summary: context_parts.append(self.short_term.to_context()) if semantic_results: context_parts.append("相关知识:\n" + "\n".join(f"- {r['content']}" for r in semantic_results)) if episodic_results: context_parts.append("历史交互:\n" + "\n".join(f"- {r['input']} → {r['output']}" for r in episodic_results)) if procedures: context_parts.append("可用流程:\n" + "\n".join(f"- {p['procedure']}: {p['steps']}" for p in procedures)) context = "\n\n".join(context_parts) # 3. 注入工作记忆 if context: self.working.add("system", f"记忆上下文:\n{context[:4000]}") self.working.add("user", user_input) # 4. 生成回复 response = await llm_call(self.working.get_context()) self.working.add("assistant", response) # 5. 异步写入记忆 asyncio.create_task(self._consolidate(user_input, response, user_id)) return response async def _consolidate(self, input: str, output: str, user_id: str): """记忆巩固: 筛选重要信息写入长期记忆""" # 判断是否值得记住 importance = await self._assess_importance(input, output) if importance > 0.7: # 高重要性: 写入语义记忆 + 情景记忆 await self.semantic.remember( f"用户说了: {input}\n助手回答: {output}", metadata={"importance": importance, "user_id": user_id} ) # 总是记录情景记忆 await self.episodic.record({ "id": str(uuid4()), "user_id": user_id, "input": input, "output": output, "outcome": "success", "embedding": await self.embed(input), }) async def _assess_importance(self, input: str, output: str) -> float: """评估信息重要性 0-1""" prompt = f"""评估以下交互的信息重要性(0-1): 输入: {input[:200]} 输出: {output[:200]} 评分标准: - 0.9+: 用户明确要求记住/涉及核心偏好 - 0.7-0.8: 包含重要事实或决策 - 0.5-0.6: 有一定参考价值 - 0.3-0.4: 闲聊但含少量信息 - 0.0-0.2: 纯闲聊无信息 只输出数字:""" return float(await llm_call(prompt, max_tokens=10)) 遗忘机制 class ForgettingMechanism: """遗忘机制: 防止记忆膨胀""" async def decay(self, user_id: str): """基于时间的记忆衰减""" await self.db.execute( """ UPDATE semantic_memory SET importance = importance * 0.95 -- 每天衰减5% WHERE user_id = $1 AND last_accessed < NOW() - INTERVAL '1 day' """, user_id ) # 删除低重要性记忆 await self.db.execute( """ DELETE FROM semantic_memory WHERE user_id = $1 AND importance < 0.1 """, user_id ) async def deduplicate(self, user_id: str): """去重: 合并语义相似的记忆""" # 找到相似度 > 0.9 的记忆对 duplicates = await self.db.fetch( """ SELECT a.id as id_a, b.id as id_b, a.content as content_a, b.content as content_b FROM semantic_memory a JOIN semantic_memory b ON a.id < b.id WHERE a.user_id = $1 AND b.user_id = $1 AND a.embedding <=> b.embedding < 0.1 """, user_id ) for dup in duplicates: # 合并: 保留更详细的,删除另一个 longer = dup['content_a'] if len(dup['content_a']) > len(dup['content_b']) else dup['content_b'] shorter_id = dup['id_b'] if len(dup['content_a']) > len(dup['content_b']) else dup['id_a'] await self.db.execute("DELETE FROM semantic_memory WHERE id = $1", shorter_id) async def compress_old_memories(self, user_id: str, days: int = 30): """压缩旧记忆: 把多条相关记忆合并为一条摘要""" old_memories = await self.db.fetch( """ SELECT content FROM semantic_memory WHERE user_id = $1 AND created_at < NOW() - INTERVAL '$2 days' ORDER BY created_at """, user_id, days ) if len(old_memories) < 10: return # 用 LLM 合并 memories_text = "\n".join(m['content'] for m in old_memories) summary = await llm_call( f"将以下记忆合并为简洁摘要,保留关键信息:\n{memories_text}" ) # 删除旧记忆,写入摘要 await self.db.execute( "DELETE FROM semantic_memory WHERE user_id = $1 AND created_at < NOW() - INTERVAL '$2 days'", user_id, days ) await self.semantic.remember(summary, metadata={"compressed": True}) MemGPT / Letta 架构参考 MemGPT (现 Letta) 的核心思想是把操作系统的虚拟内存概念引入 LLM: ...

2026-06-25 · 7 min · 1414 words · AI 实战派
agent eval framework

Agent 评估框架:如何衡量 Agent 的真正能力

引言 2026 年,AI Agent 已从简单的对话助手演进为能自主规划、调用工具、执行多步骤任务的复杂系统。但 Agent 的评估远比 LLM 困难——同一个任务可能有无数条正确路径,中间步骤的错误可能被后续步骤弥补,而「完成任务」的定义本身也充满模糊性。本文系统梳理 Agent 评估的方法论与框架。 一、Agent 评估的核心难点 1.1 与传统 LLM 评估的本质区别 维度 LLM 评估 Agent 评估 输入 单轮/多轮 prompt 任务描述 + 环境 + 工具集 输出 文本回答 多种模态(文本、代码、文件、API 调用) 评估单元 单次回答 多步骤轨迹 正确性 可对照参考答案 路径多样,无唯一正确答案 环境依赖 无 依赖外部环境状态 成本 低 高(每步消耗 tokens + 工具调用) 可复现性 高 低(环境状态变化) 1.2 核心挑战 挑战一:路径多样性。 「订一张明天去上海的机票」这个任务,Agent 可以先查日历确认日期、再搜索航班、最后预订;也可以直接搜索航班并预订。路径不同但都正确。 挑战二:中间错误的可恢复性。 Agent 在第 2 步调错了 API,但在第 3 步意识到并纠正了——这算不算错误?如何量化? 挑战三:环境不可复现。 Agent 调用的 API 返回值可能随时间变化,同一任务在不同时间执行可能得到不同结果。 ...

2026-06-25 · 3 min · 594 words · AI 实战派
agent production patterns

Agent 生产设计模式:从单 Agent 到多 Agent 编排

Agent 模式全景 复杂度 → 单Agent ──→ Router ──→ Fan-out/Fan-in ──→ Hierarchical ──→ Multi-Agent │ │ │ │ │ │ 简单任务 │ 按需分发 │ 并行处理 │ 管理者+执行者 │ 自主协作 │ │ │ │ │ └────────────┴──────────────┴──────────────────┴────────────────┘ 模式 适用场景 复杂度 延迟 错误恢复 单 Agent 简单问答、单一任务 低 低 简单重试 Router 多领域问答、任务分类 中 低+路由 单分支重试 Fan-out/Fan-in 并行研究、批量处理 中 高(并行) 部分失败容忍 Hierarchical 复杂项目、多步骤流程 高 高 子任务级恢复 Multi-Agent 开放式协作、辩论 极高 最高 最复杂 单 Agent 架构 最基础的形态:一个 Agent + 一组工具。 ...

2026-06-25 · 5 min · 997 words · AI 实战派
chatgpt agent mode deep

ChatGPT Agent 模式深度解析:OpenAI 的 Agent 野心

Agent 模式:从对话到行动的跃迁 2025 年,OpenAI 正式推出 ChatGPT Agent 模式,标志着 AI 从「回答问题」向「完成任务」的范式转移。这不是简单的功能叠加,而是底层架构的重构。 核心功能拆解 Agent 模式的本质是赋予 ChatGPT 三项关键能力: 能力 实现方式 典型场景 代码执行 沙箱 Python 运行时 数据分析、图表生成、数学计算 网络搜索 实时检索 + 内容提取 事实核查、新闻追踪、价格查询 文件操作 上传/下载/读写 文档处理、批量转换、格式转换 这三项能力的组合产生了质变。传统 ChatGPT 只能在单轮对话中生成文本,而 Agent 模式可以规划多步任务链:先搜索获取信息,再写代码处理数据,最后生成文件输出。整个过程自主决策,用户只需给出目标。 Operator 与 CUA:操作浏览器的 AI OpenAI 在 Agent 方向上最激进的尝试是 Operator,基于 CUA(Computer Using Agent) 架构。CUA 的核心思路: 屏幕感知:通过视觉模型理解浏览器界面的像素级布局 动作映射:将意图转化为鼠标点击、键盘输入、滚动等操作 反馈循环:每次操作后重新截图,判断结果是否符合预期 这意味着 ChatGPT 不再依赖 API 集成来使用外部服务——它可以直接「看到」网页并操作,就像人类用户一样。 实测中,Operator 可以完成订机票、填表单、管理邮箱等任务。但它并非没有问题: 速度慢:每步操作需要截图→分析→决策→执行,完成一个简单表单可能需要 30 秒以上 视觉理解误差:复杂页面布局会导致误点击,动态加载内容容易丢失上下文 认证壁垒:遇到验证码、双因素认证时无法继续 Agent 模式 vs GPT-4 对话模式:本质区别 维度 GPT-4 对话模式 Agent 模式 交互模式 单轮请求-响应 多步自主执行 工具使用 需用户手动触发 自主决策调用 上下文管理 对话窗口内 跨步骤状态保持 错误处理 报错给用户 自主重试与修正 输出形式 文本为主 文本+文件+代码结果 执行时间 秒级 分钟级甚至更长 关键区别在于自主性。GPT-4 是一个被动的知识引擎——你问它答。Agent 模式是一个主动的任务执行者——你给目标,它规划路径、调用工具、处理异常、交付结果。 ...

2026-06-25 · 2 min · 257 words · AI 实战派
hermes overview 2026

Hermes Agent 爱马仕智能体全景:越用越聪明的 AI

起源:Nous Research 的野心 Hermes Agent(爱马仕智能体)由 Nous Research 团队发起。Nous Research 是北美知名的独立 AI 研究组织,专注于开源大模型与自主智能体系统。团队核心成员来自 CMU、Stanford 等顶尖院校,此前已发布 Hermes 系列开源模型(Hermes 2、Hermes 3),在 HuggingFace 上累计下载量超过 2000 万次。 2026 年 2 月,Nous Research 正式开源 Hermes Agent 项目,采用 MIT 协议。这不是一个简单的聊天机器人框架,而是一个具备自进化能力的自主智能体系统。 核心定位:The Agent That Grows With You Hermes 的 slogan 是 “the agent that grows with you”——与你共同成长的智能体。传统 AI Agent 的问题在于:用得越多,对话历史越长,但能力并不会增长,反而 context window 膨胀导致性能下降。Hermes 颠覆了这一范式: 传统 Agent: 使用 → 历史膨胀 → 性能下降 → 清空 → 从零开始 Hermes: 使用 → 经验积累 → 技能提炼 → 能力增长 → 越用越强 这一核心理念通过三个机制实现: ...

2026-06-25 · 2 min · 385 words · AI 实战派
llama index agent review

LlamaIndex Agent 评测:从 RAG 到 Agent 的进化

LlamaIndex 的演进路线 LlamaIndex 起家于 RAG(检索增强生成),最初的定位是"连接你的数据与 LLM"。但随着 LLM 能力增强,单纯检索已经不够——用户需要 Agent 来动态决定何时检索、如何检索、检索后做什么。 版本阶段 核心能力 定位 0.9 之前 Index + Query Engine RAG 框架 0.10+ LlamaHub + Workflows 数据连接 + 工作流 当前 Data Agent + AgentWorkflow RAG + Agent 融合 0.10 是分水岭——LlamaIndex 重构了整个包结构,引入了 Workflow(事件驱动工作流)和 Data Agent,正式从 RAG 框架进化为 Agent 框架。 Data Agent:带检索能力的智能体 LlamaIndex 的 Data Agent = LLM + Tools + 检索能力: from llama_index.core.agent import FunctionAgent from llama_index.llms.openai import OpenAI from llama_index.core.tools import FunctionTool, QueryEngineTool llm = OpenAI(model="gpt-4o") # 工具1:网络搜索 def search_web(query: str) -> str: """搜索互联网获取最新信息""" from llama_index.tools.tavilyi import TavilyToolSpec return TavilyToolSpec().search(query) web_tool = FunctionTool.from_defaults(fn=search_web) # 工具2:RAG 查询(复用现有索引) from llama_index.core import VectorStoreIndex index = VectorStoreIndex.from_documents(documents) query_engine = index.as_query_engine(similarity_top_k=5) rag_tool = QueryEngineTool.from_defaults( query_engine=query_engine, name="knowledge_base", description="查询内部知识库,包含产品文档和技术规范" ) # 创建 Data Agent agent = FunctionAgent( tools=[web_tool, rag_tool], llm=llm, system_prompt="你是一个研究助手。先查内部知识库,找不到再搜网络。" ) response = await agent.run("我们的API限流策略是什么?和业界最佳实践比如何?") # Agent会: 1. 先用rag_tool查内部 2. 再用web_tool搜业界实践 3. 综合回答 这是 LlamaIndex 的差异化优势:RAG 不是外部组件,而是 Agent 的原生能力。在 LangChain 里你要手动把 Retriever 包装成 Tool,在 LlamaIndex 里这是内建的。 ...

2026-06-25 · 3 min · 600 words · AI 实战派
🔗 硅基 AGI 论坛 · silicon-agi.com | 📡 RSS 订阅
鲁ICP备2026018361号