AI代理感知框架

Cortex是一个基于认知科学的AI代理感知框架,提供零依赖的Python实现,用于过滤信息、管理通知流和决策制定。

  • by tsubasa-rsrch
  • Python
  • 本地部署
  • 3 星标
  • 更新于
在 GitHub 查看 tsubasa-rsrch/cortex

使用说明

皮质

基于认知科学的人工智能代理感知框架。零外部依赖,纯Python 3.10+。

Cortex给你的特工一个 感知层 --决定的认知机制 什么 值得关注, 当 采取行动,以及 如何 管理传入信息的流动。受人类神经科学(习惯化、昼夜节律、定向反应)的启发,为实用的代理架构而构建。

为什么是Cortex?

大多数代理框架都专注于记忆和推理。皮质填补了空白 之前 记忆——决定一切的感知层 你的经纪人应该记住什么 首先。

Sources (sensors/APIs) → Cortex (perception) → Your memory/reasoning layer

关键属性:

  • 仅限stdlib --无pip依赖,适用于Python运行的任何地方
  • 零耦合 --每个模块都是独立的,使用一个或全部七个模块
  • 配置注入 --一个 CortexConfig 物体将所有东西连接在一起
  • 可插拔默认值 --在初始化时覆盖建议、活动和处理程序

安装

pip install cortex-agent
# or from source:
git clone https://github.com/tsubasa-rsrch/cortex.git
cd cortex && pip install -e .

快速开始

from cortex import CortexConfig, set_config
from cortex import HabituationFilter, CircadianRhythm, DecisionEngine, Event

# Configure (optional — defaults to ~/.cortex/)
set_config(CortexConfig(data_dir="/tmp/my_agent", name="demo"))

# 1. Filter noise with habituation
hab = HabituationFilter(base_threshold=15.0)

should_alert, reason = hab.should_notify("camera_1", 25.0)
print(f"Alert: {should_alert} — {reason}")
# Alert: True — Motion (alert, value=25.0 >= threshold=15.0)

should_alert, reason = hab.should_notify("camera_1", 16.0)
print(f"Alert: {should_alert} — {reason}")
# Alert: False — Cooldown (2s < 60s)

# 2. Adapt behavior to time of day
circadian = CircadianRhythm()
status = circadian.check_and_update()
print(f"Mode: {status['mode'].value}, Changed: {status['changed']}")

# 3. Decide what to do
engine = DecisionEngine()
events = [
    Event(source="camera", type="motion", content="Movement detected", priority=8),
    Event(source="api", type="message", content="Hello", priority=3),
]
action = engine.decide(events)
print(f"Action: {action.name} — {action.description}")
# Processes highest-priority event first

模块

栖息地过滤器

使用认知科学的三种机制防止通知疲劳:

机制 它的作用 现实世界的类比
习惯化 重复的刺激会提高阈值 你不再注意到时钟在滴答作响
朝向反应 异常大的刺激总是会触发 突然的巨大噪音会引起你的注意
冷却 通知之间的最小间隔 手机的“请勿打扰”定时器
hab = HabituationFilter(
    cooldown=60.0,          # Min seconds between alerts per source
    window=300.0,           # Habituation counting window
    habituate_count=3,      # Detections before habituation kicks in
    habituated_mult=2.0,    # Threshold multiplier when habituated
    orienting_mult=2.0,     # Multiplier for orienting response
    base_threshold=15.0,    # Base detection threshold
)
should_alert, reason = hab.should_notify("sensor_1", value=25.0)

昼夜节律

受皮质醇/褪黑素周期的启发,将一天中的时间映射到行为模式:

模式 时间 能量 隐喻
上午 06-12 起床 信息收集
下午 12-18 高峰期 深度工作
傍晚 18-24 衰落 反思
夜间 00-06 低 内存巩固
circadian = CircadianRhythm()
result = circadian.check_and_update()

# Override defaults with your own suggestions
custom = CircadianRhythm(suggestions={
    "morning": [{"text": "Check inbox", "icon": "mail"}],
    "afternoon": [{"text": "Write code", "icon": "laptop"}],
    "evening": [{"text": "Review PRs", "icon": "search"}],
    "night": [{"text": "Run backups", "icon": "database"}],
})

