forked from yingslim/OxBIG_hackathon
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathchatbot.py
More file actions
90 lines (68 loc) · 2.45 KB
/
chatbot.py
File metadata and controls
90 lines (68 loc) · 2.45 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
# app.py
from fastapi import FastAPI
from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware
from session.session import *
from config.settings import DEFAULT_SYSTEM_PROMPT, CHROME_EXTENSION_ID, PLUGGING_ID
import logging
import yaml
import logging.config
import time
# Load the YAML logging configuration
with open("./log/config.yaml", "r") as f:
config = yaml.safe_load(f)
logging.config.dictConfig(config)
# Create the FastAPI application
app = FastAPI()
# Logger for this FastAPI app
logger = logging.getLogger("chatbot")
# Define Pydantic models
class ChatRequest(BaseModel):
message: str
class ChatResponse(BaseModel):
response: str
# Add CORS middleware to allow requests from your Chrome extension
origins = [
f"chrome-extension://{CHROME_EXTENSION_ID}" # Replace with your actual extension ID
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins, # Allow your extension to access the API
allow_credentials=True,
allow_methods=["*"], # Allow all methods
allow_headers=["*"], # Allow all headers
)
# Initialize system prompt and plugins
system_prompt = DEFAULT_SYSTEM_PROMPT
plugin_ids = PLUGGING_ID
# Create FastAPI instance
app = FastAPI()
# API endpoint to read root
@app.get("/")
async def read_root():
return {"message": "hello"}
# API endpoint to start a chat session
@app.get("/start_session")
async def start_session():
session_id = await create_chat_session()
if not session_id:
logger.error("start_session: Failed to create a session.")
return {"error": "Failed to create a session."}
return {"session_id": session_id}
# API endpoint to send chat messages to OnDemand
@app.post("/chat", response_model=ChatResponse)
async def chat_with_bot(chat_request: ChatRequest):
user_message = chat_request.message
if not user_message.strip():
logger.error("chat: Invalid message.")
return {"response": "Please enter a valid message."}
# Combine system prompt with user message
full_query = f"{system_prompt}\n{user_message}"
session_id = await create_chat_session()
if not session_id:
logger.error("chat: Unable to create a session.")
return {"response": "Failed to create a session."}
# Submit query and get chatbot response
response = await submit_query(session_id, full_query, plugin_ids)
logger.info(f"chat: User message: {user_message}, Chatbot response: {response}")
return {"response": response}