-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathllm_service.py
More file actions
1642 lines (1357 loc) · 70.3 KB
/
llm_service.py
File metadata and controls
1642 lines (1357 loc) · 70.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import json
import re
import httpx
import asyncio
from datetime import datetime
from pathlib import Path
from openai import OpenAI, APIStatusError, AsyncOpenAI
from openai.types.chat import ChatCompletion
from config import API_CONFIG, AI_CONFIG, GENERATION_CONFIG, PROXY_CONFIG, validate_config
from retry_utils import retry_manager, RetryError
from ui_utils import ui
class LLMService:
"""AI大语言模型服务类,封装所有AI交互逻辑"""
def __init__(self):
self.client = None
self.async_client = None
self.prompts = {}
self._load_prompts()
self._initialize_clients()
def _load_prompts(self):
"""加载提示词配置"""
try:
# 获取当前项目的prompts.json路径
prompts_path = self._get_prompts_path()
with open(prompts_path, 'r', encoding='utf-8') as f:
self.prompts = json.load(f)
except FileNotFoundError:
# 静默处理文件未找到,避免在启动时显示错误信息
self.prompts = {}
except json.JSONDecodeError as e:
# 静默处理JSON格式错误,避免在启动时显示错误信息
self.prompts = {}
def _get_prompts_path(self):
"""获取当前项目的prompts.json路径"""
try:
# 导入放在方法内部,避免循环导入
from project_data_manager import project_data_manager
data_manager = project_data_manager.get_data_manager()
if data_manager and data_manager.project_path:
# 多项目模式:使用项目路径下的prompts.json
prompts_path = data_manager.project_path / 'prompts.json'
# 如果项目路径下不存在prompts.json,从根目录复制默认的
if not prompts_path.exists():
import shutil
# 优先从根目录的 prompts.json 复制
root_prompts = Path('prompts.json')
if root_prompts.exists():
shutil.copy2(root_prompts, prompts_path)
print(f"已为项目复制默认prompts.json到: {prompts_path}")
else:
# 如果根目录也没有,尝试从默认模板复制
default_prompts = Path('prompts.default.json')
if default_prompts.exists():
shutil.copy2(default_prompts, prompts_path)
print(f"已为项目复制默认prompts模板到: {prompts_path}")
return prompts_path
except ImportError:
# 在某些测试或启动场景下,可能无法导入 project_data_manager
pass
except Exception as e:
# 记录错误,但不影响核心逻辑
print(f"获取项目特定prompts路径时出错: {e},将使用默认路径。")
# 单项目模式或回退方案:使用根目录的prompts.json
return Path('prompts.json')
def reload_prompts(self):
"""重新加载prompts配置,用于项目切换时"""
self._load_prompts()
def _get_prompt(self, prompt_type, user_prompt="", **kwargs):
"""获取格式化的提示词"""
if prompt_type not in self.prompts:
# 如果找不到配置,返回None,由调用方处理
return None
# 确保user_prompt不是None
if user_prompt is None:
user_prompt = ""
prompt_config = self.prompts[prompt_type]
# 格式化基础提示词
base_prompt = prompt_config["base_prompt"].format(**kwargs, **GENERATION_CONFIG)
# 如果有用户自定义提示词,使用模板组合
if user_prompt.strip() and "user_prompt_template" in prompt_config:
return prompt_config["user_prompt_template"].format(
base_prompt=base_prompt,
user_prompt=user_prompt.strip()
)
else:
return base_prompt
def _initialize_clients(self):
"""初始化同步和异步客户端"""
try:
# 验证配置
if not validate_config():
self.client = None
self.async_client = None
return
# 构建HTTP客户端配置
client_kwargs = {
"base_url": API_CONFIG["base_url"],
"api_key": API_CONFIG["openrouter_api_key"]
}
# 如果启用代理,配置HTTP客户端
if PROXY_CONFIG["enabled"]:
proxy_url = PROXY_CONFIG["http_proxy"]
# 同步客户端
http_client = httpx.Client(proxy=proxy_url)
client_kwargs["http_client"] = http_client
# 异步客户端
async_http_client = httpx.AsyncClient(proxy=proxy_url)
async_client_kwargs = client_kwargs.copy()
async_client_kwargs["http_client"] = async_http_client
else:
async_client_kwargs = client_kwargs.copy()
# 创建客户端
self.client = OpenAI(**client_kwargs)
self.async_client = AsyncOpenAI(**async_client_kwargs)
except Exception as e:
# 静默处理AI客户端初始化错误,避免在启动时显示错误信息
self.client = None
self.async_client = None
def is_available(self):
"""检查AI服务是否可用"""
return self.client is not None
def is_async_available(self):
"""检查异步AI服务是否可用"""
return self.async_client is not None
def _save_critique_data(self, chapter_num, chapter_title, critique_data, timestamp=None):
"""保存批评数据到文件"""
if not GENERATION_CONFIG.get('save_intermediate_data', True):
return
try:
from project_data_manager import project_data_manager
data_manager = project_data_manager.get_data_manager()
if timestamp is None:
timestamp = datetime.now().isoformat()
# 读取现有的critiques数据
critiques_path = data_manager.get_path("critiques")
if critiques_path.exists():
with open(critiques_path, 'r', encoding='utf-8') as f:
critiques = json.load(f)
else:
critiques = {}
# 添加新的critique数据
chapter_key = f"chapter_{chapter_num}"
if chapter_key not in critiques:
critiques[chapter_key] = []
critique_entry = {
"timestamp": timestamp,
"chapter_title": chapter_title,
"critique_data": critique_data
}
critiques[chapter_key].append(critique_entry)
# 保存到文件
critiques_path.parent.mkdir(parents=True, exist_ok=True)
with open(critiques_path, 'w', encoding='utf-8') as f:
json.dump(critiques, f, ensure_ascii=False, indent=2)
except Exception as e:
print(f"保存critique数据时出错: {e}")
def _save_refinement_history(self, chapter_num, chapter_title, initial_content, refined_content, critique_data, timestamp=None):
"""保存修正历史到文件(只保存摘要信息,不保存完整内容)"""
if not GENERATION_CONFIG.get('save_intermediate_data', True):
return
try:
from project_data_manager import project_data_manager
data_manager = project_data_manager.get_data_manager()
if timestamp is None:
timestamp = datetime.now().isoformat()
# 读取现有的refinement历史数据
history_path = data_manager.get_path("refinement_history")
if history_path.exists():
with open(history_path, 'r', encoding='utf-8') as f:
history = json.load(f)
else:
history = {}
# 添加新的refinement记录(只保存摘要)
chapter_key = f"chapter_{chapter_num}"
if chapter_key not in history:
history[chapter_key] = []
refinement_entry = {
"timestamp": timestamp,
"chapter_title": chapter_title,
"initial_word_count": len(initial_content) if initial_content else 0,
"refined_word_count": len(refined_content) if refined_content else 0,
"critique_summary": self._extract_critique_summary(critique_data),
"word_count_change": (len(refined_content) - len(initial_content)) if (initial_content and refined_content) else 0,
"improvement_percentage": round(((len(refined_content) - len(initial_content)) / len(initial_content)) * 100, 2) if initial_content else 0
}
history[chapter_key].append(refinement_entry)
# 保存到文件
history_path.parent.mkdir(parents=True, exist_ok=True)
with open(history_path, 'w', encoding='utf-8') as f:
json.dump(history, f, ensure_ascii=False, indent=2)
except Exception as e:
print(f"保存refinement历史时出错: {e}")
def _extract_critique_summary(self, critique_data):
"""从critique数据中提取摘要信息"""
try:
if isinstance(critique_data, str):
parsed_data = json.loads(critique_data)
else:
parsed_data = critique_data
return {
"issues_count": len(parsed_data.get("issues", [])),
"strengths": parsed_data.get("strengths", []),
"priority_fixes": parsed_data.get("priority_fixes", []),
"issue_categories": [issue.get("category", "") for issue in parsed_data.get("issues", [])]
}
except:
return {"raw_critique": str(critique_data)[:200] + "..." if len(str(critique_data)) > 200 else str(critique_data)}
def _save_initial_draft(self, chapter_num, chapter_title, content, timestamp=None):
"""保存初稿内容到单独文件"""
if not GENERATION_CONFIG.get('save_intermediate_data', True):
return
try:
from project_data_manager import project_data_manager
data_manager = project_data_manager.get_data_manager()
if timestamp is None:
timestamp = datetime.now().isoformat()
# 读取现有的初稿数据
drafts_path = data_manager.get_path("initial_drafts")
if drafts_path.exists():
with open(drafts_path, 'r', encoding='utf-8') as f:
drafts = json.load(f)
else:
drafts = {}
# 添加新的初稿数据
chapter_key = f"chapter_{chapter_num}"
if chapter_key not in drafts:
drafts[chapter_key] = []
draft_entry = {
"timestamp": timestamp,
"chapter_title": chapter_title,
"content": content,
"word_count": len(content) if content else 0
}
drafts[chapter_key].append(draft_entry)
# 保存到文件
drafts_path.parent.mkdir(parents=True, exist_ok=True)
with open(drafts_path, 'w', encoding='utf-8') as f:
json.dump(drafts, f, ensure_ascii=False, indent=2)
except Exception as e:
print(f"保存初稿数据时出错: {e}")
def _save_refined_draft(self, chapter_num, chapter_title, content, timestamp=None):
"""保存修订内容到单独文件"""
if not GENERATION_CONFIG.get('save_intermediate_data', True):
return
try:
from project_data_manager import project_data_manager
data_manager = project_data_manager.get_data_manager()
if timestamp is None:
timestamp = datetime.now().isoformat()
# 读取现有的修订数据
refined_path = data_manager.get_path("refined_drafts")
if refined_path.exists():
with open(refined_path, 'r', encoding='utf-8') as f:
refined = json.load(f)
else:
refined = {}
# 添加新的修订数据
chapter_key = f"chapter_{chapter_num}"
if chapter_key not in refined:
refined[chapter_key] = []
refined_entry = {
"timestamp": timestamp,
"chapter_title": chapter_title,
"content": content,
"word_count": len(content) if content else 0
}
refined[chapter_key].append(refined_entry)
# 保存到文件
refined_path.parent.mkdir(parents=True, exist_ok=True)
with open(refined_path, 'w', encoding='utf-8') as f:
json.dump(refined, f, ensure_ascii=False, indent=2)
except Exception as e:
print(f"保存修订数据时出错: {e}")
def _try_parse_json(self, response_text):
"""尝试多种方法解析JSON"""
# 尝试1:直接解析JSON
try:
return json.loads(response_text)
except json.JSONDecodeError:
pass
# 尝试2:提取被```json ... ```包裹的代码块
json_match = re.search(r"```json\s*(\{.*?\})\s*```", response_text, re.DOTALL)
if json_match:
try:
return json.loads(json_match.group(1))
except json.JSONDecodeError:
pass
# 尝试3:提取被```包裹的代码块(不带json标识)
code_match = re.search(r"```\s*(\{.*?\})\s*```", response_text, re.DOTALL)
if code_match:
try:
return json.loads(code_match.group(1))
except json.JSONDecodeError:
pass
# 尝试4:提取任何花括号包裹的内容
bracket_match = re.search(r"\{.*\}", response_text, re.DOTALL)
if bracket_match:
try:
return json.loads(bracket_match.group(0))
except json.JSONDecodeError:
pass
# 尝试5:使用fix_json_quotes修复引号问题
try:
# 定义内联的JSON修复函数,避免循环导入
def fix_json_quotes_inline(json_string):
try:
return json.loads(json_string)
except json.JSONDecodeError:
pass
try:
def fix_quotes_in_string(match):
key = match.group(1)
value = match.group(2)
escaped_value = value.replace('"', '\\"')
return f'"{key}": "{escaped_value}"'
pattern = r'"([^"]+)":\s*"([^"]*(?:"[^"]*)*)"'
fixed_string = re.sub(pattern, fix_quotes_in_string, json_string)
return json.loads(fixed_string)
except (json.JSONDecodeError, re.error):
pass
return None
return fix_json_quotes_inline(response_text)
except:
pass
# 尝试6:Python字典格式
try:
import ast
return ast.literal_eval(response_text)
except (ValueError, SyntaxError):
pass
# 尝试7:修复单引号为双引号后解析
try:
# 将单引号替换为双引号(简单处理)
fixed_text = response_text.replace("'", '"')
return json.loads(fixed_text)
except json.JSONDecodeError:
pass
return None
def _make_json_request(self, prompt, timeout=None, task_name="", with_retry=True):
"""专门用于需要JSON响应的请求(同步版本)"""
for attempt in range(3): # 最多尝试3次
response_text = self._make_request(prompt, timeout, task_name, with_retry)
if response_text is None:
return None
# 尝试多种JSON解析方法
parsed_result = self._try_parse_json(response_text)
if parsed_result is not None:
return parsed_result
# 如果还是失败,且不是最后一次尝试,发送修复请求
if attempt < 2:
print(f"[{task_name}] JSON解析失败,尝试修复 (第{attempt + 1}次)")
# 改进修复请求的prompt,避免LLM困惑
original_prompt_type = "Canon Bible" if "canon" in task_name.lower() else "JSON数据"
prompt = f"请重新生成{original_prompt_type},严格按照JSON格式返回。不要包含任何解释文字,只返回纯JSON:\n\n{prompt}"
else:
print(f"[{task_name}] 多次尝试后仍无法解析JSON格式")
return None
return None
async def _make_json_request_async(self, prompt, timeout=None, task_name="", with_retry=True, progress_callback=None):
"""专门用于需要JSON响应的请求(异步版本)"""
for attempt in range(3): # 最多尝试3次
response_text = await self._make_async_request(prompt, timeout, task_name, with_retry, progress_callback)
if response_text is None:
return None
# 尝试多种JSON解析方法
parsed_result = self._try_parse_json(response_text)
if parsed_result is not None:
return parsed_result
# 如果还是失败,且不是最后一次尝试,发送修复请求
if attempt < 2:
error_msg = f"[{task_name}] JSON解析失败,尝试修复 (第{attempt + 1}次)"
print(error_msg)
if progress_callback:
progress_callback(error_msg)
# 改进修复请求的prompt,避免LLM困惑
original_prompt_type = "Canon Bible" if "canon" in task_name.lower() else "JSON数据"
prompt = f"请重新生成{original_prompt_type},严格按照JSON格式返回。不要包含任何解释文字,只返回纯JSON:\n\n{prompt}"
else:
error_msg = f"[{task_name}] 多次尝试后仍无法解析JSON格式"
print(error_msg)
if progress_callback:
progress_callback(error_msg)
return None
return None
def _make_request(self, prompt, timeout=None, task_name="", with_retry=True):
"""通用的AI请求方法(同步版本)"""
if not self.is_available():
return None
if timeout is None:
timeout = AI_CONFIG["timeout"]
def _do_request():
"""执行实际的请求"""
completion = self.client.chat.completions.create(
model=AI_CONFIG["model"],
messages=[
{
"role": "user",
"content": prompt,
}
],
timeout=timeout,
)
return completion.choices[0].message.content
if with_retry:
try:
return retry_manager.retry_sync(_do_request, task_name=task_name)
except RetryError as e:
print(f"\n[{task_name}] 重试{e.retry_count}次后仍失败: {e.last_exception}")
return None
except Exception as e:
print(f"\n[{task_name}] 不可重试的错误: {e}")
return None
else:
# 原有的直接请求逻辑(向后兼容)
try:
return _do_request()
except APIStatusError as e:
print(f"\n错误: 调用 API 时出错 (状态码: {e.status_code})")
if e.status_code == 429:
print("API 资源配额已用尽或达到速率限制。请检查您在 OpenRouter 的账户。")
else:
print(f"详细信息: {e.response.text}")
return None
except Exception as e:
print(f"\n调用 AI 时出错: {e}")
if "Timeout" in str(e) or "timed out" in str(e):
print("\n错误:请求超时。")
print("这很可能是您的网络无法连接到 OpenRouter 的服务器。请检查您的网络连接、代理或防火墙设置。")
return None
async def _make_async_request(self, prompt, timeout=None, task_name="", with_retry=True, progress_callback=None):
"""通用的AI请求方法(异步版本)"""
if not self.is_async_available():
return None
if timeout is None:
timeout = AI_CONFIG["timeout"]
async def _do_async_request():
"""执行实际的异步请求"""
completion = await self.async_client.chat.completions.create(
model=AI_CONFIG["model"],
messages=[
{
"role": "user",
"content": prompt,
}
],
timeout=timeout,
)
return completion.choices[0].message.content
if with_retry:
try:
return await retry_manager.retry_async(
_do_async_request,
task_name=task_name,
progress_callback=progress_callback
)
except RetryError as e:
error_msg = f"[{task_name}] 重试{e.retry_count}次后仍失败: {e.last_exception}"
print(f"\n{error_msg}")
if progress_callback:
progress_callback(error_msg)
return None
except Exception as e:
error_msg = f"[{task_name}] 不可重试的错误: {e}"
print(f"\n{error_msg}")
if progress_callback:
progress_callback(error_msg)
return None
else:
# 原有的直接请求逻辑(向后兼容)
try:
return await _do_async_request()
except APIStatusError as e:
error_msg = f"调用 API 时出错 (状态码: {e.status_code})"
if task_name:
error_msg = f"[{task_name}] {error_msg}"
print(f"\n{error_msg}")
if e.status_code == 429:
print("API 资源配额已用尽或达到速率限制。请检查您在 OpenRouter 的账户。")
else:
print(f"详细信息: {e.response.text}")
return None
except Exception as e:
error_msg = f"调用 AI 时出错: {e}"
if task_name:
error_msg = f"[{task_name}] {error_msg}"
print(f"\n{error_msg}")
if "Timeout" in str(e) or "timed out" in str(e):
print("\n错误:请求超时。")
print("这很可能是您的网络无法连接到 OpenRouter 的服务器。请检查您的网络连接、代理或防火墙设置。")
return None
def generate_theme_paragraph(self, one_line_theme, user_prompt=""):
"""生成段落主题(简单版)"""
if user_prompt is None:
user_prompt = ""
# 尝试使用新版提示词模板,提供默认参数
try:
prompt = self._get_prompt("theme_paragraph", user_prompt,
one_line_theme=one_line_theme,
selected_genre="通用",
user_intent="扩展成更具体的段落主题",
canon="")
except KeyError:
# 如果新版提示词模板失败,使用后备提示词
prompt = None
if prompt is None:
# 后备提示词
base_prompt = f"请将以下这个一句话小说主题,扩展成一段更加具体、包含更多情节可能性的段落大纲,字数在{GENERATION_CONFIG['theme_paragraph_length']}。请直接输出扩写后的段落,不要包含额外说明和标题。\n\n一句话主题:{one_line_theme}"
prompt = f"{base_prompt}\n\n用户额外要求:{user_prompt.strip()}" if user_prompt.strip() else base_prompt
return self._make_request(prompt)
def analyze_theme_genres(self, one_line_theme, user_prompt=""):
"""分析主题并推荐作品类型"""
if user_prompt is None:
user_prompt = ""
prompt = self._get_prompt("theme_analysis", user_prompt, one_line_theme=one_line_theme)
if prompt is None:
# 后备提示词
base_prompt = f"请分析以下一句话主题,并推荐3-5种最适合的作品类型(如科幻、奇幻、悬疑、情感等),以JSON格式返回。\n\n主题:{one_line_theme}\n\n重要:你的回答必须是纯粹的、格式正确的JSON,不包含任何解释性文字、注释或代码块标记。"
prompt = f"{base_prompt}\n\n用户额外要求:{user_prompt.strip()}" if user_prompt.strip() else base_prompt
return self._make_json_request(prompt, task_name="主题分析")
def generate_canon_bible(self, one_line_theme, selected_genre, audience_and_tone="", user_prompt=""):
"""生成故事创作规范(Canon Bible)"""
if user_prompt is None:
user_prompt = ""
prompt = self._get_prompt("canon_bible", user_prompt,
one_line_theme=one_line_theme,
selected_genre=selected_genre,
audience_and_tone=audience_and_tone)
if prompt is None:
# 后备提示词
base_prompt = f"请为以下故事创建创作规范(Canon Bible),包括风格、节奏、视角策略、世界观等,以JSON格式返回。\n\n主题:{one_line_theme}\n类型:{selected_genre}\n目标读者:{audience_and_tone}"
prompt = f"{base_prompt}\n\n用户额外要求:{user_prompt.strip()}" if user_prompt.strip() else base_prompt
result = self._make_json_request(prompt, task_name="Canon Bible生成")
# 如果JSON解析完全失败,返回一个默认的Canon Bible结构
if result is None:
print("[Canon Bible生成] 使用默认结构")
return {
"tone": {
"register": "根据主题调整的语域",
"rhythm": "适合体裁的节奏"
},
"pov_rules": {
"default": "close-third",
"allowed": ["first", "close-third"],
"distance": "近距"
},
"genre_addendum": {},
"theme": {
"thesis": one_line_theme,
"antithesis": "待完善",
"synthesis": "待完善"
},
"world": {
"time_place": "根据主题设定",
"constraints": ["现实约束待补充"]
},
"style_do": ["具体名词>形容词", "动作承载心理"],
"style_dont": ["空洞情绪句", "滥用比喻"],
"lexicon": {
"key_terms": ["待补充"],
"ban_phrases": ["陈词滥调"]
},
"continuity": {
"timeline": [],
"setups": [],
"payoffs": []
},
"lengths": {
"theme_paragraph": 800,
"story_outline": 1200,
"chapter_outline": 1200,
"chapter_summary": 450,
"chapter": 1800
}
}
return result
def generate_theme_paragraph_variants(self, one_line_theme, selected_genre, user_intent, canon="", user_prompt=""):
"""生成3个版本的主题段落"""
if user_prompt is None:
user_prompt = ""
prompt = self._get_prompt("theme_paragraph_variants", user_prompt,
one_line_theme=one_line_theme,
selected_genre=selected_genre,
user_intent=user_intent,
canon=canon)
if prompt is None:
# 后备提示词
base_prompt = f"请根据以下信息生成3个不同版本的故事构想,每个版本约{GENERATION_CONFIG['theme_paragraph_length']}字,以JSON格式返回。\n\n主题:{one_line_theme}\n类型:{selected_genre}\n用户意图:{user_intent}"
prompt = f"{base_prompt}\n\n用户额外要求:{user_prompt.strip()}" if user_prompt.strip() else base_prompt
return self._make_mixed_content_request(prompt, task_name="主题段落生成")
def _make_mixed_content_request(self, prompt, timeout=None, task_name="", with_retry=True):
"""处理混合格式响应:正文内容 + JSON元数据"""
response_text = self._make_request(prompt, timeout, task_name, with_retry)
if response_text is None:
return None
try:
# 尝试分离正文和JSON部分
# 查找JSON部分(通常在最后)
json_match = re.search(r'\{[^{}]*"variants"[^{}]*\[[^\]]*\][^{}]*\}', response_text, re.DOTALL)
if json_match:
json_text = json_match.group(0)
content_text = response_text[:json_match.start()].strip()
# 解析JSON
json_data = json.loads(json_text)
# 分离正文内容为3段
paragraphs = self._split_content_into_paragraphs(content_text)
# 将内容添加到variants中
if 'variants' in json_data and len(paragraphs) >= len(json_data['variants']):
for i, variant in enumerate(json_data['variants']):
if i < len(paragraphs):
variant['content'] = paragraphs[i].strip()
return json_data
else:
# 如果没找到JSON,尝试直接解析为JSON
return json.loads(response_text)
except (json.JSONDecodeError, Exception) as e:
print(f"[{task_name}] 混合内容解析失败: {e}")
return None
def _split_content_into_paragraphs(self, content_text: str) -> list:
"""将正文内容分割为段落"""
# 移除多余的空行和空格
content_text = content_text.strip()
# 按双换行符分割段落
paragraphs = re.split(r'\n\s*\n', content_text)
# 过滤掉空段落和过短的段落
paragraphs = [p.strip() for p in paragraphs if p.strip() and len(p.strip()) > 50]
# 如果段落少于3个,尝试按其他方式分割
if len(paragraphs) < 3:
# 尝试按句号+换行分割
paragraphs = re.split(r'。\s*\n', content_text)
paragraphs = [p.strip() + '。' if not p.endswith('。') else p.strip() for p in paragraphs if p.strip() and len(p.strip()) > 50]
return paragraphs[:3] # 只返回前3个段落
def generate_theme_paragraph_with_genre(self, one_line_theme, selected_genre, user_intent, canon="", user_prompt=""):
"""基于类型和用户意图生成主题段落"""
if user_prompt is None:
user_prompt = ""
prompt = self._get_prompt("theme_paragraph", user_prompt,
one_line_theme=one_line_theme,
selected_genre=selected_genre,
user_intent=user_intent,
canon=canon)
if prompt is None:
# 后备提示词
base_prompt = f"请将以下一句话主题按照{selected_genre}类型的风格,扩展成一段具体的故事构想,字数在{GENERATION_CONFIG['theme_paragraph_length']}。\n\n主题:{one_line_theme}\n用户意图:{user_intent}"
prompt = f"{base_prompt}\n\n用户额外要求:{user_prompt.strip()}" if user_prompt.strip() else base_prompt
return self._make_request(prompt)
def generate_character_description(self, char_name, user_prompt="", one_line_theme="", story_context="", canon=""):
"""生成角色描述"""
# 如果没有提供上下文信息,尝试从数据管理器获取
if not one_line_theme or not story_context:
# 导入放在方法内部,避免循环导入
from project_data_manager import project_data_manager
data_manager = project_data_manager.get_data_manager()
if not one_line_theme:
theme_data = data_manager.read_theme_one_line()
if isinstance(theme_data, dict):
one_line_theme = theme_data.get("theme", "")
elif isinstance(theme_data, str):
one_line_theme = theme_data
else:
one_line_theme = ""
if not story_context:
# 使用段落主题作为故事背景
story_context = data_manager.read_theme_paragraph() or ""
prompt = self._get_prompt("character_description", user_prompt,
char_name=char_name,
one_line_theme=one_line_theme,
story_context=story_context,
canon=canon)
if prompt is None:
# 后备提示词
base_prompt = f"请为小说角色 '{char_name}' 创建一个详细的角色描述,包括外貌特征、性格特点、背景故事、能力特长等方面,字数在{GENERATION_CONFIG['character_description_length']}。请直接输出角色描述,不要包含额外说明和标题。"
prompt = f"{base_prompt}\n\n用户额外要求:{user_prompt.strip()}" if user_prompt.strip() else base_prompt
return self._make_request(prompt)
def generate_location_description(self, loc_name, user_prompt="", one_line_theme="", story_context="", canon=""):
"""生成场景描述"""
# 如果没有提供上下文信息,尝试从数据管理器获取
if not one_line_theme or not story_context:
# 导入放在方法内部,避免循环导入
from project_data_manager import project_data_manager
data_manager = project_data_manager.get_data_manager()
if not one_line_theme:
theme_data = data_manager.read_theme_one_line()
if isinstance(theme_data, dict):
one_line_theme = theme_data.get("theme", "")
elif isinstance(theme_data, str):
one_line_theme = theme_data
else:
one_line_theme = ""
if not story_context:
# 使用段落主题作为故事背景
story_context = data_manager.read_theme_paragraph() or ""
prompt = self._get_prompt("location_description", user_prompt,
loc_name=loc_name,
one_line_theme=one_line_theme,
story_context=story_context,
canon=canon)
if prompt is None:
# 后备提示词
base_prompt = f"请为小说场景 '{loc_name}' 创建一个详细的场景描述,包括地理位置、环境特色、建筑风格、氛围感受、历史背景、重要特征等方面,字数在{GENERATION_CONFIG['location_description_length']}。请直接输出场景描述,不要包含额外说明和标题。"
prompt = f"{base_prompt}\n\n用户额外要求:{user_prompt.strip()}" if user_prompt.strip() else base_prompt
return self._make_request(prompt)
def generate_item_description(self, item_name, user_prompt="", one_line_theme="", story_context="", canon=""):
"""生成道具描述"""
# 如果没有提供上下文信息,尝试从数据管理器获取
if not one_line_theme or not story_context:
# 导入放在方法内部,避免循环导入
from project_data_manager import project_data_manager
data_manager = project_data_manager.get_data_manager()
if not one_line_theme:
theme_data = data_manager.read_theme_one_line()
if isinstance(theme_data, dict):
one_line_theme = theme_data.get("theme", "")
elif isinstance(theme_data, str):
one_line_theme = theme_data
else:
one_line_theme = ""
if not story_context:
# 使用段落主题作为故事背景
story_context = data_manager.read_theme_paragraph() or ""
prompt = self._get_prompt("item_description", user_prompt,
item_name=item_name,
one_line_theme=one_line_theme,
story_context=story_context,
canon=canon)
if prompt is None:
# 后备提示词
base_prompt = f"请为小说道具 '{item_name}' 创建一个详细的道具描述,包括外观特征、材质工艺、功能用途、历史来源、特殊能力、重要意义等方面,字数在{GENERATION_CONFIG['item_description_length']}。请直接输出道具描述,不要包含额外说明和标题。"
prompt = f"{base_prompt}\n\n用户额外要求:{user_prompt.strip()}" if user_prompt.strip() else base_prompt
return self._make_request(prompt)
def generate_story_outline(self, one_line_theme, paragraph_theme, characters_info="", canon="", user_prompt=""):
"""生成故事大纲"""
prompt = self._get_prompt("story_outline", user_prompt,
one_line_theme=one_line_theme,
paragraph_theme=paragraph_theme,
characters_info=characters_info,
canon=canon)
if prompt is None:
# 后备提示词
base_prompt = f"""请基于以下信息创建一个详细的小说故事大纲:
一句话主题:{one_line_theme}
段落主题:{paragraph_theme}{characters_info}
请创建一个包含以下要素的完整故事大纲:
1. 故事背景设定
2. 主要情节线索
3. 关键转折点
4. 冲突与高潮
5. 结局方向
大纲应该详细具体,字数在{GENERATION_CONFIG['story_outline_length']}。请直接输出故事大纲,不要包含额外说明和标题。"""
prompt = f"{base_prompt}\n\n用户额外要求:{user_prompt.strip()}" if user_prompt.strip() else base_prompt
return self._make_request(prompt)
def generate_chapter_outline(self, one_line_theme, story_outline, characters_info="", canon="", user_prompt=""):
"""生成分章细纲"""
prompt = self._get_prompt("chapter_outline", user_prompt,
one_line_theme=one_line_theme,
story_outline=story_outline,
characters_info=characters_info,
canon=canon)
if prompt is None:
# 后备提示词
base_prompt = f"""请基于以下信息创建详细的分章细纲:
主题:{one_line_theme}
故事大纲:{story_outline}{characters_info}
请将故事分解为5-10个章节,每个章节包含:
1. 章节标题
2. 章节大纲(150-200字)
3. 主要情节点
4. 角色发展
请以JSON格式输出,格式如下:
{{
"chapters": [
{{
"title": "章节标题",
"outline": "章节详细大纲内容"
}}
]
}}
请确保输出的是有效的JSON格式。"""
if user_prompt.strip():
prompt = f"{base_prompt}\n\n用户额外要求:{user_prompt.strip()}"
else:
prompt = base_prompt
# 使用专门的JSON请求方法
result = self._make_json_request(prompt, task_name="分章细纲")
if result and isinstance(result, dict):
return result
else:
# 如果JSON解析失败,返回原始文本
return self._make_request(prompt)
def generate_chapter_summary(self, chapter_card, chapter_num, context_info, canon="", user_prompt=""):
"""生成章节概要"""
if user_prompt is None:
user_prompt = ""
prompt = self._get_prompt(
"chapter_summary",
user_prompt=user_prompt,
chapter_num=chapter_num,
chapter_card=chapter_card,
context_info=context_info,
canon=canon
)
if prompt is None:
# 后备提示词
base_prompt = f"""请基于以下信息为第{chapter_num}章创建详细的章节概要:
{context_info}
当前章节信息:
章节标题:{chapter_card.get('title', f'第{chapter_num}章')}
章节大纲:{chapter_card.get('outline', '无大纲')}
请创建一个详细的章节概要,包含:
1. 场景设定(时间、地点、环境)
2. 主要人物及其行动
3. 关键情节发展
4. 对话要点
5. 情感氛围
6. 与整体故事的连接
概要应该详细具体,字数在{GENERATION_CONFIG['chapter_summary_length']},为后续的正文写作提供充分的指导。请直接输出章节概要,不要包含额外说明和标题。"""
if user_prompt and user_prompt.strip():
prompt = f"{base_prompt}\n\n用户额外要求:{user_prompt.strip()}"
else:
prompt = base_prompt
return self._make_request(prompt)
def generate_novel_chapter(self, chapter_card, summary_info, chapter_num, context_info, canon="", user_prompt=""):
"""生成单章小说正文"""
if user_prompt is None:
user_prompt = ""
task_name = f"章节 {chapter_num} 正文生成"
prompt = self._get_prompt(
"novel_chapter",
user_prompt=user_prompt,
chapter_num=chapter_num,
chapter_card=chapter_card,
summary_info=summary_info,
context_info=context_info,
canon=canon
)
if prompt is None:
# 后备提示词
base_prompt = f"""请基于以下信息为第{chapter_num}章创建完整的小说正文: