Skip to content

Commit 918eace

Browse files
ferantiverockitteldependabot[bot]
authored
patch (orchestrator): [fix] preserve thread context for a session + dependency update + minors (#47)
Co-authored-by: Chad Kittel <chad.kittel@gmail.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
1 parent 2d48f21 commit 918eace

File tree

6 files changed

+45
-25
lines changed

6 files changed

+45
-25
lines changed

README.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -134,16 +134,16 @@ The AI agent definition would likely be deployed from your application's pipelin
134134

135135
```bash
136136
# Use the agent definition on disk
137-
curl "https://github.com/Azure-Samples/openai-end-to-end-basic/raw/refs/heads/main/agents/chat-with-bing.json"
137+
wget "https://github.com/Azure-Samples/openai-end-to-end-basic/raw/refs/heads/main/agents/chat-with-bing.json"
138138

139139
# Update to match your environment
140-
cat agents/chat-with-bing.json | \
140+
cat chat-with-bing.json | \
141141
sed "s#MODEL_CONNECTION_NAME#${MODEL_CONNECTION_NAME}#g" | \
142142
sed "s#BING_CONNECTION_ID#${BING_CONNECTION_ID}#g" \
143-
> agents/chat-with-bing-output.json
143+
> chat-with-bing-output.json
144144

145145
# Deploy the agent
146-
az rest -u $AI_FOUNDRY_AGENT_CREATE_URL -m "post" --resource "https://ai.azure.com" -b @agents/chat-with-bing-output.json
146+
az rest -u $AI_FOUNDRY_AGENT_CREATE_URL -m "post" --resource "https://ai.azure.com" -b @chat-with-bing-output.json
147147
```
148148

149149
1. Get Agent Id value

website/chatui.zip

6.7 KB
Binary file not shown.

website/chatui/Controllers/ChatController.cs

Lines changed: 21 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
using Microsoft.Extensions.Options;
33
using Azure;
44
using Azure.AI.Agents.Persistent;
5-
using chatui.Models;
65
using chatui.Configuration;
76

87
namespace chatui.Controllers;
@@ -19,41 +18,48 @@ public class ChatController(
1918
private readonly IOptionsMonitor<ChatApiOptions> _options = options;
2019
private readonly ILogger<ChatController> _logger = logger;
2120

22-
[HttpPost]
23-
public async Task<IActionResult> Completions([FromBody] string prompt)
21+
// TODO: [security] Do not trust client to provide threadId. Instead map current user to their active threadid in your application's own state store.
22+
// Without this security control in place, a user can inject messages into another user's thread.
23+
[HttpPost("{threadId}")]
24+
public async Task<IActionResult> Completions([FromRoute] string threadId, [FromBody] string prompt)
2425
{
2526
if (string.IsNullOrWhiteSpace(prompt))
2627
throw new ArgumentException("Prompt cannot be null, empty, or whitespace.", nameof(prompt));
2728

2829
_logger.LogDebug("Prompt received {Prompt}", prompt);
2930
var _config = _options.CurrentValue;
3031

31-
// TODO: Reuse chat context.
32-
PersistentAgentThread thread = await _client.Threads.CreateThreadAsync();
33-
3432
PersistentThreadMessage message = await _client.Messages.CreateMessageAsync(
35-
thread.Id,
33+
threadId,
3634
MessageRole.User,
3735
prompt);
3836

39-
ThreadRun run = await _client.Runs.CreateRunAsync(thread.Id, _config.AIAgentId);
37+
ThreadRun run = await _client.Runs.CreateRunAsync(threadId, _config.AIAgentId);
4038

4139
while (run.Status == RunStatus.Queued || run.Status == RunStatus.InProgress || run.Status == RunStatus.RequiresAction)
4240
{
4341
await Task.Delay(TimeSpan.FromMilliseconds(500));
44-
run = (await _client.Runs.GetRunAsync(thread.Id, run.Id)).Value;
42+
run = (await _client.Runs.GetRunAsync(threadId, run.Id)).Value;
4543
}
4644

47-
Pageable<PersistentThreadMessage> messages = _client.Messages.GetMessages(
48-
threadId: thread.Id, order: ListSortOrder.Ascending);
45+
Pageable<PersistentThreadMessage> messages = _client.Messages.GetMessages(
46+
threadId: threadId, order: ListSortOrder.Ascending);
4947

50-
var fullText = string.Concat(
48+
var fullText =
5149
messages
5250
.Where(m => m.Role == MessageRole.Agent)
5351
.SelectMany(m => m.ContentItems.OfType<MessageTextContent>())
54-
.Select(c => c.Text)
55-
);
52+
.Last().Text;
53+
54+
return Ok(new { data = fullText });
55+
}
56+
57+
[HttpPost]
58+
public async Task<IActionResult> Threads()
59+
{
60+
// TODO [performance efficiency] Delay creating a thread until the first user message arrives.
61+
PersistentAgentThread thread = await _client.Threads.CreateThreadAsync();
5662

57-
return Ok(new HttpChatResponse(true, fullText));
63+
return Ok(new { id = thread.Id });
5864
}
5965
}

website/chatui/Models/ChatResponse.cs

Lines changed: 0 additions & 3 deletions
This file was deleted.

website/chatui/Views/Home/Index.cshtml

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -175,11 +175,14 @@
175175
const BOT_NAME = "Chatbot";
176176
const PERSON_NAME = "";
177177
178-
document.addEventListener("DOMContentLoaded", () => {
178+
document.addEventListener("DOMContentLoaded", async () => {
179179
const chatForm = document.querySelector(".msger-inputarea");
180180
const chatContainer = document.querySelector(".msger-chat");
181181
const messageInput = chatForm?.elements?.message;
182182
183+
const { id } = await createThread();
184+
const threadId = id;
185+
183186
addChatMessage(BOT_NAME, "left", "How can I help you today?");
184187
185188
chatForm.addEventListener("submit", async (event) => {
@@ -202,7 +205,7 @@
202205
});
203206
204207
async function sendPrompt(prompt) {
205-
const response = await fetch("/chat/completions", {
208+
const response = await fetch(`/chat/completions/${threadId}`, {
206209
method: "POST",
207210
headers: { "Content-Type": "application/json" },
208211
body: JSON.stringify(prompt)
@@ -216,6 +219,20 @@
216219
return response.json();
217220
}
218221
222+
async function createThread() {
223+
const response = await fetch("/chat/threads", {
224+
method: "POST",
225+
headers: { "Content-Type": "application/json" }
226+
});
227+
228+
if (!response.ok) {
229+
const errorMessage = await response.text().catch(() => response.statusText);
230+
throw new Error(`Error creating session: ${errorMessage}`);
231+
}
232+
233+
return response.json();
234+
}
235+
219236
function addChatMessage(name, side, text) {
220237
const timestamp = formatTime(new Date());
221238

website/chatui/chatui.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,6 @@
99
</ItemGroup>
1010
<ItemGroup>
1111
<PackageReference Include="Azure.AI.Agents.Persistent" Version="1.1.0-beta.1" />
12-
<PackageReference Include="Azure.Identity" Version="1.13.2" />
12+
<PackageReference Include="Azure.Identity" Version="1.14.0" />
1313
</ItemGroup>
1414
</Project>

0 commit comments

Comments
 (0)