Skip to content

Commit 776ed57

Browse files
committed
changing code
1 parent 664431c commit 776ed57

File tree

1 file changed

+71
-115
lines changed

1 file changed

+71
-115
lines changed

articles/ai-foundry/agents/how-to/tools/deep-research-samples.md

Lines changed: 71 additions & 115 deletions
Original file line numberDiff line numberDiff line change
@@ -21,44 +21,38 @@ Use this article to find step-by-step instructions and code samples for the Deep
2121
> [!NOTE]
2222
> Limitation: The Deep Research tool is currently recommended only in nonstreaming scenarios. Using it with streaming can work, but it might occasionally time out and is therefore not recommended.
2323
24-
## Create a function to get and print an agent response
24+
## Create an agent the Deep Research tool
2525

2626
```python
27-
import asyncio
28-
import os
27+
import os, time
2928
from typing import Optional
30-
31-
from azure.ai.projects.aio import AIProjectClient
32-
from azure.ai.agents.aio import AgentsClient
29+
from azure.ai.projects import AIProjectClient
30+
from azure.identity import DefaultAzureCredential
31+
from azure.ai.agents import AgentsClient
3332
from azure.ai.agents.models import DeepResearchTool, MessageRole, ThreadMessage
34-
from azure.identity.aio import DefaultAzureCredential
3533

36-
async def fetch_and_print_new_agent_response(
34+
35+
def fetch_and_print_new_agent_response(
3736
thread_id: str,
3837
agents_client: AgentsClient,
3938
last_message_id: Optional[str] = None,
4039
) -> Optional[str]:
41-
response = await agents_client.messages.get_last_message_by_role(
40+
response = agents_client.messages.get_last_message_by_role(
4241
thread_id=thread_id,
4342
role=MessageRole.AGENT,
4443
)
45-
4644
if not response or response.id == last_message_id:
47-
return last_message_id
45+
return last_message_id # No new content
4846

4947
print("\nAgent response:")
5048
print("\n".join(t.text.value for t in response.text_messages))
5149

52-
# Print citation annotations (if any)
5350
for ann in response.url_citation_annotations:
5451
print(f"URL Citation: [{ann.url_citation.title}]({ann.url_citation.url})")
5552

5653
return response.id
57-
```
5854

59-
## Create a function to create a research summary
6055

61-
```python
6256
def create_research_summary(
6357
message : ThreadMessage,
6458
filepath: str = "research_summary.md"
@@ -84,128 +78,90 @@ def create_research_summary(
8478
seen_urls.add(url)
8579

8680
print(f"Research summary written to '{filepath}'.")
87-
```
8881

8982

83+
project_client = AIProjectClient(
84+
endpoint=os.environ["PROJECT_ENDPOINT"],
85+
credential=DefaultAzureCredential(),
86+
)
9087

91-
## Create a project client and initialize the Deep Research tool
92-
Create a client object, which will contain the endpoint for connecting to your AI project and other resources.
93-
94-
```python
95-
async def main() -> None:
96-
97-
project_client = AIProjectClient(
98-
endpoint=os.environ["PROJECT_ENDPOINT"],
99-
credential=DefaultAzureCredential(),
100-
)
101-
102-
# Initialize a Deep Research tool with Bing Connection ID and Deep Research model deployment name
103-
deep_research_tool = DeepResearchTool(
104-
bing_grounding_connection_id=os.environ["AZURE_BING_CONNECTION_ID"],
105-
deep_research_model=os.environ["DEEP_RESEARCH_MODEL_DEPLOYMENT_NAME"],
106-
)
107-
108-
```
109-
110-
## Create an agent
88+
# [START create_agent_with_deep_research_tool]
89+
conn_id = os.environ["AZURE_BING_CONNECTION_ID"]
11190

112-
To make the Deep Research tool available to your agent, use the `tools` parameter to initialize it and attach it to the agent. You can find your connection in the connected resources section of your project in the Azure AI Foundry portal. You also need to specify the deployment name of your Deep Research model.
91+
# Initialize a Deep Research tool with Bing Connection ID and Deep Research model deployment name
92+
deep_research_tool = DeepResearchTool(
93+
bing_grounding_connection_id=conn_id,
94+
deep_research_model=os.environ["DEEP_RESEARCH_MODEL_DEPLOYMENT_NAME"],
95+
)
11396

