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,173 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Built-in MemoryStore implementation that stores MemoryEntry objects
|
|
3
|
+
in process memory using dictionary-based indexing.
|
|
4
|
+
|
|
5
|
+
Suitable for development, testing, and short-lived agents where
|
|
6
|
+
persistence across process restarts is not required.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import logging
|
|
10
|
+
from typing import Optional
|
|
11
|
+
|
|
12
|
+
from ccai.agentkit.embeddingprovider import EmbeddingProvider
|
|
13
|
+
from ccai.agentkit.errors import SemanticError
|
|
14
|
+
from ccai.agentkit.expirationpolicy import ExpirationPolicy
|
|
15
|
+
from ccai.agentkit.memoryerrors import MemoryStoreError
|
|
16
|
+
from ccai.agentkit.memoryentry import MemoryEntry
|
|
17
|
+
from ccai.agentkit.memoryindex import MemoryIndex
|
|
18
|
+
from ccai.agentkit.memoryquery import MemoryQuery
|
|
19
|
+
from ccai.agentkit.memoryqueryresult import MemoryQueryResult
|
|
20
|
+
from ccai.agentkit.memorystore import MemoryStore
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
logger = logging.getLogger("ccai.agentkit.memory")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class InMemoryStore(MemoryStore):
|
|
27
|
+
"""
|
|
28
|
+
Built-in MemoryStore implementation that stores MemoryEntry objects
|
|
29
|
+
in process memory using dictionary-based indexing. Indexes entries
|
|
30
|
+
by identifier, tags, and metadata keys for efficient retrieval.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
def __init__(self, store_name: str,
|
|
34
|
+
embedding_provider: EmbeddingProvider = None,
|
|
35
|
+
expiration_policy: ExpirationPolicy = None) -> None:
|
|
36
|
+
"""
|
|
37
|
+
Constructs an InMemoryStore.
|
|
38
|
+
|
|
39
|
+
:param store_name: The name of this memory store.
|
|
40
|
+
:param embedding_provider: Optional EmbeddingProvider for generating embeddings.
|
|
41
|
+
:param expiration_policy: Optional ExpirationPolicy for entry lifecycle.
|
|
42
|
+
|
|
43
|
+
:raises: SemanticError if store_name is empty.
|
|
44
|
+
"""
|
|
45
|
+
super().__init__(
|
|
46
|
+
store_name=store_name,
|
|
47
|
+
embedding_provider=embedding_provider,
|
|
48
|
+
expiration_policy=expiration_policy,
|
|
49
|
+
)
|
|
50
|
+
self._index = MemoryIndex()
|
|
51
|
+
return
|
|
52
|
+
|
|
53
|
+
@property
|
|
54
|
+
def count(self) -> int:
|
|
55
|
+
"""
|
|
56
|
+
Returns the count of stored MemoryEntry objects.
|
|
57
|
+
|
|
58
|
+
:returns: The entry count as an integer.
|
|
59
|
+
"""
|
|
60
|
+
rtnval = self._index.count
|
|
61
|
+
return rtnval
|
|
62
|
+
|
|
63
|
+
def store(self, entry: MemoryEntry) -> MemoryEntry:
|
|
64
|
+
"""
|
|
65
|
+
Stores a MemoryEntry in the in-memory index. Checks for duplicate
|
|
66
|
+
identifiers, applies the expiration policy, generates an embedding
|
|
67
|
+
if needed, and adds the entry to the index.
|
|
68
|
+
|
|
69
|
+
:param entry: The MemoryEntry to store.
|
|
70
|
+
|
|
71
|
+
:returns: The stored MemoryEntry (potentially with generated embedding and expiration).
|
|
72
|
+
:raises: SemanticError if a MemoryEntry with the same identifier already exists.
|
|
73
|
+
"""
|
|
74
|
+
if self._index.contains(identifier=entry.identifier):
|
|
75
|
+
errmsg = "A MemoryEntry with identifier {!r} already exists in store {!r}.".format(
|
|
76
|
+
entry.identifier, self._store_name
|
|
77
|
+
)
|
|
78
|
+
raise SemanticError(errmsg)
|
|
79
|
+
|
|
80
|
+
entry = self._apply_expiration_policy(entry=entry)
|
|
81
|
+
entry = self._generate_embedding_if_needed(entry=entry)
|
|
82
|
+
self._index.add(entry=entry)
|
|
83
|
+
|
|
84
|
+
logger.info(
|
|
85
|
+
"InMemoryStore %r stored entry %r with scope %s.",
|
|
86
|
+
self._store_name, entry.identifier, entry.scope.value
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
rtnval = entry
|
|
90
|
+
return rtnval
|
|
91
|
+
|
|
92
|
+
def retrieve(self, identifier: str) -> Optional[MemoryEntry]:
|
|
93
|
+
"""
|
|
94
|
+
Retrieves a MemoryEntry by identifier.
|
|
95
|
+
|
|
96
|
+
:param identifier: The entry identifier.
|
|
97
|
+
|
|
98
|
+
:returns: The MemoryEntry, or None if not found.
|
|
99
|
+
"""
|
|
100
|
+
rtnval = self._index.get(identifier=identifier)
|
|
101
|
+
return rtnval
|
|
102
|
+
|
|
103
|
+
def search(self, query: MemoryQuery) -> MemoryQueryResult:
|
|
104
|
+
"""
|
|
105
|
+
Executes a MemoryQuery against the in-memory index. When the query
|
|
106
|
+
includes semantic text, generates a query embedding using the
|
|
107
|
+
configured EmbeddingProvider and delegates to the index for
|
|
108
|
+
cosine similarity ranking.
|
|
109
|
+
|
|
110
|
+
:param query: The MemoryQuery with filter criteria.
|
|
111
|
+
|
|
112
|
+
:returns: A MemoryQueryResult with matching entries.
|
|
113
|
+
:raises: MemoryStoreError if semantic search is requested without an EmbeddingProvider.
|
|
114
|
+
"""
|
|
115
|
+
query_embedding = None
|
|
116
|
+
if query.semantic_text is not None:
|
|
117
|
+
if self._embedding_provider is None:
|
|
118
|
+
errmsg = "Semantic search requires an EmbeddingProvider, but none is configured for store {!r}.".format(
|
|
119
|
+
self._store_name
|
|
120
|
+
)
|
|
121
|
+
raise MemoryStoreError(
|
|
122
|
+
store_name=self._store_name,
|
|
123
|
+
operation="search",
|
|
124
|
+
cause=ValueError(errmsg),
|
|
125
|
+
)
|
|
126
|
+
query_embedding = self._embedding_provider.embed(text=query.semantic_text)
|
|
127
|
+
|
|
128
|
+
rtnval = self._index.search(query=query, query_embedding=query_embedding)
|
|
129
|
+
|
|
130
|
+
logger.info(
|
|
131
|
+
"InMemoryStore %r search returned %d entries.",
|
|
132
|
+
self._store_name, rtnval.total_count
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
return rtnval
|
|
136
|
+
|
|
137
|
+
def update(self, identifier: str, entry: MemoryEntry) -> MemoryEntry:
|
|
138
|
+
"""
|
|
139
|
+
Replaces a MemoryEntry by identifier. Removes the old entry from
|
|
140
|
+
the index, generates an embedding if needed, and adds the new entry.
|
|
141
|
+
|
|
142
|
+
:param identifier: The identifier of the entry to replace.
|
|
143
|
+
:param entry: The new MemoryEntry.
|
|
144
|
+
|
|
145
|
+
:returns: The updated MemoryEntry.
|
|
146
|
+
"""
|
|
147
|
+
self._index.remove(identifier=identifier)
|
|
148
|
+
entry = self._generate_embedding_if_needed(entry=entry)
|
|
149
|
+
self._index.add(entry=entry)
|
|
150
|
+
rtnval = entry
|
|
151
|
+
return rtnval
|
|
152
|
+
|
|
153
|
+
def delete(self, identifier: str) -> None:
|
|
154
|
+
"""
|
|
155
|
+
Removes a MemoryEntry by identifier from the in-memory index.
|
|
156
|
+
|
|
157
|
+
:param identifier: The entry identifier to remove.
|
|
158
|
+
"""
|
|
159
|
+
self._index.remove(identifier=identifier)
|
|
160
|
+
|
|
161
|
+
logger.info(
|
|
162
|
+
"InMemoryStore %r deleted entry %r.",
|
|
163
|
+
self._store_name, identifier
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
return
|
|
167
|
+
|
|
168
|
+
def clear(self) -> None:
|
|
169
|
+
"""
|
|
170
|
+
Removes all entries from the in-memory index.
|
|
171
|
+
"""
|
|
172
|
+
self._index.clear()
|
|
173
|
+
return
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Defines the JsonMessageSerializer class for serializing Python
|
|
3
|
+
objects to JSON-encoded bytes and deserializing JSON-encoded bytes
|
|
4
|
+
to Python objects.
|
|
5
|
+
|
|
6
|
+
Uses the standard library json module for encoding and decoding.
|
|
7
|
+
Raises MessageSerializationError with the object type on
|
|
8
|
+
non-serializable input and with the bytes length on invalid JSON
|
|
9
|
+
input.
|
|
10
|
+
|
|
11
|
+
.. module:: ccai.agentkit.jsonmessageserializer
|
|
12
|
+
:platform: Darwin, Linux, Unix, Windows
|
|
13
|
+
:synopsis: JSON serialization implementation for message payloads.
|
|
14
|
+
|
|
15
|
+
Requirements: 9.5, 9.8, 9.9
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
import json
|
|
19
|
+
|
|
20
|
+
from ccai.agentkit.messageserializer import MessageSerializer
|
|
21
|
+
from ccai.agentkit.messagingerrors import MessageSerializationError
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class JsonMessageSerializer(MessageSerializer):
|
|
25
|
+
"""
|
|
26
|
+
Serializes Python objects to JSON-encoded bytes and deserializes
|
|
27
|
+
JSON-encoded bytes to Python objects.
|
|
28
|
+
|
|
29
|
+
Uses UTF-8 encoding for the JSON byte representation.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
def __init__(self) -> None:
|
|
33
|
+
super().__init__(format_name="json", content_type="application/json")
|
|
34
|
+
return
|
|
35
|
+
|
|
36
|
+
def serialize(self, obj: object) -> bytes:
|
|
37
|
+
"""
|
|
38
|
+
Serializes a Python object to JSON-encoded bytes.
|
|
39
|
+
|
|
40
|
+
:param obj: The Python object to serialize. Must be
|
|
41
|
+
JSON-serializable (dict, list, str, int, float, bool,
|
|
42
|
+
None).
|
|
43
|
+
|
|
44
|
+
:returns: The JSON-encoded bytes using UTF-8 encoding.
|
|
45
|
+
:raises MessageSerializationError: If the object is not
|
|
46
|
+
JSON-serializable. The error detail includes the
|
|
47
|
+
object type.
|
|
48
|
+
"""
|
|
49
|
+
try:
|
|
50
|
+
json_str = json.dumps(obj)
|
|
51
|
+
rtnval = json_str.encode("utf-8")
|
|
52
|
+
except (TypeError, ValueError) as ex:
|
|
53
|
+
object_type = type(obj).__name__
|
|
54
|
+
detail = "Object of type '{}' is not JSON serializable: {}".format(
|
|
55
|
+
object_type, ex
|
|
56
|
+
)
|
|
57
|
+
raise MessageSerializationError(
|
|
58
|
+
format_name="json",
|
|
59
|
+
direction="serialize",
|
|
60
|
+
detail=detail
|
|
61
|
+
) from ex
|
|
62
|
+
|
|
63
|
+
return rtnval
|
|
64
|
+
|
|
65
|
+
def deserialize(self, data: bytes) -> object:
|
|
66
|
+
"""
|
|
67
|
+
Deserializes JSON-encoded bytes to a Python object.
|
|
68
|
+
|
|
69
|
+
:param data: The JSON-encoded bytes to deserialize.
|
|
70
|
+
|
|
71
|
+
:returns: The deserialized Python object.
|
|
72
|
+
:raises MessageSerializationError: If the bytes are not
|
|
73
|
+
valid JSON. The error detail includes the bytes length.
|
|
74
|
+
"""
|
|
75
|
+
try:
|
|
76
|
+
json_str = data.decode("utf-8")
|
|
77
|
+
rtnval = json.loads(json_str)
|
|
78
|
+
except (json.JSONDecodeError, UnicodeDecodeError, ValueError) as ex:
|
|
79
|
+
bytes_length = len(data)
|
|
80
|
+
detail = "Invalid JSON input ({} bytes): {}".format(
|
|
81
|
+
bytes_length, ex
|
|
82
|
+
)
|
|
83
|
+
raise MessageSerializationError(
|
|
84
|
+
format_name="json",
|
|
85
|
+
direction="deserialize",
|
|
86
|
+
detail=detail
|
|
87
|
+
) from ex
|
|
88
|
+
|
|
89
|
+
return rtnval
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Defines the JsonOutputParser class for parsing LLM response text as JSON.
|
|
3
|
+
|
|
4
|
+
JsonOutputParser extends OutputParser to handle JSON-formatted LLM
|
|
5
|
+
responses. It uses json.loads to parse the raw text and raises
|
|
6
|
+
LLMResponseParsingError when the text is not valid JSON.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
|
|
11
|
+
from ccai.agentkit.llmerrors import LLMResponseParsingError
|
|
12
|
+
from ccai.agentkit.outputparser import OutputParser
|
|
13
|
+
from ccai.agentkit.outputschema import OutputSchema
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class JsonOutputParser(OutputParser):
|
|
17
|
+
"""
|
|
18
|
+
Parses LLM response text as JSON.
|
|
19
|
+
|
|
20
|
+
Extends OutputParser with JSON-specific parsing logic. Optionally
|
|
21
|
+
validates the parsed result against an OutputSchema if one was
|
|
22
|
+
provided at construction time.
|
|
23
|
+
|
|
24
|
+
:param schema: Optional OutputSchema for post-parse validation.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
def __init__(self, schema: OutputSchema = None) -> None:
|
|
28
|
+
super().__init__(schema=schema)
|
|
29
|
+
return
|
|
30
|
+
|
|
31
|
+
def _parse_raw(self, raw_text: str) -> object:
|
|
32
|
+
"""
|
|
33
|
+
Parses the raw text as JSON.
|
|
34
|
+
|
|
35
|
+
:param raw_text: The raw LLM response text.
|
|
36
|
+
|
|
37
|
+
:returns: A Python dictionary or list.
|
|
38
|
+
:raises: LLMResponseParsingError if text is not valid JSON.
|
|
39
|
+
"""
|
|
40
|
+
try:
|
|
41
|
+
rtnval = json.loads(raw_text)
|
|
42
|
+
except json.JSONDecodeError as jde:
|
|
43
|
+
errmsg = "Failed to parse JSON: {}".format(str(jde))
|
|
44
|
+
raise LLMResponseParsingError(
|
|
45
|
+
parser_name=self.__class__.__name__,
|
|
46
|
+
raw_text=raw_text,
|
|
47
|
+
message=errmsg
|
|
48
|
+
) from jde
|
|
49
|
+
|
|
50
|
+
return rtnval
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Defines the LifecycleState enum representing the possible states
|
|
3
|
+
of an agent in the codecraftai-agent-kit framework.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import enum
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class LifecycleState(enum.Enum):
|
|
10
|
+
"""
|
|
11
|
+
Enum representing the lifecycle states of an agent.
|
|
12
|
+
|
|
13
|
+
Agents transition through these states according to the
|
|
14
|
+
valid transition rules defined in the AgentStateMachine.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
CREATED = "CREATED"
|
|
18
|
+
INITIALIZED = "INITIALIZED"
|
|
19
|
+
RUNNING = "RUNNING"
|
|
20
|
+
PAUSED = "PAUSED"
|
|
21
|
+
STOPPED = "STOPPED"
|
|
22
|
+
ERROR = "ERROR"
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Defines the LLMConversation class for managing ordered sequences of
|
|
3
|
+
LLMMessage objects.
|
|
4
|
+
|
|
5
|
+
LLMConversation is a mutable collection that supports appending messages,
|
|
6
|
+
truncating to a maximum count while preserving system messages, and
|
|
7
|
+
serialization to and from JSON.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
|
|
12
|
+
from ccai.agentkit.llmmessage import LLMMessage
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class LLMConversation:
|
|
16
|
+
"""
|
|
17
|
+
An ordered, mutable sequence of LLMMessage objects representing
|
|
18
|
+
a conversation history.
|
|
19
|
+
|
|
20
|
+
Provides methods for appending messages, truncating the conversation
|
|
21
|
+
while preserving system messages, and serializing to and from JSON.
|
|
22
|
+
|
|
23
|
+
:param messages: Optional initial list of LLMMessage objects.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
def __init__(self, messages: list = None) -> None:
|
|
27
|
+
self._messages = list(messages) if messages is not None else []
|
|
28
|
+
return
|
|
29
|
+
|
|
30
|
+
@property
|
|
31
|
+
def count(self) -> int:
|
|
32
|
+
"""
|
|
33
|
+
The number of messages in the conversation.
|
|
34
|
+
|
|
35
|
+
:returns: The message count as an integer.
|
|
36
|
+
"""
|
|
37
|
+
rtnval = len(self._messages)
|
|
38
|
+
return rtnval
|
|
39
|
+
|
|
40
|
+
@property
|
|
41
|
+
def messages(self) -> list:
|
|
42
|
+
"""
|
|
43
|
+
Returns a copy of the message list.
|
|
44
|
+
|
|
45
|
+
:returns: A list of LLMMessage objects.
|
|
46
|
+
"""
|
|
47
|
+
rtnval = list(self._messages)
|
|
48
|
+
return rtnval
|
|
49
|
+
|
|
50
|
+
def append(self, message: "LLMMessage") -> None:
|
|
51
|
+
"""
|
|
52
|
+
Adds an LLMMessage to the end of the conversation.
|
|
53
|
+
|
|
54
|
+
:param message: The LLMMessage to append.
|
|
55
|
+
"""
|
|
56
|
+
self._messages.append(message)
|
|
57
|
+
return
|
|
58
|
+
|
|
59
|
+
def truncate(self, max_messages: int) -> None:
|
|
60
|
+
"""
|
|
61
|
+
Removes the oldest non-system messages to fit within the limit,
|
|
62
|
+
preserving all system messages.
|
|
63
|
+
|
|
64
|
+
System messages are always retained. When the total message count
|
|
65
|
+
exceeds max_messages, the oldest non-system messages are removed
|
|
66
|
+
first. If the number of system messages alone exceeds max_messages,
|
|
67
|
+
all non-system messages are removed.
|
|
68
|
+
|
|
69
|
+
:param max_messages: The maximum number of messages to retain.
|
|
70
|
+
"""
|
|
71
|
+
if len(self._messages) <= max_messages:
|
|
72
|
+
return
|
|
73
|
+
|
|
74
|
+
system_messages = [m for m in self._messages if m.role == "system"]
|
|
75
|
+
non_system_messages = [m for m in self._messages if m.role != "system"]
|
|
76
|
+
|
|
77
|
+
available_slots = max_messages - len(system_messages)
|
|
78
|
+
if available_slots < 0:
|
|
79
|
+
available_slots = 0
|
|
80
|
+
|
|
81
|
+
kept_non_system = non_system_messages[-available_slots:] if available_slots > 0 else []
|
|
82
|
+
|
|
83
|
+
self._messages = system_messages + kept_non_system
|
|
84
|
+
return
|
|
85
|
+
|
|
86
|
+
def as_dict(self) -> dict:
|
|
87
|
+
"""
|
|
88
|
+
Returns a dictionary representation of the conversation.
|
|
89
|
+
|
|
90
|
+
:returns: A dictionary with a messages key containing a list of
|
|
91
|
+
message dictionaries.
|
|
92
|
+
"""
|
|
93
|
+
rtnval = {
|
|
94
|
+
"messages": [m.as_dict() for m in self._messages]
|
|
95
|
+
}
|
|
96
|
+
return rtnval
|
|
97
|
+
|
|
98
|
+
def to_json(self) -> str:
|
|
99
|
+
"""
|
|
100
|
+
Returns a JSON string representation of the conversation.
|
|
101
|
+
|
|
102
|
+
:returns: A JSON string.
|
|
103
|
+
"""
|
|
104
|
+
rtnval = json.dumps(self.as_dict())
|
|
105
|
+
return rtnval
|
|
106
|
+
|
|
107
|
+
@classmethod
|
|
108
|
+
def from_json(cls, json_str: str) -> "LLMConversation":
|
|
109
|
+
"""
|
|
110
|
+
Deserializes a JSON string into an LLMConversation.
|
|
111
|
+
|
|
112
|
+
:param json_str: A JSON string.
|
|
113
|
+
|
|
114
|
+
:returns: An LLMConversation instance.
|
|
115
|
+
"""
|
|
116
|
+
data = json.loads(json_str)
|
|
117
|
+
messages = [LLMMessage.from_dict(m) for m in data["messages"]]
|
|
118
|
+
rtnval = cls(messages=messages)
|
|
119
|
+
return rtnval
|
|
120
|
+
|
|
121
|
+
def __repr__(self) -> str:
|
|
122
|
+
"""
|
|
123
|
+
Returns a detailed string representation including the class name
|
|
124
|
+
and message count.
|
|
125
|
+
|
|
126
|
+
:returns: A repr string for debugging.
|
|
127
|
+
"""
|
|
128
|
+
rtnval = "{}(count={})".format(self.__class__.__name__, len(self._messages))
|
|
129
|
+
return rtnval
|
|
130
|
+
|
|
131
|
+
def __str__(self) -> str:
|
|
132
|
+
"""
|
|
133
|
+
Returns a human-readable summary listing the message roles in order.
|
|
134
|
+
|
|
135
|
+
:returns: A human-readable string.
|
|
136
|
+
"""
|
|
137
|
+
roles = [m.role for m in self._messages]
|
|
138
|
+
rtnval = "LLMConversation: [{}]".format(", ".join(roles))
|
|
139
|
+
return rtnval
|
|
140
|
+
|
|
141
|
+
def __eq__(self, other) -> bool:
|
|
142
|
+
"""
|
|
143
|
+
Checks equality based on the message list.
|
|
144
|
+
|
|
145
|
+
:param other: The object to compare against.
|
|
146
|
+
|
|
147
|
+
:returns: True if all messages are equal, False otherwise.
|
|
148
|
+
"""
|
|
149
|
+
if not isinstance(other, LLMConversation):
|
|
150
|
+
return False
|
|
151
|
+
|
|
152
|
+
rtnval = self._messages == other._messages
|
|
153
|
+
return rtnval
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Exception classes for the LLM Integration feature.
|
|
3
|
+
|
|
4
|
+
Provides LLMRequestError for LLM provider request failures and
|
|
5
|
+
LLMResponseParsingError for output parsing and validation failures.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import os
|
|
9
|
+
|
|
10
|
+
from typing import Optional
|
|
11
|
+
|
|
12
|
+
from ccai.agentkit.errors import AgentKitError
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class LLMRequestError(AgentKitError):
|
|
16
|
+
"""
|
|
17
|
+
Raised when an LLM provider request fails due to a provider-side error.
|
|
18
|
+
|
|
19
|
+
:param provider_name: The provider that failed.
|
|
20
|
+
:param model_name: The model that failed.
|
|
21
|
+
:param category: The error category string.
|
|
22
|
+
:param cause: The original exception.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
VALID_CATEGORIES = {
|
|
26
|
+
"rate_limit", "authentication", "server_error",
|
|
27
|
+
"timeout", "connection", "invalid_request"
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
def __init__(self, provider_name: str, model_name: str,
|
|
31
|
+
category: str, cause: Exception = None) -> None:
|
|
32
|
+
|
|
33
|
+
if category not in self.VALID_CATEGORIES:
|
|
34
|
+
errmsg = "Invalid error category {!r}. Valid categories are: {}".format(
|
|
35
|
+
category, ", ".join(sorted(self.VALID_CATEGORIES))
|
|
36
|
+
)
|
|
37
|
+
raise ValueError(errmsg)
|
|
38
|
+
|
|
39
|
+
self._provider_name = provider_name
|
|
40
|
+
self._model_name = model_name
|
|
41
|
+
self._category = category
|
|
42
|
+
self._cause = cause
|
|
43
|
+
|
|
44
|
+
errmsg = self._format_message()
|
|
45
|
+
super().__init__(errmsg, cause=cause)
|
|
46
|
+
|
|
47
|
+
return
|
|
48
|
+
|
|
49
|
+
def _format_message(self) -> str:
|
|
50
|
+
"""
|
|
51
|
+
Builds a descriptive error message from the provider name,
|
|
52
|
+
model name, category, and optional cause.
|
|
53
|
+
|
|
54
|
+
:returns: A formatted error message string.
|
|
55
|
+
"""
|
|
56
|
+
lines = [
|
|
57
|
+
"LLM request failed for provider {!r} model {!r}.".format(
|
|
58
|
+
self._provider_name, self._model_name
|
|
59
|
+
),
|
|
60
|
+
"Category: {}".format(self._category)
|
|
61
|
+
]
|
|
62
|
+
|
|
63
|
+
if self._cause is not None:
|
|
64
|
+
lines.append("Cause: {}".format(str(self._cause)))
|
|
65
|
+
|
|
66
|
+
rtnval = os.linesep.join(lines)
|
|
67
|
+
|
|
68
|
+
return rtnval
|
|
69
|
+
|
|
70
|
+
@property
|
|
71
|
+
def provider_name(self) -> str:
|
|
72
|
+
"""
|
|
73
|
+
The provider that failed.
|
|
74
|
+
|
|
75
|
+
:returns: The provider name string.
|
|
76
|
+
"""
|
|
77
|
+
return self._provider_name
|
|
78
|
+
|
|
79
|
+
@property
|
|
80
|
+
def model_name(self) -> str:
|
|
81
|
+
"""
|
|
82
|
+
The model that failed.
|
|
83
|
+
|
|
84
|
+
:returns: The model name string.
|
|
85
|
+
"""
|
|
86
|
+
return self._model_name
|
|
87
|
+
|
|
88
|
+
@property
|
|
89
|
+
def category(self) -> str:
|
|
90
|
+
"""
|
|
91
|
+
The error category string.
|
|
92
|
+
|
|
93
|
+
:returns: The category string.
|
|
94
|
+
"""
|
|
95
|
+
return self._category
|
|
96
|
+
|
|
97
|
+
@property
|
|
98
|
+
def cause(self) -> Optional[Exception]:
|
|
99
|
+
"""
|
|
100
|
+
The original exception that caused the failure.
|
|
101
|
+
|
|
102
|
+
:returns: The cause exception or None.
|
|
103
|
+
"""
|
|
104
|
+
return self._cause
|
|
105
|
+
|
|
106
|
+
def __repr__(self) -> str:
|
|
107
|
+
"""
|
|
108
|
+
Returns a detailed string representation including class name,
|
|
109
|
+
provider name, model name, and category.
|
|
110
|
+
|
|
111
|
+
:returns: A repr string for debugging.
|
|
112
|
+
"""
|
|
113
|
+
rtnval = "{}(provider={!r}, model={!r}, category={!r})".format(
|
|
114
|
+
self.__class__.__name__, self._provider_name,
|
|
115
|
+
self._model_name, self._category
|
|
116
|
+
)
|
|
117
|
+
return rtnval
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class LLMResponseParsingError(AgentKitError):
|
|
121
|
+
"""
|
|
122
|
+
Raised when an OutputParser fails to parse or validate LLM response text.
|
|
123
|
+
|
|
124
|
+
:param parser_name: The parser class name.
|
|
125
|
+
:param raw_text: The raw response text that failed parsing.
|
|
126
|
+
:param message: A descriptive error message.
|
|
127
|
+
"""
|
|
128
|
+
|
|
129
|
+
def __init__(self, parser_name: str, raw_text: str, message: str) -> None:
|
|
130
|
+
self._parser_name = parser_name
|
|
131
|
+
self._raw_text = raw_text
|
|
132
|
+
self._error_message = message
|
|
133
|
+
|
|
134
|
+
errmsg = self._format_message()
|
|
135
|
+
super().__init__(errmsg)
|
|
136
|
+
|
|
137
|
+
return
|
|
138
|
+
|
|
139
|
+
def _format_message(self) -> str:
|
|
140
|
+
"""
|
|
141
|
+
Builds a descriptive error message from the parser name,
|
|
142
|
+
error message, and a truncated preview of the raw text.
|
|
143
|
+
|
|
144
|
+
:returns: A formatted error message string.
|
|
145
|
+
"""
|
|
146
|
+
lines = [
|
|
147
|
+
"LLM response parsing failed in {!r}.".format(self._parser_name),
|
|
148
|
+
"Error: {}".format(self._error_message),
|
|
149
|
+
"Raw text (first 200 chars): {!r}".format(self._raw_text[:200])
|
|
150
|
+
]
|
|
151
|
+
|
|
152
|
+
rtnval = os.linesep.join(lines)
|
|
153
|
+
|
|
154
|
+
return rtnval
|
|
155
|
+
|
|
156
|
+
@property
|
|
157
|
+
def parser_name(self) -> str:
|
|
158
|
+
"""
|
|
159
|
+
The parser class name.
|
|
160
|
+
|
|
161
|
+
:returns: The parser name string.
|
|
162
|
+
"""
|
|
163
|
+
return self._parser_name
|
|
164
|
+
|
|
165
|
+
@property
|
|
166
|
+
def raw_text(self) -> str:
|
|
167
|
+
"""
|
|
168
|
+
The raw response text that failed parsing.
|
|
169
|
+
|
|
170
|
+
:returns: The raw text string.
|
|
171
|
+
"""
|
|
172
|
+
return self._raw_text
|
|
173
|
+
|
|
174
|
+
@property
|
|
175
|
+
def error_message(self) -> str:
|
|
176
|
+
"""
|
|
177
|
+
The descriptive error message.
|
|
178
|
+
|
|
179
|
+
:returns: The error message string.
|
|
180
|
+
"""
|
|
181
|
+
return self._error_message
|
|
182
|
+
|
|
183
|
+
def __repr__(self) -> str:
|
|
184
|
+
"""
|
|
185
|
+
Returns a detailed string representation including class name,
|
|
186
|
+
parser name, and error message.
|
|
187
|
+
|
|
188
|
+
:returns: A repr string for debugging.
|
|
189
|
+
"""
|
|
190
|
+
rtnval = "{}(parser={!r}, message={!r})".format(
|
|
191
|
+
self.__class__.__name__, self._parser_name, self._error_message
|
|
192
|
+
)
|
|
193
|
+
return rtnval
|