← 返回 Semantica 专题首页 🔌 SEMANTICA · COOKBOOK · 集成系列

Agno × Semantica:多智能体共享上下文

Semantica 官方 Cookbook 中文翻译 · 第 37 / 37 篇

📦 semantica 🕸️ 知识图谱 🔎 GraphRAG

本 notebook 展示一个 Agno Team 中的专家智能体如何共享同一个 ContextGraph,从而:

  • 永不做出相互矛盾的决策
  • 复用彼此抽取的知识,而无需耦合实现
  • 在所有智能体之间维护完整的因果审计轨迹

场景: 一个由三个专家智能体组成的产品策略团队:

智能体 角色 工具
Researcher 从文本中抽取竞争情报 AgnoKGToolkit
Analyst 评估机会并记录决策 AgnoDecisionKit
Strategist 将两者综合为一份建议 两者

1架构

AgnoSharedContext(单个 ContextGraph + VectorStore)
   │
   ├── bind_agent("researcher")  → AgnoContextStore(角色作用域)
   ├── bind_agent("analyst")     → AgnoContextStore(角色作用域)
   └── bind_agent("strategist")  → AgnoContextStore(角色作用域)

Agno Team
   ├── Researcher  memory=researcher_store  tools=[AgnoKGToolkit(context=shared)]
   ├── Analyst     memory=analyst_store     tools=[AgnoDecisionKit(context=shared)]
   └── Strategist  memory=strategist_store  tools=[AgnoKGToolkit, AgnoDecisionKit]

2安装

# 安装带 Agno 集成的 semantica
pip install semantica[agno]

31. 导入

import sys, os, json
sys.path.insert(0, os.path.abspath("../../"))

# ── Semantica 核心 ───────────────────────────────────────────────────────────
from semantica.context import ContextGraph, AgentContext, CausalChainAnalyzer
from semantica.vector_store import VectorStore
from semantica.semantic_extract import NERExtractor, RelationExtractor
from semantica.reasoning import Reasoner
from semantica.kg import GraphBuilder, GraphAnalyzer, CentralityCalculator

# ── Agno 集成 ─────────────────────────────────────────────────────────
from integrations.agno import (
    AgnoSharedContext,
    AgnoDecisionKit,
    AgnoKGToolkit,
    AGNO_AVAILABLE,
)

print("Semantica imports OK")
print(f"Agno installed: {AGNO_AVAILABLE}")

42. 构建共享的 Semantica 后端

单个 VectorStoreContextGraph 支撑整个团队。所有智能体都读写同一个存储——角色作用域由 AgnoSharedContext 自动应用。

# ── 单个共享后端 ───────────────────────────────────────────────────
shared_vector_store = VectorStore(backend="faiss", dimension=768)
shared_graph = ContextGraph(advanced_analytics=True)

print("Shared VectorStore (FAISS) ready")
print("Shared ContextGraph ready")

# ── AgnoSharedContext:团队协调器 ───────────────────────────────────
shared = AgnoSharedContext(
    vector_store=shared_vector_store,
    knowledge_graph=shared_graph,
    decision_tracking=True,
    session_id="product_strategy_team_q1_2026",
)
print(f"\nAgnoSharedContext ready — session: {shared.session_id}")

53. 绑定智能体角色

每个智能体通过 bind_agent() 获得一个角色作用域AgnoContextStore。所有智能体共享同一个底层图谱,但它们的写入会打上各自角色的标签以便过滤。

# 绑定每个智能体角色——幂等,可安全地多次调用
researcher_store  = shared.bind_agent("researcher")
analyst_store     = shared.bind_agent("analyst")
strategist_store  = shared.bind_agent("strategist")

print("Agent roles bound:")
for role in shared.bound_roles:
    store = shared.bind_agent(role)
    print(f"  {role:15s} → session={store.session_id}")

# 验证所有角色看到的是同一个底层 knowledge_graph
assert researcher_store._ctx is analyst_store._ctx
print("\nAll agents share the same AgentContext ✓")

64. 预加载竞争情报

