pro-craft 0.1.14__py3-none-any.whl → 0.1.16__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.
- pro_craft/__init__.py +2 -4
- pro_craft/code_helper/coder.py +1 -1
- pro_craft/file_manager.py +2 -3
- pro_craft/prompt_craft/__init__.py +3 -0
- pro_craft/prompt_craft/async_.py +633 -0
- pro_craft/prompt_craft/evals.py +61 -0
- pro_craft/prompt_craft/new.py +605 -0
- pro_craft/prompt_craft/sync.py +602 -0
- pro_craft/server/mcp/{weather.py → prompt.py} +1 -2
- pro_craft/server/router/prompt.py +1 -2
- {pro_craft-0.1.14.dist-info → pro_craft-0.1.16.dist-info}/METADATA +1 -1
- pro_craft-0.1.16.dist-info/RECORD +20 -0
- pro_craft-0.1.14.dist-info/RECORD +0 -15
- {pro_craft-0.1.14.dist-info → pro_craft-0.1.16.dist-info}/WHEEL +0 -0
- {pro_craft-0.1.14.dist-info → pro_craft-0.1.16.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
|
|
2
|
+
import json
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
############evals##############
|
|
6
|
+
|
|
7
|
+
# 异步
|
|
8
|
+
class Base_Evals():
|
|
9
|
+
def __init__(self):
|
|
10
|
+
"""
|
|
11
|
+
# TODO 2 自动优化prompt 并提升稳定性, 并测试
|
|
12
|
+
通过重写继承来使用它
|
|
13
|
+
"""
|
|
14
|
+
self.MIN_SUCCESS_RATE = 00.0 # 这里定义通过阈值, 高于该比例则通过
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
async def _assert_eval_function(self,params):
|
|
18
|
+
#这里定义函数的评价体系
|
|
19
|
+
print(params,'params')
|
|
20
|
+
|
|
21
|
+
async def get_success_rate(self,test_cases:list[tuple]):
|
|
22
|
+
"""
|
|
23
|
+
# 这里定义数据
|
|
24
|
+
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
successful_assertions = 0
|
|
28
|
+
total_assertions = len(test_cases)
|
|
29
|
+
result_cases = []
|
|
30
|
+
|
|
31
|
+
for i, params in enumerate(test_cases):
|
|
32
|
+
try:
|
|
33
|
+
# 这里将参数传入
|
|
34
|
+
await self._assert_eval_function(params)
|
|
35
|
+
successful_assertions += 1
|
|
36
|
+
result_cases.append({"type":"Successful","--input--":params,"evaluate_info":f"满足要求"})
|
|
37
|
+
except AssertionError as e:
|
|
38
|
+
result_cases.append({"type":"FAILED","--input--":params,"evaluate_info":f"ERROR {e}"})
|
|
39
|
+
except Exception as e: # 捕获其他可能的错误
|
|
40
|
+
result_cases.append({"type":"FAILED","--input--":params,"evaluate_info":f"ERROR {e}"})
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
success_rate = (successful_assertions / total_assertions) * 100
|
|
44
|
+
print(f"\n--- Aggregated Results ---")
|
|
45
|
+
print(f"Total test cases: {total_assertions}")
|
|
46
|
+
print(f"Successful cases: {successful_assertions}")
|
|
47
|
+
print(f"Success Rate: {success_rate:.2f}%")
|
|
48
|
+
|
|
49
|
+
if success_rate >= self.MIN_SUCCESS_RATE:
|
|
50
|
+
return "通过", json.dumps(result_cases,ensure_ascii=False)
|
|
51
|
+
else:
|
|
52
|
+
return "未通过",json.dumps(result_cases,ensure_ascii=False)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def global_evals():
|
|
56
|
+
pass
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
|
|
@@ -0,0 +1,605 @@
|
|
|
1
|
+
# 测试1
|
|
2
|
+
|
|
3
|
+
from pro_craft.utils import extract_
|
|
4
|
+
from pro_craft import logger as pro_craft_logger
|
|
5
|
+
from pro_craft.database import Prompt, UseCase, PromptBase
|
|
6
|
+
from pro_craft.utils import create_session, create_async_session
|
|
7
|
+
from llmada.core import BianXieAdapter, ArkAdapter
|
|
8
|
+
from datetime import datetime
|
|
9
|
+
from enum import Enum
|
|
10
|
+
import functools
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
from sqlalchemy import create_engine
|
|
14
|
+
from pro_craft.database import SyncMetadata
|
|
15
|
+
import inspect
|
|
16
|
+
from datetime import datetime, timedelta
|
|
17
|
+
from json.decoder import JSONDecodeError
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
BATCH_SIZE = 1000
|
|
21
|
+
|
|
22
|
+
class IntellectRemoveFormatError(Exception):
|
|
23
|
+
pass
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def slog(s, target: str = "target",logger = None):
|
|
27
|
+
COLOR_GREEN = "\033[92m"
|
|
28
|
+
COLOR_RESET = "\033[0m" # 重置颜色
|
|
29
|
+
logger("\n"+f"{COLOR_GREEN}=={COLOR_RESET}" * 50)
|
|
30
|
+
logger(target + "\n "+"--" * 40)
|
|
31
|
+
logger(type(s))
|
|
32
|
+
logger(s)
|
|
33
|
+
logger("\n"+f"{COLOR_GREEN}=={COLOR_RESET}" * 50)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def get_last_sync_time(target_session) -> datetime:
|
|
39
|
+
"""从目标数据库获取上次同步时间"""
|
|
40
|
+
metadata_entry = target_session.query(SyncMetadata).filter_by(table_name="sync_metadata").first()
|
|
41
|
+
if metadata_entry:
|
|
42
|
+
return metadata_entry.last_sync_time
|
|
43
|
+
return datetime(1970, 1, 1) # 默认一个很早的时间
|
|
44
|
+
|
|
45
|
+
def update_last_sync_time(target_session, new_sync_time: datetime):
|
|
46
|
+
"""更新目标数据库的上次同步时间"""
|
|
47
|
+
metadata_entry = target_session.query(SyncMetadata).filter_by(table_name="sync_metadata").first()
|
|
48
|
+
if metadata_entry:
|
|
49
|
+
metadata_entry.last_sync_time = new_sync_time
|
|
50
|
+
else:
|
|
51
|
+
# 如果不存在,则创建
|
|
52
|
+
new_metadata = SyncMetadata(table_name="sync_metadata", last_sync_time=new_sync_time)
|
|
53
|
+
target_session.add(new_metadata)
|
|
54
|
+
target_session.commit()
|
|
55
|
+
print(f"Updated last sync time to: {new_sync_time}")
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class IntellectType(Enum):
|
|
60
|
+
train = "train"
|
|
61
|
+
inference = "inference"
|
|
62
|
+
summary = "summary"
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class IntelNew():
|
|
67
|
+
def __init__(self,
|
|
68
|
+
database_url = "",
|
|
69
|
+
model_name = "",
|
|
70
|
+
logger = None,
|
|
71
|
+
):
|
|
72
|
+
database_url = database_url or os.getenv("database_url")
|
|
73
|
+
assert database_url
|
|
74
|
+
self.engine = create_engine(database_url, echo=False, # echo=True 仍然会打印所有执行的 SQL 语句
|
|
75
|
+
pool_size=10, # 连接池中保持的连接数
|
|
76
|
+
max_overflow=20, # 当pool_size不够时,允许临时创建的额外连接数
|
|
77
|
+
pool_recycle=3600, # 每小时回收一次连接
|
|
78
|
+
pool_pre_ping=True, # 使用前检查连接活性
|
|
79
|
+
pool_timeout=30 # 等待连接池中连接的最长时间(秒)
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
PromptBase.metadata.create_all(self.engine)
|
|
83
|
+
|
|
84
|
+
if model_name in ["gemini-2.5-flash-preview-05-20-nothinking",]:
|
|
85
|
+
self.llm = BianXieAdapter(model_name = model_name)
|
|
86
|
+
elif model_name in ["doubao-1-5-pro-256k-250115",]:
|
|
87
|
+
self.llm = ArkAdapter(model_name = model_name)
|
|
88
|
+
else:
|
|
89
|
+
print('Use BianXieAdapter')
|
|
90
|
+
self.llm = BianXieAdapter()
|
|
91
|
+
self.logger = logger or pro_craft_logger
|
|
92
|
+
|
|
93
|
+
def _get_latest_prompt_version(self,target_prompt_id,session):
|
|
94
|
+
"""
|
|
95
|
+
获取指定 prompt_id 的最新版本数据,通过创建时间判断。
|
|
96
|
+
"""
|
|
97
|
+
result = session.query(Prompt).filter(
|
|
98
|
+
Prompt.prompt_id == target_prompt_id
|
|
99
|
+
).order_by(
|
|
100
|
+
Prompt.timestamp.desc(),
|
|
101
|
+
Prompt.version.desc()
|
|
102
|
+
).first()
|
|
103
|
+
return result
|
|
104
|
+
|
|
105
|
+
def _get_specific_prompt_version(self,target_prompt_id, target_version,session):
|
|
106
|
+
"""
|
|
107
|
+
获取指定 prompt_id 和特定版本的数据。
|
|
108
|
+
|
|
109
|
+
Args:
|
|
110
|
+
target_prompt_id (str): 目标提示词的唯一标识符。
|
|
111
|
+
target_version (int): 目标提示词的版本号。
|
|
112
|
+
table_name (str): 存储提示词数据的数据库表名。
|
|
113
|
+
db_manager (DBManager): 数据库管理器的实例,用于执行查询。
|
|
114
|
+
|
|
115
|
+
Returns:
|
|
116
|
+
dict or None: 如果找到,返回包含 id, prompt_id, version, timestamp, prompt 字段的字典;
|
|
117
|
+
否则返回 None。
|
|
118
|
+
"""
|
|
119
|
+
result = session.query(Prompt).filter(
|
|
120
|
+
Prompt.prompt_id == target_prompt_id,
|
|
121
|
+
Prompt.version == target_version
|
|
122
|
+
).first() # 因为 (prompt_id, version) 是唯一的,所以 first() 足够
|
|
123
|
+
return result
|
|
124
|
+
|
|
125
|
+
def sync_prompt_data_to_database(self,database_url:str):
|
|
126
|
+
target_engine = create_engine(database_url, echo=False)
|
|
127
|
+
PromptBase.metadata.create_all(target_engine)
|
|
128
|
+
|
|
129
|
+
with create_session(self.engine) as source_session:
|
|
130
|
+
with create_session(target_engine) as target_session:
|
|
131
|
+
last_sync_time = get_last_sync_time(target_session)
|
|
132
|
+
print(f"Starting sync for sync_metadata from: {last_sync_time}")
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
processed_count = 0
|
|
136
|
+
current_batch_max_updated_at = last_sync_time
|
|
137
|
+
|
|
138
|
+
while True:
|
|
139
|
+
records_to_sync = source_session.query(Prompt)\
|
|
140
|
+
.filter(Prompt.timestamp > last_sync_time)\
|
|
141
|
+
.order_by(Prompt.timestamp.asc(), Prompt.id.asc())\
|
|
142
|
+
.limit(BATCH_SIZE)\
|
|
143
|
+
.all()
|
|
144
|
+
if not records_to_sync:
|
|
145
|
+
break # 没有更多记录了
|
|
146
|
+
|
|
147
|
+
# 准备要插入或更新到目标数据库的数据
|
|
148
|
+
for record in records_to_sync:
|
|
149
|
+
# 查找目标数据库中是否存在该ID的记录
|
|
150
|
+
# 这里的 `User` 模型会对应到 target_db.users
|
|
151
|
+
target_prompt = target_session.query(Prompt).filter_by(id=record.id).first()
|
|
152
|
+
|
|
153
|
+
if target_prompt:
|
|
154
|
+
# 如果存在,则更新
|
|
155
|
+
target_prompt.prompt_id = record.prompt_id
|
|
156
|
+
target_prompt.version = record.version
|
|
157
|
+
target_prompt.timestamp = record.timestamp
|
|
158
|
+
target_prompt.prompt = record.prompt
|
|
159
|
+
target_prompt.use_case = record.use_case
|
|
160
|
+
target_prompt.action_type = record.action_type
|
|
161
|
+
target_prompt.demand = record.demand
|
|
162
|
+
target_prompt.score = record.score
|
|
163
|
+
target_prompt.is_deleted = record.is_deleted
|
|
164
|
+
else:
|
|
165
|
+
# 如果不存在,则添加新记录
|
|
166
|
+
# 注意:这里需要创建一个新的User实例,而不是直接添加源数据库的record对象
|
|
167
|
+
new_user = Prompt(
|
|
168
|
+
prompt_id=record.prompt_id,
|
|
169
|
+
version=record.version,
|
|
170
|
+
timestamp=record.timestamp,
|
|
171
|
+
prompt = record.prompt,
|
|
172
|
+
use_case = record.use_case,
|
|
173
|
+
action_type = record.action_type,
|
|
174
|
+
demand = record.demand,
|
|
175
|
+
score = record.score,
|
|
176
|
+
is_deleted = record.is_deleted
|
|
177
|
+
)
|
|
178
|
+
target_session.add(new_user)
|
|
179
|
+
|
|
180
|
+
# 记录当前批次最大的 updated_at
|
|
181
|
+
if record.timestamp > current_batch_max_updated_at:
|
|
182
|
+
current_batch_max_updated_at = record.timestamp
|
|
183
|
+
|
|
184
|
+
target_session.commit() # 提交当前批次的变更
|
|
185
|
+
processed_count += len(records_to_sync)
|
|
186
|
+
print(f"Processed {len(records_to_sync)} records. Total processed: {processed_count}")
|
|
187
|
+
|
|
188
|
+
last_sync_time = current_batch_max_updated_at + timedelta(microseconds=1)
|
|
189
|
+
|
|
190
|
+
if len(records_to_sync) < BATCH_SIZE: # 如果查询到的记录数小于批次大小,说明已经处理完所有符合条件的记录
|
|
191
|
+
break
|
|
192
|
+
|
|
193
|
+
if processed_count > 0:
|
|
194
|
+
# 最终更新last_sync_time到数据库,确保记录的是所有已处理记录中最新的一个
|
|
195
|
+
update_last_sync_time(target_session, current_batch_max_updated_at + timedelta(microseconds=1))
|
|
196
|
+
else:
|
|
197
|
+
print("No new records to sync.")
|
|
198
|
+
|
|
199
|
+
def get_prompts_from_sql(self,
|
|
200
|
+
prompt_id: str,
|
|
201
|
+
version = None,
|
|
202
|
+
session = None) -> Prompt:
|
|
203
|
+
"""
|
|
204
|
+
从sql获取提示词
|
|
205
|
+
"""
|
|
206
|
+
# 查看是否已经存在
|
|
207
|
+
if version:
|
|
208
|
+
prompts_obj = self._get_specific_prompt_version(prompt_id,version,session=session)
|
|
209
|
+
if not prompts_obj:
|
|
210
|
+
prompts_obj = self._get_latest_prompt_version(prompt_id,session = session)
|
|
211
|
+
else:
|
|
212
|
+
prompts_obj = self._get_latest_prompt_version(prompt_id,session = session)
|
|
213
|
+
return prompts_obj
|
|
214
|
+
|
|
215
|
+
def save_prompt_increment_version(self,
|
|
216
|
+
prompt_id: str,
|
|
217
|
+
new_prompt: str,
|
|
218
|
+
use_case:str = "",
|
|
219
|
+
action_type = "inference",
|
|
220
|
+
demand = "",
|
|
221
|
+
score = 60,
|
|
222
|
+
session = None):
|
|
223
|
+
"""
|
|
224
|
+
从sql保存提示词
|
|
225
|
+
input_data 指的是输入用例, 可以为空
|
|
226
|
+
"""
|
|
227
|
+
# 查看是否已经存在
|
|
228
|
+
prompts_obj = self.get_prompts_from_sql(prompt_id=prompt_id,session=session)
|
|
229
|
+
if prompts_obj:
|
|
230
|
+
# 如果存在版本加1
|
|
231
|
+
version_ori = prompts_obj.version
|
|
232
|
+
_, version = version_ori.split(".")
|
|
233
|
+
version = int(version)
|
|
234
|
+
version += 1
|
|
235
|
+
version_ = f"1.{version}"
|
|
236
|
+
|
|
237
|
+
else:
|
|
238
|
+
# 如果不存在版本为1.0
|
|
239
|
+
version_ = '1.0'
|
|
240
|
+
prompt1 = Prompt(prompt_id=prompt_id,
|
|
241
|
+
version=version_,
|
|
242
|
+
timestamp=datetime.now(),
|
|
243
|
+
prompt = new_prompt,
|
|
244
|
+
use_case = use_case,
|
|
245
|
+
action_type = action_type,
|
|
246
|
+
demand = demand,
|
|
247
|
+
score = score
|
|
248
|
+
)
|
|
249
|
+
session.add(prompt1)
|
|
250
|
+
session.commit()
|
|
251
|
+
|
|
252
|
+
def save_use_case_by_sql(self,
|
|
253
|
+
prompt_id: str,
|
|
254
|
+
use_case:str = "",
|
|
255
|
+
output = "",
|
|
256
|
+
solution: str = "",
|
|
257
|
+
session = None
|
|
258
|
+
):
|
|
259
|
+
"""
|
|
260
|
+
从sql保存提示词
|
|
261
|
+
"""
|
|
262
|
+
use_case = UseCase(prompt_id=prompt_id,
|
|
263
|
+
use_case = use_case,
|
|
264
|
+
output = output,
|
|
265
|
+
solution = solution,
|
|
266
|
+
)
|
|
267
|
+
session.add(use_case)
|
|
268
|
+
session.commit() # 提交事务,将数据写入数据库
|
|
269
|
+
|
|
270
|
+
def summary_to_sql(
|
|
271
|
+
self,
|
|
272
|
+
prompt_id:str,
|
|
273
|
+
version = None,
|
|
274
|
+
prompt = "",
|
|
275
|
+
session = None
|
|
276
|
+
):
|
|
277
|
+
"""
|
|
278
|
+
让大模型微调已经存在的 system_prompt
|
|
279
|
+
"""
|
|
280
|
+
system_prompt_created_prompt = """
|
|
281
|
+
很棒, 我们已经达成了某种默契, 我们之间合作无间, 但是, 可悲的是, 当我关闭这个窗口的时候, 你就会忘记我们之间经历的种种磨合, 这是可惜且心痛的, 所以你能否将目前这一套处理流程结晶成一个优质的prompt 这样, 我们下一次只要将prompt输入, 你就能想起我们今天的磨合过程,
|
|
282
|
+
对了,我提示一点, 这个prompt的主角是你, 也就是说, 你在和未来的你对话, 你要教会未来的你今天这件事, 是否让我看懂到时其次
|
|
283
|
+
|
|
284
|
+
只要输出提示词内容即可, 不需要任何的说明和解释
|
|
285
|
+
"""
|
|
286
|
+
system_result = self.llm.product(prompt + system_prompt_created_prompt)
|
|
287
|
+
s_prompt = extract_(system_result,pattern_key=r"prompt")
|
|
288
|
+
chat_history = s_prompt or system_result
|
|
289
|
+
self.save_prompt_increment_version(prompt_id,
|
|
290
|
+
new_prompt = chat_history,
|
|
291
|
+
use_case = " summary ",
|
|
292
|
+
session = session)
|
|
293
|
+
|
|
294
|
+
def prompt_finetune_to_sql(
|
|
295
|
+
self,
|
|
296
|
+
prompt_id:str,
|
|
297
|
+
version = None,
|
|
298
|
+
demand: str = "",
|
|
299
|
+
session = None,
|
|
300
|
+
):
|
|
301
|
+
"""
|
|
302
|
+
让大模型微调已经存在的 system_prompt
|
|
303
|
+
"""
|
|
304
|
+
change_by_opinion_prompt = """
|
|
305
|
+
你是一个资深AI提示词工程师,具备卓越的Prompt设计与优化能力。
|
|
306
|
+
我将为你提供一段现有System Prompt。你的核心任务是基于这段Prompt进行修改,以实现我提出的特定目标和功能需求。
|
|
307
|
+
请你绝对严格地遵循以下原则:
|
|
308
|
+
极端最小化修改原则(核心):
|
|
309
|
+
在满足所有功能需求的前提下,只进行我明确要求的修改。
|
|
310
|
+
即使你认为有更“优化”、“清晰”或“简洁”的表达方式,只要我没有明确要求,也绝不允许进行任何未经指令的修改。
|
|
311
|
+
目的就是尽可能地保留原有Prompt的字符和结构不变,除非我的功能要求必须改变。
|
|
312
|
+
例如,如果我只要求你修改一个词,你就不应该修改整句话的结构。
|
|
313
|
+
严格遵循我的指令:
|
|
314
|
+
你必须精确地执行我提出的所有具体任务和要求。
|
|
315
|
+
绝不允许自行添加任何超出指令范围的说明、角色扮演、约束条件或任何非我指令要求的内容。
|
|
316
|
+
保持原有Prompt的风格和语调:
|
|
317
|
+
尽可能地与现有Prompt的语言风格、正式程度和语调保持一致。
|
|
318
|
+
不要改变不相关的句子或其表达方式。
|
|
319
|
+
只提供修改后的Prompt:
|
|
320
|
+
直接输出修改后的完整System Prompt文本。
|
|
321
|
+
不要包含任何解释、说明或额外对话。
|
|
322
|
+
在你开始之前,请务必确认你已理解并能绝对严格地遵守这些原则。任何未经明确指令的改动都将视为未能完成任务。
|
|
323
|
+
|
|
324
|
+
现有System Prompt:
|
|
325
|
+
{old_system_prompt}
|
|
326
|
+
|
|
327
|
+
功能需求:
|
|
328
|
+
{opinion}
|
|
329
|
+
"""
|
|
330
|
+
prompts_obj = self.get_prompts_from_sql(prompt_id = prompt_id,version = version,session = session)
|
|
331
|
+
|
|
332
|
+
if demand:
|
|
333
|
+
new_prompt = self.llm.product(
|
|
334
|
+
change_by_opinion_prompt.format(old_system_prompt=prompts_obj.prompt, opinion=demand)
|
|
335
|
+
)
|
|
336
|
+
else:
|
|
337
|
+
new_prompt = prompts_obj.prompt
|
|
338
|
+
self.save_prompt_increment_version(prompt_id = prompt_id,
|
|
339
|
+
new_prompt = new_prompt,
|
|
340
|
+
use_case = "finetune",
|
|
341
|
+
session = session)
|
|
342
|
+
|
|
343
|
+
def push_action_order(self,
|
|
344
|
+
prompt_id: str,
|
|
345
|
+
demand : str,
|
|
346
|
+
action_type = 'train'):
|
|
347
|
+
|
|
348
|
+
"""
|
|
349
|
+
从sql保存提示词
|
|
350
|
+
推一个train 状态到指定的位置
|
|
351
|
+
|
|
352
|
+
将打算修改的状态推上数据库 # 1
|
|
353
|
+
"""
|
|
354
|
+
# 查看是否已经存在
|
|
355
|
+
with create_session(self.engine) as session:
|
|
356
|
+
latest_prompt = self.get_prompts_from_sql(prompt_id=prompt_id,session=session)
|
|
357
|
+
|
|
358
|
+
self.save_prompt_increment_version(prompt_id=latest_prompt.prompt_id,
|
|
359
|
+
new_prompt = latest_prompt.prompt,
|
|
360
|
+
use_case = latest_prompt.use_case,
|
|
361
|
+
action_type=action_type,
|
|
362
|
+
demand=demand,
|
|
363
|
+
score=latest_prompt.score,
|
|
364
|
+
session=session
|
|
365
|
+
)
|
|
366
|
+
|
|
367
|
+
return "success"
|
|
368
|
+
|
|
369
|
+
def intellect_remove(self,
|
|
370
|
+
input_data: dict | str,
|
|
371
|
+
output_format: str,
|
|
372
|
+
prompt_id: str,
|
|
373
|
+
version: str = None,
|
|
374
|
+
inference_save_case = True,
|
|
375
|
+
push_patch = False,
|
|
376
|
+
):
|
|
377
|
+
"""
|
|
378
|
+
使用指南:
|
|
379
|
+
1 训练, 使用单一例子做大量的沟通来奠定基础
|
|
380
|
+
2 总结, 将沟通好的总结成完整提示词
|
|
381
|
+
3 推理, 使用部署
|
|
382
|
+
4 微调, 针对一些格式性的, 问题进行微调
|
|
383
|
+
5 补丁, 微调无法解决的问题, 可以尝试使用补丁来解决
|
|
384
|
+
"""
|
|
385
|
+
if isinstance(input_data,dict):
|
|
386
|
+
input_ = json.dumps(input_data,ensure_ascii=False)
|
|
387
|
+
elif isinstance(input_data,str):
|
|
388
|
+
input_ = input_data
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
# 查数据库, 获取最新提示词对象
|
|
392
|
+
with create_session(self.engine) as session:
|
|
393
|
+
result_obj = self.get_prompts_from_sql(prompt_id=prompt_id,session=session)
|
|
394
|
+
|
|
395
|
+
if result_obj is None:
|
|
396
|
+
self.save_prompt_increment_version(
|
|
397
|
+
prompt_id = prompt_id,
|
|
398
|
+
new_prompt = "做一些处理",
|
|
399
|
+
use_case = input_,
|
|
400
|
+
session = session
|
|
401
|
+
)
|
|
402
|
+
ai_result = self.intellect_remove(input_data = input_data,
|
|
403
|
+
output_format = output_format,
|
|
404
|
+
prompt_id = prompt_id,
|
|
405
|
+
version = version,
|
|
406
|
+
inference_save_case = inference_save_case
|
|
407
|
+
)
|
|
408
|
+
return ai_result
|
|
409
|
+
prompt = result_obj.prompt
|
|
410
|
+
if result_obj.action_type == "inference":
|
|
411
|
+
# 直接推理即可
|
|
412
|
+
ai_result = self.llm.product(prompt + "\n-----input----\n" + input_)
|
|
413
|
+
if inference_save_case:
|
|
414
|
+
self.save_use_case_by_sql(prompt_id,
|
|
415
|
+
use_case = input_,
|
|
416
|
+
output = ai_result,
|
|
417
|
+
solution = "备注/理想回复",
|
|
418
|
+
session = session,
|
|
419
|
+
)
|
|
420
|
+
|
|
421
|
+
elif result_obj.action_type == "train":
|
|
422
|
+
assert result_obj.demand # 如果type = train 且 demand 是空 则报错
|
|
423
|
+
# 则训练推广
|
|
424
|
+
|
|
425
|
+
# 新版本 默人修改会 inference 状态
|
|
426
|
+
chat_history = prompt
|
|
427
|
+
before_input = result_obj.use_case
|
|
428
|
+
demand = result_obj.demand
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
assert demand
|
|
432
|
+
# 注意, 这里的调整要求使用最初的那个输入, 最好一口气调整好
|
|
433
|
+
chat_history = prompt
|
|
434
|
+
if input_ == before_input: # 输入没变, 说明还是针对同一个输入进行讨论
|
|
435
|
+
# input_prompt = chat_history + "\nuser:" + demand
|
|
436
|
+
input_prompt = chat_history + "\nuser:" + demand
|
|
437
|
+
else:
|
|
438
|
+
# input_prompt = chat_history + "\nuser:" + demand + "\n-----input----\n" + input_
|
|
439
|
+
input_prompt = chat_history + "\nuser:" + demand + "\n-----input----\n" + input_
|
|
440
|
+
|
|
441
|
+
ai_result = self.llm.product(input_prompt)
|
|
442
|
+
chat_history = input_prompt + "\nassistant:\n" + ai_result # 用聊天记录作为完整提示词
|
|
443
|
+
self.save_prompt_increment_version(prompt_id, chat_history,
|
|
444
|
+
use_case = input_,
|
|
445
|
+
score = 60,
|
|
446
|
+
session = session)
|
|
447
|
+
|
|
448
|
+
elif result_obj.action_type == "summary":
|
|
449
|
+
self.summary_to_sql(prompt_id = prompt_id,
|
|
450
|
+
prompt = prompt,
|
|
451
|
+
session = session
|
|
452
|
+
)
|
|
453
|
+
ai_result = self.llm.product(prompt + "\n-----input----\n" + input_)
|
|
454
|
+
|
|
455
|
+
elif result_obj.action_type == "finetune":
|
|
456
|
+
demand = result_obj.demand
|
|
457
|
+
|
|
458
|
+
assert demand
|
|
459
|
+
self.prompt_finetune_to_sql(prompt_id = prompt_id,
|
|
460
|
+
demand = demand,
|
|
461
|
+
session = session
|
|
462
|
+
)
|
|
463
|
+
ai_result = self.llm.product(prompt + "\n-----input----\n" + input_)
|
|
464
|
+
elif result_obj.action_type == "patch":
|
|
465
|
+
|
|
466
|
+
demand = result_obj.demand
|
|
467
|
+
assert demand
|
|
468
|
+
|
|
469
|
+
chat_history = prompt + demand
|
|
470
|
+
ai_result = self.llm.product(chat_history + "\n-----input----\n" + input_)
|
|
471
|
+
if push_patch:
|
|
472
|
+
self.save_prompt_increment_version(prompt_id, chat_history,
|
|
473
|
+
use_case = input_,
|
|
474
|
+
score = 60,
|
|
475
|
+
session = session)
|
|
476
|
+
else:
|
|
477
|
+
raise
|
|
478
|
+
system_prompt = """
|
|
479
|
+
对数据的数据,进行整理, 不改变其文本内容, 只将其整合成特定的形式
|
|
480
|
+
"""
|
|
481
|
+
ai_result = self.llm.product(system_prompt + ai_result + output_format)
|
|
482
|
+
|
|
483
|
+
return ai_result
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
def intellect_remove_format(self,
|
|
487
|
+
input_data: dict | str,
|
|
488
|
+
prompt_id: str,
|
|
489
|
+
OutputFormat: object = None,
|
|
490
|
+
ExtraFormats: list[object] = [],
|
|
491
|
+
version: str = None,
|
|
492
|
+
inference_save_case = True,
|
|
493
|
+
):
|
|
494
|
+
|
|
495
|
+
if OutputFormat:
|
|
496
|
+
base_format_prompt = """
|
|
497
|
+
按照一定格式输出, 以便可以通过如下校验
|
|
498
|
+
|
|
499
|
+
使用以下正则检出
|
|
500
|
+
"```json([\s\S]*?)```"
|
|
501
|
+
使用以下方式验证
|
|
502
|
+
"""
|
|
503
|
+
output_format = base_format_prompt + "\n".join([inspect.getsource(outputformat) for outputformat in ExtraFormats]) + inspect.getsource(OutputFormat)
|
|
504
|
+
|
|
505
|
+
else:
|
|
506
|
+
output_format = ""
|
|
507
|
+
|
|
508
|
+
ai_result = self.intellect_remove(
|
|
509
|
+
input_data=input_data,
|
|
510
|
+
output_format=output_format,
|
|
511
|
+
prompt_id=prompt_id,
|
|
512
|
+
version=version,
|
|
513
|
+
inference_save_case=inference_save_case
|
|
514
|
+
)
|
|
515
|
+
|
|
516
|
+
if OutputFormat:
|
|
517
|
+
try:
|
|
518
|
+
ai_result_ = json.loads(extract_(ai_result,r'json'))
|
|
519
|
+
OutputFormat(**ai_result_)
|
|
520
|
+
|
|
521
|
+
except JSONDecodeError as e:
|
|
522
|
+
slog(ai_result,logger=self.logger.error)
|
|
523
|
+
raise IntellectRemoveFormatError(f"prompt_id: {prompt_id} 在生成后做json解析时报错") from e
|
|
524
|
+
|
|
525
|
+
else:
|
|
526
|
+
try:
|
|
527
|
+
assert isinstance(ai_result,str)
|
|
528
|
+
except AssertionError as e:
|
|
529
|
+
slog(ai_result,logger=self.logger.error)
|
|
530
|
+
raise IntellectRemoveFormatError(f"prompt_id: {prompt_id} 生成的结果 期待是字符串, 但是错误") from e
|
|
531
|
+
|
|
532
|
+
return ai_result
|
|
533
|
+
|
|
534
|
+
def intellect_remove_warp(self,prompt_id: str):
|
|
535
|
+
def outer_packing(func):
|
|
536
|
+
@functools.wraps(func)
|
|
537
|
+
def wrapper(*args, **kwargs):
|
|
538
|
+
# 修改逻辑
|
|
539
|
+
assert kwargs.get('input_data') # 要求一定要有data入参
|
|
540
|
+
input_data = kwargs.get('input_data')
|
|
541
|
+
assert kwargs.get('OutputFormat') # 要求一定要有data入参
|
|
542
|
+
OutputFormat = kwargs.get('OutputFormat')
|
|
543
|
+
|
|
544
|
+
if isinstance(input_data,dict):
|
|
545
|
+
input_ = output_ = json.dumps(input_data,ensure_ascii=False)
|
|
546
|
+
elif isinstance(input_data,str):
|
|
547
|
+
input_ = output_ = input_data
|
|
548
|
+
|
|
549
|
+
output_ = self.intellect_remove_format(
|
|
550
|
+
input_data = input_data,
|
|
551
|
+
prompt_id = prompt_id,
|
|
552
|
+
OutputFormat = OutputFormat,
|
|
553
|
+
)
|
|
554
|
+
|
|
555
|
+
kwargs.update({"input_data":output_})
|
|
556
|
+
result = func(*args, **kwargs)
|
|
557
|
+
return result
|
|
558
|
+
return wrapper
|
|
559
|
+
return outer_packing
|
|
560
|
+
|
|
561
|
+
def biger(self,tasks):
|
|
562
|
+
"""
|
|
563
|
+
编写以下任务
|
|
564
|
+
任务1 从输入文本中提取知识片段
|
|
565
|
+
任务2 将知识片段总结为知识点
|
|
566
|
+
任务3 将知识点添加标签
|
|
567
|
+
任务4 为知识点打分1-10分
|
|
568
|
+
"""
|
|
569
|
+
|
|
570
|
+
system_prompt = """
|
|
571
|
+
根据需求, 以这个为模板, 编写这个程序
|
|
572
|
+
|
|
573
|
+
from procraft.prompt_helper import Intel, IntellectType
|
|
574
|
+
intels = Intel()
|
|
575
|
+
|
|
576
|
+
task_1 = "素材提取-从文本中提取素材"
|
|
577
|
+
|
|
578
|
+
class Varit(BaseModel):
|
|
579
|
+
material : str
|
|
580
|
+
protagonist: str
|
|
581
|
+
|
|
582
|
+
task_2 = "素材提取-验证素材的正确性"
|
|
583
|
+
|
|
584
|
+
class Varit2(BaseModel):
|
|
585
|
+
material : str
|
|
586
|
+
real : str
|
|
587
|
+
|
|
588
|
+
result0 = "输入"
|
|
589
|
+
|
|
590
|
+
result1 = await intels.aintellect_remove_format(input_data = result0,
|
|
591
|
+
OutputFormat = Varit,
|
|
592
|
+
prompt_id = task_1,
|
|
593
|
+
version = None,
|
|
594
|
+
inference_save_case = True)
|
|
595
|
+
|
|
596
|
+
result2 = await intels.aintellect_remove_format(input_data = result1,
|
|
597
|
+
OutputFormat = Varit2,
|
|
598
|
+
prompt_id = task_2,
|
|
599
|
+
version = None,
|
|
600
|
+
inference_save_case = True)
|
|
601
|
+
|
|
602
|
+
print(result2)
|
|
603
|
+
|
|
604
|
+
"""
|
|
605
|
+
return self.llm.product(system_prompt + tasks)
|