Skip to content

Commit ac0ad5d

Browse files
committed
Python code for create a knowledge agent
1 parent 03aa62e commit ac0ad5d

File tree

1 file changed

+202
-45
lines changed

1 file changed

+202
-45
lines changed

articles/search/search-agentic-retrieval-how-to-create.md

Lines changed: 202 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ author: HeidiSteen
77
ms.author: heidist
88
ms.service: azure-ai-search
99
ms.topic: how-to
10-
ms.date: 08/29/2025
10+
ms.date: 09/30/2025
1111
---
1212

1313
# Create a knowledge agent in Azure AI Search
@@ -31,17 +31,17 @@ After you create a knowledge agent, you can update its properties at any time. I
3131

3232
+ Familiarity with [agentic retrieval concepts and use cases](search-agentic-retrieval-concept.md).
3333

34-
+ A [supported chat completion model](#supported-models) on Azure OpenAI.
35-
3634
+ Azure AI Search, in any [region that provides semantic ranker](search-region-support.md), on the basic pricing tier or higher. Your search service must have a [managed identity](search-how-to-managed-identities.md) for role-based access to the model.
3735

38-
+ Permissions on Azure AI Search. **Search Service Contributor** can create and manage a knowledge agent. **Search Index Data Reader** can run queries. Instructions are provided in this article. [Quickstart: Connect to a search service](/azure/search/search-get-started-rbac?pivots=rest) explains how to configure roles and get a personal access token for REST calls.
36+
+ A [supported chat completion model](#supported-models) on Azure OpenAI.
3937

40-
+ A [knowledge source](search-knowledge-source-overview.md) that identifies searchable content used by the agent. It can be either a [search index knowledge source](search-knowledge-source-how-to-index.md) or a [blob knowledge source](search-knowledge-source-how-to-blob.md)
38+
+ Permission requirements. **Search Service Contributor** can create and manage a knowledge agent. **Search Index Data Reader** can run queries. Instructions are provided in this article. [Quickstart: Connect to a search service](/azure/search/search-get-started-rbac?pivots=rest) explains how to configure roles and get a personal access token for REST calls.
39+
40+
+ Content requirements. A [knowledge source](search-knowledge-source-overview.md) that identifies searchable content used by the agent. It can be either a [search index knowledge source](search-knowledge-source-how-to-index.md) or a [blob knowledge source](search-knowledge-source-how-to-blob.md)
4141

4242
+ API requirements. To create or use a knowledge agent, use the [2025-08-01-preview](/rest/api/searchservice/operation-groups?view=rest-searchservice-2025-08-01-preview&preserve-view=true) data plane REST API. Or, use a preview package of an Azure SDK that provides knowledge agent APIs: [Azure SDK for Python](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/CHANGELOG.md), [Azure SDK for .NET](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/search/Azure.Search.Documents/CHANGELOG.md#1170-beta3-2025-03-25), [Azure SDK for Java](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/search/azure-search-documents/CHANGELOG.md). **There's no Azure portal support knowledge agents at this time**.
4343

44-
To follow the steps in this guide, we recommend [Visual Studio Code](https://code.visualstudio.com/download) with a [REST client](https://marketplace.visualstudio.com/items?itemName=humao.rest-client) for sending preview REST API calls to Azure AI Search. T
44+
To follow the steps in this guide, we recommend [Visual Studio Code](https://code.visualstudio.com/download) with a [REST client](https://marketplace.visualstudio.com/items?itemName=humao.rest-client) for sending preview REST API calls to Azure AI Search or the [Python extension](https://marketplace.visualstudio.com/items?itemName=ms-python.python) and [Jupyter package](https://pypi.org/project/jupyter/).
4545

4646
## Deploy a model for agentic retrieval
4747

@@ -72,7 +72,7 @@ Use Azure OpenAI or an equivalent open source model:
7272

7373
Azure AI Search needs access to the chat completion model. You can use key-based or role-based authentication (recommended).
7474

75-
### Use role-based authentication
75+
### [**Use roles**](#tab/rbac)
7676

7777
If you're using role-based authentication, on your Azure OpenAI resource, assign the **Cognitive Services User** role to a search service managed identity.
7878

@@ -96,7 +96,7 @@ In Azure, you must have **Owner** or **User Access Administrator** permissions o
9696
> [!IMPORTANT]
9797
> If you use role-based authentication, be sure to remove all references to the API key in your requests. In a request that specifies both approaches, the API key is used instead of roles.
9898
99-
### Use key-based authentication
99+
### [**Use keys**](#tab/keys)
100100
101101
You can use API keys if you don't have permission to create role assignments.
102102
@@ -114,10 +114,94 @@ You can use API keys if you don't have permission to create role assignments.
114114
@api-key: {{search-api-key}}
115115
```
116116

117+
---
118+
117119
## Check for existing knowledge agents
118120

119121
The following request lists knowledge agents by name. Within the knowledge agents collection, all knowledge agents must be uniquely named. It's helpful to know about existing knowledge agents for reuse or for naming new agents.
120122

123+
### [**Python**](#tab/python-get-agents)
124+
125+
```python
126+
# List existing knowledge agents on the search service
127+
from azure.search.documents.indexes import SearchIndexClient
128+
129+
index_client = SearchIndexClient(endpoint=search_endpoint, credential=credential)
130+
131+
try:
132+
agents = {agent.name: agent for agent in index_client.list_agents(api_version=search_api_version)}
133+
print(f"\nKnowledge agents on search service '{search_endpoint}':")
134+
135+
if agents:
136+
print(f"Found {len(agents)} knowledge agent(s):")
137+
for i, (name, agent) in enumerate(sorted(agents.items()), 1):
138+
print(f"{i}. Name: {name}")
139+
if agent.knowledge_sources:
140+
ks_names = [ks.name for ks in agent.knowledge_sources]
141+
print(f" Knowledge Sources: {', '.join(ks_names)}")
142+
print()
143+
else:
144+
print("No knowledge agents found.")
145+
146+
except Exception as e:
147+
print(f"Error listing knowledge agents: {str(e)}")
148+
```
149+
150+
You can also return a single agent by name to review its JSON definition.
151+
152+
```python
153+
# Get knowledge agent definition for earth-knowledge-agent-2
154+
from azure.search.documents.indexes import SearchIndexClient
155+
import json
156+
157+
index_client = SearchIndexClient(endpoint=search_endpoint, credential=credential)
158+
159+
try:
160+
agent_name = "earth-knowledge-agent-2"
161+
agent = index_client.get_agent(agent_name, api_version=search_api_version)
162+
163+
print(f"Knowledge agent '{agent_name}':")
164+
print(f"Name: {agent.name}")
165+
166+
if agent.description:
167+
print(f"Description: {agent.description}")
168+
169+
if agent.models:
170+
print(f"\nModels ({len(agent.models)}):")
171+
for i, model in enumerate(agent.models, 1):
172+
print(f" {i}. {type(model).__name__}")
173+
if hasattr(model, 'azure_open_ai_parameters'):
174+
params = model.azure_open_ai_parameters
175+
print(f" Resource: {params.resource_url}")
176+
print(f" Deployment: {params.deployment_name}")
177+
print(f" Model: {params.model_name}")
178+
179+
if agent.knowledge_sources:
180+
print(f"\nKnowledge Sources ({len(agent.knowledge_sources)}):")
181+
for i, ks in enumerate(agent.knowledge_sources, 1):
182+
print(f" {i}. {ks.name} (threshold: {ks.reranker_threshold})")
183+
184+
if agent.output_configuration:
185+
config = agent.output_configuration
186+
print(f"\nOutput: {config.modality} (activity: {config.include_activity})")
187+
188+
# Full JSON definition
189+
print(f"\nJSON definition:")
190+
print(json.dumps(agent.as_dict(), indent=2))
191+
192+
except Exception as e:
193+
print(f"Error: {str(e)}")
194+
195+
# Show available agents
196+
try:
197+
agents = {agent.name: agent for agent in index_client.list_agents(api_version=search_api_version)}
198+
print(f"\nAvailable agents: {list(agents.keys())}")
199+
except Exception:
200+
print("Could not list available agents.")
201+
```
202+
203+
### [**REST**](#tab/rest-get-agents)
204+
121205
```http
122206
# List knowledge agents
123207
GET {{search-url}}/agents?api-version=2025-08-01-preview
@@ -134,6 +218,8 @@ GET {{search-url}}/agents/{{agent-name}}?api-version=2025-08-01-preview
134218
Authorization: Bearer {{accessToken}}
135219
```
136220

221+
---
222+
137223
## Create a knowledge agent
138224

139225
A knowledge agent drives the agentic retrieval pipeline. In application code, it's called by other agents or chat bots.
@@ -142,6 +228,44 @@ Its composition consists of connections between *knowledge sources* (searchable
142228

143229
To create an agent, use the 2025-08-01-preview data plane REST API or an Azure SDK preview package that provides equivalent functionality.
144230

231+
Recall that you must have an existing [knowledge source](search-knowledge-source-overview.md) to give to the agent.
232+
233+
### [**Python**](#tab/python-create-agent)
234+
235+
```python
236+
from azure.search.documents.indexes.models import KnowledgeAgent, KnowledgeAgentAzureOpenAIModel, KnowledgeSourceReference, AzureOpenAIVectorizerParameters, KnowledgeAgentOutputConfiguration, KnowledgeAgentOutputConfigurationModality
237+
from azure.search.documents.indexes import SearchIndexClient
238+
239+
aoai_params = AzureOpenAIVectorizerParameters(
240+
resource_url=aoai_endpoint,
241+
deployment_name=aoai_gpt_deployment,
242+
model_name=aoai_gpt_model,
243+
)
244+
245+
output_cfg = KnowledgeAgentOutputConfiguration(
246+
modality=KnowledgeAgentOutputConfigurationModality.ANSWER_SYNTHESIS,
247+
include_activity=True,
248+
)
249+
250+
agent = KnowledgeAgent(
251+
name=knowledge_agent_name,
252+
models=[KnowledgeAgentAzureOpenAIModel(azure_open_ai_parameters=aoai_params)],
253+
knowledge_sources=[
254+
KnowledgeSourceReference(
255+
name=knowledge_source_name,
256+
reranker_threshold=2.5,
257+
)
258+
],
259+
output_configuration=output_cfg,
260+
)
261+
262+
index_client = SearchIndexClient(endpoint=search_endpoint, credential=credential)
263+
index_client.create_or_update_agent(agent, api_version=search_api_version)
264+
print(f"Knowledge agent '{knowledge_agent_name}' created or updated successfully.")
265+
```
266+
267+
### [**REST**](#tab/rest-create-agent)
268+
145269
```http
146270
@search-url=<YOUR SEARCH SERVICE URL>
147271
@agent-name=<YOUR AGENT NAME>
@@ -242,14 +366,68 @@ PUT {{search-url}}/agents/{{agent-name}}?api-version=2025-08-01-preview
242366

243367
+ `encryptionKey` is optional. Include an encryption key definition if you're supplementing with [customer-managed keys](search-security-manage-encryption-keys.md).
244368

245-
<!-- --- -->
369+
---
246370

247371
## Query the knowledge agent
248372

249-
Call the **retrieve** action on the knowledge agent object to confirm the model connection and return a response. Use the [2025-08-01-preview](/rest/api/searchservice/operation-groups?view=rest-searchservice-2025-08-01-preview&preserve-view=true) data plane REST API or an Azure SDK preview package that provides equivalent functionality for this task.
373+
Call the **retrieve** action on the knowledge agent object to confirm the model connection and return a response. Use the [2025-08-01-preview](/rest/api/searchservice/operation-groups?view=rest-searchservice-2025-08-01-preview&preserve-view=true) data plane REST API or an Azure SDK preview package that provides equivalent functionality for this task. For more information about the **retrieve** API and the shape of the response, see [Retrieve data using a knowledge agent in Azure AI Search](search-agentic-retrieval-how-to-retrieve.md).
250374

251375
Replace "where does the ocean look green?" with a query string that's valid for your search index.
252376

377+
### [**Python**](#tab/python-query-agent)
378+
379+
Start with instructions.
380+
381+
```python
382+
instructions = """
383+
A Q&A agent that can answer questions about the Earth at night.
384+
If you don't have the answer, respond with "I don't know".
385+
"""
386+
387+
messages = [
388+
{
389+
"role": "system",
390+
"content": instructions
391+
}
392+
]
393+
```
394+
395+
Then send the query.
396+
397+
```python
398+
from azure.search.documents.agent import KnowledgeAgentRetrievalClient
399+
from azure.search.documents.agent.models import KnowledgeAgentRetrievalRequest, KnowledgeAgentMessage, KnowledgeAgentMessageTextContent, SearchIndexKnowledgeSourceParams
400+
401+
agent_client = KnowledgeAgentRetrievalClient(endpoint=search_endpoint, agent_name=knowledge_agent_name, credential=credential)
402+
query_1 = """
403+
where does the ocean look green??
404+
"""
405+
406+
messages.append({
407+
"role": "user",
408+
"content": query_1
409+
})
410+
411+
req = KnowledgeAgentRetrievalRequest(
412+
messages=[
413+
KnowledgeAgentMessage(
414+
role=m["role"],
415+
content=[KnowledgeAgentMessageTextContent(text=m["content"])]
416+
) for m in messages if m["role"] != "system"
417+
],
418+
knowledge_source_params=[
419+
SearchIndexKnowledgeSourceParams(
420+
knowledge_source_name=knowledge_source_name,
421+
)
422+
]
423+
)
424+
425+
result = agent_client.retrieve(retrieval_request=req, api_version=search_api_version)
426+
print(f"Retrieved content from '{knowledge_source_name}' successfully.")
427+
```
428+
429+
### [**REST**](#tab/rest-query-agent)
430+
253431
```http
254432
# Send grounding request
255433
POST {{search-url}}/agents/{{agent-name}}/retrieve?api-version=2025-08-01-preview
@@ -301,55 +479,34 @@ The response to the previous query might look like this:
301479
}
302480
]
303481
}
304-
],
482+
]
305483
```
306484

485+
---
307486

308-
<!-- ```http
309-
# Send grounding request
310-
POST {{search-url}}/agents/{{agent-name}}/retrieve?api-version=2025-08-01-preview
311-
Content-Type: application/json
312-
Authorization: Bearer {{accessToken}}
487+
## Delete an agent
313488

314-
{
315-
"messages" : [
316-
{
317-
"role" : "assistant",
318-
"content" : [
319-
{ "type" : "text", "text" : "You are a helpful assistant for Contoso Human Resources. You have access to a search index containing guidelines about health care coverage for Washington state. If you can't find the answer in the search, say you don't know." }
320-
]
321-
},
322-
{
323-
"role" : "user",
324-
"content" : [
325-
{ "type" : "text", "text" : "What are my vision benefits?" }
326-
]
327-
}
328-
],
329-
"targetIndexParams" : [
330-
{
331-
"indexName" : "{{index-name}}",
332-
"filterAddOn" : "State eq 'WA'",
333-
"IncludeReferenceSourceData": true,
334-
"rerankerThreshold" : 2.5
335-
"maxDocsForReranker": 250
336-
}
337-
]
338-
}
339-
``` -->
489+
If you no longer need the agent, or if you need to rebuild it on the search service, use this request to delete the current object.
340490

341-
For more information about the **retrieve** API and the shape of the response, see [Retrieve data using a knowledge agent in Azure AI Search](search-agentic-retrieval-how-to-retrieve.md).
491+
### [**Python**](#tab/python-delete-agent)
342492

343-
## Delete an agent
493+
```python
494+
from azure.search.documents.indexes import SearchIndexClient
344495

345-
If you no longer need the agent, or if you need to rebuild it on the search service, use this request to delete the current object.
496+
index_client = SearchIndexClient(endpoint=search_endpoint, credential=credential)
497+
index_client.delete_agent(knowledge_agent_name)
498+
print(f"Knowledge agent '{knowledge_agent_name}' deleted successfully.")
499+
```
346500

501+
### [**REST**](#tab/rest-delete-agent)
347502
```http
348503
# Delete agent
349504
DELETE {{search-url}}/agents/{{agent-name}}?api-version=2025-08-01-preview
350505
Authorization: Bearer {{accessToken}}
351506
```
352507

508+
---
509+
353510
## Related content
354511

355512
+ [Agentic retrieval in Azure AI Search](search-agentic-retrieval-concept.md)

0 commit comments

Comments
 (0)