kweaver-dolphin 0.1.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 (199) hide show
  1. DolphinLanguageSDK/__init__.py +58 -0
  2. dolphin/__init__.py +62 -0
  3. dolphin/cli/__init__.py +20 -0
  4. dolphin/cli/args/__init__.py +9 -0
  5. dolphin/cli/args/parser.py +567 -0
  6. dolphin/cli/builtin_agents/__init__.py +22 -0
  7. dolphin/cli/commands/__init__.py +4 -0
  8. dolphin/cli/interrupt/__init__.py +8 -0
  9. dolphin/cli/interrupt/handler.py +205 -0
  10. dolphin/cli/interrupt/keyboard.py +82 -0
  11. dolphin/cli/main.py +49 -0
  12. dolphin/cli/multimodal/__init__.py +34 -0
  13. dolphin/cli/multimodal/clipboard.py +327 -0
  14. dolphin/cli/multimodal/handler.py +249 -0
  15. dolphin/cli/multimodal/image_processor.py +214 -0
  16. dolphin/cli/multimodal/input_parser.py +149 -0
  17. dolphin/cli/runner/__init__.py +8 -0
  18. dolphin/cli/runner/runner.py +989 -0
  19. dolphin/cli/ui/__init__.py +10 -0
  20. dolphin/cli/ui/console.py +2795 -0
  21. dolphin/cli/ui/input.py +340 -0
  22. dolphin/cli/ui/layout.py +425 -0
  23. dolphin/cli/ui/stream_renderer.py +302 -0
  24. dolphin/cli/utils/__init__.py +8 -0
  25. dolphin/cli/utils/helpers.py +135 -0
  26. dolphin/cli/utils/version.py +49 -0
  27. dolphin/core/__init__.py +107 -0
  28. dolphin/core/agent/__init__.py +10 -0
  29. dolphin/core/agent/agent_state.py +69 -0
  30. dolphin/core/agent/base_agent.py +970 -0
  31. dolphin/core/code_block/__init__.py +0 -0
  32. dolphin/core/code_block/agent_init_block.py +0 -0
  33. dolphin/core/code_block/assign_block.py +98 -0
  34. dolphin/core/code_block/basic_code_block.py +1865 -0
  35. dolphin/core/code_block/explore_block.py +1327 -0
  36. dolphin/core/code_block/explore_block_v2.py +712 -0
  37. dolphin/core/code_block/explore_strategy.py +672 -0
  38. dolphin/core/code_block/judge_block.py +220 -0
  39. dolphin/core/code_block/prompt_block.py +32 -0
  40. dolphin/core/code_block/skill_call_deduplicator.py +291 -0
  41. dolphin/core/code_block/tool_block.py +129 -0
  42. dolphin/core/common/__init__.py +17 -0
  43. dolphin/core/common/constants.py +176 -0
  44. dolphin/core/common/enums.py +1173 -0
  45. dolphin/core/common/exceptions.py +133 -0
  46. dolphin/core/common/multimodal.py +539 -0
  47. dolphin/core/common/object_type.py +165 -0
  48. dolphin/core/common/output_format.py +432 -0
  49. dolphin/core/common/types.py +36 -0
  50. dolphin/core/config/__init__.py +16 -0
  51. dolphin/core/config/global_config.py +1289 -0
  52. dolphin/core/config/ontology_config.py +133 -0
  53. dolphin/core/context/__init__.py +12 -0
  54. dolphin/core/context/context.py +1580 -0
  55. dolphin/core/context/context_manager.py +161 -0
  56. dolphin/core/context/var_output.py +82 -0
  57. dolphin/core/context/variable_pool.py +356 -0
  58. dolphin/core/context_engineer/__init__.py +41 -0
  59. dolphin/core/context_engineer/config/__init__.py +5 -0
  60. dolphin/core/context_engineer/config/settings.py +402 -0
  61. dolphin/core/context_engineer/core/__init__.py +7 -0
  62. dolphin/core/context_engineer/core/budget_manager.py +327 -0
  63. dolphin/core/context_engineer/core/context_assembler.py +583 -0
  64. dolphin/core/context_engineer/core/context_manager.py +637 -0
  65. dolphin/core/context_engineer/core/tokenizer_service.py +260 -0
  66. dolphin/core/context_engineer/example/incremental_example.py +267 -0
  67. dolphin/core/context_engineer/example/traditional_example.py +334 -0
  68. dolphin/core/context_engineer/services/__init__.py +5 -0
  69. dolphin/core/context_engineer/services/compressor.py +399 -0
  70. dolphin/core/context_engineer/utils/__init__.py +6 -0
  71. dolphin/core/context_engineer/utils/context_utils.py +441 -0
  72. dolphin/core/context_engineer/utils/message_formatter.py +270 -0
  73. dolphin/core/context_engineer/utils/token_utils.py +139 -0
  74. dolphin/core/coroutine/__init__.py +15 -0
  75. dolphin/core/coroutine/context_snapshot.py +154 -0
  76. dolphin/core/coroutine/context_snapshot_profile.py +922 -0
  77. dolphin/core/coroutine/context_snapshot_store.py +268 -0
  78. dolphin/core/coroutine/execution_frame.py +145 -0
  79. dolphin/core/coroutine/execution_state_registry.py +161 -0
  80. dolphin/core/coroutine/resume_handle.py +101 -0
  81. dolphin/core/coroutine/step_result.py +101 -0
  82. dolphin/core/executor/__init__.py +18 -0
  83. dolphin/core/executor/debug_controller.py +630 -0
  84. dolphin/core/executor/dolphin_executor.py +1063 -0
  85. dolphin/core/executor/executor.py +624 -0
  86. dolphin/core/flags/__init__.py +27 -0
  87. dolphin/core/flags/definitions.py +49 -0
  88. dolphin/core/flags/manager.py +113 -0
  89. dolphin/core/hook/__init__.py +95 -0
  90. dolphin/core/hook/expression_evaluator.py +499 -0
  91. dolphin/core/hook/hook_dispatcher.py +380 -0
  92. dolphin/core/hook/hook_types.py +248 -0
  93. dolphin/core/hook/isolated_variable_pool.py +284 -0
  94. dolphin/core/interfaces.py +53 -0
  95. dolphin/core/llm/__init__.py +0 -0
  96. dolphin/core/llm/llm.py +495 -0
  97. dolphin/core/llm/llm_call.py +100 -0
  98. dolphin/core/llm/llm_client.py +1285 -0
  99. dolphin/core/llm/message_sanitizer.py +120 -0
  100. dolphin/core/logging/__init__.py +20 -0
  101. dolphin/core/logging/logger.py +526 -0
  102. dolphin/core/message/__init__.py +8 -0
  103. dolphin/core/message/compressor.py +749 -0
  104. dolphin/core/parser/__init__.py +8 -0
  105. dolphin/core/parser/parser.py +405 -0
  106. dolphin/core/runtime/__init__.py +10 -0
  107. dolphin/core/runtime/runtime_graph.py +926 -0
  108. dolphin/core/runtime/runtime_instance.py +446 -0
  109. dolphin/core/skill/__init__.py +14 -0
  110. dolphin/core/skill/context_retention.py +157 -0
  111. dolphin/core/skill/skill_function.py +686 -0
  112. dolphin/core/skill/skill_matcher.py +282 -0
  113. dolphin/core/skill/skillkit.py +700 -0
  114. dolphin/core/skill/skillset.py +72 -0
  115. dolphin/core/trajectory/__init__.py +10 -0
  116. dolphin/core/trajectory/recorder.py +189 -0
  117. dolphin/core/trajectory/trajectory.py +522 -0
  118. dolphin/core/utils/__init__.py +9 -0
  119. dolphin/core/utils/cache_kv.py +212 -0
  120. dolphin/core/utils/tools.py +340 -0
  121. dolphin/lib/__init__.py +93 -0
  122. dolphin/lib/debug/__init__.py +8 -0
  123. dolphin/lib/debug/visualizer.py +409 -0
  124. dolphin/lib/memory/__init__.py +28 -0
  125. dolphin/lib/memory/async_processor.py +220 -0
  126. dolphin/lib/memory/llm_calls.py +195 -0
  127. dolphin/lib/memory/manager.py +78 -0
  128. dolphin/lib/memory/sandbox.py +46 -0
  129. dolphin/lib/memory/storage.py +245 -0
  130. dolphin/lib/memory/utils.py +51 -0
  131. dolphin/lib/ontology/__init__.py +12 -0
  132. dolphin/lib/ontology/basic/__init__.py +0 -0
  133. dolphin/lib/ontology/basic/base.py +102 -0
  134. dolphin/lib/ontology/basic/concept.py +130 -0
  135. dolphin/lib/ontology/basic/object.py +11 -0
  136. dolphin/lib/ontology/basic/relation.py +63 -0
  137. dolphin/lib/ontology/datasource/__init__.py +27 -0
  138. dolphin/lib/ontology/datasource/datasource.py +66 -0
  139. dolphin/lib/ontology/datasource/oracle_datasource.py +338 -0
  140. dolphin/lib/ontology/datasource/sql.py +845 -0
  141. dolphin/lib/ontology/mapping.py +177 -0
  142. dolphin/lib/ontology/ontology.py +733 -0
  143. dolphin/lib/ontology/ontology_context.py +16 -0
  144. dolphin/lib/ontology/ontology_manager.py +107 -0
  145. dolphin/lib/skill_results/__init__.py +31 -0
  146. dolphin/lib/skill_results/cache_backend.py +559 -0
  147. dolphin/lib/skill_results/result_processor.py +181 -0
  148. dolphin/lib/skill_results/result_reference.py +179 -0
  149. dolphin/lib/skill_results/skillkit_hook.py +324 -0
  150. dolphin/lib/skill_results/strategies.py +328 -0
  151. dolphin/lib/skill_results/strategy_registry.py +150 -0
  152. dolphin/lib/skillkits/__init__.py +44 -0
  153. dolphin/lib/skillkits/agent_skillkit.py +155 -0
  154. dolphin/lib/skillkits/cognitive_skillkit.py +82 -0
  155. dolphin/lib/skillkits/env_skillkit.py +250 -0
  156. dolphin/lib/skillkits/mcp_adapter.py +616 -0
  157. dolphin/lib/skillkits/mcp_skillkit.py +771 -0
  158. dolphin/lib/skillkits/memory_skillkit.py +650 -0
  159. dolphin/lib/skillkits/noop_skillkit.py +31 -0
  160. dolphin/lib/skillkits/ontology_skillkit.py +89 -0
  161. dolphin/lib/skillkits/plan_act_skillkit.py +452 -0
  162. dolphin/lib/skillkits/resource/__init__.py +52 -0
  163. dolphin/lib/skillkits/resource/models/__init__.py +6 -0
  164. dolphin/lib/skillkits/resource/models/skill_config.py +109 -0
  165. dolphin/lib/skillkits/resource/models/skill_meta.py +127 -0
  166. dolphin/lib/skillkits/resource/resource_skillkit.py +393 -0
  167. dolphin/lib/skillkits/resource/skill_cache.py +215 -0
  168. dolphin/lib/skillkits/resource/skill_loader.py +395 -0
  169. dolphin/lib/skillkits/resource/skill_validator.py +406 -0
  170. dolphin/lib/skillkits/resource_skillkit.py +11 -0
  171. dolphin/lib/skillkits/search_skillkit.py +163 -0
  172. dolphin/lib/skillkits/sql_skillkit.py +274 -0
  173. dolphin/lib/skillkits/system_skillkit.py +509 -0
  174. dolphin/lib/skillkits/vm_skillkit.py +65 -0
  175. dolphin/lib/utils/__init__.py +9 -0
  176. dolphin/lib/utils/data_process.py +207 -0
  177. dolphin/lib/utils/handle_progress.py +178 -0
  178. dolphin/lib/utils/security.py +139 -0
  179. dolphin/lib/utils/text_retrieval.py +462 -0
  180. dolphin/lib/vm/__init__.py +11 -0
  181. dolphin/lib/vm/env_executor.py +895 -0
  182. dolphin/lib/vm/python_session_manager.py +453 -0
  183. dolphin/lib/vm/vm.py +610 -0
  184. dolphin/sdk/__init__.py +60 -0
  185. dolphin/sdk/agent/__init__.py +12 -0
  186. dolphin/sdk/agent/agent_factory.py +236 -0
  187. dolphin/sdk/agent/dolphin_agent.py +1106 -0
  188. dolphin/sdk/api/__init__.py +4 -0
  189. dolphin/sdk/runtime/__init__.py +8 -0
  190. dolphin/sdk/runtime/env.py +363 -0
  191. dolphin/sdk/skill/__init__.py +10 -0
  192. dolphin/sdk/skill/global_skills.py +706 -0
  193. dolphin/sdk/skill/traditional_toolkit.py +260 -0
  194. kweaver_dolphin-0.1.0.dist-info/METADATA +521 -0
  195. kweaver_dolphin-0.1.0.dist-info/RECORD +199 -0
  196. kweaver_dolphin-0.1.0.dist-info/WHEEL +5 -0
  197. kweaver_dolphin-0.1.0.dist-info/entry_points.txt +27 -0
  198. kweaver_dolphin-0.1.0.dist-info/licenses/LICENSE.txt +201 -0
  199. kweaver_dolphin-0.1.0.dist-info/top_level.txt +2 -0
