Skip to content

issue with accessing agent created in microsoft foundry from azure functions. dveloper role assigned #692

@ddruvam

Description

@ddruvam

implemented as mentioned but its not working please guide.

https://github.com/microsoft-foundry/foundry-samples/blob/main/samples/python/quickstart/chat-with-agent/quickstart-chat-with-agent.py

azure-ai-projects>=2.0.0a20250915020
azure-identity
python-dotenv
openai

logic_question_tree.py

from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
from azure.storage.blob import BlobServiceClient
import os, re, uuid, logging

import openai

def clean_agent_output(text):
# keep only CSV-like rows
rows = []
for line in text.splitlines():
if re.match(r'^(ID|Q\d+|SQ\d+)', line) or ',' in line:
rows.append(line.strip().strip('[]').replace('"','').replace("'",""))
return "\n".join(rows)

def call_question_tree_agent(text):
endpoint = os.environ["AZURE_FOUNDRY_ENDPOINT"] # MUST be the project endpoint
agent_name = os.environ["QUESTION_TREE_AGENT_NAME"]
agent_version = os.environ["QUESTION_TREE_AGENT_VERSION"]

project_client = AIProjectClient(
    endpoint=endpoint,
    credential=DefaultAzureCredential(),
)

openai = project_client.get_openai_client()

conversation = openai.conversations.create()

response = openai.responses.create(
    conversation=conversation.id,
    extra_body={"agent_reference": {"name": agent_name, "type": "agent_reference"}},
    input=text,
)

return response.output_text

///////////

logic_question_tree_blob.py

from azure.storage.blob import BlobServiceClient
import os, re, uuid, logging
from logic_question_tree import call_question_tree_agent, clean_agent_output

def process_processing_blob(container, blob_name):
conn = os.environ["AzureWebJobsStorage"]
svc = BlobServiceClient.from_connection_string(conn)

# read
blob = svc.get_blob_client(container, blob_name)
text = blob.download_blob().readall().decode("utf-8")

# call agent
raw = call_question_tree_agent(text)
cleaned = clean_agent_output(raw)

# write CSV
out_container = "questions-expected-answers"
out_name = blob_name.rsplit(".",1)[0] + ".csv"
out_blob = svc.get_blob_client(out_container, out_name)
out_blob.upload_blob(cleaned, overwrite=True)

# move original
move_to = "processed"
dst = svc.get_blob_client(container, f"{move_to}/{blob_name.split('/')[-1]}")
dst.start_copy_from_url(blob.url)
blob.delete_blob()

//////

@app.event_grid_trigger(arg_name="event")
def Question_Tree_Processor_Azure(event: func.EventGridEvent):
event_json = event.get_json()
logging.info(f"PROCESSING EVENT: {event_json}")

print("ENDPOINT:", repr(os.environ["AZURE_FOUNDRY_ENDPOINT"]))
logging.info("ENDPOINT: %s", repr(os.environ["AZURE_FOUNDRY_ENDPOINT"]))

# Extract blob URL (Azure sometimes uses 'url' or 'Url')
blob_url = event_json.get("url") or event_json.get("Url")
if not blob_url:
    logging.error("No blob URL found in event")
    return

# Parse container + blob name
parsed = urlparse(blob_url)
path = parsed.path.lstrip("/")  # e.g. processing/airlines%20faq%20-%20processing.txt
container, blob_name = path.split("/", 1)
blob_name = unquote(blob_name)

try:
    qt.process_processing_blob(container, blob_name)
    logging.info("Question tree processing complete")
except Exception as e:
    logging.error(f"Error: {e}")
    raise

//////////

