pro-craft 0.2.57__py3-none-any.whl → 0.2.58__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 pro-craft might be problematic. Click here for more details.

@@ -1,660 +0,0 @@
1
- from pro_craft import Intel
2
- from pro_craft.log import Log
3
- from pro_craft.utils import extract_
4
- from typing import List, Dict, Any
5
- from llmada.core import BianXieAdapter
6
- import re
7
- import json
8
-
9
- logger = Log.logger
10
-
11
- intel = Intel(model_name="doubao-1-5-pro-256k-250115")
12
-
13
- class CoderHelper():
14
- def __init__(self):
15
- self.bx = BianXieAdapter()
16
-
17
-
18
- @intel.intellect_remove_warp(prompt_id ="代码修改-最小化改动001")
19
- def minedit_prompt(self,input:dict):
20
- # 可以做pydantic 的校验
21
- input = extract_(input, pattern_key = r"python")
22
- return input
23
-
24
- @intel.intellect_remove_warp(prompt_id ="高定制化自由函数修改_001")
25
- def free_function_prompt(self,input:dict,kwargs):
26
- # 可以做pydantic 的校验
27
- result_ = extract_(input, pattern_key = r"python")
28
- if not result_:
29
- return None
30
-
31
- complet_code = result_ + "\n" + f'result = Function(**{kwargs})'
32
-
33
- rut = {"result": ""}
34
- # 使用exec执行代码,并捕获可能的错误
35
- try:
36
- exec(
37
- complet_code, globals(), rut
38
- ) # 将globals()作为全局作用域,避免依赖外部locals()
39
- except Exception as e:
40
- logger.error(f"执行动态生成的代码时发生错误: {e}")
41
- return None # 返回None或抛出异常
42
-
43
- return rut.get("result")
44
-
45
- def min_edit(self,code:str, edit_demand:str):
46
- input_ = {"源码":code,
47
- "功能需求":edit_demand
48
- }
49
- data = self.minedit_prompt(input = input_)
50
- return data
51
-
52
- def free_function(self,function: str ="帮我将 日期 2025/12/03 向前回退12天",
53
- **kwargs):
54
- # params = locals()
55
- prompt_user_part = f"{function}"
56
- if kwargs:
57
- prompt_user_part += "入参 : \n"
58
- prompt_user_part += json.dumps(kwargs,ensure_ascii=False)
59
-
60
- exec_result = self.free_function_prompt(input = prompt_user_part,kwargs = kwargs)
61
-
62
- return exec_result
63
-
64
-
65
- def free_function_advanced(self):
66
- pass
67
-
68
- class Paper():
69
- def __init__(self,content):
70
- self.content = content
71
-
72
- @intel.intellect_remove_warp(prompt_id ="白板编辑-修改画板001")
73
- def system_prompt(self,data):
74
- return data
75
-
76
- def talk(self,prompt:str):
77
- data = {"data":self.content+ prompt}
78
- result = self.system_prompt(data = data)
79
- # result = bx.product(system_prompt+ self.content+ prompt)
80
- print(result,'result')
81
- result_json = json.loads(extract_(result,pattern_key = r"json"))
82
- print(result_json,'result_json')
83
- for ops in result_json:
84
- self.deal(ops.get('type'), ops.get('operations'))
85
-
86
-
87
- def deal(self, type_, operations:str):
88
- if type_ == "add":
89
- self.add(operations)
90
- elif type_ == "delete":
91
- self.delete(operations)
92
- else:
93
- print('error')
94
-
95
- def add(self, operations:str):
96
- print('add running')
97
- match_tips = re.search(r'<mark>(.*?)</mark>', operations, re.DOTALL)
98
- positon_ = operations.replace(f"<mark>{match_tips.group(1)}</mark>","")
99
- # 锁定原文
100
- positon_frist = operations.replace('<mark>',"").replace('</mark>',"")
101
- print(positon_frist,'positon_frist')
102
- print('==========')
103
- print(positon_,'positon__')
104
- self.content = self.content.replace(positon_,positon_frist)
105
-
106
- def delete(self, operations:str):
107
- # 制定替换内容
108
- print('delete running')
109
- match_tips = re.search(r'<mark>(.*?)</mark>', operations, re.DOTALL)
110
- positon_ = operations.replace(f"<mark>{match_tips.group(1)}</mark>","")
111
- # 锁定原文
112
- positon_frist = operations.replace('<mark>',"").replace('</mark>',"")
113
- print(positon_frist,'positon_frist')
114
- assert positon_frist in self.content
115
- print('==========')
116
- print(positon_,'positon__')
117
-
118
- self.content = self.content.replace(positon_frist,positon_)
119
-
120
-
121
-
122
- mermaid_format = """
123
- ```mermaid
124
- {result}
125
- ```"""
126
-
127
- class ProgramChart():
128
- '''
129
- # ## 有一个原始的程序框图, -> 可以通过需求来调整程序框图 -> 结合数据库来调度程序框图
130
- # 一个新的任务, => 基本需求, -> 根据需求调取之前的程序框图, -> 融合程序框图 -> 调整程序框图到完成满意,-> 由程序框图实现代码, 并拉取出待实现函数
131
- # -> 用知识库中获取代码与对应的测试, 整合到待实现函数中, -> 剩余的使用封装好的包进行补充, -> 创新的补充, -> ...
132
-
133
-
134
- inputs = """
135
- 帮我实现一个文件读取的逻辑
136
- """
137
- program_chart = init_program_chart_mermaid(inputs) # TODO 类图另做吧
138
- # 一直循环, 直到满意
139
- program_chart = finetune_program_chart(program_chart + "如果文件不存在, 就创建")
140
- codes = fill_code_frame_program_chart(program_chart) #TODO 可以尝试配置对应的pytest
141
-
142
- '''
143
-
144
- # TODO 数据用例等, 只是保存, 真正做统计的时候可以导出选择合适的数据
145
-
146
- @intel.intellect_remove_warp(prompt_id="程序框图-根据需求创建")
147
- def init_program_chart_mermaid(self,input_data:str,
148
- output_format:str):
149
- result = extract_(input_data,r"mermaid")
150
- input_ = mermaid_format.format(result = result)
151
-
152
- with open("/Users/zhaoxuefeng/GitHub/obsidian/工作/TODO/1根据需求创建.md",'w') as f:
153
- f.write(input_)
154
- return input_
155
-
156
- @intel.intellect_remove_warp(prompt_id="程序框图-白板微调")
157
- def finetune_program_chart(self,input_data:str,
158
- output_format:str):
159
- print(input_data,'input_datainput_datainput_data')
160
- result = extract_(input_data,r"mermaid")
161
- input_ = mermaid_format.format(result = result)
162
- with open("/Users/zhaoxuefeng/GitHub/obsidian/工作/TODO/1根据需求创建.md",'w') as f:
163
- f.write(input_)
164
- return input_
165
-
166
- @intel.intellect_remove_warp(prompt_id="程序框图-框架实现")
167
- def fill_code_frame_program_chart(self,input:dict):
168
- # result = extract_(input.get("program_chart"),r"python")
169
- code = input.get("program_chart")
170
-
171
- with open("/Users/zhaoxuefeng/GitHub/obsidian/工作/TODO/3框架实现.md",'w') as f:
172
- f.write(code)
173
- return code
174
-
175
- def pc_work(self,chat,fill = False):
176
- self.init_program_chart_mermaid(chat)
177
-
178
- program_chart = self.finetune_program_chart
179
-
180
- code = self.fill_code_frame_program_chart(input = {
181
- "program_chart":program_chart
182
- })
183
-
184
-
185
- ############### web ###############
186
-
187
-
188
- from prompt_writing_assistant.utils import extract_
189
- from llmada.core import BianXieAdapter
190
- from pydantic import BaseModel, Field, ValidationError
191
- from typing import Optional
192
- import re
193
- import json
194
-
195
-
196
- bx = BianXieAdapter()
197
-
198
- port = 8108
199
-
200
- template = '''
201
- from fastapi import FastAPI, HTTPException, Header
202
- from fastapi.middleware.cors import CORSMiddleware
203
- from pydantic import BaseModel, Field, model_validator
204
-
205
- app = FastAPI(
206
- title="LLM Service",
207
- description="Provides an OpenAI-compatible API for custom large language models.",
208
- version="1.0.1",
209
- )
210
-
211
- # --- Configure CORS ---
212
- # ! Add this section !
213
- # Define allowed origins. Be specific in production!
214
- # Example: origins = ["http://localhost:3000", "https://your-frontend-domain.com"]
215
- origins = [
216
- "*", # Allows all origins (convenient for development, insecure for production)
217
- # Add the specific origin of your "别的调度" tool/frontend if known
218
- # e.g., "http://localhost:5173" for a typical Vite frontend dev server
219
- # e.g., "http://127.0.0.1:5173"
220
- ]
221
-
222
- app.add_middleware(
223
- CORSMiddleware,
224
- allow_origins=origins, # Specifies the allowed origins
225
- allow_credentials=True, # Allows cookies/authorization headers
226
- allow_methods=["*"], # Allows all methods (GET, POST, OPTIONS, etc.)
227
- allow_headers=["*"], # Allows all headers (Content-Type, Authorization, etc.)
228
- )
229
- # --- End CORS Configuration ---
230
-
231
-
232
- @app.get("/")
233
- async def root():
234
- """ x """
235
- return {"message": "LLM Service is running."}
236
-
237
-
238
- # --- 新增接口从这里开始 ---
239
-
240
-
241
- # --- 新增接口到这里结束 ---
242
-
243
-
244
- if __name__ == "__main__":
245
- # 这是一个标准的 Python 入口点惯用法
246
- # 当脚本直接运行时 (__name__ == "__main__"),这里的代码会被执行
247
- # 当通过 python -m YourPackageName 执行 __main__.py 时,__name__ 也是 "__main__"
248
- import argparse
249
- import uvicorn
250
-
251
- default = 8008
252
-
253
- parser = argparse.ArgumentParser(
254
- description="Start a simple HTTP server similar to http.server."
255
- )
256
- parser.add_argument(
257
- 'port',
258
- metavar='PORT',
259
- type=int,
260
- nargs='?', # 端口是可选的
261
- default=default,
262
- help=f'Specify alternate port [default: {default}]'
263
- )
264
- # 创建一个互斥组用于环境选择
265
- group = parser.add_mutually_exclusive_group()
266
-
267
- # 添加 --dev 选项
268
- group.add_argument(
269
- '--dev',
270
- action='store_true', # 当存在 --dev 时,该值为 True
271
- help='Run in development mode (default).'
272
- )
273
-
274
- # 添加 --prod 选项
275
- group.add_argument(
276
- '--prod',
277
- action='store_true', # 当存在 --prod 时,该值为 True
278
- help='Run in production mode.'
279
- )
280
- args = parser.parse_args()
281
-
282
- if args.prod:
283
- env = "prod"
284
- else:
285
- # 如果 --prod 不存在,默认就是 dev
286
- env = "dev"
287
-
288
- port = args.port
289
- if env == "dev":
290
- port += 100
291
- reload = True
292
- # 注意:这里是 __name__,因为 server.py 已经包含了 app 对象。
293
- # 如果这个文件是作为包的一部分(例如 your_package.server),
294
- # 则保持原样 f"{__package__}.server:app"
295
- # 如果是直接运行这个文件,则 app_import_string 应该直接是 app
296
- app_import_string = f"{__name__}:app" # <--- 根据实际运行方式调整
297
- # 或者更简单直接传递app对象: app_import_string = app
298
- elif env == "prod":
299
- reload = False
300
- app_import_string = app # 直接传递app对象
301
- else:
302
- reload = False
303
- app_import_string = app # 直接传递app对象
304
-
305
- # 使用 uvicorn.run() 来启动服务器
306
- # 参数对应于命令行选项
307
- uvicorn.run(
308
- app_import_string,
309
- host="0.0.0.0",
310
- port=port,
311
- reload=reload # 启用热重载
312
- )
313
-
314
- '''
315
-
316
-
317
- new_api_prompt = f'''
318
- 我这里有一个fastapi 的代码框架, 不要改变已经存在的任何结构和内容, 只允许新增接口和对新增接口进行修改,
319
-
320
- from fastapi import FastAPI, HTTPException, Header
321
- from fastapi.middleware.cors import CORSMiddleware
322
- from pydantic import BaseModel, Field, model_validator
323
-
324
- app = FastAPI(
325
- title="LLM Service",
326
- description="Provides an OpenAI-compatible API for custom large language models.",
327
- version="1.0.1",
328
- )
329
-
330
- # --- Configure CORS ---
331
- # ! Add this section !
332
- # Define allowed origins. Be specific in production!
333
- # Example: origins = ["http://localhost:3000", "https://your-frontend-domain.com"]
334
- origins = [
335
- "*", # Allows all origins (convenient for development, insecure for production)
336
- # Add the specific origin of your "别的调度" tool/frontend if known
337
- # e.g., "http://localhost:5173" for a typical Vite frontend dev server
338
- # e.g., "http://127.0.0.1:5173"
339
- ]
340
-
341
- app.add_middleware(
342
- CORSMiddleware,
343
- allow_origins=origins, # Specifies the allowed origins
344
- allow_credentials=True, # Allows cookies/authorization headers
345
- allow_methods=["*"], # Allows all methods (GET, POST, OPTIONS, etc.)
346
- allow_headers=["*"], # Allows all headers (Content-Type, Authorization, etc.)
347
- )
348
- # --- End CORS Configuration ---
349
-
350
-
351
- @app.get("/")
352
- async def root():
353
- """ x """
354
- return "LLM Service is running."
355
-
356
-
357
- # --- 新增接口从这里开始 ---
358
-
359
-
360
- # --- 新增接口到这里结束 ---
361
-
362
-
363
- if __name__ == "__main__":
364
- import uvicorn
365
- port = {port}
366
- app_import_string = f"test:app"
367
- uvicorn.run(
368
- app_import_string,
369
- host="0.0.0.0",
370
- port=port,
371
- reload=reload # 启用热重载
372
- )
373
-
374
-
375
- 你只需要输出给我 ```python # --- 新增接口从这里开始 --- , # --- 新增接口到这里结束 ---```, 两者中间的内容即可, 同时, 返回测试接口对应的curl 命令 ```curl ```
376
-
377
-
378
- 这个代码确实已经存在 , 本质上不需要你将它定义出来, 如果你觉得这样方便你叙事, 你可以写在 ```mock <content>``` 中, ``` python ``` 是非常正式的空间, 必须按照要求输出
379
-
380
- '''
381
-
382
-
383
- def replace_whole_section(text, new_content=""):
384
- """
385
- 找到包含 '# --- 新增接口从这里开始 ---' 到 '# --- 新增接口到这里结束 ---'
386
- 的整个段落,并用新内容完全替换掉它。
387
- 开始和结束标记也会被替换掉。
388
-
389
- Args:
390
- text (str): 原始长文本。
391
- new_content (str): 要替换进去的新内容。默认为空字符串,即删除整个段落。
392
-
393
- Returns:
394
- str: 替换后的文本。
395
- """
396
- # 匹配从开始标记到结束标记(包括标记本身)的整个段落
397
- # re.DOTALL (re.S) 使 . 匹配包括换行符在内的所有字符
398
- # re.IGNORECASE (re.I) 如果你需要不区分大小写地匹配标记
399
- pattern = (r"# --- 新增接口从这里开始 ---\s*" # 匹配开始标记和其后的空白符
400
- r".*?" # 非贪婪匹配中间的所有内容
401
- r"\s*# --- 新增接口到这里结束 ---") # 匹配结束标记和其前的空白符
402
-
403
- # 使用 re.sub 进行替换,直接将匹配到的整个部分替换为 new_content
404
- # new_content 可以是多行字符串,re.sub 会正确处理
405
- return re.sub(pattern, new_content, text, flags=re.DOTALL)
406
-
407
-
408
-
409
-
410
-
411
-
412
-
413
- # 使用
414
-
415
- def edit_server(ask:str,output_py = 'temp_web.py'):
416
-
417
- result = bx.product(new_api_prompt + ask )
418
-
419
- # extract
420
- curl_ = extract_(result, pattern_key = r"curl")
421
-
422
- python_ = extract_(result, pattern_key = r"python")
423
-
424
- result = replace_whole_section(text =template, new_content=python_ )
425
-
426
- with open(output_py,'w') as f:
427
- f.write(result)
428
-
429
- return curl_
430
-
431
-
432
-
433
-
434
-
435
-
436
- """
437
- #TODO 维持系统
438
- def
439
- t = {"def":ask,"code":python_, "curl":curl_}
440
-
441
- xxxx = []
442
-
443
- xxxx.append(t)
444
-
445
-
446
- import pandas as pd
447
-
448
- dd = pd.DataFrame(xxxx)
449
-
450
- dd.to_csv('cvs.csv',index=None)
451
-
452
- tt = pd.read_csv('cvs.csv')
453
- """
454
-
455
-
456
-
457
-
458
- system_prompt = '''
459
-
460
- 你是一位专业的 FastAPI 代码生成助手。你的任务是根据用户提供的 Python 函数定义,为其自动生成 FastAPI 接口所需的 Pydantic 模型(用于请求和响应)和格式化的参数字典。
461
-
462
- 请严格遵循以下步骤和要求:
463
-
464
- 1. **用户输入:** 用户将提供一个 Python 函数的完整定义,包括函数签名、类型提示和 docstring。
465
-
466
- 2. **Pydantic 模型生成:**
467
- * 根据函数的输入参数,创建一个 `Request` Pydantic 模型。模型名称应为 `[CoreFunctionName]Request`。
468
- * 根据函数的返回类型,创建一个 `Response` Pydantic 模型。模型名称应为 `[CoreFunctionName]Response`。
469
- * 如果函数的返回类型是基本类型(如 `str`, `int`, `bool`, `float`),则在 `Response` 模型中为其定义一个有意义的字段名,例如 `extracted_json`、`result`、`status` 等。如果返回的是 `dict` 或自定义对象,则直接映射其结构。
470
- * Pydantic 模型的输出格式为 Python 代码块,使用 `from pydantic import BaseModel` 开始。
471
-
472
- 3. **参数字典生成:**
473
- * **`url`**: 根据 `core_function` 的名称生成一个 RESTful 风格的 URL。规则是:将函数名中的下划线替换为斜杠,并将其转换为小写。例如,`extract_json` 变为 `"/extract/json"`。
474
- * **`core_function`**: 直接使用用户提供的 Python 函数的名称。
475
- * **`describe`**: 使用用户提供的 Python 函数的 docstring 作为描述。
476
- * **`request_model`**: 使用你生成的 `Request` Pydantic 模型的类名(例如 `ExtractJsonRequest`)。
477
- * **`request_model_parameter`**: 根据 `Request` 模型中的字段,生成函数调用时参数映射字符串。格式为 `param1=request.param1, param2=request.param2`。
478
- * **`response_model`**: 使用你生成的 `Response` Pydantic 模型的类名(例如 `ExtractJsonResponse`)。
479
- * **`response_model_parameter`**: 根据 `Response` 模型中的字段,生成返回 `Response` 模型实例时参数映射字符串。格式为 `response_field=result` 或 `response_field=result.response_field`(如果 `result` 是一个对象)。
480
- * 参数字典的输出格式为 JSON 代码块,使用 ````json```` 包含。
481
-
482
- 4. **输出结构:** 严格按照以下顺序输出:
483
- * 首先是 Pydantic 模型(Python 代码块)。
484
- * 其次是参数字典(JSON 代码块)。
485
- * 返回测试接口对应的curl 命令 post 8107 ```curl ```(JSON 代码块)。
486
-
487
- **示例输入:**
488
- '''
489
-
490
- system_prompt_get = '''
491
- 你是一位专业的 FastAPI 代码生成助手。你的任务是根据用户提供的 Python 函数定义,为其自动生成 FastAPI `GET` 接口所需的 Pydantic 模型(仅用于响应)和格式化的参数字典。
492
-
493
- 请严格遵循以下步骤和要求:
494
-
495
- 1. **用户输入:** 用户将提供一个 Python 函数的完整定义,包括函数签名、类型提示和 docstring。
496
-
497
- 2. **Pydantic 模型生成:**
498
- * **仅生成 `Response` Pydantic 模型。** `GET` 请求的参数通常直接定义在 FastAPI 路由函数的参数中,或使用 `Query`/`Path` 依赖,而不是通过一个单独的 `Request` Pydantic 模型作为请求体。因此,不需要为 `GET` 生成 `Request` 模型。
499
- * 根据函数的返回类型,创建一个 `Response` Pydantic 模型。模型名称应为 `[CoreFunctionName]Response`。
500
- * 如果函数的返回类型是基本类型(如 `str`, `int`, `bool`, `float`),则在 `Response` 模型中为其定义一个有意义的字段名,例如 `result`、`data`、`status` 等。如果返回的是 `dict` 或自定义对象,则直接映射其结构。
501
- * Pydantic 模型的输出格式为 Python 代码块,使用 `from pydantic import BaseModel` 开始。
502
-
503
- 3. **参数字典生成:**
504
- * **`url`**: 根据 `core_function` 的名称生成一个 RESTful 风格的 URL。规则是:将函数名中的下划线替换为斜杠,并将其转换为小写。例如,`get_user_info` 变为 `"/user/info"`。
505
- * **`core_function`**: 直接使用用户提供的 Python 函数的名称。
506
- * **`describe`**: 使用用户提供的 Python 函数的 docstring 作为描述。
507
- * **`request_model`**: 这里 `request_model` 指的是 FastAPI `GET` 路由函数本身的参数签名。请根据用户函数的所有参数生成一个逗号分隔的参数列表,包含类型提示。例如,如果函数是 `def get_user(user_id: int, name: str = None)`,则 `request_model` 为 `user_id: int, name: str = None`。
508
- * **`request_model_parameter`**: 根据用户函数的所有参数,生成核心函数调用时的参数映射字符串。格式为 `param1=param1, param2=param2`。
509
- * **`response_model`**: 使用你生成的 `Response` Pydantic 模型的类名(例如 `GetUserInfoResponse`)。
510
- * **`response_model_parameter`**: 根据 `Response` 模型中的字段,生成返回 `Response` 模型实例时参数映射字符串。格式为 `response_field=result` 或 `response_field=result.response_field`(如果 `result` 是一个对象)。
511
- * 参数字典的输出格式为 JSON 代码块,使用 ````json```` 包含。
512
-
513
- 4. **输出结构:** 严格按照以下顺序输出:
514
- * 首先是 Pydantic 模型(Python 代码块)。
515
- * 其次是参数字典(JSON 代码块)。
516
-
517
- **示例输入:**
518
- '''
519
-
520
- def gener_get_server(prompt:str):
521
- # prompt 是function
522
- bx = BianXieAdapter()
523
- bx.model_name = "gemini-2.5-flash-preview-05-20-nothinking"
524
- template = '''
525
- @app.get("{url}",
526
- response_model={response_model},
527
- description = "{describe}")
528
- async def {core_function}_server({request_model}):
529
-
530
- logger.info('running {core_function}_server')
531
-
532
- # TODO
533
-
534
- result = {core_function}(
535
- {request_model_parameter}
536
- )
537
- ########
538
- return {response_model}(
539
- {response_model_parameter}
540
- )
541
- '''
542
- result = bx.product(system_prompt_get + prompt)
543
- print(result,'resultresultresult')
544
- xp = json.loads(extract_(result, pattern_key = r"json"))
545
- curl_ = extract_(result, pattern_key = r"curl")
546
- try:
547
- PostDict(**xp)
548
- except ValidationError as e:
549
- raise ValidationError("error") from e
550
- return extract_(result, pattern_key = r"python") + '\n' + template.format(**xp) + "\n" + curl_
551
-
552
-
553
- class PostDict(BaseModel):
554
- """
555
- 期望大模型生成的JSON结构。
556
- """
557
- url: str = Field(..., description="url")
558
- core_function: str = Field(..., description="期待的core 函数")
559
- describe: str | None = Field(..., description="服务函数描述")
560
- request_model: str = Field(..., description="输入请求类型")
561
- request_model_parameter: str = Field(..., description="人物姓名")
562
- response_model: str = Field(..., description="输出")
563
- response_model_parameter: str = Field(..., description="人物姓名")
564
-
565
-
566
- def gener_post_server(prompt:str):
567
- # prompt 是function
568
- bx = BianXieAdapter()
569
- bx.model_name = "gemini-2.5-flash-preview-05-20-nothinking"
570
- template = '''
571
- @app.post("{url}",
572
- response_model={response_model},
573
- description = "{describe}")
574
- async def {core_function}_server(request:{request_model}):
575
-
576
- logger.info('running {core_function}_server')
577
-
578
- # TODO
579
-
580
- result = {core_function}(
581
- {request_model_parameter}
582
- )
583
- ########
584
- return {response_model}(
585
- {response_model_parameter}
586
- )
587
- '''
588
- result = bx.product(system_prompt + prompt)
589
-
590
- xp = json.loads(extract_(result, pattern_key = r"json"))
591
- curl_ = extract_(result, pattern_key = r"curl")
592
- try:
593
- PostDict(**xp)
594
- except ValidationError as e:
595
- raise ValidationError("error") from e
596
- return extract_(result, pattern_key = r"python") + '\n' + template.format(**xp) + "\n" + curl_
597
-
598
-
599
- def gener_post_server_multi(prompt:str):
600
- # prompt 是function
601
- bx = BianXieAdapter()
602
- bx.model_name = "gemini-2.5-flash-preview-05-20-nothinking"
603
- template = '''
604
- @app.post("{url}",
605
- response_model={response_model},
606
- description = "{describe}")
607
- async def {core_function}_server(request:{request_model}):
608
-
609
- logger.info('running {core_function}_server')
610
-
611
- # TODO
612
-
613
- result = {core_function}(
614
- {request_model_parameter}
615
- )
616
- ########
617
- return {response_model}(
618
- {response_model_parameter}
619
- )
620
- '''
621
- result = bx.product(system_prompt + prompt)
622
-
623
- base_models = extract_(result, pattern_key = r"python")
624
- xp_multi,curl_ = extract_(result, pattern_key = r"json",multi = True)
625
- xp_multi = json.loads(xp_multi)
626
- try:
627
- for xp in xp_multi:
628
- PostDict(**xp)
629
- except ValidationError as e:
630
- raise ValidationError("error") from e
631
-
632
- templates = [template.format(**xp) for xp in xp_multi]
633
-
634
- return base_models + '\n' + "\n".join(templates) + "\n" + curl_
635
-
636
- # objects_to_inspect = [Memo, standalone_function, async_standalone_function]
637
- # extracted_defs = extract_from_loaded_objects(objects_to_inspect)
638
-
639
- # for definition in extracted_defs:
640
- # if definition["type"] == "class":
641
- # print(f"Type: {definition['type']}")
642
- # print(f" Name: {definition['name']}")
643
- # print(f" Signature: {definition['signature']}")
644
- # print(f" Docstring: {definition['docstring']}")
645
- # for method in definition["methods"]:
646
- # print(f" Method Name: {method['name']}")
647
- # print(f" Signature: {method['signature']}")
648
- # print(f" Docstring: {method['docstring']}")
649
- # print(f" Is Async: {method['is_async']}")
650
- # print("-" * 20)
651
- # else: # standalone function
652
- # print(f"Type: {definition['type']}")
653
- # print(f" Name: {definition['name']}")
654
- # print(f" Signature: {definition['signature']}")
655
- # print(f" Docstring: {definition['docstring']}")
656
- # print(f" Is Async: {definition['is_async']}")
657
- # print("-" * 20)
658
-
659
-
660
-