Skip to content

Commit

Permalink
feat: Create reset button to clear session cookies (#152)
Browse files Browse the repository at this point in the history
  • Loading branch information
duwenxin99 authored Jan 6, 2024
1 parent 700e191 commit f008c04
Show file tree
Hide file tree
Showing 5 changed files with 77 additions and 19 deletions.
21 changes: 18 additions & 3 deletions langchain_tools_demo/int.tests.cloudbuild.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,25 @@ steps:
export ID_TOKEN=$(gcloud auth print-identity-token --audiences $$URL)
# Test `/` route
curl -si --fail --show-error -H "Authorization: Bearer $$ID_TOKEN" $$URL
curl -c cookies.txt -si --fail --show-error -H "Authorization: Bearer $$ID_TOKEN" $$URL
# Test `/chat`` route
curl -si --fail --show-error \
# Test `/chat` route should fail
msg=$(curl -si --show-error \
-X POST \
-H "Authorization: Bearer $$ID_TOKEN" \
-H 'Content-Type: application/json' \
-d '{"prompt":"How can you help me?"}' \
$$URL/chat)
if grep -q "400" <<< "$msg"; then
echo "Chat Handler Test: PASSED"
else
echo "Chat Handler Test: FAILED"
echo $msg && exit 1
fi
# Test `/chat` route
curl -b cookies.txt -si --fail --show-error \
-X POST \
-H "Authorization: Bearer $$ID_TOKEN" \
-H 'Content-Type: application/json' \
Expand Down
37 changes: 26 additions & 11 deletions langchain_tools_demo/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
from fastapi.responses import HTMLResponse, PlainTextResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from langchain.agents.agent import AgentExecutor
from markdown import markdown
from starlette.middleware.sessions import SessionMiddleware

Expand Down Expand Up @@ -52,12 +51,17 @@ async def lifespan(app: FastAPI):


@app.get("/", response_class=HTMLResponse)
def index(request: Request):
async def index(request: Request):
"""Render the default template."""
request.session.clear() # Clear chat history, if needed
if "uuid" not in request.session:
request.session["uuid"] = str(uuid.uuid4())
request.session["messages"] = BASE_HISTORY
# Agent setup
if request.session["uuid"] in user_agents:
user_agent = user_agents[request.session["uuid"]]
else:
user_agent = await init_agent()
user_agents[request.session["uuid"]] = user_agent
return templates.TemplateResponse(
"index.html", {"request": request, "messages": request.session["messages"]}
)
Expand All @@ -71,17 +75,14 @@ async def chat_handler(request: Request, prompt: str = Body(embed=True)):
raise HTTPException(status_code=400, detail="Error: No user query")

if "uuid" not in request.session:
request.session["uuid"] = str(uuid.uuid4())
request.session["messages"] = BASE_HISTORY
raise HTTPException(
status_code=400, detail="Error: Invoke index handler before start chatting"
)

# Add user message to chat history
request.session["messages"] += [{"role": "user", "content": prompt}]
# Agent setup
if request.session["uuid"] in user_agents:
user_agent = user_agents[request.session["uuid"]]
else:
user_agent = await init_agent()
user_agents[request.session["uuid"]] = user_agent

user_agent = user_agents[request.session["uuid"]]
try:
# Send prompt to LLM
response = await user_agent.agent.ainvoke({"input": prompt})
Expand All @@ -95,6 +96,20 @@ async def chat_handler(request: Request, prompt: str = Body(embed=True)):
raise HTTPException(status_code=500, detail=f"Error invoking agent: {err}")


@app.post("/reset")
async def reset(request: Request):
"""Reset agent"""
global user_agents
uuid = request.session["uuid"]

if uuid not in user_agents.keys():
raise HTTPException(status_code=500, detail=f"Current agent not found")

await user_agents[uuid].client.close()
del user_agents[uuid]
request.session.clear()


if __name__ == "__main__":
PORT = int(os.getenv("PORT", default=8081))
uvicorn.run(app, host="0.0.0.0", port=PORT)
22 changes: 17 additions & 5 deletions langchain_tools_demo/static/index.css
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,18 @@ body {

.chat-header {
position: relative;
min-width: 650px;
font-size: 16px;
font-weight: 500;
text-align: center;
}

.chat-header span.reset-button {
position: absolute;
margin-right: 0px;
font-size: 38px;
}

.chat-wrapper {
display: flex;
flex-direction: column;
Expand Down Expand Up @@ -77,11 +84,16 @@ div.chat-content>span {
border: none;
}

.chat-input-container span.btn-group {
position: relative;
margin: auto;
margin-right: 10px;
display: flex;
#resetButton {
font-size: 35px;
cursor: pointer;
position: absolute;
top: 47px;
right: 40px;
}

#resetButton:hover {
background-color: #c9d4e9;
}

.chat-bubble {
Expand Down
13 changes: 13 additions & 0 deletions langchain_tools_demo/static/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,11 @@ $(document).on("keypress",async (e) => {
}
});

// Reset current user via click
$('#resetButton').click(async (e) => {
await reset();
});

async function submitMessage() {
let msg = $('.chat-bar input').val();
// Add message to UI
Expand Down Expand Up @@ -62,6 +67,14 @@ async function askQuestion(prompt) {
}
}

async function reset() {
await fetch('/reset', {
method: 'POST',
}).then(()=>{
window.location.reload()
})
}

// Helper function to print to chatroom
function log(name, msg) {
let message = `<span class="chat-bubble ${name}">${msg}</span>`;
Expand Down
3 changes: 3 additions & 0 deletions langchain_tools_demo/templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,13 @@
</head>

<body>

<div class="container">
<div class="chat-header">
<h1>SFO Airport Assistant</h1>
<span class="material-symbols-outlined" id="resetButton">refresh</span>
</div>

<div class="chat-wrapper">
<div class="chat-content">
{# Add Chat history #}
Expand Down

0 comments on commit f008c04

Please sign in to comment.