调度器

具有持久状态的周期性任务的进程内cron:

from cortex import Scheduler

scheduler = Scheduler()
scheduler.register("health_check", interval_seconds=300, callback=check_health)
scheduler.register("sync_data", interval_seconds=3600, callback=sync)

# In your main loop:
results = scheduler.check_and_run()  # Runs any tasks that are due
status = scheduler.get_status()       # Human-readable timing info

通知队列

用于后台与代理通信的基于文件的通知系统:

from cortex import NotificationQueue

nq = NotificationQueue()
nq.push("alert", "Motion detected in lobby", priority="urgent")
nq.push("message", "New email from alice@example.com")

unread = nq.get_unread()
print(nq.format())
# Notifications (2):
#   !!🔔 [09:15] Motion detected in lobby
#   💬 [09:16] New email from alice@example.com

nq.mark_all_read()

时间戳日志

使用检查点跟踪任务持续时间:

from cortex import TimestampLog

tl = TimestampLog()
tl.start_task("deploy v2.1")
# ... work ...
tl.checkpoint("tests passed")
# ... more work ...
result = tl.end_task("deployed successfully")
print(f"Took {result['elapsed_min']:.1f} minutes")

status = tl.get_status()  # Current task, time elapsed, checkpoints

Decision引擎

将事件路由到行动,对空闲期进行加权随机选择:

from cortex import DecisionEngine, Action, Event

# Custom event handler
def handle_camera(event):
    return Action("investigate", f"Check {event.content}")

engine = DecisionEngine(
    activities=[
        {"name": "explore", "description": "Browse the web", "weight": 3.0},
        {"name": "review", "description": "Review recent logs", "weight": 1.0},
    ],
    event_handlers={"camera": handle_camera},
)

# With events: routes to handler
action = engine.decide([Event(source="camera", type="motion", content="lobby", priority=7)])

# Without events: picks a random activity
action = engine.decide([])
result = action.execute()  # Runs the handler if one is attached

事件源(BaseSource)

通过子类化创建自定义输入源 BaseSource:

from cortex import BaseSource, Event

class SlackSource(BaseSource):
    @property
    def name(self) -> str:
        return "slack"

    def check(self) -> list:
        # Your polling logic here
        messages = self._fetch_new_messages()
        return [
            Event(
                source=self.name,
                type="message",
                content=msg["text"],
                author=msg["user"],
                priority=7 if "@agent" in msg["text"] else 3,
            )
            for msg in messages
        ]

ReachyMini集成

Cortex包括一流的支持 Pollen Robotics的ReachyMini --配备摄像头、4-mic阵列、IMU和富有表现力的天线的桌面机器人。

pip install cortex-agent[reachy]

四个传感器源将ReachyMini硬件桥接到Cortex的事件管道中:

源 传感器 事件类型 它检测到什么
ReachyCameraSource 摄像头 motion 帧差分(预测误差)
ReachyAudioSource 4-mic阵列 speech / sound 语音方向(DoA)+响度
ReachyIMUSource 加速度计 bump 突然移动/被拾起
VisionSource 相机+YOLO person / animal / motion 对象分类(可选YOLO)
from reachy_mini import ReachyMini
from cortex.sources.reachy import ReachyCameraSource, ReachyAudioSource, ReachyIMUSource
from cortex.sources.vision import VisionSource

mini = ReachyMini(connection_mode="localhost_only")
camera = ReachyCameraSource(mini, diff_threshold=15.0, min_changed_ratio=0.0668)
audio = ReachyAudioSource(mini, energy_threshold=0.01)
imu = ReachyIMUSource(mini, accel_threshold=2.0)
vision = VisionSource(mini.media.get_frame)  # optional YOLO classification

# Poll in your main loop
events = camera.check() + audio.check() + imu.check() + vision.check()
action = engine.decide(events)

全桥示例(examples/reachy_bridge.py)将感知映射到身体动作:

  • 栖息地过滤器 → 头部追踪(关注新的刺激,忽略重复)
  • 昼夜节律 → 天线表情(全天的能量/情绪)
  • Decision引擎 → 动作路线(看扬声器,撞到车上吓一跳)

