|
| 1 | +"""Azure OpenAI chat wrapper.""" |
| 2 | +from __future__ import annotations |
| 3 | + |
| 4 | +import logging |
| 5 | +from typing import Any, Dict, Mapping |
| 6 | + |
| 7 | +from pydantic import root_validator |
| 8 | + |
| 9 | +from real_agents.adapters.models.openai import ChatOpenAI |
| 10 | +from langchain.schema import ChatResult |
| 11 | +from langchain.utils import get_from_dict_or_env |
| 12 | + |
| 13 | +logger = logging.getLogger(__name__) |
| 14 | + |
| 15 | + |
| 16 | +class AzureChatOpenAI(ChatOpenAI): |
| 17 | + """Wrapper around Azure OpenAI Chat Completion API. To use this class you |
| 18 | + must have a deployed model on Azure OpenAI. Use `deployment_name` in the |
| 19 | + constructor to refer to the "Model deployment name" in the Azure portal. |
| 20 | +
|
| 21 | + In addition, you should have the ``openai`` python package installed, and the |
| 22 | + following environment variables set or passed in constructor in lower case: |
| 23 | + - ``OPENAI_API_TYPE`` (default: ``azure``) |
| 24 | + - ``OPENAI_API_KEY`` |
| 25 | + - ``OPENAI_API_BASE`` |
| 26 | + - ``OPENAI_API_VERSION`` |
| 27 | +
|
| 28 | + For exmaple, if you have `gpt-35-turbo` deployed, with the deployment name |
| 29 | + `35-turbo-dev`, the constructor should look like: |
| 30 | +
|
| 31 | + .. code-block:: python |
| 32 | + AzureChatOpenAI( |
| 33 | + deployment_name="35-turbo-dev", |
| 34 | + openai_api_version="2023-03-15-preview", |
| 35 | + ) |
| 36 | +
|
| 37 | + Be aware the API version may change. |
| 38 | +
|
| 39 | + Any parameters that are valid to be passed to the openai.create call can be passed |
| 40 | + in, even if not explicitly saved on this class. |
| 41 | + """ |
| 42 | + |
| 43 | + deployment_name: str = "" |
| 44 | + openai_api_type: str = "azure" |
| 45 | + openai_api_base: str = "" |
| 46 | + openai_api_version: str = "" |
| 47 | + openai_api_key: str = "" |
| 48 | + openai_organization: str = "" |
| 49 | + |
| 50 | + @root_validator() |
| 51 | + def validate_environment(cls, values: Dict) -> Dict: |
| 52 | + """Validate that api key and python package exists in environment.""" |
| 53 | + openai_api_key = get_from_dict_or_env( |
| 54 | + values, |
| 55 | + "openai_api_key", |
| 56 | + "OPENAI_API_KEY", |
| 57 | + ) |
| 58 | + openai_api_base = get_from_dict_or_env( |
| 59 | + values, |
| 60 | + "openai_api_base", |
| 61 | + "OPENAI_API_BASE", |
| 62 | + ) |
| 63 | + openai_api_version = get_from_dict_or_env( |
| 64 | + values, |
| 65 | + "openai_api_version", |
| 66 | + "OPENAI_API_VERSION", |
| 67 | + ) |
| 68 | + openai_api_type = get_from_dict_or_env( |
| 69 | + values, |
| 70 | + "openai_api_type", |
| 71 | + "OPENAI_API_TYPE", |
| 72 | + ) |
| 73 | + openai_organization = get_from_dict_or_env( |
| 74 | + values, |
| 75 | + "openai_organization", |
| 76 | + "OPENAI_ORGANIZATION", |
| 77 | + default="", |
| 78 | + ) |
| 79 | + try: |
| 80 | + import openai |
| 81 | + |
| 82 | + openai.api_type = openai_api_type |
| 83 | + openai.api_base = openai_api_base |
| 84 | + openai.api_version = openai_api_version |
| 85 | + openai.api_key = openai_api_key |
| 86 | + if openai_organization: |
| 87 | + openai.organization = openai_organization |
| 88 | + except ImportError: |
| 89 | + raise ValueError( |
| 90 | + "Could not import openai python package. " |
| 91 | + "Please install it with `pip install openai`." |
| 92 | + ) |
| 93 | + try: |
| 94 | + values["client"] = openai.ChatCompletion |
| 95 | + except AttributeError: |
| 96 | + raise ValueError( |
| 97 | + "`openai` has no `ChatCompletion` attribute, this is likely " |
| 98 | + "due to an old version of the openai package. Try upgrading it " |
| 99 | + "with `pip install --upgrade openai`." |
| 100 | + ) |
| 101 | + if values["n"] < 1: |
| 102 | + raise ValueError("n must be at least 1.") |
| 103 | + if values["n"] > 1 and values["streaming"]: |
| 104 | + raise ValueError("n must be 1 when streaming.") |
| 105 | + return values |
| 106 | + |
| 107 | + @property |
| 108 | + def _default_params(self) -> Dict[str, Any]: |
| 109 | + """Get the default parameters for calling OpenAI API.""" |
| 110 | + return { |
| 111 | + **super()._default_params, |
| 112 | + "engine": self.deployment_name, |
| 113 | + } |
| 114 | + |
| 115 | + @property |
| 116 | + def _identifying_params(self) -> Mapping[str, Any]: |
| 117 | + """Get the identifying parameters.""" |
| 118 | + return {**self._default_params} |
| 119 | + |
| 120 | + @property |
| 121 | + def _llm_type(self) -> str: |
| 122 | + return "azure-openai-chat" |
| 123 | + |
| 124 | + def _create_chat_result(self, response: Mapping[str, Any]) -> ChatResult: |
| 125 | + for res in response["choices"]: |
| 126 | + if res.get("finish_reason", None) == "content_filter": |
| 127 | + raise ValueError( |
| 128 | + "Azure has not provided the response due to a content" |
| 129 | + " filter being triggered" |
| 130 | + ) |
| 131 | + return super()._create_chat_result(response) |
0 commit comments