Skip to content

Commit 027181d

Browse files
committed
update with new UX
1 parent dc4e590 commit 027181d

File tree

4 files changed

+57
-49
lines changed

4 files changed

+57
-49
lines changed

src/api/routes.py

+41-21
Original file line numberDiff line numberDiff line change
@@ -142,18 +142,31 @@ async def index(request: Request):
142142
return templates.TemplateResponse("index.html", {"request": request})
143143

144144

145-
async def get_agent_variant(feature_manager, ai_client: AIProjectClient, thread_id: str):
146-
if feature_manager:
147-
# Fetch the variant for the feature flag "my-agent" using thread_id as targeting Id
148-
agent_variant = await feature_manager.get_variant("my-agent", thread_id)
145+
async def get_agent_with_feature_flag(
146+
feature_manager: FeatureManager,
147+
ai_client: AIProjectClient,
148+
thread_id: str,
149+
default_agent: Agent = Depends(get_agent),
150+
) -> Optional[Agent]:
151+
if thread_id and feature_manager:
152+
# Fetch the variant for the feature flag "my-agent" using thread_id as targeting context
153+
try:
154+
agent_variant = await feature_manager.get_variant("my-agent", thread_id)
155+
except Exception as e:
156+
logger.error(f"Error fetching feature flag for thread_id={thread_id}: {e}")
157+
agent_variant = None
158+
159+
# Retrieve the agent variant if available
149160
if agent_variant and agent_variant.configuration:
150161
try:
151-
await ai_client.agents.get_agent(agent_variant.configuration)
162+
assigned_agent = await ai_client.agents.get_agent(agent_variant.configuration)
152163
logger.info(f"Using variant={agent_variant.name} with agent Id={agent_variant.configuration} for thread_id={thread_id}")
153-
return agent_variant
164+
return assigned_agent
154165
except Exception as e:
155-
logger.error(f"Error retrieving agent variant with Id={agent_variant.configuration} from AI project. {e}")
156-
return None
166+
logger.error(f"Error retrieving agent variant with Id={agent_variant.configuration} from AI project. Fallback to default agent: {e}")
167+
168+
# No agent variant found, fallback to default agent
169+
return default_agent
157170

158171
async def get_result(thread_id: str, agent_id: str, ai_client : AIProjectClient) -> AsyncGenerator[str, None]:
159172
logger.info(f"get_result invoked for thread_id={thread_id} and agent_id={agent_id}")
@@ -180,15 +193,25 @@ async def get_result(thread_id: str, agent_id: str, ai_client : AIProjectClient)
180193
@router.get("/chat/history")
181194
async def history(
182195
request: Request,
183-
ai_client : AIProjectClient = Depends(get_ai_client)
196+
default_agent: Agent = Depends(get_agent),
197+
ai_client : AIProjectClient = Depends(get_ai_client),
198+
feature_manager: FeatureManager = Depends(get_feature_manager),
199+
app_config: AzureAppConfigurationProvider = Depends(get_app_config),
184200
):
201+
# Refresh config if configured
202+
if app_config:
203+
await app_config.refresh()
204+
185205
# Retrieve the thread ID from the cookies (if available).
186206
thread_id = request.cookies.get('thread_id')
187207
agent_id = request.cookies.get('agent_id')
188208