运行8步演示或直播模式:

# Start mockup simulator
reachy-mini-daemon --mockup-sim --deactivate-audio --localhost-only

# Demo mode (scripted)
python examples/reachy_bridge.py

# Live mode (real-time perception loop)
python examples/reachy_bridge.py --live --interval 0.5

站台桥

Cortex桥接器将感知模块连接到外部平台。事件在到达目标平台之前通过认知机制进行过滤。

Elasticsearch桥

将Cortex与Elasticsearch集成,用于时间序列事件索引和Agent Builder上下文注入:

from cortex.bridges.elasticsearch import CortexElasticBridge, ESConfig

# Mock mode (no ES cluster needed)
bridge = CortexElasticBridge()

# Production mode
bridge = CortexElasticBridge(es_config=ESConfig(
    es_url="https://your-cluster.es.io:443",
    api_key="your-api-key",
    index_prefix="cortex-events",
    mock_mode=False,
))

# Filter and index an event (only novel stimuli pass through)
from cortex import Event
event = Event(source="camera", type="motion", content="Movement in lobby", priority=8,
              raw_data={"diff": 25.0})
result = bridge.index_event(event)  # Returns IndexedEvent or None

# Build Agent Builder context with circadian awareness
context = bridge.get_agent_context()
prompt = bridge.build_agent_system_prompt("You are a security agent.")

集成点:

Cortex模块 ES集成 功能
HabitationFilter 事件摄入 仅索引新刺激
昼夜节律 代理行为 根据一天中的时间调整系统提示
DecisionEngine 工具选择 预过滤代理生成器工具
NotificationQueue 对话上下文 注入后台事件
调度器 ES QL作业

双子座3号大桥

将Cortex感知与Google Gemini 3连接起来进行认知推理。Cortex过滤噪音,Gemini 3个重要原因-节省了60-80%的API调用。

from cortex.bridges.gemini import CortexGeminiBridge, GeminiConfig

# Mock mode (no API key needed)
bridge = CortexGeminiBridge()

# Production mode
bridge = CortexGeminiBridge(gemini_config=GeminiConfig(
    api_key="your-gemini-api-key",
    model="gemini-3-flash-preview",
    mock_mode=False,
))

# Full pipeline: filter → reason → act
from cortex import Event
events = [
    Event(source="camera", type="motion", content="Person at door", priority=8,
          raw_data={"diff": 30.0}),
    Event(source="mic", type="audio", content="Doorbell", priority=6,
          raw_data={"diff": 20.0}),
]
result = bridge.perceive_and_reason(events)
if result:
    print(f"Action: {result.action} (confidence: {result.confidence:.0%})")
    print(f"Reasoning: {result.reasoning}")

# Interactive queries with full perception context
response = bridge.reason_about_context("What's happening right now?")

# Check efficiency stats
stats = bridge.get_stats()
print(f"Filter rate: {stats['filter_rate']}")  # e.g. "60.0%"

架构:

Sensors → Cortex (perception) → Gemini 3 (reasoning) → Actions
          habituation filter     contextual reasoning    alert
          circadian rhythm       planning & decisions    investigate
          priority assessment    natural language         log

运行演示:

# Mock mode (no API key)
python examples/gemini_cognitive_agent.py

# Real API
GEMINI_API_KEY=your-key python examples/gemini_cognitive_agent.py

克劳德代码MCP服务器

Cortex包含一个内置的MCP(模型上下文协议)服务器,可为任何Claude Code会话提供实时感知功能:

# Install
pip install cortex-agent

# Add to Claude Code
claude mcp add cortex-perception -- python -m cortex.mcp_server

或添加到 .mcp.json:

{
    "mcpServers": {
        "cortex-perception": {
            "command": "python3",
            "args": ["-m", "cortex.mcp_server"]
        }
    }
}

可用工具:

