Skip to content

Commit df6240d

Browse files
committed
Merge to upstream
2 parents 061cb39 + f4431fb commit df6240d

File tree

5 files changed

+71
-27
lines changed

5 files changed

+71
-27
lines changed

src/api/main.py

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import logging
66
import os
77
import sys
8+
import json
89
from typing import Dict
910

1011
from azure.ai.projects.aio import AIProjectClient
@@ -56,10 +57,7 @@
5657

5758
@contextlib.asynccontextmanager
5859
async def lifespan(app: fastapi.FastAPI):
59-
files: Dict[str, Dict[str, str]] = {} # File name -> {"id": file_id, "path": file_path}
60-
vector_store = None
6160
agent = None
62-
create_new_agent = True
6361

6462
try:
6563
if not os.getenv("RUNNING_IN_PRODUCTION"):
@@ -89,33 +87,35 @@ async def lifespan(app: fastapi.FastAPI):
8987
if os.environ.get("AZURE_AI_AGENT_ID") is not None:
9088
try:
9189
agent = await ai_client.agents.get_agent(os.environ["AZURE_AI_AGENT_ID"])
92-
create_new_agent = False
9390
logger.info("Agent already exists, skipping creation")
9491
logger.info(f"Fetched agent, agent ID: {agent.id}")
9592
logger.info(f"Fetched agent, model name: {agent.model}")
9693
except Exception as e:
9794
logger.error(f"Error fetching agent: {e}", exc_info=True)
98-
create_new_agent = True
99-
if create_new_agent:
100-
# Check if a previous agent created by the template exists
95+
96+
if not agent:
97+
# Fallback to searching by name
98+
agent_name = os.environ["AZURE_AI_AGENT_NAME"]
10199
agent_list = await ai_client.agents.list_agents()
102100
if agent_list.data:
103101
for agent_object in agent_list.data:
104-
if agent_object.name == os.environ["AZURE_AI_AGENT_NAME"]:
102+
if agent_object.name == agent_name:
105103
agent = agent_object
106-
if agent == None:
107-
raise Exception("Agent not found")
104+
logger.info(f"Found agent by name '{agent_name}', ID={agent_object.id}")
105+
break
108106

109-
except Exception as e:
110-
logger.error(f"Error creating agent: {e}", exc_info=True)
111-
raise RuntimeError(f"Failed to create the agent: {e}")
107+
if not agent:
108+
raise RuntimeError("No agent found. Ensure qunicorn.py created one or set AZURE_AI_AGENT_ID.")
112109

113-
app.state.ai_client = ai_client
114-
app.state.agent = agent
115-
app.state.files = files
110+
app.state.ai_client = ai_client
111+
app.state.agent = agent
116112

117-
try:
118113
yield
114+
115+
except Exception as e:
116+
logger.error(f"Error during startup: {e}", exc_info=True)
117+
raise RuntimeError(f"Error during startup: {e}")
118+
119119
finally:
120120
try:
121121
await ai_client.close()

src/api/routes.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -197,7 +197,15 @@ async def fetch_document(request: Request):
197197
if not file_name:
198198
raise HTTPException(status_code=400, detail="file_name is required")
199199

200-
files = getattr(request.app.state, "files", {})
200+
# Reconstruct the file dictionary from the env variable:
201+
files_env = os.environ['UPLOADED_FILE_MAP']
202+
try:
203+
files = json.loads(files_env)
204+
logger.info("Successfully parsed UPLOADED_FILE_MAP from environment variable.")
205+
except json.JSONDecodeError:
206+
files = {}
207+
logger.warning("Failed to parse UPLOADED_FILE_MAP from environment variable.", exc_info=True)
208+
201209
logger.info(f"File requested: {file_name}. Current file keys: {list(files.keys())}")
202210

203211
if file_name not in files:

src/api/static/main.js

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,18 @@ function initChat() {
99
const chatClient = new ChatClient(chatUI);
1010

1111
const form = document.getElementById("chat-form");
12-
1312
const messageInput = document.getElementById("message");
14-
13+
const targetContainer = document.getElementById("messages");
14+
const placeholderWrapper = document.getElementById("placeholder-wrapper");
1515

1616
form.addEventListener("submit", async function(e) {
1717
e.preventDefault();
18+
19+
// Remove placeholder message if it exists
20+
if (placeholderWrapper) {
21+
placeholderWrapper.remove();
22+
}
23+
1824
await chatClient.sendMessage("/chat", messageInput.value.trim());
1925
messageInput.value = "";
2026
});
@@ -24,4 +30,4 @@ function initChat() {
2430
};
2531
}
2632

