# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------

"""
DESCRIPTION:
    This sample demonstrates how to use function tools with the Azure AI Projects client
    using asynchronous operations. It shows the complete workflow of defining a function tool,
    handling function calls from the model, executing the function, and providing results
    back to get a final response.

USAGE:
    python sample_agent_responses_function_tool_async.py

    Before running the sample:

    pip install "azure-ai-projects>=2.0.0" python-dotenv aiohttp

    Set these environment variables with your own values:
    1) FOUNDRY_PROJECT_ENDPOINT - The Azure AI Project endpoint, as found in the Overview
       page of your Microsoft Foundry portal.
    2) FOUNDRY_MODEL_NAME - The deployment name of the AI model, as found under the "Name" column in
       the "Models + endpoints" tab in your Microsoft Foundry project.
"""

# pylint: disable=docstring-missing-param,docstring-missing-return,docstring-missing-rtype
import os
import json
import asyncio
from dotenv import load_dotenv
from openai.types.responses.response_input_param import FunctionCallOutput, ResponseInputParam
from azure.identity.aio import DefaultAzureCredential
from azure.ai.projects.aio import AIProjectClient
from azure.ai.projects.models import PromptAgentDefinition, FunctionTool

load_dotenv()

endpoint = os.environ["FOUNDRY_PROJECT_ENDPOINT"]


async def get_horoscope(sign: str) -> str:
    """Generate a horoscope for the given astrological sign."""
    return f"{sign}: Next Tuesday you will befriend a baby otter."


async def main():
    async with (
        DefaultAzureCredential() as credential,
        AIProjectClient(endpoint=endpoint, credential=credential) as project_client,
        project_client.get_openai_client() as openai_client,
    ):
        # Define a function tool for the model to use
        func_tool = FunctionTool(
            name="get_horoscope",
            parameters={
                "type": "object",
                "properties": {
                    "sign": {
                        "type": "string",
                        "description": "An astrological sign like Taurus or Aquarius",
                    },
                },
                "required": ["sign"],
                "additionalProperties": False,
            },
            description="Get today's horoscope for an astrological sign.",
            strict=True,
        )

        agent = await project_client.agents.create_version(
            agent_name="MyAgent",
            definition=PromptAgentDefinition(
                model=os.environ["FOUNDRY_MODEL_NAME"],
                instructions="You are a helpful assistant that can use function tools.",
                tools=[func_tool],
            ),
        )

        # Prompt the model with tools defined
        response = await openai_client.responses.create(
            input="What is my horoscope? I am an Aquarius.",
            extra_body={"agent_reference": {"name": agent.name, "type": "agent_reference"}},
        )
        print(f"Response output: {response.output_text}")

        input_list: ResponseInputParam = []
        # Process function calls
        for item in response.output:
            if item.type == "function_call":
                if item.name == "get_horoscope":
                    # Execute the function logic for get_horoscope
                    horoscope = await get_horoscope(**json.loads(item.arguments))

                    # Provide function call results to the model
                    input_list.append(
                        FunctionCallOutput(
                            type="function_call_output",
                            call_id=item.call_id,
                            output=json.dumps({"horoscope": horoscope}),
                        )
                    )

        print("Final input:")
        print(input_list)

        response = await openai_client.responses.create(
            input=input_list,
            previous_response_id=response.id,
            extra_body={"agent_reference": {"name": agent.name, "type": "agent_reference"}},
        )

        print(f"Agent response: {response.output_text}")


if __name__ == "__main__":
    asyncio.run(main())
