Skip to content

Commit c00954e

Browse files
update for importing agent with agent_id (#6)
* update readme with create agent instructions for AI Foundry, SDK samples, and assistants tool * allow functionality to import agent and update main.py to use get_agent("AZURE_AI_AGENT_ID") * if there is an error getting the agent or the environment variable has not been set, it creates a new agent and deletes it when the app is done running
1 parent 63fbf12 commit c00954e

File tree

4 files changed

+87
-39
lines changed

4 files changed

+87
-39
lines changed

README.md

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,36 @@ You can find the connection string on the overview page of your Azure AI project
4343

4444
This solution has been configured to use "gpt-4o-mini" model. If you do not have a deployment named "gpt-4o-mini" in your existing AI project, you should either create one in Azure AI Foundry or follow the steps in [Customizing model deployments](#customizing-model-deployments) to specify a different model.
4545

46+
#### Creating and Importing an Agent
47+
48+
You can create an agent in your project to import to this template. For more information on creating an agent, view [Quickstart: Create a New Agent](https://learn.microsoft.com/azure/ai-services/agents/quickstart?pivots=ai-foundry). There are three agent creation options:
49+
50+
<details>
51+
<summary><b>Azure AI Foundry Agents Playground</b></summary>
52+
53+
In [Azure AI Foundry](https://ai.azure.com/), navigate to the Agents Playground for your project. Here, you can create an agent and customize its name, model deployment, instructions, and tools, as well as upload files for file search.
54+
</details>
55+
56+
<details>
57+
<summary><b>SDK Samples</b></summary>
58+
59+
You can create an agent using the Azure AI Projects SDK. By following the [instructions to create an agent using Python](https://learn.microsoft.com/azure/ai-services/agents/quickstart?pivots=programming-language-python-azure), you can create an agent using code based on the SDK samples.
60+
61+
</details>
62+
63+
<details>
64+
<summary><b>Assistants Tool</b></summary>
65+
66+
Using the [Azure AI Assistants Tool](https://github.com/Azure-Samples/azureai-assistant-tool), you can create an agent and customize it with tools and functions. Then, you can export the agent and use the agent_id.
67+
<!-- TODO: do we need to implement agents.yaml changes in order to use this solution? -->
68+
</details>
69+
70+
After creating your agent, import the agent into this template by copying the agent_id and setting the following environment variable:
71+
72+
```shell
73+
azd env set AZURE_AI_AGENT_ID "<agent_id>"
74+
```
75+
4676

4777
## Development
4878

scripts/write_env.ps1

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,10 @@ Set-Content -Path $envFilePath -Value ""
77
# Append new values to the .env file
88
$azureAiProjectConnectionString = azd env get-value AZURE_AIPROJECT_CONNECTION_STRING
99
$azureAiChatDeploymentName = azd env get-value AZURE_AI_CHAT_DEPLOYMENT_NAME
10+
$azureAiAgentId = azd env get-value AZURE_AI_AGENT_ID
1011
$azureTenantId = azd env get-value AZURE_TENANT_ID
1112

1213
Add-Content -Path $envFilePath -Value "AZURE_AIPROJECT_CONNECTION_STRING=$azureAiProjectConnectionString"
1314
Add-Content -Path $envFilePath -Value "AZURE_AI_CHAT_DEPLOYMENT_NAME=$azureAiChatDeploymentName"
15+
Add-Content -Path $envFilePath -Value "AZURE_AI_AGENT_ID=$azureAiAgentId"
1416
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
@@ -8,4 +8,5 @@ ENV_FILE_PATH="src/.env"
88

99
echo "AZURE_AIPROJECT_CONNECTION_STRING=$(azd env get-value AZURE_AIPROJECT_CONNECTION_STRING)" >> $ENV_FILE_PATH
1010
echo "AZURE_AI_CHAT_DEPLOYMENT_NAME=$(azd env get-value AZURE_AI_CHAT_DEPLOYMENT_NAME)" >> $ENV_FILE_PATH
11+
echo "AZURE_AI_AGENT_ID=$(azd env get-value AZURE_AI_AGENT_ID)" >> $ENV_FILE_PATH
1112
echo "AZURE_TENANT_ID=$(azd env get-value AZURE_TENANT_ID)" >> $ENV_FILE_PATH

src/api/main.py

Lines changed: 54 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ async def lifespan(app: fastapi.FastAPI):
5959
files: Dict[str, Dict[str, str]] = {} # File name -> {"id": file_id, "path": file_path}
6060
vector_store = None
6161
agent = None
62+
create_new_agent = True
6263

6364
try:
6465
if not os.getenv("RUNNING_IN_PRODUCTION"):
@@ -85,32 +86,45 @@ async def lifespan(app: fastapi.FastAPI):
8586
else:
8687
configure_azure_monitor(connection_string=application_insights_connection_string)
8788

88-
file_names = ["product_info_1.md", "product_info_2.md"] #TODO: can we get the file names from the folder so customers can upload?
89-
for file_name in file_names:
90-
file_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'files', file_name))
91-
file = await ai_client.agents.upload_file_and_poll(file_path=file_path, purpose=FilePurpose.AGENTS)
92-
logger.info(f"Uploaded file {file_path}, file ID: {file.id}")
93-
# Store both file id and the file path using the file name as key.
94-
files[file_name] = {"id": file.id, "path": file_path}
89+
if os.environ.get("AZURE_AI_AGENT_ID") is not None:
90+
try:
91+
agent = await ai_client.agents.get_agent(os.environ["AZURE_AI_AGENT_ID"])
92+
create_new_agent = False
93+
logger.info("Agent already exists, skipping creation")
94+
logger.info(f"Fetched agent, agent ID: {agent.id}")
95+
logger.info(f"Fetched agent, model name: {agent.model}")
96+
except Exception as e:
97+
logger.error(f"Error fetching agent: {e}", exc_info=True)
98+
create_new_agent = True
99+
if create_new_agent:
100+
logger.info("Creating agent")
101+
file_names = ["product_info_1.md", "product_info_2.md"]
102+
for file_name in file_names:
103+
file_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'files', file_name))
104+
file = await ai_client.agents.upload_file_and_poll(file_path=file_path, purpose=FilePurpose.AGENTS)
105+
logger.info(f"Uploaded file {file_path}, file ID: {file.id}")
106+
# Store both file id and the file path using the file name as key.
107+
files[file_name] = {"id": file.id, "path": file_path}
108+
109+
# Create the vector store using the file IDs.
110+
vector_store = await ai_client.agents.create_vector_store_and_poll(
111+
file_ids=[info["id"] for info in files.values()],
112+
name="sample_store"
113+
)
114+
115+
file_search_tool = FileSearchTool(vector_store_ids=[vector_store.id])
116+
toolset = AsyncToolSet()
117+
toolset.add(file_search_tool)
118+
119+
agent = await ai_client.agents.create_agent(
120+
model=os.environ["AZURE_AI_CHAT_DEPLOYMENT_NAME"],
121+
name="my-assistant",
122+
instructions="You are helpful assistant",
123+
toolset=toolset
124+
)
95125

96-
# Create the vector store using the file IDs.
97-
vector_store = await ai_client.agents.create_vector_store_and_poll(
98-
file_ids=[info["id"] for info in files.values()],
99-
name="sample_store"
100-
)
101-
102-
file_search_tool = FileSearchTool(vector_store_ids=[vector_store.id])
103-
toolset = AsyncToolSet()
104-
toolset.add(file_search_tool)
105-
106-
agent = await ai_client.agents.create_agent(
107-
model=os.environ["AZURE_AI_CHAT_DEPLOYMENT_NAME"],
108-
name="my-assistant",
109-
instructions="You are helpful assistant",
110-
toolset=toolset
111-
)
112-
logger.info(f"Created agent, agent ID: {agent.id}")
113-
logger.info(f"Created agent, model name: {agent.model}")
126+
logger.info(f"Created agent, agent ID: {agent.id}")
127+
logger.info(f"Created agent, model name: {agent.model}")
114128

115129
except Exception as e:
116130
logger.error(f"Error creating agent: {e}", exc_info=True)
@@ -124,20 +138,21 @@ async def lifespan(app: fastapi.FastAPI):
124138
yield
125139
finally:
126140
# Cleanup on shutdown.
127-
try:
128-
for info in files.values():
129-
await ai_client.agents.delete_file(info["id"])
130-
logger.info(f"Deleted file {info['id']}")
131-
132-
if vector_store:
133-
await ai_client.agents.delete_vector_store(vector_store.id)
134-
logger.info(f"Deleted vector store {vector_store.id}")
135-
136-
if agent:
137-
await ai_client.agents.delete_agent(agent.id)
138-
logger.info(f"Deleted agent {agent.id}")
139-
except Exception as e:
140-
logger.error(f"Error during cleanup: {e}", exc_info=True)
141+
if create_new_agent:
142+
try:
143+
for info in files.values():
144+
await ai_client.agents.delete_file(info["id"])
145+
logger.info(f"Deleted file {info['id']}")
146+
147+
if vector_store:
148+
await ai_client.agents.delete_vector_store(vector_store.id)
149+
logger.info(f"Deleted vector store {vector_store.id}")
150+
151+
if agent:
152+
await ai_client.agents.delete_agent(agent.id)
153+
logger.info(f"Deleted agent {agent.id}")
154+
except Exception as e:
155+
logger.error(f"Error during cleanup: {e}", exc_info=True)
141156

142157
try:
143158
await ai_client.close()

0 commit comments

Comments
 (0)