Skip to content

Commit 74cfde9

Browse files
committed
Merge remote-tracking branch 'origin/main' into 112-selectai-integration
2 parents 98d9624 + 2ddb48c commit 74cfde9

File tree

4 files changed

+62
-23
lines changed

4 files changed

+62
-23
lines changed

src/client/utils/st_common.py

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
import os
88
from io import BytesIO
99
from typing import Union, get_args
10-
from uuid import uuid4
1110
import pandas as pd
1211

1312
import streamlit as st
@@ -28,12 +27,6 @@
2827
#############################################################################
2928
# Common Helpers
3029
#############################################################################
31-
def client_gen_id() -> ClientIdType:
32-
"""Generate a new client ID; can be used to clear history"""
33-
logger.info("Creating new client identifier")
34-
return str(uuid4())
35-
36-
3730
def local_file_payload(uploaded_files: Union[BytesIO, list[BytesIO]]) -> list:
3831
"""Upload Single file from Streamlit to the Server"""
3932
# If it's a single file, convert it to a list for consistent processing
@@ -124,8 +117,11 @@ def history_sidebar() -> None:
124117
on_change=update_user_settings("ll_model"),
125118
)
126119
if button_col.button("Clear", disabled=not chat_history_enable, use_container_width=True):
127-
# Establish a new thread
128-
state.user_settings["client"] = client_gen_id()
120+
# Clean out history
121+
try:
122+
api_call.patch(endpoint="v1/chat/history")
123+
except api_call.ApiError as ex:
124+
logger.error("Clearing Chat History for %s failed: %s", state.user_settings["client"], ex)
129125
clear_state_key("user_client")
130126

131127

src/launch_client.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,13 @@
88
# spell-checker:ignore streamlit, scriptrunner
99

1010
import os
11+
from uuid import uuid4
1112

1213
import streamlit as st
1314
from streamlit import session_state as state
1415

1516
from client.utils import api_call
16-
from client.utils.st_common import set_server_state, client_gen_id
17+
from client.utils.st_common import set_server_state
1718

1819
import common.logging_config as logging_config
1920

@@ -62,7 +63,7 @@ def main() -> None:
6263
if "user_settings" not in state:
6364
try:
6465
state.user_settings = api_call.post(
65-
endpoint="v1/settings", params={"client": client_gen_id()}, retries=10, backoff_factor=1.5
66+
endpoint="v1/settings", params={"client": str(uuid4())}, retries=10, backoff_factor=1.5
6667
)
6768
except api_call.ApiError:
6869
logger.error("Unable to contact API Server; setting as Down!")

src/server/endpoints.py

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,14 @@
1818
from pydantic import HttpUrl
1919

2020
from langgraph.graph.state import CompiledStateGraph
21-
from langchain_core.messages import HumanMessage, AnyMessage, convert_to_openai_messages, ChatMessage
21+
from langgraph.graph.message import REMOVE_ALL_MESSAGES
22+
from langchain_core.messages import (
23+
HumanMessage,
24+
AnyMessage,
25+
convert_to_openai_messages,
26+
ChatMessage,
27+
RemoveMessage,
28+
)
2229
from langchain_core.runnables import RunnableConfig
2330
from giskard.rag import evaluate, QATestset
2431
from giskard.rag.metrics import correctness_metric
@@ -751,12 +758,32 @@ async def chat_stream(request: schema.ChatRequest, client: schema.ClientIdType =
751758
media_type="application/octet-stream",
752759
)
753760

