File size: 1,342 Bytes
e89a1ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import FastAPI

from fastapi.middleware.cors import CORSMiddleware

from chatbot import Chatbot

from chatbotmemory import ChatbotMemory

import logging

from langchain_core.messages import AIMessage, HumanMessage


app = FastAPI()

# Add logging 

logging.basicConfig(level=logging.INFO)

logger = logging.getLogger(__name__)

formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")

handler = logging.StreamHandler()

handler.setFormatter(formatter)

logger.addHandler(handler)

# Add CORS

origins = ["*"]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["GET", "POST", "PUT", "DELETE"],
    allow_headers=["*"],
)

bot1 = Chatbot()
bot2 = ChatbotMemory()

@app.get("/")

def read_root():

    return {

        "message": "API running successfully",

        "endpoints": [

            "/chat/v1/",

            "/chat/v2/",

        ]

    }

@app.post("/chat/v1/")
def chat(q: str):
    logger.info(q)
    answer = bot1.rag_chain.invoke(q)
    return {"answer": answer}

@app.post("/chat/v2/")
def chatMemory(q: str):
    chat_history = []
    logger.info(q)
    ai_msg = bot2.rag_chain.invoke({"question": q, "chat_history": chat_history})     
    chat_history.extend([HumanMessage(content=q), ai_msg])   
    return {"answer": ai_msg}