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.
Files changed (230) hide show
  1. ccai/agentkit/__init__.py +304 -0
  2. ccai/agentkit/addressresolver.py +177 -0
  3. ccai/agentkit/agent.py +2945 -0
  4. ccai/agentkit/agentaddress.py +187 -0
  5. ccai/agentkit/agentconfiguration.py +581 -0
  6. ccai/agentkit/agentidentity.py +152 -0
  7. ccai/agentkit/agentregistry.py +221 -0
  8. ccai/agentkit/agentstatemachine.py +134 -0
  9. ccai/agentkit/alternateproviderstrategy.py +36 -0
  10. ccai/agentkit/approvalgate.py +238 -0
  11. ccai/agentkit/approvalrequest.py +250 -0
  12. ccai/agentkit/asyncagent.py +187 -0
  13. ccai/agentkit/breakpoint.py +150 -0
  14. ccai/agentkit/builtinagentmetrics.py +114 -0
  15. ccai/agentkit/builtins/__init__.py +11 -0
  16. ccai/agentkit/builtins/filereadtool.py +90 -0
  17. ccai/agentkit/builtins/filewritetool.py +93 -0
  18. ccai/agentkit/builtins/httprequesttool.py +169 -0
  19. ccai/agentkit/builtins/shellcommandtool.py +190 -0
  20. ccai/agentkit/cachedresultstrategy.py +43 -0
  21. ccai/agentkit/checkpointmanager.py +219 -0
  22. ccai/agentkit/circuitbreaker.py +230 -0
  23. ccai/agentkit/circuitbreakerconfiguration.py +158 -0
  24. ccai/agentkit/circuitbreakerevent.py +158 -0
  25. ccai/agentkit/circuitbreakerhealthcheck.py +32 -0
  26. ccai/agentkit/circuitbreakerregistry.py +116 -0
  27. ccai/agentkit/circuitbreakerstate.py +44 -0
  28. ccai/agentkit/clearcacheaction.py +46 -0
  29. ccai/agentkit/concurrencybridge.py +143 -0
  30. ccai/agentkit/concurrencymodel.py +19 -0
  31. ccai/agentkit/conditionevaluator.py +594 -0
  32. ccai/agentkit/configurationchangeevent.py +179 -0
  33. ccai/agentkit/configurationerrors.py +152 -0
  34. ccai/agentkit/configurationlayer.py +160 -0
  35. ccai/agentkit/configurationlayersource.py +46 -0
  36. ccai/agentkit/configurationmanager.py +680 -0
  37. ccai/agentkit/configurationschema.py +224 -0
  38. ccai/agentkit/configurationschemafield.py +217 -0
  39. ccai/agentkit/configurationserializer.py +163 -0
  40. ccai/agentkit/configurationvalidationresult.py +118 -0
  41. ccai/agentkit/contextsummarizer.py +170 -0
  42. ccai/agentkit/contextwindow.py +264 -0
  43. ccai/agentkit/contextwindowstrategy.py +57 -0
  44. ccai/agentkit/correlationcontext.py +156 -0
  45. ccai/agentkit/costestimate.py +139 -0
  46. ccai/agentkit/costtracker.py +121 -0
  47. ccai/agentkit/deadletterentry.py +134 -0
  48. ccai/agentkit/deadletterquery.py +119 -0
  49. ccai/agentkit/deadletterqueue.py +123 -0
  50. ccai/agentkit/deadletterstore.py +86 -0
  51. ccai/agentkit/debuginspector.py +211 -0
  52. ccai/agentkit/debugsession.py +223 -0
  53. ccai/agentkit/defaultvaluestrategy.py +43 -0
  54. ccai/agentkit/degradationchangeevent.py +120 -0
  55. ccai/agentkit/degradationlevel.py +44 -0
  56. ccai/agentkit/degradationmanager.py +212 -0
  57. ccai/agentkit/degradationpolicy.py +130 -0
  58. ccai/agentkit/degradationstrategy.py +66 -0
  59. ccai/agentkit/embeddingprovider.py +106 -0
  60. ccai/agentkit/errors.py +95 -0
  61. ccai/agentkit/executionrecord.py +213 -0
  62. ccai/agentkit/executionrecorder.py +180 -0
  63. ccai/agentkit/executionrecording.py +230 -0
  64. ccai/agentkit/executionreplayer.py +187 -0
  65. ccai/agentkit/expirationpolicy.py +116 -0
  66. ccai/agentkit/fallbackchain.py +82 -0
  67. ccai/agentkit/featureflag.py +154 -0
  68. ccai/agentkit/featureflagevaluator.py +109 -0
  69. ccai/agentkit/featureflagregistry.py +258 -0
  70. ccai/agentkit/filedeadletterstore.py +112 -0
  71. ccai/agentkit/filememorystore.py +291 -0
  72. ccai/agentkit/healthcheck.py +46 -0
  73. ccai/agentkit/healthcheckregistry.py +51 -0
  74. ccai/agentkit/healthmonitor.py +258 -0
  75. ccai/agentkit/healthstatus.py +105 -0
  76. ccai/agentkit/hotreloadmonitor.py +214 -0
  77. ccai/agentkit/hotreloadpolicy.py +160 -0
  78. ccai/agentkit/inmemorydeadletterstore.py +61 -0
  79. ccai/agentkit/inmemorystore.py +173 -0
  80. ccai/agentkit/jsonmessageserializer.py +89 -0
  81. ccai/agentkit/jsonoutputparser.py +50 -0
  82. ccai/agentkit/lifecyclestate.py +22 -0
  83. ccai/agentkit/llmconversation.py +153 -0
  84. ccai/agentkit/llmerrors.py +193 -0
  85. ccai/agentkit/llmmessage.py +158 -0
  86. ccai/agentkit/llmprovider.py +158 -0
  87. ccai/agentkit/llmproviderregistry.py +200 -0
  88. ccai/agentkit/llmresponse.py +190 -0
  89. ccai/agentkit/llmstreamchunk.py +65 -0
  90. ccai/agentkit/llmstreamhandler.py +48 -0
  91. ccai/agentkit/llmtoolbridge.py +154 -0
  92. ccai/agentkit/logexporter.py +316 -0
  93. ccai/agentkit/logformatter.py +169 -0
  94. ccai/agentkit/memoryconfiguration.py +243 -0
  95. ccai/agentkit/memoryentry.py +254 -0
  96. ccai/agentkit/memoryerrors.py +135 -0
  97. ccai/agentkit/memoryindex.py +213 -0
  98. ccai/agentkit/memoryquery.py +248 -0
  99. ccai/agentkit/memoryqueryresult.py +86 -0
  100. ccai/agentkit/memoryscope.py +54 -0
  101. ccai/agentkit/memorystore.py +260 -0
  102. ccai/agentkit/memorystorehealthcheck.py +33 -0
  103. ccai/agentkit/memorystoreregistry.py +106 -0
  104. ccai/agentkit/message.py +310 -0
  105. ccai/agentkit/messageenvelope.py +144 -0
  106. ccai/agentkit/messagepattern.py +50 -0
  107. ccai/agentkit/messagerouter.py +290 -0
  108. ccai/agentkit/messageserializer.py +106 -0
  109. ccai/agentkit/messageserializerregistry.py +163 -0
  110. ccai/agentkit/messagingconfiguration.py +397 -0
  111. ccai/agentkit/messagingerrors.py +338 -0
  112. ccai/agentkit/metricdefinition.py +164 -0
  113. ccai/agentkit/metricmeasurement.py +178 -0
  114. ccai/agentkit/metricscollector.py +258 -0
  115. ccai/agentkit/metricsexporter.py +303 -0
  116. ccai/agentkit/metricsregistry.py +130 -0
  117. ccai/agentkit/metricssnapshot.py +155 -0
  118. ccai/agentkit/metrictype.py +51 -0
  119. ccai/agentkit/msgpackmessageserializer.py +97 -0
  120. ccai/agentkit/observabilityconfiguration.py +546 -0
  121. ccai/agentkit/observabilityerror.py +67 -0
  122. ccai/agentkit/observabilitypipeline.py +252 -0
  123. ccai/agentkit/outputparser.py +82 -0
  124. ccai/agentkit/outputschema.py +142 -0
  125. ccai/agentkit/parallelbranch.py +87 -0
  126. ccai/agentkit/platform/__init__.py +43 -0
  127. ccai/agentkit/platform/adapters/__init__.py +18 -0
  128. ccai/agentkit/platform/adapters/awsplatformadapter.py +1272 -0
  129. ccai/agentkit/platform/adapters/azureplatformadapter.py +1227 -0
  130. ccai/agentkit/platform/adapters/gcpplatformadapter.py +1257 -0
  131. ccai/agentkit/platform/adapters/localplatformadapter.py +956 -0
  132. ccai/agentkit/platform/adapters/platformadapter.py +139 -0
  133. ccai/agentkit/platform/deployment/__init__.py +15 -0
  134. ccai/agentkit/platform/deployment/deploymentdescriptor.py +234 -0
  135. ccai/agentkit/platform/deployment/deploymentdescriptorparser.py +178 -0
  136. ccai/agentkit/platform/deployment/deploymentdescriptorprinter.py +97 -0
  137. ccai/agentkit/platform/errors.py +224 -0
  138. ccai/agentkit/platform/platformconfiguration.py +412 -0
  139. ccai/agentkit/platform/platformdetector.py +125 -0
  140. ccai/agentkit/platform/platformruntime.py +331 -0
  141. ccai/agentkit/platform/platformserviceregistry.py +149 -0
  142. ccai/agentkit/platform/platformtype.py +60 -0
  143. ccai/agentkit/platform/services/__init__.py +19 -0
  144. ccai/agentkit/platform/services/computeservice.py +112 -0
  145. ccai/agentkit/platform/services/invocationresult.py +173 -0
  146. ccai/agentkit/platform/services/messagingservice.py +135 -0
  147. ccai/agentkit/platform/services/platformservice.py +111 -0
  148. ccai/agentkit/platform/services/queuemessage.py +193 -0
  149. ccai/agentkit/platform/services/storageobject.py +195 -0
  150. ccai/agentkit/platform/services/storageservice.py +159 -0
  151. ccai/agentkit/pluginconfiguration.py +241 -0
  152. ccai/agentkit/plugindependency.py +129 -0
  153. ccai/agentkit/plugindescriptor.py +225 -0
  154. ccai/agentkit/pluginlifecyclehook.py +41 -0
  155. ccai/agentkit/pluginmanager.py +360 -0
  156. ccai/agentkit/pluginstatus.py +47 -0
  157. ccai/agentkit/pooledagent.py +116 -0
  158. ccai/agentkit/prompttemplate.py +221 -0
  159. ccai/agentkit/prompttemplateregistry.py +145 -0
  160. ccai/agentkit/protobufmessageserializer.py +144 -0
  161. ccai/agentkit/pubsubbroker.py +311 -0
  162. ccai/agentkit/py.typed +0 -0
  163. ccai/agentkit/reconnecttransportaction.py +47 -0
  164. ccai/agentkit/regexoutputparser.py +68 -0
  165. ccai/agentkit/requestresponsehandler.py +274 -0
  166. ccai/agentkit/resetcircuitbreakeraction.py +48 -0
  167. ccai/agentkit/resilienceconfiguration.py +191 -0
  168. ccai/agentkit/resilienceerrors.py +103 -0
  169. ccai/agentkit/resiliencepipeline.py +201 -0
  170. ccai/agentkit/retryattempt.py +158 -0
  171. ccai/agentkit/retryexecutor.py +157 -0
  172. ccai/agentkit/retrypolicy.py +195 -0
  173. ccai/agentkit/retryresult.py +186 -0
  174. ccai/agentkit/selfhealingaction.py +42 -0
  175. ccai/agentkit/selfhealingpolicy.py +67 -0
  176. ccai/agentkit/selfhealingresult.py +130 -0
  177. ccai/agentkit/stepexecutionstatus.py +52 -0
  178. ccai/agentkit/stepresult.py +198 -0
  179. ccai/agentkit/steps/__init__.py +9 -0
  180. ccai/agentkit/steps/agentstep.py +247 -0
  181. ccai/agentkit/steps/approvalstep.py +276 -0
  182. ccai/agentkit/steps/llmstep.py +403 -0
  183. ccai/agentkit/steps/subworkflowstep.py +270 -0
  184. ccai/agentkit/steps/toolstep.py +265 -0
  185. ccai/agentkit/structuredlogentry.py +222 -0
  186. ccai/agentkit/structuredlogger.py +189 -0
  187. ccai/agentkit/subscription.py +141 -0
  188. ccai/agentkit/threadedagent.py +94 -0
  189. ccai/agentkit/tokenusage.py +136 -0
  190. ccai/agentkit/tool.py +203 -0
  191. ccai/agentkit/toolchain.py +268 -0
  192. ccai/agentkit/toolchainexecutor.py +134 -0
  193. ccai/agentkit/toolchainresult.py +166 -0
  194. ccai/agentkit/tooldescriptor.py +203 -0
  195. ccai/agentkit/toolerrors.py +160 -0
  196. ccai/agentkit/toolexecutor.py +168 -0
  197. ccai/agentkit/toolfactory.py +60 -0
  198. ccai/agentkit/toolregistry.py +184 -0
  199. ccai/agentkit/toolresult.py +142 -0
  200. ccai/agentkit/toolschema.py +197 -0
  201. ccai/agentkit/tracecontext.py +294 -0
  202. ccai/agentkit/traceevent.py +166 -0
  203. ccai/agentkit/traceexporter.py +305 -0
  204. ccai/agentkit/tracer.py +234 -0
  205. ccai/agentkit/tracespan.py +349 -0
  206. ccai/agentkit/transitionrecord.py +84 -0
  207. ccai/agentkit/transport.py +334 -0
  208. ccai/agentkit/transportconfiguration.py +436 -0
  209. ccai/agentkit/transporthealthcheck.py +36 -0
  210. ccai/agentkit/transportregistry.py +224 -0
  211. ccai/agentkit/transports/__init__.py +28 -0
  212. ccai/agentkit/transports/grpctransport.py +410 -0
  213. ccai/agentkit/transports/httptransport.py +423 -0
  214. ccai/agentkit/transports/messagequeuetransport.py +489 -0
  215. ccai/agentkit/transports/websockettransport.py +473 -0
  216. ccai/agentkit/workflowcheckpoint.py +208 -0
  217. ccai/agentkit/workflowconfiguration.py +295 -0
  218. ccai/agentkit/workflowcontext.py +249 -0
  219. ccai/agentkit/workflowdefinition.py +790 -0
  220. ccai/agentkit/workflowedge.py +128 -0
  221. ccai/agentkit/workflowerrors.py +295 -0
  222. ccai/agentkit/workflowexecutionstatus.py +48 -0
  223. ccai/agentkit/workflowexecutor.py +1121 -0
  224. ccai/agentkit/workflowregistry.py +185 -0
  225. ccai/agentkit/workflowresult.py +250 -0
  226. ccai/agentkit/workflowstep.py +195 -0
  227. codecraftai_agent_kit-1.3.0.dist-info/METADATA +99 -0
  228. codecraftai_agent_kit-1.3.0.dist-info/RECORD +230 -0
  229. codecraftai_agent_kit-1.3.0.dist-info/WHEEL +4 -0
  230. codecraftai_agent_kit-1.3.0.dist-info/licenses/LICENSE.md +204 -0
