Skip to content

Commit 8e678b9

Browse files
committed
update agent sample
1 parent 3d8831f commit 8e678b9

File tree

3 files changed

+107
-37
lines changed

3 files changed

+107
-37
lines changed

agentic-retrieval-pipeline-example/agent-example.ipynb

Lines changed: 103 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -116,15 +116,16 @@
116116
},
117117
{
118118
"cell_type": "code",
119-
"execution_count": null,
119+
"execution_count": 1,
120120
"id": "e42b4a10",
121121
"metadata": {},
122122
"outputs": [],
123123
"source": [
124-
"from dotenv import load_dotenv\n",
124+
"import os\n",
125+
"\n",
125126
"from azure.identity import DefaultAzureCredential\n",
126127
"from azure.mgmt.core.tools import parse_resource_id\n",
127-
"import os\n",
128+
"from dotenv import load_dotenv\n",
128129
"\n",
129130
"load_dotenv(override=True) # take environment variables from .env.\n",
130131
"\n",
@@ -164,7 +165,7 @@
164165
},
165166
{
166167
"cell_type": "code",
167-
"execution_count": null,
168+
"execution_count": 2,
168169
"id": "91fd6810",
169170
"metadata": {},
170171
"outputs": [
@@ -177,8 +178,13 @@
177178
}
178179
],
179180
"source": [
180-
"from azure.search.documents.indexes.models import SearchIndex, SearchField, VectorSearch, VectorSearchProfile, HnswAlgorithmConfiguration, AzureOpenAIVectorizer, AzureOpenAIVectorizerParameters, SemanticSearch, SemanticConfiguration, SemanticPrioritizedFields, SemanticField\n",
181181
"from azure.search.documents.indexes import SearchIndexClient\n",
182+
"from azure.search.documents.indexes.models import (\n",
183+
" AzureOpenAIVectorizer, AzureOpenAIVectorizerParameters,\n",
184+
" HnswAlgorithmConfiguration, SearchField, SearchIndex,\n",
185+
" SemanticConfiguration, SemanticField, SemanticPrioritizedFields,\n",
186+
" SemanticSearch, VectorSearch, VectorSearchProfile\n",
187+
")\n",
182188
"\n",
183189
"index = SearchIndex(\n",
184190
" name=index_name,\n",
@@ -234,7 +240,7 @@
234240
},
235241
{
236242
"cell_type": "code",
237-
"execution_count": null,
243+
"execution_count": 3,
238244
"id": "f98f31e7",
239245
"metadata": {},
240246
"outputs": [
@@ -284,8 +290,11 @@
284290
}
285291
],
286292
"source": [
287-
"from azure.search.documents.indexes.models import SearchIndexKnowledgeSource, SearchIndexKnowledgeSourceParameters, SearchIndexFieldReference\n",
288293
"from azure.search.documents.indexes import SearchIndexClient\n",
294+
"from azure.search.documents.indexes.models import (\n",
295+
" SearchIndexFieldReference, SearchIndexKnowledgeSource,\n",
296+
" SearchIndexKnowledgeSourceParameters\n",
297+
")\n",
289298
"\n",
290299
"ks = SearchIndexKnowledgeSource(\n",
291300
" name=knowledge_source_name,\n",
@@ -310,7 +319,7 @@
310319
"\n",
311320
"This step creates a knowledge base, which acts as a wrapper for your knowledge source and LLM deployment.\n",
312321
"\n",
313-
"`EXTRACTIVE_DATA` is the default modality and returns content from your knowledge sources without generative alteration. This is recommended for interaction with Foundry Agent Service"
322+
"`EXTRACTIVE_DATA` is the default modality and returns content from your knowledge sources without answer generation. This is recommended for interaction with Foundry Agent Service."
314323
]
315324
},
316325
{
@@ -328,8 +337,11 @@
328337
}
329338
],
330339
"source": [
331-
"from azure.search.documents.indexes.models import KnowledgeBase, KnowledgeSourceReference, AzureOpenAIVectorizerParameters, KnowledgeRetrievalOutputMode, KnowledgeRetrievalMinimalReasoningEffort\n",
332340
"from azure.search.documents.indexes import SearchIndexClient\n",
341+
"from azure.search.documents.indexes.models import (\n",
342+
" KnowledgeBase, KnowledgeRetrievalMinimalReasoningEffort,\n",
343+
" KnowledgeRetrievalOutputMode, KnowledgeSourceReference\n",
344+
")\n",
333345
"\n",
334346
"knowledge_base = KnowledgeBase(\n",
335347
" name=base_name,\n",
@@ -357,7 +369,9 @@
357369
"source": [
358370
"## Create an agent\n",
359371
"\n",
360-
"In Foundry Agent Service, an agent is a smart micro-service that can do RAG. The purpose of this agent is to decide when to send a query to the agentic retrieval pipeline."
372+
"In Foundry Agent Service, an agent is an smart micro-service that can use an LLM with tools. The purpose of this agent is to use retrieval tools from the knowledge base to do RAG.\n",
373+
"\n",
374+
"Your Foundry project may have no agents at this stage, but if you've already run this notebook, you will see the agent listed here."
361375
]
362376
},
363377
{
@@ -399,8 +413,6 @@
399413
}
400414
],
401415
"source": [
402-
"from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient\n",
403-
"from azure.mgmt.cognitiveservices.models import ConnectionPropertiesV2BasicResource, CustomKeysConnectionProperties, CustomKeys\n",
404416
"import requests\n",
405417
"from azure.identity import get_bearer_token_provider\n",
406418
"\n",
@@ -429,9 +441,27 @@
429441
"print(f\"Connection '{project_connection_name}' created or updated successfully.\")"
430442
]
431443
},
444+
{
445+
"cell_type": "markdown",
446+
"id": "6631324e",
447+
"metadata": {},
448+
"source": [
449+
"## Optimize agent instructions for knowledge retrieval\n",
450+
"\n",
451+
"To maximize the accuracy of knowledge base invocations and ensure proper citation formatting, use optimized agent instructions. Based on our experiments, we recommend the following instruction template as a starting point:\n",
452+
"\n",
453+
"```\n",
454+
"You are a helpful assistant that must use the knowledge base to answer all the questions from user. You must never answer from your own knowledge under any circumstances.\n",
455+
"Every answer must always provide annotations for using the MCP knowledge base tool and render them as: `【message_idx:search_idx†source_name】`\n",
456+
"If you cannot find the answer in the provided knowledge base you must respond with \"I don't know\".\n",
457+
"```\n",
458+
"\n",
459+
"The specified citation format ensures the agent includes provenance information in responses, making it clear which knowledge sources were used."
460+
]
461+
},
432462
{
433463
"cell_type": "code",
434-
"execution_count": 8,
464+
"execution_count": null,
435465
"id": "aa363122",
436466
"metadata": {},
437467
"outputs": [
@@ -447,9 +477,9 @@
447477
"from azure.ai.projects.models import PromptAgentDefinition, MCPTool\n",
448478
"\n",
449479
"instructions = \"\"\"\n",
450-
"A Q&A agent that can answer questions about the Earth at night.\n",
451-
"Always provide references to the ID of the data source used to answer the question.\n",
452-
"If you do not have the answer, respond with \"I don't know\".\n",
480+
"You are a helpful assistant that must use the knowledge base to answer all the questions from user. You must never answer from your own knowledge under any circumstances.\n",
481+
"Every answer must always provide annotations for using the MCP knowledge base tool and render them as: `【message_idx:search_idx†source_name】`\n",
482+
"If you cannot find the answer in the provided knowledge base you must respond with \"I don't know\".\n",
453483
"\"\"\"\n",
454484
"mcp_kb_tool = MCPTool(\n",
455485
" server_label=\"knowledge-base\",\n",
@@ -476,7 +506,9 @@
476506
"id": "16a2d5ed",
477507
"metadata": {},
478508
"source": [
479-
"## Start a chat with the agent"
509+
"## Start a chat with the agent\n",
510+
"\n",
511+
"Set the `tool_choice` parameter to \"required\" to ensure the knowledge base tool is consistently used"
480512
]
481513
},
482514
{
@@ -489,21 +521,36 @@
489521
"name": "stdout",
490522
"output_type": "stream",
491523
"text": [
492-
"Response: The larger December brightening observed in suburban belts compared to urban cores, despite higher absolute light levels downtown, is primarily because suburban areas have more yard space and a prevalence of single-family homes where holiday light displays are more common and prominent. Urban cores do experience brightening during the holidays, but suburban areas show greater increases in lighting intensity due to more extensive holiday light decorations in residential yards and neighborhoods [source 4:4, page 176].\n",
524+
"Response: Here are evidence-based explanations to your questions:\n",
525+
"\n",
526+
"---\n",
527+
"\n",
528+
"**1. Why do suburban belts display larger December brightening than urban cores, even though absolute light levels are higher downtown?**\n",
529+
"\n",
530+
"- Suburban belts show a *larger percentage increase* in night brightness during December compared to urban cores, largely because suburban residential areas feature more single-family homes and larger yards, which are typically decorated with holiday lights. These areas start from a lower baseline (less bright overall at night compared to dense urban centers), so the relative change (brightening) is much more noticeable.\n",
531+
"\n",
532+
"- In contrast, the downtown core is already very bright at night due to dense commercial lighting and streetlights. While it also sees a December increase (often 20–30% brighter), the *absolute* change is less striking because it begins at a much higher base of illumination.\n",
493533
"\n",
494-
"Regarding the sharp visibility of Phoenix's nighttime street grid from space, the Phoenix metropolitan area is laid out along a regular grid of city blocks and streets, which is clearly visible at night due to street lighting. The sharp street grid pattern is emphasized by the extensive street lighting that traces the grid, and the presence of brightly lit transportation corridors (like Grand Avenue) and nodes such as shopping centers and gas stations at street intersections. Additionally, Phoenix's urban spread includes many suburban municipalities linked by well-illuminated surface streets and freeways, enhancing the visibility of the grid pattern from space [source 4:0 and 4:1, pages 104-105].\n",
534+
"- This pattern is observed across U.S. cities, with the phenomenon driven by widespread cultural practices and the suburban landscape’s suitability for holiday lighting displays. The effect is visible in satellite data and was quantified at 20–50% brighter in December, especially in suburbs and city outskirts.\n",
495535
"\n",
496-
"In contrast, large stretches of interstate highways between Midwestern cities are comparatively dim at night because these transportation corridors often do not have extensive street-level lighting along the highways themselves, as lighting is typically limited to city areas and major intersections. While the interstates are well-traveled, fewer lights are installed directly on these long stretches of highway, making them less visible from space in nighttime imagery [source 4:3, page 124].\n",
536+
"---\n",
497537
"\n",
498-
"Summary:\n",
499-
"- Suburban December brightening larger due to more holiday yard lighting in single-family homes and yards.\n",
500-
"- Phoenix’s nighttime grid visibility is due to its regular urban street grid with comprehensive street lighting and connected suburban municipalities with illuminated streets.\n",
501-
"- Midwest interstate highways are dimmer because highways themselves are less illuminated between cities.\n",
538+
"**2. Why is the Phoenix nighttime street grid so sharply visible from space, whereas large stretches of the interstate between midwestern cities remain comparatively dim?**\n",
502539
"\n",
503-
"References: \n",
504-
"- Source 4:4 (page 176) for December brightening in suburban vs urban areas. \n",
505-
"- Sources 4:0 and 4:1 (pages 104-105) for Phoenix nighttime grid visibility. \n",
506-
"- Source 4:3 (page 124) for dimmer interstate stretches between Midwestern cities.\n"
540+
"- Phoenix’s sharply visible nighttime street grid from space is a result of its urban layout: the city (like many western U.S. cities) was developed using a regular grid system, with extensive and uniform street lighting and strong urban sprawl. The grid pattern, and the dense network of intersecting surface streets, is brightly illuminated, particularly at intersections, commercial areas, and major thoroughfares.\n",
541+
"\n",
542+
"- The interstate highways between midwestern cities, though significant in length and crucial to national infrastructure, traverse sparsely populated rural areas. These stretches typically have very little artificial lighting (due to low traffic volumes at night and cost considerations), making them much less visible in nighttime satellite imagery. Only nodes (cities and towns) along the route show as bright \"pearls\" in the darkness, while the \"strings\" (highways) connecting them remain faint or invisible.\n",
543+
"\n",
544+
"- In summary:\n",
545+
" - Urban areas like Phoenix stand out with strong, connected patterns of light due to dense development and extensive lighting.\n",
546+
" - Rural interstates are sparsely lit, and only their endpoints—cities and large towns—generate notable light visible from space.\n",
547+
"\n",
548+
"---\n",
549+
"\n",
550+
"**References**:\n",
551+
"- [Holiday Lights increase most dramatically in suburbs, not downtowns: earth_at_night_508_page_176_verbalized, page 160](4:5)\n",
552+
"- [Lighting paths and urban grids are visible from space, while rural highways remain dim: earth_at_night_508_page_124_verbalized, page 108](4:3)\n",
553+
"- [Phoenix’s grid and surrounding urban structure: earth_at_night_508_page_104_verbalized, page 88](4:1)\n"
507554
]
508555
}
509556
],
@@ -516,6 +563,7 @@
516563
"# Send initial request that will trigger the MCP tool\n",
517564
"response = openai_client.responses.create(\n",
518565
" conversation=conversation.id,\n",
566+
" tool_choice=\"required\",\n",
519567
" input=\"\"\"\n",
520568
" Why do suburban belts display larger December brightening than urban cores even though absolute light levels are higher downtown?\n",
521569
" Why is the Phoenix nighttime street grid is so sharply visible from space, whereas large stretches of the interstate between midwestern cities remain comparatively dim?\n",
@@ -526,6 +574,26 @@
526574
"print(f\"Response: {response.output_text}\")\n"
527575
]
528576
},
577+
{
578+
"cell_type": "markdown",
579+
"id": "39c02785",
580+
"metadata": {},
581+
"source": [
582+
"## Inspect the response\n",
583+
"\n",
584+
"The underlying response from the agent contains metadata about what queries the agent sent to the knowledge base and what citations were found"
585+
]
586+
},
587+
{
588+
"cell_type": "code",
589+
"execution_count": null,
590+
"id": "b845d2ae",
591+
"metadata": {},
592+
"outputs": [],
593+
"source": [
594+
"response.to_dict()"
595+
]
596+
},
529597
{
530598
"cell_type": "markdown",
531599
"id": "3b328340",
@@ -538,7 +606,7 @@
538606
},
539607
{
540608
"cell_type": "code",
541-
"execution_count": 10,
609+
"execution_count": 11,
542610
"id": "3711252f",
543611
"metadata": {},
544612
"outputs": [
@@ -615,15 +683,15 @@
615683
},
616684
{
617685
"cell_type": "code",
618-
"execution_count": 11,
686+
"execution_count": 12,
619687
"id": "409befbb",
620688
"metadata": {},
621689
"outputs": [
622690
{
623691
"name": "stdout",
624692
"output_type": "stream",
625693
"text": [
626-
"AI agent 'earth-knowledge-agent' version '4' deleted successfully\n"
694+
"AI agent 'earth-knowledge-agent' version '7' deleted successfully\n"
627695
]
628696
}
629697
],
@@ -642,7 +710,7 @@
642710
},
643711
{
644712
"cell_type": "code",
645-
"execution_count": 12,
713+
"execution_count": 13,
646714
"id": "d67f8609",
647715
"metadata": {},
648716
"outputs": [
@@ -669,7 +737,7 @@
669737
},
670738
{
671739
"cell_type": "code",
672-
"execution_count": 13,
740+
"execution_count": 14,
673741
"id": "e35a6eb0",
674742
"metadata": {},
675743
"outputs": [
@@ -696,7 +764,7 @@
696764
},
697765
{
698766
"cell_type": "code",
699-
"execution_count": 14,
767+
"execution_count": 15,
700768
"id": "d9895f27",
701769
"metadata": {},
702770
"outputs": [
@@ -716,7 +784,7 @@
716784
],
717785
"metadata": {
718786
"kernelspec": {
719-
"display_name": ".venv (3.12.10)",
787+
"display_name": ".venv",
720788
"language": "python",
721789
"name": "python3"
722790
},

agentic-retrieval-pipeline-example/requirements.txt

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,5 @@ azure-identity
44
ipykernel
55
dotenv
66
azure-search-documents==11.7.0b2
7-
requests
7+
requests
8+
openai
Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
PROJECT_ENDPOINT=https://your-foundry-resource.services.ai.azure.com/api/projects/your-foundry-project
2+
AGENT_MODEL=gpt-4.1-mini
23
PROJECT_RESOURCE_ID=/subscriptions/your-subscription-id/resourceGroups/your-resource-group/providers/Microsoft.CognitiveServices/accounts/your-account/projects/your-project
34
AZURE_OPENAI_ENDPOINT=https://your-openai-service.openai.azure.com
45
AZURE_OPENAI_GPT_DEPLOYMENT=gpt-5-mini
56
AZURE_SEARCH_ENDPOINT=https://your-search-service.search.windows.net
6-
AZURE_SEARCH_INDEX_NAME=earth_at_night
7+
AZURE_SEARCH_INDEX_NAME=earth-at-night

0 commit comments

Comments
 (0)