Skip to main content

Azure OpenAI

API Keys, Params

api_key, api_base, api_version 等可以直接传递给 litellm.completion - 参见此处或设置为 litellm.api_key 参数参见此处

import os
os.environ["AZURE_API_KEY"] = "" # "my-azure-api-key"
os.environ["AZURE_API_BASE"] = "" # "https://example-endpoint.openai.azure.com"
os.environ["AZURE_API_VERSION"] = "" # "2023-05-15"

# 可选
os.environ["AZURE_AD_TOKEN"] = ""
os.environ["AZURE_API_TYPE"] = ""

使用方法 - LiteLLM Python SDK

Open In Colab

完成 - 使用 .env 变量

from litellm import completion

## 设置 ENV 变量
os.environ["AZURE_API_KEY"] = ""
os.environ["AZURE_API_BASE"] = ""
os.environ["AZURE_API_VERSION"] = ""

# azure 调用
response = completion(
model = "azure/<your_deployment_name>",
messages = [{ "content": "Hello, how are you?","role": "user"}]
)

完成 - 使用 api_key, api_base, api_version

import litellm

# azure 调用
response = litellm.completion(
model = "azure/<your deployment name>", # model = azure/<your deployment name>
api_base = "", # azure api base
api_version = "", # azure api version
api_key = "", # azure api key
messages = [{"role": "user", "content": "good morning"}],
)

完成 - 使用 azure_ad_token, api_base, api_version

import litellm

# azure 调用
response = litellm.completion(
model = "azure/<your deployment name>", # model = azure/<your deployment name>
api_base = "", # azure api base
api_version = "", # azure api version
azure_ad_token="", # azure_ad_token
messages = [{"role": "user", "content": "good morning"}],
)

使用方法 - LiteLLM 代理服务器

以下是如何使用 LiteLLM 代理服务器调用 Azure OpenAI 模型

1. 将密钥保存到您的环境中

export AZURE_API_KEY=""

2. 启动代理

model_list:
- model_name: gpt-3.5-turbo
litellm_params:
model: azure/chatgpt-v-2
api_base: https://openai-gpt-4-test-v-1.openai.azure.com/
api_version: "2023-05-15"
api_key: os.environ/AZURE_API_KEY # `os.environ/` 前缀告诉 litellm 从环境中读取这个值。

3. 测试它

curl --location 'http://0.0.0.0:4000/chat/completions' \
--header 'Content-Type: application/json' \
--data ' {
"model": "gpt-3.5-turbo",
"messages": [
{
"role": "user",
"content": "what llm are you"
}
]
}
'

Azure OpenAI 聊天完成模型

tip

我们支持所有 Azure 模型,只需在发送 litellm 请求时将 model=azure/<your deployment name> 作为前缀设置

模型名称函数调用
o1-miniresponse = completion(model="azure/<your deployment name>", messages=messages)
o1-previewresponse = completion(model="azure/<your deployment name>", messages=messages)
gpt-4o-minicompletion('azure/<your deployment name>', messages)
gpt-4ocompletion('azure/<your deployment name>', messages)
gpt-4completion('azure/<your deployment name>', messages)
| gpt-4-0314            | `completion('azure/<your deployment name>', messages)`         | 
| gpt-4-0613 | `completion('azure/<your deployment name>', messages)` |
| gpt-4-32k | `completion('azure/<your deployment name>', messages)` |
| gpt-4-32k-0314 | `completion('azure/<your deployment name>', messages)` |
| gpt-4-32k-0613 | `completion('azure/<your deployment name>', messages)` |
| gpt-4-1106-preview | `completion('azure/<your deployment name>', messages)` |
| gpt-4-0125-preview | `completion('azure/<your deployment name>', messages)` |
| gpt-3.5-turbo | `completion('azure/<your deployment name>', messages)` |
| gpt-3.5-turbo-0301 | `completion('azure/<your deployment name>', messages)` |
| gpt-3.5-turbo-0613 | `completion('azure/<your deployment name>', messages)` |
| gpt-3.5-turbo-16k | `completion('azure/<your deployment name>', messages)` |
| gpt-3.5-turbo-16k-0613 | `completion('azure/<your deployment name>', messages)`

