smart_brain 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE +21 -0
  3. data/README.en.md +173 -0
  4. data/README.md +173 -0
  5. data/agents/brain_assistant.rb +11 -0
  6. data/config/brain.yml +32 -0
  7. data/conversation_demo.rb +438 -0
  8. data/db/migrate/001_init.sql +98 -0
  9. data/example.rb +91 -0
  10. data/lib/smart_brain/adapters/smart_rag/direct_client.rb +47 -0
  11. data/lib/smart_brain/adapters/smart_rag/http_client.rb +61 -0
  12. data/lib/smart_brain/adapters/smart_rag/null_client.rb +22 -0
  13. data/lib/smart_brain/configuration.rb +41 -0
  14. data/lib/smart_brain/consolidator/working_summary.rb +102 -0
  15. data/lib/smart_brain/context_composer/composer.rb +75 -0
  16. data/lib/smart_brain/contracts/context_package.rb +16 -0
  17. data/lib/smart_brain/contracts/evidence_pack.rb +16 -0
  18. data/lib/smart_brain/contracts/retrieval_plan.rb +17 -0
  19. data/lib/smart_brain/event_store/in_memory.rb +103 -0
  20. data/lib/smart_brain/fusion/merger.rb +137 -0
  21. data/lib/smart_brain/memory_extractor/extractor.rb +92 -0
  22. data/lib/smart_brain/memory_store/in_memory.rb +78 -0
  23. data/lib/smart_brain/observability/tracker.rb +60 -0
  24. data/lib/smart_brain/retrieval_planner/planner.rb +122 -0
  25. data/lib/smart_brain/retrievers/exact_retriever.rb +62 -0
  26. data/lib/smart_brain/retrievers/memory_retriever.rb +30 -0
  27. data/lib/smart_brain/retrievers/relational_retriever.rb +53 -0
  28. data/lib/smart_brain/runtime.rb +195 -0
  29. data/lib/smart_brain/version.rb +5 -0
  30. data/lib/smart_brain.rb +35 -0
  31. data/templates/brain_assistant.erb +5 -0
  32. data/workers/brain_assistant.rb +9 -0
  33. metadata +283 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 034abbb06e5d99b9bda6b84d3934270e47f8406ff78f78b6bc8c269941bd0504
