veadk-python 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.

Potentially problematic release.


This version of veadk-python might be problematic. Click here for more details.

Files changed (110) hide show
  1. veadk/__init__.py +31 -0
  2. veadk/a2a/__init__.py +13 -0
  3. veadk/a2a/agent_card.py +45 -0
  4. veadk/a2a/remote_ve_agent.py +19 -0
  5. veadk/a2a/ve_a2a_server.py +77 -0
  6. veadk/a2a/ve_agent_executor.py +78 -0
  7. veadk/a2a/ve_task_store.py +37 -0
  8. veadk/agent.py +253 -0
  9. veadk/cli/__init__.py +13 -0
  10. veadk/cli/main.py +278 -0
  11. veadk/cli/services/agentpilot/__init__.py +17 -0
  12. veadk/cli/services/agentpilot/agentpilot.py +77 -0
  13. veadk/cli/services/veapig/__init__.py +17 -0
  14. veadk/cli/services/veapig/apig.py +224 -0
  15. veadk/cli/services/veapig/apig_utils.py +332 -0
  16. veadk/cli/services/vefaas/__init__.py +17 -0
  17. veadk/cli/services/vefaas/template/deploy.py +44 -0
  18. veadk/cli/services/vefaas/template/src/app.py +30 -0
  19. veadk/cli/services/vefaas/template/src/config.py +58 -0
  20. veadk/cli/services/vefaas/vefaas.py +346 -0
  21. veadk/cli/services/vefaas/vefaas_utils.py +408 -0
  22. veadk/cli/services/vetls/__init__.py +17 -0
  23. veadk/cli/services/vetls/vetls.py +87 -0
  24. veadk/cli/studio/__init__.py +13 -0
  25. veadk/cli/studio/agent_processor.py +247 -0
  26. veadk/cli/studio/fast_api.py +232 -0
  27. veadk/cli/studio/model.py +116 -0
  28. veadk/cloud/__init__.py +13 -0
  29. veadk/cloud/cloud_agent_engine.py +144 -0
  30. veadk/cloud/cloud_app.py +123 -0
  31. veadk/cloud/template/app.py +30 -0
  32. veadk/cloud/template/config.py +55 -0
  33. veadk/config.py +131 -0
  34. veadk/consts.py +17 -0
  35. veadk/database/__init__.py +17 -0
  36. veadk/database/base_database.py +45 -0
  37. veadk/database/database_factory.py +80 -0
  38. veadk/database/kv/__init__.py +13 -0
  39. veadk/database/kv/redis_database.py +109 -0
  40. veadk/database/local_database.py +43 -0
  41. veadk/database/relational/__init__.py +13 -0
  42. veadk/database/relational/mysql_database.py +114 -0
  43. veadk/database/vector/__init__.py +13 -0
  44. veadk/database/vector/opensearch_vector_database.py +205 -0
  45. veadk/database/vector/type.py +50 -0
  46. veadk/database/viking/__init__.py +13 -0
  47. veadk/database/viking/viking_database.py +378 -0
  48. veadk/database/viking/viking_memory_db.py +521 -0
  49. veadk/evaluation/__init__.py +17 -0
  50. veadk/evaluation/adk_evaluator/__init__.py +13 -0
  51. veadk/evaluation/adk_evaluator/adk_evaluator.py +291 -0
  52. veadk/evaluation/base_evaluator.py +242 -0
  53. veadk/evaluation/deepeval_evaluator/__init__.py +17 -0
  54. veadk/evaluation/deepeval_evaluator/deepeval_evaluator.py +223 -0
  55. veadk/evaluation/eval_set_file_loader.py +28 -0
  56. veadk/evaluation/eval_set_recorder.py +91 -0
  57. veadk/evaluation/utils/prometheus.py +142 -0
  58. veadk/knowledgebase/__init__.py +17 -0
  59. veadk/knowledgebase/knowledgebase.py +83 -0
  60. veadk/knowledgebase/knowledgebase_database_adapter.py +259 -0
  61. veadk/memory/__init__.py +13 -0
  62. veadk/memory/long_term_memory.py +119 -0
  63. veadk/memory/memory_database_adapter.py +235 -0
  64. veadk/memory/short_term_memory.py +124 -0
  65. veadk/memory/short_term_memory_processor.py +90 -0
  66. veadk/prompts/__init__.py +13 -0
  67. veadk/prompts/agent_default_prompt.py +30 -0
  68. veadk/prompts/prompt_evaluator.py +20 -0
  69. veadk/prompts/prompt_memory_processor.py +55 -0
  70. veadk/prompts/prompt_optimization.py +158 -0
  71. veadk/runner.py +252 -0
  72. veadk/tools/__init__.py +13 -0
  73. veadk/tools/builtin_tools/__init__.py +13 -0
  74. veadk/tools/builtin_tools/lark.py +67 -0
  75. veadk/tools/builtin_tools/las.py +23 -0
  76. veadk/tools/builtin_tools/vesearch.py +49 -0
  77. veadk/tools/builtin_tools/web_scraper.py +76 -0
  78. veadk/tools/builtin_tools/web_search.py +192 -0
  79. veadk/tools/demo_tools.py +58 -0
  80. veadk/tools/load_knowledgebase_tool.py +144 -0
  81. veadk/tools/sandbox/__init__.py +13 -0
  82. veadk/tools/sandbox/browser_sandbox.py +27 -0
  83. veadk/tools/sandbox/code_sandbox.py +30 -0
  84. veadk/tools/sandbox/computer_sandbox.py +27 -0
  85. veadk/tracing/__init__.py +13 -0
  86. veadk/tracing/base_tracer.py +172 -0
  87. veadk/tracing/telemetry/__init__.py +13 -0
  88. veadk/tracing/telemetry/exporters/__init__.py +13 -0
  89. veadk/tracing/telemetry/exporters/apiserver_exporter.py +60 -0
  90. veadk/tracing/telemetry/exporters/apmplus_exporter.py +101 -0
  91. veadk/tracing/telemetry/exporters/base_exporter.py +28 -0
  92. veadk/tracing/telemetry/exporters/cozeloop_exporter.py +69 -0
  93. veadk/tracing/telemetry/exporters/inmemory_exporter.py +88 -0
  94. veadk/tracing/telemetry/exporters/tls_exporter.py +78 -0
  95. veadk/tracing/telemetry/metrics/__init__.py +13 -0
  96. veadk/tracing/telemetry/metrics/opentelemetry_metrics.py +73 -0
  97. veadk/tracing/telemetry/opentelemetry_tracer.py +167 -0
  98. veadk/types.py +23 -0
  99. veadk/utils/__init__.py +13 -0
  100. veadk/utils/logger.py +59 -0
  101. veadk/utils/misc.py +33 -0
  102. veadk/utils/patches.py +85 -0
  103. veadk/utils/volcengine_sign.py +199 -0
  104. veadk/version.py +15 -0
  105. veadk_python-0.1.0.dist-info/METADATA +124 -0
  106. veadk_python-0.1.0.dist-info/RECORD +110 -0
  107. veadk_python-0.1.0.dist-info/WHEEL +5 -0
  108. veadk_python-0.1.0.dist-info/entry_points.txt +2 -0
  109. veadk_python-0.1.0.dist-info/licenses/LICENSE +201 -0
  110. veadk_python-0.1.0.dist-info/top_level.txt +1 -0