5/2/2026, 12:52:22 AM
Error
Error: Error code: 401 - {'error': {'code': 'PermissionDenied', 'message': 'The principal 238d16af-467a-4c66-8f07-2048c59b6c43 lacks the required data action Microsoft.CognitiveServices/accounts/AIServices/agents/write to perform POST /api/projects/{projectName}/openai/* operation. For instructions on granting the necessary permissions, see https://aka.ms/FoundryPermissions.'}}
5/2/2026, 12:52:22 AM
Error
Result: Failure Type: Exception: AuthenticationError: Error code: 401 - {'error': {'code': 'PermissionDenied', 'message': 'The principal 238d16af-467a-4c66-8f07-2048c59b6c43 lacks the required data action Microsoft.CognitiveServices/accounts/AIServices/agents/write to perform POST /api/projects/{projectName}/openai/* operation. For instructions on granting the necessary permissions, see https://aka.ms/FoundryPermissions.'}} Stack: Traceback (most recent call last): File "/azure-functions-host/workers/python/3.11/LINUX/X64/azure_functions_worker/dispatcher.py", line 685, in _handle__invocation_request call_result = await self._loop.run_in_executor( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/concurrent/futures/thread.py", line 58, in run result = self.fn(*self.args, **self.kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/azure-functions-host/workers/python/3.11/LINUX/X64/azure_functions_worker/dispatcher.py", line 1019, in _run_sync_func return ExtensionManager.get_sync_invocation_wrapper(context, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/azure-functions-host/workers/python/3.11/LINUX/X64/azure_functions_worker/extension.py", line 211, in _raw_invocation_wrapper result = function(**args) ^^^^^^^^^^^^^^^^ File "/home/site/wwwroot/function_app.py", line 85, in Question_Tree_Processor_Azure qt.process_processing_blob(container, blob_name) File "/home/site/wwwroot/logic_question_tree_blob.py", line 16, in process_processing_blob raw = call_question_tree_agent(text) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/site/wwwroot/logic_question_tree.py", line 29, in call_question_tree_agent conversation = openai.conversations.create() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/site/wwwroot/.python_packages/lib/site-packages/openai/resources/conversations/conversations.py", line 94, in create return self._post( ^^^^^^^^^^^ File "/home/site/wwwroot/.python_packages/lib/site-packages/openai/_base_client.py", line 1314, in post return cast(ResponseT, self.request(cast_to, opts, stream=stream, stream_cls=stream_cls)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/site/wwwroot/.python_packages/lib/site-packages/openai/_base_client.py", line 1087, in request raise self._make_status_error_from_response(err.response) from None openai.AuthenticationError: Error code: 401 - {'error': {'code': 'PermissionDenied', 'message': 'The principal 238d16af-467a-4c66-8f07-2048c59b6c43 lacks the required data action Microsoft.CognitiveServices/accounts/AIServices/agents/write to perform POST /api/projects/{projectName}/openai/* operation. For instructions on granting the necessary permissions, see https://aka.ms/FoundryPermissions.'}}
5/2/2026, 12:52:22 AM
Error
Executed 'Functions.Question_Tree_Processor_Azure' (Failed, Id=447a1a82-50cb-4f5e-b6cd-e1b352c3e018, Duration=939ms)
5/2/2026, 12:52:22 AM
Error
Result: Failure Type: Exception: AuthenticationError: Error code: 401 - {'error': {'code': 'PermissionDenied', 'message': 'The principal 238d16af-467a-4c66-8f07-2048c59b6c43 lacks the required data action Microsoft.CognitiveServices/accounts/AIServices/agents/write to perform POST /api/projects/{projectName}/openai/* operation. For instructions on granting the necessary permissions, see https://aka.ms/FoundryPermissions.'}} Stack: Traceback (most recent call last): File "/azure-functions-host/workers/python/3.11/LINUX/X64/azure_functions_worker/dispatcher.py", line 685, in _handle__invocation_request call_result = await self._loop.run_in_executor( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/concurrent/futures/thread.py", line 58, in run result = self.fn(*self.args, **self.kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/azure-functions-host/workers/python/3.11/LINUX/X64/azure_functions_worker/dispatcher.py", line 1019, in _run_sync_func return ExtensionManager.get_sync_invocation_wrapper(context, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/azure-functions-host/workers/python/3.11/LINUX/X64/azure_functions_worker/extension.py", line 211, in _raw_invocation_wrapper result = function(**args) ^^^^^^^^^^^^^^^^ File "/home/site/wwwroot/function_app.py", line 85, in Question_Tree_Processor_Azure qt.process_processing_blob(container, blob_name) File "/home/site/wwwroot/logic_question_tree_blob.py", line 16, in process_processing_blob raw = call_question_tree_agent(text) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/site/wwwroot/logic_question_tree.py", line 29, in call_question_tree_agent conversation = openai.conversations.create() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/site/wwwroot/.python_packages/lib/site-packages/openai/resources/conversations/conversations.py", line 94, in create return self._post( ^^^^^^^^^^^ File "/home/site/wwwroot/.python_packages/lib/site-packages/openai/_base_client.py", line 1314, in post return cast(ResponseT, self.request(cast_to, opts, stream=stream, stream_cls=stream_cls)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/site/wwwroot/.python_packages/lib/site-packages/openai/_base_client.py", line 1087, in request raise self._make_status_error_from_response(err.response) from None openai.AuthenticationError: Error code: 401 - {'error': {'code': 'PermissionDenied', 'message': 'The principal 238d16af-467a-4c66-8f07-2048c59b6c43 lacks the required data action Microsoft.CognitiveServices/accounts/AIServices/agents/write to perform POST /api/projects/{projectName}/openai/* operation. For instructions on granting the necessary permissions, see https://aka.ms/FoundryPermissions.'}}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions