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
ccai/agentkit/agent.py
ADDED
|
@@ -0,0 +1,2945 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Defines the Agent abstract base class for the codecraftai-agent-kit framework.
|
|
3
|
+
|
|
4
|
+
Agent provides the foundational abstraction for all agents in the SDK,
|
|
5
|
+
including lifecycle management, identity, configuration, hooks,
|
|
6
|
+
sub-agent composition, and structured logging.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import abc
|
|
10
|
+
import logging
|
|
11
|
+
import os
|
|
12
|
+
import threading
|
|
13
|
+
import time
|
|
14
|
+
|
|
15
|
+
from typing import Callable
|
|
16
|
+
from typing import Dict
|
|
17
|
+
from typing import List
|
|
18
|
+
from typing import Optional
|
|
19
|
+
|
|
20
|
+
from ccai.agentkit.agentconfiguration import AgentConfiguration
|
|
21
|
+
from ccai.agentkit.agentidentity import AgentIdentity
|
|
22
|
+
from ccai.agentkit.agentregistry import AgentRegistry
|
|
23
|
+
from ccai.agentkit.agentstatemachine import AgentStateMachine
|
|
24
|
+
from ccai.agentkit.configurationmanager import ConfigurationManager
|
|
25
|
+
from ccai.agentkit.contextwindow import ContextWindow
|
|
26
|
+
from ccai.agentkit.contextwindowstrategy import ContextWindowStrategy
|
|
27
|
+
from ccai.agentkit.costtracker import CostTracker
|
|
28
|
+
from ccai.agentkit.debugsession import DebugSession
|
|
29
|
+
from ccai.agentkit.errors import SemanticError
|
|
30
|
+
from ccai.agentkit.fallbackchain import FallbackChain
|
|
31
|
+
from ccai.agentkit.featureflagregistry import FeatureFlagRegistry
|
|
32
|
+
from ccai.agentkit.hotreloadmonitor import HotReloadMonitor
|
|
33
|
+
from ccai.agentkit.hotreloadpolicy import HotReloadPolicy
|
|
34
|
+
from ccai.agentkit.inmemorystore import InMemoryStore
|
|
35
|
+
from ccai.agentkit.lifecyclestate import LifecycleState
|
|
36
|
+
from ccai.agentkit.llmconversation import LLMConversation
|
|
37
|
+
from ccai.agentkit.llmerrors import LLMRequestError
|
|
38
|
+
from ccai.agentkit.llmprovider import LLMProvider
|
|
39
|
+
from ccai.agentkit.llmproviderregistry import LLMProviderRegistry
|
|
40
|
+
from ccai.agentkit.llmresponse import LLMResponse
|
|
41
|
+
from ccai.agentkit.memoryconfiguration import MemoryConfiguration
|
|
42
|
+
from ccai.agentkit.memoryentry import MemoryEntry
|
|
43
|
+
from ccai.agentkit.memoryquery import MemoryQuery
|
|
44
|
+
from ccai.agentkit.memoryqueryresult import MemoryQueryResult
|
|
45
|
+
from ccai.agentkit.memoryscope import MemoryScope
|
|
46
|
+
from ccai.agentkit.memorystore import MemoryStore
|
|
47
|
+
from ccai.agentkit.memorystoreregistry import MemoryStoreRegistry
|
|
48
|
+
from ccai.agentkit.observabilityconfiguration import ObservabilityConfiguration
|
|
49
|
+
from ccai.agentkit.observabilitypipeline import ObservabilityPipeline
|
|
50
|
+
from ccai.agentkit.pluginmanager import PluginManager
|
|
51
|
+
from ccai.agentkit.resilienceconfiguration import ResilienceConfiguration
|
|
52
|
+
from ccai.agentkit.resiliencepipeline import ResiliencePipeline
|
|
53
|
+
from ccai.agentkit.retrypolicy import RetryPolicy
|
|
54
|
+
from ccai.agentkit.tool import Tool
|
|
55
|
+
from ccai.agentkit.toolchain import ToolChain
|
|
56
|
+
from ccai.agentkit.toolchainexecutor import ToolChainExecutor
|
|
57
|
+
from ccai.agentkit.toolchainresult import ToolChainResult
|
|
58
|
+
from ccai.agentkit.toolexecutor import ToolExecutor
|
|
59
|
+
from ccai.agentkit.toolregistry import ToolRegistry
|
|
60
|
+
from ccai.agentkit.toolresult import ToolResult
|
|
61
|
+
from ccai.agentkit.transitionrecord import TransitionRecord
|
|
62
|
+
from ccai.agentkit.workflowconfiguration import WorkflowConfiguration
|
|
63
|
+
from ccai.agentkit.workflowdefinition import WorkflowDefinition
|
|
64
|
+
from ccai.agentkit.workflowexecutor import WorkflowExecutor
|
|
65
|
+
from ccai.agentkit.workflowregistry import WorkflowRegistry
|
|
66
|
+
from ccai.agentkit.workflowresult import WorkflowResult
|
|
67
|
+
from ccai.agentkit.addressresolver import AddressResolver
|
|
68
|
+
from ccai.agentkit.jsonmessageserializer import JsonMessageSerializer
|
|
69
|
+
from ccai.agentkit.agentaddress import AgentAddress
|
|
70
|
+
from ccai.agentkit.approvalgate import ApprovalGate
|
|
71
|
+
from ccai.agentkit.checkpointmanager import CheckpointManager
|
|
72
|
+
from ccai.agentkit.message import Message
|
|
73
|
+
from ccai.agentkit.messageenvelope import MessageEnvelope
|
|
74
|
+
from ccai.agentkit.messagepattern import MessagePattern
|
|
75
|
+
from ccai.agentkit.messagerouter import MessageRouter
|
|
76
|
+
from ccai.agentkit.messageserializerregistry import MessageSerializerRegistry
|
|
77
|
+
from ccai.agentkit.messagingconfiguration import MessagingConfiguration
|
|
78
|
+
from ccai.agentkit.messagingerrors import NoMessageAvailableError
|
|
79
|
+
from ccai.agentkit.pubsubbroker import PubSubBroker
|
|
80
|
+
from ccai.agentkit.requestresponsehandler import RequestResponseHandler
|
|
81
|
+
from ccai.agentkit.subscription import Subscription
|
|
82
|
+
from ccai.agentkit.transport import DEFAULT_SERIALIZATION_FORMAT
|
|
83
|
+
from ccai.agentkit.transport import Transport
|
|
84
|
+
from ccai.agentkit.transportregistry import TransportRegistry
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
VALID_TRANSITION_POINTS = [
|
|
88
|
+
"on_initialize",
|
|
89
|
+
"on_start",
|
|
90
|
+
"on_pause",
|
|
91
|
+
"on_resume",
|
|
92
|
+
"on_stop",
|
|
93
|
+
"on_error",
|
|
94
|
+
]
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
# The number of seconds a receive loop waits before polling a transport again
|
|
98
|
+
# after it found no message or the receive failed.
|
|
99
|
+
DEFAULT_RECEIVE_POLL_INTERVAL = 0.05
|
|
100
|
+
|
|
101
|
+
# The number of seconds stop_receiving waits for a receive loop thread to end.
|
|
102
|
+
DEFAULT_RECEIVE_STOP_TIMEOUT = 5.0
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class Agent(abc.ABC):
|
|
106
|
+
"""
|
|
107
|
+
Abstract base class for all agents in the codecraftai-agent-kit framework.
|
|
108
|
+
|
|
109
|
+
Provides lifecycle management, identity, configuration, hooks,
|
|
110
|
+
sub-agent composition with cycle detection, and structured logging.
|
|
111
|
+
Subclasses must implement the abstract lifecycle methods: initialize,
|
|
112
|
+
start, pause, resume, stop, and reset.
|
|
113
|
+
|
|
114
|
+
:param configuration: The AgentConfiguration for this agent.
|
|
115
|
+
"""
|
|
116
|
+
|
|
117
|
+
def __init__(self, configuration: AgentConfiguration) -> None:
|
|
118
|
+
self._configuration: AgentConfiguration = configuration
|
|
119
|
+
self._identity: AgentIdentity = self._create_identity_from_config(configuration)
|
|
120
|
+
self._state_machine: AgentStateMachine = AgentStateMachine()
|
|
121
|
+
self._parent: Optional["Agent"] = None
|
|
122
|
+
self._sub_agents: List["Agent"] = []
|
|
123
|
+
self._extensions: List = []
|
|
124
|
+
self._hooks: Dict[str, List[Callable]] = {
|
|
125
|
+
"on_initialize": [],
|
|
126
|
+
"on_start": [],
|
|
127
|
+
"on_pause": [],
|
|
128
|
+
"on_resume": [],
|
|
129
|
+
"on_stop": [],
|
|
130
|
+
"on_error": [],
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
logger_name = "ccai.agentkit.agent.{}".format(self._identity.identifier)
|
|
134
|
+
self._logger: logging.Logger = logging.getLogger(logger_name)
|
|
135
|
+
|
|
136
|
+
self._configuration_manager = ConfigurationManager(
|
|
137
|
+
agent_identifier=self._identity.identifier
|
|
138
|
+
)
|
|
139
|
+
self._feature_flag_registry = FeatureFlagRegistry()
|
|
140
|
+
self._plugin_manager = PluginManager(
|
|
141
|
+
agent_identifier=self._identity.identifier
|
|
142
|
+
)
|
|
143
|
+
self._hot_reload_monitor = None
|
|
144
|
+
self._hot_reload_policy = None
|
|
145
|
+
self._resilience_pipeline = None
|
|
146
|
+
self._observability_pipeline = None
|
|
147
|
+
self._debug_session = None
|
|
148
|
+
|
|
149
|
+
self._tool_registry = ToolRegistry()
|
|
150
|
+
self._tool_executor = ToolExecutor()
|
|
151
|
+
self._tool_chain_executor = ToolChainExecutor(tool_executor=self._tool_executor)
|
|
152
|
+
|
|
153
|
+
self._llm_provider_registry = LLMProviderRegistry()
|
|
154
|
+
self._cost_tracker = CostTracker()
|
|
155
|
+
|
|
156
|
+
self._memory_store: Optional[MemoryStore] = None
|
|
157
|
+
self._memory_store_registry: MemoryStoreRegistry = MemoryStoreRegistry()
|
|
158
|
+
self._context_window: Optional[ContextWindow] = None
|
|
159
|
+
self._memory_configuration: Optional[MemoryConfiguration] = None
|
|
160
|
+
|
|
161
|
+
self._workflow_registry: WorkflowRegistry = WorkflowRegistry()
|
|
162
|
+
self._workflow_executor: Optional[WorkflowExecutor] = None
|
|
163
|
+
self._checkpoint_manager: Optional[CheckpointManager] = None
|
|
164
|
+
self._approval_gate: ApprovalGate = ApprovalGate()
|
|
165
|
+
self._workflow_configuration: Optional[WorkflowConfiguration] = None
|
|
166
|
+
|
|
167
|
+
self._transport_registry: TransportRegistry = TransportRegistry()
|
|
168
|
+
self._message_serializer_registry: MessageSerializerRegistry = MessageSerializerRegistry()
|
|
169
|
+
self._message_router: MessageRouter = MessageRouter()
|
|
170
|
+
self._pubsub_broker: PubSubBroker = PubSubBroker()
|
|
171
|
+
self._address_resolver: AddressResolver = AddressResolver(agent_registry=AgentRegistry.instance())
|
|
172
|
+
self._request_response_handler: RequestResponseHandler = RequestResponseHandler()
|
|
173
|
+
self._messaging_configuration: Optional[MessagingConfiguration] = None
|
|
174
|
+
# Background receive loops keyed by transport name; each entry holds
|
|
175
|
+
# the loop thread and the event that stops it.
|
|
176
|
+
self._receive_loops: Dict[str, dict] = {}
|
|
177
|
+
self._receive_loops_lock = threading.Lock()
|
|
178
|
+
|
|
179
|
+
self._platform_runtime = None
|
|
180
|
+
|
|
181
|
+
platform_config = configuration.get_platform_configuration()
|
|
182
|
+
if platform_config is not None:
|
|
183
|
+
from ccai.agentkit.platform.platformruntime import PlatformRuntime
|
|
184
|
+
self._platform_runtime = PlatformRuntime.create_auto(
|
|
185
|
+
configuration=platform_config
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
AgentRegistry.instance().register(self)
|
|
189
|
+
|
|
190
|
+
self._initialize_observability()
|
|
191
|
+
|
|
192
|
+
return
|
|
193
|
+
|
|
194
|
+
@staticmethod
|
|
195
|
+
def _create_identity_from_config(configuration: AgentConfiguration) -> AgentIdentity:
|
|
196
|
+
"""
|
|
197
|
+
Creates an AgentIdentity from the configuration identity dictionary.
|
|
198
|
+
|
|
199
|
+
:param configuration: The AgentConfiguration containing identity data.
|
|
200
|
+
|
|
201
|
+
:returns: An AgentIdentity instance.
|
|
202
|
+
"""
|
|
203
|
+
identity_data = configuration.identity
|
|
204
|
+
name = identity_data["name"]
|
|
205
|
+
version = identity_data["version"]
|
|
206
|
+
tags = identity_data.get("tags", None)
|
|
207
|
+
identifier = identity_data.get("identifier", None)
|
|
208
|
+
|
|
209
|
+
identity = AgentIdentity(
|
|
210
|
+
name=name,
|
|
211
|
+
version=version,
|
|
212
|
+
tags=tags,
|
|
213
|
+
identifier=identifier
|
|
214
|
+
)
|
|
215
|
+
return identity
|
|
216
|
+
|
|
217
|
+
# -----------------------------------------------------------------------
|
|
218
|
+
# Read-only properties
|
|
219
|
+
# -----------------------------------------------------------------------
|
|
220
|
+
|
|
221
|
+
@property
|
|
222
|
+
def state(self) -> LifecycleState:
|
|
223
|
+
"""
|
|
224
|
+
The current lifecycle state of the agent.
|
|
225
|
+
|
|
226
|
+
:returns: The current LifecycleState.
|
|
227
|
+
"""
|
|
228
|
+
return self._state_machine.current_state
|
|
229
|
+
|
|
230
|
+
@property
|
|
231
|
+
def identity(self) -> AgentIdentity:
|
|
232
|
+
"""
|
|
233
|
+
The identity and metadata of the agent.
|
|
234
|
+
|
|
235
|
+
:returns: The AgentIdentity instance.
|
|
236
|
+
"""
|
|
237
|
+
return self._identity
|
|
238
|
+
|
|
239
|
+
@property
|
|
240
|
+
def configuration(self) -> AgentConfiguration:
|
|
241
|
+
"""
|
|
242
|
+
The configuration of the agent.
|
|
243
|
+
|
|
244
|
+
:returns: The AgentConfiguration instance.
|
|
245
|
+
"""
|
|
246
|
+
return self._configuration
|
|
247
|
+
|
|
248
|
+
@property
|
|
249
|
+
def parent(self) -> Optional["Agent"]:
|
|
250
|
+
"""
|
|
251
|
+
The parent agent, or None if this agent has no parent.
|
|
252
|
+
|
|
253
|
+
:returns: The parent Agent instance or None.
|
|
254
|
+
"""
|
|
255
|
+
return self._parent
|
|
256
|
+
|
|
257
|
+
@property
|
|
258
|
+
def sub_agents(self) -> List["Agent"]:
|
|
259
|
+
"""
|
|
260
|
+
A list of sub-agent instances managed by this agent.
|
|
261
|
+
|
|
262
|
+
:returns: A list of Agent instances.
|
|
263
|
+
"""
|
|
264
|
+
return list(self._sub_agents)
|
|
265
|
+
|
|
266
|
+
@property
|
|
267
|
+
def extensions(self) -> List:
|
|
268
|
+
"""
|
|
269
|
+
A list of loaded extensions for this agent.
|
|
270
|
+
|
|
271
|
+
:returns: A list of extension objects.
|
|
272
|
+
"""
|
|
273
|
+
return list(self._extensions)
|
|
274
|
+
|
|
275
|
+
@property
|
|
276
|
+
def configuration_manager(self) -> ConfigurationManager:
|
|
277
|
+
"""
|
|
278
|
+
The configuration manager for this agent.
|
|
279
|
+
|
|
280
|
+
:returns: The ConfigurationManager instance.
|
|
281
|
+
"""
|
|
282
|
+
return self._configuration_manager
|
|
283
|
+
|
|
284
|
+
@property
|
|
285
|
+
def feature_flags(self) -> FeatureFlagRegistry:
|
|
286
|
+
"""
|
|
287
|
+
The feature flag registry for this agent.
|
|
288
|
+
|
|
289
|
+
:returns: The FeatureFlagRegistry instance.
|
|
290
|
+
"""
|
|
291
|
+
return self._feature_flag_registry
|
|
292
|
+
|
|
293
|
+
@property
|
|
294
|
+
def plugin_manager(self) -> PluginManager:
|
|
295
|
+
"""
|
|
296
|
+
The plugin manager for this agent.
|
|
297
|
+
|
|
298
|
+
:returns: The PluginManager instance.
|
|
299
|
+
"""
|
|
300
|
+
return self._plugin_manager
|
|
301
|
+
|
|
302
|
+
@property
|
|
303
|
+
def resilience(self):
|
|
304
|
+
"""
|
|
305
|
+
The ResiliencePipeline for this agent.
|
|
306
|
+
|
|
307
|
+
:returns: The ResiliencePipeline instance or None.
|
|
308
|
+
"""
|
|
309
|
+
return self._resilience_pipeline
|
|
310
|
+
|
|
311
|
+
@property
|
|
312
|
+
def health_monitor(self):
|
|
313
|
+
"""
|
|
314
|
+
The HealthMonitor from the ResiliencePipeline.
|
|
315
|
+
|
|
316
|
+
:returns: The HealthMonitor instance or None.
|
|
317
|
+
"""
|
|
318
|
+
if self._resilience_pipeline is not None:
|
|
319
|
+
return self._resilience_pipeline.health_monitor
|
|
320
|
+
return None
|
|
321
|
+
|
|
322
|
+
@property
|
|
323
|
+
def circuit_breakers(self):
|
|
324
|
+
"""
|
|
325
|
+
The CircuitBreakerRegistry from the ResiliencePipeline.
|
|
326
|
+
|
|
327
|
+
:returns: The CircuitBreakerRegistry instance or None.
|
|
328
|
+
"""
|
|
329
|
+
if self._resilience_pipeline is not None:
|
|
330
|
+
return self._resilience_pipeline.circuit_breaker_registry
|
|
331
|
+
return None
|
|
332
|
+
|
|
333
|
+
@property
|
|
334
|
+
def dead_letter_queue(self):
|
|
335
|
+
"""
|
|
336
|
+
The DeadLetterQueue from the ResiliencePipeline.
|
|
337
|
+
|
|
338
|
+
:returns: The DeadLetterQueue instance or None.
|
|
339
|
+
"""
|
|
340
|
+
if self._resilience_pipeline is not None:
|
|
341
|
+
return self._resilience_pipeline.dead_letter_queue
|
|
342
|
+
return None
|
|
343
|
+
|
|
344
|
+
@property
|
|
345
|
+
def observability(self) -> ObservabilityPipeline:
|
|
346
|
+
"""
|
|
347
|
+
The ObservabilityPipeline instance for this agent.
|
|
348
|
+
|
|
349
|
+
:returns: The ObservabilityPipeline instance.
|
|
350
|
+
"""
|
|
351
|
+
return self._observability_pipeline
|
|
352
|
+
|
|
353
|
+
@property
|
|
354
|
+
def debug_session(self) -> Optional[DebugSession]:
|
|
355
|
+
"""
|
|
356
|
+
The DebugSession instance for this agent, or None when
|
|
357
|
+
debug mode is not enabled.
|
|
358
|
+
|
|
359
|
+
:returns: A DebugSession instance or None.
|
|
360
|
+
"""
|
|
361
|
+
return self._debug_session
|
|
362
|
+
|
|
363
|
+
@property
|
|
364
|
+
def tools(self) -> ToolRegistry:
|
|
365
|
+
"""
|
|
366
|
+
Returns the Agent's ToolRegistry instance.
|
|
367
|
+
|
|
368
|
+
:returns: The ToolRegistry for this agent.
|
|
369
|
+
"""
|
|
370
|
+
return self._tool_registry
|
|
371
|
+
|
|
372
|
+
@property
|
|
373
|
+
def llm_providers(self) -> LLMProviderRegistry:
|
|
374
|
+
"""
|
|
375
|
+
Returns the Agent's LLMProviderRegistry instance.
|
|
376
|
+
|
|
377
|
+
:returns: The LLMProviderRegistry for this agent.
|
|
378
|
+
"""
|
|
379
|
+
return self._llm_provider_registry
|
|
380
|
+
|
|
381
|
+
@property
|
|
382
|
+
def cost_tracker(self) -> CostTracker:
|
|
383
|
+
"""
|
|
384
|
+
Returns the Agent's CostTracker instance.
|
|
385
|
+
|
|
386
|
+
:returns: The CostTracker for this agent.
|
|
387
|
+
"""
|
|
388
|
+
return self._cost_tracker
|
|
389
|
+
|
|
390
|
+
@property
|
|
391
|
+
def memory(self) -> Optional[MemoryStore]:
|
|
392
|
+
"""
|
|
393
|
+
The Agent's primary MemoryStore instance.
|
|
394
|
+
|
|
395
|
+
:returns: The primary MemoryStore or None.
|
|
396
|
+
"""
|
|
397
|
+
return self._memory_store
|
|
398
|
+
|
|
399
|
+
@property
|
|
400
|
+
def memory_stores(self) -> MemoryStoreRegistry:
|
|
401
|
+
"""
|
|
402
|
+
The Agent's MemoryStoreRegistry instance.
|
|
403
|
+
|
|
404
|
+
:returns: The MemoryStoreRegistry for this agent.
|
|
405
|
+
"""
|
|
406
|
+
return self._memory_store_registry
|
|
407
|
+
|
|
408
|
+
@property
|
|
409
|
+
def context_window(self) -> Optional[ContextWindow]:
|
|
410
|
+
"""
|
|
411
|
+
The Agent's ContextWindow instance.
|
|
412
|
+
|
|
413
|
+
:returns: The ContextWindow or None.
|
|
414
|
+
"""
|
|
415
|
+
return self._context_window
|
|
416
|
+
|
|
417
|
+
@property
|
|
418
|
+
def workflows(self) -> WorkflowRegistry:
|
|
419
|
+
"""
|
|
420
|
+
Returns the Agent's WorkflowRegistry instance.
|
|
421
|
+
|
|
422
|
+
:returns: The WorkflowRegistry for this agent.
|
|
423
|
+
"""
|
|
424
|
+
return self._workflow_registry
|
|
425
|
+
|
|
426
|
+
@property
|
|
427
|
+
def approval_gate(self) -> ApprovalGate:
|
|
428
|
+
"""
|
|
429
|
+
Returns the Agent's ApprovalGate instance.
|
|
430
|
+
|
|
431
|
+
:returns: The ApprovalGate for this agent.
|
|
432
|
+
"""
|
|
433
|
+
return self._approval_gate
|
|
434
|
+
|
|
435
|
+
@property
|
|
436
|
+
def transports(self) -> TransportRegistry:
|
|
437
|
+
"""
|
|
438
|
+
Returns the Agent's TransportRegistry instance.
|
|
439
|
+
|
|
440
|
+
:returns: The TransportRegistry for this agent.
|
|
441
|
+
"""
|
|
442
|
+
return self._transport_registry
|
|
443
|
+
|
|
444
|
+
@property
|
|
445
|
+
def message_router(self) -> MessageRouter:
|
|
446
|
+
"""
|
|
447
|
+
Returns the Agent's MessageRouter instance.
|
|
448
|
+
|
|
449
|
+
:returns: The MessageRouter for this agent.
|
|
450
|
+
"""
|
|
451
|
+
return self._message_router
|
|
452
|
+
|
|
453
|
+
@property
|
|
454
|
+
def pubsub(self) -> PubSubBroker:
|
|
455
|
+
"""
|
|
456
|
+
Returns the Agent's PubSubBroker instance.
|
|
457
|
+
|
|
458
|
+
:returns: The PubSubBroker for this agent.
|
|
459
|
+
"""
|
|
460
|
+
return self._pubsub_broker
|
|
461
|
+
|
|
462
|
+
@property
|
|
463
|
+
def address_resolver(self) -> AddressResolver:
|
|
464
|
+
"""
|
|
465
|
+
Returns the Agent's AddressResolver instance.
|
|
466
|
+
|
|
467
|
+
:returns: The AddressResolver for this agent.
|
|
468
|
+
"""
|
|
469
|
+
return self._address_resolver
|
|
470
|
+
|
|
471
|
+
@property
|
|
472
|
+
def platform_runtime(self):
|
|
473
|
+
"""
|
|
474
|
+
Returns the PlatformRuntime instance, or None when not configured.
|
|
475
|
+
|
|
476
|
+
:returns: The PlatformRuntime or None.
|
|
477
|
+
"""
|
|
478
|
+
rtnval = self._platform_runtime
|
|
479
|
+
return rtnval
|
|
480
|
+
|
|
481
|
+
# -----------------------------------------------------------------------
|
|
482
|
+
# Abstract lifecycle methods
|
|
483
|
+
# -----------------------------------------------------------------------
|
|
484
|
+
|
|
485
|
+
@abc.abstractmethod
|
|
486
|
+
def initialize(self) -> None:
|
|
487
|
+
"""
|
|
488
|
+
Initializes the agent. Subclasses must implement this method.
|
|
489
|
+
"""
|
|
490
|
+
|
|
491
|
+
@abc.abstractmethod
|
|
492
|
+
def start(self) -> None:
|
|
493
|
+
"""
|
|
494
|
+
Starts the agent. Subclasses must implement this method.
|
|
495
|
+
"""
|
|
496
|
+
|
|
497
|
+
@abc.abstractmethod
|
|
498
|
+
def pause(self) -> None:
|
|
499
|
+
"""
|
|
500
|
+
Pauses the agent. Subclasses must implement this method.
|
|
501
|
+
"""
|
|
502
|
+
|
|
503
|
+
@abc.abstractmethod
|
|
504
|
+
def resume(self) -> None:
|
|
505
|
+
"""
|
|
506
|
+
Resumes the agent. Subclasses must implement this method.
|
|
507
|
+
"""
|
|
508
|
+
|
|
509
|
+
@abc.abstractmethod
|
|
510
|
+
def stop(self) -> None:
|
|
511
|
+
"""
|
|
512
|
+
Stops the agent. Subclasses must implement this method.
|
|
513
|
+
"""
|
|
514
|
+
|
|
515
|
+
@abc.abstractmethod
|
|
516
|
+
def reset(self) -> None:
|
|
517
|
+
"""
|
|
518
|
+
Resets the agent. Subclasses must implement this method.
|
|
519
|
+
"""
|
|
520
|
+
|
|
521
|
+
# -----------------------------------------------------------------------
|
|
522
|
+
# Configuration and extensibility convenience methods
|
|
523
|
+
# -----------------------------------------------------------------------
|
|
524
|
+
|
|
525
|
+
def get_config(self, field_path: str, default=None):
|
|
526
|
+
"""
|
|
527
|
+
Returns the resolved configuration value at the given field path,
|
|
528
|
+
delegating to the ConfigurationManager.
|
|
529
|
+
|
|
530
|
+
:param field_path: Dot-separated path string.
|
|
531
|
+
:param default: Value to return when the field path is not found.
|
|
532
|
+
|
|
533
|
+
:returns: The resolved configuration value or default.
|
|
534
|
+
"""
|
|
535
|
+
value = self._configuration_manager.get(field_path, default=default)
|
|
536
|
+
return value
|
|
537
|
+
|
|
538
|
+
def is_feature_enabled(self, flag_name: str) -> bool:
|
|
539
|
+
"""
|
|
540
|
+
Returns whether the named feature flag is enabled, delegating
|
|
541
|
+
to the FeatureFlagRegistry.
|
|
542
|
+
|
|
543
|
+
:param flag_name: The flag name to evaluate.
|
|
544
|
+
|
|
545
|
+
:returns: True if the flag is enabled.
|
|
546
|
+
"""
|
|
547
|
+
result = self._feature_flag_registry.is_enabled(flag_name)
|
|
548
|
+
return result
|
|
549
|
+
|
|
550
|
+
# -----------------------------------------------------------------------
|
|
551
|
+
# Configuration lifecycle helpers for subclasses
|
|
552
|
+
# -----------------------------------------------------------------------
|
|
553
|
+
|
|
554
|
+
def _initialize_configuration(self) -> None:
|
|
555
|
+
"""
|
|
556
|
+
Loads configuration from the AgentConfiguration into the
|
|
557
|
+
ConfigurationManager and validates against the schema if defined.
|
|
558
|
+
|
|
559
|
+
Subclasses should call this method during their initialize()
|
|
560
|
+
implementation to set up configuration.
|
|
561
|
+
"""
|
|
562
|
+
agent_config = self._configuration
|
|
563
|
+
config_dict = agent_config.as_dict()
|
|
564
|
+
|
|
565
|
+
self._configuration_manager.load_defaults(config_dict)
|
|
566
|
+
|
|
567
|
+
self._logger.info(
|
|
568
|
+
"Configuration initialized for agent '%s'",
|
|
569
|
+
self._identity.identifier
|
|
570
|
+
)
|
|
571
|
+
return
|
|
572
|
+
|
|
573
|
+
def _initialize_plugins(self) -> None:
|
|
574
|
+
"""
|
|
575
|
+
Discovers and loads plugins through the PluginManager.
|
|
576
|
+
|
|
577
|
+
Subclasses should call this method during their initialize()
|
|
578
|
+
implementation to set up plugins.
|
|
579
|
+
"""
|
|
580
|
+
self._plugin_manager.discover()
|
|
581
|
+
|
|
582
|
+
self._logger.info(
|
|
583
|
+
"Plugins initialized for agent '%s'",
|
|
584
|
+
self._identity.identifier
|
|
585
|
+
)
|
|
586
|
+
return
|
|
587
|
+
|
|
588
|
+
def _initialize_feature_flags(self) -> None:
|
|
589
|
+
"""
|
|
590
|
+
Loads feature flag definitions from the configuration.
|
|
591
|
+
|
|
592
|
+
Subclasses should call this method during their initialize()
|
|
593
|
+
implementation to set up feature flags.
|
|
594
|
+
"""
|
|
595
|
+
self._logger.info(
|
|
596
|
+
"Feature flags initialized for agent '%s'",
|
|
597
|
+
self._identity.identifier
|
|
598
|
+
)
|
|
599
|
+
return
|
|
600
|
+
|
|
601
|
+
def _start_hot_reload(self, policy: HotReloadPolicy) -> None:
|
|
602
|
+
"""
|
|
603
|
+
Starts the HotReloadMonitor with the given policy.
|
|
604
|
+
|
|
605
|
+
Subclasses should call this method during their start()
|
|
606
|
+
implementation when a HotReloadPolicy is configured.
|
|
607
|
+
|
|
608
|
+
:param policy: The HotReloadPolicy defining monitoring behavior.
|
|
609
|
+
"""
|
|
610
|
+
self._hot_reload_policy = policy
|
|
611
|
+
self._hot_reload_monitor = HotReloadMonitor(
|
|
612
|
+
configuration_manager=self._configuration_manager,
|
|
613
|
+
policy=policy
|
|
614
|
+
)
|
|
615
|
+
self._hot_reload_monitor.start()
|
|
616
|
+
|
|
617
|
+
self._logger.info(
|
|
618
|
+
"Hot-reload monitor started for agent '%s' with polling interval %.1f",
|
|
619
|
+
self._identity.identifier,
|
|
620
|
+
policy.polling_interval
|
|
621
|
+
)
|
|
622
|
+
return
|
|
623
|
+
|
|
624
|
+
def _stop_configuration(self) -> None:
|
|
625
|
+
"""
|
|
626
|
+
Stops the HotReloadMonitor if running, deactivates and unloads
|
|
627
|
+
all plugins, and clears runtime configuration overrides.
|
|
628
|
+
|
|
629
|
+
Subclasses should call this method during their stop()
|
|
630
|
+
implementation to clean up configuration resources.
|
|
631
|
+
"""
|
|
632
|
+
if self._hot_reload_monitor is not None:
|
|
633
|
+
self._hot_reload_monitor.stop()
|
|
634
|
+
self._hot_reload_monitor = None
|
|
635
|
+
|
|
636
|
+
plugin_list = self._plugin_manager.list_all()
|
|
637
|
+
for plugin_desc in plugin_list:
|
|
638
|
+
self._plugin_manager.unload_plugin(plugin_desc.name)
|
|
639
|
+
|
|
640
|
+
self._logger.info(
|
|
641
|
+
"Configuration stopped for agent '%s'",
|
|
642
|
+
self._identity.identifier
|
|
643
|
+
)
|
|
644
|
+
return
|
|
645
|
+
|
|
646
|
+
# -----------------------------------------------------------------------
|
|
647
|
+
# Observability lifecycle helpers
|
|
648
|
+
# -----------------------------------------------------------------------
|
|
649
|
+
|
|
650
|
+
def _initialize_observability(self) -> None:
|
|
651
|
+
"""
|
|
652
|
+
Initializes the ObservabilityPipeline and optionally a
|
|
653
|
+
DebugSession based on the agent's configuration.
|
|
654
|
+
|
|
655
|
+
Reads the "observability" key from the AgentConfiguration's
|
|
656
|
+
settings dictionary. If not present, uses default values:
|
|
657
|
+
log_level="info", log_format="human_readable", tracing/metrics/
|
|
658
|
+
recording/debug disabled, sampling_rate=1.0.
|
|
659
|
+
|
|
660
|
+
When debug_mode_enabled is True in the observability config,
|
|
661
|
+
a DebugSession is created for this agent.
|
|
662
|
+
|
|
663
|
+
After constructing the pipeline, attempts to discover and
|
|
664
|
+
register exporter plugins from extension points.
|
|
665
|
+
"""
|
|
666
|
+
settings = self._configuration.settings
|
|
667
|
+
observability_data = settings.get("observability", None)
|
|
668
|
+
|
|
669
|
+
if observability_data is not None:
|
|
670
|
+
obs_config = ObservabilityConfiguration.from_dict(observability_data)
|
|
671
|
+
else:
|
|
672
|
+
obs_config = ObservabilityConfiguration(
|
|
673
|
+
log_level="info",
|
|
674
|
+
log_format="human_readable",
|
|
675
|
+
tracing_enabled=False,
|
|
676
|
+
metrics_enabled=False,
|
|
677
|
+
recording_enabled=False,
|
|
678
|
+
debug_mode_enabled=False,
|
|
679
|
+
sampling_rate=1.0
|
|
680
|
+
)
|
|
681
|
+
|
|
682
|
+
self._observability_pipeline = ObservabilityPipeline(
|
|
683
|
+
configuration=obs_config,
|
|
684
|
+
agent_id=self._identity.identifier
|
|
685
|
+
)
|
|
686
|
+
|
|
687
|
+
if obs_config.debug_mode_enabled:
|
|
688
|
+
self._debug_session = DebugSession(agent=self)
|
|
689
|
+
|
|
690
|
+
self._discover_exporter_plugins()
|
|
691
|
+
|
|
692
|
+
return
|
|
693
|
+
|
|
694
|
+
def _discover_exporter_plugins(self) -> None:
|
|
695
|
+
"""
|
|
696
|
+
Discovers and registers exporter plugins from extension points.
|
|
697
|
+
|
|
698
|
+
Queries the following extension points:
|
|
699
|
+
- "ccai.agentkit.log_exporters"
|
|
700
|
+
- "ccai.agentkit.trace_exporters"
|
|
701
|
+
- "ccai.agentkit.metrics_exporters"
|
|
702
|
+
|
|
703
|
+
Logs plugin loading failures at WARNING and continues.
|
|
704
|
+
Logs conflicts at WARNING and skips the conflicting plugin.
|
|
705
|
+
"""
|
|
706
|
+
if self._observability_pipeline is None:
|
|
707
|
+
return
|
|
708
|
+
|
|
709
|
+
extension_point_map = {
|
|
710
|
+
"ccai.agentkit.log_exporters": "register_log_exporter",
|
|
711
|
+
"ccai.agentkit.trace_exporters": "register_trace_exporter",
|
|
712
|
+
"ccai.agentkit.metrics_exporters": "register_metrics_exporter",
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
for ext_point_name, register_method_name in extension_point_map.items():
|
|
716
|
+
try:
|
|
717
|
+
extensions = self._extensions
|
|
718
|
+
if extensions is None:
|
|
719
|
+
continue
|
|
720
|
+
|
|
721
|
+
exporters = []
|
|
722
|
+
for ext in extensions:
|
|
723
|
+
ext_point = getattr(ext, "extension_point", None)
|
|
724
|
+
if ext_point == ext_point_name:
|
|
725
|
+
exporters.append(ext)
|
|
726
|
+
|
|
727
|
+
register_method = getattr(self._observability_pipeline, register_method_name)
|
|
728
|
+
|
|
729
|
+
for exporter in exporters:
|
|
730
|
+
try:
|
|
731
|
+
register_method(exporter)
|
|
732
|
+
except Exception as plugin_err:
|
|
733
|
+
self._logger.warning(
|
|
734
|
+
"Failed to register exporter plugin from extension point '%s': %s",
|
|
735
|
+
ext_point_name,
|
|
736
|
+
str(plugin_err)
|
|
737
|
+
)
|
|
738
|
+
|
|
739
|
+
except Exception as discovery_err:
|
|
740
|
+
self._logger.warning(
|
|
741
|
+
"Failed to discover exporter plugins from extension point '%s': %s",
|
|
742
|
+
ext_point_name,
|
|
743
|
+
str(discovery_err)
|
|
744
|
+
)
|
|
745
|
+
|
|
746
|
+
return
|
|
747
|
+
|
|
748
|
+
# -----------------------------------------------------------------------
|
|
749
|
+
# Resilience lifecycle helpers for subclasses
|
|
750
|
+
# -----------------------------------------------------------------------
|
|
751
|
+
|
|
752
|
+
def _initialize_resilience(self, resilience_config: ResilienceConfiguration = None) -> None:
|
|
753
|
+
"""
|
|
754
|
+
Initializes the ResiliencePipeline from the given configuration.
|
|
755
|
+
|
|
756
|
+
Subclasses should call this method during their initialize()
|
|
757
|
+
implementation to set up resilience.
|
|
758
|
+
|
|
759
|
+
:param resilience_config: Optional ResilienceConfiguration. If None,
|
|
760
|
+
a default configuration is used.
|
|
761
|
+
"""
|
|
762
|
+
if resilience_config is None:
|
|
763
|
+
resilience_config = ResilienceConfiguration()
|
|
764
|
+
|
|
765
|
+
self._resilience_pipeline = ResiliencePipeline(
|
|
766
|
+
resilience_config, self._identity.identifier
|
|
767
|
+
)
|
|
768
|
+
|
|
769
|
+
self._discover_resilience_plugins()
|
|
770
|
+
|
|
771
|
+
self._logger.info(
|
|
772
|
+
"Resilience initialized for agent '%s'",
|
|
773
|
+
self._identity.identifier
|
|
774
|
+
)
|
|
775
|
+
return
|
|
776
|
+
|
|
777
|
+
def _discover_resilience_plugins(self) -> None:
|
|
778
|
+
"""
|
|
779
|
+
Discovers and registers ResiliencePlugin instances from the
|
|
780
|
+
"ccai.agentkit.resilience" extension point.
|
|
781
|
+
|
|
782
|
+
Queries the agent's extensions list for entries with
|
|
783
|
+
extension_point == "ccai.agentkit.resilience" and registers
|
|
784
|
+
discovered HealthCheck, DegradationStrategy, SelfHealingAction,
|
|
785
|
+
and DeadLetterStore instances with the appropriate pipeline
|
|
786
|
+
components.
|
|
787
|
+
|
|
788
|
+
Logs plugin loading failures at WARNING and continues.
|
|
789
|
+
Logs name conflicts at WARNING and skips the conflicting component.
|
|
790
|
+
"""
|
|
791
|
+
if self._resilience_pipeline is None:
|
|
792
|
+
return
|
|
793
|
+
|
|
794
|
+
extensions = self._extensions
|
|
795
|
+
if extensions is None:
|
|
796
|
+
return
|
|
797
|
+
|
|
798
|
+
from ccai.agentkit.healthcheck import HealthCheck
|
|
799
|
+
|
|
800
|
+
for ext in extensions:
|
|
801
|
+
ext_point = getattr(ext, "extension_point", None)
|
|
802
|
+
if ext_point != "ccai.agentkit.resilience":
|
|
803
|
+
continue
|
|
804
|
+
|
|
805
|
+
try:
|
|
806
|
+
if isinstance(ext, HealthCheck):
|
|
807
|
+
monitor = self._resilience_pipeline.health_monitor
|
|
808
|
+
if monitor is not None:
|
|
809
|
+
registry = monitor._health_check_registry
|
|
810
|
+
check_name = ext.name
|
|
811
|
+
if registry.has_health_check(check_name):
|
|
812
|
+
self._logger.warning(
|
|
813
|
+
"Resilience plugin name conflict: health check '%s' "
|
|
814
|
+
"is already registered in agent '%s'. Skipping.",
|
|
815
|
+
check_name,
|
|
816
|
+
self._identity.identifier,
|
|
817
|
+
)
|
|
818
|
+
continue
|
|
819
|
+
registry.register(ext)
|
|
820
|
+
|
|
821
|
+
except Exception as plugin_err:
|
|
822
|
+
try:
|
|
823
|
+
plugin_name = getattr(ext, "name", "unknown")
|
|
824
|
+
except Exception:
|
|
825
|
+
plugin_name = "unknown"
|
|
826
|
+
self._logger.warning(
|
|
827
|
+
"Failed to load resilience plugin '%s' for agent '%s': %s",
|
|
828
|
+
plugin_name,
|
|
829
|
+
self._identity.identifier,
|
|
830
|
+
str(plugin_err),
|
|
831
|
+
)
|
|
832
|
+
|
|
833
|
+
return
|
|
834
|
+
|
|
835
|
+
def _start_resilience(self) -> None:
|
|
836
|
+
"""
|
|
837
|
+
Starts the HealthMonitor if resilience is initialized and
|
|
838
|
+
health monitoring is enabled.
|
|
839
|
+
|
|
840
|
+
Subclasses should call this method during their start()
|
|
841
|
+
implementation.
|
|
842
|
+
"""
|
|
843
|
+
if self._resilience_pipeline is not None:
|
|
844
|
+
monitor = self._resilience_pipeline.health_monitor
|
|
845
|
+
if monitor is not None:
|
|
846
|
+
monitor.start()
|
|
847
|
+
self._logger.info(
|
|
848
|
+
"Health monitor started for agent '%s'",
|
|
849
|
+
self._identity.identifier
|
|
850
|
+
)
|
|
851
|
+
return
|
|
852
|
+
|
|
853
|
+
def _stop_resilience(self) -> None:
|
|
854
|
+
"""
|
|
855
|
+
Stops the HealthMonitor if running.
|
|
856
|
+
|
|
857
|
+
Subclasses should call this method during their stop()
|
|
858
|
+
implementation.
|
|
859
|
+
"""
|
|
860
|
+
if self._resilience_pipeline is not None:
|
|
861
|
+
monitor = self._resilience_pipeline.health_monitor
|
|
862
|
+
if monitor is not None and monitor.is_active:
|
|
863
|
+
monitor.stop()
|
|
864
|
+
self._logger.info(
|
|
865
|
+
"Health monitor stopped for agent '%s'",
|
|
866
|
+
self._identity.identifier
|
|
867
|
+
)
|
|
868
|
+
return
|
|
869
|
+
|
|
870
|
+
def register_tool(self, tool: Tool) -> None:
|
|
871
|
+
"""
|
|
872
|
+
Registers a Tool with this Agent's ToolRegistry.
|
|
873
|
+
|
|
874
|
+
:param tool: The Tool instance to register.
|
|
875
|
+
"""
|
|
876
|
+
self._tool_registry.register(tool=tool)
|
|
877
|
+
return
|
|
878
|
+
|
|
879
|
+
def execute_tool(self, tool_name: str, inputs: dict) -> ToolResult:
|
|
880
|
+
"""
|
|
881
|
+
Looks up and executes a tool by name.
|
|
882
|
+
|
|
883
|
+
:param tool_name: Name of the tool to execute.
|
|
884
|
+
:param inputs: Input dictionary.
|
|
885
|
+
|
|
886
|
+
:returns: A ToolResult.
|
|
887
|
+
:raises: SemanticError if tool not found.
|
|
888
|
+
"""
|
|
889
|
+
tool = self._tool_registry.lookup(tool_name=tool_name)
|
|
890
|
+
|
|
891
|
+
if tool is None:
|
|
892
|
+
err_msg_lines = [
|
|
893
|
+
"Tool '{}' not found in agent '{}'.".format(
|
|
894
|
+
tool_name, self._identity.identifier
|
|
895
|
+
),
|
|
896
|
+
]
|
|
897
|
+
err_msg = os.linesep.join(err_msg_lines)
|
|
898
|
+
raise SemanticError(err_msg)
|
|
899
|
+
|
|
900
|
+
rtnval = self._tool_executor.execute(
|
|
901
|
+
tool=tool,
|
|
902
|
+
inputs=inputs,
|
|
903
|
+
agent_identifier=self._identity.identifier,
|
|
904
|
+
)
|
|
905
|
+
return rtnval
|
|
906
|
+
|
|
907
|
+
def execute_chain(self, chain: ToolChain, inputs: dict) -> ToolChainResult:
|
|
908
|
+
"""
|
|
909
|
+
Executes a ToolChain through the ToolChainExecutor.
|
|
910
|
+
|
|
911
|
+
:param chain: The ToolChain to execute.
|
|
912
|
+
:param inputs: Initial input dictionary.
|
|
913
|
+
|
|
914
|
+
:returns: A ToolChainResult.
|
|
915
|
+
"""
|
|
916
|
+
rtnval = self._tool_chain_executor.execute(
|
|
917
|
+
chain=chain,
|
|
918
|
+
initial_inputs=inputs,
|
|
919
|
+
agent_identifier=self._identity.identifier,
|
|
920
|
+
)
|
|
921
|
+
return rtnval
|
|
922
|
+
|
|
923
|
+
def _initialize_tools(self) -> None:
|
|
924
|
+
"""
|
|
925
|
+
Discovers and registers ToolPlugin instances from the
|
|
926
|
+
"ccai.agentkit.tools" extension point.
|
|
927
|
+
|
|
928
|
+
Subclasses should call this method during their initialize()
|
|
929
|
+
implementation to set up tools.
|
|
930
|
+
"""
|
|
931
|
+
try:
|
|
932
|
+
from ccai.extension import ExtensionPoint
|
|
933
|
+
extension_point = ExtensionPoint("ccai.agentkit.tools")
|
|
934
|
+
discovered_tools = extension_point.query()
|
|
935
|
+
|
|
936
|
+
for tool_entry in discovered_tools:
|
|
937
|
+
try:
|
|
938
|
+
tool_instance = tool_entry
|
|
939
|
+
tool_name = tool_instance.name
|
|
940
|
+
has_conflict = self._tool_registry.has_tool(tool_name=tool_name)
|
|
941
|
+
|
|
942
|
+
if has_conflict is True:
|
|
943
|
+
self._logger.warning(
|
|
944
|
+
"Tool plugin name conflict: tool '%s' is already registered "
|
|
945
|
+
"in agent '%s'. Skipping plugin tool.",
|
|
946
|
+
tool_name,
|
|
947
|
+
self._identity.identifier,
|
|
948
|
+
)
|
|
949
|
+
continue
|
|
950
|
+
|
|
951
|
+
self._tool_registry.register(tool=tool_instance)
|
|
952
|
+
|
|
953
|
+
except Exception as plugin_err:
|
|
954
|
+
self._logger.warning(
|
|
955
|
+
"Failed to load tool plugin for agent '%s': %s",
|
|
956
|
+
self._identity.identifier,
|
|
957
|
+
str(plugin_err),
|
|
958
|
+
)
|
|
959
|
+
|
|
960
|
+
except ImportError:
|
|
961
|
+
self._logger.info(
|
|
962
|
+
"codecraftai-extension not available; skipping tool plugin discovery "
|
|
963
|
+
"for agent '%s'",
|
|
964
|
+
self._identity.identifier,
|
|
965
|
+
)
|
|
966
|
+
except Exception as discovery_err:
|
|
967
|
+
self._logger.warning(
|
|
968
|
+
"Tool plugin discovery failed for agent '%s': %s",
|
|
969
|
+
self._identity.identifier,
|
|
970
|
+
str(discovery_err),
|
|
971
|
+
)
|
|
972
|
+
|
|
973
|
+
self._logger.info(
|
|
974
|
+
"Tools initialized for agent '%s'",
|
|
975
|
+
self._identity.identifier,
|
|
976
|
+
)
|
|
977
|
+
return
|
|
978
|
+
|
|
979
|
+
def _stop_tools(self) -> None:
|
|
980
|
+
"""
|
|
981
|
+
Clears the Agent's ToolRegistry.
|
|
982
|
+
|
|
983
|
+
Subclasses should call this method during their stop()
|
|
984
|
+
implementation to clean up tools.
|
|
985
|
+
"""
|
|
986
|
+
self._tool_registry.clear()
|
|
987
|
+
self._logger.info(
|
|
988
|
+
"Tools cleared for agent '%s'",
|
|
989
|
+
self._identity.identifier,
|
|
990
|
+
)
|
|
991
|
+
return
|
|
992
|
+
|
|
993
|
+
# -----------------------------------------------------------------------
|
|
994
|
+
# Messaging lifecycle helpers for subclasses
|
|
995
|
+
# -----------------------------------------------------------------------
|
|
996
|
+
|
|
997
|
+
def _initialize_messaging(self, messaging_configuration=None) -> None:
|
|
998
|
+
"""
|
|
999
|
+
Initializes the messaging subsystem for this Agent.
|
|
1000
|
+
|
|
1001
|
+
Stores the messaging configuration, configures the
|
|
1002
|
+
RequestResponseHandler with the default request timeout,
|
|
1003
|
+
registers a default JsonMessageSerializer when no
|
|
1004
|
+
MessagingConfiguration is provided, and discovers Transport
|
|
1005
|
+
and MessageSerializer plugins from codecraftai-extension
|
|
1006
|
+
ExtensionPoint entries.
|
|
1007
|
+
|
|
1008
|
+
Subclasses should call this method during their initialize()
|
|
1009
|
+
implementation to set up messaging.
|
|
1010
|
+
|
|
1011
|
+
:param messaging_configuration: Optional MessagingConfiguration.
|
|
1012
|
+
If None, defaults to a JsonMessageSerializer and no
|
|
1013
|
+
registered transports.
|
|
1014
|
+
"""
|
|
1015
|
+
self._messaging_configuration = messaging_configuration
|
|
1016
|
+
|
|
1017
|
+
if messaging_configuration is not None:
|
|
1018
|
+
default_timeout = messaging_configuration.default_request_timeout
|
|
1019
|
+
self._request_response_handler = RequestResponseHandler(
|
|
1020
|
+
default_timeout=default_timeout
|
|
1021
|
+
)
|
|
1022
|
+
|
|
1023
|
+
# Register default JsonMessageSerializer when no configuration is provided
|
|
1024
|
+
if messaging_configuration is None:
|
|
1025
|
+
default_serializer = JsonMessageSerializer()
|
|
1026
|
+
default_format_name = default_serializer.format_name
|
|
1027
|
+
has_default = self._message_serializer_registry.has_serializer(default_format_name)
|
|
1028
|
+
|
|
1029
|
+
if has_default is not True:
|
|
1030
|
+
self._message_serializer_registry.register(default_serializer)
|
|
1031
|
+
|
|
1032
|
+
# Discover and register Transport plugins
|
|
1033
|
+
try:
|
|
1034
|
+
from ccai.extension import ExtensionPoint
|
|
1035
|
+
transport_extension_point = ExtensionPoint("ccai.agentkit.transports")
|
|
1036
|
+
discovered_transports = transport_extension_point.query()
|
|
1037
|
+
|
|
1038
|
+
for transport_entry in discovered_transports:
|
|
1039
|
+
try:
|
|
1040
|
+
transport_instance = transport_entry
|
|
1041
|
+
transport_name = transport_instance.name
|
|
1042
|
+
has_conflict = self._transport_registry.has_transport(transport_name)
|
|
1043
|
+
|
|
1044
|
+
if has_conflict is True:
|
|
1045
|
+
self._logger.warning(
|
|
1046
|
+
"Transport plugin name conflict: transport '%s' is already "
|
|
1047
|
+
"registered in agent '%s'. Skipping plugin transport.",
|
|
1048
|
+
transport_name,
|
|
1049
|
+
self._identity.identifier,
|
|
1050
|
+
)
|
|
1051
|
+
continue
|
|
1052
|
+
|
|
1053
|
+
self._transport_registry.register(transport=transport_instance)
|
|
1054
|
+
transport_instance.attach_serializer_registry(self._message_serializer_registry)
|
|
1055
|
+
|
|
1056
|
+
except Exception as plugin_err:
|
|
1057
|
+
self._logger.warning(
|
|
1058
|
+
"Failed to load transport plugin for agent '%s': %s",
|
|
1059
|
+
self._identity.identifier,
|
|
1060
|
+
str(plugin_err),
|
|
1061
|
+
)
|
|
1062
|
+
|
|
1063
|
+
except ImportError:
|
|
1064
|
+
self._logger.info(
|
|
1065
|
+
"codecraftai-extension not available; skipping transport plugin "
|
|
1066
|
+
"discovery for agent '%s'",
|
|
1067
|
+
self._identity.identifier,
|
|
1068
|
+
)
|
|
1069
|
+
except Exception as discovery_err:
|
|
1070
|
+
self._logger.warning(
|
|
1071
|
+
"Transport plugin discovery failed for agent '%s': %s",
|
|
1072
|
+
self._identity.identifier,
|
|
1073
|
+
str(discovery_err),
|
|
1074
|
+
)
|
|
1075
|
+
|
|
1076
|
+
# Discover and register MessageSerializer plugins
|
|
1077
|
+
try:
|
|
1078
|
+
from ccai.extension import ExtensionPoint
|
|
1079
|
+
serializer_extension_point = ExtensionPoint("ccai.agentkit.message_serializers")
|
|
1080
|
+
discovered_serializers = serializer_extension_point.query()
|
|
1081
|
+
|
|
1082
|
+
for serializer_entry in discovered_serializers:
|
|
1083
|
+
try:
|
|
1084
|
+
serializer_instance = serializer_entry
|
|
1085
|
+
format_name = serializer_instance.format_name
|
|
1086
|
+
has_conflict = self._message_serializer_registry.has_serializer(format_name)
|
|
1087
|
+
|
|
1088
|
+
if has_conflict is True:
|
|
1089
|
+
self._logger.warning(
|
|
1090
|
+
"MessageSerializer plugin name conflict: format '%s' is "
|
|
1091
|
+
"already registered in agent '%s'. Skipping plugin serializer.",
|
|
1092
|
+
format_name,
|
|
1093
|
+
self._identity.identifier,
|
|
1094
|
+
)
|
|
1095
|
+
continue
|
|
1096
|
+
|
|
1097
|
+
self._message_serializer_registry.register(serializer_instance)
|
|
1098
|
+
|
|
1099
|
+
except Exception as plugin_err:
|
|
1100
|
+
self._logger.warning(
|
|
1101
|
+
"Failed to load message serializer plugin for agent '%s': %s",
|
|
1102
|
+
self._identity.identifier,
|
|
1103
|
+
str(plugin_err),
|
|
1104
|
+
)
|
|
1105
|
+
|
|
1106
|
+
except ImportError:
|
|
1107
|
+
self._logger.info(
|
|
1108
|
+
"codecraftai-extension not available; skipping message serializer plugin "
|
|
1109
|
+
"discovery for agent '%s'",
|
|
1110
|
+
self._identity.identifier,
|
|
1111
|
+
)
|
|
1112
|
+
except Exception as discovery_err:
|
|
1113
|
+
self._logger.warning(
|
|
1114
|
+
"Message serializer plugin discovery failed for agent '%s': %s",
|
|
1115
|
+
self._identity.identifier,
|
|
1116
|
+
str(discovery_err),
|
|
1117
|
+
)
|
|
1118
|
+
|
|
1119
|
+
self._logger.info(
|
|
1120
|
+
"Messaging initialized for agent '%s'",
|
|
1121
|
+
self._identity.identifier,
|
|
1122
|
+
)
|
|
1123
|
+
return
|
|
1124
|
+
|
|
1125
|
+
def _stop_messaging(self) -> None:
|
|
1126
|
+
"""
|
|
1127
|
+
Stops all receive loops, disconnects all connected transports,
|
|
1128
|
+
clears the TransportRegistry, removes all PubSubBroker
|
|
1129
|
+
subscriptions, and resets the messaging configuration.
|
|
1130
|
+
|
|
1131
|
+
Subclasses should call this method during their stop()
|
|
1132
|
+
implementation to clean up messaging resources.
|
|
1133
|
+
"""
|
|
1134
|
+
# Stop the receive loops before their transports go away
|
|
1135
|
+
self.stop_receiving()
|
|
1136
|
+
|
|
1137
|
+
# Disconnect all connected transports
|
|
1138
|
+
all_transports = self._transport_registry.list_all()
|
|
1139
|
+
|
|
1140
|
+
for transport in all_transports:
|
|
1141
|
+
is_connected = transport.is_connected()
|
|
1142
|
+
|
|
1143
|
+
if is_connected is True:
|
|
1144
|
+
try:
|
|
1145
|
+
transport.disconnect()
|
|
1146
|
+
except Exception as disconnect_err:
|
|
1147
|
+
self._logger.warning(
|
|
1148
|
+
"Failed to disconnect transport '%s' for agent '%s': %s",
|
|
1149
|
+
transport.name,
|
|
1150
|
+
self._identity.identifier,
|
|
1151
|
+
str(disconnect_err),
|
|
1152
|
+
)
|
|
1153
|
+
|
|
1154
|
+
# Clear the TransportRegistry
|
|
1155
|
+
registered_transports = self._transport_registry.list_all()
|
|
1156
|
+
|
|
1157
|
+
for transport in registered_transports:
|
|
1158
|
+
self._transport_registry.deregister(transport.name)
|
|
1159
|
+
|
|
1160
|
+
# Remove all PubSubBroker subscriptions
|
|
1161
|
+
all_subscriptions = list(self._pubsub_broker._subscriptions)
|
|
1162
|
+
|
|
1163
|
+
for subscription in all_subscriptions:
|
|
1164
|
+
self._pubsub_broker.unsubscribe(subscription)
|
|
1165
|
+
|
|
1166
|
+
# Reset messaging configuration
|
|
1167
|
+
self._messaging_configuration = None
|
|
1168
|
+
|
|
1169
|
+
self._logger.info(
|
|
1170
|
+
"Messaging stopped for agent '%s'",
|
|
1171
|
+
self._identity.identifier,
|
|
1172
|
+
)
|
|
1173
|
+
return
|
|
1174
|
+
|
|
1175
|
+
# -----------------------------------------------------------------------
|
|
1176
|
+
# Platform runtime convenience methods
|
|
1177
|
+
# -----------------------------------------------------------------------
|
|
1178
|
+
|
|
1179
|
+
def get_compute_service(self):
|
|
1180
|
+
"""
|
|
1181
|
+
Convenience method delegating to the PlatformRuntime.
|
|
1182
|
+
|
|
1183
|
+
:returns: A ComputeService instance.
|
|
1184
|
+
:raises: SemanticError
|
|
1185
|
+
"""
|
|
1186
|
+
if self._platform_runtime is None:
|
|
1187
|
+
err_msg = "PlatformRuntime must be configured before accessing platform services."
|
|
1188
|
+
raise SemanticError(err_msg)
|
|
1189
|
+
rtnval = self._platform_runtime.get_compute_service()
|
|
1190
|
+
return rtnval
|
|
1191
|
+
|
|
1192
|
+
def get_storage_service(self):
|
|
1193
|
+
"""
|
|
1194
|
+
Convenience method delegating to the PlatformRuntime.
|
|
1195
|
+
|
|
1196
|
+
:returns: A StorageService instance.
|
|
1197
|
+
:raises: SemanticError
|
|
1198
|
+
"""
|
|
1199
|
+
if self._platform_runtime is None:
|
|
1200
|
+
err_msg = "PlatformRuntime must be configured before accessing platform services."
|
|
1201
|
+
raise SemanticError(err_msg)
|
|
1202
|
+
rtnval = self._platform_runtime.get_storage_service()
|
|
1203
|
+
return rtnval
|
|
1204
|
+
|
|
1205
|
+
def get_messaging_service(self):
|
|
1206
|
+
"""
|
|
1207
|
+
Convenience method delegating to the PlatformRuntime.
|
|
1208
|
+
|
|
1209
|
+
:returns: A MessagingService instance.
|
|
1210
|
+
:raises: SemanticError
|
|
1211
|
+
"""
|
|
1212
|
+
if self._platform_runtime is None:
|
|
1213
|
+
err_msg = "PlatformRuntime must be configured before accessing platform services."
|
|
1214
|
+
raise SemanticError(err_msg)
|
|
1215
|
+
rtnval = self._platform_runtime.get_messaging_service()
|
|
1216
|
+
return rtnval
|
|
1217
|
+
|
|
1218
|
+
def _stop_platform(self) -> None:
|
|
1219
|
+
"""
|
|
1220
|
+
Logs the platform runtime status at INFO level when the Agent
|
|
1221
|
+
transitions to the STOPPED state.
|
|
1222
|
+
|
|
1223
|
+
Subclasses should call this method during their stop()
|
|
1224
|
+
implementation to log platform runtime status.
|
|
1225
|
+
"""
|
|
1226
|
+
if self._platform_runtime is not None:
|
|
1227
|
+
platform_type = self._platform_runtime.platform_type.to_string()
|
|
1228
|
+
try:
|
|
1229
|
+
health_results = self._platform_runtime.health_check()
|
|
1230
|
+
except Exception as health_err:
|
|
1231
|
+
health_results = {"error": str(health_err)}
|
|
1232
|
+
|
|
1233
|
+
self._logger.info(
|
|
1234
|
+
"Platform runtime status for agent '%s': platform=%s, health=%s",
|
|
1235
|
+
self._identity.identifier,
|
|
1236
|
+
platform_type,
|
|
1237
|
+
health_results,
|
|
1238
|
+
)
|
|
1239
|
+
return
|
|
1240
|
+
|
|
1241
|
+
# -----------------------------------------------------------------------
|
|
1242
|
+
# LLM provider lifecycle helpers for subclasses
|
|
1243
|
+
# -----------------------------------------------------------------------
|
|
1244
|
+
|
|
1245
|
+
def _initialize_llm_providers(self) -> None:
|
|
1246
|
+
"""
|
|
1247
|
+
Discovers and registers LLMProviderPlugin instances from the
|
|
1248
|
+
"ccai.agentkit.llm_providers" extension point.
|
|
1249
|
+
|
|
1250
|
+
Subclasses should call this method during their initialize()
|
|
1251
|
+
implementation to set up LLM providers.
|
|
1252
|
+
|
|
1253
|
+
Logs WARNING and continues on plugin load failure.
|
|
1254
|
+
Logs WARNING and skips on name-model conflict.
|
|
1255
|
+
"""
|
|
1256
|
+
try:
|
|
1257
|
+
from ccai.extension import ExtensionPoint
|
|
1258
|
+
extension_point = ExtensionPoint("ccai.agentkit.llm_providers")
|
|
1259
|
+
discovered_providers = extension_point.query()
|
|
1260
|
+
|
|
1261
|
+
for provider_entry in discovered_providers:
|
|
1262
|
+
try:
|
|
1263
|
+
provider_instance = provider_entry
|
|
1264
|
+
provider_name = provider_instance.provider_name
|
|
1265
|
+
model_name = provider_instance.model_name
|
|
1266
|
+
has_conflict = self._llm_provider_registry.has_provider(
|
|
1267
|
+
provider_name, model_name
|
|
1268
|
+
)
|
|
1269
|
+
|
|
1270
|
+
if has_conflict is True:
|
|
1271
|
+
self._logger.warning(
|
|
1272
|
+
"LLM provider plugin name conflict: provider '%s' model '%s' "
|
|
1273
|
+
"is already registered in agent '%s'. Skipping plugin provider.",
|
|
1274
|
+
provider_name,
|
|
1275
|
+
model_name,
|
|
1276
|
+
self._identity.identifier,
|
|
1277
|
+
)
|
|
1278
|
+
continue
|
|
1279
|
+
|
|
1280
|
+
self._llm_provider_registry.register(provider_instance)
|
|
1281
|
+
|
|
1282
|
+
except Exception as plugin_err:
|
|
1283
|
+
self._logger.warning(
|
|
1284
|
+
"Failed to load LLM provider plugin for agent '%s': %s",
|
|
1285
|
+
self._identity.identifier,
|
|
1286
|
+
str(plugin_err),
|
|
1287
|
+
)
|
|
1288
|
+
|
|
1289
|
+
except ImportError:
|
|
1290
|
+
self._logger.info(
|
|
1291
|
+
"codecraftai-extension not available; skipping LLM provider plugin "
|
|
1292
|
+
"discovery for agent '%s'",
|
|
1293
|
+
self._identity.identifier,
|
|
1294
|
+
)
|
|
1295
|
+
except Exception as discovery_err:
|
|
1296
|
+
self._logger.warning(
|
|
1297
|
+
"LLM provider plugin discovery failed for agent '%s': %s",
|
|
1298
|
+
self._identity.identifier,
|
|
1299
|
+
str(discovery_err),
|
|
1300
|
+
)
|
|
1301
|
+
|
|
1302
|
+
self._logger.info(
|
|
1303
|
+
"LLM providers initialized for agent '%s'",
|
|
1304
|
+
self._identity.identifier,
|
|
1305
|
+
)
|
|
1306
|
+
return
|
|
1307
|
+
|
|
1308
|
+
def _stop_llm_providers(self) -> None:
|
|
1309
|
+
"""
|
|
1310
|
+
Clears the Agent's LLMProviderRegistry.
|
|
1311
|
+
|
|
1312
|
+
Subclasses should call this method during their stop()
|
|
1313
|
+
implementation to clean up LLM providers.
|
|
1314
|
+
"""
|
|
1315
|
+
self._llm_provider_registry.clear()
|
|
1316
|
+
self._logger.info(
|
|
1317
|
+
"LLM providers cleared for agent '%s'",
|
|
1318
|
+
self._identity.identifier,
|
|
1319
|
+
)
|
|
1320
|
+
return
|
|
1321
|
+
|
|
1322
|
+
# -----------------------------------------------------------------------
|
|
1323
|
+
# Memory lifecycle helpers for subclasses
|
|
1324
|
+
# -----------------------------------------------------------------------
|
|
1325
|
+
|
|
1326
|
+
def _initialize_memory(self, memory_configuration: MemoryConfiguration = None) -> None:
|
|
1327
|
+
"""
|
|
1328
|
+
Initializes the memory system from the given MemoryConfiguration.
|
|
1329
|
+
|
|
1330
|
+
Constructs the primary MemoryStore and ContextWindow based on
|
|
1331
|
+
the configuration. When no configuration is provided, defaults
|
|
1332
|
+
to an InMemoryStore with MemoryScope.AGENT and no expiration.
|
|
1333
|
+
|
|
1334
|
+
Discovers and registers MemoryBackendPlugin instances from the
|
|
1335
|
+
"ccai.agentkit.memory_backends" extension point.
|
|
1336
|
+
|
|
1337
|
+
Subclasses should call this method during their initialize()
|
|
1338
|
+
implementation to set up memory.
|
|
1339
|
+
|
|
1340
|
+
:param memory_configuration: Optional MemoryConfiguration. If None,
|
|
1341
|
+
defaults to InMemoryStore with AGENT scope.
|
|
1342
|
+
"""
|
|
1343
|
+
self._memory_configuration = memory_configuration
|
|
1344
|
+
|
|
1345
|
+
if memory_configuration is not None:
|
|
1346
|
+
backend_type = memory_configuration.backend_type
|
|
1347
|
+
expiration_policy = memory_configuration.expiration_policy
|
|
1348
|
+
|
|
1349
|
+
if backend_type == "inmemory":
|
|
1350
|
+
self._memory_store = InMemoryStore(
|
|
1351
|
+
store_name="primary",
|
|
1352
|
+
expiration_policy=expiration_policy,
|
|
1353
|
+
)
|
|
1354
|
+
elif backend_type == "file":
|
|
1355
|
+
from ccai.agentkit.filememorystore import FileMemoryStore
|
|
1356
|
+
directory_path = memory_configuration.connection_params.get("directory_path", ".memory")
|
|
1357
|
+
self._memory_store = FileMemoryStore(
|
|
1358
|
+
store_name="primary",
|
|
1359
|
+
directory_path=directory_path,
|
|
1360
|
+
expiration_policy=expiration_policy,
|
|
1361
|
+
)
|
|
1362
|
+
else:
|
|
1363
|
+
self._memory_store = InMemoryStore(
|
|
1364
|
+
store_name="primary",
|
|
1365
|
+
expiration_policy=expiration_policy,
|
|
1366
|
+
)
|
|
1367
|
+
|
|
1368
|
+
context_settings = memory_configuration.connection_params.get("context_window", {})
|
|
1369
|
+
max_tokens = context_settings.get("max_tokens", 4096)
|
|
1370
|
+
strategy_str = context_settings.get("strategy", "FIFO")
|
|
1371
|
+
strategy = ContextWindowStrategy.from_string(strategy_str)
|
|
1372
|
+
|
|
1373
|
+
self._context_window = ContextWindow(
|
|
1374
|
+
max_tokens=max_tokens,
|
|
1375
|
+
strategy=strategy,
|
|
1376
|
+
token_counter=lambda text: len(text.split()),
|
|
1377
|
+
)
|
|
1378
|
+
else:
|
|
1379
|
+
self._memory_store = InMemoryStore(store_name="primary")
|
|
1380
|
+
|
|
1381
|
+
self._context_window = ContextWindow(
|
|
1382
|
+
max_tokens=4096,
|
|
1383
|
+
strategy=ContextWindowStrategy.FIFO,
|
|
1384
|
+
token_counter=lambda text: len(text.split()),
|
|
1385
|
+
)
|
|
1386
|
+
|
|
1387
|
+
self._memory_store_registry = MemoryStoreRegistry()
|
|
1388
|
+
self._memory_store_registry.register(store=self._memory_store)
|
|
1389
|
+
|
|
1390
|
+
self._discover_memory_backend_plugins()
|
|
1391
|
+
|
|
1392
|
+
self._logger.info(
|
|
1393
|
+
"Memory initialized for agent '%s' with store '%s'",
|
|
1394
|
+
self._identity.identifier,
|
|
1395
|
+
self._memory_store.store_name,
|
|
1396
|
+
)
|
|
1397
|
+
return
|
|
1398
|
+
|
|
1399
|
+
def _discover_memory_backend_plugins(self) -> None:
|
|
1400
|
+
"""
|
|
1401
|
+
Discovers and registers MemoryBackendPlugin instances from the
|
|
1402
|
+
"ccai.agentkit.memory_backends" extension point.
|
|
1403
|
+
|
|
1404
|
+
Logs WARNING on plugin load failure and continues.
|
|
1405
|
+
Logs WARNING on store name conflict and skips.
|
|
1406
|
+
"""
|
|
1407
|
+
try:
|
|
1408
|
+
from ccai.extension import ExtensionPoint
|
|
1409
|
+
extension_point = ExtensionPoint("ccai.agentkit.memory_backends")
|
|
1410
|
+
discovered_stores = extension_point.query()
|
|
1411
|
+
|
|
1412
|
+
for store_entry in discovered_stores:
|
|
1413
|
+
try:
|
|
1414
|
+
store_instance = store_entry
|
|
1415
|
+
store_name = store_instance.store_name
|
|
1416
|
+
has_conflict = self._memory_store_registry.has_store(name=store_name)
|
|
1417
|
+
|
|
1418
|
+
if has_conflict is True:
|
|
1419
|
+
self._logger.warning(
|
|
1420
|
+
"Memory backend plugin name conflict: store '%s' is already "
|
|
1421
|
+
"registered in agent '%s'. Skipping plugin store.",
|
|
1422
|
+
store_name,
|
|
1423
|
+
self._identity.identifier,
|
|
1424
|
+
)
|
|
1425
|
+
continue
|
|
1426
|
+
|
|
1427
|
+
self._memory_store_registry.register(store=store_instance)
|
|
1428
|
+
|
|
1429
|
+
except Exception as plugin_err:
|
|
1430
|
+
self._logger.warning(
|
|
1431
|
+
"Failed to load memory backend plugin for agent '%s': %s",
|
|
1432
|
+
self._identity.identifier,
|
|
1433
|
+
str(plugin_err),
|
|
1434
|
+
)
|
|
1435
|
+
|
|
1436
|
+
except ImportError:
|
|
1437
|
+
self._logger.info(
|
|
1438
|
+
"codecraftai-extension not available; skipping memory backend plugin "
|
|
1439
|
+
"discovery for agent '%s'",
|
|
1440
|
+
self._identity.identifier,
|
|
1441
|
+
)
|
|
1442
|
+
except Exception as discovery_err:
|
|
1443
|
+
self._logger.warning(
|
|
1444
|
+
"Memory backend plugin discovery failed for agent '%s': %s",
|
|
1445
|
+
self._identity.identifier,
|
|
1446
|
+
str(discovery_err),
|
|
1447
|
+
)
|
|
1448
|
+
|
|
1449
|
+
return
|
|
1450
|
+
|
|
1451
|
+
def _stop_memory(self) -> None:
|
|
1452
|
+
"""
|
|
1453
|
+
Clears the Agent's MemoryStoreRegistry and resets memory references.
|
|
1454
|
+
|
|
1455
|
+
Subclasses should call this method during their stop()
|
|
1456
|
+
implementation to clean up memory resources.
|
|
1457
|
+
"""
|
|
1458
|
+
self._memory_store_registry.clear()
|
|
1459
|
+
self._memory_store = None
|
|
1460
|
+
self._context_window = None
|
|
1461
|
+
self._memory_configuration = None
|
|
1462
|
+
|
|
1463
|
+
self._logger.info(
|
|
1464
|
+
"Memory cleared for agent '%s'",
|
|
1465
|
+
self._identity.identifier,
|
|
1466
|
+
)
|
|
1467
|
+
return
|
|
1468
|
+
|
|
1469
|
+
# -----------------------------------------------------------------------
|
|
1470
|
+
# Workflow lifecycle methods
|
|
1471
|
+
# -----------------------------------------------------------------------
|
|
1472
|
+
|
|
1473
|
+
def _initialize_workflows(self) -> None:
|
|
1474
|
+
"""
|
|
1475
|
+
Initializes the workflow subsystem for this Agent.
|
|
1476
|
+
|
|
1477
|
+
Constructs the WorkflowExecutor and CheckpointManager from the
|
|
1478
|
+
WorkflowConfiguration. If no WorkflowConfiguration is provided,
|
|
1479
|
+
defaults to a WorkflowConfiguration with default values.
|
|
1480
|
+
|
|
1481
|
+
Queries the "ccai.agentkit.workflow_steps" ExtensionPoint
|
|
1482
|
+
and registers all discovered WorkflowStep types.
|
|
1483
|
+
|
|
1484
|
+
Subclasses should call this method during their initialize()
|
|
1485
|
+
implementation to set up workflow capabilities.
|
|
1486
|
+
"""
|
|
1487
|
+
if self._workflow_configuration is None:
|
|
1488
|
+
self._workflow_configuration = WorkflowConfiguration()
|
|
1489
|
+
|
|
1490
|
+
if self._memory_store is not None:
|
|
1491
|
+
self._checkpoint_manager = CheckpointManager(
|
|
1492
|
+
memory_store=self._memory_store
|
|
1493
|
+
)
|
|
1494
|
+
|
|
1495
|
+
self._workflow_executor = WorkflowExecutor(
|
|
1496
|
+
configuration=self._workflow_configuration,
|
|
1497
|
+
checkpoint_manager=self._checkpoint_manager
|
|
1498
|
+
)
|
|
1499
|
+
|
|
1500
|
+
self._logger.info(
|
|
1501
|
+
"Workflow subsystem initialized for agent '%s'.",
|
|
1502
|
+
self._identity.identifier,
|
|
1503
|
+
)
|
|
1504
|
+
|
|
1505
|
+
# Discover workflow step plugins via ExtensionPoint
|
|
1506
|
+
try:
|
|
1507
|
+
from ccai.extension import ExtensionPoint
|
|
1508
|
+
extension_point = ExtensionPoint("ccai.agentkit.workflow_steps")
|
|
1509
|
+
discovered_steps = extension_point.query()
|
|
1510
|
+
|
|
1511
|
+
for step_entry in discovered_steps:
|
|
1512
|
+
try:
|
|
1513
|
+
step_type_name = step_entry.step_type if hasattr(step_entry, "step_type") else str(step_entry)
|
|
1514
|
+
|
|
1515
|
+
self._logger.info(
|
|
1516
|
+
"Discovered workflow step plugin '%s' for agent '%s'.",
|
|
1517
|
+
step_type_name,
|
|
1518
|
+
self._identity.identifier,
|
|
1519
|
+
)
|
|
1520
|
+
|
|
1521
|
+
except Exception as plugin_err:
|
|
1522
|
+
self._logger.warning(
|
|
1523
|
+
"Failed to load workflow step plugin for agent '%s': %s",
|
|
1524
|
+
self._identity.identifier,
|
|
1525
|
+
str(plugin_err),
|
|
1526
|
+
)
|
|
1527
|
+
|
|
1528
|
+
except ImportError:
|
|
1529
|
+
self._logger.info(
|
|
1530
|
+
"codecraftai-extension not available; skipping workflow step plugin "
|
|
1531
|
+
"discovery for agent '%s'.",
|
|
1532
|
+
self._identity.identifier,
|
|
1533
|
+
)
|
|
1534
|
+
except Exception as discovery_err:
|
|
1535
|
+
self._logger.warning(
|
|
1536
|
+
"Workflow step plugin discovery failed for agent '%s': %s",
|
|
1537
|
+
self._identity.identifier,
|
|
1538
|
+
str(discovery_err),
|
|
1539
|
+
)
|
|
1540
|
+
|
|
1541
|
+
return
|
|
1542
|
+
|
|
1543
|
+
def _stop_workflows(self) -> None:
|
|
1544
|
+
"""
|
|
1545
|
+
Clears the Agent's WorkflowRegistry and cancels all pending
|
|
1546
|
+
ApprovalRequests.
|
|
1547
|
+
|
|
1548
|
+
Subclasses should call this method during their stop()
|
|
1549
|
+
implementation to clean up workflow resources.
|
|
1550
|
+
"""
|
|
1551
|
+
self._workflow_registry = WorkflowRegistry()
|
|
1552
|
+
self._workflow_executor = None
|
|
1553
|
+
self._checkpoint_manager = None
|
|
1554
|
+
self._workflow_configuration = None
|
|
1555
|
+
|
|
1556
|
+
# Cancel all pending approval requests
|
|
1557
|
+
pending_requests = self._approval_gate.list_pending()
|
|
1558
|
+
for request in pending_requests:
|
|
1559
|
+
try:
|
|
1560
|
+
self._approval_gate.reject(
|
|
1561
|
+
request.identifier,
|
|
1562
|
+
reason="Agent stopped."
|
|
1563
|
+
)
|
|
1564
|
+
except Exception:
|
|
1565
|
+
# Best-effort cancellation during shutdown; a failure to reject one request
|
|
1566
|
+
# must not prevent the remaining requests from being cancelled or the agent
|
|
1567
|
+
# from stopping.
|
|
1568
|
+
pass
|
|
1569
|
+
|
|
1570
|
+
self._logger.info(
|
|
1571
|
+
"Workflow subsystem stopped for agent '%s'.",
|
|
1572
|
+
self._identity.identifier,
|
|
1573
|
+
)
|
|
1574
|
+
return
|
|
1575
|
+
|
|
1576
|
+
# -----------------------------------------------------------------------
|
|
1577
|
+
# Memory convenience methods
|
|
1578
|
+
# -----------------------------------------------------------------------
|
|
1579
|
+
|
|
1580
|
+
def register_memory_store(self, store: MemoryStore) -> None:
|
|
1581
|
+
"""
|
|
1582
|
+
Registers a MemoryStore with this Agent's MemoryStoreRegistry.
|
|
1583
|
+
|
|
1584
|
+
:param store: The MemoryStore instance to register.
|
|
1585
|
+
"""
|
|
1586
|
+
self._memory_store_registry.register(store=store)
|
|
1587
|
+
return
|
|
1588
|
+
|
|
1589
|
+
def store_memory(self, content: str, metadata: dict = None,
|
|
1590
|
+
tags: list = None, scope: MemoryScope = None) -> MemoryEntry:
|
|
1591
|
+
"""
|
|
1592
|
+
Creates a MemoryEntry and stores it in the Agent's primary MemoryStore.
|
|
1593
|
+
|
|
1594
|
+
:param content: The content string for the memory entry.
|
|
1595
|
+
:param metadata: Optional metadata dictionary.
|
|
1596
|
+
:param tags: Optional list of tag strings.
|
|
1597
|
+
:param scope: Optional MemoryScope. Defaults to AGENT.
|
|
1598
|
+
|
|
1599
|
+
:returns: The stored MemoryEntry.
|
|
1600
|
+
:raises: SemanticError if no primary MemoryStore is configured.
|
|
1601
|
+
"""
|
|
1602
|
+
if self._memory_store is None:
|
|
1603
|
+
errmsg = "No primary MemoryStore is configured for agent '{}'.".format(
|
|
1604
|
+
self._identity.identifier
|
|
1605
|
+
)
|
|
1606
|
+
raise SemanticError(errmsg)
|
|
1607
|
+
|
|
1608
|
+
if scope is None:
|
|
1609
|
+
scope = MemoryScope.AGENT
|
|
1610
|
+
|
|
1611
|
+
entry = MemoryEntry(
|
|
1612
|
+
content=content,
|
|
1613
|
+
scope=scope,
|
|
1614
|
+
metadata=metadata,
|
|
1615
|
+
tags=tags,
|
|
1616
|
+
)
|
|
1617
|
+
|
|
1618
|
+
stored_entry = self._memory_store.store(entry=entry)
|
|
1619
|
+
rtnval = stored_entry
|
|
1620
|
+
return rtnval
|
|
1621
|
+
|
|
1622
|
+
def search_memory(self, query: MemoryQuery) -> MemoryQueryResult:
|
|
1623
|
+
"""
|
|
1624
|
+
Executes a MemoryQuery against the Agent's primary MemoryStore.
|
|
1625
|
+
|
|
1626
|
+
:param query: The MemoryQuery with filter criteria.
|
|
1627
|
+
|
|
1628
|
+
:returns: A MemoryQueryResult with matching entries.
|
|
1629
|
+
:raises: SemanticError if no primary MemoryStore is configured.
|
|
1630
|
+
"""
|
|
1631
|
+
if self._memory_store is None:
|
|
1632
|
+
errmsg = "No primary MemoryStore is configured for agent '{}'.".format(
|
|
1633
|
+
self._identity.identifier
|
|
1634
|
+
)
|
|
1635
|
+
raise SemanticError(errmsg)
|
|
1636
|
+
|
|
1637
|
+
rtnval = self._memory_store.search(query=query)
|
|
1638
|
+
return rtnval
|
|
1639
|
+
|
|
1640
|
+
def build_context(self, conversation: LLMConversation,
|
|
1641
|
+
memory_query: MemoryQuery = None) -> LLMConversation:
|
|
1642
|
+
"""
|
|
1643
|
+
Builds a trimmed LLMConversation using the Agent's ContextWindow.
|
|
1644
|
+
|
|
1645
|
+
If a memory_query is provided, searches the primary MemoryStore
|
|
1646
|
+
and passes the matching entries to the ContextWindow for inclusion.
|
|
1647
|
+
|
|
1648
|
+
:param conversation: The input LLMConversation.
|
|
1649
|
+
:param memory_query: Optional MemoryQuery for retrieving relevant memory.
|
|
1650
|
+
|
|
1651
|
+
:returns: A trimmed LLMConversation that fits within the token limit.
|
|
1652
|
+
:raises: SemanticError if no ContextWindow is configured.
|
|
1653
|
+
"""
|
|
1654
|
+
if self._context_window is None:
|
|
1655
|
+
errmsg = "No ContextWindow is configured for agent '{}'.".format(
|
|
1656
|
+
self._identity.identifier
|
|
1657
|
+
)
|
|
1658
|
+
raise SemanticError(errmsg)
|
|
1659
|
+
|
|
1660
|
+
memory_entries = None
|
|
1661
|
+
if memory_query is not None and self._memory_store is not None:
|
|
1662
|
+
query_result = self._memory_store.search(query=memory_query)
|
|
1663
|
+
memory_entries = query_result.entries
|
|
1664
|
+
|
|
1665
|
+
rtnval = self._context_window.build(
|
|
1666
|
+
conversation=conversation,
|
|
1667
|
+
memory_entries=memory_entries,
|
|
1668
|
+
)
|
|
1669
|
+
return rtnval
|
|
1670
|
+
|
|
1671
|
+
# -----------------------------------------------------------------------
|
|
1672
|
+
# Workflow methods
|
|
1673
|
+
# -----------------------------------------------------------------------
|
|
1674
|
+
|
|
1675
|
+
def register_workflow(self, workflow: WorkflowDefinition) -> None:
|
|
1676
|
+
"""
|
|
1677
|
+
Registers a WorkflowDefinition with this Agent's WorkflowRegistry.
|
|
1678
|
+
|
|
1679
|
+
:param workflow: The WorkflowDefinition instance to register.
|
|
1680
|
+
"""
|
|
1681
|
+
self._workflow_registry.register(workflow)
|
|
1682
|
+
return
|
|
1683
|
+
|
|
1684
|
+
def execute_workflow(self, name: str, inputs: dict,
|
|
1685
|
+
version: str = None) -> WorkflowResult:
|
|
1686
|
+
"""
|
|
1687
|
+
Looks up and executes a workflow by name and optional version.
|
|
1688
|
+
|
|
1689
|
+
Retrieves the WorkflowDefinition from the Agent's WorkflowRegistry
|
|
1690
|
+
using the provided name and optional version, then executes the
|
|
1691
|
+
workflow through the WorkflowExecutor.
|
|
1692
|
+
|
|
1693
|
+
:param name: The workflow name to look up.
|
|
1694
|
+
:param inputs: The initial input dictionary for the workflow.
|
|
1695
|
+
:param version: Optional version string. When None, the latest version is used.
|
|
1696
|
+
|
|
1697
|
+
:returns: A WorkflowResult with the execution outcome.
|
|
1698
|
+
:raises: SemanticError if the workflow is not found in the registry.
|
|
1699
|
+
"""
|
|
1700
|
+
workflow = self._workflow_registry.lookup(name, version)
|
|
1701
|
+
if workflow is None:
|
|
1702
|
+
errmsg = "Workflow '{}' not found in the registry.".format(name)
|
|
1703
|
+
raise SemanticError(errmsg)
|
|
1704
|
+
|
|
1705
|
+
if self._workflow_executor is None:
|
|
1706
|
+
self._workflow_executor = WorkflowExecutor(
|
|
1707
|
+
configuration=self._workflow_configuration,
|
|
1708
|
+
checkpoint_manager=self._checkpoint_manager
|
|
1709
|
+
)
|
|
1710
|
+
|
|
1711
|
+
result = self._workflow_executor.execute(workflow, inputs, agent=self)
|
|
1712
|
+
return result
|
|
1713
|
+
|
|
1714
|
+
def resume_workflow(self, execution_id: str,
|
|
1715
|
+
workflow_name: str = None) -> WorkflowResult:
|
|
1716
|
+
"""
|
|
1717
|
+
Resumes a workflow from the last checkpoint.
|
|
1718
|
+
|
|
1719
|
+
Loads the most recent checkpoint for the given execution identifier
|
|
1720
|
+
and continues execution from the step following the last completed step.
|
|
1721
|
+
|
|
1722
|
+
:param execution_id: The workflow execution identifier.
|
|
1723
|
+
:param workflow_name: Optional workflow name to look up the WorkflowDefinition.
|
|
1724
|
+
|
|
1725
|
+
:returns: A WorkflowResult with the execution outcome.
|
|
1726
|
+
:raises: SemanticError if the workflow name is provided but not found.
|
|
1727
|
+
"""
|
|
1728
|
+
if self._workflow_executor is None:
|
|
1729
|
+
self._workflow_executor = WorkflowExecutor(
|
|
1730
|
+
configuration=self._workflow_configuration,
|
|
1731
|
+
checkpoint_manager=self._checkpoint_manager
|
|
1732
|
+
)
|
|
1733
|
+
|
|
1734
|
+
workflow = None
|
|
1735
|
+
if workflow_name is not None:
|
|
1736
|
+
workflow = self._workflow_registry.lookup(workflow_name)
|
|
1737
|
+
if workflow is None:
|
|
1738
|
+
errmsg = "Workflow '{}' not found in the registry.".format(workflow_name)
|
|
1739
|
+
raise SemanticError(errmsg)
|
|
1740
|
+
|
|
1741
|
+
result = self._workflow_executor.resume(execution_id, workflow, agent=self)
|
|
1742
|
+
return result
|
|
1743
|
+
|
|
1744
|
+
# -----------------------------------------------------------------------
|
|
1745
|
+
# Messaging methods
|
|
1746
|
+
# -----------------------------------------------------------------------
|
|
1747
|
+
|
|
1748
|
+
def register_transport(self, transport: Transport) -> None:
|
|
1749
|
+
"""
|
|
1750
|
+
Registers a Transport with this Agent's TransportRegistry and
|
|
1751
|
+
attaches the Agent's MessageSerializerRegistry to it, so the
|
|
1752
|
+
transport serializes messages with the serializers registered
|
|
1753
|
+
with this Agent.
|
|
1754
|
+
|
|
1755
|
+
:param transport: The Transport instance to register.
|
|
1756
|
+
"""
|
|
1757
|
+
self._transport_registry.register(transport=transport)
|
|
1758
|
+
transport.attach_serializer_registry(self._message_serializer_registry)
|
|
1759
|
+
return
|
|
1760
|
+
|
|
1761
|
+
def _prepare_message_serialization(self, transport: Transport,
|
|
1762
|
+
serialization_format: Optional[str]) -> str:
|
|
1763
|
+
"""
|
|
1764
|
+
Resolves the serialization format for an outgoing message and
|
|
1765
|
+
makes sure the transport can serialize the message in it.
|
|
1766
|
+
|
|
1767
|
+
The format is the explicitly requested format, else the
|
|
1768
|
+
MessagingConfiguration default, else the built-in 'json'
|
|
1769
|
+
format. The format must be provided by a MessageSerializer
|
|
1770
|
+
registered with this Agent, except for 'json', which is always
|
|
1771
|
+
available. The Agent's MessageSerializerRegistry is attached to
|
|
1772
|
+
the transport when it is not attached already, which covers
|
|
1773
|
+
transports registered directly with the TransportRegistry.
|
|
1774
|
+
|
|
1775
|
+
:param transport: The Transport the message will be sent through.
|
|
1776
|
+
:param serialization_format: The requested serialization format
|
|
1777
|
+
name or None.
|
|
1778
|
+
|
|
1779
|
+
:returns: The effective serialization format name to set on the
|
|
1780
|
+
Message.
|
|
1781
|
+
|
|
1782
|
+
:raises SemanticError: If no MessageSerializer is registered with
|
|
1783
|
+
this Agent for the format.
|
|
1784
|
+
"""
|
|
1785
|
+
effective_serialization_format = serialization_format
|
|
1786
|
+
if effective_serialization_format is None and self._messaging_configuration is not None:
|
|
1787
|
+
effective_serialization_format = self._messaging_configuration.default_serialization_format
|
|
1788
|
+
|
|
1789
|
+
if effective_serialization_format is None:
|
|
1790
|
+
effective_serialization_format = DEFAULT_SERIALIZATION_FORMAT
|
|
1791
|
+
|
|
1792
|
+
has_serializer = self._message_serializer_registry.has_serializer(effective_serialization_format)
|
|
1793
|
+
is_default_format = effective_serialization_format == DEFAULT_SERIALIZATION_FORMAT
|
|
1794
|
+
|
|
1795
|
+
if has_serializer is not True and is_default_format is not True:
|
|
1796
|
+
registered_formats = []
|
|
1797
|
+
for registered_serializer in self._message_serializer_registry.list_all():
|
|
1798
|
+
registered_formats.append(registered_serializer.format_name)
|
|
1799
|
+
registered_formats.sort()
|
|
1800
|
+
|
|
1801
|
+
errmsg_lines = [
|
|
1802
|
+
"Serialization format '{}' is not available in agent '{}'.".format(
|
|
1803
|
+
effective_serialization_format, self._identity.identifier
|
|
1804
|
+
),
|
|
1805
|
+
" REGISTERED FORMATS: {}".format(registered_formats),
|
|
1806
|
+
" The '{}' format is always available. Other formats need a MessageSerializer".format(
|
|
1807
|
+
DEFAULT_SERIALIZATION_FORMAT
|
|
1808
|
+
),
|
|
1809
|
+
" registered through the 'ccai.agentkit.message_serializers' extension point.",
|
|
1810
|
+
]
|
|
1811
|
+
errmsg = os.linesep.join(errmsg_lines)
|
|
1812
|
+
raise SemanticError(errmsg)
|
|
1813
|
+
|
|
1814
|
+
self._attach_serializers_to_transport(transport)
|
|
1815
|
+
|
|
1816
|
+
return effective_serialization_format
|
|
1817
|
+
|
|
1818
|
+
def _attach_serializers_to_transport(self, transport: Transport) -> None:
|
|
1819
|
+
"""
|
|
1820
|
+
Attaches the Agent's MessageSerializerRegistry to a transport when
|
|
1821
|
+
it is not attached already, so the transport encodes and decodes
|
|
1822
|
+
messages with the serializers registered with this Agent. This
|
|
1823
|
+
covers transports registered directly with the TransportRegistry.
|
|
1824
|
+
|
|
1825
|
+
:param transport: The Transport to attach the registry to.
|
|
1826
|
+
"""
|
|
1827
|
+
if transport.serializer_registry is not self._message_serializer_registry:
|
|
1828
|
+
transport.attach_serializer_registry(self._message_serializer_registry)
|
|
1829
|
+
|
|
1830
|
+
return
|
|
1831
|
+
|
|
1832
|
+
def send_message(self, recipient_id: str, payload: object,
|
|
1833
|
+
transport_name: str = None,
|
|
1834
|
+
serialization_format: str = None,
|
|
1835
|
+
pattern: MessagePattern = MessagePattern.FIRE_AND_FORGET,
|
|
1836
|
+
headers: dict = None) -> MessageEnvelope:
|
|
1837
|
+
"""
|
|
1838
|
+
Constructs and sends a Message to the specified recipient.
|
|
1839
|
+
|
|
1840
|
+
Resolves the default transport name and serialization format
|
|
1841
|
+
from the MessagingConfiguration when not provided. Looks up
|
|
1842
|
+
the transport from the TransportRegistry, resolves the
|
|
1843
|
+
recipient address via the AddressResolver, constructs a
|
|
1844
|
+
Message that carries the serialization format, and sends it
|
|
1845
|
+
through the transport, which serializes the message with the
|
|
1846
|
+
MessageSerializer registered for that format.
|
|
1847
|
+
|
|
1848
|
+
:param recipient_id: The recipient agent identifier.
|
|
1849
|
+
:param payload: The message payload.
|
|
1850
|
+
:param transport_name: Optional transport name. Defaults to
|
|
1851
|
+
the MessagingConfiguration default.
|
|
1852
|
+
:param serialization_format: Optional serialization format
|
|
1853
|
+
name. Defaults to the MessagingConfiguration default, or
|
|
1854
|
+
'json' when no MessagingConfiguration is provided.
|
|
1855
|
+
:param pattern: The MessagePattern. Defaults to
|
|
1856
|
+
FIRE_AND_FORGET.
|
|
1857
|
+
:param headers: Optional headers dictionary.
|
|
1858
|
+
|
|
1859
|
+
:returns: A MessageEnvelope with delivery metadata.
|
|
1860
|
+
|
|
1861
|
+
:raises SemanticError: If the requested transport is not
|
|
1862
|
+
found in the TransportRegistry, or if no
|
|
1863
|
+
MessageSerializer is registered for the serialization
|
|
1864
|
+
format.
|
|
1865
|
+
"""
|
|
1866
|
+
effective_transport_name = transport_name
|
|
1867
|
+
if effective_transport_name is None and self._messaging_configuration is not None:
|
|
1868
|
+
effective_transport_name = self._messaging_configuration.default_transport
|
|
1869
|
+
|
|
1870
|
+
transport = self._transport_registry.lookup(effective_transport_name)
|
|
1871
|
+
|
|
1872
|
+
if transport is None:
|
|
1873
|
+
errmsg_lines = [
|
|
1874
|
+
"Transport '{}' not found in agent '{}'.".format(
|
|
1875
|
+
effective_transport_name, self._identity.identifier
|
|
1876
|
+
),
|
|
1877
|
+
]
|
|
1878
|
+
errmsg = os.linesep.join(errmsg_lines)
|
|
1879
|
+
raise SemanticError(errmsg)
|
|
1880
|
+
|
|
1881
|
+
effective_serialization_format = self._prepare_message_serialization(
|
|
1882
|
+
transport=transport,
|
|
1883
|
+
serialization_format=serialization_format,
|
|
1884
|
+
)
|
|
1885
|
+
|
|
1886
|
+
recipient_address = self._address_resolver.resolve(
|
|
1887
|
+
agent_identifier=recipient_id,
|
|
1888
|
+
transport_name=effective_transport_name,
|
|
1889
|
+
)
|
|
1890
|
+
|
|
1891
|
+
sender_address = AgentAddress(
|
|
1892
|
+
agent_identifier=self._identity.identifier,
|
|
1893
|
+
transport_name=effective_transport_name,
|
|
1894
|
+
)
|
|
1895
|
+
|
|
1896
|
+
message = Message(
|
|
1897
|
+
sender=sender_address,
|
|
1898
|
+
recipient=recipient_address,
|
|
1899
|
+
payload=payload,
|
|
1900
|
+
pattern=pattern,
|
|
1901
|
+
headers=headers,
|
|
1902
|
+
serialization_format=effective_serialization_format,
|
|
1903
|
+
)
|
|
1904
|
+
|
|
1905
|
+
envelope = transport.send(message)
|
|
1906
|
+
|
|
1907
|
+
return envelope
|
|
1908
|
+
|
|
1909
|
+
def request(self, recipient_id: str, payload: object,
|
|
1910
|
+
transport_name: str = None,
|
|
1911
|
+
serialization_format: str = None,
|
|
1912
|
+
timeout: float = None,
|
|
1913
|
+
headers: dict = None) -> Message:
|
|
1914
|
+
"""
|
|
1915
|
+
Sends a request and awaits a correlated response.
|
|
1916
|
+
|
|
1917
|
+
Resolves the default transport name and serialization format
|
|
1918
|
+
from the MessagingConfiguration when not provided. Constructs
|
|
1919
|
+
a REQUEST Message that carries the serialization format and
|
|
1920
|
+
delegates to the RequestResponseHandler for correlated
|
|
1921
|
+
response tracking. The transport serializes the request with
|
|
1922
|
+
the MessageSerializer registered for that format.
|
|
1923
|
+
|
|
1924
|
+
The call blocks until the response is delivered by
|
|
1925
|
+
receive_message, so the replies must be received on another
|
|
1926
|
+
thread while it waits: start a receive loop for the transport
|
|
1927
|
+
with start_receiving, or have the transport hand incoming
|
|
1928
|
+
messages to receive_message.
|
|
1929
|
+
|
|
1930
|
+
:param recipient_id: The recipient agent identifier.
|
|
1931
|
+
:param payload: The request payload.
|
|
1932
|
+
:param transport_name: Optional transport name. Defaults to
|
|
1933
|
+
the MessagingConfiguration default.
|
|
1934
|
+
:param serialization_format: Optional serialization format
|
|
1935
|
+
name. Defaults to the MessagingConfiguration default, or
|
|
1936
|
+
'json' when no MessagingConfiguration is provided.
|
|
1937
|
+
:param timeout: Optional timeout in seconds.
|
|
1938
|
+
:param headers: Optional headers dictionary.
|
|
1939
|
+
|
|
1940
|
+
:returns: The correlated response Message.
|
|
1941
|
+
|
|
1942
|
+
:raises SemanticError: If the requested transport is not
|
|
1943
|
+
found in the TransportRegistry, or if no
|
|
1944
|
+
MessageSerializer is registered for the serialization
|
|
1945
|
+
format.
|
|
1946
|
+
:raises MessageTimeoutError: If no response is received
|
|
1947
|
+
within the timeout duration.
|
|
1948
|
+
"""
|
|
1949
|
+
effective_transport_name = transport_name
|
|
1950
|
+
if effective_transport_name is None and self._messaging_configuration is not None:
|
|
1951
|
+
effective_transport_name = self._messaging_configuration.default_transport
|
|
1952
|
+
|
|
1953
|
+
transport = self._transport_registry.lookup(effective_transport_name)
|
|
1954
|
+
|
|
1955
|
+
if transport is None:
|
|
1956
|
+
errmsg_lines = [
|
|
1957
|
+
"Transport '{}' not found in agent '{}'.".format(
|
|
1958
|
+
effective_transport_name, self._identity.identifier
|
|
1959
|
+
),
|
|
1960
|
+
]
|
|
1961
|
+
errmsg = os.linesep.join(errmsg_lines)
|
|
1962
|
+
raise SemanticError(errmsg)
|
|
1963
|
+
|
|
1964
|
+
effective_serialization_format = self._prepare_message_serialization(
|
|
1965
|
+
transport=transport,
|
|
1966
|
+
serialization_format=serialization_format,
|
|
1967
|
+
)
|
|
1968
|
+
|
|
1969
|
+
recipient_address = self._address_resolver.resolve(
|
|
1970
|
+
agent_identifier=recipient_id,
|
|
1971
|
+
transport_name=effective_transport_name,
|
|
1972
|
+
)
|
|
1973
|
+
|
|
1974
|
+
sender_address = AgentAddress(
|
|
1975
|
+
agent_identifier=self._identity.identifier,
|
|
1976
|
+
transport_name=effective_transport_name,
|
|
1977
|
+
)
|
|
1978
|
+
|
|
1979
|
+
message = Message(
|
|
1980
|
+
sender=sender_address,
|
|
1981
|
+
recipient=recipient_address,
|
|
1982
|
+
payload=payload,
|
|
1983
|
+
pattern=MessagePattern.REQUEST,
|
|
1984
|
+
headers=headers,
|
|
1985
|
+
serialization_format=effective_serialization_format,
|
|
1986
|
+
)
|
|
1987
|
+
|
|
1988
|
+
response = self._request_response_handler.send_request(
|
|
1989
|
+
message=message,
|
|
1990
|
+
transport=transport,
|
|
1991
|
+
timeout=timeout,
|
|
1992
|
+
)
|
|
1993
|
+
|
|
1994
|
+
return response
|
|
1995
|
+
|
|
1996
|
+
def receive_message(self, message: Message, transport_name: Optional[str] = None) -> None:
|
|
1997
|
+
"""
|
|
1998
|
+
Dispatches a message received by this Agent.
|
|
1999
|
+
|
|
2000
|
+
This is the single entry point for incoming messages.
|
|
2001
|
+
poll_transport and the receive loops started with
|
|
2002
|
+
start_receiving call it for every message they receive, and a
|
|
2003
|
+
transport or server that is handed messages calls it directly.
|
|
2004
|
+
|
|
2005
|
+
A RESPONSE message that carries a correlation identifier is a
|
|
2006
|
+
reply to a request sent with request(). It is delivered to the
|
|
2007
|
+
RequestResponseHandler, which completes the waiting request()
|
|
2008
|
+
call. A reply that matches no pending request, because it is
|
|
2009
|
+
unknown or arrived after the request timed out, is logged at
|
|
2010
|
+
WARNING and ignored, as RequestResponseHandler.handle_response
|
|
2011
|
+
documents; it is not routed. Every other message is routed
|
|
2012
|
+
through the MessageRouter to the registered handlers. A handler
|
|
2013
|
+
answers a REQUEST message by calling reply().
|
|
2014
|
+
|
|
2015
|
+
:param message: The received Message.
|
|
2016
|
+
:param transport_name: The name of the transport the message was
|
|
2017
|
+
received on, used for logging.
|
|
2018
|
+
|
|
2019
|
+
:raises MessageRoutingError: If a message that is not a reply
|
|
2020
|
+
matches no registered handler.
|
|
2021
|
+
"""
|
|
2022
|
+
pattern_value = message.pattern.value if message.pattern is not None else None
|
|
2023
|
+
sender_identifier = message.sender.agent_identifier if message.sender is not None else None
|
|
2024
|
+
|
|
2025
|
+
self._logger.info(
|
|
2026
|
+
"Message received: agent='%s', message_id='%s', sender='%s', "
|
|
2027
|
+
"transport='%s', pattern='%s', correlation_id='%s'",
|
|
2028
|
+
self._identity.identifier, message.identifier, sender_identifier,
|
|
2029
|
+
transport_name, pattern_value, message.correlation_id,
|
|
2030
|
+
)
|
|
2031
|
+
|
|
2032
|
+
is_response = message.pattern == MessagePattern.RESPONSE
|
|
2033
|
+
has_correlation_id = message.correlation_id is not None
|
|
2034
|
+
|
|
2035
|
+
if is_response is True and has_correlation_id is True:
|
|
2036
|
+
self._request_response_handler.handle_response(message)
|
|
2037
|
+
return
|
|
2038
|
+
|
|
2039
|
+
self._message_router.route(message)
|
|
2040
|
+
|
|
2041
|
+
return
|
|
2042
|
+
|
|
2043
|
+
def reply(self, request_message: Message, payload: object,
|
|
2044
|
+
transport_name: Optional[str] = None,
|
|
2045
|
+
headers: Optional[Dict] = None) -> MessageEnvelope:
|
|
2046
|
+
"""
|
|
2047
|
+
Sends the RESPONSE to a REQUEST message received by this Agent.
|
|
2048
|
+
|
|
2049
|
+
The response is addressed to the sender of the request and
|
|
2050
|
+
carries the request's correlation identifier, so the requesting
|
|
2051
|
+
Agent's request() call completes with it. It is serialized in the
|
|
2052
|
+
request's serialization format.
|
|
2053
|
+
|
|
2054
|
+
:param request_message: The received REQUEST Message to answer.
|
|
2055
|
+
:param payload: The response payload.
|
|
2056
|
+
:param transport_name: Optional transport to send the response
|
|
2057
|
+
through. Defaults to the transport named in the request's
|
|
2058
|
+
sender address, which is the transport the requester used.
|
|
2059
|
+
:param headers: Optional headers dictionary for the response.
|
|
2060
|
+
|
|
2061
|
+
:returns: A MessageEnvelope with delivery metadata.
|
|
2062
|
+
|
|
2063
|
+
:raises SemanticError: If the message is not a REQUEST with a
|
|
2064
|
+
correlation identifier, if the transport is not found in the
|
|
2065
|
+
TransportRegistry, or if no MessageSerializer is registered
|
|
2066
|
+
for the request's serialization format.
|
|
2067
|
+
"""
|
|
2068
|
+
is_request = request_message.pattern == MessagePattern.REQUEST
|
|
2069
|
+
has_correlation_id = request_message.correlation_id is not None
|
|
2070
|
+
|
|
2071
|
+
if is_request is not True or has_correlation_id is not True:
|
|
2072
|
+
pattern_value = request_message.pattern.value if request_message.pattern is not None else None
|
|
2073
|
+
errmsg_lines = [
|
|
2074
|
+
"Agent '{}' can only reply to a REQUEST message with a correlation identifier.".format(
|
|
2075
|
+
self._identity.identifier
|
|
2076
|
+
),
|
|
2077
|
+
" MESSAGE: {}".format(request_message.identifier),
|
|
2078
|
+
" PATTERN: {}".format(pattern_value),
|
|
2079
|
+
" CORRELATION ID: {}".format(request_message.correlation_id),
|
|
2080
|
+
]
|
|
2081
|
+
errmsg = os.linesep.join(errmsg_lines)
|
|
2082
|
+
raise SemanticError(errmsg)
|
|
2083
|
+
|
|
2084
|
+
effective_transport_name = transport_name
|
|
2085
|
+
if effective_transport_name is None:
|
|
2086
|
+
effective_transport_name = request_message.sender.transport_name
|
|
2087
|
+
|
|
2088
|
+
transport = self._transport_registry.lookup(effective_transport_name)
|
|
2089
|
+
|
|
2090
|
+
if transport is None:
|
|
2091
|
+
errmsg_lines = [
|
|
2092
|
+
"Transport '{}' not found in agent '{}'.".format(
|
|
2093
|
+
effective_transport_name, self._identity.identifier
|
|
2094
|
+
),
|
|
2095
|
+
" The reply to request '{}' is sent through the transport named in the".format(
|
|
2096
|
+
request_message.identifier
|
|
2097
|
+
),
|
|
2098
|
+
" request's sender address unless a transport_name is passed to reply().",
|
|
2099
|
+
]
|
|
2100
|
+
errmsg = os.linesep.join(errmsg_lines)
|
|
2101
|
+
raise SemanticError(errmsg)
|
|
2102
|
+
|
|
2103
|
+
effective_serialization_format = self._prepare_message_serialization(
|
|
2104
|
+
transport=transport,
|
|
2105
|
+
serialization_format=request_message.serialization_format,
|
|
2106
|
+
)
|
|
2107
|
+
|
|
2108
|
+
sender_address = AgentAddress(
|
|
2109
|
+
agent_identifier=self._identity.identifier,
|
|
2110
|
+
transport_name=effective_transport_name,
|
|
2111
|
+
)
|
|
2112
|
+
|
|
2113
|
+
response_message = Message(
|
|
2114
|
+
sender=sender_address,
|
|
2115
|
+
recipient=request_message.sender,
|
|
2116
|
+
payload=payload,
|
|
2117
|
+
pattern=MessagePattern.RESPONSE,
|
|
2118
|
+
headers=headers,
|
|
2119
|
+
correlation_id=request_message.correlation_id,
|
|
2120
|
+
serialization_format=effective_serialization_format,
|
|
2121
|
+
)
|
|
2122
|
+
|
|
2123
|
+
envelope = transport.send(response_message)
|
|
2124
|
+
|
|
2125
|
+
return envelope
|
|
2126
|
+
|
|
2127
|
+
def _receive_from_transport(self, transport_name: str) -> Optional[Message]:
|
|
2128
|
+
"""
|
|
2129
|
+
Receives at most one message from a registered transport without
|
|
2130
|
+
dispatching it.
|
|
2131
|
+
|
|
2132
|
+
:param transport_name: The name of the registered transport.
|
|
2133
|
+
|
|
2134
|
+
:returns: The received Message, or None when the transport has no
|
|
2135
|
+
message available.
|
|
2136
|
+
|
|
2137
|
+
:raises SemanticError: If the transport is not registered.
|
|
2138
|
+
:raises TransportError: If the receive fails for any reason other
|
|
2139
|
+
than no message being available.
|
|
2140
|
+
"""
|
|
2141
|
+
transport = self._transport_registry.lookup(transport_name)
|
|
2142
|
+
|
|
2143
|
+
if transport is None:
|
|
2144
|
+
errmsg_lines = [
|
|
2145
|
+
"Transport '{}' not found in agent '{}'.".format(
|
|
2146
|
+
transport_name, self._identity.identifier
|
|
2147
|
+
),
|
|
2148
|
+
]
|
|
2149
|
+
errmsg = os.linesep.join(errmsg_lines)
|
|
2150
|
+
raise SemanticError(errmsg)
|
|
2151
|
+
|
|
2152
|
+
self._attach_serializers_to_transport(transport)
|
|
2153
|
+
|
|
2154
|
+
try:
|
|
2155
|
+
message = transport.receive()
|
|
2156
|
+
except NoMessageAvailableError:
|
|
2157
|
+
message = None
|
|
2158
|
+
|
|
2159
|
+
return message
|
|
2160
|
+
|
|
2161
|
+
def poll_transport(self, transport_name: str) -> Optional[Message]:
|
|
2162
|
+
"""
|
|
2163
|
+
Receives at most one message from a registered transport and
|
|
2164
|
+
dispatches it with receive_message.
|
|
2165
|
+
|
|
2166
|
+
:param transport_name: The name of the registered transport.
|
|
2167
|
+
|
|
2168
|
+
:returns: The Message that was received and dispatched, or None
|
|
2169
|
+
when the transport has no message available.
|
|
2170
|
+
|
|
2171
|
+
:raises SemanticError: If the transport is not registered.
|
|
2172
|
+
:raises TransportError: If the receive fails for any reason other
|
|
2173
|
+
than no message being available.
|
|
2174
|
+
:raises MessageRoutingError: If the received message is not a
|
|
2175
|
+
reply and matches no registered handler.
|
|
2176
|
+
"""
|
|
2177
|
+
message = self._receive_from_transport(transport_name)
|
|
2178
|
+
|
|
2179
|
+
if message is not None:
|
|
2180
|
+
self.receive_message(message=message, transport_name=transport_name)
|
|
2181
|
+
|
|
2182
|
+
return message
|
|
2183
|
+
|
|
2184
|
+
def start_receiving(self, transport_name: str,
|
|
2185
|
+
poll_interval: float = DEFAULT_RECEIVE_POLL_INTERVAL) -> None:
|
|
2186
|
+
"""
|
|
2187
|
+
Starts a background thread that keeps receiving messages from a
|
|
2188
|
+
registered transport and dispatches each one with
|
|
2189
|
+
receive_message. Replies then complete the request() calls that
|
|
2190
|
+
are waiting for them and requests reach their handlers while the
|
|
2191
|
+
calling threads are blocked.
|
|
2192
|
+
|
|
2193
|
+
The loop waits poll_interval seconds whenever the transport has
|
|
2194
|
+
no message available. A failed receive is logged at WARNING for
|
|
2195
|
+
the first failure of a run of consecutive failures and at DEBUG
|
|
2196
|
+
for the repeats, and the loop waits poll_interval seconds and
|
|
2197
|
+
continues. A message that cannot be dispatched, for example
|
|
2198
|
+
because no handler matches it, is logged at WARNING and the loop
|
|
2199
|
+
continues with the next message. SemanticError and
|
|
2200
|
+
ConfigurationError are not caught. stop_receiving ends the loop.
|
|
2201
|
+
|
|
2202
|
+
A handler that runs on the receive loop must not call request()
|
|
2203
|
+
through the same transport, because the loop cannot receive the
|
|
2204
|
+
reply while the handler waits for it.
|
|
2205
|
+
|
|
2206
|
+
:param transport_name: The name of the registered transport to
|
|
2207
|
+
receive from.
|
|
2208
|
+
:param poll_interval: The number of seconds to wait before
|
|
2209
|
+
polling again after an empty or failed receive. Must be
|
|
2210
|
+
greater than 0.
|
|
2211
|
+
|
|
2212
|
+
:raises SemanticError: If the transport is not registered, if
|
|
2213
|
+
poll_interval is not greater than 0, or if a receive loop is
|
|
2214
|
+
already running for the transport.
|
|
2215
|
+
"""
|
|
2216
|
+
if poll_interval is None or poll_interval <= 0:
|
|
2217
|
+
errmsg = "The poll_interval for agent '{}' must be greater than 0, got {!r}.".format(
|
|
2218
|
+
self._identity.identifier, poll_interval
|
|
2219
|
+
)
|
|
2220
|
+
raise SemanticError(errmsg)
|
|
2221
|
+
|
|
2222
|
+
transport = self._transport_registry.lookup(transport_name)
|
|
2223
|
+
|
|
2224
|
+
if transport is None:
|
|
2225
|
+
errmsg_lines = [
|
|
2226
|
+
"Transport '{}' not found in agent '{}'.".format(
|
|
2227
|
+
transport_name, self._identity.identifier
|
|
2228
|
+
),
|
|
2229
|
+
]
|
|
2230
|
+
errmsg = os.linesep.join(errmsg_lines)
|
|
2231
|
+
raise SemanticError(errmsg)
|
|
2232
|
+
|
|
2233
|
+
with self._receive_loops_lock:
|
|
2234
|
+
existing_entry = self._receive_loops.get(transport_name, None)
|
|
2235
|
+
|
|
2236
|
+
if existing_entry is not None:
|
|
2237
|
+
existing_thread = existing_entry["thread"]
|
|
2238
|
+
|
|
2239
|
+
if existing_thread.is_alive() is True:
|
|
2240
|
+
errmsg = "Agent '{}' is already receiving from transport '{}'.".format(
|
|
2241
|
+
self._identity.identifier, transport_name
|
|
2242
|
+
)
|
|
2243
|
+
raise SemanticError(errmsg)
|
|
2244
|
+
|
|
2245
|
+
stop_event = threading.Event()
|
|
2246
|
+
thread_name = "AgentReceive-{}-{}".format(self._identity.identifier, transport_name)
|
|
2247
|
+
receive_thread = threading.Thread(
|
|
2248
|
+
target=self._receive_loop,
|
|
2249
|
+
kwargs={
|
|
2250
|
+
"transport_name": transport_name,
|
|
2251
|
+
"poll_interval": poll_interval,
|
|
2252
|
+
"stop_event": stop_event,
|
|
2253
|
+
},
|
|
2254
|
+
name=thread_name,
|
|
2255
|
+
daemon=True,
|
|
2256
|
+
)
|
|
2257
|
+
|
|
2258
|
+
self._receive_loops[transport_name] = {
|
|
2259
|
+
"thread": receive_thread,
|
|
2260
|
+
"stop_event": stop_event,
|
|
2261
|
+
}
|
|
2262
|
+
|
|
2263
|
+
receive_thread.start()
|
|
2264
|
+
|
|
2265
|
+
self._logger.info(
|
|
2266
|
+
"Receive loop started: agent='%s', transport='%s', poll_interval=%s",
|
|
2267
|
+
self._identity.identifier, transport_name, poll_interval,
|
|
2268
|
+
)
|
|
2269
|
+
return
|
|
2270
|
+
|
|
2271
|
+
def stop_receiving(self, transport_name: Optional[str] = None,
|
|
2272
|
+
timeout: float = DEFAULT_RECEIVE_STOP_TIMEOUT) -> None:
|
|
2273
|
+
"""
|
|
2274
|
+
Stops the receive loop of a transport, or of every transport when
|
|
2275
|
+
transport_name is None, and waits up to timeout seconds for each
|
|
2276
|
+
loop thread to end. Stopping a transport that has no receive loop
|
|
2277
|
+
does nothing.
|
|
2278
|
+
|
|
2279
|
+
A loop blocked inside a transport receive that waits for data,
|
|
2280
|
+
such as a WebSocket receive, ends when that receive returns; a
|
|
2281
|
+
WARNING is logged when it has not ended within the timeout.
|
|
2282
|
+
|
|
2283
|
+
:param transport_name: The transport whose receive loop to stop,
|
|
2284
|
+
or None for all receive loops.
|
|
2285
|
+
:param timeout: The number of seconds to wait for each loop thread
|
|
2286
|
+
to end.
|
|
2287
|
+
"""
|
|
2288
|
+
stopping_entries = []
|
|
2289
|
+
|
|
2290
|
+
with self._receive_loops_lock:
|
|
2291
|
+
if transport_name is None:
|
|
2292
|
+
loop_names = list(self._receive_loops.keys())
|
|
2293
|
+
elif transport_name in self._receive_loops:
|
|
2294
|
+
loop_names = [transport_name]
|
|
2295
|
+
else:
|
|
2296
|
+
loop_names = []
|
|
2297
|
+
|
|
2298
|
+
for loop_name in loop_names:
|
|
2299
|
+
entry = self._receive_loops.pop(loop_name)
|
|
2300
|
+
entry["stop_event"].set()
|
|
2301
|
+
stopping_entries.append((loop_name, entry["thread"]))
|
|
2302
|
+
|
|
2303
|
+
current_thread = threading.current_thread()
|
|
2304
|
+
|
|
2305
|
+
for loop_name, receive_thread in stopping_entries:
|
|
2306
|
+
if receive_thread is current_thread:
|
|
2307
|
+
# A handler running on the loop asked it to stop; the loop ends
|
|
2308
|
+
# when the handler returns.
|
|
2309
|
+
continue
|
|
2310
|
+
|
|
2311
|
+
receive_thread.join(timeout)
|
|
2312
|
+
|
|
2313
|
+
if receive_thread.is_alive() is True:
|
|
2314
|
+
self._logger.warning(
|
|
2315
|
+
"Receive loop did not stop within %s seconds: agent='%s', transport='%s'",
|
|
2316
|
+
timeout, self._identity.identifier, loop_name,
|
|
2317
|
+
)
|
|
2318
|
+
else:
|
|
2319
|
+
self._logger.info(
|
|
2320
|
+
"Receive loop stopped: agent='%s', transport='%s'",
|
|
2321
|
+
self._identity.identifier, loop_name,
|
|
2322
|
+
)
|
|
2323
|
+
|
|
2324
|
+
return
|
|
2325
|
+
|
|
2326
|
+
def is_receiving(self, transport_name: str) -> bool:
|
|
2327
|
+
"""
|
|
2328
|
+
Returns whether a receive loop is running for a transport.
|
|
2329
|
+
|
|
2330
|
+
:param transport_name: The transport name to check.
|
|
2331
|
+
|
|
2332
|
+
:returns: True if a receive loop thread for the transport is
|
|
2333
|
+
alive, False otherwise.
|
|
2334
|
+
"""
|
|
2335
|
+
with self._receive_loops_lock:
|
|
2336
|
+
entry = self._receive_loops.get(transport_name, None)
|
|
2337
|
+
|
|
2338
|
+
if entry is None:
|
|
2339
|
+
return False
|
|
2340
|
+
|
|
2341
|
+
receive_thread = entry["thread"]
|
|
2342
|
+
rtnval = receive_thread.is_alive()
|
|
2343
|
+
return rtnval
|
|
2344
|
+
|
|
2345
|
+
def _receive_loop(self, transport_name: str, poll_interval: float,
|
|
2346
|
+
stop_event: threading.Event) -> None:
|
|
2347
|
+
"""
|
|
2348
|
+
Body of a receive loop thread started by start_receiving.
|
|
2349
|
+
|
|
2350
|
+
Receives messages from the transport and dispatches them until
|
|
2351
|
+
stop_event is set. See start_receiving for how empty receives
|
|
2352
|
+
and failures are handled.
|
|
2353
|
+
|
|
2354
|
+
:param transport_name: The name of the transport to receive from.
|
|
2355
|
+
:param poll_interval: The number of seconds to wait after an empty
|
|
2356
|
+
or failed receive.
|
|
2357
|
+
:param stop_event: The event that ends the loop when set.
|
|
2358
|
+
"""
|
|
2359
|
+
consecutive_failures = 0
|
|
2360
|
+
|
|
2361
|
+
while stop_event.is_set() is not True:
|
|
2362
|
+
try:
|
|
2363
|
+
message = self._receive_from_transport(transport_name)
|
|
2364
|
+
except Exception as receive_err:
|
|
2365
|
+
consecutive_failures = consecutive_failures + 1
|
|
2366
|
+
|
|
2367
|
+
if consecutive_failures == 1:
|
|
2368
|
+
self._logger.warning(
|
|
2369
|
+
"Receive failed: agent='%s', transport='%s', error=[%s] %s. "
|
|
2370
|
+
"Retrying every %s seconds; repeated failures are logged at DEBUG.",
|
|
2371
|
+
self._identity.identifier, transport_name,
|
|
2372
|
+
type(receive_err).__name__, receive_err, poll_interval,
|
|
2373
|
+
)
|
|
2374
|
+
else:
|
|
2375
|
+
self._logger.debug(
|
|
2376
|
+
"Receive failed again: agent='%s', transport='%s', "
|
|
2377
|
+
"consecutive_failures=%d, error=[%s] %s",
|
|
2378
|
+
self._identity.identifier, transport_name, consecutive_failures,
|
|
2379
|
+
type(receive_err).__name__, receive_err,
|
|
2380
|
+
)
|
|
2381
|
+
|
|
2382
|
+
stop_event.wait(poll_interval)
|
|
2383
|
+
continue
|
|
2384
|
+
|
|
2385
|
+
consecutive_failures = 0
|
|
2386
|
+
|
|
2387
|
+
if message is None:
|
|
2388
|
+
stop_event.wait(poll_interval)
|
|
2389
|
+
continue
|
|
2390
|
+
|
|
2391
|
+
try:
|
|
2392
|
+
self.receive_message(message=message, transport_name=transport_name)
|
|
2393
|
+
except Exception as dispatch_err:
|
|
2394
|
+
self._logger.warning(
|
|
2395
|
+
"Received message could not be dispatched: agent='%s', transport='%s', "
|
|
2396
|
+
"message_id='%s', error=[%s] %s",
|
|
2397
|
+
self._identity.identifier, transport_name, message.identifier,
|
|
2398
|
+
type(dispatch_err).__name__, dispatch_err,
|
|
2399
|
+
)
|
|
2400
|
+
|
|
2401
|
+
return
|
|
2402
|
+
|
|
2403
|
+
def publish(self, topic: str, payload: object) -> None:
|
|
2404
|
+
"""
|
|
2405
|
+
Publishes an event message to a topic.
|
|
2406
|
+
|
|
2407
|
+
Constructs a sender AgentAddress from the agent's identity,
|
|
2408
|
+
constructs an EVENT Message with a None recipient, and
|
|
2409
|
+
delegates to the PubSubBroker for topic-based delivery.
|
|
2410
|
+
|
|
2411
|
+
:param topic: The topic string.
|
|
2412
|
+
:param payload: The event payload.
|
|
2413
|
+
"""
|
|
2414
|
+
sender_address = AgentAddress(
|
|
2415
|
+
agent_identifier=self._identity.identifier,
|
|
2416
|
+
transport_name="pubsub",
|
|
2417
|
+
)
|
|
2418
|
+
|
|
2419
|
+
recipient_address = AgentAddress(
|
|
2420
|
+
agent_identifier="",
|
|
2421
|
+
transport_name="pubsub",
|
|
2422
|
+
)
|
|
2423
|
+
|
|
2424
|
+
message = Message(
|
|
2425
|
+
sender=sender_address,
|
|
2426
|
+
recipient=recipient_address,
|
|
2427
|
+
payload=payload,
|
|
2428
|
+
pattern=MessagePattern.EVENT,
|
|
2429
|
+
)
|
|
2430
|
+
|
|
2431
|
+
self._pubsub_broker.publish(topic=topic, message=message)
|
|
2432
|
+
|
|
2433
|
+
return
|
|
2434
|
+
|
|
2435
|
+
def subscribe(self, topic: str, handler: callable) -> Subscription:
|
|
2436
|
+
"""
|
|
2437
|
+
Subscribes to a topic with a handler callback.
|
|
2438
|
+
|
|
2439
|
+
Delegates to the PubSubBroker subscribe method using the
|
|
2440
|
+
agent's identity identifier as the subscriber agent ID.
|
|
2441
|
+
|
|
2442
|
+
:param topic: The topic string.
|
|
2443
|
+
:param handler: The MessageHandler callback.
|
|
2444
|
+
|
|
2445
|
+
:returns: A Subscription object.
|
|
2446
|
+
"""
|
|
2447
|
+
subscription = self._pubsub_broker.subscribe(
|
|
2448
|
+
topic=topic,
|
|
2449
|
+
subscriber_agent_id=self._identity.identifier,
|
|
2450
|
+
handler=handler,
|
|
2451
|
+
)
|
|
2452
|
+
|
|
2453
|
+
return subscription
|
|
2454
|
+
|
|
2455
|
+
# -----------------------------------------------------------------------
|
|
2456
|
+
# LLM provider methods
|
|
2457
|
+
# -----------------------------------------------------------------------
|
|
2458
|
+
|
|
2459
|
+
def register_llm_provider(self, provider: LLMProvider) -> None:
|
|
2460
|
+
"""
|
|
2461
|
+
Registers an LLMProvider with this Agent's LLMProviderRegistry.
|
|
2462
|
+
|
|
2463
|
+
:param provider: The LLMProvider instance to register.
|
|
2464
|
+
"""
|
|
2465
|
+
self._llm_provider_registry.register(provider)
|
|
2466
|
+
return
|
|
2467
|
+
|
|
2468
|
+
def complete(self, provider_name: str, model_name: str,
|
|
2469
|
+
conversation: LLMConversation, retry_policy: RetryPolicy = None,
|
|
2470
|
+
fallback_chain: FallbackChain = None, **kwargs) -> LLMResponse:
|
|
2471
|
+
"""
|
|
2472
|
+
Looks up the LLMProvider and executes a completion request.
|
|
2473
|
+
|
|
2474
|
+
Looks up the provider in the Agent's LLMProviderRegistry using
|
|
2475
|
+
the provider name and model name. If found, executes the
|
|
2476
|
+
completion request and records token usage and cost in the
|
|
2477
|
+
Agent's CostTracker. If not found, raises a SemanticError.
|
|
2478
|
+
|
|
2479
|
+
When a RetryPolicy is configured and the completion fails, the
|
|
2480
|
+
request is retried according to the policy. When all retries are
|
|
2481
|
+
exhausted and a FallbackChain is configured, the next provider
|
|
2482
|
+
in the chain is attempted. If all providers fail, an
|
|
2483
|
+
LLMRequestError is raised with a summary of all attempted
|
|
2484
|
+
providers.
|
|
2485
|
+
|
|
2486
|
+
:param provider_name: The provider name.
|
|
2487
|
+
:param model_name: The model name.
|
|
2488
|
+
:param conversation: The conversation history.
|
|
2489
|
+
:param retry_policy: Optional RetryPolicy for retry behavior.
|
|
2490
|
+
:param fallback_chain: Optional FallbackChain for fallback behavior.
|
|
2491
|
+
|
|
2492
|
+
:returns: An LLMResponse.
|
|
2493
|
+
|
|
2494
|
+
:raises: SemanticError if provider not found.
|
|
2495
|
+
:raises: LLMRequestError on provider failure after retries and fallbacks.
|
|
2496
|
+
"""
|
|
2497
|
+
llm_logger = logging.getLogger("ccai.agentkit.llm")
|
|
2498
|
+
|
|
2499
|
+
provider = self._llm_provider_registry.lookup(provider_name, model_name)
|
|
2500
|
+
|
|
2501
|
+
if provider is None:
|
|
2502
|
+
err_msg_lines = [
|
|
2503
|
+
"LLM provider '{}' with model '{}' not found in agent '{}'.".format(
|
|
2504
|
+
provider_name, model_name, self._identity.identifier
|
|
2505
|
+
),
|
|
2506
|
+
]
|
|
2507
|
+
err_msg = os.linesep.join(err_msg_lines)
|
|
2508
|
+
raise SemanticError(err_msg)
|
|
2509
|
+
|
|
2510
|
+
failed_providers = []
|
|
2511
|
+
|
|
2512
|
+
current_provider_name = provider_name
|
|
2513
|
+
current_model_name = model_name
|
|
2514
|
+
current_provider = provider
|
|
2515
|
+
|
|
2516
|
+
while True:
|
|
2517
|
+
response = self._attempt_completion_with_retries(
|
|
2518
|
+
current_provider, current_provider_name, current_model_name,
|
|
2519
|
+
conversation, retry_policy, fallback_chain, llm_logger,
|
|
2520
|
+
failed_providers, **kwargs
|
|
2521
|
+
)
|
|
2522
|
+
|
|
2523
|
+
if response is not None:
|
|
2524
|
+
return response
|
|
2525
|
+
|
|
2526
|
+
if fallback_chain is None:
|
|
2527
|
+
break
|
|
2528
|
+
|
|
2529
|
+
next_pair = fallback_chain.next_provider(
|
|
2530
|
+
current_provider_name, current_model_name
|
|
2531
|
+
)
|
|
2532
|
+
|
|
2533
|
+
if next_pair is None:
|
|
2534
|
+
break
|
|
2535
|
+
|
|
2536
|
+
fallback_provider_name = next_pair[0]
|
|
2537
|
+
fallback_model_name = next_pair[1]
|
|
2538
|
+
|
|
2539
|
+
llm_logger.warning(
|
|
2540
|
+
"Falling back from provider '%s/%s' to '%s/%s'",
|
|
2541
|
+
current_provider_name, current_model_name,
|
|
2542
|
+
fallback_provider_name, fallback_model_name,
|
|
2543
|
+
)
|
|
2544
|
+
|
|
2545
|
+
fallback_provider = self._llm_provider_registry.lookup(
|
|
2546
|
+
fallback_provider_name, fallback_model_name
|
|
2547
|
+
)
|
|
2548
|
+
|
|
2549
|
+
if fallback_provider is None:
|
|
2550
|
+
failure_entry = {
|
|
2551
|
+
"provider_name": fallback_provider_name,
|
|
2552
|
+
"model_name": fallback_model_name,
|
|
2553
|
+
"error": "Provider not found in registry",
|
|
2554
|
+
}
|
|
2555
|
+
failed_providers.append(failure_entry)
|
|
2556
|
+
current_provider_name = fallback_provider_name
|
|
2557
|
+
current_model_name = fallback_model_name
|
|
2558
|
+
continue
|
|
2559
|
+
|
|
2560
|
+
current_provider_name = fallback_provider_name
|
|
2561
|
+
current_model_name = fallback_model_name
|
|
2562
|
+
current_provider = fallback_provider
|
|
2563
|
+
|
|
2564
|
+
err_msg_lines = [
|
|
2565
|
+
"All LLM providers failed for agent '{}'.".format(
|
|
2566
|
+
self._identity.identifier
|
|
2567
|
+
),
|
|
2568
|
+
]
|
|
2569
|
+
|
|
2570
|
+
for entry in failed_providers:
|
|
2571
|
+
err_msg_lines.append(
|
|
2572
|
+
" Provider '{}' model '{}': {}".format(
|
|
2573
|
+
entry["provider_name"], entry["model_name"], entry["error"]
|
|
2574
|
+
)
|
|
2575
|
+
)
|
|
2576
|
+
|
|
2577
|
+
err_msg = os.linesep.join(err_msg_lines)
|
|
2578
|
+
|
|
2579
|
+
raise LLMRequestError(
|
|
2580
|
+
provider_name=provider_name,
|
|
2581
|
+
model_name=model_name,
|
|
2582
|
+
category="server_error",
|
|
2583
|
+
cause=Exception(err_msg),
|
|
2584
|
+
)
|
|
2585
|
+
|
|
2586
|
+
def _attempt_completion_with_retries(
|
|
2587
|
+
self, provider: LLMProvider, provider_name: str, model_name: str,
|
|
2588
|
+
conversation: LLMConversation, retry_policy: RetryPolicy,
|
|
2589
|
+
fallback_chain: FallbackChain,
|
|
2590
|
+
llm_logger: logging.Logger, failed_providers: list, **kwargs
|
|
2591
|
+
) -> Optional[LLMResponse]:
|
|
2592
|
+
"""
|
|
2593
|
+
Attempts a completion request with optional retry logic.
|
|
2594
|
+
|
|
2595
|
+
If the completion succeeds, records cost and returns the
|
|
2596
|
+
LLMResponse. If it fails and a retry policy is configured,
|
|
2597
|
+
retries according to the policy. If all attempts fail and
|
|
2598
|
+
a fallback chain or retry policy is configured, appends the
|
|
2599
|
+
failure to the failed_providers list and returns None.
|
|
2600
|
+
If neither retry_policy nor fallback_chain is configured,
|
|
2601
|
+
the exception is re-raised directly.
|
|
2602
|
+
|
|
2603
|
+
:param provider: The LLMProvider instance.
|
|
2604
|
+
:param provider_name: The provider name.
|
|
2605
|
+
:param model_name: The model name.
|
|
2606
|
+
:param conversation: The conversation history.
|
|
2607
|
+
:param retry_policy: Optional RetryPolicy for retry behavior.
|
|
2608
|
+
:param fallback_chain: Optional FallbackChain for fallback behavior.
|
|
2609
|
+
:param llm_logger: The logger for LLM operations.
|
|
2610
|
+
:param failed_providers: List to append failure entries to.
|
|
2611
|
+
|
|
2612
|
+
:returns: An LLMResponse on success, or None on failure.
|
|
2613
|
+
"""
|
|
2614
|
+
attempt = 0
|
|
2615
|
+
last_exception = None
|
|
2616
|
+
|
|
2617
|
+
while True:
|
|
2618
|
+
try:
|
|
2619
|
+
llm_logger.info(
|
|
2620
|
+
"Completion request begin: provider '%s', model '%s', agent '%s'",
|
|
2621
|
+
provider_name, model_name, self._identity.identifier,
|
|
2622
|
+
)
|
|
2623
|
+
|
|
2624
|
+
response = provider.complete(conversation, **kwargs)
|
|
2625
|
+
|
|
2626
|
+
token_usage = response.token_usage
|
|
2627
|
+
cost_estimate = getattr(response, "cost_estimate", None)
|
|
2628
|
+
|
|
2629
|
+
if cost_estimate is not None:
|
|
2630
|
+
self._cost_tracker.record(provider_name, token_usage, cost_estimate)
|
|
2631
|
+
|
|
2632
|
+
llm_logger.info(
|
|
2633
|
+
"Completion request success: provider '%s', model '%s', "
|
|
2634
|
+
"tokens=%d, duration=%.2fs",
|
|
2635
|
+
provider_name, model_name,
|
|
2636
|
+
token_usage.total_tokens, response.duration,
|
|
2637
|
+
)
|
|
2638
|
+
|
|
2639
|
+
return response
|
|
2640
|
+
|
|
2641
|
+
except Exception as exc:
|
|
2642
|
+
last_exception = exc
|
|
2643
|
+
|
|
2644
|
+
llm_logger.warning(
|
|
2645
|
+
"Completion request failure: provider '%s', model '%s', "
|
|
2646
|
+
"error_type='%s', detail='%s'",
|
|
2647
|
+
provider_name, model_name,
|
|
2648
|
+
type(exc).__name__, str(exc),
|
|
2649
|
+
)
|
|
2650
|
+
|
|
2651
|
+
if retry_policy is not None:
|
|
2652
|
+
should_retry = retry_policy.should_retry(exc, attempt)
|
|
2653
|
+
|
|
2654
|
+
if should_retry is True:
|
|
2655
|
+
delay = retry_policy.get_delay(attempt)
|
|
2656
|
+
|
|
2657
|
+
llm_logger.info(
|
|
2658
|
+
"Retrying provider '%s/%s', attempt %d, delay %.2fs",
|
|
2659
|
+
provider_name, model_name, attempt + 1, delay,
|
|
2660
|
+
)
|
|
2661
|
+
|
|
2662
|
+
time.sleep(delay)
|
|
2663
|
+
attempt = attempt + 1
|
|
2664
|
+
continue
|
|
2665
|
+
|
|
2666
|
+
failure_entry = {
|
|
2667
|
+
"provider_name": provider_name,
|
|
2668
|
+
"model_name": model_name,
|
|
2669
|
+
"error": str(last_exception),
|
|
2670
|
+
}
|
|
2671
|
+
failed_providers.append(failure_entry)
|
|
2672
|
+
|
|
2673
|
+
return None
|
|
2674
|
+
|
|
2675
|
+
if fallback_chain is not None:
|
|
2676
|
+
failure_entry = {
|
|
2677
|
+
"provider_name": provider_name,
|
|
2678
|
+
"model_name": model_name,
|
|
2679
|
+
"error": str(last_exception),
|
|
2680
|
+
}
|
|
2681
|
+
failed_providers.append(failure_entry)
|
|
2682
|
+
|
|
2683
|
+
return None
|
|
2684
|
+
|
|
2685
|
+
raise
|
|
2686
|
+
|
|
2687
|
+
def execute_resilient(self, callable_op, operation_name: str = None,
|
|
2688
|
+
retry_policy=None, circuit_breaker_name: str = None):
|
|
2689
|
+
"""
|
|
2690
|
+
Executes the callable with resilience protection, delegating to
|
|
2691
|
+
the ResiliencePipeline execute_with_resilience method.
|
|
2692
|
+
|
|
2693
|
+
:param callable_op: The callable to execute.
|
|
2694
|
+
:param operation_name: Optional name for the operation.
|
|
2695
|
+
:param retry_policy: Optional RetryPolicy override.
|
|
2696
|
+
:param circuit_breaker_name: Optional circuit breaker name.
|
|
2697
|
+
|
|
2698
|
+
:returns: The operation result.
|
|
2699
|
+
:raises SemanticError: If resilience is not initialized.
|
|
2700
|
+
"""
|
|
2701
|
+
if self._resilience_pipeline is None:
|
|
2702
|
+
raise SemanticError("Resilience pipeline is not initialized")
|
|
2703
|
+
|
|
2704
|
+
result = self._resilience_pipeline.execute_with_resilience(
|
|
2705
|
+
callable_op,
|
|
2706
|
+
operation_name=operation_name,
|
|
2707
|
+
retry_policy=retry_policy,
|
|
2708
|
+
circuit_breaker_name=circuit_breaker_name
|
|
2709
|
+
)
|
|
2710
|
+
return result
|
|
2711
|
+
|
|
2712
|
+
# -----------------------------------------------------------------------
|
|
2713
|
+
# Hook registration and invocation
|
|
2714
|
+
# -----------------------------------------------------------------------
|
|
2715
|
+
|
|
2716
|
+
def register_hook(self, transition_point: str, callback: Callable) -> None:
|
|
2717
|
+
"""
|
|
2718
|
+
Registers a lifecycle hook callback for a transition point.
|
|
2719
|
+
|
|
2720
|
+
:param transition_point: One of on_initialize, on_start, on_pause,
|
|
2721
|
+
on_resume, on_stop, on_error.
|
|
2722
|
+
:param callback: A callable that accepts (agent, record) arguments.
|
|
2723
|
+
|
|
2724
|
+
:raises: SemanticError
|
|
2725
|
+
"""
|
|
2726
|
+
is_valid_point = transition_point in self._hooks
|
|
2727
|
+
|
|
2728
|
+
if is_valid_point is not True:
|
|
2729
|
+
err_msg_lines = [
|
|
2730
|
+
"Invalid transition point for hook registration."
|
|
2731
|
+
]
|
|
2732
|
+
err_msg_lines.append(" Transition point: {!r}".format(transition_point))
|
|
2733
|
+
err_msg_lines.append(" Valid transition points: {}".format(VALID_TRANSITION_POINTS))
|
|
2734
|
+
err_msg = os.linesep.join(err_msg_lines)
|
|
2735
|
+
raise SemanticError(err_msg)
|
|
2736
|
+
|
|
2737
|
+
self._hooks[transition_point].append(callback)
|
|
2738
|
+
|
|
2739
|
+
return
|
|
2740
|
+
|
|
2741
|
+
def deregister_hook(self, transition_point: str, callback: Callable) -> None:
|
|
2742
|
+
"""
|
|
2743
|
+
Deregisters a previously registered lifecycle hook callback.
|
|
2744
|
+
|
|
2745
|
+
:param transition_point: The transition point the hook was registered for.
|
|
2746
|
+
:param callback: The callback to remove.
|
|
2747
|
+
|
|
2748
|
+
:raises: SemanticError
|
|
2749
|
+
"""
|
|
2750
|
+
is_valid_point = transition_point in self._hooks
|
|
2751
|
+
|
|
2752
|
+
if is_valid_point is not True:
|
|
2753
|
+
err_msg_lines = [
|
|
2754
|
+
"Invalid transition point for hook deregistration."
|
|
2755
|
+
]
|
|
2756
|
+
err_msg_lines.append(" Transition point: {!r}".format(transition_point))
|
|
2757
|
+
err_msg_lines.append(" Valid transition points: {}".format(VALID_TRANSITION_POINTS))
|
|
2758
|
+
err_msg = os.linesep.join(err_msg_lines)
|
|
2759
|
+
raise SemanticError(err_msg)
|
|
2760
|
+
|
|
2761
|
+
hook_list = self._hooks[transition_point]
|
|
2762
|
+
is_present = callback in hook_list
|
|
2763
|
+
|
|
2764
|
+
if is_present is True:
|
|
2765
|
+
hook_list.remove(callback)
|
|
2766
|
+
|
|
2767
|
+
return
|
|
2768
|
+
|
|
2769
|
+
def _invoke_hooks(self, transition_point: str, record: TransitionRecord) -> None:
|
|
2770
|
+
"""
|
|
2771
|
+
Invokes all registered hooks for a transition point in registration order.
|
|
2772
|
+
|
|
2773
|
+
If a hook raises an exception, the exception is logged at WARNING level
|
|
2774
|
+
and invocation continues with the remaining hooks.
|
|
2775
|
+
|
|
2776
|
+
:param transition_point: The transition point to invoke hooks for.
|
|
2777
|
+
:param record: The TransitionRecord to pass to each hook.
|
|
2778
|
+
"""
|
|
2779
|
+
hook_list = list(self._hooks.get(transition_point, []))
|
|
2780
|
+
|
|
2781
|
+
for callback in hook_list:
|
|
2782
|
+
try:
|
|
2783
|
+
callback(self, record)
|
|
2784
|
+
except Exception as exc:
|
|
2785
|
+
self._logger.warning(
|
|
2786
|
+
"Hook exception in agent %s at transition point %s: %s",
|
|
2787
|
+
self._identity.identifier,
|
|
2788
|
+
transition_point,
|
|
2789
|
+
str(exc)
|
|
2790
|
+
)
|
|
2791
|
+
|
|
2792
|
+
return
|
|
2793
|
+
|
|
2794
|
+
# -----------------------------------------------------------------------
|
|
2795
|
+
# Lifecycle transition helper
|
|
2796
|
+
# -----------------------------------------------------------------------
|
|
2797
|
+
|
|
2798
|
+
def _perform_transition(self, target_state: LifecycleState, transition_point: str,
|
|
2799
|
+
metadata: Optional[dict] = None) -> TransitionRecord:
|
|
2800
|
+
"""
|
|
2801
|
+
Performs a lifecycle state transition, logs it, and invokes hooks.
|
|
2802
|
+
|
|
2803
|
+
If the target state is ERROR and this agent has a parent, the parent
|
|
2804
|
+
on_error hooks are invoked with the child identity in metadata.
|
|
2805
|
+
|
|
2806
|
+
:param target_state: The target LifecycleState.
|
|
2807
|
+
:param transition_point: The hook transition point to invoke.
|
|
2808
|
+
:param metadata: Optional metadata for the transition.
|
|
2809
|
+
|
|
2810
|
+
:returns: The TransitionRecord for the transition.
|
|
2811
|
+
"""
|
|
2812
|
+
record = self._state_machine.transition_to(target_state, metadata=metadata)
|
|
2813
|
+
|
|
2814
|
+
self._logger.info(
|
|
2815
|
+
"Agent %s transitioned from %s to %s",
|
|
2816
|
+
self._identity.identifier,
|
|
2817
|
+
record.previous_state.value,
|
|
2818
|
+
record.new_state.value
|
|
2819
|
+
)
|
|
2820
|
+
|
|
2821
|
+
self._invoke_hooks(transition_point, record)
|
|
2822
|
+
|
|
2823
|
+
if target_state is LifecycleState.ERROR and self._parent is not None:
|
|
2824
|
+
error_metadata = {
|
|
2825
|
+
"child_identifier": self._identity.identifier,
|
|
2826
|
+
"child_name": self._identity.name,
|
|
2827
|
+
}
|
|
2828
|
+
parent_record = TransitionRecord(
|
|
2829
|
+
previous_state=record.previous_state,
|
|
2830
|
+
new_state=record.new_state,
|
|
2831
|
+
timestamp=record.timestamp,
|
|
2832
|
+
metadata=error_metadata
|
|
2833
|
+
)
|
|
2834
|
+
self._parent._invoke_hooks("on_error", parent_record)
|
|
2835
|
+
|
|
2836
|
+
return record
|
|
2837
|
+
|
|
2838
|
+
# -----------------------------------------------------------------------
|
|
2839
|
+
# Sub-agent management
|
|
2840
|
+
# -----------------------------------------------------------------------
|
|
2841
|
+
|
|
2842
|
+
def add_sub_agent(self, agent: "Agent") -> None:
|
|
2843
|
+
"""
|
|
2844
|
+
Adds a child agent as a sub-agent of this agent.
|
|
2845
|
+
|
|
2846
|
+
Performs cycle detection by walking up the ancestor chain.
|
|
2847
|
+
Sets the parent reference on the child agent.
|
|
2848
|
+
|
|
2849
|
+
:param agent: The agent to add as a sub-agent.
|
|
2850
|
+
|
|
2851
|
+
:raises: SemanticError
|
|
2852
|
+
"""
|
|
2853
|
+
if agent is self:
|
|
2854
|
+
err_msg_lines = [
|
|
2855
|
+
"Cannot add an agent as a sub-agent of itself."
|
|
2856
|
+
]
|
|
2857
|
+
err_msg_lines.append(" Agent identifier: {!r}".format(self._identity.identifier))
|
|
2858
|
+
err_msg = os.linesep.join(err_msg_lines)
|
|
2859
|
+
raise SemanticError(err_msg)
|
|
2860
|
+
|
|
2861
|
+
current = self
|
|
2862
|
+
while current is not None:
|
|
2863
|
+
if current is agent:
|
|
2864
|
+
err_msg_lines = [
|
|
2865
|
+
"Circular parent-child relationship detected."
|
|
2866
|
+
]
|
|
2867
|
+
err_msg_lines.append(" Agent causing cycle: {!r}".format(agent.identity.identifier))
|
|
2868
|
+
err_msg_lines.append(" Attempted parent: {!r}".format(self._identity.identifier))
|
|
2869
|
+
err_msg = os.linesep.join(err_msg_lines)
|
|
2870
|
+
raise SemanticError(err_msg)
|
|
2871
|
+
current = current._parent
|
|
2872
|
+
|
|
2873
|
+
agent._parent = self
|
|
2874
|
+
self._sub_agents.append(agent)
|
|
2875
|
+
|
|
2876
|
+
return
|
|
2877
|
+
|
|
2878
|
+
def remove_sub_agent(self, identifier: str) -> None:
|
|
2879
|
+
"""
|
|
2880
|
+
Removes a sub-agent by its unique identifier.
|
|
2881
|
+
|
|
2882
|
+
Clears the parent reference on the removed child agent.
|
|
2883
|
+
|
|
2884
|
+
:param identifier: The unique identifier of the sub-agent to remove.
|
|
2885
|
+
"""
|
|
2886
|
+
agent_to_remove = None
|
|
2887
|
+
|
|
2888
|
+
for sub_agent in self._sub_agents:
|
|
2889
|
+
if sub_agent.identity.identifier == identifier:
|
|
2890
|
+
agent_to_remove = sub_agent
|
|
2891
|
+
break
|
|
2892
|
+
|
|
2893
|
+
if agent_to_remove is not None:
|
|
2894
|
+
agent_to_remove._parent = None
|
|
2895
|
+
self._sub_agents.remove(agent_to_remove)
|
|
2896
|
+
|
|
2897
|
+
return
|
|
2898
|
+
|
|
2899
|
+
# -----------------------------------------------------------------------
|
|
2900
|
+
# Logging
|
|
2901
|
+
# -----------------------------------------------------------------------
|
|
2902
|
+
|
|
2903
|
+
def get_logger(self) -> logging.Logger:
|
|
2904
|
+
"""
|
|
2905
|
+
Returns a logger scoped to this agent's identity.
|
|
2906
|
+
|
|
2907
|
+
The logger name follows the pattern:
|
|
2908
|
+
ccai.agentkit.agent.<agent_identifier>
|
|
2909
|
+
|
|
2910
|
+
:returns: A logging.Logger instance.
|
|
2911
|
+
"""
|
|
2912
|
+
return self._logger
|
|
2913
|
+
|
|
2914
|
+
# -----------------------------------------------------------------------
|
|
2915
|
+
# String representations
|
|
2916
|
+
# -----------------------------------------------------------------------
|
|
2917
|
+
|
|
2918
|
+
def __repr__(self) -> str:
|
|
2919
|
+
"""
|
|
2920
|
+
Returns a detailed string representation including class name,
|
|
2921
|
+
agent identifier, agent name, and current lifecycle state.
|
|
2922
|
+
|
|
2923
|
+
:returns: A repr string for debugging.
|
|
2924
|
+
"""
|
|
2925
|
+
repr_str = "{}(identifier={!r}, name={!r}, state={!r})".format(
|
|
2926
|
+
self.__class__.__name__,
|
|
2927
|
+
self._identity.identifier,
|
|
2928
|
+
self._identity.name,
|
|
2929
|
+
self._state_machine.current_state
|
|
2930
|
+
)
|
|
2931
|
+
return repr_str
|
|
2932
|
+
|
|
2933
|
+
def __str__(self) -> str:
|
|
2934
|
+
"""
|
|
2935
|
+
Returns a human-readable summary including the agent name
|
|
2936
|
+
and current lifecycle state.
|
|
2937
|
+
|
|
2938
|
+
:returns: A human-readable string.
|
|
2939
|
+
"""
|
|
2940
|
+
str_val = "{}: {} [{}]".format(
|
|
2941
|
+
self.__class__.__name__,
|
|
2942
|
+
self._identity.name,
|
|
2943
|
+
self._state_machine.current_state.value
|
|
2944
|
+
)
|
|
2945
|
+
return str_val
|