codecraftai-agent-kit 1.3.0__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.
- ccai/agentkit/__init__.py +304 -0
- ccai/agentkit/addressresolver.py +177 -0
- ccai/agentkit/agent.py +2945 -0
- ccai/agentkit/agentaddress.py +187 -0
- ccai/agentkit/agentconfiguration.py +581 -0
- ccai/agentkit/agentidentity.py +152 -0
- ccai/agentkit/agentregistry.py +221 -0
- ccai/agentkit/agentstatemachine.py +134 -0
- ccai/agentkit/alternateproviderstrategy.py +36 -0
- ccai/agentkit/approvalgate.py +238 -0
- ccai/agentkit/approvalrequest.py +250 -0
- ccai/agentkit/asyncagent.py +187 -0
- ccai/agentkit/breakpoint.py +150 -0
- ccai/agentkit/builtinagentmetrics.py +114 -0
- ccai/agentkit/builtins/__init__.py +11 -0
- ccai/agentkit/builtins/filereadtool.py +90 -0
- ccai/agentkit/builtins/filewritetool.py +93 -0
- ccai/agentkit/builtins/httprequesttool.py +169 -0
- ccai/agentkit/builtins/shellcommandtool.py +190 -0
- ccai/agentkit/cachedresultstrategy.py +43 -0
- ccai/agentkit/checkpointmanager.py +219 -0
- ccai/agentkit/circuitbreaker.py +230 -0
- ccai/agentkit/circuitbreakerconfiguration.py +158 -0
- ccai/agentkit/circuitbreakerevent.py +158 -0
- ccai/agentkit/circuitbreakerhealthcheck.py +32 -0
- ccai/agentkit/circuitbreakerregistry.py +116 -0
- ccai/agentkit/circuitbreakerstate.py +44 -0
- ccai/agentkit/clearcacheaction.py +46 -0
- ccai/agentkit/concurrencybridge.py +143 -0
- ccai/agentkit/concurrencymodel.py +19 -0
- ccai/agentkit/conditionevaluator.py +594 -0
- ccai/agentkit/configurationchangeevent.py +179 -0
- ccai/agentkit/configurationerrors.py +152 -0
- ccai/agentkit/configurationlayer.py +160 -0
- ccai/agentkit/configurationlayersource.py +46 -0
- ccai/agentkit/configurationmanager.py +680 -0
- ccai/agentkit/configurationschema.py +224 -0
- ccai/agentkit/configurationschemafield.py +217 -0
- ccai/agentkit/configurationserializer.py +163 -0
- ccai/agentkit/configurationvalidationresult.py +118 -0
- ccai/agentkit/contextsummarizer.py +170 -0
- ccai/agentkit/contextwindow.py +264 -0
- ccai/agentkit/contextwindowstrategy.py +57 -0
- ccai/agentkit/correlationcontext.py +156 -0
- ccai/agentkit/costestimate.py +139 -0
- ccai/agentkit/costtracker.py +121 -0
- ccai/agentkit/deadletterentry.py +134 -0
- ccai/agentkit/deadletterquery.py +119 -0
- ccai/agentkit/deadletterqueue.py +123 -0
- ccai/agentkit/deadletterstore.py +86 -0
- ccai/agentkit/debuginspector.py +211 -0
- ccai/agentkit/debugsession.py +223 -0
- ccai/agentkit/defaultvaluestrategy.py +43 -0
- ccai/agentkit/degradationchangeevent.py +120 -0
- ccai/agentkit/degradationlevel.py +44 -0
- ccai/agentkit/degradationmanager.py +212 -0
- ccai/agentkit/degradationpolicy.py +130 -0
- ccai/agentkit/degradationstrategy.py +66 -0
- ccai/agentkit/embeddingprovider.py +106 -0
- ccai/agentkit/errors.py +95 -0
- ccai/agentkit/executionrecord.py +213 -0
- ccai/agentkit/executionrecorder.py +180 -0
- ccai/agentkit/executionrecording.py +230 -0
- ccai/agentkit/executionreplayer.py +187 -0
- ccai/agentkit/expirationpolicy.py +116 -0
- ccai/agentkit/fallbackchain.py +82 -0
- ccai/agentkit/featureflag.py +154 -0
- ccai/agentkit/featureflagevaluator.py +109 -0
- ccai/agentkit/featureflagregistry.py +258 -0
- ccai/agentkit/filedeadletterstore.py +112 -0
- ccai/agentkit/filememorystore.py +291 -0
- ccai/agentkit/healthcheck.py +46 -0
- ccai/agentkit/healthcheckregistry.py +51 -0
- ccai/agentkit/healthmonitor.py +258 -0
- ccai/agentkit/healthstatus.py +105 -0
- ccai/agentkit/hotreloadmonitor.py +214 -0
- ccai/agentkit/hotreloadpolicy.py +160 -0
- ccai/agentkit/inmemorydeadletterstore.py +61 -0
- ccai/agentkit/inmemorystore.py +173 -0
- ccai/agentkit/jsonmessageserializer.py +89 -0
- ccai/agentkit/jsonoutputparser.py +50 -0
- ccai/agentkit/lifecyclestate.py +22 -0
- ccai/agentkit/llmconversation.py +153 -0
- ccai/agentkit/llmerrors.py +193 -0
- ccai/agentkit/llmmessage.py +158 -0
- ccai/agentkit/llmprovider.py +158 -0
- ccai/agentkit/llmproviderregistry.py +200 -0
- ccai/agentkit/llmresponse.py +190 -0
- ccai/agentkit/llmstreamchunk.py +65 -0
- ccai/agentkit/llmstreamhandler.py +48 -0
- ccai/agentkit/llmtoolbridge.py +154 -0
- ccai/agentkit/logexporter.py +316 -0
- ccai/agentkit/logformatter.py +169 -0
- ccai/agentkit/memoryconfiguration.py +243 -0
- ccai/agentkit/memoryentry.py +254 -0
- ccai/agentkit/memoryerrors.py +135 -0
- ccai/agentkit/memoryindex.py +213 -0
- ccai/agentkit/memoryquery.py +248 -0
- ccai/agentkit/memoryqueryresult.py +86 -0
- ccai/agentkit/memoryscope.py +54 -0
- ccai/agentkit/memorystore.py +260 -0
- ccai/agentkit/memorystorehealthcheck.py +33 -0
- ccai/agentkit/memorystoreregistry.py +106 -0
- ccai/agentkit/message.py +310 -0
- ccai/agentkit/messageenvelope.py +144 -0
- ccai/agentkit/messagepattern.py +50 -0
- ccai/agentkit/messagerouter.py +290 -0
- ccai/agentkit/messageserializer.py +106 -0
- ccai/agentkit/messageserializerregistry.py +163 -0
- ccai/agentkit/messagingconfiguration.py +397 -0
- ccai/agentkit/messagingerrors.py +338 -0
- ccai/agentkit/metricdefinition.py +164 -0
- ccai/agentkit/metricmeasurement.py +178 -0
- ccai/agentkit/metricscollector.py +258 -0
- ccai/agentkit/metricsexporter.py +303 -0
- ccai/agentkit/metricsregistry.py +130 -0
- ccai/agentkit/metricssnapshot.py +155 -0
- ccai/agentkit/metrictype.py +51 -0
- ccai/agentkit/msgpackmessageserializer.py +97 -0
- ccai/agentkit/observabilityconfiguration.py +546 -0
- ccai/agentkit/observabilityerror.py +67 -0
- ccai/agentkit/observabilitypipeline.py +252 -0
- ccai/agentkit/outputparser.py +82 -0
- ccai/agentkit/outputschema.py +142 -0
- ccai/agentkit/parallelbranch.py +87 -0
- ccai/agentkit/platform/__init__.py +43 -0
- ccai/agentkit/platform/adapters/__init__.py +18 -0
- ccai/agentkit/platform/adapters/awsplatformadapter.py +1272 -0
- ccai/agentkit/platform/adapters/azureplatformadapter.py +1227 -0
- ccai/agentkit/platform/adapters/gcpplatformadapter.py +1257 -0
- ccai/agentkit/platform/adapters/localplatformadapter.py +956 -0
- ccai/agentkit/platform/adapters/platformadapter.py +139 -0
- ccai/agentkit/platform/deployment/__init__.py +15 -0
- ccai/agentkit/platform/deployment/deploymentdescriptor.py +234 -0
- ccai/agentkit/platform/deployment/deploymentdescriptorparser.py +178 -0
- ccai/agentkit/platform/deployment/deploymentdescriptorprinter.py +97 -0
- ccai/agentkit/platform/errors.py +224 -0
- ccai/agentkit/platform/platformconfiguration.py +412 -0
- ccai/agentkit/platform/platformdetector.py +125 -0
- ccai/agentkit/platform/platformruntime.py +331 -0
- ccai/agentkit/platform/platformserviceregistry.py +149 -0
- ccai/agentkit/platform/platformtype.py +60 -0
- ccai/agentkit/platform/services/__init__.py +19 -0
- ccai/agentkit/platform/services/computeservice.py +112 -0
- ccai/agentkit/platform/services/invocationresult.py +173 -0
- ccai/agentkit/platform/services/messagingservice.py +135 -0
- ccai/agentkit/platform/services/platformservice.py +111 -0
- ccai/agentkit/platform/services/queuemessage.py +193 -0
- ccai/agentkit/platform/services/storageobject.py +195 -0
- ccai/agentkit/platform/services/storageservice.py +159 -0
- ccai/agentkit/pluginconfiguration.py +241 -0
- ccai/agentkit/plugindependency.py +129 -0
- ccai/agentkit/plugindescriptor.py +225 -0
- ccai/agentkit/pluginlifecyclehook.py +41 -0
- ccai/agentkit/pluginmanager.py +360 -0
- ccai/agentkit/pluginstatus.py +47 -0
- ccai/agentkit/pooledagent.py +116 -0
- ccai/agentkit/prompttemplate.py +221 -0
- ccai/agentkit/prompttemplateregistry.py +145 -0
- ccai/agentkit/protobufmessageserializer.py +144 -0
- ccai/agentkit/pubsubbroker.py +311 -0
- ccai/agentkit/py.typed +0 -0
- ccai/agentkit/reconnecttransportaction.py +47 -0
- ccai/agentkit/regexoutputparser.py +68 -0
- ccai/agentkit/requestresponsehandler.py +274 -0
- ccai/agentkit/resetcircuitbreakeraction.py +48 -0
- ccai/agentkit/resilienceconfiguration.py +191 -0
- ccai/agentkit/resilienceerrors.py +103 -0
- ccai/agentkit/resiliencepipeline.py +201 -0
- ccai/agentkit/retryattempt.py +158 -0
- ccai/agentkit/retryexecutor.py +157 -0
- ccai/agentkit/retrypolicy.py +195 -0
- ccai/agentkit/retryresult.py +186 -0
- ccai/agentkit/selfhealingaction.py +42 -0
- ccai/agentkit/selfhealingpolicy.py +67 -0
- ccai/agentkit/selfhealingresult.py +130 -0
- ccai/agentkit/stepexecutionstatus.py +52 -0
- ccai/agentkit/stepresult.py +198 -0
- ccai/agentkit/steps/__init__.py +9 -0
- ccai/agentkit/steps/agentstep.py +247 -0
- ccai/agentkit/steps/approvalstep.py +276 -0
- ccai/agentkit/steps/llmstep.py +403 -0
- ccai/agentkit/steps/subworkflowstep.py +270 -0
- ccai/agentkit/steps/toolstep.py +265 -0
- ccai/agentkit/structuredlogentry.py +222 -0
- ccai/agentkit/structuredlogger.py +189 -0
- ccai/agentkit/subscription.py +141 -0
- ccai/agentkit/threadedagent.py +94 -0
- ccai/agentkit/tokenusage.py +136 -0
- ccai/agentkit/tool.py +203 -0
- ccai/agentkit/toolchain.py +268 -0
- ccai/agentkit/toolchainexecutor.py +134 -0
- ccai/agentkit/toolchainresult.py +166 -0
- ccai/agentkit/tooldescriptor.py +203 -0
- ccai/agentkit/toolerrors.py +160 -0
- ccai/agentkit/toolexecutor.py +168 -0
- ccai/agentkit/toolfactory.py +60 -0
- ccai/agentkit/toolregistry.py +184 -0
- ccai/agentkit/toolresult.py +142 -0
- ccai/agentkit/toolschema.py +197 -0
- ccai/agentkit/tracecontext.py +294 -0
- ccai/agentkit/traceevent.py +166 -0
- ccai/agentkit/traceexporter.py +305 -0
- ccai/agentkit/tracer.py +234 -0
- ccai/agentkit/tracespan.py +349 -0
- ccai/agentkit/transitionrecord.py +84 -0
- ccai/agentkit/transport.py +334 -0
- ccai/agentkit/transportconfiguration.py +436 -0
- ccai/agentkit/transporthealthcheck.py +36 -0
- ccai/agentkit/transportregistry.py +224 -0
- ccai/agentkit/transports/__init__.py +28 -0
- ccai/agentkit/transports/grpctransport.py +410 -0
- ccai/agentkit/transports/httptransport.py +423 -0
- ccai/agentkit/transports/messagequeuetransport.py +489 -0
- ccai/agentkit/transports/websockettransport.py +473 -0
- ccai/agentkit/workflowcheckpoint.py +208 -0
- ccai/agentkit/workflowconfiguration.py +295 -0
- ccai/agentkit/workflowcontext.py +249 -0
- ccai/agentkit/workflowdefinition.py +790 -0
- ccai/agentkit/workflowedge.py +128 -0
- ccai/agentkit/workflowerrors.py +295 -0
- ccai/agentkit/workflowexecutionstatus.py +48 -0
- ccai/agentkit/workflowexecutor.py +1121 -0
- ccai/agentkit/workflowregistry.py +185 -0
- ccai/agentkit/workflowresult.py +250 -0
- ccai/agentkit/workflowstep.py +195 -0
- codecraftai_agent_kit-1.3.0.dist-info/METADATA +99 -0
- codecraftai_agent_kit-1.3.0.dist-info/RECORD +230 -0
- codecraftai_agent_kit-1.3.0.dist-info/WHEEL +4 -0
- codecraftai_agent_kit-1.3.0.dist-info/licenses/LICENSE.md +204 -0
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Exception classes for the Memory & Context Management feature.
|
|
3
|
+
|
|
4
|
+
Provides MemoryStoreError for memory backend operation failures
|
|
5
|
+
and ContextWindowError for context window fitting failures.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from typing import Optional
|
|
9
|
+
|
|
10
|
+
from ccai.agentkit.errors import AgentKitError
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class MemoryStoreError(AgentKitError):
|
|
14
|
+
"""
|
|
15
|
+
Raised when a MemoryStore operation fails due to a backend error
|
|
16
|
+
(connection failure, write error, query error).
|
|
17
|
+
|
|
18
|
+
:param store_name: The name of the store where the error occurred.
|
|
19
|
+
:param operation: The operation that failed (store, retrieve, search, etc.).
|
|
20
|
+
:param cause: The original exception that caused the failure.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
def __init__(self, store_name: str, operation: str, cause: Optional[Exception] = None) -> None:
|
|
24
|
+
self._store_name = store_name
|
|
25
|
+
self._operation = operation
|
|
26
|
+
|
|
27
|
+
errmsg = self._format_message(store_name=store_name, operation=operation, cause=cause)
|
|
28
|
+
super().__init__(errmsg, cause=cause)
|
|
29
|
+
|
|
30
|
+
return
|
|
31
|
+
|
|
32
|
+
@property
|
|
33
|
+
def store_name(self) -> str:
|
|
34
|
+
"""
|
|
35
|
+
The name of the store where the error occurred.
|
|
36
|
+
|
|
37
|
+
:returns: The store name string.
|
|
38
|
+
"""
|
|
39
|
+
return self._store_name
|
|
40
|
+
|
|
41
|
+
@property
|
|
42
|
+
def operation(self) -> str:
|
|
43
|
+
"""
|
|
44
|
+
The operation that failed.
|
|
45
|
+
|
|
46
|
+
:returns: The operation name string.
|
|
47
|
+
"""
|
|
48
|
+
return self._operation
|
|
49
|
+
|
|
50
|
+
def _format_message(self, store_name: str, operation: str, cause: Optional[Exception] = None) -> str:
|
|
51
|
+
"""
|
|
52
|
+
Builds a descriptive error message from the store name, operation, and cause.
|
|
53
|
+
|
|
54
|
+
:param store_name: The name of the store where the error occurred.
|
|
55
|
+
:param operation: The operation that failed.
|
|
56
|
+
:param cause: The original exception.
|
|
57
|
+
|
|
58
|
+
:returns: A formatted error message string.
|
|
59
|
+
"""
|
|
60
|
+
cause_str = str(cause) if cause is not None else "unknown error"
|
|
61
|
+
errmsg = "MemoryStoreError in store {!r} during operation {!r}: {}".format(
|
|
62
|
+
store_name, operation, cause_str
|
|
63
|
+
)
|
|
64
|
+
return errmsg
|
|
65
|
+
|
|
66
|
+
def __repr__(self) -> str:
|
|
67
|
+
"""
|
|
68
|
+
Returns a detailed string representation including class name,
|
|
69
|
+
store name, and operation.
|
|
70
|
+
|
|
71
|
+
:returns: A repr string for debugging.
|
|
72
|
+
"""
|
|
73
|
+
repr_str = "{}(store_name={!r}, operation={!r})".format(
|
|
74
|
+
self.__class__.__name__, self._store_name, self._operation
|
|
75
|
+
)
|
|
76
|
+
return repr_str
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class ContextWindowError(AgentKitError):
|
|
80
|
+
"""
|
|
81
|
+
Raised when the ContextWindow cannot produce a valid context
|
|
82
|
+
within the configured token limit or when summarization fails.
|
|
83
|
+
|
|
84
|
+
:param max_tokens: The maximum token count that was configured.
|
|
85
|
+
:param strategy: The strategy name that was in use.
|
|
86
|
+
:param message: A descriptive error message.
|
|
87
|
+
"""
|
|
88
|
+
|
|
89
|
+
def __init__(self, max_tokens: int, strategy: str, message: str) -> None:
|
|
90
|
+
self._max_tokens = max_tokens
|
|
91
|
+
self._strategy = strategy
|
|
92
|
+
self._error_message = message
|
|
93
|
+
|
|
94
|
+
super().__init__(message)
|
|
95
|
+
|
|
96
|
+
return
|
|
97
|
+
|
|
98
|
+
@property
|
|
99
|
+
def max_tokens(self) -> int:
|
|
100
|
+
"""
|
|
101
|
+
The maximum token count that was configured.
|
|
102
|
+
|
|
103
|
+
:returns: The max tokens integer.
|
|
104
|
+
"""
|
|
105
|
+
return self._max_tokens
|
|
106
|
+
|
|
107
|
+
@property
|
|
108
|
+
def strategy(self) -> str:
|
|
109
|
+
"""
|
|
110
|
+
The strategy name that was in use when the error occurred.
|
|
111
|
+
|
|
112
|
+
:returns: The strategy name string.
|
|
113
|
+
"""
|
|
114
|
+
return self._strategy
|
|
115
|
+
|
|
116
|
+
@property
|
|
117
|
+
def error_message(self) -> str:
|
|
118
|
+
"""
|
|
119
|
+
The descriptive error message.
|
|
120
|
+
|
|
121
|
+
:returns: The error message string.
|
|
122
|
+
"""
|
|
123
|
+
return self._error_message
|
|
124
|
+
|
|
125
|
+
def __repr__(self) -> str:
|
|
126
|
+
"""
|
|
127
|
+
Returns a detailed string representation including class name,
|
|
128
|
+
max tokens, strategy, and message.
|
|
129
|
+
|
|
130
|
+
:returns: A repr string for debugging.
|
|
131
|
+
"""
|
|
132
|
+
repr_str = "{}(max_tokens={}, strategy={!r}, message={!r})".format(
|
|
133
|
+
self.__class__.__name__, self._max_tokens, self._strategy, self._error_message
|
|
134
|
+
)
|
|
135
|
+
return repr_str
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Internal indexing component for efficient tag-based, metadata-based,
|
|
3
|
+
and semantic similarity search over MemoryEntry objects.
|
|
4
|
+
|
|
5
|
+
Maintains a searchable index supporting tag filtering, metadata filtering,
|
|
6
|
+
scope filtering, time range filtering, and cosine similarity ranking
|
|
7
|
+
when embeddings are available.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import math
|
|
11
|
+
|
|
12
|
+
from ccai.agentkit.memoryentry import MemoryEntry
|
|
13
|
+
from ccai.agentkit.memoryquery import MemoryQuery
|
|
14
|
+
from ccai.agentkit.memoryqueryresult import MemoryQueryResult
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class MemoryIndex:
|
|
18
|
+
"""
|
|
19
|
+
Internal indexing component for efficient tag-based, metadata-based,
|
|
20
|
+
and semantic similarity search over MemoryEntry objects.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
def __init__(self) -> None:
|
|
24
|
+
"""
|
|
25
|
+
Constructs a MemoryIndex with empty entries, tag index,
|
|
26
|
+
and metadata index dictionaries.
|
|
27
|
+
"""
|
|
28
|
+
self._entries = {}
|
|
29
|
+
self._tag_index = {}
|
|
30
|
+
self._metadata_index = {}
|
|
31
|
+
return
|
|
32
|
+
|
|
33
|
+
def add(self, entry: MemoryEntry) -> None:
|
|
34
|
+
"""
|
|
35
|
+
Adds a MemoryEntry to the index, indexing by identifier,
|
|
36
|
+
tags, and metadata key-value pairs.
|
|
37
|
+
|
|
38
|
+
:param entry: The MemoryEntry to index.
|
|
39
|
+
"""
|
|
40
|
+
self._entries[entry.identifier] = entry
|
|
41
|
+
|
|
42
|
+
for tag in entry.tags:
|
|
43
|
+
if tag not in self._tag_index:
|
|
44
|
+
self._tag_index[tag] = set()
|
|
45
|
+
self._tag_index[tag].add(entry.identifier)
|
|
46
|
+
|
|
47
|
+
for key in entry.metadata:
|
|
48
|
+
compound_key = (key, entry.metadata[key])
|
|
49
|
+
if compound_key not in self._metadata_index:
|
|
50
|
+
self._metadata_index[compound_key] = set()
|
|
51
|
+
self._metadata_index[compound_key].add(entry.identifier)
|
|
52
|
+
|
|
53
|
+
return
|
|
54
|
+
|
|
55
|
+
def remove(self, identifier: str) -> None:
|
|
56
|
+
"""
|
|
57
|
+
Removes a MemoryEntry from the index by identifier,
|
|
58
|
+
cleaning up all tag and metadata index references.
|
|
59
|
+
|
|
60
|
+
:param identifier: The entry identifier to remove.
|
|
61
|
+
"""
|
|
62
|
+
if identifier not in self._entries:
|
|
63
|
+
return
|
|
64
|
+
|
|
65
|
+
entry = self._entries[identifier]
|
|
66
|
+
|
|
67
|
+
for tag in entry.tags:
|
|
68
|
+
if tag in self._tag_index:
|
|
69
|
+
self._tag_index[tag].discard(identifier)
|
|
70
|
+
|
|
71
|
+
for key in entry.metadata:
|
|
72
|
+
compound_key = (key, entry.metadata[key])
|
|
73
|
+
if compound_key in self._metadata_index:
|
|
74
|
+
self._metadata_index[compound_key].discard(identifier)
|
|
75
|
+
|
|
76
|
+
del self._entries[identifier]
|
|
77
|
+
return
|
|
78
|
+
|
|
79
|
+
def clear(self) -> None:
|
|
80
|
+
"""
|
|
81
|
+
Removes all entries from the index, resetting all indexes.
|
|
82
|
+
"""
|
|
83
|
+
self._entries = {}
|
|
84
|
+
self._tag_index = {}
|
|
85
|
+
self._metadata_index = {}
|
|
86
|
+
return
|
|
87
|
+
|
|
88
|
+
def contains(self, identifier: str) -> bool:
|
|
89
|
+
"""
|
|
90
|
+
Returns True if an entry with the given identifier exists.
|
|
91
|
+
|
|
92
|
+
:param identifier: The entry identifier to check.
|
|
93
|
+
|
|
94
|
+
:returns: True if the entry exists, False otherwise.
|
|
95
|
+
"""
|
|
96
|
+
rtnval = identifier in self._entries
|
|
97
|
+
return rtnval
|
|
98
|
+
|
|
99
|
+
def get(self, identifier: str) -> MemoryEntry:
|
|
100
|
+
"""
|
|
101
|
+
Returns the MemoryEntry with the given identifier, or None.
|
|
102
|
+
|
|
103
|
+
:param identifier: The entry identifier.
|
|
104
|
+
|
|
105
|
+
:returns: The MemoryEntry or None.
|
|
106
|
+
"""
|
|
107
|
+
rtnval = self._entries.get(identifier)
|
|
108
|
+
return rtnval
|
|
109
|
+
|
|
110
|
+
@property
|
|
111
|
+
def count(self) -> int:
|
|
112
|
+
"""
|
|
113
|
+
The number of entries in the index.
|
|
114
|
+
|
|
115
|
+
:returns: The entry count as an integer.
|
|
116
|
+
"""
|
|
117
|
+
rtnval = len(self._entries)
|
|
118
|
+
return rtnval
|
|
119
|
+
|
|
120
|
+
def search(self, query: MemoryQuery, query_embedding: list = None) -> MemoryQueryResult:
|
|
121
|
+
"""
|
|
122
|
+
Executes a search against the index using the given query.
|
|
123
|
+
Applies tag, metadata, scope, and time range filters, then
|
|
124
|
+
ranks by cosine similarity when a query embedding is provided.
|
|
125
|
+
|
|
126
|
+
:param query: The MemoryQuery with filter criteria.
|
|
127
|
+
:param query_embedding: Optional embedding vector for semantic search.
|
|
128
|
+
|
|
129
|
+
:returns: A MemoryQueryResult with matching entries and scores.
|
|
130
|
+
"""
|
|
131
|
+
candidate_ids = set(self._entries.keys())
|
|
132
|
+
|
|
133
|
+
if query.tags is not None and len(query.tags) > 0:
|
|
134
|
+
for tag in query.tags:
|
|
135
|
+
if tag in self._tag_index:
|
|
136
|
+
candidate_ids = candidate_ids.intersection(self._tag_index[tag])
|
|
137
|
+
else:
|
|
138
|
+
candidate_ids = set()
|
|
139
|
+
break
|
|
140
|
+
|
|
141
|
+
if query.metadata is not None and len(query.metadata) > 0:
|
|
142
|
+
for key, value in query.metadata.items():
|
|
143
|
+
compound_key = (key, value)
|
|
144
|
+
if compound_key in self._metadata_index:
|
|
145
|
+
candidate_ids = candidate_ids.intersection(self._metadata_index[compound_key])
|
|
146
|
+
else:
|
|
147
|
+
candidate_ids = set()
|
|
148
|
+
break
|
|
149
|
+
|
|
150
|
+
if query.scope is not None:
|
|
151
|
+
filtered = set()
|
|
152
|
+
for cid in candidate_ids:
|
|
153
|
+
entry = self._entries[cid]
|
|
154
|
+
if entry.scope == query.scope:
|
|
155
|
+
filtered.add(cid)
|
|
156
|
+
candidate_ids = filtered
|
|
157
|
+
|
|
158
|
+
if query.start_time is not None or query.end_time is not None:
|
|
159
|
+
filtered = set()
|
|
160
|
+
for cid in candidate_ids:
|
|
161
|
+
entry = self._entries[cid]
|
|
162
|
+
if query.start_time is not None and entry.created_at < query.start_time:
|
|
163
|
+
continue
|
|
164
|
+
if query.end_time is not None and entry.created_at > query.end_time:
|
|
165
|
+
continue
|
|
166
|
+
filtered.add(cid)
|
|
167
|
+
candidate_ids = filtered
|
|
168
|
+
|
|
169
|
+
entries = [self._entries[cid] for cid in candidate_ids]
|
|
170
|
+
scores = None
|
|
171
|
+
|
|
172
|
+
if query_embedding is not None and len(query_embedding) > 0:
|
|
173
|
+
scored_entries = []
|
|
174
|
+
for entry in entries:
|
|
175
|
+
if entry.embedding is not None:
|
|
176
|
+
score = self._cosine_similarity(query_embedding, entry.embedding)
|
|
177
|
+
if query.min_relevance is not None and score < query.min_relevance:
|
|
178
|
+
continue
|
|
179
|
+
scored_entries.append((entry, score))
|
|
180
|
+
|
|
181
|
+
scored_entries.sort(key=lambda pair: pair[1], reverse=True)
|
|
182
|
+
entries = [pair[0] for pair in scored_entries]
|
|
183
|
+
scores = [pair[1] for pair in scored_entries]
|
|
184
|
+
|
|
185
|
+
if query.max_results is not None and len(entries) > query.max_results:
|
|
186
|
+
entries = entries[:query.max_results]
|
|
187
|
+
if scores is not None:
|
|
188
|
+
scores = scores[:query.max_results]
|
|
189
|
+
|
|
190
|
+
total_count = len(entries)
|
|
191
|
+
rtnval = MemoryQueryResult(entries=entries, scores=scores, total_count=total_count)
|
|
192
|
+
return rtnval
|
|
193
|
+
|
|
194
|
+
@staticmethod
|
|
195
|
+
def _cosine_similarity(vec_a: list, vec_b: list) -> float:
|
|
196
|
+
"""
|
|
197
|
+
Computes cosine similarity between two vectors.
|
|
198
|
+
|
|
199
|
+
:param vec_a: First vector as a list of floats.
|
|
200
|
+
:param vec_b: Second vector as a list of floats.
|
|
201
|
+
|
|
202
|
+
:returns: Cosine similarity as a float between -1 and 1.
|
|
203
|
+
"""
|
|
204
|
+
dot_product = sum(a * b for a, b in zip(vec_a, vec_b))
|
|
205
|
+
magnitude_a = math.sqrt(sum(a * a for a in vec_a))
|
|
206
|
+
magnitude_b = math.sqrt(sum(b * b for b in vec_b))
|
|
207
|
+
|
|
208
|
+
if magnitude_a == 0.0 or magnitude_b == 0.0:
|
|
209
|
+
rtnval = 0.0
|
|
210
|
+
return rtnval
|
|
211
|
+
|
|
212
|
+
rtnval = dot_product / (magnitude_a * magnitude_b)
|
|
213
|
+
return rtnval
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Immutable object representing a search request against a MemoryStore.
|
|
3
|
+
|
|
4
|
+
Supports filtering by tags, metadata, scope, time range, and
|
|
5
|
+
semantic similarity.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
from datetime import datetime
|
|
10
|
+
from typing import Optional
|
|
11
|
+
|
|
12
|
+
from ccai.agentkit.memoryscope import MemoryScope
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class MemoryQuery:
|
|
16
|
+
"""
|
|
17
|
+
Immutable object representing a search request against a MemoryStore.
|
|
18
|
+
Supports filtering by tags, metadata, scope, time range, and
|
|
19
|
+
semantic similarity.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
def __init__(self, tags: list = None, metadata: dict = None,
|
|
23
|
+
scope: MemoryScope = None, start_time: datetime = None,
|
|
24
|
+
end_time: datetime = None, semantic_text: str = None,
|
|
25
|
+
max_results: int = None, min_relevance: float = None) -> None:
|
|
26
|
+
"""
|
|
27
|
+
Constructs a MemoryQuery.
|
|
28
|
+
|
|
29
|
+
:param tags: Optional list of required tags.
|
|
30
|
+
:param metadata: Optional metadata key-value pairs to match.
|
|
31
|
+
:param scope: Optional MemoryScope filter.
|
|
32
|
+
:param start_time: Optional start of time range.
|
|
33
|
+
:param end_time: Optional end of time range.
|
|
34
|
+
:param semantic_text: Optional semantic query text for similarity search.
|
|
35
|
+
:param max_results: Optional maximum number of results.
|
|
36
|
+
:param min_relevance: Optional minimum relevance score threshold.
|
|
37
|
+
"""
|
|
38
|
+
self._tags = list(tags) if tags is not None else None
|
|
39
|
+
self._metadata = dict(metadata) if metadata is not None else None
|
|
40
|
+
self._scope = scope
|
|
41
|
+
self._start_time = start_time
|
|
42
|
+
self._end_time = end_time
|
|
43
|
+
self._semantic_text = semantic_text
|
|
44
|
+
self._max_results = max_results
|
|
45
|
+
self._min_relevance = min_relevance
|
|
46
|
+
return
|
|
47
|
+
|
|
48
|
+
@property
|
|
49
|
+
def tags(self) -> Optional[list]:
|
|
50
|
+
"""
|
|
51
|
+
The list of required tags, or None if not set.
|
|
52
|
+
Returns a defensive copy.
|
|
53
|
+
|
|
54
|
+
:returns: A list of tag strings or None.
|
|
55
|
+
"""
|
|
56
|
+
if self._tags is not None:
|
|
57
|
+
rtnval = list(self._tags)
|
|
58
|
+
return rtnval
|
|
59
|
+
return None
|
|
60
|
+
|
|
61
|
+
@property
|
|
62
|
+
def metadata(self) -> Optional[dict]:
|
|
63
|
+
"""
|
|
64
|
+
The metadata key-value pairs to match, or None if not set.
|
|
65
|
+
Returns a defensive copy.
|
|
66
|
+
|
|
67
|
+
:returns: A dictionary or None.
|
|
68
|
+
"""
|
|
69
|
+
if self._metadata is not None:
|
|
70
|
+
rtnval = dict(self._metadata)
|
|
71
|
+
return rtnval
|
|
72
|
+
return None
|
|
73
|
+
|
|
74
|
+
@property
|
|
75
|
+
def scope(self) -> Optional[MemoryScope]:
|
|
76
|
+
"""
|
|
77
|
+
The MemoryScope filter, or None if not set.
|
|
78
|
+
|
|
79
|
+
:returns: A MemoryScope value or None.
|
|
80
|
+
"""
|
|
81
|
+
return self._scope
|
|
82
|
+
|
|
83
|
+
@property
|
|
84
|
+
def start_time(self) -> Optional[datetime]:
|
|
85
|
+
"""
|
|
86
|
+
The start of the time range filter, or None if not set.
|
|
87
|
+
|
|
88
|
+
:returns: A datetime object or None.
|
|
89
|
+
"""
|
|
90
|
+
return self._start_time
|
|
91
|
+
|
|
92
|
+
@property
|
|
93
|
+
def end_time(self) -> Optional[datetime]:
|
|
94
|
+
"""
|
|
95
|
+
The end of the time range filter, or None if not set.
|
|
96
|
+
|
|
97
|
+
:returns: A datetime object or None.
|
|
98
|
+
"""
|
|
99
|
+
return self._end_time
|
|
100
|
+
|
|
101
|
+
@property
|
|
102
|
+
def semantic_text(self) -> Optional[str]:
|
|
103
|
+
"""
|
|
104
|
+
The semantic query text for similarity search, or None if not set.
|
|
105
|
+
|
|
106
|
+
:returns: A string or None.
|
|
107
|
+
"""
|
|
108
|
+
return self._semantic_text
|
|
109
|
+
|
|
110
|
+
@property
|
|
111
|
+
def max_results(self) -> Optional[int]:
|
|
112
|
+
"""
|
|
113
|
+
The maximum number of results, or None if not set.
|
|
114
|
+
|
|
115
|
+
:returns: An integer or None.
|
|
116
|
+
"""
|
|
117
|
+
return self._max_results
|
|
118
|
+
|
|
119
|
+
@property
|
|
120
|
+
def min_relevance(self) -> Optional[float]:
|
|
121
|
+
"""
|
|
122
|
+
The minimum relevance score threshold, or None if not set.
|
|
123
|
+
|
|
124
|
+
:returns: A float or None.
|
|
125
|
+
"""
|
|
126
|
+
return self._min_relevance
|
|
127
|
+
|
|
128
|
+
def as_dict(self) -> dict:
|
|
129
|
+
"""
|
|
130
|
+
Returns a dictionary representation of the query fields.
|
|
131
|
+
|
|
132
|
+
:returns: A dictionary with all query fields.
|
|
133
|
+
"""
|
|
134
|
+
rtnval = {
|
|
135
|
+
"tags": list(self._tags) if self._tags is not None else None,
|
|
136
|
+
"metadata": dict(self._metadata) if self._metadata is not None else None,
|
|
137
|
+
"scope": self._scope.value if self._scope is not None else None,
|
|
138
|
+
"start_time": self._start_time.isoformat() if self._start_time is not None else None,
|
|
139
|
+
"end_time": self._end_time.isoformat() if self._end_time is not None else None,
|
|
140
|
+
"semantic_text": self._semantic_text,
|
|
141
|
+
"max_results": self._max_results,
|
|
142
|
+
"min_relevance": self._min_relevance,
|
|
143
|
+
}
|
|
144
|
+
return rtnval
|
|
145
|
+
|
|
146
|
+
def to_json(self) -> str:
|
|
147
|
+
"""
|
|
148
|
+
Returns a JSON string representation of the query fields.
|
|
149
|
+
|
|
150
|
+
:returns: A JSON string.
|
|
151
|
+
"""
|
|
152
|
+
rtnval = json.dumps(self.as_dict())
|
|
153
|
+
return rtnval
|
|
154
|
+
|
|
155
|
+
@classmethod
|
|
156
|
+
def from_dict(cls, data: dict) -> "MemoryQuery":
|
|
157
|
+
"""
|
|
158
|
+
Constructs a MemoryQuery from a dictionary.
|
|
159
|
+
|
|
160
|
+
:param data: A dictionary with query fields.
|
|
161
|
+
|
|
162
|
+
:returns: A MemoryQuery instance.
|
|
163
|
+
"""
|
|
164
|
+
scope = None
|
|
165
|
+
if "scope" in data and data["scope"] is not None:
|
|
166
|
+
scope = MemoryScope.from_string(data["scope"])
|
|
167
|
+
|
|
168
|
+
start_time = None
|
|
169
|
+
if "start_time" in data and data["start_time"] is not None:
|
|
170
|
+
start_time = datetime.fromisoformat(data["start_time"])
|
|
171
|
+
|
|
172
|
+
end_time = None
|
|
173
|
+
if "end_time" in data and data["end_time"] is not None:
|
|
174
|
+
end_time = datetime.fromisoformat(data["end_time"])
|
|
175
|
+
|
|
176
|
+
rtnval = cls(
|
|
177
|
+
tags=data.get("tags"),
|
|
178
|
+
metadata=data.get("metadata"),
|
|
179
|
+
scope=scope,
|
|
180
|
+
start_time=start_time,
|
|
181
|
+
end_time=end_time,
|
|
182
|
+
semantic_text=data.get("semantic_text"),
|
|
183
|
+
max_results=data.get("max_results"),
|
|
184
|
+
min_relevance=data.get("min_relevance"),
|
|
185
|
+
)
|
|
186
|
+
return rtnval
|
|
187
|
+
|
|
188
|
+
@classmethod
|
|
189
|
+
def from_json(cls, json_str: str) -> "MemoryQuery":
|
|
190
|
+
"""
|
|
191
|
+
Deserializes a JSON string into a MemoryQuery instance.
|
|
192
|
+
|
|
193
|
+
:param json_str: A JSON string.
|
|
194
|
+
|
|
195
|
+
:returns: A MemoryQuery instance.
|
|
196
|
+
"""
|
|
197
|
+
data = json.loads(json_str)
|
|
198
|
+
rtnval = cls.from_dict(data)
|
|
199
|
+
return rtnval
|
|
200
|
+
|
|
201
|
+
def __repr__(self) -> str:
|
|
202
|
+
criteria = []
|
|
203
|
+
if self._tags is not None:
|
|
204
|
+
criteria.append("tags={}".format(len(self._tags)))
|
|
205
|
+
if self._metadata is not None:
|
|
206
|
+
criteria.append("metadata={}".format(len(self._metadata)))
|
|
207
|
+
if self._scope is not None:
|
|
208
|
+
criteria.append("scope={}".format(self._scope.value))
|
|
209
|
+
if self._semantic_text is not None:
|
|
210
|
+
criteria.append("semantic=True")
|
|
211
|
+
if self._max_results is not None:
|
|
212
|
+
criteria.append("max={}".format(self._max_results))
|
|
213
|
+
summary = ", ".join(criteria) if len(criteria) > 0 else "no filters"
|
|
214
|
+
rtnval = "{}({})".format(self.__class__.__name__, summary)
|
|
215
|
+
return rtnval
|
|
216
|
+
|
|
217
|
+
def __str__(self) -> str:
|
|
218
|
+
criteria = []
|
|
219
|
+
if self._tags is not None:
|
|
220
|
+
criteria.append("tags: {}".format(self._tags))
|
|
221
|
+
if self._metadata is not None:
|
|
222
|
+
criteria.append("metadata: {}".format(list(self._metadata.keys())))
|
|
223
|
+
if self._scope is not None:
|
|
224
|
+
criteria.append("scope: {}".format(self._scope.value))
|
|
225
|
+
if self._start_time is not None or self._end_time is not None:
|
|
226
|
+
criteria.append("time range: {} to {}".format(self._start_time, self._end_time))
|
|
227
|
+
if self._semantic_text is not None:
|
|
228
|
+
preview = self._semantic_text[:50] + "..." if len(self._semantic_text) > 50 else self._semantic_text
|
|
229
|
+
criteria.append("semantic: {!r}".format(preview))
|
|
230
|
+
summary = "; ".join(criteria) if len(criteria) > 0 else "no filters"
|
|
231
|
+
rtnval = "MemoryQuery: {}".format(summary)
|
|
232
|
+
return rtnval
|
|
233
|
+
|
|
234
|
+
def __eq__(self, other) -> bool:
|
|
235
|
+
if not isinstance(other, MemoryQuery):
|
|
236
|
+
rtnval = False
|
|
237
|
+
return rtnval
|
|
238
|
+
rtnval = (
|
|
239
|
+
self._tags == other._tags
|
|
240
|
+
and self._metadata == other._metadata
|
|
241
|
+
and self._scope == other._scope
|
|
242
|
+
and self._start_time == other._start_time
|
|
243
|
+
and self._end_time == other._end_time
|
|
244
|
+
and self._semantic_text == other._semantic_text
|
|
245
|
+
and self._max_results == other._max_results
|
|
246
|
+
and self._min_relevance == other._min_relevance
|
|
247
|
+
)
|
|
248
|
+
return rtnval
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Immutable object encapsulating the result of a MemoryQuery.
|
|
3
|
+
|
|
4
|
+
Contains matching MemoryEntry objects, optional relevance scores,
|
|
5
|
+
and the total count of matches.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from typing import Optional
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class MemoryQueryResult:
|
|
12
|
+
"""
|
|
13
|
+
Immutable object encapsulating the result of a MemoryQuery.
|
|
14
|
+
Contains matching MemoryEntry objects, optional relevance scores,
|
|
15
|
+
and the total count of matches.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
def __init__(self, entries: list, scores: list = None, total_count: int = None) -> None:
|
|
19
|
+
"""
|
|
20
|
+
Constructs a MemoryQueryResult.
|
|
21
|
+
|
|
22
|
+
:param entries: List of matching MemoryEntry objects.
|
|
23
|
+
:param scores: Optional list of relevance scores as floats.
|
|
24
|
+
:param total_count: Optional total count of matches. Defaults to len(entries).
|
|
25
|
+
"""
|
|
26
|
+
self._entries = list(entries)
|
|
27
|
+
self._scores = list(scores) if scores is not None else None
|
|
28
|
+
self._total_count = total_count if total_count is not None else len(entries)
|
|
29
|
+
return
|
|
30
|
+
|
|
31
|
+
@property
|
|
32
|
+
def entries(self) -> list:
|
|
33
|
+
"""
|
|
34
|
+
The list of matching MemoryEntry objects.
|
|
35
|
+
Returns a defensive copy.
|
|
36
|
+
|
|
37
|
+
:returns: A list of MemoryEntry objects.
|
|
38
|
+
"""
|
|
39
|
+
rtnval = list(self._entries)
|
|
40
|
+
return rtnval
|
|
41
|
+
|
|
42
|
+
@property
|
|
43
|
+
def scores(self) -> Optional[list]:
|
|
44
|
+
"""
|
|
45
|
+
The list of relevance scores, or None if not set.
|
|
46
|
+
Returns a defensive copy.
|
|
47
|
+
|
|
48
|
+
:returns: A list of floats or None.
|
|
49
|
+
"""
|
|
50
|
+
if self._scores is not None:
|
|
51
|
+
rtnval = list(self._scores)
|
|
52
|
+
return rtnval
|
|
53
|
+
return None
|
|
54
|
+
|
|
55
|
+
@property
|
|
56
|
+
def total_count(self) -> int:
|
|
57
|
+
"""
|
|
58
|
+
The total count of matches.
|
|
59
|
+
|
|
60
|
+
:returns: An integer.
|
|
61
|
+
"""
|
|
62
|
+
return self._total_count
|
|
63
|
+
|
|
64
|
+
def as_dict(self) -> dict:
|
|
65
|
+
"""
|
|
66
|
+
Returns a dictionary representation of the result fields.
|
|
67
|
+
|
|
68
|
+
:returns: A dictionary with entries, scores, and total_count.
|
|
69
|
+
"""
|
|
70
|
+
rtnval = {
|
|
71
|
+
"entries": [e.as_dict() for e in self._entries],
|
|
72
|
+
"scores": list(self._scores) if self._scores is not None else None,
|
|
73
|
+
"total_count": self._total_count,
|
|
74
|
+
}
|
|
75
|
+
return rtnval
|
|
76
|
+
|
|
77
|
+
def __repr__(self) -> str:
|
|
78
|
+
rtnval = "{}(count={})".format(self.__class__.__name__, self._total_count)
|
|
79
|
+
return rtnval
|
|
80
|
+
|
|
81
|
+
def __str__(self) -> str:
|
|
82
|
+
top_ids = [e.identifier for e in self._entries[:5]]
|
|
83
|
+
rtnval = "MemoryQueryResult: {} matches, top: [{}]".format(
|
|
84
|
+
self._total_count, ", ".join(top_ids)
|
|
85
|
+
)
|
|
86
|
+
return rtnval
|