-
Notifications
You must be signed in to change notification settings - Fork 1
/
api.py
175 lines (144 loc) · 6.34 KB
/
api.py
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
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import main
from typing import Dict, Any
from fastapi.responses import JSONResponse
import json
import os
from datetime import datetime
app = FastAPI(title="Game API", description="API for game interactions")
class ScreenplayRequest(BaseModel):
screenplay: str
class ChatRequest(BaseModel):
input: str
class ApiKeyRequest(BaseModel):
api_key: str
base_url: str = "https://internlm-chat.intern-ai.org.cn/puyu/api/v1"
class InitRequest(BaseModel):
api_key: str
base_url: str = "https://internlm-chat.intern-ai.org.cn/puyu/api/v1"
def save_response_to_file(endpoint: str, response_data: Dict[str, Any]):
"""保存 API 响应到单个JSON文件,每次都覆盖之前的内容"""
filename = "responses.json"
# 验证响应数据是否可以被序列化为JSON
try:
# 先尝试序列化响应数据,确保它是有效的JSON
json.dumps(response_data, ensure_ascii=False)
except (TypeError, json.JSONDecodeError) as e:
print(f"Error: Invalid response data format: {str(e)}")
return
# 创建新的响应数据结构
all_responses = {}
# 添加时间戳到响应数据中
response_data['timestamp'] = datetime.now().strftime("%Y%m%d_%H%M%S")
# 设置新的响应数据
all_responses[endpoint] = response_data
# 直接写入新文件,覆盖旧内容
try:
with open(filename, 'w', encoding='utf-8') as f:
json.dump(all_responses, f, ensure_ascii=False, indent=2)
except Exception as e:
print(f"Error: Failed to save response data: {str(e)}")
@app.post("/select-screenplay")
@app.get("/select-screenplay/{screenplay}")
async def select_screenplay(screenplay: str = None, request: ScreenplayRequest = None):
try:
# Handle both GET and POST methods
screenplay_value = screenplay if screenplay else request.screenplay if request else None
if not screenplay_value:
raise HTTPException(status_code=400, detail="Screenplay value is required")
main.user_select_screenplay(screenplay_value)
return JSONResponse(content={"message": "Screenplay selected successfully"}, media_type="application/json; charset=utf-8")
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/chat")
@app.get("/chat/{input}")
async def chat(input: str = None, request: ChatRequest = None):
try:
# Handle both GET and POST methods
chat_input = input if input else request.input if request else None
if not chat_input:
raise HTTPException(status_code=400, detail="Chat input is required")
# 进行对话
main.user_chat(chat_input)
# 获取最新的状态信息
mood = main.game_state.oneesan.get_mood()
favorability = main.game_state.favorability_instance.get_favorability()
clock = main.game_state.clock_instance.get_time()
state = main.game_state.state_instance.get_state()
# 准备响应数据
response_data = {
"response": main.game_state.oneesan.get_last_response(),
"mood": mood,
"favorability": favorability,
"clock": clock,
"state": state
}
# 保存响应到文件
save_response_to_file("chat", response_data)
# 返回响应
return JSONResponse(content=response_data, media_type="application/json; charset=utf-8")
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/next")
@app.get("/next")
async def next_plot():
try:
response = main.next()
# 获取所有状态信息
mood = main.game_state.oneesan.get_mood()
favorability = main.game_state.favorability_instance.get_favorability()
clock = main.game_state.clock_instance.get_time()
state = main.game_state.state_instance.get_state()
# 准备响应数据
response_data = {
"response": response,
"mood": mood,
"favorability": favorability,
"clock": clock,
"state": state
}
# 保存响应到文件
save_response_to_file("next", response_data)
return JSONResponse(content=response_data, media_type="application/json; charset=utf-8")
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/set-api-key")
async def set_api_key(request: ApiKeyRequest):
try:
main.api_key = request.api_key
main.base_url = request.base_url
return JSONResponse(content={"message": "API key and base URL set successfully"}, media_type="application/json; charset=utf-8")
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/init")
async def initialize():
try:
# 设置API密钥和base_url(使用测试中的值)
main.api_key = "API填在这里"
main.base_url = "https://internlm-chat.intern-ai.org.cn/puyu/api/v1"
# 选择剧本并初始化
main.user_select_screenplay("A screenplay")
# 获取所有状态信息
response = main.game_state.oneesan.chat("哎呀,小朋友,摔疼了吧?要不要来我家坐坐?(月芙的栗色长发散落脸前,我呆呆地望着她,痴痴地伸出手)")["句子"] # 获取初始对话
mood = main.game_state.oneesan.get_mood()
favorability = main.game_state.favorability_instance.get_favorability()
clock = main.game_state.clock_instance.get_time()
state = main.game_state.state_instance.get_state()
# 准备响应数据
response_data = {
"message": "Game initialized successfully",
"response": response,
"mood": mood,
"favorability": favorability,
"clock": clock,
"state": state
}
# 保存响应到文件
save_response_to_file("init", response_data)
return JSONResponse(content=response_data, media_type="application/json; charset=utf-8")
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)