veadk/cli/main.py ADDED
@@ -0,0 +1,278 @@
1
+ # Copyright (c) 2025 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import annotations
16
+
17
+ import importlib.util
18
+ import os
19
+ import shutil
20
+ import sys
21
+ from pathlib import Path
22
+
23
+ import typer
24
+ import uvicorn
25
+
26
+ from veadk.utils.logger import get_logger
27
+ from veadk.version import VERSION
28
+
29
+ logger = get_logger(__name__)
30
+
31
+ app = typer.Typer(name="vego")
32
+
33
+
34
+ @app.command()
35
+ def init():
36
+ """Init a veadk project that can be deployed to Volcengine VeFaaS."""
37
+ from rich.prompt import Confirm, Prompt
38
+
39
+ cwd = Path.cwd()
40
+ template_dir = Path(__file__).parent.resolve() / "services" / "vefaas" / "template"
41
+
42
+ name = Prompt.ask("Project name", default="veadk-cloud-agent")
43
+
44
+ target_dir = cwd / name
45
+
46
+ if target_dir.exists():
47
+ response = Confirm.ask(
48
+ f"Target directory '{target_dir}' already exists, do you want to overwrite it?: "
49
+ )
50
+ if not response:
51
+ print("Operation cancelled.")
52
+ return
53
+ else:
54
+ shutil.rmtree(target_dir) # 删除旧目录
55
+ print(f"Deleted existing directory: {target_dir}")
56
+
57
+ shutil.copytree(template_dir, target_dir)
58
+ print(f"Created new project: {name}")
59
+
60
+
61
+ # @app.command()
62
+ # def web(
63
+ # path: str = typer.Option(".", "--path", help="Agent project path"),
64
+ # ):
65
+ # from google.adk.cli import cli_tools_click
66
+
67
+ # def my_decorator(func):
68
+ # @wraps(func)
69
+ # def wrapper(*args, **kwargs):
70
+ # adk_app: FastAPI = func(*args, **kwargs)
71
+ # import importlib.util
72
+ # import mimetypes
73
+
74
+ # from fastapi.staticfiles import StaticFiles
75
+
76
+ # mimetypes.add_type("application/javascript", ".js", True)
77
+ # mimetypes.add_type("text/javascript", ".js", True)
78
+
79
+ # spec = importlib.util.find_spec("veadk.cli.browser")
80
+ # if spec is not None:
81
+ # ANGULAR_DIST_PATH = spec.submodule_search_locations[0]
82
+ # logger.info(f"Static source path: {ANGULAR_DIST_PATH}")
83
+ # else:
84
+ # raise Exception("veadk.cli.browser not found")
85
+
86
+ # # ----- 8< Unmount app -----
87
+ # from starlette.routing import Mount
88
+
89
+ # for index, route in enumerate(adk_app.routes):
90
+ # if isinstance(route, Mount) and route.path == "/dev-ui":
91
+ # del adk_app.routes[index]
92
+ # break
93
+ # # ----- 8< Mount our app -----
94
+
95
+ # adk_app.mount(
96
+ # "/dev-ui/",
97
+ # StaticFiles(directory=ANGULAR_DIST_PATH, html=True),
98
+ # name="static",
99
+ # )
100
+
101
+ # from fastapi.middleware.cors import CORSMiddleware
102
+
103
+ # adk_app.add_middleware(
104
+ # CORSMiddleware,
105
+ # allow_origins=["*"],
106
+ # allow_credentials=True,
107
+ # allow_methods=["*"],
108
+ # allow_headers=["*"],
109
+ # )
110
+ # return adk_app
111
+
112
+ # return wrapper
113
+
114
+ # # Monkey patch
115
+ # fast_api.get_fast_api_app = my_decorator(fast_api.get_fast_api_app)
116
+
117
+ # # reload cli_tools_click
118
+ # importlib.reload(cli_tools_click)
119
+
120
+ # agents_dir = str(Path(path).resolve())
121
+ # logger.info(f"Agents dir is {agents_dir}")
122
+ # cli_tools_click.cli_web.main(args=[agents_dir])
123
+
124
+
125
+ @app.command()
126
+ def web(
127
+ session_service_uri: str = typer.Option(
128
+ None,
129
+ "--session_service_uri",
130
+ ),
131
+ ):
132
+ from google.adk.memory import in_memory_memory_service
133
+
134
+ from veadk.memory.long_term_memory import LongTermMemory
135
+
136
+ in_memory_memory_service.InMemoryMemoryService = LongTermMemory
137
+
138
+ from google.adk.cli import cli_tools_click
139
+
140
+ importlib.reload(cli_tools_click)
141
+ agents_dir = os.getcwd()
142
+ if not session_service_uri:
143
+ session_service_uri = ""
144
+
145
+ cli_tools_click.cli_web.main(
146
+ args=[agents_dir, "--session_service_uri", session_service_uri]
147
+ )
148
+
149
+
150
+ @app.command()
151
+ def studio(
152
+ path: str = typer.Option(".", "--path", help="Project path"),
153
+ ):
154
+ path = Path(path).resolve()
155
+
156
+ from veadk.cli.studio.fast_api import get_fast_api_app
157
+
158
+ app = get_fast_api_app(agents_dir=str(path))
159
+
160
+ uvicorn.run(
161
+ app,
162
+ host="127.0.0.1",
163
+ port=8000,
164
+ log_level="info",
165
+ loop="asyncio", # for deepeval
166
+ )
167
+
168
+
169
+ @app.command()
170
+ def prompt(
171
+ path: str = typer.Option(
172
+ ...,
173
+ "--path",
174
+ help="Your agent file path. Please ensure that your agent(s) are global variable(s).",
175
+ ),
176
+ feedback: str = typer.Option(
177
+ "",
178
+ "--feedback",
179
+ help="Feedback of prompt from agent evaluation.",
180
+ ),
181
+ api_key: str = typer.Option(
182
+ ..., "--api-key", help="API Key of AgentPilot Platform"
183
+ ),
184
+ model_name: str = typer.Option(
185
+ "doubao-1.5-pro-32k-250115",
186
+ "--model-name",
187
+ help="Model name for prompt optimization",
188
+ ),
189
+ ):
190
+ from veadk import Agent
191
+
192
+ """
193
+ NOTE(nkfyz): Detecting agents from a file is not fully correct, we will fix this feature asap.
194
+ """
195
+ module_name = "veadk_agent"
196
+ path = Path(path).resolve()
197
+ logger.info(f"Detect agents in {path}")
198
+
199
+ spec = importlib.util.spec_from_file_location(module_name, path)
200
+ module = importlib.util.module_from_spec(spec)
201
+ sys.modules[module_name] = module
202
+ spec.loader.exec_module(module)
203
+ globals_in_module = vars(module) # get all global variables in module
204
+
205
+ agents = []
206
+ for global_variable_name, global_variable_value in globals_in_module.items():
207
+ if isinstance(global_variable_value, Agent):
208
+ agent = global_variable_value
209
+ agents.append(agent)
210
+ logger.info(f"Found {len(agents)} agent(s) in {path}")
211
+
212
+ if len(agents) == 0:
213
+ logger.info(
214
+ "No agent found. Please put your agent definition as a global variable in your agent file."
215
+ )
216
+ print(
217
+ f"No agent found in {path}. Please put your agent definition as a global variable in your agent file."
218
+ )
219
+ return
220
+
221
+ from veadk.cli.services.agentpilot import AgentPilot
222
+
223
+ ap = AgentPilot(api_key)
224
+ ap.optimize(agents=agents, feedback=feedback, model_name=model_name)
225
+
226
+
227
+ # @app.command()
228
+ # def studio():
229
+ # import os
230
+
231
+ # # pre-load
232
+ # from veadk import Agent # noqa
233
+
234
+ # os.environ["VEADK_STUDIO_AGENTS_DIR"] = os.getcwd()
235
+ # app_path = os.path.join(os.path.dirname(__file__), "../../app/app.py")
236
+
237
+ # os.system(f"streamlit run {app_path}")
238
+
239
+
240
+ @app.command()
241
+ def deploy(
242
+ access_key: str = typer.Option(..., "--access-key", help="Access Key"),
243
+ secret_key: str = typer.Option(..., "--secret-key", help="Secret Key"),
244
+ name: str = typer.Option(..., "--name", help="Deployment name"),
245
+ path: str = typer.Option(".", "--path", help="Project path"),
246
+ ):
247
+ from veadk.cli.services.vefaas import VeFaaS
248
+
249
+ path = Path(path).resolve()
250
+ vefaas = VeFaaS(access_key, secret_key)
251
+ vefaas.deploy(name=name, path=path)
252
+
253
+
254
+ @app.command()
255
+ def log(
256
+ access_key: str = typer.Option(..., "--access-key", help="Access Key"),
257
+ secret_key: str = typer.Option(..., "--secret-key", help="Secret Key"),
258
+ query: str = typer.Option(..., "--query", help="Query statement"),
259
+ topic_id: str = typer.Option(..., "--topic-id", help="Topic ID in VeTLS"),
260
+ dump_path: str = typer.Option(
261
+ ".", "--dump-path", help="Local path for log storage file"
262
+ ),
263
+ ):
264
+ path = Path(dump_path).resolve()
265
+
266
+ from veadk.cli.services.vetls import VeTLS
267
+
268
+ vetls = VeTLS(access_key, secret_key, dump_path=str(path))
269
+ vetls.query(topic_id=topic_id, query=query)
270
+
271
+
272
+ @app.command()
273
+ def version():
274
+ print(f"VeADK {VERSION}")
275
+
276
+
277
+ if __name__ == "__main__":
278
+ app()
@@ -0,0 +1,17 @@
1
+ # Copyright (c) 2025 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from .agentpilot import AgentPilot
16
+
17
+ __all__ = ["AgentPilot"]
@@ -0,0 +1,77 @@
1
+ # Copyright (c) 2025 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import annotations
16
+
17
+ import agent_pilot as ap
18
+ from agent_pilot.models import TaskType
19
+
20
+ from veadk import Agent
21
+ from veadk.prompts import prompt_optimization
22
+ from veadk.utils.logger import get_logger
23
+
24
+ logger = get_logger(__name__)
25
+
26
+
27
+ class AgentPilot:
28
+ def __init__(self, api_key: str, path: str = "", task_id: str = None) -> None:
29
+ self.api_key = api_key
30
+ self.path = path
31
+ self.task_id = task_id
32
+
33
+ def optimize(
34
+ self,
35
+ agents: list[Agent],
36
+ feedback: str = "",
37
+ model_name: str = "doubao-1.5-pro-32k-250115",
38
+ ) -> str:
39
+ for idx, agent in enumerate(agents):
40
+ optimized_prompt = ""
41
+ if feedback == "":
42
+ logger.info("Optimizing prompt without feedback.")
43
+ task_description = prompt_optimization.render_prompt_with_jinja2(agent)
44
+ else:
45
+ logger.info(f"Optimizing prompt with feedback: {feedback}")
46
+ task_description = (
47
+ prompt_optimization.render_prompt_feedback_with_jinja2(
48
+ agent, feedback
49
+ )
50
+ )
51
+
52
+ logger.info(
53
+ f"Optimizing prompt for agent {agent.name} by {model_name} [{idx + 1}/{len(agents)}]"
54
+ )
55
+
56
+ usage = None
57
+ for chunk in ap.generate_prompt_stream(
58
+ task_description=task_description,
59
+ current_prompt=agent.instruction,
60
+ model_name=model_name,
61
+ task_type=TaskType.DIALOG,
62
+ temperature=1.0,
63
+ top_p=0.7,
64
+ api_key=self.api_key,
65
+ ): # stream chunks of optimized prompt
66
+ # Process each chunk as it arrives
67
+ optimized_prompt += chunk.data.content
68
+ # print(chunk.data.content, end="", flush=True)
69
+ if chunk.event == "usage":
70
+ usage = chunk.data.usage
71
+ optimized_prompt = optimized_prompt.replace("\\n", "\n")
72
+ print(f"Optimized prompt for agent {agent.name}:\n{optimized_prompt}")
73
+ logger.info(f"Token usage: {usage['total_tokens']}")
74
+
75
+ return optimized_prompt
76
+ return optimized_prompt
77
+ return optimized_prompt
@@ -0,0 +1,17 @@
1
+ # Copyright (c) 2025 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from .apig import APIGateway
16
+
17
+ __all__ = ["APIGateway"]
@@ -0,0 +1,224 @@
1
+ # Copyright (c) 2025 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import time
16
+
17
+ import volcenginesdkcore
18
+ from volcenginesdkapig import (
19
+ APIGApi,
20
+ ListGatewaysRequest,
21
+ UpstreamSpecForCreateUpstreamInput,
22
+ VeFaasForCreateUpstreamInput,
23
+ )
24
+ from volcenginesdkapig20221112 import APIG20221112Api, UpstreamListForCreateRouteInput
25
+
26
+
27
+ class APIGateway:
28
+ def __init__(self, access_key: str, secret_key: str, region: str = "cn-beijing"):
29
+ self.ak = access_key
30
+ self.sk = secret_key
31
+ self.region = region
32
+ configuration = volcenginesdkcore.Configuration()
33
+ configuration.ak = self.ak
34
+ configuration.sk = self.sk
35
+ configuration.region = region
36
+
37
+ self.api_client = volcenginesdkcore.ApiClient(configuration=configuration)
38
+ self.apig_20221112_client = APIG20221112Api(api_client=self.api_client)
39
+ self.apig_client = APIGApi(api_client=self.api_client)
40
+
41
+ def list_gateways(self):
42
+ request = ListGatewaysRequest()
43
+ thread = self.apig_client.list_gateways(request, async_req=True)
44
+ result = thread.get()
45
+ return result
46
+
47
+ def create_serverless_gateway(self, instance_name: str) -> str: # instance
48
+ from volcenginesdkapig import (
49
+ CreateGatewayRequest,
50
+ ResourceSpecForCreateGatewayInput,
51
+ )
52
+
53
+ request = CreateGatewayRequest(
54
+ name=instance_name,
55
+ region=self.region,
56
+ type="serverless",
57
+ resource_spec=ResourceSpecForCreateGatewayInput(
58
+ replicas=2,
59
+ instance_spec_code="1c2g",
60
+ clb_spec_code="small_1",
61
+ public_network_billing_type="traffic",
62
+ network_type={
63
+ "EnablePublicNetwork": True,
64
+ "EnablePrivateNetwork": False,
65
+ },
66
+ ),
67
+ )
68
+ thread = self.apig_client.create_gateway(request, async_req=True)
69
+ result = thread.get()
70
+ gateway_id = result.to_dict()["id"]
71
+
72
+ found = False
73
+ while not found:
74
+ request = ListGatewaysRequest()
75
+ thread = self.apig_client.list_gateways(request, async_req=True)
76
+ result = thread.get()
77
+ for item in result.items:
78
+ if (
79
+ item.to_dict()["id"] == gateway_id
80
+ and item.to_dict()["status"] == "Running"
81
+ ):
82
+ found = True
83
+ break
84
+ if not found:
85
+ time.sleep(5)
86
+ return gateway_id
87
+
88
+ def create_gateway_service(self, gateway_id: str, service_name: str) -> str:
89
+ """
90
+ Create a gateway service. (Domain name)
91
+ Args:
92
+ gateway_id (str): The ID of the gateway to which the service belongs.
93
+ service_name (str): The name of the service to be created.
94
+ Returns:
95
+ str: The ID of the created service.
96
+ """
97
+ from volcenginesdkapig import (
98
+ AuthSpecForCreateGatewayServiceInput,
99
+ CreateGatewayServiceRequest,
100
+ )
101
+
102
+ request = CreateGatewayServiceRequest(
103
+ gateway_id=gateway_id,
104
+ service_name=service_name,
105
+ protocol=["HTTP", "HTTPS"],
106
+ auth_spec=AuthSpecForCreateGatewayServiceInput(enable=False),
107
+ )
108
+ thread = self.apig_client.create_gateway_service(request, async_req=True)
109
+ result = thread.get()
110
+ return result.to_dict()["id"]
111
+
112
+ def create_upstream(self, function_id: str, gateway_id: str, upstream_name: str):
113
+ from volcenginesdkapig import CreateUpstreamRequest
114
+
115
+ request = CreateUpstreamRequest(
116
+ gateway_id=gateway_id,
117
+ name=upstream_name,
118
+ source_type="VeFaas",
119
+ upstream_spec=UpstreamSpecForCreateUpstreamInput(
120
+ ve_faas=VeFaasForCreateUpstreamInput(function_id=function_id)
121
+ ),
122
+ )
123
+ thread = self.apig_client.create_upstream(request, async_req=True)
124
+ result = thread.get()
125
+ return result.to_dict()["id"]
126
+
127
+ def create_gateway_service_routes(
128
+ self, service_id: str, upstream_id: str, route_name: str, match_rule: dict
129
+ ):
130
+ """
131
+ Create gateway service routes.
132
+
133
+ Args:
134
+ service_id (str): The ID of the gateway service, used to specify the target service for which the route is to be created.
135
+ upstream_id (str): The ID of the upstream service, to which the route will point.
136
+ route_name (str): The name of the route to be created.
137
+ match_rule (dict): The route matching rule, containing the following key - value pairs:
138
+ - match_content (str): The path matching content, a string like "/abc", used to specify the path to be matched.
139
+ - match_type (str): The path matching type, with optional values "Exact", "Regex", "Prefix".
140
+ - match_method (list[str]): The list of HTTP request methods, possible values include "GET", "POST", etc.
141
+ Returns:
142
+ str: The ID of the created route.
143
+ """
144
+ from volcenginesdkapig20221112 import (
145
+ CreateRouteRequest,
146
+ MatchRuleForCreateRouteInput,
147
+ PathForCreateRouteInput,
148
+ )
149
+
150
+ match_content: str = match_rule["match_content"]
151
+ match_type: str = match_rule["match_type"]
152
+ match_method: list[str] = match_rule["match_method"]
153
+
154
+ request = CreateRouteRequest(
155
+ service_id=service_id,
156
+ enable=True,
157
+ match_rule=MatchRuleForCreateRouteInput(
158
+ path=PathForCreateRouteInput(
159
+ match_content=match_content, match_type=match_type
160
+ ),
161
+ method=match_method,
162
+ ),
163
+ name=route_name,
164
+ priority=1,
165
+ upstream_list=[
166
+ UpstreamListForCreateRouteInput(
167
+ upstream_id=upstream_id,
168
+ weight=1,
169
+ )
170
+ ],
171
+ )
172
+
173
+ thread = self.apig_20221112_client.create_route(request, async_req=True)
174
+ result = thread.get()
175
+ return result.to_dict()["id"]
176
+
177
+ def create(
178
+ self,
179
+ function_id: str,
180
+ apig_instance_name: str,
181
+ service_name: str,
182
+ upstream_name: str,
183
+ routes: list[dict],
184
+ ):
185
+ """
186
+ Create an API gateway instance, service, and multiple routes.
187
+
188
+ Args:
189
+ function_id (str): The ID of the function to be associated with the routes.
190
+ apig_instance_name (str): The name of the API gateway instance.
191
+ service_name (str): The name of the service to be created.
192
+ upstream_name (str): The name of the upstream service to be created.
193
+ routes (list[dict]): A list of route configurations. Each dictionary in the list contains the following key - value pairs:
194
+ - route_name (str): The name of the route to be created.
195
+ - match_content (str): The path matching content, a string like "/abc", used to specify the path to be matched.
196
+ - match_type (str): The path matching type, with optional values "Exact", "Regex", "Prefix".
197
+ - match_method (list[str]): The list of HTTP request methods, possible values include "GET", "POST", etc.
198
+
199
+ Returns:
200
+ dict: A dictionary containing the IDs of the created gateway, service, upstream, and routes.
201
+ """
202
+ gateway_id = self.create_serverless_gateway(apig_instance_name)
203
+ service_id = self.create_gateway_service(gateway_id, service_name)
204
+ upstream_id = self.create_upstream(function_id, gateway_id, upstream_name)
205
+
206
+ route_ids = []
207
+ for route in routes:
208
+ route_name = route["route_name"]
209
+ match_rule = {
210
+ "match_content": route["match_content"],
211
+ "match_type": route["match_type"],
212
+ "match_method": route["match_method"],
213
+ }
214
+ route_id = self.create_gateway_service_routes(
215
+ service_id, upstream_id, route_name, match_rule
216
+ )
217
+ route_ids.append(route_id)
218
+
219
+ return {
220
+ "gateway_id": gateway_id,
221
+ "service_id": service_id,
222
+ "upstream_id": upstream_id,
223
+ "route_ids": route_ids,
224
+ }