-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathmain.py
252 lines (188 loc) · 7.11 KB
/
main.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
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
import os
import shutil
from fastapi import FastAPI, Depends, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from sqlmodel import SQLModel, create_engine, Session, desc
from models.all import Conversation, Message, ConversationWithMessages
from typing import List
from settings import load_config, logger
from plugins import load_plugins
from alembic import command
from alembic.config import Config
from configparser import ConfigParser
config = load_config()
sqlite_database_url = config.database_url
connect_args = {"check_same_thread": False}
engine = create_engine(sqlite_database_url, echo=True, connect_args=connect_args)
# Introducing a new feature flag
# So GuidanceLLaMAcpp can coexist with FlowAgents
if config.use_flow_agents:
logger.info("Using (experimental) flow agents")
from conversations.document_based_flow import DocumentBasedConversationFlowAgent
convo = DocumentBasedConversationFlowAgent()
else:
logger.info("Using experimental Guidance LLaMA cpp implementation.")
from conversations.document_based import DocumentBasedConversation
convo = DocumentBasedConversation()
def create_db_and_tables():
confparser = ConfigParser()
confparser.read(f"{config.backend_root_path}/alembic.ini")
confparser.set('alembic', 'script_location', f"{config.backend_root_path}/migrations")
confparser.set('alembic', 'prepend_sys_path', config.backend_root_path)
migrations_config_path = os.path.join(config.backend_root_path, "generated_alembic.ini")
with open(migrations_config_path, 'w') as config_file:
confparser.write(config_file)
migrations_config = Config(migrations_config_path)
command.upgrade(migrations_config, "head")
def get_session():
with Session(engine) as session:
yield session
app = FastAPI()
# Load the plugins
load_plugins(app=app)
origins = [
"http://127.0.0.1:5173",
"http://localhost:5173",
"http://0.0.0.0:5173",
]
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.on_event("startup")
def on_startup():
create_db_and_tables()
@app.post('/llm/query/', response_model=str)
def llm_query(*, query: str, session: Session = Depends(get_session)):
"""
Query the LLM
"""
return convo.predict(query, [])
@app.post("/conversations", response_model=Conversation)
def create_conversation(*, session: Session = Depends(get_session), conversation: Conversation):
"""
Create a new conversation.
"""
conversation = Conversation.from_orm(conversation)
session.add(conversation)
session.commit()
session.refresh(conversation)
print(str(conversation))
return conversation
@app.put('/conversations/{conversation_id}', response_model=Conversation)
def update_conversation(*, session: Session = Depends(get_session), conversation_id: int, payload: dict):
"""
Update the title of a conversation.
"""
conversation = session.get(Conversation, conversation_id)
conversation.title = payload["title"]
session.add(conversation)
session.commit()
session.refresh(conversation)
return conversation
@app.delete("/conversations/{conversation_id}")
def delete_conversation(*, session: Session = Depends(get_session), conversation_id: int):
"""
Delete a conversation.
"""
conversation = session.get(Conversation, conversation_id)
session.delete(conversation)
session.commit()
return conversation
@app.get("/conversations", response_model=List[Conversation])
def get_conversations(session: Session = Depends(get_session)):
"""
Get all conversations.
"""
return session.query(Conversation).order_by(desc(Conversation.id)).all()
@app.get("/conversations/{conversation_id}", response_model=ConversationWithMessages)
def get_conversation(conversation_id: int, session: Session = Depends(get_session)):
"""
Get a conversation by id.
"""
conversation = session.get(Conversation, conversation_id)
return conversation
@app.post("/conversations/{conversation_id}/messages", response_model=Message)
def create_message(*, session: Session = Depends(get_session), conversation_id: int, message: Message):
"""
Create a new message.
"""
message = Message.from_orm(message)
session.add(message)
session.commit()
session.refresh(message)
return message
@app.post("/conversations/{conversation_id}/files", response_model=dict)
def upload_file(*, conversation_id: int, file: UploadFile):
"""
Upload a file.
"""
try:
uploaded_file_name = file.filename
filepath = os.path.join(os.getcwd(), "data", config.upload_path, uploaded_file_name)
os.makedirs(os.path.dirname(filepath), mode=0o777, exist_ok=True)
with open(filepath, "wb") as f:
shutil.copyfileobj(file.file, f)
convo.load_document(filepath, conversation_id)
return {"text": f"{uploaded_file_name} has been loaded into memory for this conversation."}
except Exception as e:
logger.error(f"Error adding file to history: {e}")
return f"Error adding file to history: {e}"
@app.post('/llm/{conversation_id}/', response_model=str)
def llm(*, conversation_id: str, query: str, session: Session = Depends(get_session)):
"""
Query the LLM
"""
conversation_data = get_conversation(conversation_id, session)
history = conversation_data.messages
return convo.predict(query, conversation_id)
# we could also work from history only
# return convo.predict(query, history)
@app.post("/conversations/{conversation_id}/messages/{message_id}/upvote", response_model=Message)
def upvote_message(*, session: Session = Depends(get_session), conversation_id: int, message_id: int):
"""
Upvote a message.
"""
message = session.get(Message, message_id)
message.rating = 1
session.add(message)
session.commit()
session.refresh(message)
return message
@app.post("/conversations/{conversation_id}/messages/{message_id}/downvote", response_model=Message)
def downvote_message(*, session: Session = Depends(get_session), conversation_id: int, message_id: int):
"""
Downvote a message.
"""
message = session.get(Message, message_id)
message.rating = -1
session.add(message)
session.commit()
session.refresh(message)
return message
@app.post("/conversations/{conversation_id}/messages/{message_id}/resetVote", response_model=Message)
def reset_message_vote(*, session: Session = Depends(get_session), conversation_id: int, message_id: int):
"""
Reset a message vote.
"""
message = session.get(Message, message_id)
message.rating = 0
session.add(message)
session.commit()
session.refresh(message)
return message
@app.post("/reset", response_model=dict)
def reset_all():
"""
Reset the database.
"""
SQLModel.metadata.drop_all(engine)
print("Database has been reset.")
SQLModel.metadata.create_all(engine)
return {"text": "Database has been reset."}
if __name__ == "__main__":
import uvicorn
uvicorn.run("main:app", host="0.0.0.0", port=7865, reload=False)