|
| 1 | +# pylint: disable=too-many-lines,line-too-long,useless-suppression |
| 2 | +# ------------------------------------ |
| 3 | +# Copyright (c) Microsoft Corporation. |
| 4 | +# Licensed under the MIT License. |
| 5 | +# ------------------------------------ |
| 6 | +# cSpell:disable |
| 7 | + |
| 8 | +import os |
| 9 | +import base64 |
| 10 | +import pytest |
| 11 | +from test_base import TestBase, servicePreparer |
| 12 | +from devtools_testutils.aio import recorded_by_proxy_async |
| 13 | +from devtools_testutils import RecordedTransport |
| 14 | +from azure.ai.projects.models import PromptAgentDefinition, ImageGenTool |
| 15 | +from azure.core.exceptions import ResourceNotFoundError |
| 16 | + |
| 17 | + |
| 18 | +class TestAgentImageGenerationAsync(TestBase): |
| 19 | + |
| 20 | + @servicePreparer() |
| 21 | + @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) |
| 22 | + async def test_agent_image_generation_async(self, **kwargs): |
| 23 | + |
| 24 | + model = self.test_agents_params["model_deployment_name"] |
| 25 | + image_model = self.test_agents_tools_params["image_generation_model_deployment_name"] |
| 26 | + agent_name = "image-gen-agent" |
| 27 | + |
| 28 | + async with ( |
| 29 | + self.create_async_client(operation_group="agents", **kwargs) as project_client, |
| 30 | + project_client.get_openai_client() as openai_client, |
| 31 | + ): |
| 32 | + # Check if the image model deployment exists in the project |
| 33 | + try: |
| 34 | + deployment = await project_client.deployments.get(image_model) |
| 35 | + print(f"Image model deployment found: {deployment.name}") |
| 36 | + except ResourceNotFoundError: |
| 37 | + pytest.fail(f"Image generation model '{image_model}' not available in this project") |
| 38 | + except Exception as e: |
| 39 | + pytest.fail(f"Unable to verify image model deployment: {e}") |
| 40 | + |
| 41 | + # Disable retries for faster failure when service returns 500 |
| 42 | + openai_client.max_retries = 0 |
| 43 | + |
| 44 | + # Create agent with image generation tool |
| 45 | + agent = await project_client.agents.create_version( |
| 46 | + agent_name=agent_name, |
| 47 | + definition=PromptAgentDefinition( |
| 48 | + model=model, |
| 49 | + instructions="Generate images based on user prompts", |
| 50 | + tools=[ImageGenTool(model=image_model, quality="low", size="1024x1024")], # type: ignore |
| 51 | + ), |
| 52 | + description="Agent for testing image generation.", |
| 53 | + ) |
| 54 | + print(f"Agent created (id: {agent.id}, name: {agent.name}, version: {agent.version})") |
| 55 | + self._validate_agent_version(agent, expected_name=agent_name) |
| 56 | + |
| 57 | + # Request image generation |
| 58 | + print("\nAsking agent to generate an image of a simple geometric shape...") |
| 59 | + |
| 60 | + response = await openai_client.responses.create( |
| 61 | + input="Generate an image of a blue circle on a white background.", |
| 62 | + extra_headers={"x-ms-oai-image-generation-deployment": image_model}, # Required for image generation |
| 63 | + extra_body={"agent": {"name": agent.name, "type": "agent_reference"}}, |
| 64 | + ) |
| 65 | + |
| 66 | + print(f"Response created (id: {response.id})") |
| 67 | + assert response.id |
| 68 | + assert response.output is not None |
| 69 | + assert len(response.output) > 0 |
| 70 | + |
| 71 | + # Extract image data from response |
| 72 | + image_data = [output.result for output in response.output if output.type == "image_generation_call"] |
| 73 | + |
| 74 | + # Verify image was generated |
| 75 | + assert len(image_data) > 0, "Expected at least one image to be generated" |
| 76 | + assert image_data[0], "Expected image data to be non-empty" |
| 77 | + |
| 78 | + print(f"✓ Image data received ({len(image_data[0])} base64 characters)") |
| 79 | + |
| 80 | + # Decode the base64 image |
| 81 | + image_bytes = b"" |
| 82 | + try: |
| 83 | + image_bytes = base64.b64decode(image_data[0]) |
| 84 | + assert len(image_bytes) > 0, "Decoded image should have content" |
| 85 | + print(f"✓ Image decoded successfully ({len(image_bytes)} bytes)") |
| 86 | + except Exception as e: |
| 87 | + pytest.fail(f"Failed to decode base64 image data: {e}") |
| 88 | + |
| 89 | + # Verify it's a PNG image (check magic bytes) |
| 90 | + # PNG files start with: 89 50 4E 47 (‰PNG) |
| 91 | + assert image_bytes[:4] == b"\x89PNG", "Image does not appear to be a valid PNG" |
| 92 | + print("✓ Image is a valid PNG") |
| 93 | + |
| 94 | + # Verify reasonable image size (should be > 1KB for a 1024x1024 image) |
| 95 | + assert len(image_bytes) > 1024, f"Image seems too small ({len(image_bytes)} bytes)" |
| 96 | + print(f"✓ Image size is reasonable ({len(image_bytes):,} bytes)") |
| 97 | + |
| 98 | + print("\n✓ Agent successfully generated and returned a valid image") |
| 99 | + |
| 100 | + # Save the image to a file in the .assets directory (which is .gitignored) |
| 101 | + os.makedirs(".assets", exist_ok=True) |
| 102 | + with open(".assets/generated_image_async.png", "wb") as f: |
| 103 | + f.write(image_bytes) |
| 104 | + print("✓ Image saved to .assets/generated_image_async.png") |
| 105 | + |
| 106 | + # Teardown |
| 107 | + await project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) |
| 108 | + print("Agent deleted") |
0 commit comments