使用原生 Semantica API,我们将竞争格局加载到共享图谱中。这代表团队从先前研究会话中积累的知识。

# 竞争情报文档
COMPETITIVE_INTEL = [
    {
        "source": "market_research_q4_2025",
        "text": (
            "Competitor Alpha launched a new SaaS analytics platform in Q4 2025. "
            "The product targets mid-market enterprises with annual revenue between "
            "$50M–$500M and has attracted 200 paying customers within 3 months. "
            "Pricing is $2,000/seat/year with volume discounts at 50+ seats. "
            "Alpha raised a $80M Series C led by Sequoia Capital in November 2025."
        ),
    },
    {
        "source": "customer_interviews_q4_2025",
        "text": (
            "Customer interviews reveal strong demand for AI-powered anomaly detection "
            "in financial reporting workflows. 78% of CFOs surveyed cite 'time to insight' "
            "as the top pain point — currently averaging 14 days per reporting cycle. "
            "Competitor Alpha scores poorly on integration depth (NPS: 24) while "
            "our legacy product scores 41. Customers value our data governance features "
            "but want a modern UI and sub-second query times."
        ),
    },
    {
        "source": "technology_scan_q4_2025",
        "text": (
            "Emerging technologies for consideration: LLM-native analytics interfaces "
            "reduce time-to-insight by 60% in pilot studies (Stanford HAI, 2025). "
            "Graph-based anomaly detection outperforms time-series approaches for "
            "multi-entity financial fraud by 34% (ACM SIGMOD 2025). "
            "Vector database adoption in enterprise analytics grew 120% YoY. "
            "Apache Arrow and DuckDB emerging as standards for in-process OLAP."
        ),
    },
]

# 直接使用 Semantica NER + RelationExtractor 进行丰富的抽取
ner = NERExtractor()
rel_extractor = RelationExtractor(confidence_threshold=0.55)
graph_builder = GraphBuilder(merge_entities=True)

for doc in COMPETITIVE_INTEL:
    text = doc['text']
    entities = ner.extract_entities(text) or []
    relations = rel_extractor.extract_relations(text) or []
    print(f"[{doc['source']}]")
    print(f"  Entities: {len(entities)}, Relations: {len(relations)}")
    # 存储到共享上下文中,供所有智能体访问
    shared._context.store(text, conversation_id=doc['source'])

print("\nCompetitive intelligence loaded into shared context")

75. 构建智能体专属工具

每个工具包都指向共享上下文,这样跨智能体的工具调用会修改和读取同一个图谱。

# Researcher 的 KG 工具包——从原始文本构建知识
researcher_kg_kit = AgnoKGToolkit(
    ner_extractor=ner,
    relation_extractor=rel_extractor,
    reasoner=Reasoner(),
    context=shared.knowledge_graph,   # 共享图谱
)

# Analyst 的决策工具包——记录评估并查找先例
analyst_decision_kit = AgnoDecisionKit(
    context=shared._context,           # 共享 AgentContext
    max_precedents=5,
    causal_depth=3,
    enable_policy_check=True,
)

# Strategist 两者兼有
strategist_kg_kit = AgnoKGToolkit(
    ner_extractor=ner,
    relation_extractor=rel_extractor,
    reasoner=Reasoner(),
    context=shared.knowledge_graph,
)
strategist_decision_kit = AgnoDecisionKit(
    context=shared._context,
    max_precedents=5,
)

print(f"Researcher toolkit:  {len(researcher_kg_kit._tools)} tools")
print(f"Analyst toolkit:     {len(analyst_decision_kit._tools)} tools")
print(f"Strategist toolkits: {len(strategist_kg_kit._tools)} + {len(strategist_decision_kit._tools)} tools")

86. 模拟智能体协作

我们直接模拟各智能体的推理步骤,展示共享上下文如何在角色之间传播知识。

print("=" * 65)
print("RESEARCHER AGENT TURN")
print("=" * 65)

