Azure AI Foundry Agent ServiceのDeep Researchを使ってみた

先日、Deep ResearchがAzure AI Foundry Agent Serviceに登場しました。

azure.microsoft.com

これを利用すればWebから最新の情報を取得して、詳細な調査結果をアプリ内に組み込むことができそうです。

今回の記事では,、実際に動作させて検証を行いました。

環境

  • Python 3.11.3
  • azure-ai-agents 1.1.0b3
  • azure-ai-projects 1.0.0b12

利用する手順

公式ドキュメントに手順があるので、基本的にはそのまま進めます。

1. ポータルでの設定

手順は以下のページにまとめられています。 learn.microsoft.com

2. ソースコードの実装

ポータルでは実行できないので、コードを書く必要があります。

ソースコードは、以下に記載のコードを少し修正して、プロンプトを入力する形式に変更してみました。 learn.microsoft.com

import os, time
from typing import Optional
from azure.ai.projects import AIProjectClient
from azure.ai.agents import AgentsClient
from azure.ai.agents.models import DeepResearchTool, MessageRole, ThreadMessage
from azure.identity import DefaultAzureCredential


def fetch_and_print_new_agent_response(
    thread_id: str,
    agents_client: AgentsClient,
    last_message_id: Optional[str] = None,
) -> Optional[str]:
    response = agents_client.messages.get_last_message_by_role(
        thread_id=thread_id,
        role=MessageRole.AGENT,
    )
    if not response or response.id == last_message_id:
        return last_message_id  # No new content

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

    for ann in response.url_citation_annotations:
        print(f"URL Citation: [{ann.url_citation.title}]({ann.url_citation.url})")

    return response.id


def create_research_summary(
            message : ThreadMessage,
            filepath: str = "research_summary.md"
    ) -> None:
    if not message:
        print("No message content provided, cannot create research summary.")
        return

    with open(filepath, "w", encoding="utf-8") as fp:
        # Write text summary
        text_summary = "\n\n".join([t.text.value.strip() for t in message.text_messages])
        fp.write(text_summary)

        # Write unique URL citations, if present
        if message.url_citation_annotations:
            fp.write("\n\n## References\n")
            seen_urls = set()
            for ann in message.url_citation_annotations:
                url = ann.url_citation.url
                title = ann.url_citation.title or url
                if url not in seen_urls:
                    fp.write(f"- [{title}]({url})\n")
                    seen_urls.add(url)

    print(f"Research summary written to '{filepath}'.")

# ユーザー入力を取得
prompt = input("プロンプトを入力してください")

# Azure AI Projectsではアプリケーション認証が必要
# API_KEYは使わず、DefaultAzureCredentialまたはプロジェクトキーを使用
project_client = AIProjectClient(
    endpoint=os.environ["PROJECT_ENDPOINT"],
    credential=DefaultAzureCredential(),
)

bing_resource_name = os.environ["BING_RESOURCE_NAME"]
conn_id = project_client.connections.get(name=bing_resource_name).id


# Initialize a Deep Research tool with Bing Connection ID and Deep Research model deployment name
deep_research_tool = DeepResearchTool(
    bing_grounding_connection_id=conn_id,
    deep_research_model=os.environ["DEEP_RESEARCH_MODEL_DEPLOYMENT_NAME"],
)

# Create Agent with the Deep Research tool and process Agent run
with project_client:

    with project_client.agents as agents_client:

        # Create a new agent that has the Deep Research tool attached.
        # NOTE: To add Deep Research to an existing agent, fetch it with `get_agent(agent_id)` and then,
        # update the agent with the Deep Research tool.
        agent = agents_client.create_agent(
            model=os.environ["MODEL_DEPLOYMENT_NAME"],
            name="my-agent",
            instructions="You are a helpful Agent.",
            tools=deep_research_tool.definitions,
        )

        # [END create_agent_with_deep_research_tool]
        print(f"Created agent, ID: {agent.id}")

        # Create thread for communication
        thread = agents_client.threads.create()
        print(f"Created thread, ID: {thread.id}")

        # Create message to thread
        message = agents_client.messages.create(
            thread_id=thread.id,
            role="user",
            content=(prompt),
        )
        print(f"Created message, ID: {message.id}")

        print(f"Start processing the message... this may take a few minutes to finish. Be patient!")
        # Poll the run as long as run status is queued or in progress
        run = agents_client.runs.create(thread_id=thread.id, agent_id=agent.id)
        last_message_id = None
        while run.status in ("queued", "in_progress"):
            time.sleep(1)
            run = agents_client.runs.get(thread_id=thread.id, run_id=run.id)

            last_message_id = fetch_and_print_new_agent_response(
                thread_id=thread.id,
                agents_client=agents_client,
                last_message_id=last_message_id,
            )
            print(f"Run status: {run.status}")

        print(f"Run finished with status: {run.status}, ID: {run.id}")

        if run.status == "failed":
            print(f"Run failed: {run.last_error}")

        # Fetch the final message from the agent in the thread and create a research summary
        final_message = agents_client.messages.get_last_message_by_role(
            thread_id=thread.id, role=MessageRole.AGENT
        )
        if final_message:
            create_research_summary(final_message)

        # Clean-up and delete the agent once the run is finished.
        # NOTE: Comment out this line if you plan to reuse the agent later.
        agents_client.delete_agent(agent.id)
        print("Deleted agent")

