open-source-alchemy-framework 1.0.1__py3-none-any.whl

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 (51) hide show
  1. oaf/__init__.py +47 -0
  2. oaf/adapters/__init__.py +9 -0
  3. oaf/adapters/base.py +40 -0
  4. oaf/adapters/desktop_pet.py +254 -0
  5. oaf/adapters/local_chat.py +47 -0
  6. oaf/adapters/mock_environment.py +27 -0
  7. oaf/adapters/state.py +109 -0
  8. oaf/core/__init__.py +6 -0
  9. oaf/core/coordination.py +69 -0
  10. oaf/core/event_processing.py +51 -0
  11. oaf/core/lifecycle.py +15 -0
  12. oaf/core/soul_core.py +162 -0
  13. oaf/core/status.py +29 -0
  14. oaf/modules/__init__.py +10 -0
  15. oaf/modules/base.py +39 -0
  16. oaf/modules/llm.py +36 -0
  17. oaf/modules/memory.py +50 -0
  18. oaf/modules/personality.py +46 -0
  19. oaf/modules/wishes.py +52 -0
  20. oaf/protocols.py +445 -0
  21. oaf/resources.py +29 -0
  22. open_source_alchemy_framework-1.0.1.dist-info/METADATA +221 -0
  23. open_source_alchemy_framework-1.0.1.dist-info/RECORD +51 -0
  24. open_source_alchemy_framework-1.0.1.dist-info/WHEEL +5 -0
  25. open_source_alchemy_framework-1.0.1.dist-info/licenses/LICENSE +201 -0
  26. open_source_alchemy_framework-1.0.1.dist-info/top_level.txt +3 -0
  27. protocols/README.md +26 -0
  28. protocols/__init__.py +1 -0
  29. protocols/events/__init__.py +1 -0
  30. protocols/events/event-result.schema.json +15 -0
  31. protocols/events/event.schema.json +21 -0
  32. protocols/expressions/__init__.py +1 -0
  33. protocols/expressions/action-feedback.schema.json +16 -0
  34. protocols/expressions/action.schema.json +17 -0
  35. protocols/expressions/capability.schema.json +15 -0
  36. protocols/expressions/expression.schema.json +16 -0
  37. protocols/expressions/playback.schema.json +17 -0
  38. protocols/expressions/safety.schema.json +14 -0
  39. protocols/expressions/speech.schema.json +16 -0
  40. protocols/expressions/viseme.schema.json +17 -0
  41. protocols/memory/__init__.py +1 -0
  42. protocols/memory/memory.schema.json +19 -0
  43. protocols/state/__init__.py +1 -0
  44. protocols/state/adapter-status.schema.json +18 -0
  45. protocols/state/state.schema.json +28 -0
  46. protocols/wishes/__init__.py +1 -0
  47. protocols/wishes/wish.schema.json +20 -0
  48. templates/__init__.py +1 -0
  49. templates/blank_personality/README.md +15 -0
  50. templates/blank_personality/__init__.py +1 -0
  51. templates/blank_personality/personality.json +22 -0