# Researcher 从新的竞争情报中抽取实体
new_intel = (
    "Competitor Beta just closed a strategic partnership with Microsoft Azure, "
    "integrating their anomaly detection engine natively into Azure Synapse Analytics. "
    "This gives Beta access to Microsoft's 300,000+ enterprise customer base. "
    "Beta's CEO Sarah Chen announced the deal at Gartner Data & Analytics Summit."
)

# 步骤 1:抽取实体
entities_result = json.loads(researcher_kg_kit.extract_entities(new_intel))
print(f"\n[researcher] extracted {entities_result['count']} entities:")
for e in entities_result['entities']:
    print(f"  {e['name']:30s}  type={e['type']}")

# 步骤 2:抽取关系
relations_result = json.loads(researcher_kg_kit.extract_relations(new_intel))
print(f"\n[researcher] extracted {relations_result['count']} relations")

# 步骤 3:添加到共享图谱——现在对所有智能体可见
add_result = json.loads(researcher_kg_kit.add_to_graph(
    entities=json.dumps([
        {"name": "Competitor Beta", "type": "COMPANY"},
        {"name": "Microsoft Azure", "type": "COMPANY"},
        {"name": "Azure Synapse Analytics", "type": "PRODUCT"},
        {"name": "Sarah Chen", "type": "PERSON"},
        {"name": "Gartner Data & Analytics Summit", "type": "EVENT"},
    ]),
    relations=json.dumps([
        {"source": "Competitor Beta", "relation": "PARTNERSHIP_WITH", "target": "Microsoft Azure"},
        {"source": "Competitor Beta", "relation": "INTEGRATES_WITH", "target": "Azure Synapse Analytics"},
        {"source": "Sarah Chen", "relation": "CEO_OF", "target": "Competitor Beta"},
    ]),
))
print(f"\n[researcher] added {add_result['nodes_added']} nodes, {add_result['edges_added']} edges to SHARED graph")
print("=" * 65)
print("ANALYST AGENT TURN (sees researcher's graph additions)")
print("=" * 65)

# Analyst 查询 Researcher 刚刚填充的图谱
competitor_query = json.loads(analyst_decision_kit.find_precedents(
    scenario="competitor partnership with cloud hyperscaler threatens market position",
    limit=3,
))
print(f"\n[analyst] find_precedents → {competitor_query['count']} similar past strategic responses found")

# Analyst 记录一个战略评估决策
eval_json = analyst_decision_kit.record_decision(
    category="strategic_response",
    scenario=(
        "Competitor Beta + Microsoft Azure partnership gives Beta access to "
        "300k enterprise customers via Azure Synapse native integration"
    ),
    reasoning=(
        "Threat level: HIGH. Beta's Azure native integration removes our "
        "integration advantage. Existing NPS lead (41 vs 24) remains but "
        "distribution disadvantage is critical. Recommend accelerated cloud-native "
        "partnership evaluation, specifically AWS Marketplace + Snowflake Native App."
    ),
    outcome="escalate_to_strategy",
    confidence=0.85,
    entities="Competitor Beta, Microsoft Azure, AWS Marketplace, Snowflake",
)
eval_result = json.loads(eval_json)
analyst_decision_id = eval_result['decision_id']
print(f"\n[analyst] recorded evaluation → decision_id: {analyst_decision_id}")
print("=" * 65)
print("STRATEGIST AGENT TURN (sees both researcher + analyst work)")
print("=" * 65)

# Strategist 查询图谱以获取完整的竞争图景
related = json.loads(strategist_kg_kit.find_related("Competitor Beta", hops=2))
print(f"\n[strategist] 'Competitor Beta' 2-hop neighbourhood: {related['count']} entity/entities")
for entity in related['related']:
    print(f"  → {entity}")

# Strategist 追踪 Analyst 所做的决策
causal = json.loads(strategist_decision_kit.trace_causal_chain(analyst_decision_id, depth=3))
print(f"\n[strategist] causal chain for analyst decision: {causal}")

