Skip to content

Azure openai

AzureOpenAI #

Bases: OpenAI

Azure OpenAI.

要使用此功能,您必须首先在Azure OpenAI上部署一个模型。 与OpenAI不同,您需要指定一个 engine 参数来标识 您的部署(在Azure门户中称为“模型部署名称”)。

  • model: 模型的名称(例如 text-davinci-003) 这仅用于决定完成 vs. 聊天终端。
  • engine: 这将对应于您在部署模型时选择的自定义名称。

您必须设置以下环境变量: - OPENAI_API_VERSION:将其设置为 2023-07-01-preview 或更新版本。 这可能会在将来更改。 - AZURE_OPENAI_ENDPOINT:您的终结点应该类似于以下内容 https://YOUR_RESOURCE_NAME.openai.azure.com/ - AZURE_OPENAI_API_KEY:如果api类型为 azure,则为您的API密钥

可以在此处找到更多信息: https://learn.microsoft.com/en-us/azure/cognitive-services/openai/quickstart?tabs=command-line&pivots=programming-language-python

示例: pip install llama-index-llms-azure-openai

```python
from llama_index.llms.azure_openai import AzureOpenAI

aoai_api_key = "YOUR_AZURE_OPENAI_API_KEY"
aoai_endpoint = "YOUR_AZURE_OPENAI_ENDPOINT"
aoai_api_version = "2023-07-01-preview"

llm = AzureOpenAI(
    model="YOUR_AZURE_OPENAI_COMPLETION_MODEL_NAME",
    deployment_name="YOUR_AZURE_OPENAI_COMPLETION_DEPLOYMENT_NAME",
    api_key=aoai_api_key,
    azure_endpoint=aoai_endpoint,
    api_version=aoai_api_version,
)
```
Source code in llama_index/llms/azure_openai/base.py
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
class AzureOpenAI(OpenAI):
    """    Azure OpenAI.

    要使用此功能,您必须首先在Azure OpenAI上部署一个模型。
    与OpenAI不同,您需要指定一个 `engine` 参数来标识
    您的部署(在Azure门户中称为“模型部署名称”)。

    - model: 模型的名称(例如 `text-davinci-003`)
        这仅用于决定完成 vs. 聊天终端。
    - engine: 这将对应于您在部署模型时选择的自定义名称。

    您必须设置以下环境变量:
    - `OPENAI_API_VERSION`:将其设置为 `2023-07-01-preview` 或更新版本。
        这可能会在将来更改。
    - `AZURE_OPENAI_ENDPOINT`:您的终结点应该类似于以下内容
        https://YOUR_RESOURCE_NAME.openai.azure.com/
    - `AZURE_OPENAI_API_KEY`:如果api类型为 `azure`,则为您的API密钥

    可以在此处找到更多信息:
        https://learn.microsoft.com/en-us/azure/cognitive-services/openai/quickstart?tabs=command-line&pivots=programming-language-python

    示例:
        `pip install llama-index-llms-azure-openai`

        ```python
        from llama_index.llms.azure_openai import AzureOpenAI

        aoai_api_key = "YOUR_AZURE_OPENAI_API_KEY"
        aoai_endpoint = "YOUR_AZURE_OPENAI_ENDPOINT"
        aoai_api_version = "2023-07-01-preview"

        llm = AzureOpenAI(
            model="YOUR_AZURE_OPENAI_COMPLETION_MODEL_NAME",
            deployment_name="YOUR_AZURE_OPENAI_COMPLETION_DEPLOYMENT_NAME",
            api_key=aoai_api_key,
            azure_endpoint=aoai_endpoint,
            api_version=aoai_api_version,
        )
        ```"""

    engine: str = Field(description="The name of the deployed azure engine.")
    azure_endpoint: Optional[str] = Field(
        default=None, description="The Azure endpoint to use."
    )
    azure_deployment: Optional[str] = Field(
        default=None, description="The Azure deployment to use."
    )
    use_azure_ad: bool = Field(
        description="Indicates if Microsoft Entra ID (former Azure AD) is used for token authentication"
    )

    azure_ad_token_provider: AzureADTokenProvider = Field(
        default=None, description="Callback function to provide Azure AD token."
    )

    _azure_ad_token: Any = PrivateAttr(default=None)
    _client: SyncAzureOpenAI = PrivateAttr()
    _aclient: AsyncAzureOpenAI = PrivateAttr()

    def __init__(
        self,
        model: str = "gpt-35-turbo",
        engine: Optional[str] = None,
        temperature: float = 0.1,
        max_tokens: Optional[int] = None,
        additional_kwargs: Optional[Dict[str, Any]] = None,
        max_retries: int = 3,
        timeout: float = 60.0,
        reuse_client: bool = True,
        api_key: Optional[str] = None,
        api_version: Optional[str] = None,
        # azure specific
        azure_endpoint: Optional[str] = None,
        azure_deployment: Optional[str] = None,
        azure_ad_token_provider: Optional[AzureADTokenProvider] = None,
        use_azure_ad: bool = False,
        callback_manager: Optional[CallbackManager] = None,
        # aliases for engine
        deployment_name: Optional[str] = None,
        deployment_id: Optional[str] = None,
        deployment: Optional[str] = None,
        # custom httpx client
        http_client: Optional[httpx.Client] = None,
        async_http_client: Optional[httpx.AsyncClient] = None,
        # base class
        system_prompt: Optional[str] = None,
        messages_to_prompt: Optional[Callable[[Sequence[ChatMessage]], str]] = None,
        completion_to_prompt: Optional[Callable[[str], str]] = None,
        pydantic_program_mode: PydanticProgramMode = PydanticProgramMode.DEFAULT,
        output_parser: Optional[BaseOutputParser] = None,
        **kwargs: Any,
    ) -> None:
        engine = resolve_from_aliases(
            engine, deployment_name, deployment_id, deployment, azure_deployment
        )

        if engine is None:
            raise ValueError("You must specify an `engine` parameter.")

        azure_endpoint = get_from_param_or_env(
            "azure_endpoint", azure_endpoint, "AZURE_OPENAI_ENDPOINT", ""
        )

        super().__init__(
            engine=engine,
            model=model,
            temperature=temperature,
            max_tokens=max_tokens,
            additional_kwargs=additional_kwargs,
            max_retries=max_retries,
            timeout=timeout,
            reuse_client=reuse_client,
            api_key=api_key,
            azure_endpoint=azure_endpoint,
            azure_deployment=azure_deployment,
            azure_ad_token_provider=azure_ad_token_provider,
            use_azure_ad=use_azure_ad,
            api_version=api_version,
            callback_manager=callback_manager,
            http_client=http_client,
            async_http_client=async_http_client,
            system_prompt=system_prompt,
            messages_to_prompt=messages_to_prompt,
            completion_to_prompt=completion_to_prompt,
            pydantic_program_mode=pydantic_program_mode,
            output_parser=output_parser,
            **kwargs,
        )

    @root_validator(pre=True)
    def validate_env(cls, values: Dict[str, Any]) -> Dict[str, Any]:
        """验证必要的凭据是否已设置。"""
        if (
            values["api_base"] == "https://api.openai.com/v1"
            and values["azure_endpoint"] is None
        ):
            raise ValueError(
                "You must set OPENAI_API_BASE to your Azure endpoint. "
                "It should look like https://YOUR_RESOURCE_NAME.openai.azure.com/"
            )
        if values["api_version"] is None:
            raise ValueError("You must set OPENAI_API_VERSION for Azure OpenAI.")

        return values

    def _get_client(self) -> SyncAzureOpenAI:
        if not self.reuse_client:
            return SyncAzureOpenAI(**self._get_credential_kwargs())

        if self._client is None:
            self._client = SyncAzureOpenAI(
                **self._get_credential_kwargs(),
            )
        return self._client

    def _get_aclient(self) -> AsyncAzureOpenAI:
        if not self.reuse_client:
            return AsyncAzureOpenAI(**self._get_credential_kwargs())

        if self._aclient is None:
            self._aclient = AsyncAzureOpenAI(
                **self._get_credential_kwargs(),
            )
        return self._aclient

    def _get_credential_kwargs(
        self, is_async: bool = False, **kwargs: Any
    ) -> Dict[str, Any]:
        if self.use_azure_ad:
            self._azure_ad_token = refresh_openai_azuread_token(self._azure_ad_token)
            self.api_key = self._azure_ad_token.token
        else:
            import os

            self.api_key = self.api_key or os.getenv("AZURE_OPENAI_API_KEY")

        if self.api_key is None:
            raise ValueError(
                "You must set an `api_key` parameter. "
                "Alternatively, you can set the AZURE_OPENAI_API_KEY env var OR set `use_azure_ad=True`."
            )

        return {
            "api_key": self.api_key,
            "max_retries": self.max_retries,
            "timeout": self.timeout,
            "azure_endpoint": self.azure_endpoint,
            "azure_deployment": self.azure_deployment,
            "azure_ad_token_provider": self.azure_ad_token_provider,
            "api_version": self.api_version,
            "default_headers": self.default_headers,
            "http_client": self._async_http_client if is_async else self._http_client,
            **kwargs,
        }

    def _get_model_kwargs(self, **kwargs: Any) -> Dict[str, Any]:
        model_kwargs = super()._get_model_kwargs(**kwargs)
        model_kwargs["model"] = self.engine
        return model_kwargs

    @classmethod
    def class_name(cls) -> str:
        return "azure_openai_llm"

validate_env #

validate_env(values: Dict[str, Any]) -> Dict[str, Any]

验证必要的凭据是否已设置。

Source code in llama_index/llms/azure_openai/base.py
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
@root_validator(pre=True)
def validate_env(cls, values: Dict[str, Any]) -> Dict[str, Any]:
    """验证必要的凭据是否已设置。"""
    if (
        values["api_base"] == "https://api.openai.com/v1"
        and values["azure_endpoint"] is None
    ):
        raise ValueError(
            "You must set OPENAI_API_BASE to your Azure endpoint. "
            "It should look like https://YOUR_RESOURCE_NAME.openai.azure.com/"
        )
    if values["api_version"] is None:
        raise ValueError("You must set OPENAI_API_VERSION for Azure OpenAI.")

    return values