761+
@auth.patch(
762+
"/v1/chat/history",
763+
description="Delete Chat History",
764+
response_model=list[schema.ChatMessage],
765+
)
766+
async def chat_history_clean(client: schema.ClientIdType = Header(...)) -> list[ChatMessage]:
767+
agent: CompiledStateGraph = chatbot.chatbot_graph
768+
try:
769+
_ = agent.update_state(
770+
config=RunnableConfig(
771+
configurable={
772+
"thread_id": client,
773+
}
774+
),
775+
values={"messages": RemoveMessage(id=REMOVE_ALL_MESSAGES)},
776+
)
777+
return [ChatMessage(content="As requested, I've forgotten our conversation.", role="system")]
778+
except KeyError:
779+
return [ChatMessage(content="I'm sorry, I have no history of this conversation.", role="system")]
780+
754781
@auth.get(
755782
"/v1/chat/history",
756783
description="Get Chat History",
757784
response_model=list[schema.ChatMessage],
758785
)
759-
async def chat_history(client: schema.ClientIdType = Header(...)) -> list[ChatMessage]:
786+
async def chat_history_return(client: schema.ClientIdType = Header(...)) -> list[ChatMessage]:
760787
"""Return Chat History"""
761788
agent: CompiledStateGraph = chatbot.chatbot_graph
762789
try:
@@ -771,7 +798,7 @@ async def chat_history(client: schema.ClientIdType = Header(...)) -> list[ChatMe
771798
chat_messages = convert_to_openai_messages(messages)
772799
return chat_messages
773800
except KeyError:
774-
return [ChatMessage(content="I'm sorry, I have no history of this conversation", role="system")]
801+
return [ChatMessage(content="I'm sorry, I have no history of this conversation.", role="system")]
775802

776803
#################################################
777804
# testbed Endpoints

tests/server/test_endpoints_chat.py

Lines changed: 24 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,8 @@ class TestInvalidAuthEndpoints:
2929
[
3030
pytest.param("/v1/chat/completions", "post", id="chat_post"),
3131
pytest.param("/v1/chat/streams", "post", id="chat_stream"),
32-
pytest.param("/v1/chat/history", "get", id="chat_history"),
32+
pytest.param("/v1/chat/history", "patch", id="chat_history_clean"),
33+
pytest.param("/v1/chat/history", "get", id="chat_history_return"),
3334
],
3435
)
3536
def test_endpoints(self, client, auth_headers, endpoint, api_method, auth_type, status_code):
@@ -125,14 +126,6 @@ def test_chat_stream_valid_mock(self, client, auth_headers):
125126
content = b"".join(response.iter_bytes())
126127
assert b"Test streaming response" in content
127128

128-
def test_chat_history_empty(self, client, auth_headers):
129-
"""Test no model chat completion request"""
130-
response = client.get("/v1/chat/history", headers=auth_headers["valid_auth"])
131-
assert response.status_code == 200
132-
history = response.json()
133-
assert history[0]["role"] == "system"
134-
assert history[0]["content"] == "I'm sorry, I have no history of this conversation"
135-
136129
def test_chat_history_valid_mock(self, client, auth_headers):
137130
"""Test valid chat history request"""
138131
# Create the mock history response
@@ -152,3 +145,25 @@ def test_chat_history_valid_mock(self, client, auth_headers):
152145
assert len(history) == 2
153146
assert history[0]["role"] == "user"
154147
assert history[0]["content"] == "Hello"
148+
149+
def test_chat_history_clean(self, client, auth_headers):
150+
"""Test chat history with no history"""
151+
with patch("server.agents.chatbot.chatbot_graph") as mock_graph:
152+
mock_graph.get_state.side_effect = KeyError()
153+
response = client.patch("/v1/chat/history", headers=auth_headers["valid_auth"])
154+
assert response.status_code == 200
155+
history = response.json()
156+
assert len(history) == 1
157+
assert history[0]["role"] == "system"
158+
assert "forgotten" in history[0]["content"].lower()
159+
160+
def test_chat_history_empty(self, client, auth_headers):
161+
"""Test chat history with no history"""
162+
with patch("server.agents.chatbot.chatbot_graph") as mock_graph:
163+
mock_graph.get_state.side_effect = KeyError()
164+
response = client.get("/v1/chat/history", headers=auth_headers["valid_auth"])
165+
assert response.status_code == 200
166+
history = response.json()
167+
assert len(history) == 1
168+
assert history[0]["role"] == "system"
169+
assert "no history" in history[0]["content"].lower()

0 commit comments

Comments
 (0)