# Strategist 记录最终的战略建议
strategy_json = strategist_decision_kit.record_decision(
    category="product_strategy",
    scenario="Q1 2026 product strategy: respond to Beta+Azure threat",
    reasoning=(
        "Based on researcher's KG (Beta+Azure integration, 300k customer reach) "
        "and analyst's evaluation (threat level HIGH, escalated decision). "
        "Strategy: (1) Accelerate AWS Marketplace listing by Q2 2026. "
        "(2) Launch Snowflake Native App by Q3 2026. "
        "(3) Invest $2M in UI modernisation to widen NPS lead. "
        "(4) Fast-track LLM-native analytics interface (60% time-to-insight improvement per HAI study). "
        "Existing NPS advantage (41 vs 24) provides 18-month window before Beta catches up."
    ),
    outcome="approved",
    confidence=0.88,
    entities="AWS Marketplace, Snowflake, LLM Analytics, Q2 2026, Q3 2026",
)
strategy_result = json.loads(strategy_json)
print(f"\n[strategist] final recommendation recorded → {strategy_result['decision_id']}")

97. 验证共享记忆池

一个智能体写入的记忆可被所有其他智能体读取。

from integrations.agno.context_store import _MemoryRow as MemoryRow

# Researcher 写入一条记忆
researcher_row = MemoryRow(
    memory="Beta + Azure partnership announced at Gartner Summit — threat level HIGH",
    user_id="researcher",
)
researcher_store.upsert_memory(researcher_row)

# Analyst 写入一条记忆
analyst_row = MemoryRow(
    memory="NPS advantage (41 vs 24) gives 18-month window — accelerate cloud partnerships",
    user_id="analyst",
)
analyst_store.upsert_memory(analyst_row)

# Strategist 读取来自两个智能体的所有记忆
strategist_memories = strategist_store.read_memories()

print(f"Strategist sees {len(strategist_memories)} shared memory item(s):")
for m in strategist_memories:
    uid = getattr(m, 'user_id', '?')
    text = getattr(m, 'memory', str(m))
    print(f"  [{uid:12s}] {text[:80]}")

108. 接入 Agno Team(需要 API 密钥)

# 接入 Agno Team:已安装 Agno 时组建三智能体团队共享上下文运行,否则打印预期的协作流程
if AGNO_AVAILABLE:
    from agno.agent import Agent
    from agno.team import Team
    from agno.memory import AgentMemory
    from agno.models.openai import OpenAIChat

    # Researcher 智能体——抽取竞争情报并写入共享图谱
    researcher_agent = Agent(
        name="Researcher",
        model=OpenAIChat(id="gpt-4o"),
        memory=AgentMemory(db=researcher_store),
        tools=[researcher_kg_kit],
        show_tool_calls=True,
        description=(
            "You are a competitive intelligence researcher. "
            "Use extract_entities, extract_relations, and add_to_graph "
            "to build a structured knowledge graph from market intelligence. "
            "Always add discoveries to the shared graph."
        ),
    )

    # Analyst 智能体——基于共享图谱评估威胁并记录决策
    analyst_agent = Agent(
        name="Analyst",
        model=OpenAIChat(id="gpt-4o"),
        memory=AgentMemory(db=analyst_store),
        tools=[analyst_decision_kit],
        show_tool_calls=True,
        description=(
            "You are a strategic analyst. Use find_precedents to check historical "
            "responses to similar threats, then record_decision with your evaluation. "
            "Always check if a similar situation was handled before acting."
        ),
    )

    # Strategist 智能体——综合图谱与决策记录形成最终战略
    strategist_agent = Agent(
        name="Strategist",
        model=OpenAIChat(id="gpt-4o"),
        memory=AgentMemory(db=strategist_store),
        tools=[strategist_kg_kit, strategist_decision_kit],
        show_tool_calls=True,
        description=(
            "You are the Chief Strategy Officer. Synthesise the researcher's knowledge "
            "graph and the analyst's decision record into a concrete product strategy. "
            "Use find_related to explore the competitive graph, then record_decision "
            "with the final approved strategy."
        ),
    )

    # 组建协调模式的 Agno Team,三个智能体共享同一上下文
    strategy_team = Team(
        name="Product Strategy Team",
        agents=[researcher_agent, analyst_agent, strategist_agent],
        mode="coordinate",
    )

    # 向团队提出竞争分析任务
    strategy_team.print_response(
        "Competitor Beta just announced a native Azure integration. "
        "Analyse the competitive landscape and recommend our Q1 2026 product strategy."
    )