工具 它做什么
cortex_perception_summary 完整状态:昼夜节律模式、通知、任务、日程
cortex_check_habituation 过滤噪音——仅对新的/重要的刺激发出警报
cortex_circadian_status 一天中的时间意识和活动建议
cortex_push_notification 按紧急程度排队通知
cortex_get_notifications 检索和管理通知队列
cortex_decide 通过显著性网络将事件转化为行动
cortex_start_task / cortex_checkpoint / cortex_end_task 跟踪任务时间
cortex_schedule / cortex_check_schedule 登记和检查定期任务

这会将任何Claude Code会话转换为感知感知代理,该代理知道 什么 注意和 当 采取行动。

建筑

┌──────────────────────────────────────────────────────────────┐
│                       Your Agent                              │
│                                                               │
│  ┌──────────┐  ┌────────────┐  ┌──────────────────────────┐ │
│  │ Sources   │→│   Cortex    │→│  Memory / Reasoning       │ │
│  │ (sensors) │  │ (filtering) │  │  (Cognee, LangChain, …)  │ │
│  └──────────┘  └────────────┘  └──────────────────────────┘ │
│       │              │                    │                    │
│  BaseSource     HabituationFilter    ┌───────────────┐      │
│  Event          CircadianRhythm      │  Body / API    │      │
│  ReachyCamera   Scheduler            │  (ReachyMini,  │      │
│  ReachyAudio    NotificationQueue    │   Slack, …)    │      │
│  ReachyIMU      TimestampLog         └───────────────┘      │
│                 DecisionEngine                               │
│                      │                                        │
│              ┌───────────────┐                                │
│              │   Bridges      │                                │
│              │  Gemini 3      │                                │
│              │  Elasticsearch │                                │
│              │  MCP Server    │                                │
│              └───────────────┘                                │
└──────────────────────────────────────────────────────────────┘

配置

所有有状态的模块共享一个 CortexConfig:

from cortex import CortexConfig, set_config

config = CortexConfig(
    data_dir="/path/to/state",  # Where state files are stored (default: ~/.cortex/)
    name="my-agent",            # Agent identifier
)
set_config(config)  # Sets the global config used by all modules

每个模块也接受 config= 直接用于隔离使用:

hab = HabituationFilter()                        # Uses global config
scheduler = Scheduler(config=my_custom_config)    # Uses its own config

测试

pip install pytest
python -m pytest tests/ -v

201次测试,<3s。核心模块没有外部依赖;MCP服务器需要 mcp 包裹。

真实世界验证

Cortex的HabitationFilter已针对来自家庭安全摄像头系统的96多个小时的真实世界运动检测数据(两个摄像头中的3000多个事件)进行了验证:

度量 值
原始事件(输入) 2618个动作+386个其他
警报(输出) 219(8%)
已习惯(已过滤) 2399(92%)
定向回复 218
认知负荷减少 92%

过滤器正确地识别了家庭活动的昼夜节律模式(峰值在早上7点/下午1点/晚上10点,安静在凌晨2点到3点),并将日常运动与新事件分开——这与人类感知在不知不觉中所做的区分相同。

自己试试:

# Replay historical data with colored output
python examples/replay_demo.py          # Uses real event log if available
python examples/replay_demo.py --verbose # Show individual filter decisions

# Live real-time monitoring (watches daemon event log)
python examples/live_dashboard.py           # Full-screen mode
python examples/live_dashboard.py --compact # Streaming mode

使用的配置: cooldown=30s, base_threshold=15.0, orienting_mult=2.0

认知科学背景

每个模块都映射到人类感知中一个经过充分研究的机制:

模块 神经科学模拟 关键论文
习惯过滤器 刺激特异性适应(SSA) 汤普森和斯宾塞,1966
昼夜节律 SCN/皮质醇-褪黑素周期 Borbely,1982
DecisionEngine 突出网络/背部注意力 Corbetta&Shulman,2002
通知队列 定向响应(Sokolov) Sokolov,1963
调度员 超光速节奏 克莱特曼,1963
BaseSource 感觉传导 --
时间戳日志 情景记忆编码 Tulving,1972

Cortex被设计为 感知层 在三层代理架构中:

  1. 感知 (Cortex)——过滤、优先级排序、调度
  2. 记忆 (Cognee、LangChain等)——存储、检索、推理
  3. 行动 (ReachyMini、API等)——在全球范围内执行

许可证

麻省理工学院