27-
document.addEventListener("DOMContentLoaded", initChat);
33+
document.addEventListener("DOMContentLoaded", initChat);

src/api/templates/index.html

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,14 +12,44 @@
1212
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/cosmo/bootstrap.min.css"
1313
integrity="sha256-axRDISYf7Hht1KhcMnfDV2nq7hD/8Q9Rxa0YlW/o3NU=" crossorigin="anonymous">
1414
<link href="/static/styles.css" rel="stylesheet" type="text/css">
15+
<style>
16+
#messages {
17+
display: flex;
18+
flex-direction: column;
19+
align-items: center;
20+
text-align: center;
21+
}
22+
#placeholder-wrapper {
23+
display: flex;
24+
flex-grow: 1;
25+
justify-content: center;
26+
align-items: center;
27+
width: 100%;
28+
}
29+
#placeholder-message {
30+
color: #6c757d;
31+
}
32+
.header {
33+
font-size: 2em;
34+
font-weight: bold;
35+
margin-bottom: 10px;
36+
}
37+
.message-content {
38+
text-align: left;
39+
}
40+
</style>
1541
</head>
1642
<body>
1743
<div class="container-fluid h-100 d-flex flex-row">
1844
<div class="row flex-grow-1 h-100">
1945
<!-- Chat Section -->
2046
<div class="col-full d-flex flex-column h-100" id="chat-container"> <!-- Full width initially -->
2147
<div id="messages" class="px-4 pb-4 pt-2 flex-grow-1 overflow-y-auto align-items-stretch">
22-
<!-- Message content goes here -->
48+
<div id="placeholder-wrapper">
49+
<div id="placeholder-message" class="text-center text-muted my-3">
50+
<div class="header">Getting Started with Agents Using Azure AI Foundry</div>
51+
Type your message below. You can start casually with something fun like "Tell me a joke," or ask specifically about the Azure Search files, such as "What is Contoso Galaxy Innovations product?" </div>
52+
</div>
2353
</div>
2454

2555
<div id="chat-area" class="text-light px-4 py-2 rounded-top text-dark d-flex flex-column justify-content-center background-user">
@@ -76,4 +106,4 @@ <h5 class="mb-0">Document Viewer</h5>
76106
<script src="https://cdn.jsdelivr.net/npm/markdown-it/dist/markdown-it.min.js"></script>
77107
<script type="module" src="/static/main.js"></script>
78108
</body>
79-
</html>
109+
</html>

src/gunicorn.conf.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ async def create_index_maybe(
9494
vector_index_dimensions=int(
9595
os.getenv('AZURE_AI_EMBED_DIMENSIONS'))):
9696
embeddings_path = os.path.join(
97-
os.path.dirname(__file__), 'api', 'data', 'embeddings.csv')
97+
os.path.dirname(__file__), 'data', 'embeddings.csv')
9898

9999
assert embeddings_path, f'File {embeddings_path} not found.'
100100
await search_mgr.upload_documents(embeddings_path)
@@ -224,15 +224,15 @@ async def initialize_resources():
224224
"AZURE_AI_AGENT_NAME"]:
225225
logger.info(
226226
"Found existing agent named "
227-
f"'{agent_object.name}', "
228-
f"ID: {agent_object.id}")
227+
f"'{agent_object.name}'"
228+
f", ID: {agent_object.id}")
229229
os.environ["AZURE_AI_AGENT_ID"] = agent_object.id
230230
# Update the agent with the latest resources
231231
agent = await update_agent(agent_object, ai_client)
232232
return
233233

234234
# Create a new agent
235-
agent = await create_agent(ai_client, creds)
235+
agent = await create_agent(ai_client)
236236
os.environ["AZURE_AI_AGENT_ID"] = agent.id
237237
logger.info(f"Created agent, agent ID: {agent.id}")
238238

0 commit comments

Comments
 (0)