Skip to content

Commit d4c6cff

Browse files
Set agent name as env variable (#16)
* set agent name as env variable, defaults to agents-template-assistant * renames template azd-agents-starter instead of azd-aistudio-starter
1 parent 98bd258 commit d4c6cff

File tree

7 files changed

+42
-11
lines changed

7 files changed

+42
-11
lines changed

azure.yaml

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@
22
# TODO: do we need hooks?
33
# TODO: do we need all of the variables?
44

5-
name: azd-aistudio-starter
5+
name: azd-agents-starter
66
metadata:
7-
template: azd-aistudio[email protected]
7+
template: azd-agents[email protected]
88

99
services:
1010
api:
@@ -42,6 +42,7 @@ pipeline:
4242
- USE_CONTAINER_REGISTRY
4343
- USE_APPLICATION_INSIGHTS
4444
- USE_SEARCH_SERVICE
45+
- AZURE_AI_AGENT_NAME
4546
- AZURE_AI_AGENT_DEPLOYMENT_NAME
4647
- AZURE_AI_AGENT_DEPLOYMENT_SKU
4748
- AZURE_AI_AGENT_DEPLOYMENT_CAPACITY

infra/main.bicep

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,8 @@ param principalId string = ''
7373
@description('Format of the chat model to deploy')
7474
@allowed(['Microsoft', 'OpenAI'])
7575
param agentModelFormat string
76-
76+
@description('Name of agent to deploy')
77+
param agentName string
7778
@description('Name of the chat model to deploy')
7879
param agentModelName string
7980
@description('Name of the model deployment')
@@ -339,6 +340,7 @@ output AZURE_RESOURCE_GROUP string = rg.name
339340
output AZURE_TENANT_ID string = tenant().tenantId
340341
output AZURE_AIPROJECT_CONNECTION_STRING string = projectConnectionString
341342
output AZURE_AI_AGENT_DEPLOYMENT_NAME string = agentDeploymentName
343+
output AZURE_AI_AGENT_NAME string = agentName
342344

343345
// Outputs required by azd for ACA
344346
output AZURE_CONTAINER_ENVIRONMENT_NAME string = containerApps.outputs.environmentName

infra/main.parameters.json

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,9 @@
5050
"useSearchService": {
5151
"value": "${USE_SEARCH_SERVICE=true}"
5252
},
53+
"agentName": {
54+
"value": "${AZURE_AI_AGENT_NAME=agent-template-assistant}"
55+
},
5356
"agentDeploymentName": {
5457
"value": "${AZURE_AI_AGENT_MODEL_NAME=gpt-4o-mini}"
5558
},

scripts/write_env.ps1

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,11 @@ Set-Content -Path $envFilePath -Value ""
88
$azureAiProjectConnectionString = azd env get-value AZURE_AIPROJECT_CONNECTION_STRING
99
$azureAiagentDeploymentName = azd env get-value AZURE_AI_AGENT_DEPLOYMENT_NAME
1010
$azureAiAgentId = azd env get-value AZURE_AI_AGENT_ID
11+
$azureAiAgentName = azd env get-value AZURE_AI_AGENT_NAME
1112
$azureTenantId = azd env get-value AZURE_TENANT_ID
1213

1314
Add-Content -Path $envFilePath -Value "AZURE_AIPROJECT_CONNECTION_STRING=$azureAiProjectConnectionString"
1415
Add-Content -Path $envFilePath -Value "AZURE_AI_AGENT_DEPLOYMENT_NAME=$azureAiagentDeploymentName"
1516
Add-Content -Path $envFilePath -Value "AZURE_AI_AGENT_ID=$azureAiAgentId"
17+
Add-Content -Path $envFilePath -Value "AZURE_AI_AGENT_NAME=$azureAiAgentName"
1618
Add-Content -Path $envFilePath -Value "AZURE_TENANT_ID=$azureTenantId"

scripts/write_env.sh

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,4 +9,5 @@ ENV_FILE_PATH="src/.env"
99
echo "AZURE_AIPROJECT_CONNECTION_STRING=$(azd env get-value AZURE_AIPROJECT_CONNECTION_STRING)" >> $ENV_FILE_PATH
1010
echo "AZURE_AI_AGENT_DEPLOYMENT_NAME=$(azd env get-value AZURE_AI_AGENT_DEPLOYMENT_NAME)" >> $ENV_FILE_PATH
1111
echo "AZURE_AI_AGENT_ID=$(azd env get-value AZURE_AI_AGENT_ID)" >> $ENV_FILE_PATH
12+
echo "AZURE_AI_AGENT_NAME=$(azd env get-value AZURE_AI_AGENT_NAME)" >> $ENV_FILE_PATH
1213
echo "AZURE_TENANT_ID=$(azd env get-value AZURE_TENANT_ID)" >> $ENV_FILE_PATH

src/api/main.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ async def lifespan(app: fastapi.FastAPI):
101101
agent_list = await ai_client.agents.list_agents()
102102
if agent_list.data:
103103
for agent_object in agent_list.data:
104-
if agent_object.name == "agent-template-assistant":
104+
if agent_object.name == os.environ["AZURE_AI_AGENT_NAME"]:
105105
agent = agent_object
106106
if agent == None:
107107
raise Exception("Agent not found")

src/gunicorn.conf.py

Lines changed: 29 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
import multiprocessing
22
import os
3+
import sys
34
from typing import Dict
45
import asyncio
6+
import logging
57
from azure.ai.projects.aio import AIProjectClient
68
from azure.ai.projects.models import FilePurpose, FileSearchTool, AsyncToolSet
79
from azure.identity import DefaultAzureCredential
@@ -10,6 +12,26 @@
1012

1113
load_dotenv()
1214

15+
# Create a central logger for the application
16+
logger = logging.getLogger("azureaiapp")
17+
logger.setLevel(logging.INFO)
18+
19+
# Configure the stream handler (stdout)
20+
stream_handler = logging.StreamHandler(sys.stdout)
21+
stream_handler.setLevel(logging.INFO)
22+
stream_formatter = logging.Formatter("%(asctime)s [%(levelname)s] %(name)s: %(message)s")
23+
stream_handler.setFormatter(stream_formatter)
24+
logger.addHandler(stream_handler)
25+
26+
# Configure logging to file, if log file name is provided
27+
log_file_name = os.getenv("APP_LOG_FILE", "")
28+
if log_file_name != "":
29+
file_handler = logging.FileHandler(log_file_name)
30+
file_handler.setLevel(logging.INFO)
31+
file_formatter = logging.Formatter("%(asctime)s [%(levelname)s] %(name)s: %(message)s")
32+
file_handler.setFormatter(file_formatter)
33+
logger.addHandler(file_handler)
34+
1335
async def list_or_create_agent():
1436
files: Dict[str, Dict[str, str]] = {} # File name -> {"id": file_id, "path": file_path}
1537
vector_store = None
@@ -26,17 +48,17 @@ async def list_or_create_agent():
2648
agent = await ai_client.agents.get_agent(os.environ["AZURE_AI_AGENT_ID"])
2749
return
2850
except Exception as e:
29-
print(f"Error fetching agent: {e}")
51+
logger.info("Error with agent ID")
3052

3153
# Check if a previous agent created by the template exists
3254
agent_list = await ai_client.agents.list_agents()
3355
if agent_list.data:
3456
for agent_object in agent_list.data:
35-
if agent_object.name == "agent-template-assistant":
57+
if agent_object.name == os.environ["AZURE_AI_AGENT_NAME"]:
3658
return
3759

3860
# Create a new agent with the required resources
39-
print(f"Creating new agent with resources")
61+
logger.info("Creating new agent with resources")
4062
file_names = ["product_info_1.md", "product_info_2.md"]
4163
for file_name in file_names:
4264
file_path = os.path.abspath(os.path.join(os.path.dirname(__file__), 'files', file_name))
@@ -49,22 +71,22 @@ async def list_or_create_agent():
4971
file_ids=[info["id"] for info in files.values()],
5072
name="sample_store"
5173
)
52-
print(f"agent: file store and vector store success")
74+
logger.info("agent: file store and vector store success")
5375

5476
file_search_tool = FileSearchTool(vector_store_ids=[vector_store.id])
5577
toolset = AsyncToolSet()
5678
toolset.add(file_search_tool)
5779

5880
agent = await ai_client.agents.create_agent(
5981
model=os.environ["AZURE_AI_AGENT_DEPLOYMENT_NAME"],
60-
name="agent-template-assistant",
82+
name=os.environ["AZURE_AI_AGENT_NAME"],
6183
instructions="You are helpful assistant",
6284
toolset=toolset
6385
)
64-
print(f"Created agent, agent ID: {agent.id}")
86+
logger.info("Created agent, agent ID: {agent.id}")
6587

6688
except Exception as e:
67-
print(f"Error creating agent: {e}", exc_info=True)
89+
logger.info("Error creating agent: {e}", exc_info=True)
6890
raise RuntimeError(f"Failed to create the agent: {e}")
6991

7092
def on_starting(server):

0 commit comments

Comments
 (0)