# ------------------------------------
# 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.0b1" azure-identity openai python-dotenv aiohttp

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

import os
import json
import asyncio
from dotenv import load_dotenv
from azure.ai.projects.aio import AIProjectClient
from azure.ai.projects.models import PromptAgentDefinition, Tool, FunctionTool
from azure.identity.aio import DefaultAzureCredential
from openai.types.responses.response_input_param import FunctionCallOutput, ResponseInputParam

load_dotenv()

# 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,
)

tools: list[Tool] = [func_tool]


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():
    credential = DefaultAzureCredential()

    async with credential:

        project_client = AIProjectClient(
            endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
            credential=credential,
        )

        async with project_client:

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

            openai_client = await project_client.get_openai_client()

            async with openai_client:

                # Prompt the model with tools defined
                response = await openai_client.responses.create(
                    input="What is my horoscope? I am an Aquarius.",
                    extra_body={"agent": {"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": {"name": agent.name, "type": "agent_reference"}},
                )

                # The model should be able to give a response!
                print("Final output:")
                print("\n" + response.output_text)


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