Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
# Copyright (c) Microsoft. All rights reserved.
import asyncio
import os
from typing import Any

from agent_framework._types import AgentRunResponse, CitationAnnotation, TextContent
from agent_framework.azure import AzureAIClient
from azure.identity.aio import AzureCliCredential

Expand All @@ -18,6 +20,38 @@
"""


def extract_citations_from_response(response: AgentRunResponse) -> list[dict[str, Any]]:
"""Extract citation information from an AgentRunResponse."""
citations: list[dict[str, Any]] = []

if hasattr(response, "messages") and response.messages:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you can skip a bunch of these checks (it's a sample, so we can be a less strict on typing, to improve readability) and inverse the logic for the rest:

Suggested change
if hasattr(response, "messages") and response.messages:
from itertools import chain
if not response.messages:
return citations
for content in chain.from_iterable(message.contents for message in response.messages):
if not content.annotations:
continue
# parse the annotations

Also why not just return the citations instead of this dict?

for message in response.messages:
if hasattr(message, "contents") and message.contents:
for content in message.contents:
if isinstance(content, TextContent) and hasattr(content, "annotations") and content.annotations:
for annotation in content.annotations:
if isinstance(annotation, CitationAnnotation):
citation_info = {
"url": annotation.url,
"title": getattr(annotation, "title", None),
"file_id": getattr(annotation, "file_id", None),
}

# Extract text position information
if hasattr(annotation, "annotated_regions") and annotation.annotated_regions:
citation_info["positions"] = [
{
"start_index": region.start_index,
"end_index": region.end_index,
}
for region in annotation.annotated_regions
]

citations.append(citation_info)

return citations


async def main() -> None:
async with (
AzureCliCredential() as credential,
Expand All @@ -33,17 +67,33 @@ async def main() -> None:
"project_connection_id": os.environ["AI_SEARCH_PROJECT_CONNECTION_ID"],
"index_name": os.environ["AI_SEARCH_INDEX_NAME"],
# For query_type=vector, ensure your index has a field with vectorized data.
"query_type": "simple",
"query_type": "vector",
}
]
},
},
) as agent,
):
query = "Tell me about insurance options"
query = (
"Use Azure AI search knowledge tool to find detailed information about a winter hotel."
" Use the search tool and index."
)
print(f"User: {query}")
result = await agent.run(query)
print(f"Result: {result}\n")

# Get the response
response = await agent.run(query)
print(f"Agent: {response}\n")

# Extract citation data
citations = extract_citations_from_response(response)

print("=== CITATION INFORMATION ===")
if citations:
for i, citation in enumerate(citations, 1):
print(f"Citation {i}:")
print(f" URL: {citation['url']}")
Copy link

Copilot AI Dec 2, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The extract_citations_from_response function has incomplete citation output. Currently only the URL is printed (line 94), but the function extracts title, file_id, and positions which are not displayed. This makes the citation information incomplete for users who may need these additional details.

Consider printing all extracted citation information:

print(f"Citation {i}:")
print(f"  URL: {citation['url']}")
if citation.get('title'):
    print(f"  Title: {citation['title']}")
if citation.get('file_id'):
    print(f"  File ID: {citation['file_id']}")
if citation.get('positions'):
    print(f"  Positions: {citation['positions']}")
Suggested change
print(f" URL: {citation['url']}")
print(f" URL: {citation['url']}")
if citation.get('title'):
print(f" Title: {citation['title']}")
if citation.get('file_id'):
print(f" File ID: {citation['file_id']}")
if citation.get('positions'):
print(f" Positions: {citation['positions']}")

Copilot uses AI. Check for mistakes.
else:
print("No citations found in the response.")


if __name__ == "__main__":
Expand Down
Loading