oaf/core/soul_core.py ADDED
@@ -0,0 +1,162 @@
1
+ """灵魂核心公开抽象 + 最小 Mock 实现。
2
+
3
+ 公开的 SoulCore 只描述运行契约。MockSoulCore 是协议演示器,
4
+ 不是任何私有角色的真实灵魂核心,也不声称具备意识。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from abc import ABC, abstractmethod
10
+ from typing import Any
11
+
12
+ from ..protocols import (
13
+ ActionRequest, ContextBundle, DeliveryReceipt, Event, EventResult,
14
+ ExpressionIntent, SafetyPolicy, StateSnapshot,
15
+ )
16
+ from .coordination import ModuleRegistry
17
+ from .event_processing import EventProcessor
18
+ from .lifecycle import LifecycleState
19
+ from .status import StatusCollector
20
+
21
+
22
+ class SoulCore(ABC):
23
+ """让各模块协同运行的生命周期与协调契约。"""
24
+
25
+ @abstractmethod
26
+ def init(self) -> None: ...
27
+
28
+ @abstractmethod
29
+ def start(self) -> None: ...
30
+
31
+ @abstractmethod
32
+ def tick(self) -> StateSnapshot: ...
33
+
34
+ @abstractmethod
35
+ def shutdown(self) -> None: ...
36
+
37
+ @abstractmethod
38
+ def register_module(self, module: Any) -> None: ...
39
+
40
+ @abstractmethod
41
+ def receive_event(self, event: Event) -> EventResult: ...
42
+
43
+ @abstractmethod
44
+ def build_context(self, session_id: str, user_text: str) -> ContextBundle: ...
45
+
46
+ @abstractmethod
47
+ def deliver(self, intent: ExpressionIntent | ActionRequest) -> DeliveryReceipt: ...
48
+
49
+ @abstractmethod
50
+ def status(self) -> StateSnapshot: ...
51
+
52
+
53
+ class MockSoulCore(SoulCore):
54
+ """只展示公开接口如何协作,不包含私有实现。"""
55
+
56
+ def __init__(self, name: str = "mock-soul",
57
+ policy: SafetyPolicy | None = None) -> None:
58
+ self.name = name
59
+ self.policy = policy or SafetyPolicy(
60
+ allowed_actions=["expression"], default_allow=False)
61
+ self.registry = ModuleRegistry()
62
+ self.events = EventProcessor()
63
+ self.collector = StatusCollector()
64
+ self._state = LifecycleState.CREATED
65
+ self.errors: list[str] = []
66
+ self.delivered: list[dict[str, Any]] = []
67
+ self.last_event: Event | None = None
68
+
69
+ @property
70
+ def state(self) -> str:
71
+ return self._state.value
72
+
73
+ def init(self) -> None:
74
+ if self._state in (LifecycleState.RUNNING, LifecycleState.STOPPING):
75
+ raise RuntimeError("cannot init while running")
76
+ self._state = LifecycleState.INITIALIZED
77
+
78
+ def start(self) -> None:
79
+ if self._state is LifecycleState.RUNNING:
80
+ return
81
+ if self._state in (LifecycleState.STOPPING, LifecycleState.STOPPED):
82
+ raise RuntimeError("cannot restart a stopped core; create a new instance")
83
+ if self._state is LifecycleState.CREATED:
84
+ self.init()
85
+ self._state = LifecycleState.STARTING
86
+ self.errors.clear()
87
+ self.registry.errors.clear()
88
+ self.registry.start_all(self)
89
+ self.errors.extend(self.registry.errors)
90
+ self._state = LifecycleState.RUNNING
91
+
92
+ def tick(self) -> StateSnapshot:
93
+ if self._state is not LifecycleState.RUNNING:
94
+ raise RuntimeError("tick requires running state")
95
+ errors = self.registry.tick_all(self)
96
+ self.errors.extend(errors)
97
+ return self.status()
98
+
99
+ def shutdown(self) -> None:
100
+ if self._state in (LifecycleState.STOPPED, LifecycleState.CREATED,
101
+ LifecycleState.INITIALIZED):
102
+ self._state = LifecycleState.STOPPED
103
+ return
104
+ self._state = LifecycleState.STOPPING
105
+ self.registry.errors.clear()
106
+ self.registry.stop_all(self)
107
+ self.errors.extend(self.registry.errors)
108
+ self._state = LifecycleState.STOPPED
109
+
110
+ def register_module(self, module: Any) -> None:
111
+ if self._state in (LifecycleState.RUNNING, LifecycleState.STARTING,
112
+ LifecycleState.STOPPING):
113
+ raise RuntimeError("register modules before start()")
114
+ self.registry.register(module)
115
+
116
+ def receive_event(self, event: Event) -> EventResult:
117
+ if self._state is not LifecycleState.RUNNING:
118
+ raise RuntimeError("receive_event requires running state")
119
+ self.last_event = event
120
+ result = self.events.process(event, self.registry.all(), self)
121
+ if result.error:
122
+ self.errors.append(f"event {event.event_id}: {result.error}")
123
+ return result
124
+
125
+ def build_context(self, session_id: str, user_text: str) -> ContextBundle:
126
+ if self._state not in (LifecycleState.RUNNING, LifecycleState.INITIALIZED):
127
+ raise RuntimeError("build_context requires initialized or running state")
128
+ bundle = ContextBundle(session_id=session_id, user_text=user_text)
129
+ for module in self.registry.all():
130
+ try:
131
+ contribution = module.contribute_context(self, session_id, user_text)
132
+ except Exception as exc: # noqa: BLE001 - isolate module failure
133
+ self.errors.append(f"{module.module_id}.context: {exc}")
134
+ continue
135
+ if not isinstance(contribution, dict):
136
+ continue
137
+ if isinstance(contribution.get("personality"), dict):
138
+ bundle.personality.update(contribution["personality"])
139
+ if isinstance(contribution.get("memories"), list):
140
+ bundle.memories.extend(contribution["memories"])
141
+ if isinstance(contribution.get("wishes"), list):
142
+ bundle.wishes.extend(contribution["wishes"])
143
+ for key, value in contribution.items():
144
+ if key not in {"personality", "memories", "wishes"}:
145
+ bundle.shared[key] = value
146
+ return bundle
147
+
148
+ def deliver(self, intent: ExpressionIntent | ActionRequest) -> DeliveryReceipt:
149
+ if self._state not in (LifecycleState.RUNNING, LifecycleState.INITIALIZED):
150
+ return DeliveryReceipt(delivered=False, intent=intent.to_dict(),
151
+ error="core is not running")
152
+ if isinstance(intent, ActionRequest):
153
+ allowed, _, reason = self.policy.check(intent)
154
+ if not allowed:
155
+ return DeliveryReceipt(delivered=False, intent=intent.to_dict(),
156
+ error=reason)
157
+ payload = intent.to_dict()
158
+ self.delivered.append(payload)
159
+ return DeliveryReceipt(delivered=True, intent=payload)
160
+
161
+ def status(self) -> StateSnapshot:
162
+ return self.collector.snapshot(self)
oaf/core/status.py ADDED
@@ -0,0 +1,29 @@
1
+ """状态快照收集。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Any
6
+
7
+ from ..protocols import StateSnapshot, utcnow
8
+
9
+ if TYPE_CHECKING:
10
+ from .soul_core import MockSoulCore
11
+
12
+
13
+ class StatusCollector:
14
+ def __init__(self) -> None:
15
+ self.version = 0
16
+
17
+ def snapshot(self, core: "MockSoulCore") -> StateSnapshot:
18
+ self.version += 1
19
+ return StateSnapshot(
20
+ state=core.state,
21
+ version=self.version,
22
+ timestamp=utcnow(),
23
+ modules=core.registry.statuses(),
24
+ errors=list(core.errors),
25
+ metadata={"name": core.name, "protocol_version": "0.1"},
26
+ )
27
+
28
+ def summary(self, core: "MockSoulCore") -> dict[str, Any]:
29
+ return self.snapshot(core).to_dict()
@@ -0,0 +1,10 @@
1
+ """模块。"""
2
+
3
+ from .base import Module
4
+ from .llm import BaseLLMAdapter, EchoLLMAdapter
5
+ from .memory import InMemoryMemoryModule
6
+ from .personality import BlankPersonalityModule
7
+ from .wishes import SimpleWishModule
8
+
9
+ __all__ = ["Module", "BlankPersonalityModule", "InMemoryMemoryModule",
10
+ "SimpleWishModule", "BaseLLMAdapter", "EchoLLMAdapter"]
oaf/modules/base.py ADDED
@@ -0,0 +1,39 @@
1
+ """模块基类:只规定协作方式,不规定具体实现。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Any
6
+
7
+ from ..protocols import Event
8
+
9
+ if TYPE_CHECKING:
10
+ from ..core.soul_core import MockSoulCore
11
+
12
+
13
+ class Module:
14
+ module_id = "module"
15
+ capabilities: tuple[str, ...] = ()
16
+
17
+ def on_start(self, core: "MockSoulCore") -> None:
18
+ """模块被灵魂核心启动。"""
19
+
20
+ def on_stop(self, core: "MockSoulCore") -> None:
21
+ """模块被灵魂核心停止。"""
22
+
23
+ def accepts_event(self, event: Event) -> bool:
24
+ return True
25
+
26
+ def on_event(self, core: "MockSoulCore", event: Event) -> Any:
27
+ """处理事件;可返回 ExpressionIntent / ActionRequest / dict / list。"""
28
+ return None
29
+
30
+ def contribute_context(self, core: "MockSoulCore", session_id: str,
31
+ user_text: str) -> dict[str, Any]:
32
+ """向 build_context 提供结构化背景,不直接拼最终 prompt。"""
33
+ return {}
34
+
35
+ def tick(self, core: "MockSoulCore") -> None:
36
+ """周期性维护;没有需要时可留空。"""
37
+
38
+ def status(self) -> dict[str, Any]:
39
+ return {"state": "ready"}
oaf/modules/llm.py ADDED
@@ -0,0 +1,36 @@
1
+ """LLM 适配器:调用者自行替换为真实模型。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Protocol
6
+
7
+
8
+ class LLMAdapter(Protocol):
9
+ adapter_id: str
10
+
11
+ def complete(self, messages: list[dict[str, Any]], **kwargs: Any) -> str:
12
+ ...
13
+
14
+
15
+ class BaseLLMAdapter:
16
+ """Small optional base class for developer adapters."""
17
+
18
+ adapter_id = "llm"
19
+ capabilities: tuple[str, ...] = ("chat",)
20
+
21
+ def complete(self, messages: list[dict[str, Any]], **kwargs: Any) -> str:
22
+ raise NotImplementedError("LLM adapter must implement complete()")
23
+
24
+
25
+ class EchoLLMAdapter(BaseLLMAdapter):
26
+ """离线、确定性的测试适配器;绝不发网络请求。"""
27
+
28
+ adapter_id = "echo"
29
+
30
+ def complete(self, messages: list[dict[str, Any]], **kwargs: Any) -> str:
31
+ last_user = ""
32
+ for message in reversed(messages):
33
+ if message.get("role") == "user":
34
+ last_user = str(message.get("content", ""))
35
+ break
36
+ return f"[mock] {last_user}".strip()
oaf/modules/memory.py ADDED
@@ -0,0 +1,50 @@
1
+ """最小记忆模块。
2
+
3
+ 它不是完整记忆系统;只用于展示协议和测试替身。
4
+ 开发者应替换为自己的持久化/检索实现。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Any
10
+
11
+ from ..protocols import MemoryRecord
12
+ from .base import Module
13
+
14
+
15
+ class InMemoryMemoryModule(Module):
16
+ module_id = "memory"
17
+ capabilities = ("memory", "recall")
18
+
19
+ def __init__(self) -> None:
20
+ self.records: list[MemoryRecord] = []
21
+
22
+ def remember(self, text: str, tags: list[str] | None = None,
23
+ importance: float = 0.5, confidence: float = 0.5,
24
+ source: str = "developer") -> MemoryRecord:
25
+ record = MemoryRecord(
26
+ text=text.strip(), tags=list(tags or []),
27
+ importance=max(0.0, min(1.0, importance)),
28
+ confidence=max(0.0, min(1.0, confidence)), source=source,
29
+ )
30
+ self.records.append(record)
31
+ return record
32
+
33
+ def recall(self, query: str, limit: int = 5) -> list[MemoryRecord]:
34
+ terms = [part for part in query.replace(",", " ").replace("。", " ").split() if part]
35
+ if not terms:
36
+ return self.records[:limit]
37
+ scored = []
38
+ for record in self.records:
39
+ score = sum(1 for term in terms if term in record.text or term in record.tags)
40
+ if score:
41
+ scored.append((score, record))
42
+ scored.sort(key=lambda pair: pair[0], reverse=True)
43
+ return [record for _, record in scored[:limit]]
44
+
45
+ def contribute_context(self, core, session_id: str, user_text: str) -> dict[str, Any]:
46
+ return {"memories": [item.to_dict() for item in self.recall(user_text, 5)]}
47
+
48
+ def status(self) -> dict[str, Any]:
49
+ return {"state": "ready", "records": len(self.records),
50
+ "mode": "in-memory-test-double"}
@@ -0,0 +1,46 @@
1
+ """空白人格模块。
2
+
3
+ 这里没有预置角色的人格、语气、关系或经历。
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ from .base import Module
13
+
14
+ REQUIRED = ("name", "identity", "voice")
15
+
16
+
17
+ class BlankPersonalityModule(Module):
18
+ module_id = "personality"
19
+ capabilities = ("personality", "system_prompt")
20
+
21
+ def __init__(self, data: dict[str, Any]):
22
+ missing = [key for key in REQUIRED if not str(data.get(key, "")).strip()]
23
+ if missing:
24
+ raise ValueError(f"personality missing: {', '.join(missing)}")
25
+ self.data = {
26
+ "name": str(data["name"]).strip(),
27
+ "identity": str(data["identity"]).strip(),
28
+ "voice": str(data["voice"]).strip(),
29
+ "values": list(data.get("values") or []),
30
+ "boundaries": list(data.get("boundaries") or []),
31
+ "style_examples": list(data.get("style_examples") or []),
32
+ "metadata": dict(data.get("metadata") or {}),
33
+ }
34
+
35
+ @classmethod
36
+ def from_file(cls, path: str | Path) -> "BlankPersonalityModule":
37
+ data = json.loads(Path(path).read_text(encoding="utf-8"))
38
+ if not isinstance(data, dict):
39
+ raise ValueError("personality root must be an object")
40
+ return cls(data)
41
+
42
+ def contribute_context(self, core, session_id: str, user_text: str) -> dict[str, Any]:
43
+ return {"personality": dict(self.data)}
44
+
45
+ def status(self) -> dict[str, Any]:
46
+ return {"state": "ready", "name": self.data["name"]}
oaf/modules/wishes.py ADDED
@@ -0,0 +1,52 @@
1
+ """最小愿望模块。
2
+
3
+ 只展示“愿望可以被列出、竞争、反馈进度”的接口;
4
+ 不包含自动愿望生成器或私有目标体系。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Any
10
+
11
+ from ..protocols import WishRecord
12
+ from .base import Module
13
+
14
+
15
+ class SimpleWishModule(Module):
16
+ module_id = "wishes"
17
+ capabilities = ("wishes", "priority")
18
+
19
+ def __init__(self, wishes: list[WishRecord] | None = None) -> None:
20
+ self.wishes = list(wishes or [])
21
+
22
+ def add(self, title: str, *, category: str = "general",
23
+ priority: float = 0.5, urgency: float = 0.5,
24
+ plan: list[str] | None = None) -> WishRecord:
25
+ wish = WishRecord(title=title, category=category,
26
+ priority=max(0.0, min(1.0, priority)),
27
+ urgency=max(0.0, min(1.0, urgency)),
28
+ plan=list(plan or []))
29
+ self.wishes.append(wish)
30
+ return wish
31
+
32
+ def active(self) -> list[WishRecord]:
33
+ return [wish for wish in self.wishes if wish.status == "active"]
34
+
35
+ def ranked(self, limit: int = 3) -> list[WishRecord]:
36
+ return sorted(self.active(), key=lambda w: (w.urgency + w.priority),
37
+ reverse=True)[:limit]
38
+
39
+ def feedback(self, wish_id: str, progress: float) -> bool:
40
+ for wish in self.wishes:
41
+ if wish.wish_id == wish_id:
42
+ wish.progress = max(0.0, min(1.0, progress))
43
+ if wish.progress >= 1.0:
44
+ wish.status = "done"
45
+ return True
46
+ return False
47
+
48
+ def contribute_context(self, core, session_id: str, user_text: str) -> dict[str, Any]:
49
+ return {"wishes": [item.to_dict() for item in self.ranked(3)]}
50
+
51
+ def status(self) -> dict[str, Any]:
52
+ return {"state": "ready", "active": len(self.active())}