4
+ data.tar.gz: a48aec950053b94adb32798c47f0ed2c0a81be794fd74911547c3f68a924b477
5
+ SHA512:
6
+ metadata.gz: 88c1ccdfdd8a6bd7e3fd0350127e1f4f040a5cd3103601210705960f7db7d6e9a08e595be4725efb4f7b532cbb3a42263f0aaa2b085dee1f5a7e07a2c38df865
7
+ data.tar.gz: e6059ec7ca9c966781b0e19db2068916f8c8c9aa09ab344b87be23f902df6d7e889d90a2ef7d1e655ed4ae97f9ae4ebce846fa136c3dc20e2f3ca21d8bf62c59
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 zhuang biaowei
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.en.md ADDED
@@ -0,0 +1,173 @@
1
+ # SmartBrain
2
+
3
+ SmartBrain is an Agent Memory Runtime and Context Composer.
4
+
5
+ Core responsibilities:
6
+ - `commit_turn`: persist event truth and structured memory
7
+ - `compose_context`: build minimal, sufficient context per turn
8
+ - integrate with SmartRAG: SmartBrain handles conversation memory, SmartRAG handles resource retrieval
9
+
10
+ ## Current Progress
11
+
12
+ The repository now includes a runnable v0.1 flow with:
13
+ - `commit_turn` / `compose_context` end-to-end pipeline
14
+ - retention / consolidation / retrieval / composition policies
15
+ - retrievers: exact + relational
16
+ - fusion: dedupe, rule-based rerank, diversity, budget truncation
17
+ - SmartRAG adapters: `NullClient`, `HttpClient`, `DirectClient`
18
+ - traceability via `request_id` / `plan_id` / `context_id`
19
+ - RSpec coverage (unit + integration + regression)
20
+
21
+ ## Project Layout
22
+
23
+ - `lib/smart_brain.rb`: public API
24
+ - `lib/smart_brain/runtime.rb`: runtime orchestration
25
+ - `lib/smart_brain/contracts/`: RetrievalPlan / EvidencePack / ContextPackage validation
26
+ - `lib/smart_brain/observability/`: logs and metrics
27
+ - `lib/smart_brain/event_store/`: event storage (in-memory currently)
28
+ - `lib/smart_brain/memory_store/`: memory storage (in-memory currently)
29
+ - `lib/smart_brain/retrievers/`: exact/relational retrievers
30
+ - `lib/smart_brain/fusion/`: multi-source fusion
31
+ - `lib/smart_brain/context_composer/`: context assembly
32
+ - `lib/smart_brain/adapters/smart_rag/`: SmartRAG adapters
33
+ - `config/brain.yml`: policy config
34
+ - `example.rb`: SmartBrain + SmartAgent + SmartPrompt + SmartRAG demo
35
+ - `docs/`: design and protocol documents
36
+
37
+ ## Installation
38
+
39
+ ```bash
40
+ bundle install
41
+ ```
42
+
43
+ If you hit permission/shared-gem issues:
44
+
45
+ ```bash
46
+ bundle config set --local path 'vendor/bundle'
47
+ bundle config set --local disable_shared_gems 'true'
48
+ ```
49
+
50
+ ## Quick Start (SmartBrain Only)
51
+
52
+ ```ruby
53
+ require_relative 'lib/smart_brain'
54
+
55
+ SmartBrain.configure
56
+
57
+ SmartBrain.commit_turn(
58
+ session_id: 'demo',
59
+ turn_events: {
60
+ messages: [
61
+ { role: 'user', content: 'Remember this: default DB is Postgres.' },
62
+ { role: 'assistant', content: 'Saved.' }
63
+ ],
64
+ decisions: [
65
+ { key: 'decision:smartbrain:storage', decision: 'Use Postgres by default' }
66
+ ]
67
+ }
68
+ )
69
+
70
+ context = SmartBrain.compose_context(
71
+ session_id: 'demo',
72
+ user_message: 'Continue and summarize key points'
73
+ )
74
+
75
+ puts context[:context_id]
76
+ puts context.dig(:debug, :trace, :request_id)
77
+ puts context.dig(:debug, :trace, :plan_id)
78
+ ```
79
+
80
+ ## SmartRAG Integration Options
81
+
82
+ ### 1) NullClient (default)
83
+
84
+ If no SmartRAG client is injected, resource evidence is empty.
85
+
86
+ ### 2) HttpClient
87
+
88
+ ```ruby
89
+ transport = lambda do |plan, timeout_seconds:|
90
+ {
91
+ plan_id: 'p1',
92
+ supports_language_filter: true,
93
+ evidences: []
94
+ }
95
+ end
96
+
97
+ client = SmartBrain::Adapters::SmartRag::HttpClient.new(transport: transport, timeout_seconds: 2)
98
+ SmartBrain.configure(smart_rag_client: client)
99
+ ```
100
+
101
+ ### 3) DirectClient (used in `example.rb`)
102
+
103
+ ```ruby
104
+ require '/home/mlf/smart_ai/smart_rag/lib/smart_rag'
105
+ require_relative 'lib/smart_brain/adapters/smart_rag/direct_client'
106
+
107
+ rag_config = SmartRAG::Config.load('/home/mlf/smart_ai/smart_rag/config/smart_rag.yml')
108
+ rag = SmartRAG::SmartRAG.new(rag_config)
109
+ client = SmartBrain::Adapters::SmartRag::DirectClient.new(rag: rag)
110
+
111
+ SmartBrain.configure(smart_rag_client: client)
112
+ ```
113
+
114
+ ## `example.rb` (Updated)
115
+
116
+ The example demonstrates the real loop:
117
+ 1. SmartBrain `compose_context`
118
+ 2. SmartAgent calls SmartPrompt worker via `call_worker`
119
+ 3. SmartBrain `commit_turn`
120
+ 4. prints `evidence(memory/resource)` so you can verify SmartRAG participation
121
+
122
+ Files used by the demo:
123
+ - `config/example_agent.yml`
124
+ - `config/example_llm.yml`
125
+ - `agents/brain_assistant.rb`
126
+ - `workers/brain_assistant.rb`
127
+ - `templates/brain_assistant.erb`
128
+
129
+ Run:
130
+
131
+ ```bash
132
+ bundle exec ruby example.rb
133
+ ```
134
+
135
+ ## Core API
136
+
137
+ ### `SmartBrain.configure(config_path: nil, smart_rag_client: nil, clock: -> { Time.now.utc })`
138
+ Initialize runtime and optionally inject a SmartRAG client.
139
+
140
+ ### `SmartBrain.commit_turn(session_id:, turn_events:)`
141
+ Persist events, extract memory, resolve conflicts, update summary.
142
+
143
+ ### `SmartBrain.compose_context(session_id:, user_message:, agent_state: {})`
144
+ Build a `ContextPackage` with planning and fused evidence.
145
+
146
+ ### `SmartBrain.diagnostics`
147
+ Return observability snapshot for compose/commit logs and metrics.
148
+
149
+ ## Test
150
+
151
+ ```bash
152
+ rspec
153
+ ```
154
+
155
+ ## Troubleshooting
156
+
157
+ ### 1) `cannot load such file -- sequel/extensions/pgvector`
158
+ `example.rb` already applies compatibility handling (`Sequel.extension 'pgvector'` and strips `database.extensions` from DB connect config).
159
+
160
+ ### 2) `Config file not found: config/llm_config.yml`
161
+ `example.rb` injects `config_path: ./config/example_llm.yml` for SmartRAG EmbeddingService startup.
162
+
163
+ ### 3) `ruby-lsp: not found`
164
+ ```bash
165
+ gem install --user-install ruby-lsp debug
166
+ ```
167
+ and ensure user gem `bin` is in `PATH`.
168
+
169
+ ## Roadmap
170
+
171
+ - migrate EventStore/MemoryStore from in-memory to Postgres-backed implementations
172
+ - integrate real reranker/embedding models
173
+ - improve SmartRAG ingest pipeline and cross-session evaluation tooling
data/README.md ADDED
@@ -0,0 +1,173 @@
1
+ # SmartBrain
2
+
3
+ SmartBrain 是一个面向 Agent 的记忆运行时(Memory Runtime)与上下文编排器(Context Composer)。
4
+
5
+ 它的核心职责:
6
+ - `commit_turn`:记录事件真相并沉淀结构化记忆
7
+ - `compose_context`:在每轮请求前组装最小充分上下文
8
+ - 联动 SmartRAG:对话记忆由 SmartBrain 管理,资源检索由 SmartRAG 提供
9
+
10
+ ## 当前进展
11
+
12
+ 当前仓库已实现并打通:
13
+ - `commit_turn` / `compose_context` 主链路
14
+ - Retention / Consolidation / Retrieval / Composition 策略
15
+ - 检索器:exact + relational
16
+ - 融合层:去重、规则重排、多样性、预算截断
17
+ - SmartRAG 适配器:`NullClient` / `HttpClient` / `DirectClient`
18
+ - 契约与可观测:`request_id` / `plan_id` / `context_id` 全链路追踪
19
+ - RSpec 测试(单元 + 集成 + 回归)
20
+
21
+ ## 项目结构
22
+
23
+ - `lib/smart_brain.rb`:入口 API
24
+ - `lib/smart_brain/runtime.rb`:主运行时编排
25
+ - `lib/smart_brain/contracts/`:RetrievalPlan / EvidencePack / ContextPackage 校验
26
+ - `lib/smart_brain/observability/`:日志与指标
27
+ - `lib/smart_brain/event_store/`:事件存储(当前内存实现)
28
+ - `lib/smart_brain/memory_store/`:记忆存储(当前内存实现)
29
+ - `lib/smart_brain/retrievers/`:exact/relational 检索
30
+ - `lib/smart_brain/fusion/`:多源融合
31
+ - `lib/smart_brain/context_composer/`:上下文装配
32
+ - `lib/smart_brain/adapters/smart_rag/`:SmartRAG 适配层
33
+ - `config/brain.yml`:策略配置
34
+ - `example.rb`:SmartBrain + SmartAgent + SmartPrompt + SmartRAG 联动示例
35
+ - `docs/`:设计与协议文档
36
+
37
+ ## 安装
38
+
39
+ ```bash
40
+ bundle install
41
+ ```
42
+
43
+ 如遇本地权限或 shared gem 污染,建议:
44
+
45
+ ```bash
46
+ bundle config set --local path 'vendor/bundle'
47
+ bundle config set --local disable_shared_gems 'true'
48
+ ```
49
+
50
+ ## 快速开始(仅 SmartBrain)
51
+
52
+ ```ruby
53
+ require_relative 'lib/smart_brain'
54
+
55
+ SmartBrain.configure
56
+
57
+ SmartBrain.commit_turn(
58
+ session_id: 'demo',
59
+ turn_events: {
60
+ messages: [
61
+ { role: 'user', content: '请记住:默认数据库是 Postgres。' },
62
+ { role: 'assistant', content: '已记录。' }
63
+ ],
64
+ decisions: [
65
+ { key: 'decision:smartbrain:storage', decision: 'Use Postgres by default' }
66
+ ]
67
+ }
68
+ )
69
+
70
+ context = SmartBrain.compose_context(
71
+ session_id: 'demo',
72
+ user_message: '继续并总结关键结论'
73
+ )
74
+
75
+ puts context[:context_id]
76
+ puts context.dig(:debug, :trace, :request_id)
77
+ puts context.dig(:debug, :trace, :plan_id)
78
+ ```
79
+
80
+ ## SmartRAG 集成方式
81
+
82
+ ### 1) NullClient(默认)
83
+
84
+ 不配置 `smart_rag_client` 时,资源证据为空,仅使用记忆侧证据。
85
+
86
+ ### 2) HttpClient
87
+
88
+ ```ruby
89
+ transport = lambda do |plan, timeout_seconds:|
90
+ {
91
+ plan_id: 'p1',
92
+ supports_language_filter: true,
93
+ evidences: []
94
+ }
95
+ end
96
+
97
+ client = SmartBrain::Adapters::SmartRag::HttpClient.new(transport: transport, timeout_seconds: 2)
98
+ SmartBrain.configure(smart_rag_client: client)
99
+ ```
100
+
101
+ ### 3) DirectClient(当前示例使用)
102
+
103
+ ```ruby
104
+ require '/home/mlf/smart_ai/smart_rag/lib/smart_rag'
105
+ require_relative 'lib/smart_brain/adapters/smart_rag/direct_client'
106
+
107
+ rag_config = SmartRAG::Config.load('/home/mlf/smart_ai/smart_rag/config/smart_rag.yml')
108
+ rag = SmartRAG::SmartRAG.new(rag_config)
109
+ client = SmartBrain::Adapters::SmartRag::DirectClient.new(rag: rag)
110
+
111
+ SmartBrain.configure(smart_rag_client: client)
112
+ ```
113
+
114
+ ## example.rb 说明(已更新)
115
+
116
+ `example.rb` 演示完整链路:
117
+ 1. SmartBrain `compose_context`
118
+ 2. SmartAgent 通过 `call_worker` 调用 SmartPrompt worker
119
+ 3. SmartBrain `commit_turn`
120
+ 4. 打印 `evidence(memory/resource)` 验证 SmartRAG 是否参与
121
+
122
+ 示例依赖的本地文件:
123
+ - `config/example_agent.yml`
124
+ - `config/example_llm.yml`
125
+ - `agents/brain_assistant.rb`
126
+ - `workers/brain_assistant.rb`
127
+ - `templates/brain_assistant.erb`
128
+
129
+ 运行:
130
+
131
+ ```bash
132
+ bundle exec ruby example.rb
133
+ ```
134
+
135
+ ## 核心 API
136
+
137
+ ### `SmartBrain.configure(config_path: nil, smart_rag_client: nil, clock: -> { Time.now.utc })`
138
+ 初始化运行时并注入 SmartRAG 客户端(可选)。
139
+
140
+ ### `SmartBrain.commit_turn(session_id:, turn_events:)`
141
+ 写入事件、抽取记忆、冲突处理、摘要更新。
142
+
143
+ ### `SmartBrain.compose_context(session_id:, user_message:, agent_state: {})`
144
+ 生成 `ContextPackage`,内部包含检索计划与证据融合结果。
145
+
146
+ ### `SmartBrain.diagnostics`
147
+ 返回 compose/commit 观测日志与指标快照。
148
+
149
+ ## 测试
150
+
151
+ ```bash
152
+ rspec
153
+ ```
154
+
155
+ ## 常见问题
156
+
157
+ ### 1) `cannot load such file -- sequel/extensions/pgvector`
158
+ 当前示例已在 `example.rb` 做兼容处理(`Sequel.extension 'pgvector'` + 去除 `database.extensions` 连接参数)。
159
+
160
+ ### 2) `Config file not found: config/llm_config.yml`
161
+ `example.rb` 已将 SmartRAG 里 EmbeddingService 的 `config_path` 注入为 `./config/example_llm.yml`。
162
+
163
+ ### 3) `ruby-lsp: not found`
164
+ ```bash
165
+ gem install --user-install ruby-lsp debug
166
+ ```
167
+ 并将用户 gem bin 加入 `PATH`。
168
+
169
+ ## 路线图
170
+
171
+ - 将 EventStore/MemoryStore 从内存实现切换到 Postgres 实现
172
+ - 接入真实 reranker / embedding 模型
173
+ - 完善 SmartRAG ingest 与跨会话评估工具
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ SmartAgent.define :brain_assistant do
4
+ result = call_worker(:brain_assistant_worker, params, with_tools: false, with_history: true)
5
+ if result.call_tools
6
+ call_tools(result)
7
+ params[:text] = 'Please continue.'
8
+ result = call_worker(:brain_assistant_worker, params, with_tools: false, with_history: true)
9
+ end
10
+ result.content
11
+ end
data/config/brain.yml ADDED
@@ -0,0 +1,32 @@
1
+ policies:
2
+ retention:
3
+ summarize_after_turns: 12
4
+ entity_gate:
5
+ window_turns: 20
6
+ freq_threshold: 2
7
+ confidence:
8
+ user_asserted: 0.8
9
+ tool_derived: 0.9
10
+ inferred: 0.6
11
+ retrieval:
12
+ enable_resource_retrieval: auto
13
+ top_k: 30
14
+ candidate_k: 200
15
+ query_expansion:
16
+ enabled: true
17
+ max_queries: 8
18
+ composition:
19
+ token_limit: 8192
20
+ system_blocks_max_tokens: 800
21
+ summary_max_tokens: 600
22
+ recent_turns_max: 8
23
+ evidence_max_items: 12
24
+ max_snippet_chars: 800
25
+ diversity:
26
+ by_document: 3
27
+ by_source_uri: 2
28
+ memory_resource_ratio: '40/60'
29
+ observability:
30
+ trace: true
31
+ store_plans: true
32
+ store_contexts: true