|
| 1 | +# azure_ai_utils.py |
| 2 | +import io |
| 3 | +import matplotlib.pyplot as plt |
| 4 | +from typing import Iterable |
| 5 | +from pathlib import Path |
| 6 | +from tenacity import retry, stop_after_attempt, wait_exponential, retry_if_exception_type |
| 7 | + |
| 8 | +# Import AzureOpenAI and assistant-related Message classes |
| 9 | +from openai import AzureOpenAI |
| 10 | +from openai.types.beta.threads.message_content_image_file import MessageContentImageFile |
| 11 | +from openai.types.beta.threads.message_content_text import MessageContentText |
| 12 | +from openai.types.beta.threads.messages import MessageFile |
| 13 | + |
| 14 | + |
| 15 | +class NotCompletedException(Exception): |
| 16 | + """Custom exception for handling incomplete run statuses.""" |
| 17 | + pass |
| 18 | + |
| 19 | + |
| 20 | +class AzureAIUtils: |
| 21 | + """ |
| 22 | + A utility class for various Azure AI operations including |
| 23 | + message formatting, file uploading, and lifecycle status checking. |
| 24 | + """ |
| 25 | + |
| 26 | + def __init__(self, client: AzureOpenAI): |
| 27 | + """ |
| 28 | + Initialize the utility class with an AzureOpenAI client. |
| 29 | +
|
| 30 | + Parameters: |
| 31 | + client (AzureOpenAI): An instance of the AzureOpenAI client. |
| 32 | + """ |
| 33 | + self.client = client |
| 34 | + |
| 35 | + def format_response(self, messages: Iterable[MessageFile]) -> None: |
| 36 | + """ |
| 37 | + Formats and prints the content of messages from AzureOpenAI. |
| 38 | +
|
| 39 | + Parameters: |
| 40 | + messages (Iterable[MessageFile]): An iterable of MessageFile objects. |
| 41 | + """ |
| 42 | + message_list = [] |
| 43 | + |
| 44 | + for message in messages: |
| 45 | + message_list.append(message) |
| 46 | + if message.role == "user": |
| 47 | + break |
| 48 | + |
| 49 | + message_list.reverse() |
| 50 | + |
| 51 | + for message in message_list: |
| 52 | + for item in message.content: |
| 53 | + if isinstance(item, MessageContentText): |
| 54 | + print(f"{message.role}:\n{item.text.value}\n") |
| 55 | + elif isinstance(item, MessageContentImageFile): |
| 56 | + try: |
| 57 | + response_content = self.client.files.content( |
| 58 | + item.image_file.file_id |
| 59 | + ) |
| 60 | + data_in_bytes = response_content.read() |
| 61 | + readable_buffer = io.BytesIO(data_in_bytes) |
| 62 | + image = plt.imread(readable_buffer, format="jpeg") |
| 63 | + plt.imshow(image) |
| 64 | + plt.axis("off") |
| 65 | + plt.show() |
| 66 | + except Exception as e: |
| 67 | + print(f"Exception: {e}") |
| 68 | + |
| 69 | + def upload_file(self, path: Path): |
| 70 | + """ |
| 71 | + Uploads a file to AzureOpenAI. |
| 72 | +
|
| 73 | + Parameters: |
| 74 | + path (Path): The path to the file to be uploaded. |
| 75 | +
|
| 76 | + Returns: |
| 77 | + FileObject: The file object created in AzureOpenAI. |
| 78 | + """ |
| 79 | + with path.open("rb") as f: |
| 80 | + return self.client.files.create(file=f, purpose="assistants") |
| 81 | + |
| 82 | + @retry( |
| 83 | + stop=stop_after_attempt(15), |
| 84 | + wait=wait_exponential(multiplier=1.5, min=4, max=20), |
| 85 | + retry=retry_if_exception_type(NotCompletedException), |
| 86 | + ) |
| 87 | + def get_run_lifecycle_status(self, thread_id, run_id): |
| 88 | + """ |
| 89 | + Retrieves and prints the lifecycle status of a run and |
| 90 | + retries based on specific conditions. |
| 91 | +
|
| 92 | + Parameters: |
| 93 | + thread_id: The ID of the thread. |
| 94 | + run_id: The ID of the run. |
| 95 | +
|
| 96 | + Returns: |
| 97 | + The run object if its status is 'completed', 'failed', 'expired', or 'cancelled'. |
| 98 | +
|
| 99 | + Raises: |
| 100 | + NotCompletedException: If the run is not yet completed. |
| 101 | + """ |
| 102 | + run = self.client.beta.threads.runs.retrieve(thread_id=thread_id, run_id=run_id) |
| 103 | + print(f"Run status: {run.status}") |
| 104 | + if run.status in ["completed", "failed", "expired", "cancelled"]: |
| 105 | + print(f"Run info: {run}") |
| 106 | + return run |
| 107 | + elif run.status == "requires_action": |
| 108 | + pass # Handle cases that require action differently |
| 109 | + else: |
| 110 | + raise NotCompletedException("Run not completed yet") |
0 commit comments