Warning
Azure OpenAI for Azure Functions 擴充功能將於 2027 年 4 月 20 日退休。 預覽擴充包 4.60.0 及以後版本不包含這個擴充功能。
根據你的情況,直接遷移到 OpenAI、Microsoft Foundry 或 Azure AI 搜尋服務 SDK。 現有應用程式可透過將版本範圍[4.*, 4.60.0)host.json設為 ,使用預覽擴充包 4.60.0 之前的版本。 .NET 應用程式可以直接使用對應的 Azure OpenAI 擴充套件 NuGet 套件。 無論是固定舊的套件還是繼續使用 NuGet 套件,都不會延長支援超過 2027 年 4 月 20 日。
Azure OpenAI 小幫手會建立輸出繫結,讓您從函式程式碼執行建立新的助理聊天機器人。
如需 Azure OpenAI 延伸模組的安裝和設定詳細資料,請參閱適用於 Azure Functions 的 Azure OpenAI 延伸模組。 若要深入了解 Azure OpenAI 助理,請參閱 Azure OpenAI 助理 API。
注意
參考和範例僅適用於 Node.js v4 模型。
注意
參考和範例僅適用於 Python v2 模型。
注意
雖然支援這兩個 C# 進程模型,但只會 提供隔離的背景工作模型 範例。
範例
目前這款綁定沒有 Go 支援。
此範例示範了建立程序,其中 HTTP PUT 函式會以指定識別碼建立新的助理聊天機器人。 提示的回應會在 HTTP 回應中會傳回。
/// <summary>
/// HTTP PUT function that creates a new assistant chat bot with the specified ID.
/// </summary>
[Function(nameof(CreateAssistant))]
public static async Task<CreateChatBotOutput> CreateAssistant(
[HttpTrigger(AuthorizationLevel.Function, "put", Route = "assistants/{assistantId}")] HttpRequestData req,
string assistantId)
{
string instructions =
"""
Don't make assumptions about what values to plug into functions.
Ask for clarification if a user request is ambiguous.
""";
using StreamReader reader = new(req.Body);
string request = await reader.ReadToEndAsync();
return new CreateChatBotOutput
{
HttpResponse = new ObjectResult(new { assistantId }) { StatusCode = 201 },
ChatBotCreateRequest = new AssistantCreateRequest(assistantId, instructions)
{
ChatStorageConnectionSetting = DefaultChatStorageConnectionSetting,
CollectionName = DefaultCollectionName,
},
};
}
public class CreateChatBotOutput
{
[AssistantCreateOutput()]
public AssistantCreateRequest? ChatBotCreateRequest { get; set; }
[HttpResult]
public IActionResult? HttpResponse { get; set; }
}
此範例示範了建立程序,其中 HTTP PUT 函式會以指定識別碼建立新的助理聊天機器人。 提示的回應會在 HTTP 回應中會傳回。
/**
* The default storage account setting for the table storage account.
* This constant is used to specify the connection string for the table storage
* account
* where chat data will be stored.
*/
final String DEFAULT_CHATSTORAGE = "AzureWebJobsStorage";
/**
* The default collection name for the table storage account.
* This constant is used to specify the collection name for the table storage
* account
* where chat data will be stored.
*/
final String DEFAULT_COLLECTION = "ChatState";
/*
* HTTP PUT function that creates a new assistant chat bot with the specified ID.
*/
@FunctionName("CreateAssistant")
public HttpResponseMessage createAssistant(
@HttpTrigger(
name = "req",
methods = {HttpMethod.PUT},
authLevel = AuthorizationLevel.FUNCTION,
route = "assistants/{assistantId}")
HttpRequestMessage<Optional<String>> request,
@BindingName("assistantId") String assistantId,
@AssistantCreate(name = "AssistantCreate") OutputBinding<AssistantCreateRequest> message,
final ExecutionContext context) {
context.getLogger().info("Java HTTP trigger processed a request.");
String instructions = "Don't make assumptions about what values to plug into functions.\n" +
"Ask for clarification if a user request is ambiguous.";
AssistantCreateRequest assistantCreateRequest = new AssistantCreateRequest(assistantId, instructions);
assistantCreateRequest.setChatStorageConnectionSetting(DEFAULT_CHATSTORAGE);
assistantCreateRequest.setCollectionName(DEFAULT_COLLECTION);
message.setValue(assistantCreateRequest);
JSONObject response = new JSONObject();
response.put("assistantId", assistantId);
return request.createResponseBuilder(HttpStatus.CREATED)
.header("Content-Type", "application/json")
.body(response.toString())
.build();
}
此範例示範了建立程序,其中 HTTP PUT 函式會以指定識別碼建立新的助理聊天機器人。 提示的回應會在 HTTP 回應中會傳回。
const { app, input, output } = require("@azure/functions");
const CHAT_STORAGE_CONNECTION_SETTING = "AzureWebJobsStorage";
const COLLECTION_NAME = "ChatState";
const chatBotCreateOutput = output.generic({
type: 'assistantCreate'
})
app.http('CreateAssistant', {
methods: ['PUT'],
route: 'assistants/{assistantId}',
authLevel: 'function',
extraOutputs: [chatBotCreateOutput],
handler: async (request, context) => {
const assistantId = request.params.assistantId
const instructions =
`
Don't make assumptions about what values to plug into functions.
Ask for clarification if a user request is ambiguous.
`
const createRequest = {
id: assistantId,
instructions: instructions,
chatStorageConnectionSetting: CHAT_STORAGE_CONNECTION_SETTING,
collectionName: COLLECTION_NAME
}
context.extraOutputs.set(chatBotCreateOutput, createRequest)
return { status: 202, jsonBody: { assistantId: assistantId } }
}
})
import { HttpRequest, InvocationContext, app, input, output } from "@azure/functions"
const CHAT_STORAGE_CONNECTION_SETTING = "AzureWebJobsStorage";
const COLLECTION_NAME = "ChatState";
const chatBotCreateOutput = output.generic({
type: 'assistantCreate'
})
app.http('CreateAssistant', {
methods: ['PUT'],
route: 'assistants/{assistantId}',
authLevel: 'function',
extraOutputs: [chatBotCreateOutput],
handler: async (request: HttpRequest, context: InvocationContext) => {
const assistantId = request.params.assistantId
const instructions =
`
Don't make assumptions about what values to plug into functions.
Ask for clarification if a user request is ambiguous.
`
const createRequest = {
id: assistantId,
instructions: instructions,
chatStorageConnectionSetting: CHAT_STORAGE_CONNECTION_SETTING,
collectionName: COLLECTION_NAME
}
context.extraOutputs.set(chatBotCreateOutput, createRequest)
return { status: 202, jsonBody: { assistantId: assistantId } }
}
})
此範例示範了建立程序,其中 HTTP PUT 函式會以指定識別碼建立新的助理聊天機器人。 提示的回應會在 HTTP 回應中會傳回。
以下是 建立小幫手的function.json 檔案:
{
"bindings": [
{
"authLevel": "function",
"type": "httpTrigger",
"direction": "in",
"name": "Request",
"route": "assistants/{assistantId}",
"methods": [
"put"
]
},
{
"type": "http",
"direction": "out",
"name": "Response"
},
{
"type": "assistantCreate",
"direction": "out",
"dataType": "string",
"name": "Requests"
}
]
}
如需 function.json 檔案屬性的詳細資訊,請參閱設定一節。
{{這來自範例程序代碼批注}}
using namespace System.Net
param($Request, $TriggerMetadata)
$assistantId = $Request.params.assistantId
$instructions = "Don't make assumptions about what values to plug into functions."
$instructions += "\nAsk for clarification if a user request is ambiguous."
$create_request = @{
"id" = $assistantId
"instructions" = $instructions
"chatStorageConnectionSetting" = "AzureWebJobsStorage"
"collectionName" = "ChatState"
}
Push-OutputBinding -Name Requests -Value (ConvertTo-Json $create_request)
Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
StatusCode = [HttpStatusCode]::Accepted
Body = (ConvertTo-Json @{ "assistantId" = $assistantId})
Headers = @{
"Content-Type" = "application/json"
}
})
此範例示範了建立程序,其中 HTTP PUT 函式會以指定識別碼建立新的助理聊天機器人。 提示的回應會在 HTTP 回應中會傳回。
DEFAULT_CHAT_STORAGE_SETTING = "AzureWebJobsStorage"
DEFAULT_CHAT_COLLECTION_NAME = "ChatState"
@apis.function_name("CreateAssistant")
@apis.route(route="assistants/{assistantId}", methods=["PUT"])
@apis.assistant_create_output(arg_name="requests")
def create_assistant(
req: func.HttpRequest, requests: func.Out[str]
) -> func.HttpResponse:
assistantId = req.route_params.get("assistantId")
instructions = """
Don't make assumptions about what values to plug into functions.
Ask for clarification if a user request is ambiguous.
"""
create_request = {
"id": assistantId,
"instructions": instructions,
"chatStorageConnectionSetting": DEFAULT_CHAT_STORAGE_SETTING,
"collectionName": DEFAULT_CHAT_COLLECTION_NAME,
}
requests.set(json.dumps(create_request))
response_json = {"assistantId": assistantId}
return func.HttpResponse(
json.dumps(response_json), status_code=202, mimetype="application/json"
)
屬性
套用 CreateAssistant 屬性來定義助理建立輸出繫結,其支援下列參數:
| 參數 | 描述 |
|---|---|
| 標識碼 | 要建立之助理的識別碼。 |
| 指示 | 選擇性。 提供給助理的遵循指示。 |
| ChatStorageConnectionSetting |
選擇性。 聊天記憶體數據表設定的組態區段名稱。 預設值是 AzureWebJobsStorage。 |
| CollectionName |
選擇性。 聊天記憶體的數據表集合名稱。 預設值是 ChatState。 |
註釋
CreateAssistant 註釋可讓您定義助理建立輸出繫結,其支援下列參數:
| 元素 | 描述 |
|---|---|
| 名字 | 取得或設定輸出繫結的名稱。 |
| 識別碼 | 要建立之助理的識別碼。 |
| 指示 | 選擇性。 提供給助理的遵循指示。 |
| chatStorageConnectionSetting |
選擇性。 聊天記憶體數據表設定的組態區段名稱。 預設值是 AzureWebJobsStorage。 |
| collectionName |
選擇性。 聊天記憶體的數據表集合名稱。 預設值是 ChatState。 |
裝飾項目
在預覽期間,將輸出繫結定義為 generic_output_binding 類型的 createAssistant 繫結,其支援下列參數:
| 參數 | 描述 |
|---|---|
| arg_name | 代表繫結參數的變數名稱。 |
| 識別碼 | 要建立之助理的識別碼。 |
| 指示 | 選擇性。 提供給助理的遵循指示。 |
| chat_storage_connection_setting |
選擇性。 聊天記憶體數據表設定的組態區段名稱。 預設值是 AzureWebJobsStorage。 |
| collection_name |
選擇性。 聊天記憶體的數據表集合名稱。 預設值是 ChatState。 |
組態
繫結支援您在 function.json 檔案中設定的下列組態屬性。
| 屬性 | 描述 |
|---|---|
| 類型 | 必須是 CreateAssistant。 |
| 方向 | 必須是 out。 |
| 名字 | 輸出繫結的名稱。 |
| 識別碼 | 要建立之助理的識別碼。 |
| 指示 | 選擇性。 提供給助理的遵循指示。 |
| chatStorageConnectionSetting |
選擇性。 聊天記憶體數據表設定的組態區段名稱。 預設值是 AzureWebJobsStorage。 |
| collectionName |
選擇性。 聊天記憶體的數據表集合名稱。 預設值是 ChatState。 |
組態
繫結支援您在程式碼中定義的下列屬性:
| 屬性 | 描述 |
|---|---|
| 識別碼 | 要建立之助理的識別碼。 |
| 指示 | 選擇性。 提供給助理的遵循指示。 |
| chatStorageConnectionSetting |
選擇性。 聊天記憶體數據表設定的組態區段名稱。 預設值是 AzureWebJobsStorage。 |
| collectionName |
選擇性。 聊天記憶體的數據表集合名稱。 預設值是 ChatState。 |
使用方式
如需完整範例,請參閱範例一節。
連結
此連線指引適用於使用Azure OpenAI擴充功能的現有應用程式,該擴充功能將於2027年4月20日退役。 遷移到 Direct SDK 呼叫時,請依照你選擇的 SDK 的認證與連線指引,而非使用擴充套件的綁定設定。
要使用 Azure OpenAI 綁定擴充功能,你需要指定一個連接到 OpenAI 模型定義的連結。 請使用以下其中一種方法在綁定中設定 OpenAI 模型連線:
- 使用
AIConnectionNamebinding 屬性(Azure OpenAI 偏好)。 - 在應用程式內設定並設定
AZURE_OPENAI_ENDPOINTAZURE_OPENAI_KEY(針對 Azure OpenAI)。 - 只
Open_API_Key在應用程式設定中設定(針對https://api.openai.com)。
連線的設定方式取決於模型 API 與認證方法,如下表所示:
| 認證/模型 API | Azure OpenAI | OpenAI (https://api.openai.com) |
|---|---|---|
| 管理身份連線 | AIConnectionName |
不支援 |
| 金鑰保存庫 參考 | AZURE_OPENAI_ENDPOINTAZURE_OPENAI_KEY |
Open_API_Key |
| 應用程式配置參考 | AZURE_OPENAI_ENDPOINTAZURE_OPENAI_KEY |
Open_API_Key |
| 共用密碼 | AZURE_OPENAI_ENDPOINTAZURE_OPENAI_KEY |
Open_API_Key |
使用基於管理身份的連線和屬性 AIConnectionName 。
當你使用 AIConnectionName時,這個屬性設定的值會依連接類型而異:
-
管理身份連線:此
AIConnectionName屬性由<CONNECTION_NAME_PREFIX>一組設定共享,這些設定共同定義了與 Azure OpenAI 的身份基礎連線。 欲了解更多資訊,請參閱定義身份連結。 -
金鑰保存庫 參考:
AIConnectionName屬性設定回傳一個 Azure Key Vault 參考,指向 API 金鑰集中維護的位置。 欲了解更多資訊,請參閱定義 金鑰保存庫 連接。 -
App Configuration 參考:
AIConnectionName屬性設定會回傳一個 Azure 應用程式組態 參考,該參考會回傳 API 金鑰或 金鑰保存庫 參考。 欲了解更多資訊,請參閱連接條目中的 Azure 應用程式組態。 -
API 金鑰:
AIConnectionName屬性設定會解析成包含端點與金鑰的應用程式設定。 由於共享金鑰可能被入侵,請盡可能使用受管理身份連線。 欲了解更多資訊,請參閱定義連結。
想了解更多關於綁定連接的資訊,請參閱 Azure Functions 中的 Manage connections 。
OpenAI 綁定包含一個AIConnectionName屬性,你可以用來指定定義與 Azure OpenAI 連結的應用程式設定群組:<ConnectionNamePrefix>
當你將屬性設定 AIConnectionName 為 myAzureOpenAI:
myAzureOpenAI__endpoint=https://contoso.openai.azure.com/myAzureOpenAI__credential=managedidentitymyAzureOpenAI__clientId=aaaaaaaa-bbbb-cccc-1111-222222222222
執行時,主機將這些設定解讀為單一 myAzureOpenAI 設定:
"myAzureOpenAI":
{
"endpoint": "https://contoso.openai.azure.com/",
"credential": "managedidentity",
"clientId": "00001111-aaaa-2222-bbbb-3333cccc4444"
}
使用受管理身份時,務必將你的身份加入認知 服務 OpenAI 使用者 角色。
本地執行時,請將這些設定加入 local.settings.json 專案檔案。 如需詳細資訊,請參閱 使用身分識別型連線進行本機開發。
如需詳細資訊,請參閱使用應用程式設定。