-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
178 lines (144 loc) · 5.4 KB
/
app.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
from fastapi import FastAPI, WebSocket
from fastapi.responses import HTMLResponse
import uvicorn
from llm_dialog_manager import Agent
import time
from pathlib import Path
from dotenv import load_dotenv
# Local imports
import logging
# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
import json
from datetime import datetime
import os
app = FastAPI()
def load_env_vars():
"""Load environment variables from .env file"""
env_path = Path(__file__).parent.parent / '.env'
if env_path.exists():
load_dotenv(env_path)
else:
logger.warning(".env file not found. Using system environment variables.")
load_env_vars()
class ChatManager:
def __init__(self):
self.agent = None
self.current_model = None
async def handle_message(self, data):
if isinstance(data, dict):
# Get model from request data
model = data.get('model', 'claude-3-5-sonnet-20241022') # Default to Claude if not specified
# Initialize or update agent with selected model
self.agent = Agent(model_name=model)
# Handle system prompt
system_prompt = data.get('system', '')
if system_prompt:
self.agent.system_prompt = system_prompt
else:
self.agent.system_prompt = "You are an assistant"
# Clear previous messages
self.agent.messages = []
# Add system message
self.agent.add_message("system", self.agent.system_prompt)
# Process message pairs
for pair in data.get('messages', []):
user_message = pair.get('user')
assistant_message = pair.get('assistant')
if user_message:
self.agent.add_message("user", user_message)
if assistant_message:
self.agent.add_message("assistant", assistant_message)
print(self.agent.messages)
#TODO: not working with multiple messages
print("start generate response")
start_time = time.time()
try:
response = self.agent.generate_response() # Removed await
print("response", response)
if isinstance(response, dict):
content = response.get('content', '') # Handle dict response
else:
content = str(response) # Convert response to string if it's not a dict
except Exception as e:
print(f"Generation error: {e}")
content = f"Error generating response: {str(e)}"
end_time = time.time()
# Calculate metrics
elapsed_time = end_time - start_time
formatted_time = f"{elapsed_time:.1f}s"
token_count = len(content) // 4 # Using content instead of response
return {
"content": content, # Using processed content
"metrics": {
"confidence": 92,
"time": formatted_time,
"tokens": token_count
},
"actions": {
"add_to_chat": True
}
}
else:
# Handle other types of data if necessary
pass
chat_manager = ChatManager()
@app.get("/")
async def get():
with open("llm_dialog_manager/interface/static/index.html") as f:
return HTMLResponse(f.read())
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
while True:
try:
data = await websocket.receive_json()
response = await chat_manager.handle_message(data)
await websocket.send_json(response)
except Exception as e:
print(f"Error: {e}")
break
@app.get("/api/history")
async def get_history():
"""Get list of saved chat histories"""
history_dir = Path("chat_history")
if not history_dir.exists():
history_dir.mkdir(exist_ok=True)
return []
histories = []
for file in history_dir.glob("*.json"):
with open(file) as f:
data = json.load(f)
histories.append({
"id": file.stem,
"title": data.get("title", "Untitled"),
"timestamp": data.get("timestamp"),
})
# Sort by timestamp descending
histories.sort(key=lambda x: x["timestamp"], reverse=True)
return histories
@app.get("/api/history/{history_id}")
async def get_history_by_id(history_id: str):
"""Get specific chat history by ID"""
file_path = Path(f"chat_history/{history_id}.json")
if not file_path.exists():
return {"error": "History not found"}
with open(file_path) as f:
return json.load(f)
@app.post("/api/history")
async def save_history(data: dict):
"""Save chat history"""
history_dir = Path("chat_history")
history_dir.mkdir(exist_ok=True)
# Generate unique ID using timestamp
history_id = datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
# Add timestamp to data
data["timestamp"] = datetime.now().isoformat()
with open(history_dir / f"{history_id}.json", "w") as f:
json.dump(data, f)
return {"id": history_id}
def main():
uvicorn.run(app, host="0.0.0.0", port=8000)
if __name__ == "__main__":
main()