114-
```python
115-
async with project_client:
97+
# Create Agent with the Deep Research tool and process Agent run
98+
with project_client:
11699

117-
agents_client = project_client.agents
100+
with project_client.agents as agents_client:
118101

119102
# Create a new agent that has the Deep Research tool attached.
120103
# NOTE: To add Deep Research to an existing agent, fetch it with `get_agent(agent_id)` and then,
121104
# update the agent with the Deep Research tool.
122-
agent = await agents_client.create_agent(
105+
agent = agents_client.create_agent(
123106
model=os.environ["MODEL_DEPLOYMENT_NAME"],
124107
name="my-agent",
125108
instructions="You are a helpful Agent that assists in researching scientific topics.",
126109
tools=deep_research_tool.definitions,
127110
)
128-
print(f"Created agent, ID: {agent.id}")
129-
```
130-
131-
## Create a thread
132-
133-
Create a thread and attach a message to it
134-
135-
```python
136-
# Create thread for communication
137-
thread = await agents_client.threads.create()
138-
print(f"Created thread, ID: {thread.id}")
139-
140-
# Create message to thread
141-
message = await agents_client.messages.create(
142-
thread_id=thread.id,
143-
role="user",
144-
content=(
145-
"Research the current state of studies on orca intelligence and orca language, including what is currently known about orcas' cognitive capabilities and communication systems."
146-
),
147-
)
148-
print(f"Created message, ID: {message.id}")
149-
150-
```
151-
152-
## Create a run and check the output
153-
154-
Create a run and observe the response to the question.
155-
156-
> [!NOTE]
157-
> According to Grounding with Bing's [terms of use and use and display requirements](https://www.microsoft.com/bing/apis/grounding-legal#use-and-display-requirements), you need to display both website URLs and Bing search query URLs in your custom interface. See the [Grounding with Bing Search documentation](./bing-grounding.md#how-to-display-grounding-with-bing-search-results) for more information.
158-
159-
```python
160-
print("Start processing the message... this may take a few minutes to finish. Be patient!")
161-
# Poll the run as long as run status is queued or in progress
162-
run = await agents_client.runs.create(thread_id=thread.id, agent_id=agent.id)
163-
last_message_id: Optional[str] = None
164-
while run.status in ("queued", "in_progress"):
165-
await asyncio.sleep(1)
166-
run = await agents_client.runs.get(thread_id=thread.id, run_id=run.id)
167-
168-
last_message_id = await fetch_and_print_new_agent_response(
169-
thread_id=thread.id,
170-
agents_client=agents_client,
171-
last_message_id=last_message_id,
172-
)
173-
print(f"Run status: {run.status}")
174-
175-
print(f"Run finished with status: {run.status}, ID: {run.id}")
176111

177-
if run.status == "failed":
178-
print(f"Run failed: {run.last_error}")
179-
180-
# Fetch the final message from the agent in the thread and create a research summary
181-
final_message = await agents_client.messages.get_last_message_by_role(
182-
thread_id=thread.id, role=MessageRole.AGENT
183-
)
184-
if final_message:
185-
create_research_summary(final_message)
186-
187-
# Clean-up and delete the agent once the run is finished.
188-
# NOTE: Comment out this line if you plan to reuse the agent later.
189-
await agents_client.delete_agent(agent.id)
190-
print("Deleted agent")
191-
192-
193-
if __name__ == "__main__":
194-
asyncio.run(main())
195-
```
196-
197-
## Delete the agent (optional)
112+
# [END create_agent_with_deep_research_tool]
113+
print(f"Created agent, ID: {agent.id}")
198114

199-
If you decide you don't need your agent, you can delete with:
115+
# Create thread for communication
116+
thread = agents_client.threads.create()
117+
print(f"Created thread, ID: {thread.id}")
118+
119+
# Create message to thread
120+
message = agents_client.messages.create(
121+
thread_id=thread.id,
122+
role="user",
123+
content=(
124+
"Research the current state of studies on orca intelligence and orca language, including what is currently known about orcas' cognitive capabilities and communication systems."
125+
),
126+
)
127+
print(f"Created message, ID: {message.id}")
128+
129+
print(f"Start processing the message... this may take a few minutes to finish. Be patient!")
130+
# Poll the run as long as run status is queued or in progress
131+
run = agents_client.runs.create(thread_id=thread.id, agent_id=agent.id)
132+
last_message_id = None
133+
while run.status in ("queued", "in_progress"):
134+
time.sleep(1)
135+
run = agents_client.runs.get(thread_id=thread.id, run_id=run.id)
136+
137+
last_message_id = fetch_and_print_new_agent_response(
138+
thread_id=thread.id,
139+
agents_client=agents_client,
140+
last_message_id=last_message_id,
141+
)
142+
print(f"Run status: {run.status}")
143+
144+
print(f"Run finished with status: {run.status}, ID: {run.id}")
145+
146+
if run.status == "failed":
147+
print(f"Run failed: {run.last_error}")
148+
149+
# Fetch the final message from the agent in the thread and create a research summary
150+
final_message = agents_client.messages.get_last_message_by_role(
151+
thread_id=thread.id, role=MessageRole.AGENT
152+
)
153+
if final_message:
154+
create_research_summary(final_message)
200155

201-
```python
202-
agents_client.delete_agent(agent.id)
203-
print("Deleted agent")
156+
# Clean-up and delete the agent once the run is finished.
157+
# NOTE: Comment out this line if you plan to reuse the agent later.
158+
agents_client.delete_agent(agent.id)
159+
print("Deleted agent")
204160
```
205161

206162
## Next steps
207163

208164
* [Reference documentation](https://aka.ms/azsdk/azure-ai-projects/python/reference)
209-
* [Sample on GitHub](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-agents/samples/agents_async/sample_agents_deep_research_async.py)
165+
* [Asynchronous sample on GitHub](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-agents/samples/agents_async/sample_agents_deep_research_async.py)
210166
* [Library source code](https://aka.ms/azsdk/azure-ai-projects/python/code)
211167
* [Package (PyPi)](https://aka.ms/azsdk/azure-ai-projects/python/package) |

0 commit comments

Comments
 (0)