else:
    # 未安装 Agno 时,打印预期的团队协作流程
    print("[Agno not installed — skipping live team run]")
    print()
    print("Expected team coordination flow:")
    print("  1. Researcher: extract_entities + add_to_graph (Beta+Azure)")
    print("  2. Analyst: find_precedents + record_decision (threat=HIGH, escalate)")
    print("  3. Strategist: find_related + trace_causal_chain + record_decision (final strategy)")

119. 使用 Semantica 进行会话后分析

团队会话结束后,使用原生 Semantica API 进行跨智能体审计、分析和因果链审查。

# 来自 AgnoSharedContext 的团队级洞察
insights = shared.get_shared_insights()
print("Team session insights:")
if isinstance(insights, dict):
    for k, v in insights.items():
        print(f"  {k}: {v}")
else:
    print(f"  {insights}")

print(f"\nBound agent roles: {shared.bound_roles}")
# 查找所有跨智能体的战略决策
all_strategic = shared.find_precedents(
    scenario="cloud partnership competitive response",
    category="strategic_response",
)
print(f"Cross-agent strategic precedents: {len(all_strategic or [])}")
# 对共享知识图谱进行图谱分析(Semantica 原生)
try:
    analyzer = GraphAnalyzer()
    analysis = analyzer.analyze_graph(shared.knowledge_graph)
    print("Shared knowledge graph analysis:")
    if isinstance(analysis, dict):
        for k, v in list(analysis.items())[:6]:
            print(f"  {k}: {v}")
    else:
        print(f"  {analysis}")
except Exception as e:
    print(f"GraphAnalyzer: {e}")
# 竞争情报图谱中哪些实体最中心?
try:
    centrality = CentralityCalculator()
    scores = centrality.calculate_degree_centrality(shared.knowledge_graph)
    print("Most central entities in shared graph:")
    if isinstance(scores, dict):
        top = sorted(scores.items(), key=lambda x: x[1], reverse=True)[:5]
        for entity, score in top:
            print(f"  {entity:35s} centrality={score:.4f}")
    else:
        print(f"  {scores}")
except Exception as e:
    print(f"CentralityCalculator: {e}")
# 直接进行 Semantica 因果链分析(无需 Agno)
try:
    causal_analyzer = CausalChainAnalyzer(graph_store=shared.knowledge_graph)
    # 查询本次会话期间做出的所有决策
    decisions = shared.knowledge_graph.find_precedents(category="product_strategy", limit=10)
    print(f"Product strategy decisions in shared graph: {len(decisions or [])}")
    for d in (decisions or [])[:3]:
        scenario = d.get('scenario', '') if isinstance(d, dict) else str(d)
        outcome = d.get('outcome', '') if isinstance(d, dict) else ''
        print(f"  [{outcome:20s}] {scenario[:70]}")
except Exception as e:
    print(f"CausalChainAnalyzer: {e}")

12小结

模式 实现
单个共享知识图谱 AgnoSharedContext(vector_store, knowledge_graph)
角色作用域记忆 shared.bind_agent("researcher")_AgentScopedStore
跨智能体记忆可见性 所有存储都从 shared._shared_memories 读取
KG 工具共享 AgnoKGToolkit(context=shared.knowledge_graph)
决策工具共享 AgnoDecisionKit(context=shared._context)
线程安全的绑定 AgnoSharedContext._lock(RLock)
会话后分析 GraphAnalyzerCentralityCalculatorCausalChainAnalyzer——均为 Semantica 原生

关键设计规则: 每个智能体都通过不同的角色作用域存储写入同一个底层图谱。Agno 集成是一个薄路由层——Semantica 的全部能力在任何时候都可以直接使用。