189-
# Attempt to get an existing thread. If not found, create a new one.
209+
# Attempt to get agent from feature flag and fallback to default agent if not found.
210+
agent = await get_agent_with_feature_flag(feature_manager, ai_client, thread_id, default_agent)
211+
212+
# Attempt to get an existing thread. If not found or agent has changed, create a new one.
190213
try:
191-
if thread_id:
214+
if thread_id and agent_id == agent.id:
192215
logger.info(f"Retrieving thread with ID {thread_id}")
193216
thread = await ai_client.agents.get_thread(thread_id)
194217
else:
@@ -199,7 +222,6 @@ async def history(
199222
raise HTTPException(status_code=400, detail=f"Error handling thread: {e}")
200223

201224
thread_id = thread.id
202-
agent_id = agent.id
203225

204226
# Create a new message from the user's input.
205227
try:
@@ -229,21 +251,24 @@ async def history(
229251
async def chat(
230252
request: Request,
231253
ai_client : AIProjectClient = Depends(get_ai_client),
232-
agent: Agent = Depends(get_agent),
254+
default_agent: Agent = Depends(get_agent),
233255
feature_manager: FeatureManager = Depends(get_feature_manager),
234256
app_config: AzureAppConfigurationProvider = Depends(get_app_config),
235257
):
236258
# Refresh config if configured
237259
if app_config:
238-
app_config.refresh()
260+
await app_config.refresh()
239261

240262
# Retrieve the thread ID from the cookies (if available).
241263
thread_id = request.cookies.get('thread_id')
242264
agent_id = request.cookies.get('agent_id')
243265

266+
# Attempt to get agent from feature flag and fallback to default agent if not found.
267+
agent = await get_agent_with_feature_flag(feature_manager, ai_client, thread_id, default_agent)
268+
244269
# Attempt to get an existing thread. If not found, create a new one.
245270
try:
246-
if thread_id:
271+
if thread_id and agent_id == agent.id:
247272
logger.info(f"Retrieving thread with ID {thread_id}")
248273
thread = await ai_client.agents.get_thread(thread_id)
249274
else:
@@ -254,8 +279,7 @@ async def chat(
254279
raise HTTPException(status_code=400, detail=f"Error handling thread: {e}")
255280

256281
thread_id = thread.id
257-
agent_variant = await get_agent_variant(feature_manager, ai_client, thread_id)
258-
agent_id = agent_variant.configuration if agent_variant else agent.id
282+
agent_id = agent.id
259283

260284
# Parse the JSON from the request.
261285
try:
@@ -293,10 +317,6 @@ async def chat(
293317
response.set_cookie("thread_id", thread_id)
294318
response.set_cookie("agent_id", agent_id)
295319

296-
# Set the agent variant name in the response headers if available.
297-
if agent_variant:
298-
response.headers["agent-variant"] = str(agent_variant.name)
299-
300320
return response
301321

302322

src/api/static/ChatClient.js

+4-6
Original file line numberDiff line numberDiff line change
@@ -45,10 +45,8 @@ class ChatClient {
4545
throw new Error('ReadableStream not supported or response.body is null');
4646
}
4747

48-
const agentVariant = response.headers.get('agent-variant');
49-
5048
console.log("[ChatClient] Starting to handle streaming response...");
51-
this.handleMessages(response.body, agentVariant);
49+
this.handleMessages(response.body);
5250

5351
} catch (error) {
5452
document.getElementById("generating-message").style.display = "none";
@@ -63,7 +61,7 @@ class ChatClient {
6361
}
6462
}
6563

66-
handleMessages(stream, agentVariant) {
64+
handleMessages(stream) {
6765
let messageDiv = null;
6866
let accumulatedContent = '';
6967
let isStreaming = true;
@@ -112,7 +110,7 @@ class ChatClient {
112110

113111
if (data.error) {
114112
if (!messageDiv) {
115-
messageDiv = this.ui.createAssistantMessageDiv(agentVariant);
113+
messageDiv = this.ui.createAssistantMessageDiv();
116114
console.log("[ChatClient] Created new messageDiv for assistant.");
117115
}
118116
document.getElementById("generating-message").style.display = "none";
@@ -137,7 +135,7 @@ class ChatClient {
137135
} else {
138136
// If we have no messageDiv yet, create one
139137
if (!messageDiv) {
140-
messageDiv = this.ui.createAssistantMessageDiv(agentVariant);
138+
messageDiv = this.ui.createAssistantMessageDiv();
141139
console.log("[ChatClient] Created new messageDiv for assistant.");
142140
}
143141

src/api/static/ChatUI.js

+12-12
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ class ChatUI {
1111
}
1212
this.addCitationClickListener();
1313
this.attachCloseButtonListener();
14-
this.addNewThreadClickListener();
1514
}
1615

1716
preprocessContent(content, annotations) {
@@ -53,6 +52,12 @@ class ChatUI {
5352
this.deleteAllCookies();
5453
}
5554

55+
getCookie(name) {
56+
const value = `; ${document.cookie}`;
57+
const parts = value.split(`; ${name}=`);
58+
if (parts.length === 2) return parts.pop().split(';').shift();
59+
}
60+
5661
deleteAllCookies() {
5762
document.cookie.split(';').forEach(cookie => {
5863
const eqPos = cookie.indexOf('=');
@@ -155,7 +160,7 @@ class ChatUI {
155160
this.scrollToBottom();
156161
}
157162

158-
appendAssistantMessage(messageDiv, accumulatedContent, isStreaming, annotations) {
163+
appendAssistantMessage(messageDiv, accumulatedContent, isStreaming, annotations, agentId) {
159164
const md = window.markdownit({
160165
html: true,
161166
linkify: true,
@@ -174,6 +179,9 @@ class ChatUI {
174179

175180
// Set the innerHTML of the message text div to the HTML content
176181
messageDiv.innerHTML = htmlContent;
182+
var tooltip = "Agent Id: " + this.getCookie("agent_id") + "\n"
183+
tooltip += "Thread Id: " + this.getCookie("thread_id") + "\n"
184+
messageDiv.setAttribute("title", tooltip);
177185

178186
// Use requestAnimationFrame to ensure the DOM has updated before scrolling
179187
// Only scroll if not streaming
@@ -193,7 +201,7 @@ class ChatUI {
193201
}
194202
}
195203

196-
createAssistantMessageDiv(agentVariant) {
204+
createAssistantMessageDiv() {
197205
const assistantTemplateClone = this.assistantTemplate.content.cloneNode(true);
198206
if (!assistantTemplateClone) {
199207
console.error("Failed to clone assistant template.");
@@ -222,15 +230,7 @@ class ChatUI {
222230
if (!messageDiv) {
223231
console.error("Message content div not found in the template.");
224232
}
225-
226-
// Update message title if a variant is used
227-
if (agentVariant) {
228-
const messageTitleDiv = newlyAddedToast.querySelector(".message-title");
229-
if (messageTitleDiv) {
230-
messageTitleDiv.innerHTML += ` (Variant: ${agentVariant})`;
231-
}
232-
}
233-
233+
234234
return messageDiv;
235235
}
236236

src/api/templates/index.html

-10
Original file line numberDiff line numberDiff line change
@@ -62,12 +62,6 @@
6262
<i class="bi bi-body-text input-group-text dark-border" aria-hidden="true"></i>
6363
<input id="message" name="message" class="form-control form-control-sm dark-border" type="text" placeholder="Your Message" aria-label="Ask ChatGPT" />
6464
<button type="submit" class="btn btn-outline-dark" style="border-left-width: 0" aria-label="Submit">
65-
<button class="btn btn-secondary new-thread" id="new-thread-button" title="Start New Thread">
66-
<i class="bi bi-pencil-square" aria-hidden="true"></i>
67-
</button>
68-
<i class="bi bi-body-text input-group-text" aria-hidden="true"></i>
69-
<input id="message" name="message" class="form-control form-control-sm" type="text" placeholder="Your Message" aria-label="Ask ChatGPT"></input>
70-
<button type="submit" class="btn btn-outline-light">
7165
Send <i class="bi bi-send-fill" aria-hidden="true"></i>
7266
</button>
7367
</div>
@@ -97,10 +91,6 @@ <h5 class="mb-0">Document Viewer</h5>
9791
<template id="message-template-assistant">
9892
<div class="toast-container position-static w-100 d-flex flex-column align-items-stretch">
9993
<div class="toast fade show w-75 rounded-3 align-self-start">
100-
<div class="toast-header text-light background-assistant message-title">
101-
<i class="bi bi-robot me-1" aria-hidden="true"></i>
102-
<strong class="me-auto text-capitalize">Assistant</strong>
103-
</div>
10494
<div class="toast-body message-content">
10595
</div>
10696
</div>

0 commit comments

Comments
 (0)