## Azure OpenAI Vision Models
| Model Name | Function Call |
|-----------------------|-----------------------------------------------------------------|
| gpt-4-vision | `completion(model="azure/<your deployment name>", messages=messages)` |
| gpt-4o | `completion('azure/<your deployment name>', messages)` |

#### Usage
```python
import os
from litellm import completion

os.environ["AZURE_API_KEY"] = "your-api-key"

# azure call
response = completion(
model = "azure/<your deployment name>",
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": "What’s in this image?"
},
{
"type": "image_url",
"image_url": {
"url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg"
}
}
]
}
],
)

Usage - with Azure Vision enhancements

Note: Azure requires the base_url to be set with /extensions

Example

base_url=https://gpt-4-vision-resource.openai.azure.com/openai/deployments/gpt-4-vision/extensions
# base_url="{azure_endpoint}/openai/deployments/{azure_deployment}/extensions"

Usage

import os 
from litellm import completion

os.environ["AZURE_API_KEY"] = "your-api-key"

# azure call
response = completion(
model="azure/gpt-4-vision",
timeout=5,
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "Whats in this image?"},
{
"type": "image_url",
"image_url": {
"url": "https://avatars.githubusercontent.com/u/29436595?v=4"
},
},
],
}
],
base_url="https://gpt-4-vision-resource.openai.azure.com/openai/deployments/gpt-4-vision/extensions",
api_key=os.getenv("AZURE_VISION_API_KEY"),
enhancements={"ocr": {"enabled": True}, "grounding": {"enabled": True}},
dataSources=[
{
"type": "AzureComputerVision",
"parameters": {
"endpoint": "https://gpt-4-vision-enhancement.cognitiveservices.azure.com/",
"key": os.environ["AZURE_VISION_ENHANCE_KEY"],
},
}
],
)

Azure O1 Models

Model NameFunction Call
o1-miniresponse = completion(model="azure/<your deployment name>", messages=messages)
o1-previewresponse = completion(model="azure/<your deployment name>", messages=messages)

Set litellm.enable_preview_features = True to use Azure O1 Models with streaming support.

import litellm

litellm.enable_preview_features = True # 👈 KEY CHANGE

response = litellm.completion(
model="azure/<your deployment name>",
messages=[{"role": "user", "content": "What is the weather like in Boston?"}],
stream=True
)

for chunk in response:
print(chunk)

Azure 指令模型

使用 model="azure_text/<your-deployment>"

模型名称函数调用
gpt-3.5-turbo-instructresponse = completion(model="azure_text/<your deployment name>", messages=messages)
gpt-3.5-turbo-instruct-0914response = completion(model="azure_text/<your deployment name>", messages=messages)
import litellm

## 设置环境变量
os.environ["AZURE_API_KEY"] = ""
os.environ["AZURE_API_BASE"] = ""
os.environ["AZURE_API_VERSION"] = ""

response = litellm.completion(
model="azure_text/<your-deployment-name",
messages=[{"role": "user", "content": "波士顿的天气怎么样?"}]
)

print(response)

Azure 文字转语音 (tts)

LiteLLM 代理

 - model_name: azure/tts-1
litellm_params:
model: azure/tts-1
api_base: "os.environ/AZURE_API_BASE_TTS"
api_key: "os.environ/AZURE_API_KEY_TTS"
api_version: "os.environ/AZURE_API_VERSION"

LiteLLM SDK

from litellm import completion

## 设置环境变量
os.environ["AZURE_API_KEY"] = ""
os.environ["AZURE_API_BASE"] = ""
os.environ["AZURE_API_VERSION"] = ""

# azure 调用
speech_file_path = Path(__file__).parent / "speech.mp3"
response = speech(
model="azure/<your-deployment-name",
voice="alloy",
input="敏捷的棕色狐狸跃过懒狗",
)
response.stream_to_file(speech_file_path)

认证

Entrata ID - 使用 azure_ad_token

这是一个如何使用 Azure Active Directory 令牌 - Microsoft Entra ID 进行 litellm.completion() 调用的演练

步骤 1 - 下载 Azure CLI 安装说明: https://learn.microsoft.com/en-us/cli/azure/install-azure-cli

brew update && brew install azure-cli

步骤 2 - 使用 az 登录

az login --output table

步骤 3 - 生成 azure ad 令牌

az account get-access-token --resource https://cognitiveservices.azure.com

在此步骤中,您应该看到生成了一个 accessToken

{
"accessToken": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6IjlHbW55RlBraGMzaE91UjIybXZTdmduTG83WSIsImtpZCI6IjlHbW55RlBraGMzaE91UjIybXZTdmduTG83WSJ9",
"expiresOn": "2023-11-14 15:50:46.000000",
"expires_on": 1700005846,
"subscription": "db38de1f-4bb3..",
"tenant": "bdfd79b3-8401-47..",
"tokenType": "Bearer"
}

步骤 4 - 使用 Azure AD 令牌进行 litellm.completion 调用

设置 azure_ad_token = 步骤 3 中的 accessToken 或设置 os.environ['AZURE_AD_TOKEN']

response = litellm.completion(
model = "azure/<your deployment name>", # model = azure/<your deployment name>
api_base = "", # azure api base
api_version = "", # azure api version
azure_ad_token="", # 步骤 3 中的 accessToken
messages = [{"role": "user", "content": "早上好"}],
)

Entrata ID - 使用 tenant_id, client_id, client_secret

以下是在您的 litellm 代理 config.yaml 中设置 tenant_id, client_id, client_secret 的示例

model_list:
- model_name: gpt-3.5-turbo
litellm_params:
model: azure/chatgpt-v-2
api_base: https://openai-gpt-4-test-v-1.openai.azure.com/
api_version: "2023-05-15"
tenant_id: os.environ/AZURE_TENANT_ID
client_id: os.environ/AZURE_CLIENT_ID
client_secret: os.environ/AZURE_CLIENT_SECRET

测试

curl --location 'http://0.0.0.0:4000/chat/completions' \
--header 'Content-Type: application/json' \
--data ' {
"model": "gpt-3.5-turbo",
"messages": [
{
"role": "user",
"content": "你是什么llm"
}
]
}
'

使用 tenant_id, client_id, client_secret 与 LiteLLM 代理服务器的示例视频

### Azure AD 令牌刷新 - `DefaultAzureCredential`

如果你想在请求中使用 Azure 的 DefaultAzureCredential 进行身份验证,请使用此功能。

from litellm import completion
from azure.identity import DefaultAzureCredential, get_bearer_token_provider

token_provider = get_bearer_token_provider(DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default")


response = completion(
model = "azure/<你的部署名称>", # model = azure/<你的部署名称>
api_base = "", # azure api base
api_version = "", # azure api version
azure_ad_token_provider=token_provider
messages = [{"role": "user", "content": "早上好"}],
)

高级功能

Azure API 负载均衡

如果你试图在多个 Azure/OpenAI 部署之间进行负载均衡,请使用此功能。

Router 通过选择未达到速率限制且使用令牌最少的部署,防止请求失败。

在生产环境中,Router 连接到 Redis 缓存,以跟踪多个部署的使用情况。

快速开始

pip install litellm
from litellm import Router

model_list = [{ # 模型部署列表
"model_name": "gpt-3.5-turbo", # openai 模型名称
"litellm_params": { # litellm 完成/嵌入调用的参数
"model": "azure/chatgpt-v-2",
"api_key": os.getenv("AZURE_API_KEY"),
"api_version": os.getenv("AZURE_API_VERSION"),
"api_base": os.getenv("AZURE_API_BASE")
},
"tpm": 240000,
"rpm": 1800
}, {
"model_name": "gpt-3.5-turbo", # openai 模型名称
"litellm_params": { # litellm 完成/嵌入调用的参数
"model": "azure/chatgpt-functioncalling",
"api_key": os.getenv("AZURE_API_KEY"),
"api_version": os.getenv("AZURE_API_VERSION"),
"api_base": os.getenv("AZURE_API_BASE")
},
"tpm": 240000,
"rpm": 1800
}, {
"model_name": "gpt-3.5-turbo", # openai 模型名称
"litellm_params": { # litellm 完成/嵌入调用的参数
"model": "gpt-3.5-turbo",
"api_key": os.getenv("OPENAI_API_KEY"),
},
"tpm": 1000000,
"rpm": 9000
}]

router = Router(model_list=model_list)

# 替换 openai.chat.completions.create
response = router.completion(model="gpt-3.5-turbo",
messages=[{"role": "user", "content": "嘿,最近怎么样?"}]

print(response)

Redis 队列

router = Router(model_list=model_list, 
redis_host=os.getenv("REDIS_HOST"),
redis_password=os.getenv("REDIS_PASSWORD"),
redis_port=os.getenv("REDIS_PORT"))

print(response)

并行函数调用

有关使用 litellm 进行并行函数调用的详细演练,请参见此处

# 设置Azure环境变量
import os
os.environ['AZURE_API_KEY'] = "" # litellm从.env中读取AZURE_API_KEY并发送请求
os.environ['AZURE_API_BASE'] = "https://openai-gpt-4-test-v-1.openai.azure.com/"
os.environ['AZURE_API_VERSION'] = "2023-07-01-preview"

import litellm
import json
# 示例硬编码的虚拟函数,始终返回相同的天气信息
# 在生产环境中,这可以是你的后端API或外部API
def get_current_weather(location, unit="fahrenheit"):
"""获取给定地点的当前天气"""
if "tokyo" in location.lower():
return json.dumps({"location": "Tokyo", "temperature": "10", "unit": "celsius"})
elif "san francisco" in location.lower():
return json.dumps({"location": "San Francisco", "temperature": "72", "unit": "fahrenheit"})
elif "paris" in location.lower():
return json.dumps({"location": "Paris", "temperature": "22", "unit": "celsius"})
else:
return json.dumps({"location": location, "temperature": "unknown"})

## 步骤1:将对话和可用函数发送给模型
messages = [{"role": "user", "content": "旧金山、东京和巴黎的天气怎么样?"}]
tools = [
{
"type": "function",
"function": {
"name": "get_current_weather",
"description": "获取给定地点的当前天气",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "城市和州,例如:San Francisco, CA",
},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
},
"required": ["location"],
},
},
}
]

response = litellm.completion(
model="azure/chatgpt-functioncalling", # model = azure/<你的Azure部署名称>
messages=messages,
tools=tools,
tool_choice="auto", # auto是默认值,但我们这里显式指定
)
print("\nLLM响应1:\n", response)
response_message = response.choices[0].message
tool_calls = response.choices[0].message.tool_calls
print("\n工具选择:\n", tool_calls)

定义

人工智能(Artificial Intelligence,简称AI)是指通过计算机系统来模拟人类智能过程的技术。这些过程包括学习、推理、问题解决、感知和语言理解等。

关键组成部分

  1. 机器学习:机器学习是AI的一个子领域,涉及使计算机能够从数据中学习,而无需进行明确编程。
  2. 深度学习:深度学习是机器学习的一种,使用多层神经网络来处理和分析复杂数据。
  3. 自然语言处理(NLP):NLP涉及使计算机能够理解、解释和生成人类语言。
  4. 计算机视觉:计算机视觉使机器能够解释和理解视觉信息,如图像和视频。

应用领域

  • 医疗保健:AI用于诊断、个性化治疗和药物发现。
  • 金融:AI用于欺诈检测、算法交易和客户服务。
  • 零售:AI用于个性化推荐、库存管理和无人商店。
  • 交通:AI用于自动驾驶汽车、交通管理和物流优化。

挑战

  1. 数据隐私:AI系统需要大量数据,这引发了关于数据隐私和安全的担忧。
  2. 伦理问题:AI决策的透明度和公平性是重要的伦理问题。
  3. 失业:自动化和AI可能导致某些行业的失业率增加。

未来展望

AI的进步有望带来革命性的变化,但也需要解决当前的挑战和限制。随着技术的不断发展,AI将在各个领域继续扩展其应用,改变我们的生活和工作方式。

优云智算