@@ -0,0 +1,276 @@
1
+ """
2
+ Defines the ApprovalStep class, a concrete WorkflowStep that
3
+ creates an ApprovalRequest via the Agent's ApprovalGate and
4
+ pauses workflow execution until the approval is resolved.
5
+
6
+ ApprovalStep retrieves the ApprovalGate from the executing
7
+ Agent, creates a pending ApprovalRequest with the step's
8
+ description, and inspects the request status after handler
9
+ invocation. If the request is approved, a StepResult with
10
+ COMPLETED status and the approval metadata is returned. If
11
+ the request is rejected, a StepResult with FAILED status and
12
+ the rejection reason is returned. If the request remains
13
+ pending and a timeout is configured, an ApprovalTimeoutError
14
+ is raised. If the request remains pending with no timeout, a
15
+ StepResult with PENDING_APPROVAL status is returned.
16
+
17
+ .. module:: ccai.agentkit.steps.approvalstep
18
+ :platform: Darwin, Linux, Unix, Windows
19
+ :synopsis: Built-in workflow step for human-in-the-loop approval gates.
20
+ """
21
+
22
+ import logging
23
+ import time
24
+
25
+ from typing import Optional
26
+
27
+ from ccai.agentkit.stepexecutionstatus import StepExecutionStatus
28
+ from ccai.agentkit.stepresult import StepResult
29
+ from ccai.agentkit.workflowcontext import WorkflowContext
30
+ from ccai.agentkit.workflowerrors import ApprovalTimeoutError
31
+ from ccai.agentkit.workflowstep import WorkflowStep
32
+
33
+
34
+ class ApprovalStep(WorkflowStep):
35
+ """
36
+ Creates an ApprovalRequest and pauses workflow execution
37
+ until the approval is resolved.
38
+
39
+ ApprovalStep is a concrete WorkflowStep subclass that
40
+ integrates with the ApprovalGate system. At execution
41
+ time, it retrieves the ApprovalGate from the executing
42
+ Agent, creates a pending ApprovalRequest with the step's
43
+ description and the requesting agent's identity, and
44
+ inspects the resulting request status.
45
+
46
+ If a registered ApprovalHandler immediately approves or
47
+ rejects the request during creation, the step returns a
48
+ StepResult reflecting that resolution. If the request
49
+ remains pending and a timeout is configured, an
50
+ ApprovalTimeoutError is raised. If the request remains
51
+ pending with no timeout, a StepResult with
52
+ PENDING_APPROVAL status is returned to signal that the
53
+ workflow should pause.
54
+
55
+ :param step_id: The unique identifier for this step within
56
+ the workflow. Must not be None or empty.
57
+ :param name: The human-readable name for this step. Must
58
+ not be None or empty.
59
+ :param description: A human-readable description of what
60
+ is being approved.
61
+ :param timeout: An optional timeout in seconds as a float.
62
+ When set and the request remains pending after handler
63
+ invocation, an ApprovalTimeoutError is raised. Defaults
64
+ to None, meaning no timeout is enforced at the step
65
+ level.
66
+ :param kwargs: Additional keyword arguments passed to the
67
+ WorkflowStep base class constructor (e.g. input_schema,
68
+ output_schema, tags, retry_policy).
69
+ """
70
+
71
+ def __init__(self, step_id: str, name: str, description: str,
72
+ timeout: Optional[float] = None, **kwargs) -> None:
73
+ super().__init__(step_id=step_id, name=name, step_type="approval", **kwargs)
74
+ self._description = description
75
+ self._timeout = timeout
76
+ self._logger = logging.getLogger("ccai.agentkit.workflow.steps.approval")
77
+ return
78
+
79
+ @property
80
+ def description(self) -> str:
81
+ """
82
+ A human-readable description of what is being approved.
83
+
84
+ :returns: The description string.
85
+ """
86
+ return self._description
87
+
88
+ @property
89
+ def timeout(self) -> Optional[float]:
90
+ """
91
+ The optional timeout in seconds for the approval request.
92
+
93
+ When set and the request remains pending after handler
94
+ invocation, an ApprovalTimeoutError is raised.
95
+
96
+ :returns: The timeout in seconds as a float or None when
97
+ no timeout is configured at the step level.
98
+ """
99
+ return self._timeout
100
+
101
+ def execute(self, context: WorkflowContext) -> StepResult:
102
+ """
103
+ Executes this ApprovalStep using the provided workflow
104
+ context.
105
+
106
+ Retrieves the Agent from the context, obtains the
107
+ ApprovalGate from the Agent, extracts the execution
108
+ identifier from the context metadata, and creates an
109
+ ApprovalRequest via the ApprovalGate. The ApprovalGate
110
+ invokes all registered handlers during request creation,
111
+ which may immediately approve or reject the request.
112
+
113
+ After request creation, the step inspects the request
114
+ status in the ApprovalGate's internal store:
115
+
116
+ - If "approved", returns a StepResult with COMPLETED
117
+ status and the approval metadata in the output.
118
+ - If "rejected", returns a StepResult with FAILED
119
+ status and the rejection reason in the error field.
120
+ - If still "pending" and a timeout is configured,
121
+ raises an ApprovalTimeoutError.
122
+ - If still "pending" with no timeout, returns a
123
+ StepResult with PENDING_APPROVAL status.
124
+
125
+ If the Agent is None, a StepResult with FAILED status
126
+ is returned.
127
+
128
+ :param context: The WorkflowContext with inputs and
129
+ prior step outputs.
130
+
131
+ :returns: A StepResult with the execution outcome.
132
+
133
+ :raises ApprovalTimeoutError: When the request remains
134
+ pending and a timeout is configured.
135
+ """
136
+ start_time = time.monotonic()
137
+
138
+ agent = context.agent
139
+
140
+ if agent is None:
141
+ duration = time.monotonic() - start_time
142
+ errmsg = "ApprovalStep '{}' failed: no agent available in the workflow context.".format(
143
+ self._name
144
+ )
145
+ self._logger.warning(errmsg)
146
+
147
+ result = StepResult(
148
+ step_id=self._step_id,
149
+ step_name=self._name,
150
+ status=StepExecutionStatus.FAILED,
151
+ duration=duration,
152
+ error=errmsg
153
+ )
154
+ return result
155
+
156
+ # Retrieve the ApprovalGate from the Agent
157
+ approval_gate = agent.approval_gate
158
+
159
+ # Extract execution context information
160
+ execution_id = context.get_metadata("execution_id", "unknown")
161
+ requesting_agent_id = str(agent.identity.identifier)
162
+
163
+ # Create the ApprovalRequest via the ApprovalGate
164
+ self._logger.info(
165
+ "ApprovalStep '%s' creating approval request for step '%s' "
166
+ "in execution '%s'.",
167
+ self._name, self._step_id, execution_id
168
+ )
169
+
170
+ request = approval_gate.create_request(
171
+ execution_id=execution_id,
172
+ step_id=self._step_id,
173
+ description=self._description,
174
+ requesting_agent_id=requesting_agent_id
175
+ )
176
+
177
+ request_id = request.identifier
178
+
179
+ # After handler invocation, check the resolved status.
180
+ # The ApprovalGate stores the updated request internally
181
+ # under the same identifier. Retrieve the current state
182
+ # from the gate's internal store.
183
+ current_request = approval_gate._pending_requests.get(request_id, request)
184
+ current_status = current_request.status
185
+
186
+ if current_status == "approved":
187
+ duration = time.monotonic() - start_time
188
+ output = dict(current_request.metadata)
189
+ output["approval_request_id"] = request_id
190
+
191
+ self._logger.info(
192
+ "ApprovalStep '%s' approved for request '%s'.",
193
+ self._name, request_id
194
+ )
195
+
196
+ result = StepResult(
197
+ step_id=self._step_id,
198
+ step_name=self._name,
199
+ status=StepExecutionStatus.COMPLETED,
200
+ output=output,
201
+ duration=duration
202
+ )
203
+ return result
204
+
205
+ if current_status == "rejected":
206
+ duration = time.monotonic() - start_time
207
+ rejection_reason = current_request.rejection_reason
208
+ errmsg = "ApprovalStep '{}' rejected for request '{}': {}".format(
209
+ self._name, request_id,
210
+ rejection_reason if rejection_reason is not None else "No reason provided."
211
+ )
212
+ self._logger.warning(errmsg)
213
+
214
+ result = StepResult(
215
+ step_id=self._step_id,
216
+ step_name=self._name,
217
+ status=StepExecutionStatus.FAILED,
218
+ duration=duration,
219
+ error=errmsg
220
+ )
221
+ return result
222
+
223
+ # Request is still pending
224
+ if self._timeout is not None:
225
+ self._logger.warning(
226
+ "ApprovalStep '%s' timed out for request '%s' after %s seconds.",
227
+ self._name, request_id, self._timeout
228
+ )
229
+ raise ApprovalTimeoutError(
230
+ request_id=request_id,
231
+ step_id=self._step_id,
232
+ timeout=self._timeout
233
+ )
234
+
235
+ # No timeout configured, return PENDING_APPROVAL status
236
+ duration = time.monotonic() - start_time
237
+
238
+ self._logger.info(
239
+ "ApprovalStep '%s' pending approval for request '%s'.",
240
+ self._name, request_id
241
+ )
242
+
243
+ result = StepResult(
244
+ step_id=self._step_id,
245
+ step_name=self._name,
246
+ status=StepExecutionStatus.PENDING_APPROVAL,
247
+ output={"approval_request_id": request_id},
248
+ duration=duration
249
+ )
250
+ return result
251
+
252
+ def __repr__(self) -> str:
253
+ """
254
+ Returns a detailed string representation including the
255
+ class name, step identifier, step name, and description.
256
+
257
+ :returns: A repr string for debugging.
258
+ """
259
+ repr_str = "{}(step_id={!r}, name={!r}, description={!r})".format(
260
+ self.__class__.__name__, self._step_id, self._name,
261
+ self._description
262
+ )
263
+ return repr_str
264
+
265
+ def __str__(self) -> str:
266
+ """
267
+ Returns a human-readable summary including the step name
268
+ and description.
269
+
270
+ :returns: A human-readable string describing the approval
271
+ step.
272
+ """
273
+ str_val = "ApprovalStep: {} [description: {}]".format(
274
+ self._name, self._description
275
+ )
276
+ return str_val
@@ -0,0 +1,403 @@
1
+ """
2
+ Defines the LLMStep class, a concrete WorkflowStep that executes
3
+ an LLM completion request through the Agent's LLMProviderRegistry
4
+ during workflow execution.
5
+
6
+ LLMStep renders a prompt from the WorkflowContext using either a
7
+ prompt template or a static prompt string, constructs an
8
+ LLMConversation, executes the completion request through the
9
+ Agent's complete method, optionally parses the response with an
10
+ OutputParser, and returns a StepResult containing the LLMResponse
11
+ content or a FAILED status on failure.
12
+
13
+ .. module:: ccai.agentkit.steps.llmstep
14
+ :platform: Darwin, Linux, Unix, Windows
15
+ :synopsis: Built-in workflow step for LLM completion execution.
16
+ """
17
+
18
+ import logging
19
+ import time
20
+
21
+ from typing import Optional
22
+
23
+ from ccai.agentkit.stepexecutionstatus import StepExecutionStatus
24
+ from ccai.agentkit.stepresult import StepResult
25
+ from ccai.agentkit.workflowcontext import WorkflowContext
26
+ from ccai.agentkit.workflowstep import WorkflowStep
27
+
28
+
29
+ class _AttributeDict:
30
+ """
31
+ A lightweight wrapper around a dictionary that exposes keys
32
+ as attributes. Used internally by LLMStep to support dotted
33
+ reference resolution in prompt templates via str.format_map.
34
+
35
+ For example, given a dictionary {"text": "hello"}, accessing
36
+ .text on this wrapper returns "hello".
37
+ """
38
+
39
+ def __init__(self, data: dict) -> None:
40
+ self._data = data
41
+ return
42
+
43
+ def __getattr__(self, name: str):
44
+ if name.startswith("_"):
45
+ raise AttributeError(name)
46
+
47
+ if name in self._data:
48
+ value = self._data[name]
49
+
50
+ if isinstance(value, dict):
51
+ return _AttributeDict(value)
52
+
53
+ return value
54
+
55
+ raise AttributeError(
56
+ "_AttributeDict has no attribute {!r}".format(name)
57
+ )
58
+
59
+ def __repr__(self) -> str:
60
+ return "_AttributeDict({!r})".format(self._data)
61
+
62
+
63
+ def _build_format_namespace(context) -> dict:
64
+ """
65
+ Builds a format namespace dictionary for prompt template
66
+ rendering from a WorkflowContext.
67
+
68
+ Returns a dictionary with "inputs" and "steps" keys, each
69
+ mapped to an _AttributeDict wrapper that supports
70
+ attribute-style access for str.format_map resolution.
71
+
72
+ :param context: The WorkflowContext to build the namespace
73
+ from.
74
+
75
+ :returns: A dictionary suitable for str.format_map.
76
+ """
77
+ inputs_wrapper = _AttributeDict(context.inputs)
78
+
79
+ steps_dict = {}
80
+ for step_id, step_output in context.step_outputs.items():
81
+ if isinstance(step_output, dict):
82
+ steps_dict[step_id] = step_output
83
+ else:
84
+ steps_dict[step_id] = {}
85
+
86
+ steps_wrapper = _AttributeDict(steps_dict)
87
+
88
+ namespace = {
89
+ "inputs": inputs_wrapper,
90
+ "steps": steps_wrapper
91
+ }
92
+ return namespace
93
+
94
+
95
+ class LLMStep(WorkflowStep):
96
+ """
97
+ Executes an LLM completion request through the Agent's
98
+ LLMProviderRegistry.
99
+
100
+ LLMStep is a concrete WorkflowStep subclass that integrates
101
+ with the LLM Integration system. At execution time, it
102
+ renders a prompt from the WorkflowContext, constructs an
103
+ LLMConversation with a single user message, executes the
104
+ completion request through the Agent's complete method, and
105
+ wraps the result in a StepResult.
106
+
107
+ The prompt can be provided as either a prompt_template or a
108
+ static prompt_string. When a prompt_template is provided, it
109
+ is rendered using the WorkflowContext inputs and step outputs
110
+ via Python string formatting. When a prompt_string is
111
+ provided, it is used directly without rendering.
112
+
113
+ An optional output_parser can be provided to parse the LLM
114
+ response content into structured output. The output_parser
115
+ must be a callable that accepts a string and returns a
116
+ dictionary.
117
+
118
+ :param step_id: The unique identifier for this step within
119
+ the workflow. Must not be None or empty.
120
+ :param name: The human-readable name for this step. Must
121
+ not be None or empty.
122
+ :param provider_name: The name of the LLMProvider to use
123
+ for the completion request.
124
+ :param model_name: The name of the model to use for the
125
+ completion request.
126
+ :param prompt_template: An optional prompt template string
127
+ that supports {inputs.<field>} and
128
+ {steps.<step_id>.<field>} references for rendering
129
+ against the WorkflowContext. Defaults to None.
130
+ :param prompt_string: An optional static prompt string
131
+ used directly without rendering. Defaults to None.
132
+ :param output_parser: An optional callable that accepts
133
+ the LLM response content string and returns a
134
+ dictionary of parsed output. Defaults to None.
135
+ :param kwargs: Additional keyword arguments passed to the
136
+ WorkflowStep base class constructor (e.g. input_schema,
137
+ output_schema, tags, retry_policy).
138
+ """
139
+
140
+ def __init__(self, step_id: str, name: str, provider_name: str,
141
+ model_name: str, prompt_template: Optional[str] = None,
142
+ prompt_string: Optional[str] = None,
143
+ output_parser=None, **kwargs) -> None:
144
+ super().__init__(step_id=step_id, name=name, step_type="llm", **kwargs)
145
+ self._provider_name = provider_name
146
+ self._model_name = model_name
147
+ self._prompt_template = prompt_template
148
+ self._prompt_string = prompt_string
149
+ self._output_parser = output_parser
150
+ self._logger = logging.getLogger("ccai.agentkit.workflow.steps.llm")
151
+ return
152
+
153
+ @property
154
+ def provider_name(self) -> str:
155
+ """
156
+ The name of the LLMProvider to use for the completion
157
+ request.
158
+
159
+ :returns: The provider name string.
160
+ """
161
+ return self._provider_name
162
+
163
+ @property
164
+ def model_name(self) -> str:
165
+ """
166
+ The name of the model to use for the completion request.
167
+
168
+ :returns: The model name string.
169
+ """
170
+ return self._model_name
171
+
172
+ @property
173
+ def prompt_template(self) -> Optional[str]:
174
+ """
175
+ The prompt template string for rendering against the
176
+ WorkflowContext, or None when no template is configured.
177
+
178
+ :returns: The prompt template string or None.
179
+ """
180
+ return self._prompt_template
181
+
182
+ @property
183
+ def prompt_string(self) -> Optional[str]:
184
+ """
185
+ The static prompt string used directly without rendering,
186
+ or None when no static prompt is configured.
187
+
188
+ :returns: The prompt string or None.
189
+ """
190
+ return self._prompt_string
191
+
192
+ @property
193
+ def output_parser(self):
194
+ """
195
+ The optional output parser callable for parsing the LLM
196
+ response content into structured output, or None when
197
+ no parser is configured.
198
+
199
+ :returns: The output parser callable or None.
200
+ """
201
+ return self._output_parser
202
+
203
+ def _render_prompt(self, context: WorkflowContext) -> str:
204
+ """
205
+ Renders the prompt from the WorkflowContext.
206
+
207
+ When a prompt_template is configured, builds a namespace
208
+ dictionary from the context inputs and step outputs and
209
+ renders the template using Python string formatting.
210
+ Template references use the form {inputs.<field>} and
211
+ {steps.<step_id>.<field>}. The namespace objects support
212
+ attribute-style access so that Python's str.format_map
213
+ can resolve dotted references.
214
+
215
+ When a prompt_string is configured, returns it directly
216
+ without rendering.
217
+
218
+ When neither is configured, returns an empty string.
219
+
220
+ :param context: The WorkflowContext to render the prompt
221
+ against.
222
+
223
+ :returns: The rendered prompt string.
224
+ """
225
+ if self._prompt_template is not None:
226
+ format_dict = _build_format_namespace(context)
227
+ rendered_prompt = self._prompt_template.format_map(format_dict)
228
+ return rendered_prompt
229
+
230
+ if self._prompt_string is not None:
231
+ return self._prompt_string
232
+
233
+ return ""
234
+
235
+ def execute(self, context: WorkflowContext) -> StepResult:
236
+ """
237
+ Executes this LLMStep using the provided workflow context.
238
+
239
+ Renders the prompt from the WorkflowContext, retrieves the
240
+ Agent from the context, constructs an LLMConversation with
241
+ a single user message containing the rendered prompt,
242
+ executes the completion request through the Agent's
243
+ complete method, optionally parses the response with the
244
+ output_parser, and returns a StepResult with the execution
245
+ outcome.
246
+
247
+ If the Agent is None, a StepResult with FAILED status is
248
+ returned. If the LLM completion request fails, a StepResult
249
+ with FAILED status and the error information is returned.
250
+ If the output_parser fails to parse the response, a
251
+ StepResult with FAILED status and the parsing error
252
+ information is returned.
253
+
254
+ :param context: The WorkflowContext with inputs and prior
255
+ step outputs.
256
+
257
+ :returns: A StepResult with the execution outcome.
258
+ """
259
+ start_time = time.monotonic()
260
+
261
+ agent = context.agent
262
+
263
+ if agent is None:
264
+ duration = time.monotonic() - start_time
265
+ errmsg = "LLMStep '{}' failed: no agent available in the workflow context.".format(
266
+ self._name
267
+ )
268
+ self._logger.warning(errmsg)
269
+
270
+ result = StepResult(
271
+ step_id=self._step_id,
272
+ step_name=self._name,
273
+ status=StepExecutionStatus.FAILED,
274
+ duration=duration,
275
+ error=errmsg
276
+ )
277
+ return result
278
+
279
+ # Render the prompt from the WorkflowContext
280
+ try:
281
+ rendered_prompt = self._render_prompt(context)
282
+ except Exception as render_err:
283
+ duration = time.monotonic() - start_time
284
+ errmsg = "LLMStep '{}' failed during prompt rendering: {}".format(
285
+ self._name, str(render_err)
286
+ )
287
+ self._logger.warning(errmsg)
288
+
289
+ result = StepResult(
290
+ step_id=self._step_id,
291
+ step_name=self._name,
292
+ status=StepExecutionStatus.FAILED,
293
+ duration=duration,
294
+ error=errmsg
295
+ )
296
+ return result
297
+
298
+ # Construct an LLMConversation with a single user message
299
+ from ccai.agentkit.llmconversation import LLMConversation
300
+ from ccai.agentkit.llmmessage import LLMMessage
301
+
302
+ user_message = LLMMessage(role="user", content=rendered_prompt)
303
+ conversation = LLMConversation(messages=[user_message])
304
+
305
+ # Execute the completion request through the Agent
306
+ try:
307
+ llm_response = agent.complete(
308
+ provider_name=self._provider_name,
309
+ model_name=self._model_name,
310
+ conversation=conversation
311
+ )
312
+ except Exception as llm_err:
313
+ duration = time.monotonic() - start_time
314
+ errmsg = "LLMStep '{}' failed during LLM completion with provider '{}' model '{}': {}".format(
315
+ self._name, self._provider_name, self._model_name, str(llm_err)
316
+ )
317
+ self._logger.warning(errmsg)
318
+
319
+ result = StepResult(
320
+ step_id=self._step_id,
321
+ step_name=self._name,
322
+ status=StepExecutionStatus.FAILED,
323
+ duration=duration,
324
+ error=errmsg
325
+ )
326
+ return result
327
+
328
+ # Extract the response content
329
+ response_content = llm_response.message.content
330
+
331
+ # If an output_parser is provided, parse the response content
332
+ if self._output_parser is not None:
333
+ try:
334
+ parsed_output = self._output_parser(response_content)
335
+
336
+ if not isinstance(parsed_output, dict):
337
+ parsed_output = {"content": parsed_output}
338
+
339
+ duration = time.monotonic() - start_time
340
+
341
+ result = StepResult(
342
+ step_id=self._step_id,
343
+ step_name=self._name,
344
+ status=StepExecutionStatus.COMPLETED,
345
+ output=parsed_output,
346
+ duration=duration
347
+ )
348
+ return result
349
+
350
+ except Exception as parse_err:
351
+ duration = time.monotonic() - start_time
352
+ errmsg = "LLMStep '{}' failed during output parsing: {}".format(
353
+ self._name, str(parse_err)
354
+ )
355
+ self._logger.warning(errmsg)
356
+
357
+ result = StepResult(
358
+ step_id=self._step_id,
359
+ step_name=self._name,
360
+ status=StepExecutionStatus.FAILED,
361
+ duration=duration,
362
+ error=errmsg
363
+ )
364
+ return result
365
+
366
+ # No output_parser: return the raw response content
367
+ duration = time.monotonic() - start_time
368
+ output = {"content": response_content}
369
+
370
+ result = StepResult(
371
+ step_id=self._step_id,
372
+ step_name=self._name,
373
+ status=StepExecutionStatus.COMPLETED,
374
+ output=output,
375
+ duration=duration
376
+ )
377
+ return result
378
+
379
+ def __repr__(self) -> str:
380
+ """
381
+ Returns a detailed string representation including the
382
+ class name, step identifier, step name, provider name,
383
+ and model name.
384
+
385
+ :returns: A repr string for debugging.
386
+ """
387
+ repr_str = "{}(step_id={!r}, name={!r}, provider_name={!r}, model_name={!r})".format(
388
+ self.__class__.__name__, self._step_id, self._name,
389
+ self._provider_name, self._model_name
390
+ )
391
+ return repr_str
392
+
393
+ def __str__(self) -> str:
394
+ """
395
+ Returns a human-readable summary including the step name,
396
+ provider name, and model name.
397
+
398
+ :returns: A human-readable string describing the LLM step.
399
+ """
400
+ rtnval = "LLMStep: {} [provider: {}, model: {}]".format(
401
+ self._name, self._provider_name, self._model_name
402
+ )
403
+ return rtnval