alpha-avatar-plugins-context 0.6.8__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.
@@ -0,0 +1,64 @@
1
+ Metadata-Version: 2.5
2
+ Name: alpha-avatar-plugins-context
3
+ Version: 0.6.8
4
+ Summary: Runtime context management for AlphaAvatar.
5
+ Project-URL: Source, https://github.com/AlphaAvatar/AlphaAvatar
6
+ Project-URL: Issues, https://github.com/AlphaAvatar/AlphaAvatar/issues
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3 :: Only
12
+ Classifier: Programming Language :: Python :: 3.13
13
+ Requires-Python: <3.14,>=3.13
14
+ Requires-Dist: alpha-avatar-agents
15
+ Requires-Dist: alpha-avatar-core
16
+ Requires-Dist: pydantic<3,>=2
17
+ Description-Content-Type: text/markdown
18
+
19
+ # AlphaAvatar Context Plugin
20
+
21
+ The default Context manager is created by Host against a partial AvatarRuntime and then owned by FoundationRuntime. Engine lends Memory/Persona read sources; it does not assemble native Loop prompts or own an SDK ChatContext.
22
+
23
+ ## Interface
24
+
25
+ Use `runtime.foundation.context` through the public ContextManager contract:
26
+
27
+ - `accept_turn(snapshot)` accepts a committed Turn and supplies its current input seed.
28
+ - `prepare(ContextPrepareRequest)` captures the native history, perception and query prefix.
29
+ - `build(prefix, continuation=...)` appends execution continuation without refreshing State.
30
+
31
+ There is no parallel query-manager API. ContextContribution and ContextPrepareRequest live in the public `alphaavatar.agents.avatar.context.schemas` namespace.
32
+
33
+ Preparation waits for the explicitly identified committed Turn, captures State, source properties, time and modality information once, and renders the prefix off the event loop. Pending preparations are bounded and remain owned until settled, even when their requesting execution is cancelled.
34
+
35
+ State and static `loop_budget` use the synthetic `alphaavatar_runtime_context` function-call/output pair. Its identity, content and position remain stable inside one query. No middle system/developer update or per-model-step budget rewrite is introduced. Stable prefixes permit reuse but do not guarantee provider cache hits.
36
+
37
+ ## Native history
38
+
39
+ The manager retains bounded history by context and Turn and independently consumes canonical model records from Output. User input comes from committed Turns; Engine does not reconstruct assistant/tool records from a LoopResult or inject Memory writes.
40
+
41
+ Incomplete tool-call/output pairs are excluded from the next model input. Retiring Run results remain associated with their original identity and do not resurrect evicted Turns. Context acknowledgement is independent of Memory acknowledgement and is not a database-persistence guarantee.
42
+
43
+ ```yaml
44
+ context:
45
+ plugin: default
46
+ init_config:
47
+ behavior_rules: "Follow the application's execution and authorization policies."
48
+ max_pending_preparations: 16
49
+ history_max_turns: 32
50
+ history_max_items: 4096
51
+ history_max_bytes: 8388608
52
+ ```
53
+
54
+ The history byte limit bounds serialized retained content, not total process memory or shared media caches. Eviction respects whole-Turn history ownership.
55
+
56
+ StateRuntime.global_behavior_rules may originate from client metadata. It is captured as reference/preferences, not promoted into application system instructions. Binding Memory/Persona sources does not transfer their ownership.
57
+
58
+ ## Lifecycle
59
+
60
+ Host constructs Context, Voice and the required Loop before binding Foundation. It initializes Loop only after binding. Context creation must not request an unavailable Foundation service. Loop is not optional and `loop: null` is invalid.
61
+
62
+ Ingress and execution producers stop before record consumers are drained. Foundation closes Loop, Context/preparation work, and shared Provider/Voice before Output and Inference are released. Context does not close borrowed Memory or Persona components.
63
+
64
+ The SDK generation bridge is removed. Native history and ContextManager are the main path, not a fallback beside SDK ChatContext. Temporal alignment and visual rendering remain separate components; there is no process-global query cache or per-step mutation of State.
@@ -0,0 +1,24 @@
1
+ alphaavatar/plugins/context/__init__.py,sha256=BYfl3DNgRJPnr36PlWkmC5BwA0BtnQuD3m8r0fMe7Ko,1601
2
+ alphaavatar/plugins/context/config.py,sha256=saB-TM8M53AsJXsuoVK0dEkS1_24YwK6S212_4MNBJs,1101
3
+ alphaavatar/plugins/context/manager.py,sha256=j_zc3GUCJGCMYK10kPSl4OBdr7X4PsQPia6SP85Z2fE,12512
4
+ alphaavatar/plugins/context/snapshot.py,sha256=3Md4fg9Op2ew0xZWebfMVMM4ShYIaIpRR7Iv65GzyLU,2376
5
+ alphaavatar/plugins/context/template.py,sha256=R0QRh4iKWoW80rn32uWPT_byzfftQLcXZsUyFNKd61I,4415
6
+ alphaavatar/plugins/context/version.py,sha256=tukoyyKeNvOr5GJz3XIPeEDJaf1waKPrUMLcqTkfZAQ,604
7
+ alphaavatar/plugins/context/builder/__init__.py,sha256=H-iYU4zSjnMP50S9tG5RPCl1bZ98xsqApYyMYnaAuI0,657
8
+ alphaavatar/plugins/context/builder/context_builder.py,sha256=eRqfWkL_v8qAFVfW-adIcUa6Rb638RTOXAkFpkQYlsI,7336
9
+ alphaavatar/plugins/context/history/__init__.py,sha256=qMsJGjq9Ar3KgIvSzYH_8g3sssrMaJjGzanQrr8OCPc,657
10
+ alphaavatar/plugins/context/history/context_history.py,sha256=a8upcihWfAi2B3nMwgzGIaSOzAwBK1-NSyDGA8AADoA,15984
11
+ alphaavatar/plugins/context/prompts/avatar_system_prompts.py,sha256=UnCaDbkHAbAMffRV2Xcrw8NgPPd_nXju1Ab0txd99TU,8534
12
+ alphaavatar/plugins/context/prompts/runtime_context_prompts.py,sha256=e8kdn78uWkaa36Q28lJP4sNyG68eYk3ybIAowaTKEF4,1881
13
+ alphaavatar/plugins/context/prompts/xlm_protocol_prompts.py,sha256=eLXTs68WFKft563MHoHG4SLRdeIoPac_AN7tJVrG-zY,1965
14
+ alphaavatar/plugins/context/renderer/__init__.py,sha256=tayCi6YogvSmfxn4JK8puL6gAxer6drLcuWZwShmyVE,800
15
+ alphaavatar/plugins/context/renderer/base.py,sha256=90EwZ62m5OpDpIt3eHAnHvoAKvIEi42Apnt3w8v1aTc,1406
16
+ alphaavatar/plugins/context/renderer/op.py,sha256=kwUMwS3stuqBpuuJZloOXL4N8OgtqcOg_tS2Hc02lT8,18699
17
+ alphaavatar/plugins/context/renderer/realtime.py,sha256=OE_Mm7bZUHgU8DWC5Bg7EHmHXeIxMdLzBqZsnloeWog,1280
18
+ alphaavatar/plugins/context/renderer/text.py,sha256=K7RZp1f7NZ7OFUEERNKdchRmoPT-iXkJ5P1AySLdXyI,1067
19
+ alphaavatar/plugins/context/renderer/vlm.py,sha256=Q1hH0ewuEEc4b66-3k8xVxYPxmsTIwIs2dAhIhKMok0,1065
20
+ alpha_avatar_plugins_context-0.6.8.dist-info/METADATA,sha256=Hg1rJeCoveO_dMvuK6wosGghC4QK3kxb9XLArlZf1DM,4072
21
+ alpha_avatar_plugins_context-0.6.8.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
22
+ alpha_avatar_plugins_context-0.6.8.dist-info/entry_points.txt,sha256=HcbuTqFxG7FeqjTaFD54ZA3ktTh7WyeGYjIPmhIc8WE,60
23
+ alpha_avatar_plugins_context-0.6.8.dist-info/licenses/LICENSE,sha256=_qJuMp5913P77iW5A6b83Wo41on3mDtiWSy9RwoARFA,11355
24
+ alpha_avatar_plugins_context-0.6.8.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [alphaavatar.context]
2
+ default = alphaavatar.plugins.context
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,45 @@
1
+ # Copyright 2026 AlphaAvatar project
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from __future__ import annotations
15
+
16
+ from typing import TYPE_CHECKING, Any
17
+
18
+ from alphaavatar.agents.runtime.plugin import AvatarModule, AvatarModulePlugin
19
+
20
+ from .version import __version__
21
+
22
+ if TYPE_CHECKING:
23
+ from alphaavatar.agents.avatar.context import ContextManager
24
+ from alphaavatar.agents.configs import AvatarConfig
25
+ from alphaavatar.agents.runtime import AvatarRuntime
26
+
27
+
28
+ class ContextPlugin(AvatarModulePlugin):
29
+ def __init__(self) -> None:
30
+ super().__init__("Query context manager", __version__, __name__)
31
+
32
+ def get_plugin(
33
+ self, *, runtime: AvatarRuntime, avatar_config: AvatarConfig, init_config: Any
34
+ ) -> ContextManager:
35
+ from .config import ContextConfig
36
+ from .manager import AvatarContextManager
37
+
38
+ return AvatarContextManager(
39
+ runtime=runtime,
40
+ avatar_config=avatar_config,
41
+ config=ContextConfig.model_validate(init_config),
42
+ )
43
+
44
+
45
+ AvatarModulePlugin.register(AvatarModule.CONTEXT, "default", ContextPlugin())
@@ -0,0 +1,16 @@
1
+ # Copyright 2026 AlphaAvatar project
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from .context_builder import ContextBuilder
15
+
16
+ __all__ = ["ContextBuilder"]
@@ -0,0 +1,193 @@
1
+ # Copyright 2026 AlphaAvatar project
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from __future__ import annotations
15
+
16
+ import hashlib
17
+ import json
18
+ from dataclasses import replace
19
+ from types import MappingProxyType
20
+ from typing import TYPE_CHECKING
21
+ from xml.sax.saxutils import escape
22
+
23
+ from alphaavatar.agents.avatar.context.schemas import ContextContribution
24
+ from alphaavatar.agents.avatar.provider.enums import ModelInputType, ModelRole
25
+ from alphaavatar.agents.avatar.provider.schemas import (
26
+ ModelAudioPart,
27
+ ModelFunctionCall,
28
+ ModelFunctionOutput,
29
+ ModelImagePart,
30
+ ModelInput,
31
+ ModelInputMessage,
32
+ ModelTextPart,
33
+ )
34
+ from alphaavatar.agents.constants import RUNTIME_CONTEXT_TOOL_NAME
35
+
36
+ if TYPE_CHECKING:
37
+ from alphaavatar.agents.avatar.context.schemas import ContextBuildRequest, ContextBuildResult
38
+
39
+ from ..renderer import RendererRegistry
40
+
41
+
42
+ class ContextBuilder:
43
+ """Compose model inputs; synthetic runtime items are projections, not history or tool work."""
44
+
45
+ SYSTEM_MESSAGE_ID = "alphaavatar.system"
46
+
47
+ def __init__(self, registry: RendererRegistry | None = None) -> None:
48
+ self._registry = registry
49
+
50
+ def _renderers(self) -> RendererRegistry:
51
+ if self._registry is None:
52
+ from ..renderer import RealtimeRenderer, RendererRegistry, TextRenderer, VLMRenderer
53
+
54
+ self._registry = RendererRegistry()
55
+ for kind, renderer in (
56
+ (ModelInputType.TEXT, TextRenderer()),
57
+ (ModelInputType.VLM, VLMRenderer()),
58
+ (ModelInputType.REALTIME, RealtimeRenderer()),
59
+ ):
60
+ self._registry.register(input_type=kind, renderer=renderer)
61
+
62
+ return self._registry
63
+
64
+ @staticmethod
65
+ def _is_runtime_context_item(item: object) -> bool:
66
+ return (
67
+ isinstance(item, ModelFunctionCall | ModelFunctionOutput)
68
+ and item.name == RUNTIME_CONTEXT_TOOL_NAME
69
+ )
70
+
71
+ @staticmethod
72
+ def _historical_media_placeholder(*, image_count: int, audio_count: int) -> ModelTextPart:
73
+ return ModelTextPart(
74
+ '<historical_media omitted="true" current="false" '
75
+ f'image_count="{image_count}" audio_count="{audio_count}">'
76
+ "This media belonged to an earlier message and is not current input."
77
+ "</historical_media>"
78
+ )
79
+
80
+ def _compact_historical_message(self, message: ModelInputMessage) -> ModelInputMessage:
81
+ parts = []
82
+ image_count = audio_count = 0
83
+ for part in message.parts:
84
+ if isinstance(part, ModelImagePart):
85
+ image_count += 1
86
+ elif isinstance(part, ModelAudioPart):
87
+ audio_count += 1
88
+ else:
89
+ parts.append(part)
90
+ if image_count or audio_count:
91
+ parts.append(
92
+ self._historical_media_placeholder(image_count=image_count, audio_count=audio_count)
93
+ )
94
+ return replace(message, parts=tuple(parts))
95
+
96
+ def _prepare_base_input(self, model_input: ModelInput, *, current_input_id: str) -> ModelInput:
97
+ items = []
98
+ for item in model_input.items:
99
+ if self._is_runtime_context_item(item):
100
+ continue
101
+ if isinstance(item, ModelInputMessage) and item.id != current_input_id:
102
+ item = self._compact_historical_message(item)
103
+ items.append(item)
104
+ return replace(model_input, items=tuple(items))
105
+
106
+ def _with_system_prompt(self, model_input: ModelInput, *, system_prompt: str) -> ModelInput:
107
+ items = tuple(
108
+ item
109
+ for item in model_input.items
110
+ if not (isinstance(item, ModelInputMessage) and item.role == ModelRole.SYSTEM)
111
+ )
112
+ message = ModelInputMessage(
113
+ id=self.SYSTEM_MESSAGE_ID, role=ModelRole.SYSTEM, parts=(ModelTextPart(system_prompt),)
114
+ )
115
+ return replace(model_input, items=(message, *items))
116
+
117
+ def _inject_runtime_context(
118
+ self,
119
+ model_input: ModelInput,
120
+ *,
121
+ input_id: str,
122
+ runtime_context: str,
123
+ contributions: tuple[ContextContribution, ...] = (),
124
+ query_scope: str = "",
125
+ ) -> ModelInput:
126
+ names = [item.name for item in contributions]
127
+ if len(set(names)) != len(names):
128
+ raise ValueError("Context contribution names must be unique")
129
+ sections = [runtime_context.strip()] if runtime_context.strip() else []
130
+ sections.extend(
131
+ f"<{item.name}>\n{escape(item.content)}\n</{item.name}>" for item in contributions
132
+ )
133
+ if not sections:
134
+ return model_input
135
+
136
+ positions = [
137
+ index
138
+ for index, item in enumerate(model_input.items)
139
+ if isinstance(item, ModelInputMessage) and item.id == input_id
140
+ ]
141
+ if len(positions) != 1:
142
+ raise ValueError("Runtime context requires exactly one current input message")
143
+
144
+ seed = json.dumps([query_scope, input_id], ensure_ascii=False, separators=(",", ":"))
145
+ call_id = f"alphaavatar_runtime_{hashlib.sha256(seed.encode()).hexdigest()[:32]}"
146
+ call = ModelFunctionCall(
147
+ id=call_id,
148
+ call_id=call_id,
149
+ name=RUNTIME_CONTEXT_TOOL_NAME,
150
+ arguments='{"source":"alphaavatar","scope":"current_query_only"}',
151
+ metadata=MappingProxyType({"alphaavatar_runtime_context": True}),
152
+ )
153
+ output = ModelFunctionOutput(
154
+ id=f"{call_id}:result",
155
+ call_id=call_id,
156
+ name=RUNTIME_CONTEXT_TOOL_NAME,
157
+ parts=(ModelTextPart("\n\n".join(sections)),),
158
+ is_error=False,
159
+ )
160
+ index = positions[0] + 1
161
+
162
+ return replace(
163
+ model_input,
164
+ items=(*model_input.items[:index], call, output, *model_input.items[index:]),
165
+ )
166
+
167
+ def build(
168
+ self,
169
+ *,
170
+ request: ContextBuildRequest,
171
+ system_prompt: str,
172
+ runtime_context: str,
173
+ contributions: tuple[ContextContribution, ...] = (),
174
+ query_scope: str = "",
175
+ ) -> ContextBuildResult:
176
+ from alphaavatar.agents.avatar.context.schemas import ContextBuildResult
177
+
178
+ base = self._prepare_base_input(request.base_input, current_input_id=request.input_id)
179
+ base = self._with_system_prompt(base, system_prompt=system_prompt)
180
+ rendered = (
181
+ self._renderers()
182
+ .resolve(request.model_input_type)
183
+ .render(replace(request, base_input=base))
184
+ )
185
+ model_input = self._inject_runtime_context(
186
+ rendered.model_input,
187
+ input_id=request.input_id,
188
+ runtime_context=runtime_context,
189
+ contributions=contributions,
190
+ query_scope=query_scope,
191
+ )
192
+
193
+ return ContextBuildResult(model_input=model_input)
@@ -0,0 +1,28 @@
1
+ # Copyright 2026 AlphaAvatar project
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from pydantic import BaseModel, ConfigDict, Field
15
+
16
+ from alphaavatar.agents.constants import DEFAULT_SYSTEM_VALUE
17
+
18
+
19
+ class ContextConfig(BaseModel):
20
+ model_config = ConfigDict(extra="forbid", frozen=True)
21
+
22
+ behavior_rules: str = DEFAULT_SYSTEM_VALUE
23
+ max_pending_preparations: int = Field(default=16, ge=1, le=128)
24
+
25
+ # History Config
26
+ history_max_turns: int = Field(default=32, ge=1)
27
+ history_max_items: int = Field(default=4096, ge=1)
28
+ history_max_bytes: int = Field(default=8 * 1024 * 1024, ge=1)
@@ -0,0 +1,16 @@
1
+ # Copyright 2026 AlphaAvatar project
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from .context_history import ContextHistory
15
+
16
+ __all__ = ["ContextHistory"]