コードの実行と結果

上記のソースコードを実行するとプロンプトを求められるので「Microsoft Build2025の発表内容について調査してください。」としました。

ログは以下のように表示されます。

Created agent, ID: asst_FsXMAEhlHuwq13fU3YoLUZxl
Created thread, ID: thread_zNUcEFpkwPRvaLeCWuJFQIN6
Created message, ID: msg_dQ7oAx4HnUhIGcVEvEN3oP6S
Start processing the message... this may take a few minutes to finish. Be patient!
Run status: RunStatus.IN_PROGRESS

Agent response:
Microsoft Build 2025の発表内容について調査し、主要な製品や技術の開示点を分かりやすくまとめます。完了後に結果をご報告します。

Title: Microsoft Build 2025の発表内容

 Starting deep research... 

Run status: RunStatus.IN_PROGRESS
Run status: RunStatus.IN_PROGRESS
Run status: RunStatus.IN_PROGRESS
Run status: RunStatus.IN_PROGRESS
Run status: RunStatus.IN_PROGRESS
Run status: RunStatus.IN_PROGRESS

Agent response:
cot_summary: **Gathering announcements**

OK, let me see. The user wants detailed, clearly organized, and possibly image-inclusive summaries of Microsoft Build 2025 announcements, focusing on major products, technology, services, AI-related advancements, and developer tools. 【1†Bing Search】
...
Run status: RunStatus.IN_PROGRESS
Run status: RunStatus.IN_PROGRESS
Run status: RunStatus.IN_PROGRESS
Run status: RunStatus.IN_PROGRESS
Output is truncated. View as a scrollable element or open in a text editor. Adjust cell output settings...
Unable to stream download.
Run status: RunStatus.IN_PROGRESS
Run status: RunStatus.IN_PROGRESS
Run status: RunStatus.IN_PROGRESS
Run status: RunStatus.IN_PROGRESS
Run status: RunStatus.IN_PROGRESS
Run status: RunStatus.IN_PROGRESS
Run status: RunStatus.IN_PROGRESS
Run status: RunStatus.IN_PROGRESS
Run status: RunStatus.IN_PROGRESS
Run status: RunStatus.IN_PROGRESS
Run status: RunStatus.IN_PROGRESS
Run status: RunStatus.IN_PROGRESS
Run status: RunStatus.IN_PROGRESS
Run status: RunStatus.IN_PROGRESS
Run status: RunStatus.IN_PROGRESS
Run status: RunStatus.IN_PROGRESS
Run status: RunStatus.IN_PROGRESS
Run status: RunStatus.IN_PROGRESS
Run status: RunStatus.IN_PROGRESS
Run status: RunStatus.IN_PROGRESS
Run status: RunStatus.IN_PROGRESS
Run status: RunStatus.IN_PROGRESS
Run status: RunStatus.IN_PROGRESS
Run status: RunStatus.IN_PROGRESS
Run status: RunStatus.IN_PROGRESS
...
Run status: RunStatus.COMPLETED
Run finished with status: RunStatus.COMPLETED, ID: run_23DSVmWmyDmsPFTcUu9NW0RI
Research summary written to 'research_summary.md'.
Deleted agent

今回の場合、実行時間は20分ほどかかりました。

結果は、以下のようにマークダウンとして出力されます。

実装する上での考慮事項

Bing Searchの利用条件

Deep ResearchはBing Searchを利用します。

料金や利用条件などが以下にまとめられているので、実装の際はこちらをご一読ください。

learn.microsoft.com

ストリーミングは非推奨

記事執筆時点では以下の記述があるため、ストリーミングは利用しないことが推奨されています。

制限事項: ディープ リサーチ ツールは、現在、非ストリーミング シナリオでのみ推奨されています。   
ストリーミングでの使用は機能しますが、タイムアウトする場合があるため、お勧めしません。

参考ページ learn.microsoft.com

終わりに

今回は、Azure AI Foundry Agent ServiceのDeep Researchについて調査しました。

実行に少し時間がかかるなど考慮するべき点がありますが、詳細な調査をする機能をアプリに組み込む場合に便利そうだと思いました。

是非皆さんも使ってみてください。

執筆担当者プロフィール
古川 貴浩

古川 貴浩(日本ビジネスシステムズ株式会社)

アプリケーション開発をしています。.NETやAI関連が好きです。

担当記事一覧