@@ -0,0 +1,686 @@
1
+ # =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
2
+ # Licensed under the Apache License, Version 2.0 (the “License”);
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ #
6
+ # http://www.apache.org/licenses/LICENSE-2.0
7
+ #
8
+ # Unless required by applicable law or agreed to in writing, software
9
+ # distributed under the License is distributed on an “AS IS” BASIS,
10
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ # See the License for the specific language governing permissions and
12
+ # limitations under the License.
13
+ # =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
14
+ from inspect import Parameter, signature
15
+ from typing import Any, Callable, Dict, Mapping, Optional, Tuple, List
16
+
17
+ from docstring_parser import parse
18
+ from jsonschema.exceptions import SchemaError
19
+ from jsonschema.validators import Draft202012Validator as JSONValidator
20
+ from pydantic import BaseModel, create_model
21
+ from pydantic.fields import FieldInfo
22
+ import re
23
+ import aiohttp
24
+
25
+
26
+ def to_pascal(snake: str) -> str:
27
+ """Convert a snake_case string to PascalCase.
28
+
29
+ Args:
30
+ snake (str): The snake_case string to be converted.
31
+
32
+ Returns:
33
+ str: The converted PascalCase string.
34
+ """
35
+ # Check if the string is already in PascalCase
36
+ if re.match(r"^[A-Z][a-zA-Z0-9]*([A-Z][a-zA-Z0-9]*)*$", snake):
37
+ return snake
38
+ # Remove leading and trailing underscores
39
+ snake = snake.strip("_")
40
+ # Replace multiple underscores with a single one
41
+ snake = re.sub("_+", "_", snake)
42
+ # Convert to PascalCase
43
+ return re.sub(
44
+ "_([0-9A-Za-z])",
45
+ lambda m: m.group(1).upper(),
46
+ snake.title(),
47
+ )
48
+
49
+
50
+ def get_pydantic_object_schema(pydantic_params: BaseModel) -> Dict:
51
+ r"""Get the JSON schema of a Pydantic model.
52
+
53
+ Args:
54
+ pydantic_params (BaseModel): The Pydantic model to retrieve the schema
55
+ for.
56
+
57
+ Returns:
58
+ dict: The JSON schema of the Pydantic model.
59
+ """
60
+ # Import typing module to provide namespace for types like Union, List, etc.
61
+ import typing
62
+
63
+ # Rebuild model with typing namespace to resolve forward references
64
+ # This is needed when dynamic models use types like Union[str, List[str]]
65
+ try:
66
+ pydantic_params.model_rebuild(_types_namespace={"Union": typing.Union, "List": typing.List, "Optional": typing.Optional, "Any": typing.Any})
67
+ except Exception:
68
+ # If rebuild fails, try without (may work for simple models)
69
+ pass
70
+
71
+ return pydantic_params.model_json_schema()
72
+
73
+
74
+ def _remove_a_key(d: Dict, remove_key: Any) -> None:
75
+ r"""Remove a key from a dictionary recursively."""
76
+ if isinstance(d, dict):
77
+ for key in list(d.keys()):
78
+ if key == remove_key:
79
+ del d[key]
80
+ else:
81
+ _remove_a_key(d[key], remove_key)
82
+
83
+
84
+ def get_openai_function_schema(func: Callable) -> Dict[str, Any]:
85
+ r"""Generates a schema dict for an OpenAI function based on its signature.
86
+
87
+ This function is deprecated and will be replaced by
88
+ :obj:`get_openai_tool_schema()` in future versions. It parses the
89
+ function's parameters and docstring to construct a JSON schema-like
90
+ dictionary.
91
+
92
+ Args:
93
+ func (Callable): The OpenAI function to generate the schema for.
94
+
95
+ Returns:
96
+ Dict[str, Any]: A dictionary representing the JSON schema of the
97
+ function, including its name, description, and parameter
98
+ specifications.
99
+ """
100
+ openai_function_schema = get_openai_tool_schema(func)["function"]
101
+ return openai_function_schema
102
+
103
+
104
+ def get_openai_tool_schema(func: Callable) -> Dict[str, Any]:
105
+ r"""Generates an OpenAI JSON schema from a given Python function.
106
+
107
+ This function creates a schema compatible with OpenAI's API specifications,
108
+ based on the provided Python function. It processes the function's
109
+ parameters, types, and docstrings, and constructs a schema accordingly.
110
+
111
+ Note:
112
+ - Each parameter in `func` must have a type annotation; otherwise, it's
113
+ treated as 'Any'.
114
+ - Variable arguments (*args) and keyword arguments (**kwargs) are not
115
+ supported and will be ignored.
116
+ - A functional description including a brief and detailed explanation
117
+ should be provided in the docstring of `func`.
118
+ - All parameters of `func` must be described in its docstring.
119
+ - Supported docstring styles: ReST, Google, Numpydoc, and Epydoc.
120
+
121
+ Args:
122
+ func (Callable): The Python function to be converted into an OpenAI
123
+ JSON schema.
124
+
125
+ Returns:
126
+ Dict[str, Any]: A dictionary representing the OpenAI JSON schema of
127
+ the provided function.
128
+
129
+ See Also:
130
+ `OpenAI API Reference
131
+ <https://platform.openai.com/docs/api-reference/assistants/object>`_
132
+ """
133
+ params: Mapping[str, Parameter] = signature(func).parameters
134
+ fields: Dict[str, Tuple[type, FieldInfo]] = {}
135
+ for param_name, p in params.items():
136
+ param_type = p.annotation
137
+ param_default = p.default
138
+ param_kind = p.kind
139
+ param_annotation = p.annotation
140
+ # Variable parameters are not supported
141
+ if (
142
+ param_kind == Parameter.VAR_POSITIONAL
143
+ or param_kind == Parameter.VAR_KEYWORD
144
+ ):
145
+ continue
146
+ # If the parameter type is not specified, it defaults to typing.Any
147
+ if param_annotation is Parameter.empty:
148
+ param_type = Any
149
+ # Check if the parameter has a default value
150
+ if param_default is Parameter.empty:
151
+ fields[param_name] = (param_type, FieldInfo())
152
+ else:
153
+ fields[param_name] = (param_type, FieldInfo(default=param_default))
154
+
155
+ # Applying `create_model()` directly will result in a mypy error,
156
+ # create an alias to avoid this.
157
+ def _create_mol(name, field):
158
+ return create_model(name, **field)
159
+
160
+ model = _create_mol(to_pascal(func.__name__), fields)
161
+ parameters_dict = get_pydantic_object_schema(model)
162
+ # The `"title"` is generated by `model.model_json_schema()`
163
+ # but is useless for openai json schema
164
+ _remove_a_key(parameters_dict, "title")
165
+
166
+ docstring = parse(func.__doc__ or "")
167
+ for param in docstring.params:
168
+ if (name := param.arg_name) in parameters_dict["properties"] and (
169
+ description := param.description
170
+ ):
171
+ parameters_dict["properties"][name]["description"] = description
172
+
173
+ short_description = docstring.short_description or ""
174
+ long_description = docstring.long_description or ""
175
+ if long_description:
176
+ func_description = f"{short_description}\n{long_description}"
177
+ else:
178
+ func_description = short_description
179
+
180
+ openai_function_schema = {
181
+ "name": func.__name__,
182
+ "description": func_description,
183
+ "parameters": parameters_dict,
184
+ }
185
+
186
+ openai_tool_schema = {
187
+ "type": "function",
188
+ "function": openai_function_schema,
189
+ }
190
+ return openai_tool_schema
191
+
192
+
193
+ class OpenAIFunction:
194
+ r"""An abstraction of a function that OpenAI chat models can call. See
195
+ https://platform.openai.com/docs/api-reference/chat/create.
196
+
197
+ By default, the tool schema will be parsed from the func, or you can
198
+ provide a user-defined tool schema to override.
199
+
200
+ Args:
201
+ func (Callable): The function to call.The tool schema is parsed from
202
+ the signature and docstring by default.
203
+ openai_tool_schema (Optional[Dict[str, Any]], optional): A user-defined
204
+ openai tool schema to override the default result.
205
+ (default: :obj:`None`)
206
+ """
207
+
208
+ def __init__(
209
+ self,
210
+ func: Callable,
211
+ openai_tool_schema: Optional[Dict[str, Any]] = None,
212
+ ) -> None:
213
+ self.func = func
214
+ self.openai_tool_schema = openai_tool_schema or get_openai_tool_schema(func)
215
+
216
+ @staticmethod
217
+ def validate_openai_tool_schema(
218
+ openai_tool_schema: Dict[str, Any],
219
+ ) -> None:
220
+ r"""Validates the OpenAI tool schema against
221
+ :obj:`ToolAssistantToolsFunction`.
222
+ This function checks if the provided :obj:`openai_tool_schema` adheres
223
+ to the specifications required by OpenAI's
224
+ :obj:`ToolAssistantToolsFunction`. It ensures that the function
225
+ description and parameters are correctly formatted according to JSON
226
+ Schema specifications.
227
+ Args:
228
+ openai_tool_schema (Dict[str, Any]): The OpenAI tool schema to
229
+ validate.
230
+ Raises:
231
+ ValidationError: If the schema does not comply with the
232
+ specifications.
233
+ ValueError: If the function description or parameter descriptions
234
+ are missing in the schema.
235
+ SchemaError: If the parameters do not meet JSON Schema reference
236
+ specifications.
237
+ """
238
+ # Check the type
239
+ if not openai_tool_schema["type"]:
240
+ raise ValueError("miss type")
241
+ # Check the function description
242
+ if not openai_tool_schema["function"]["description"]:
243
+ raise ValueError("miss function description")
244
+
245
+ # Validate whether parameters
246
+ # meet the JSON Schema reference specifications.
247
+ # See https://platform.openai.com/docs/guides/gpt/function-calling
248
+ # for examples, and the
249
+ # https://json-schema.org/understanding-json-schema/ for
250
+ # documentation about the format.
251
+ parameters = openai_tool_schema["function"]["parameters"]
252
+ try:
253
+ JSONValidator.check_schema(parameters)
254
+ except SchemaError as e:
255
+ raise e
256
+ # Check the parameter description
257
+ properties: Dict[str, Any] = parameters["properties"]
258
+ for param_name in properties.keys():
259
+ param_dict = properties[param_name]
260
+ if "description" not in param_dict:
261
+ raise ValueError(f'miss description of parameter "{param_name}"')
262
+
263
+ def get_openai_tool_schema(self) -> Dict[str, Any]:
264
+ r"""Gets the OpenAI tool schema for this function.
265
+
266
+ This method returns the OpenAI tool schema associated with this
267
+ function, after validating it to ensure it meets OpenAI's
268
+ specifications.
269
+
270
+ Returns:
271
+ Dict[str, Any]: The OpenAI tool schema for this function.
272
+ """
273
+ self.validate_openai_tool_schema(self.openai_tool_schema)
274
+ return self.openai_tool_schema
275
+
276
+ def set_openai_tool_schema(self, schema: Dict[str, Any]) -> None:
277
+ r"""Sets the OpenAI tool schema for this function.
278
+
279
+ Allows setting a custom OpenAI tool schema for this function.
280
+
281
+ Args:
282
+ schema (Dict[str, Any]): The OpenAI tool schema to set.
283
+ """
284
+ self.openai_tool_schema = schema
285
+
286
+ def get_openai_function_schema(self) -> Dict[str, Any]:
287
+ r"""Gets the schema of the function from the OpenAI tool schema.
288
+
289
+ This method extracts and returns the function-specific part of the
290
+ OpenAI tool schema associated with this function.
291
+
292
+ Returns:
293
+ Dict[str, Any]: The schema of the function within the OpenAI tool
294
+ schema.
295
+ """
296
+ self.validate_openai_tool_schema(self.openai_tool_schema)
297
+ return self.openai_tool_schema["function"]
298
+
299
+ def set_openai_function_schema(
300
+ self,
301
+ openai_function_schema: Dict[str, Any],
302
+ ) -> None:
303
+ r"""Sets the schema of the function within the OpenAI tool schema.
304
+
305
+ Args:
306
+ openai_function_schema (Dict[str, Any]): The function schema to set
307
+ within the OpenAI tool schema.
308
+ """
309
+ self.openai_tool_schema["function"] = openai_function_schema
310
+
311
+ def get_function_name(self) -> str:
312
+ r"""Gets the name of the function from the OpenAI tool schema.
313
+
314
+ Returns:
315
+ str: The name of the function.
316
+ """
317
+ return self.openai_tool_schema["function"]["name"]
318
+
319
+ def set_function_name(self, name: str) -> None:
320
+ r"""Sets the name of the function in the OpenAI tool schema.
321
+
322
+ Args:
323
+ name (str): The name of the function to set.
324
+ """
325
+ self.openai_tool_schema["function"]["name"] = name
326
+
327
+ def get_function_description(self) -> str:
328
+ r"""Gets the description of the function from the OpenAI tool
329
+ schema.
330
+
331
+ Returns:
332
+ str: The description of the function.
333
+ """
334
+ self.validate_openai_tool_schema(self.openai_tool_schema)
335
+ return self.openai_tool_schema["function"]["description"]
336
+
337
+ def set_function_description(self, description: str) -> None:
338
+ r"""Sets the description of the function in the OpenAI tool schema.
339
+
340
+ Args:
341
+ description (str): The description for the function.
342
+ """
343
+ self.openai_tool_schema["function"]["description"] = description
344
+
345
+ def get_paramter_description(self, param_name: str) -> str:
346
+ r"""Gets the description of a specific parameter from the function
347
+ schema.
348
+
349
+ Args:
350
+ param_name (str): The name of the parameter to get the
351
+ description.
352
+
353
+ Returns:
354
+ str: The description of the specified parameter.
355
+ """
356
+ self.validate_openai_tool_schema(self.openai_tool_schema)
357
+ return self.openai_tool_schema["function"]["parameters"]["properties"][
358
+ param_name
359
+ ]["description"]
360
+
361
+ def set_paramter_description(
362
+ self,
363
+ param_name: str,
364
+ description: str,
365
+ ) -> None:
366
+ r"""Sets the description for a specific parameter in the function
367
+ schema.
368
+
369
+ Args:
370
+ param_name (str): The name of the parameter to set the description
371
+ for.
372
+ description (str): The description for the parameter.
373
+ """
374
+ self.openai_tool_schema["function"]["parameters"]["properties"][param_name][
375
+ "description"
376
+ ] = description
377
+
378
+ def get_parameter(self, param_name: str) -> Dict[str, Any]:
379
+ r"""Gets the schema for a specific parameter from the function schema.
380
+
381
+ Args:
382
+ param_name (str): The name of the parameter to get the schema.
383
+
384
+ Returns:
385
+ Dict[str, Any]: The schema of the specified parameter.
386
+ """
387
+ self.validate_openai_tool_schema(self.openai_tool_schema)
388
+ return self.openai_tool_schema["function"]["parameters"]["properties"][
389
+ param_name
390
+ ]
391
+
392
+ def set_parameter(self, param_name: str, value: Dict[str, Any]):
393
+ r"""Sets the schema for a specific parameter in the function schema.
394
+
395
+ Args:
396
+ param_name (str): The name of the parameter to set the schema for.
397
+ value (Dict[str, Any]): The schema to set for the parameter.
398
+ """
399
+ try:
400
+ JSONValidator.check_schema(value)
401
+ except SchemaError as e:
402
+ raise e
403
+ self.openai_tool_schema["function"]["parameters"]["properties"][
404
+ param_name
405
+ ] = value
406
+
407
+ @property
408
+ def parameters(self) -> Dict[str, Any]:
409
+ r"""Getter method for the property :obj:`parameters`.
410
+
411
+ Returns:
412
+ Dict[str, Any]: the dictionary containing information of
413
+ parameters of this function.
414
+ """
415
+ self.validate_openai_tool_schema(self.openai_tool_schema)
416
+ return self.openai_tool_schema["function"]["parameters"]["properties"]
417
+
418
+ @parameters.setter
419
+ def parameters(self, value: Dict[str, Any]) -> None:
420
+ r"""Setter method for the property :obj:`parameters`. It will
421
+ firstly check if the input parameters schema is valid. If invalid,
422
+ the method will raise :obj:`jsonschema.exceptions.SchemaError`.
423
+
424
+ Args:
425
+ value (Dict[str, Any]): the new dictionary value for the
426
+ function's parameters.
427
+ """
428
+ try:
429
+ JSONValidator.check_schema(value)
430
+ except SchemaError as e:
431
+ raise e
432
+ self.openai_tool_schema["function"]["parameters"]["properties"] = value
433
+
434
+
435
+ class SkillFunction(OpenAIFunction):
436
+ def __init__(
437
+ self,
438
+ func: Callable,
439
+ openai_tool_schema: Optional[Dict[str, Any]] = None,
440
+ block_as_parameter: Optional[Tuple[str, str]] = None,
441
+ result_process_strategies: Optional[List[Dict[str, str]]] = None,
442
+ owner_skillkit: Optional[
443
+ Any
444
+ ] = None, # Skillkit object (set by Skillkit._bindOwnerToSkills)
445
+ ):
446
+ super().__init__(func, openai_tool_schema)
447
+
448
+ self.owner_skillkit = owner_skillkit
449
+
450
+ self.block_as_parameter = block_as_parameter
451
+ """Strategy for handling tool call results
452
+ Example:
453
+ [
454
+ {"category": "llm", "strategy": "default"},
455
+ {"category": "app", "strategy": "default"},
456
+ ]
457
+ """
458
+ self.result_process_strategies = result_process_strategies or [
459
+ {
460
+ "strategy": "default",
461
+ "category": "llm",
462
+ },
463
+ {
464
+ "strategy": "default",
465
+ "category": "app",
466
+ },
467
+ ]
468
+
469
+ @property
470
+ def owner_name(self) -> Optional[str]:
471
+ """Get the owner skillkit name.
472
+
473
+ Returns the skillkit name via getName() method.
474
+ Returns None if no owner is set.
475
+ """
476
+ if self.owner_skillkit is None:
477
+ return None
478
+ if hasattr(self.owner_skillkit, "getName"):
479
+ return self.owner_skillkit.getName()
480
+ return None
481
+
482
+ def get_owner_skillkit(self) -> Optional[Any]:
483
+ """Get the owner skillkit object."""
484
+ return self.owner_skillkit
485
+
486
+ def set_owner_skillkit(self, owner_skillkit: Optional[Any]) -> None:
487
+ """Set the owner skillkit object."""
488
+ self.owner_skillkit = owner_skillkit
489
+
490
+ def get_block_parameter_info(self):
491
+ return self.block_as_parameter
492
+
493
+ # Get result processing strategy
494
+ def get_result_process_strategies(self):
495
+ return self.result_process_strategies
496
+
497
+ # Get the first available APP strategy
498
+ def get_first_valid_app_strategy(self) -> Optional[str]:
499
+ for strategy in self.result_process_strategies:
500
+ if strategy.get("category") == "app":
501
+ return strategy.get("strategy")
502
+ return None
503
+
504
+ # Get the first available LLM strategy
505
+ def get_first_valid_llm_strategy(self) -> Optional[str]:
506
+ for strategy in self.result_process_strategies:
507
+ if strategy.get("category") == "llm":
508
+ return strategy.get("strategy")
509
+ return None
510
+
511
+
512
+ class DynamicAPISkillFunction(SkillFunction):
513
+ """
514
+ Initialize dynamic API tool
515
+
516
+ Args:
517
+ name: Tool name
518
+ description: Tool description
519
+ parameters: OpenAI function call parameter schema
520
+ api_url: API endpoint URL
521
+ original_schema: Original openapi schema information
522
+ fixed_params: Fixed parameters dictionary
523
+ headers: HTTP tool request headers dictionary (e.g., authentication info: x-account-type, x-account-id)
524
+ result_process_strategies: Result processing strategies (optional), inherited from SkillFunction
525
+ owner_skillkit: Owner skillkit (optional), inherited from SkillFunction
526
+ """
527
+
528
+ def __init__(
529
+ self,
530
+ name: str,
531
+ description: str,
532
+ parameters: Dict[str, Any],
533
+ api_url: str,
534
+ original_schema: Optional[Dict[str, Any]] = None,
535
+ fixed_params: Optional[Dict[str, str]] = None,
536
+ headers: Optional[Dict[str, str]] = None,
537
+ result_process_strategies: Optional[List[Dict[str, str]]] = None,
538
+ owner_skillkit: Optional[Any] = None,
539
+ ):
540
+ # Build OpenAI tool schema
541
+ openai_tool_schema = {
542
+ "type": "function",
543
+ "function": {
544
+ "name": name,
545
+ "description": description,
546
+ "parameters": parameters,
547
+ },
548
+ }
549
+
550
+ # Save dynamic tool-specific attributes (must be done before creating wrapper function)
551
+ self.api_url = api_url
552
+ self.original_schema = original_schema or {}
553
+ self.fixed_params = fixed_params or {}
554
+ self.headers = headers or {}
555
+
556
+ # Create wrapper function that calls arun_stream
557
+ # This ensures Skillkit correctly executes arun_stream when calling self.func
558
+ async def wrapper_func(**kwargs):
559
+ """Wrapper function that calls arun_stream"""
560
+ async for result in self.arun_stream(**kwargs):
561
+ yield result
562
+
563
+ # Call parent class constructor
564
+ super().__init__(
565
+ func=wrapper_func,
566
+ openai_tool_schema=openai_tool_schema,
567
+ result_process_strategies=result_process_strategies,
568
+ owner_skillkit=owner_skillkit,
569
+ )
570
+
571
+ async def arun_stream(self, **kwargs):
572
+ """
573
+ Call action API
574
+
575
+ Args:
576
+ **kwargs: Call parameters (including tool_input, props, gvp, etc.)
577
+
578
+ Yields:
579
+ API call result
580
+ """
581
+ try:
582
+ # Execution policy is carried by the app strategy (see BasicCodeBlock._load_dynamic_tools).
583
+ # Keep backward compatibility: do not hard-fail on unexpected strategy values.
584
+ app_strategy = None
585
+ try:
586
+ app_strategy = self.get_first_valid_app_strategy()
587
+ except Exception:
588
+ app_strategy = None
589
+
590
+ # Extract parameters
591
+ tool_input = kwargs.get("tool_input", {})
592
+ if not isinstance(tool_input, dict):
593
+ tool_input = {}
594
+
595
+ # Extract other parameters from kwargs (excluding system parameters)
596
+ final_params = {
597
+ k: v
598
+ for k, v in kwargs.items()
599
+ if k not in ["tool_input", "props", "gvp"]
600
+ }
601
+ # Merge parameters (tool_input takes priority)
602
+ # final_params = {**params, **tool_input}
603
+ # Apply fixed parameter replacement
604
+ # Handle nested fixed_params structure with body, header, path, query keys
605
+ if isinstance(self.fixed_params, dict):
606
+ # Process body parameters - merge into final_params
607
+ body_params = self.fixed_params.get("body")
608
+ if isinstance(body_params, dict):
609
+ final_params["body"] = final_params.get("body", {})
610
+ if not isinstance(final_params["body"], dict):
611
+ final_params["body"] = {}
612
+ for param_name, fixed_value in body_params.items():
613
+ if fixed_value is not None:
614
+ final_params["body"][param_name] = fixed_value
615
+
616
+ # Process header parameters - merge into final_params (special key)
617
+ header_params = self.fixed_params.get("header")
618
+ if isinstance(header_params, dict):
619
+ final_params["header"] = final_params.get("header", {})
620
+ for header_name, fixed_value in header_params.items():
621
+ if fixed_value is not None:
622
+ final_params["header"][header_name] = str(fixed_value)
623
+
624
+ # Process path parameters - merge into final_params (special key)
625
+ path_params = self.fixed_params.get("path")
626
+ if isinstance(path_params, dict):
627
+ final_params["path"] = final_params.get("path", {})
628
+ for param_name, fixed_value in path_params.items():
629
+ if fixed_value is not None:
630
+ final_params["path"][param_name] = str(fixed_value)
631
+
632
+ # Process query parameters - merge into final_params (special key)
633
+ query_params = self.fixed_params.get("query")
634
+ if isinstance(query_params, dict):
635
+ final_params["query"] = final_params.get("query", {})
636
+ for param_name, fixed_value in query_params.items():
637
+ if fixed_value is not None:
638
+ final_params["query"][param_name] = str(fixed_value)
639
+ else:
640
+ # Backward compatibility: flat fixed_params structure
641
+ for param_name, fixed_value in self.fixed_params.items():
642
+ if fixed_value and param_name in final_params:
643
+ final_params[param_name] = fixed_value
644
+
645
+ # Call API
646
+ async with aiohttp.ClientSession() as session:
647
+ async with session.post(
648
+ self.api_url,
649
+ json=final_params,
650
+ headers=self.headers,
651
+ timeout=aiohttp.ClientTimeout(total=30),
652
+ ) as response:
653
+ if response.status == 200:
654
+ result = await response.json()
655
+ yield result
656
+ else:
657
+ error_msg = f"API call failed: HTTP {response.status}"
658
+ error_text = await response.text()
659
+ yield {"error": error_msg, "details": error_text}
660
+
661
+ except Exception as e:
662
+ error_msg = f"Dynamic API tool execution error: {str(e)}"
663
+ import traceback
664
+
665
+ traceback.print_exc()
666
+ yield {"error": error_msg, "traceback": traceback.format_exc()}
667
+
668
+ def get_openai_tool_schema(self) -> Dict[str, Any]:
669
+ """Gets the OpenAI tool schema for this dynamic function.
670
+
671
+ Override parent method to auto-fill missing parameter descriptions
672
+ instead of raising an error. This is necessary because dynamic tools
673
+ from external APIs may not always provide complete descriptions.
674
+
675
+ Returns:
676
+ Dict[str, Any]: The OpenAI tool schema for this function.
677
+ """
678
+ # Auto-fill missing descriptions for dynamic tools
679
+ schema = self.openai_tool_schema
680
+ if "function" in schema and "parameters" in schema["function"]:
681
+ parameters = schema["function"]["parameters"]
682
+ if "properties" in parameters:
683
+ for param_name, param_dict in parameters["properties"].items():
684
+ if isinstance(param_dict, dict) and "description" not in param_dict:
685
+ param_dict["description"] = f"Parameter: {param_name}"
686
+ return schema