Using Azure OpenAI with Semantic Kernel
Building an AI agent with Semantic Kernel that uses Azure OpenAI can be done following this guide. When using Azure OpenAI authentication can use either API keys or EntraID (OAuth) shown in the initialization step below.
Install the package
npm install --save semantic-kernel @semantic-kernel/azure-openai
Initialize the Kernel
Using EntraID based authentication. Use az login to set the context used for login.
import { AzureOpenAIChatCompletionService } from '@semantic-kernel/azure-openai';
import { FunctionChoiceBehavior, kernel, kernelFunction } from "semantic-kernel";
const sk = kernel().addService(
new AzureOpenAIChatCompletionService({
deploymentName: '<OpenAI model name>',
endpoint: '<Azure OpenAI endpoint>',
apiVersion: '<OpenAPI version>'
})
);
Using API key based authentication.
import { AzureOpenAIChatCompletionService } from '@semantic-kernel/azure-openai';
import { FunctionChoiceBehavior, kernel, kernelFunction } from "semantic-kernel";
const sk = kernel().addService(
new AzureOpenAIChatCompletionService({
apiKey: '<your API key>',
deploymentName: '<OpenAI model name>',
endpoint: '<Azure OpenAI endpoint>',
apiVersion: '<OpenAPI version>'
})
);
Add your plugins
const temperature = kernelFunction(({ loc }) => (loc === 'Dublin' ? 10 : 24), {
name: 'temperature',
description: 'Returns the temperature for the given location',
schema: {
type: 'object',
properties: {
loc: { type: 'string', description: 'The location to return the temperature for' },
},
},
});
sk.addPlugin({
name: 'weather',
description: 'Weather plugin',
functions: [temperature],
});
Invoke prompt
function test() {
sk.invokePrompt({
promptTemplate: 'Return the current temperature in Dublin',
executionSettings: {
functionChoiceBehavior: FunctionChoiceBehavior.Auto(),
},
}).then((result) => {
console.log(result?.value);
});
}
test();
Here is the full example:
import { AzureOpenAIChatCompletionService } from '@semantic-kernel/azure-openai';
import { FunctionChoiceBehavior, kernel, kernelFunction } from "semantic-kernel";
const sk = kernel().addService(
new AzureOpenAIChatCompletionService({
deploymentName: '<OpenAI model name>',
endpoint: '<Azure OpenAI endpoint>',
apiVersion: '<OpenAPI version>'
})
);
const temperature = kernelFunction(({ loc }) => (loc === 'Dublin' ? 10 : 24), {
name: 'temperature',
description: 'Returns the temperature in a given location',
schema: {
type: 'object',
properties: {
loc: { type: 'string', description: 'The location to get the temperature for' },
},
},
});
sk.addPlugin({
name: 'weather',
description: 'Weather plugin',
functions: [temperature],
});
function test() {
sk.invokePrompt({
promptTemplate: 'Return the current temperature in Dublin',
executionSettings: {
functionChoiceBehavior: FunctionChoiceBehavior.Auto(),
},
}).then((result) => {
console.log(result?.value);
});
}
test();