-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoc_apiagent.py
More file actions
1213 lines (1014 loc) · 43.8 KB
/
Copy pathcoc_apiagent.py
File metadata and controls
1213 lines (1014 loc) · 43.8 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
# coc_apiagent_fixed.py - 修复版本,支持角色卡聊天系统
import uvicorn
from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import StreamingResponse
from pydantic import BaseModel, Field
from typing import Dict, List, Optional, Any, Tuple
import uuid # 用于生成 Session ID
import threading # 线程安全
import json # 用于SSE数据编码
# --- 导入 Agent 逻辑核心和状态模型 ---
from coc_agent import (
CoCAgentLogic,
SessionState,
GameState,
KeeperState,
Investigator,
Characteristics,
InvestigatorSkills,
PREGEN_CHARACTERS
)
# --- 导入角色卡聊天系统 ---
from character_card import CharacterCard
from chat_agent import ChatAgent, ChatState
from card_registry import registry as card_registry
from base_agent import BaseAgent, BaseChatState
# --- 导入职业数据和背景故事模型 ---
from occupation_data import (
get_all_occupations,
get_occupation_by_id,
search_occupations,
Occupation
)
from character_sheet import Background
# --- 导入统计日志模块 ---
from session_logger import logger, safe_log
# --- 导入会话持久化模块 ---
from session_persistence import SessionPersistence
# --- 导入统计分析模块 ---
from stats_analyzer import analyzer
from app_config import load_settings
from admin_security import is_admin_request_allowed
from session_contracts import investigator_to_dto, session_state_to_dto
from playable_keeper import (
build_action_payload as build_playable_action_payload,
handle_action as handle_playable_action,
start_session_state as start_playable_session_state,
text_chunks as playable_text_chunks,
)
# --- 1. 配置 ---
# 默认 API 配置现在在 base_agent.py 中统一管理
settings = load_settings()
# 存储用户自定义的API配置(全局)
user_api_config: Optional[Dict] = None
# --- 2. 初始化 ---
print("正在初始化 FastAPI 应用...")
app = FastAPI(
title="CoC Agent API (无用户注册版)",
description="提供 CoC Agent 游戏逻辑和状态管理的后端服务",
version="1.2.0" # 版本升级到1.2.0,支持自定义API
)
# 添加 CORS 中间件
app.add_middleware(
CORSMiddleware,
allow_origins=settings.cors_origins,
allow_origin_regex=r"https://.*\.trycloudflare\.com" if settings.allow_public_tunnel_hosts else None,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
print("正在初始化 Agent 逻辑核心...")
try:
# 如果有用户配置,使用用户配置;否则使用默认配置
agent_logic = CoCAgentLogic(custom_config=user_api_config)
print("[SUCCESS] Agent logic core loaded successfully!")
except Exception as e:
print(f"[ERROR] Agent logic core loading failed: {e}")
agent_logic = None
def reinitialize_agent():
"""重新初始化Agent(用于更新API配置后)"""
global agent_logic
try:
agent_logic = CoCAgentLogic(custom_config=user_api_config)
print(f"[SUCCESS] Agent重新初始化成功 (使用{'自定义' if user_api_config else '默认'}配置)")
return True
except Exception as e:
print(f"[ERROR] Agent重新初始化失败: {e}")
return False
# --- 3. 简化的会话管理(无需用户) ---
# 直接管理session_id -> SessionState
sessions: Dict[str, SessionState] = {}
# 线程安全锁
sessions_lock = threading.RLock()
# --- 会话持久化管理器 ---
persistence = SessionPersistence()
# --- 启动时自动加载上次的会话(如果存在)---
print("检查是否有之前的会话备份...")
try:
loaded_sessions = persistence.import_sessions()
if loaded_sessions:
with sessions_lock:
sessions.update(loaded_sessions)
print(f"[OK] 已恢复 {len(loaded_sessions)} 个会话!玩家可以继续之前的游戏。")
except Exception as e:
print(f"[!] 加载会话备份失败: {e}")
print(" 将从空白状态开始")
# --- 4. API 数据模型 ---
class StartSessionRequest(BaseModel):
# 不需要user_id,直接开始游戏
pass
class StartSessionResponse(BaseModel):
session_id: str
initial_response: Dict
class ActionRequest(BaseModel):
session_id: str
player_input: Optional[str] = None
roll_result: Optional[int] = None
# 移除user_id字段
class SaveGameRequest(BaseModel):
session_id: str
filename: str = "quicksave"
class ActionResponse(BaseModel):
kp_response: Any # 改为Any类型,支持字符串、字典等各种格式
investigator: Optional[Dict] = None
session_state: Optional[Dict] = None
class SimpleResponse(BaseModel):
status: str
message: Optional[str] = None
class ApiConfigRequest(BaseModel):
api_key: str
base_url: str
model: str
provider: Optional[str] = "Custom API"
class ApiConfigResponse(BaseModel):
status: str
message: str
current_config: Optional[Dict] = None
# ========== 新增:车卡系统API模型 ==========
class CreateCustomCharacterRequest(BaseModel):
"""创建自定义角色请求"""
session_id: str
name: str
age: int = Field(default=30, ge=15, le=90)
sex: str = Field(default="未知")
birthplace: Optional[str] = None
residence: Optional[str] = None
occupation_id: str
characteristics: Dict[str, int] # STR, CON, SIZ等
class AllocateSkillsRequest(BaseModel):
"""分配技能点请求"""
session_id: str
occupation_skills: Dict[str, int] # {技能名: 分配点数}
personal_skills: Dict[str, int] # {技能名: 分配点数}
class UpdateBackgroundRequest(BaseModel):
"""更新背景故事请求"""
session_id: str
background: Dict[str, Any] # Background模型的字典形式
class OccupationListResponse(BaseModel):
"""职业列表响应"""
occupations: List[Dict]
total: int
class CharacterCreationResponse(BaseModel):
"""角色创建响应"""
status: str
message: str
investigator: Optional[Dict] = None
# --- 5. 会话辅助函数 ---
def create_session() -> str:
"""创建新的游戏会话"""
session_id = str(uuid.uuid4())
with sessions_lock:
# 初始化游戏状态和会话状态
initial_game_state = GameState()
initial_kp_state = KeeperState()
session_state = SessionState(
session_id=session_id,
game_state=initial_game_state,
keeper_state=initial_kp_state
)
sessions[session_id] = session_state
print(f"[API] 创建新会话: {session_id}")
return session_id
def get_session(session_id: str) -> Optional[SessionState]:
"""获取会话"""
with sessions_lock:
return sessions.get(session_id)
def require_admin_access(request: Request):
client_host = request.client.host if request.client else None
if not is_admin_request_allowed(request.headers, client_host, settings):
raise HTTPException(status_code=403, detail="Admin access denied")
# --- 6. API 路由 ---
@app.get("/health", response_model=SimpleResponse)
async def health_check():
"""健康检查"""
return SimpleResponse(status="ok", message="服务正常运行")
@app.post("/api/start_session", response_model=StartSessionResponse)
@app.post("/start_session", response_model=StartSessionResponse)
async def start_session(request: StartSessionRequest):
"""开始新的游戏会话 - 无需用户登录"""
session_id = str(uuid.uuid4())
session_state, initial_response = start_playable_session_state(session_id)
with sessions_lock:
sessions[session_id] = session_state
try:
logger.log_session_start(session_id=session_id)
logger.log_game_phase(session_id=session_id, phase="choose_investigator")
except Exception as e:
print(f"[!] [统计] 记录会话开始失败: {e}")
return StartSessionResponse(session_id=session_id, initial_response=initial_response)
@app.post("/api/send_action", response_model=ActionResponse)
@app.post("/send_action", response_model=ActionResponse)
async def send_action(request: ActionRequest):
"""发送玩家行动 - 无需用户ID"""
session_state = get_session(request.session_id)
if not session_state:
raise HTTPException(status_code=404, detail="会话不存在,请重新开始游戏")
new_state, kp_response = handle_playable_action(
session_state,
player_input=request.player_input,
roll_result=request.roll_result,
)
with sessions_lock:
sessions[request.session_id] = new_state
try:
logger.log_session_state(session_id=request.session_id, session_state=new_state)
except Exception as e:
print(f"[!] [统计] 记录状态快照失败: {e}")
return build_playable_action_payload(new_state, kp_response)
# 【统计】记录玩家行动
try:
if request.player_input:
logger.log_player_action(
session_id=request.session_id,
action_text=request.player_input,
game_state={
'current_location': getattr(session_state.game_state, 'current_location', None),
'current_enemies': getattr(session_state.game_state, 'current_enemies', []),
'current_npcs': getattr(session_state.game_state, 'current_npcs', []),
'combat_turn': getattr(session_state.game_state, 'combat_turn', 0)
}
)
except Exception as e:
print(f"[!] [统计] 记录玩家行动失败: {e}")
try:
print(f"[DEBUG] 收到send_action请求: session_id={request.session_id}")
print(f"[DEBUG] player_input: {request.player_input}, roll_result: {request.roll_result}")
# 检查是否有roll_result需要处理
if request.roll_result is not None:
# 处理技能检定结果
if session_state.pending_roll:
print(f"[DEBUG] 处理技能检定: {session_state.pending_roll.skill_name}, 投骰: {request.roll_result}")
outcome_str, outcome_level = agent_logic.resolve_skill_check(
investigator=session_state.investigator,
roll_result=request.roll_result,
skill_name=session_state.pending_roll.skill_name,
difficulty=session_state.pending_roll.difficulty,
session_id=request.session_id # 传递session_id以启用日志记录
)
# 清除pending_roll
session_state.pending_roll = None
# 调用next_turn处理检定结果
new_state, kp_response = agent_logic.next_turn(
current_state=session_state,
roll_outcome=outcome_str
)
# 处理SAN检定结果
elif session_state.pending_san_check:
print(f"[DEBUG] 处理SAN检定: 投骰: {request.roll_result}")
outcome_str, san_loss, madness = agent_logic.resolve_sanity_check(
investigator=session_state.investigator,
roll_result=request.roll_result,
success_loss_str=session_state.pending_san_check.success_loss,
failure_loss_str=session_state.pending_san_check.failure_loss,
session_id=request.session_id # 传递session_id以启用日志记录
)
# 更新SAN值
session_state.investigator.current_sanity = max(0, session_state.investigator.current_sanity - san_loss)
# 清除pending_san_check
session_state.pending_san_check = None
# 调用next_turn处理SAN检定结果
new_state, kp_response = agent_logic.next_turn(
current_state=session_state,
san_check_outcome=outcome_str
)
else:
print(f"[WARNING] 收到roll_result但没有pending_roll或pending_san_check")
# 当作普通输入处理
new_state, kp_response = agent_logic.process_action(
session_id=request.session_id,
player_input=request.player_input,
session_state=session_state
)
else:
# 没有roll_result,正常处理玩家行动
new_state, kp_response = agent_logic.process_action(
session_id=request.session_id,
player_input=request.player_input,
session_state=session_state
)
# 更新会话状态
with sessions_lock:
sessions[request.session_id] = new_state
# 【统计】记录状态快照
try:
logger.log_session_state(
session_id=request.session_id,
session_state=new_state
)
# 如果角色刚创建,记录角色选择
if new_state.investigator and request.player_input:
# 检测是否是角色选择的行动(如 "1,李明" 格式)
if ',' in request.player_input:
character_data = {
'name': getattr(new_state.investigator, 'name', None),
'occupation': getattr(new_state.investigator, 'occupation', None),
'current_sanity': getattr(new_state.investigator, 'current_sanity', None) or getattr(new_state.investigator, 'current_san', None),
'hp': getattr(new_state.investigator, 'hp', None) or getattr(new_state.investigator, 'current_hp', None)
}
if character_data['name'] and character_data['occupation']:
logger.log_character_selected(request.session_id, character_data)
logger.log_game_phase(session_id=request.session_id, phase='in-room')
# 检测场景切换
old_location = getattr(session_state.game_state, 'current_location', None)
new_location = getattr(new_state.game_state, 'current_location', None)
if old_location and new_location and old_location != new_location:
logger.log_location_change(request.session_id, old_location, new_location)
except Exception as e:
print(f"[!] [统计] 记录状态快照失败: {e}")
# 构建完整的响应,包含 kp_response 和 investigator 数据
response_data = {
"kp_response": kp_response
}
# 添加更新后的调查员数据(如果有)
if new_state.investigator:
response_data["investigator"] = investigator_to_dto(new_state.investigator)
response_data["session_state"] = session_state_to_dto(new_state)
return response_data
except Exception as e:
print(f"[API] 处理行动失败: {e}")
raise HTTPException(status_code=500, detail=f"处理行动失败: {str(e)}")
@app.post("/api/send_action_stream")
@app.post("/send_action_stream")
async def send_action_stream(request: ActionRequest):
"""发送玩家行动(流式版本)- 使用SSE流式返回AI响应"""
session_state = get_session(request.session_id)
if not session_state:
raise HTTPException(status_code=404, detail="会话不存在,请重新开始游戏")
new_state, kp_response = handle_playable_action(
session_state,
player_input=request.player_input,
roll_result=request.roll_result,
)
with sessions_lock:
sessions[request.session_id] = new_state
async def generate_playable_sse():
text = kp_response.get("text", "") if isinstance(kp_response, dict) else str(kp_response)
for chunk in playable_text_chunks(text):
yield f"data: {json.dumps({'type': 'chunk', 'data': chunk}, ensure_ascii=False)}\n\n"
complete_data = {
"type": "complete",
**build_playable_action_payload(new_state, kp_response),
}
yield f"data: {json.dumps(complete_data, ensure_ascii=False)}\n\n"
return StreamingResponse(
generate_playable_sse(),
media_type="text/event-stream",
headers={
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"X-Accel-Buffering": "no",
},
)
# 【统计】记录玩家行动
try:
if request.player_input:
logger.log_player_action(
session_id=request.session_id,
action_text=request.player_input,
game_state={
'current_location': getattr(session_state.game_state, 'current_location', None),
'current_enemies': getattr(session_state.game_state, 'current_enemies', []),
'current_npcs': getattr(session_state.game_state, 'current_npcs', []),
'combat_turn': getattr(session_state.game_state, 'combat_turn', 0)
}
)
except Exception as e:
print(f"[!] [统计] 记录玩家行动失败: {e}")
async def generate_sse():
"""SSE生成器"""
try:
print(f"[DEBUG_STREAM] 收到流式请求: session_id={request.session_id}")
# 处理检定结果
if request.roll_result is not None:
if session_state.pending_roll:
outcome_str, outcome_level = agent_logic.resolve_skill_check(
investigator=session_state.investigator,
roll_result=request.roll_result,
skill_name=session_state.pending_roll.skill_name,
difficulty=session_state.pending_roll.difficulty,
session_id=request.session_id
)
session_state.pending_roll = None
generator = agent_logic.next_turn_stream(current_state=session_state, roll_outcome=outcome_str)
elif session_state.pending_san_check:
outcome_str, san_loss, madness = agent_logic.resolve_sanity_check(
investigator=session_state.investigator,
roll_result=request.roll_result,
success_loss_str=session_state.pending_san_check.success_loss,
failure_loss_str=session_state.pending_san_check.failure_loss,
session_id=request.session_id
)
session_state.investigator.current_sanity = max(0, session_state.investigator.current_sanity - san_loss)
session_state.pending_san_check = None
generator = agent_logic.next_turn_stream(current_state=session_state, san_check_outcome=outcome_str)
else:
generator = agent_logic.next_turn_stream(current_state=session_state, player_input=request.player_input)
else:
generator = agent_logic.next_turn_stream(current_state=session_state, player_input=request.player_input)
# 逐步发送流式响应
new_state = None
final_response = None
while True:
try:
event = next(generator)
except StopIteration as e:
if e.value is not None:
new_state, final_response_from_gen = e.value
if final_response is None:
final_response = final_response_from_gen
break
event_type = event.get("type")
event_data = event.get("data")
if event_type == "chunk":
sse_data = json.dumps({"type": "chunk", "data": event_data}, ensure_ascii=False)
yield f"data: {sse_data}\n\n"
elif event_type == "tool_call":
sse_data = json.dumps({"type": "tool_call", "data": event_data}, ensure_ascii=False)
yield f"data: {sse_data}\n\n"
elif event_type == "complete":
final_response = event_data
elif event_type == "error":
sse_data = json.dumps({"type": "error", "data": event_data}, ensure_ascii=False)
yield f"data: {sse_data}\n\n"
return
# 更新会话状态
if new_state:
with sessions_lock:
sessions[request.session_id] = new_state
try:
logger.log_session_state(session_id=request.session_id, session_state=new_state)
if new_state.investigator and request.player_input and ',' in request.player_input:
character_data = {
'name': getattr(new_state.investigator, 'name', None),
'occupation': getattr(new_state.investigator, 'occupation', None),
'current_sanity': getattr(new_state.investigator, 'current_sanity', None),
'hp': getattr(new_state.investigator, 'current_hp', None)
}
if character_data['name'] and character_data['occupation']:
logger.log_character_selected(request.session_id, character_data)
logger.log_game_phase(session_id=request.session_id, phase='in-room')
except Exception as e:
print(f"[!] [统计] 记录失败: {e}")
# 发送完成事件
complete_data = {"type": "complete", "kp_response": final_response}
if new_state and new_state.investigator:
complete_data["investigator"] = investigator_to_dto(new_state.investigator)
complete_data["session_state"] = session_state_to_dto(new_state)
sse_data = json.dumps(complete_data, ensure_ascii=False)
yield f"data: {sse_data}\n\n"
except Exception as e:
print(f"[API_STREAM] 流式处理失败: {e}")
error_data = json.dumps({"type": "error", "data": str(e)}, ensure_ascii=False)
yield f"data: {error_data}\n\n"
return StreamingResponse(
generate_sse(),
media_type="text/event-stream",
headers={
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"X-Accel-Buffering": "no"
}
)
@app.get("/api/get_state/{session_id}")
@app.get("/get_state/{session_id}")
async def get_session_state(session_id: str):
"""获取游戏状态"""
session_state = get_session(session_id)
if not session_state:
raise HTTPException(status_code=404, detail="会话不存在")
return {
"session_id": session_id,
"game_state": session_state.game_state.__dict__,
"keeper_state": session_state.keeper_state.__dict__,
"investigator": investigator_to_dto(session_state.investigator),
"session_state": session_state_to_dto(session_state)
}
@app.post("/api/save_game")
@app.post("/save_game")
async def save_game(request: SaveGameRequest):
"""保存当前游戏会话快照。"""
session_state = get_session(request.session_id)
if not session_state:
raise HTTPException(status_code=404, detail="会话不存在,请重新开始游戏")
safe_name = "".join(ch for ch in request.filename if ch.isalnum() or ch in ("-", "_")) or "quicksave"
if not safe_name.endswith(".pkl"):
safe_name = f"{safe_name}.pkl"
with sessions_lock:
snapshot = dict(sessions)
filepath = persistence.export_sessions(snapshot, safe_name)
return {
"status": "success",
"message": "游戏已保存",
"session_id": request.session_id,
"filename": safe_name,
"filepath": filepath,
}
@app.post("/admin/export_sessions")
async def admin_export_sessions(request: Request):
"""管理员接口:导出所有会话到文件,用于服务器重启前备份"""
require_admin_access(request)
try:
with sessions_lock:
# 复制当前所有会话
sessions_copy = dict(sessions)
# 导出到文件
filepath = persistence.export_sessions(sessions_copy)
# 统计信息
active_count = sum(1 for s in sessions_copy.values() if hasattr(s, 'investigator') and s.investigator)
return {
"status": "success",
"message": "会话导出成功",
"filepath": filepath,
"total_sessions": len(sessions_copy),
"sessions_with_characters": active_count
}
except Exception as e:
print(f"[API] 导出会话失败: {e}")
raise HTTPException(status_code=500, detail=f"导出失败: {str(e)}")
@app.get("/admin/sessions_summary")
async def admin_sessions_summary(request: Request):
"""管理员接口:获取当前会话摘要(增强版 + 排行榜)"""
require_admin_access(request)
try:
with sessions_lock:
total = len(sessions)
with_characters = sum(1 for s in sessions.values() if hasattr(s, 'investigator') and s.investigator)
# 统计角色职业偏好
character_preferences = {}
recent_players = []
active_count = 0
for session_id, session in sessions.items():
if hasattr(session, 'investigator') and session.investigator:
investigator_dto = investigator_to_dto(session.investigator)
# 统计职业
occupation = investigator_dto.get('occupation', '未知')
character_preferences[occupation] = character_preferences.get(occupation, 0) + 1
# 收集玩家信息
player_info = {
'name': investigator_dto.get('name', '未命名'),
'occupation': occupation,
'san': investigator_dto.get('san', {}).get('current', 0),
'hp': investigator_dto.get('hp', {}).get('current', 0)
}
recent_players.append(player_info)
active_count += 1
# 按最新的排序,只返回前10个
recent_players = recent_players[-10:][::-1]
# 从日志文件分析排行榜数据
try:
leaderboards = analyzer.analyze_leaderboards()
overall_stats = analyzer.get_overall_stats()
except Exception as e:
print(f"[!] 分析排行榜数据失败: {e}")
leaderboards = {
'chatterbox': [],
'daredevil': [],
'lucky_player': [],
'unlucky_player': []
}
overall_stats = {}
return {
"status": "ok",
"total_sessions": total,
"sessions_with_characters": with_characters,
"active_sessions": active_count,
"character_preferences": character_preferences,
"recent_players": recent_players,
"leaderboards": leaderboards,
"overall_stats": overall_stats
}
except Exception as e:
print(f"[API] 获取会话摘要失败: {e}")
raise HTTPException(status_code=500, detail=str(e))
@app.post("/set_api_config", response_model=ApiConfigResponse)
async def set_api_config(config: ApiConfigRequest):
"""设置用户自定义API配置"""
global user_api_config
try:
# 验证配置
if not config.api_key or not config.base_url or not config.model:
raise HTTPException(status_code=400, detail="API配置不完整,请提供api_key、base_url和model")
# 保存配置
user_api_config = {
'api_key': config.api_key,
'base_url': config.base_url,
'model': config.model,
'provider': config.provider
}
# 重新初始化Agent
if not reinitialize_agent():
raise HTTPException(status_code=500, detail="API配置保存成功但初始化失败,请检查配置是否正确")
print(f"[API] 用户API配置已更新: {config.provider} ({config.model})")
return ApiConfigResponse(
status="success",
message=f"API配置已成功设置为 {config.provider}",
current_config={
'provider': config.provider,
'model': config.model,
'base_url': config.base_url,
}
)
except HTTPException:
raise
except Exception as e:
print(f"[API] 设置API配置失败: {e}")
raise HTTPException(status_code=500, detail=f"设置API配置失败: {str(e)}")
@app.post("/test_api_config")
async def test_api_config(config: ApiConfigRequest):
"""测试API配置连接"""
try:
# 验证配置
if not config.api_key or not config.base_url or not config.model:
raise HTTPException(status_code=400, detail="API配置不完整")
# 尝试创建临时客户端并测试连接
import openai
test_client = openai.OpenAI(
api_key=config.api_key,
base_url=config.base_url
)
# 发送测试请求
test_response = test_client.chat.completions.create(
model=config.model,
messages=[{"role": "user", "content": "测试"}],
max_tokens=10,
timeout=10
)
print(f"[API] API配置测试成功: {config.provider} ({config.model})")
return {
"status": "success",
"message": f"成功连接到 {config.provider}",
"model": config.model
}
except Exception as e:
print(f"[API] API配置测试失败: {e}")
raise HTTPException(
status_code=400,
detail=f"连接测试失败: {str(e)}"
)
@app.get("/api_config_status")
async def get_api_config_status():
"""获取当前API配置状态"""
if user_api_config:
return {
"status": "custom",
"message": "使用自定义API配置",
"config": {
'provider': user_api_config.get('provider'),
'model': user_api_config.get('model'),
'base_url': user_api_config.get('base_url'),
}
}
else:
# 返回默认配置信息
default_llm = load_settings().selected_llm()
default_config = {
'provider': default_llm.provider,
'model': default_llm.model,
}
return {
"status": "default",
"message": "使用默认API配置",
"config": default_config
}
# ========== 新增:车卡系统API端点 ==========
@app.get("/api/occupations", response_model=OccupationListResponse)
async def get_occupations(search: Optional[str] = None):
"""
获取职业列表
Args:
search: 可选,搜索关键词(支持中英文名称和描述搜索)
"""
try:
if search:
occupations = search_occupations(search)
else:
occupations = get_all_occupations()
# 转换为字典格式
occupations_dict = [occ.model_dump() for occ in occupations]
return OccupationListResponse(
occupations=occupations_dict,
total=len(occupations_dict)
)
except Exception as e:
print(f"[API] 获取职业列表失败: {e}")
raise HTTPException(status_code=500, detail=f"获取职业列表失败: {str(e)}")
@app.get("/api/occupations/{occupation_id}")
async def get_occupation(occupation_id: str):
"""
获取指定职业的详细信息
Args:
occupation_id: 职业ID
"""
try:
occupation = get_occupation_by_id(occupation_id)
if not occupation:
raise HTTPException(status_code=404, detail=f"职业 '{occupation_id}' 不存在")
return occupation.model_dump()
except HTTPException:
raise
except Exception as e:
print(f"[API] 获取职业详情失败: {e}")
raise HTTPException(status_code=500, detail=f"获取职业详情失败: {str(e)}")
@app.post("/api/character/create_custom", response_model=CharacterCreationResponse)
async def create_custom_character(request: CreateCustomCharacterRequest):
"""
创建自定义角色
这是车卡流程的第一步,创建基础角色信息
"""
try:
# 获取会话,如果不存在则创建
session_state = get_session(request.session_id)
if not session_state:
# 为车卡系统创建临时会话
print(f"[API] 车卡系统:创建临时会话 {request.session_id}")
with sessions_lock:
initial_game_state = GameState()
initial_kp_state = KeeperState()
session_state = SessionState(
session_id=request.session_id,
game_state=initial_game_state,
keeper_state=initial_kp_state
)
sessions[request.session_id] = session_state
# 获取职业信息
occupation = get_occupation_by_id(request.occupation_id)
if not occupation:
raise HTTPException(status_code=404, detail=f"职业 '{request.occupation_id}' 不存在")
# 创建Characteristics对象
char = Characteristics(**request.characteristics)
# 创建Investigator对象
investigator = Investigator(
name=request.name,
occupation=occupation.name,
age=request.age,
sex=request.sex,
birthplace=request.birthplace,
residence=request.residence,
occupation_id=request.occupation_id,
characteristics=char
)
# 保存到会话状态
with sessions_lock:
session_state.investigator = investigator
session_state.game_state.current_phase = "character_creation"
print(f"[API] 创建自定义角色成功: {request.name} ({occupation.name})")
return CharacterCreationResponse(
status="success",
message=f"角色 '{request.name}' 创建成功",
investigator=investigator_to_dto(investigator)
)
except HTTPException:
raise
except Exception as e:
print(f"[API] 创建自定义角色失败: {e}")
raise HTTPException(status_code=500, detail=f"创建角色失败: {str(e)}")
@app.put("/api/character/allocate_skills", response_model=CharacterCreationResponse)
async def allocate_skills(request: AllocateSkillsRequest):
"""
分配技能点
车卡流程的技能分配步骤
"""
try:
# 获取会话
session_state = get_session(request.session_id)
if not session_state:
raise HTTPException(status_code=404, detail="会话不存在")
# 检查是否已创建角色
if not session_state.investigator:
raise HTTPException(status_code=400, detail="请先创建角色")
investigator = session_state.investigator
# 应用技能点分配
success = investigator.apply_skill_allocation(
request.occupation_skills,
request.personal_skills
)
if not success:
raise HTTPException(status_code=400, detail="技能点分配失败,请检查点数是否超限")
# 更新会话
with sessions_lock:
session_state.investigator = investigator
print(f"[API] 技能分配成功: {investigator.name}")
return CharacterCreationResponse(
status="success",
message="技能点分配成功",
investigator=investigator_to_dto(investigator)
)
except HTTPException:
raise
except Exception as e:
print(f"[API] 技能分配失败: {e}")
raise HTTPException(status_code=500, detail=f"技能分配失败: {str(e)}")
@app.put("/api/character/update_background", response_model=CharacterCreationResponse)
async def update_background(request: UpdateBackgroundRequest):
"""
更新角色背景故事
车卡流程的背景故事编辑步骤
"""
try:
# 获取会话
session_state = get_session(request.session_id)
if not session_state:
raise HTTPException(status_code=404, detail="会话不存在")
# 检查是否已创建角色
if not session_state.investigator:
raise HTTPException(status_code=400, detail="请先创建角色")
investigator = session_state.investigator
# 创建Background对象
background = Background(**request.background)
# 设置背景故事
investigator.set_background(background)
# 更新会话
with sessions_lock:
session_state.investigator = investigator
session_state.game_state.current_phase = "ready" # 标记为准备完成
print(f"[API] 背景故事更新成功: {investigator.name}")
return CharacterCreationResponse(
status="success",
message="背景故事更新成功,角色创建完成!",
investigator=investigator_to_dto(investigator)
)
except HTTPException:
raise
except Exception as e:
print(f"[API] 更新背景故事失败: {e}")
raise HTTPException(status_code=500, detail=f"更新背景故事失败: {str(e)}")
# ============================================================
# 通用角色聊天 API(新增,与 CoC 端点并存)