Teams AI ライブラリを使用すると、AI コンポーネントを使用してインテリジェントなMicrosoft Teams アプリケーションを簡単に構築できます。 データ アクセス、カスタム UI の作成、プロンプト管理、および安全性モデレーション用の API を提供します。 OpenAI または Azure OpenAI を使用してボットを簡単に作成して、AI 主導のエクスペリエンスを提供できます。
最初のセットアップ
Teams AI ライブラリは、Bot Framework SDK の上に構築されています。 これは、コア機能をインポートすることで、Bot Framework の機能を拡張します。 初期セットアップの一環として、Bot Framework SDK コンポーネントをインポートします。 チャネルとの接続を処理するアダプター クラスは、 Bot Framework SDK からインポートされます。
.NET コード: 初期構成とアダプターのセットアップ
using Microsoft.Teams.AI;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.Integration.AspNet.Core;
using Microsoft.Bot.Connector.Authentication;
using Microsoft.TeamsFx.Conversation;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddHttpClient("WebClient", client => client.Timeout = TimeSpan.FromSeconds(600));
builder.Services.AddHttpContextAccessor();
// Prepare Configuration for ConfigurationBotFrameworkAuthentication
var config = builder.Configuration.Get<ConfigOptions>();
builder.Configuration["MicrosoftAppType"] = "MultiTenant";
builder.Configuration["MicrosoftAppId"] = config.BOT_ID;
builder.Configuration["MicrosoftAppPassword"] = config.BOT_PASSWORD;
// Create the Bot Framework Authentication to be used with the Bot Adapter.
builder.Services.AddSingleton<BotFrameworkAuthentication, ConfigurationBotFrameworkAuthentication>();
// Create the Cloud Adapter with error handling enabled.
// Note: some classes expect a BotAdapter and some expect a BotFrameworkHttpAdapter, so
// register the same adapter instance for all types.
builder.Services.AddSingleton<CloudAdapter, AdapterWithErrorHandler>();
builder.Services.AddSingleton<IBotFrameworkHttpAdapter>(sp => sp.GetService<CloudAdapter>());
builder.Services.AddSingleton<BotAdapter>(sp => sp.GetService<CloudAdapter>());
Teams AI ライブラリをインポートする
@microsoft/teams-ai
からすべてのクラスをインポートしてボットを構築し、Teams AI ライブラリ機能を使用します。
JavaScript コード: Teams AI ライブラリのインポート
// import Teams AI library
import {
AI,
Application,
ActionPlanner,
OpenAIModerator,
OpenAIModel,
PromptManager,
TurnState
} from '@microsoft/teams-ai';
import { addResponseFormatter } from './responseFormatter';
import { VectraDataSource } from './VectraDataSource';
AI コンポーネントを作成する
AI コンポーネントは、既存のボット アプリまたは新しい Bot Framework アプリで作成できます。 メインコンポーネントには、次のものが含まれます。
- OpenAIModel: OpenAI API または OpenAI REST 形式に従う任意のサービスへのアクセスを提供します。 OpenAI 言語モデルと Azure OpenAI 言語モデルの両方で動作します。
- プロンプト マネージャー: プロンプトの作成を管理します。 関数、会話状態、およびユーザー状態が自動的にプロンプトに挿入されます。
- ActionPlanner: 大規模言語モデル (LLM) を呼び出し、モデルを強化およびカスタマイズするための機能が含まれています。 このコンポーネントは、ユーザー入力と使用可能なアクションに基づいてプランを生成して実行します。
.NET コード: AI コンポーネントの作成
// Create model
OpenAIModel? model = null;
if (!string.IsNullOrEmpty(config.OpenAI?.ApiKey))
{
model = new(new OpenAIModelOptions(config.OpenAI.ApiKey, "gpt-3.5-turbo"));
}
else if (!string.IsNullOrEmpty(config.Azure?.OpenAIApiKey) && !string.IsNullOrEmpty(config.Azure.OpenAIEndpoint))
{
model = new(new AzureOpenAIModelOptions(
config.Azure.OpenAIApiKey,
"gpt-35-turbo",
config.Azure.OpenAIEndpoint
));
}
if (model == null)
{
throw new Exception("please configure settings for either OpenAI or Azure");
}
// Create prompt manager
PromptManager prompts = new(new()
{
PromptFolder = "./Prompts",
});
// Add function to be referenced in the prompt template
prompts.AddFunction("getLightStatus", async (context, memory, functions, tokenizer, args) =>
{
bool lightsOn = (bool)(memory.GetValue("conversation.lightsOn") ?? false);
return await Task.FromResult(lightsOn ? "on" : "off");
});
// Create ActionPlanner
ActionPlanner<AppState> planner = new(
options: new(
model: model,
prompts: prompts,
defaultPrompt: async (context, state, planner) =>
{
PromptTemplate template = prompts.GetPrompt("sequence");
return await Task.FromResult(template);
}
)
{ LogRepairs = true },
loggerFactory: loggerFactory
);
ストレージとアプリケーションを定義する
アプリケーション オブジェクトは、ボットの会話とユーザーの状態を自動的に管理します。 内容は以下のとおりです。
- ストレージ: ストレージ プロバイダーは、会話とユーザーの状態を格納します。
-
アプリケーション:
Application
クラスは、アプリのアクションまたはアクティビティ ハンドラーを登録します。 これには、必要なすべての情報とボット ロジックが含まれています。
.NET コード: ストレージとアプリケーションの定義
return new TeamsLightBot(new()
{
Storage = sp.GetService<IStorage>(),
AI = new(planner),
LoggerFactory = loggerFactory,
TurnStateFactory = () =>
{
return new AppState();
}
});
TurnStateFactory
プロパティを使用すると、追加情報またはロジックを格納するカスタム状態クラスを作成できます。 追加のプロパティ (ユーザー入力、ボット出力、会話履歴など) を含むクラスを作成し、クラスのインスタンスを作成する関数をアプリ コンストラクターに渡すことで、既定のターン状態を拡張します。
データ ソースを登録する
ベクター データ ソースを使用すると、任意のプロンプトに Retrieval-Augmented 生成 (RAG) を簡単に追加できます。 名前付きデータ ソースを planner に登録し、プロンプトの config.json
ファイルで指定してプロンプトを拡張します。 これにより、AI は外部ソース (ベクター データベースやコグニティブ検索など) からの関連情報をプロンプトに挿入できます。
JavaScript コード: Plannerにデータ ソースを登録する
// Register your data source with planner
planner.prompts.addDataSource(new VectraDataSource({
name: 'teams-ai',
apiKey: process.env.OPENAI_API_KEY!,
indexFolder: path.join(__dirname, '../index'),
}));
埋め込み
埋め込みは、テキストを表す LLM によって生成されたベクトルであり、そのセマンティックな意味をキャプチャします。 埋め込みは、テキスト分類、センチメント分析、検索などで使用されます。 たとえば、OpenAI の text-embedding-ada-002
モデルは、入力テキストを表す 1536 個の数値のリストを返します。 これらの埋め込みは、ベクター データベースに格納されます。 カスタム エンジン エージェントでは、RAG パターンでベクター データベースから関連するデータを取得し、プロンプトを拡張できます。
例: VectraDataSource と OpenAIEmbeddings
import { DataSource, Memory, RenderedPromptSection, Tokenizer } from '@microsoft/teams-ai';
import { OpenAIEmbeddings, LocalDocumentIndex } from 'vectra';
import * as path from 'path';
import { TurnContext } from 'botbuilder';
/**
* Options for creating a `VectraDataSource`.
*/
export interface VectraDataSourceOptions {
/**
* Name of the data source and local index.
*/
name: string;
/**
* OpenAI API key to use for generating embeddings.
*/
apiKey: string;
/**
* Path to the folder containing the local index.
* @remarks
* This should be the root folder for all local indexes and the index itself
* needs to be in a subfolder under this folder.
*/
indexFolder: string;
/**
* Optional. Maximum number of documents to return.
* @remarks
* Defaults to `5`.
*/
maxDocuments?: number;
/**
* Optional. Maximum number of chunks to return per document.
* @remarks
* Defaults to `50`.
*/
maxChunks?: number;
/**
* Optional. Maximum number of tokens to return per document.
* @remarks
* Defaults to `600`.
*/
maxTokensPerDocument?: number;
}
/**
* A data source that uses a local Vectra index to inject text snippets into a prompt.
*/
export class VectraDataSource implements DataSource {
private readonly _options: VectraDataSourceOptions;
private readonly _index: LocalDocumentIndex;
/**
* Name of the data source.
* @remarks
* This is also the name of the local Vectra index.
*/
public readonly name: string;
/**
* Creates a new `VectraDataSource` instance.
* @param options Options for creating the data source.
*/
public constructor(options: VectraDataSourceOptions) {
this._options = options;
this.name = options.name;
// Create embeddings model
const embeddings = new OpenAIEmbeddings({
model: 'text-embedding-ada-002',
apiKey: options.apiKey,
});
// Create local index
this._index = new LocalDocumentIndex({
embeddings,
folderPath: path.join(options.indexFolder, options.name),
});
}
/**
* Renders the data source as a string of text.
* @param context Turn context for the current turn of conversation with the user.
* @param memory An interface for accessing state values.
* @param tokenizer Tokenizer to use when rendering the data source.
* @param maxTokens Maximum number of tokens allowed to be rendered.
*/
public async renderData(context: TurnContext, memory: Memory, tokenizer: Tokenizer, maxTokens: number): Promise<RenderedPromptSection<string>> {
// Query index
const query = memory.getValue('temp.input') as string;
const results = await this._index.queryDocuments(query, {
maxDocuments: this._options.maxDocuments ?? 5,
maxChunks: this._options.maxChunks ?? 50,
});
// Add documents until you run out of tokens
let length = 0;
let output = '';
let connector = '';
for (const result of results) {
// Start a new doc
let doc = `${connector}url: ${result.uri}\n`;
let docLength = tokenizer.encode(doc).length;
const remainingTokens = maxTokens - (length + docLength);
if (remainingTokens <= 0) {
break;
}
// Render document section
const sections = await result.renderSections(Math.min(remainingTokens, this._options.maxTokensPerDocument ?? 600), 1);
docLength += sections[0].tokenCount;
doc += sections[0].text;
// Append doc to output
output += doc;
length += docLength;
connector = '\n\n';
}
return { output, length, tooLong: length > maxTokens };
}
}
プロンプト
プロンプトは、会話の開始、質問、応答の生成など、会話エクスペリエンスを作成するために使用されるテキスト セグメントです。 新しいオブジェクト ベースのプロンプト システムは、プロンプトをセクションに分割し、それぞれに独自のトークン予算 (固定または残りのトークンに比例) を使用します。 プロンプトは、テキスト入力候補とチャット入力候補スタイル API の両方に対して生成できます。
次のガイドラインに従って、効果的なプロンプトを作成します。
- 明確な手順と例を示します。
- 十分な例を使用して、高品質の校正データを確保します。
-
temperature
とtop_p
を使用してプロンプト設定を調整して、モデルの出力を制御します。 値が大きいほど (0.8 など) ランダムな出力が生成されます。より低い値 (例: 0.2) は、焦点を絞った決定的な応答を作成します。
プロンプトを実装するには:
-
prompts
という名前のフォルダーを作成します。 - 専用ファイルでプロンプト テンプレートと設定を定義します。
-
skprompt.txt
: テンプレート変数と関数をサポートするプロンプト テキストが含まれます。 -
config.json
: ボットの応答が要件を満たしていることを確認するプロンプト モデル設定が含まれています。
-
例: プロンプト設定のconfig.json
{
"schema": 1.1,
"description": "A bot that can turn the lights on and off",
"type": "completion",
"completion": {
"model": "gpt-3.5-turbo",
"completion_type": "chat",
"include_history": true,
"include_input": true,
"max_input_tokens": 2800,
"max_tokens": 1000,
"temperature": 0.2,
"top_p": 0.0,
"presence_penalty": 0.6,
"frequency_penalty": 0.0,
"stop_sequences": []
},
"augmentation": {
"augmentation_type": "sequence"
"data_sources": {
"teams-ai": 1200
}
}
}
クエリ パラメーター
次の表では、クエリ パラメーターの詳細を示します。
値 | 説明 |
---|---|
model |
使用するモデルの ID。 |
completion_type |
使用する完了の種類。 モデルは、1 つ以上の予測完了と代替トークンの確率を返します。 サポートされているオプション: chat と text 。 既定値: chat 。 |
include_history |
ブール型 (Boolean) の値 履歴を含めるかどうかを示します。 各プロンプトは、混乱を避けるために独自の会話履歴を取得します。 |
include_input |
ブール型 (Boolean) の値 true に設定すると、ユーザーの入力がプロンプトに含まれます。 |
max_input_tokens |
入力に許可されるトークンの最大数。 (サポートされているトークンの最大数: 4000) |
max_tokens |
生成するトークンの最大数。 プロンプト トークンと max_tokens の合計は、モデルのコンテキスト長を超えてはなりません。 |
temperature |
サンプリング温度 (範囲: 0 から 2)。 値が大きいほど (例: 0.8) よりランダムな出力が生成されます。より小さい値 (例: 0.2) はフォーカスされた出力を生成します。 |
top_p |
核サンプリングと呼ばれる温度によるサンプリングに代わる方法。 たとえば、値が 0.1 の場合、上位 10% の確率質量のトークンのみが考慮されます。 |
presence_penalty |
-2.0 から 2.0 までの数値。 正の値を指定すると、新しいトークンがテキストに表示されるかどうかに基づいて新しいトークンが罰され、新しいトピックの議論が促進されます。 |
frequency_penalty |
-2.0 から 2.0 までの数値。 正の値は、頻度に基づいてトークンを罰し、繰り返しの可能性を減らします。 |
stop_sequences |
API がトークンの生成を停止する最大 4 つのシーケンス。 返されるテキストには、停止シーケンスは含まれません。 |
augmentation_type |
拡張の種類。 サポートされている値は sequence 、monologue 、tools です。 |
プロンプト管理
プロンプト管理は、トークンの予算と使用可能なデータ ソースに基づいて、プロンプトのサイズとコンテンツを動的に調整します。 たとえば、4,000 トークンの制限 (入力の場合は 2,800、出力の場合は 1,000) のボットの場合、モデルは会話履歴、入力、外部ソースからの拡張データのトークンを予約します。
プロンプト アクション
プロンプト アクションを使用すると、モデルでアクションを実行したり、ユーザー入力に応答したりできます。 対応するパラメーターを使用して、サポートされているアクションを一覧表示するスキーマを作成できます。 OpenAI エンドポイントはエンティティを抽出し、それらを引数としてアクション ハンドラーに渡します。
例:
The following is a conversation with an AI assistant.
The assistant can turn a light on or off.
context:
The lights are currently {{getLightStatus}}.
プロンプト テンプレート
プロンプト テンプレートは、プレーン テキストを使用して AI 関数を定義して作成します。 これにより、次のことができます。
- 自然言語プロンプトを作成します。
- 応答を生成します。
- 情報を抽出します。
- 他のプロンプトを呼び出します。
この言語では、中かっこ {{...}}
を使用した変数と関数の埋め込みをサポートしています。 一部のキー式には、次のものが含まれます。
-
{{function}}
: 登録済み関数を呼び出し、その戻り値を挿入します。 -
{{$input}}
:state.temp.input
から取得したユーザーのメッセージ テキストを挿入します。 -
{{$state.[property]}}
: 状態プロパティを挿入します。
アクション
アクションは、AI コンポーネントによってトリガーされるイベントを処理します。 組み込みの FlaggedInputAction
と FlaggedOutputAction
はモデレーター フラグを処理します。 メッセージにフラグが設定されると、ボットは context.sendActivity
を介してユーザーに通知します。 アクションを停止するには、 AI.StopCommandName
を返します。
JavaScript コード: フラグ付き入力アクションと出力アクションの登録
// Register other AI actions
app.ai.action(
AI.FlaggedInputActionName,
async (context: TurnContext, state: ApplicationTurnState, data: Record<string, any>) => {
await context.sendActivity(`I'm sorry your message was flagged: ${JSON.stringify(data)}`);
return AI.StopCommandName;
}
);
app.ai.action(AI.FlaggedOutputActionName, async (context: TurnContext, state: ApplicationTurnState, data: any) => {
await context.sendActivity(`I'm not allowed to talk about such things.`);
return AI.StopCommandName;
});
アクション ハンドラーの登録
アクション ハンドラーは、ボットが特定のタスクを実行するのに役立ちます。 まず、プロンプトにアクションを登録してから、不明なアクションを含む各アクションのハンドラーを実装します。
次のライト ボットの例では、アクションには LightsOn
、 LightsOff
、 Pause
が含まれます。 各アクション ハンドラーは、 string
を返します。 時間を返すアクション (一時停止期間など) の場合、 PauseParameters
プロパティは時間が数値形式であることを確認します。
.NET コード: LightBot のアクション ハンドラー
public class LightBotActions
{
[Action("LightsOn")]
public async Task<string> LightsOn([ActionTurnContext] ITurnContext turnContext, [ActionTurnState] AppState turnState)
{
turnState.Conversation!.LightsOn = true;
await turnContext.SendActivityAsync(MessageFactory.Text("[lights on]"));
return "the lights are now on";
}
[Action("LightsOff")]
public async Task<string> LightsOff([ActionTurnContext] ITurnContext turnContext, [ActionTurnState] AppState turnState)
{
turnState.Conversation!.LightsOn = false;
await turnContext.SendActivityAsync(MessageFactory.Text("[lights off]"));
return "the lights are now off";
}
[Action("Pause")]
public async Task<string> LightsOff([ActionTurnContext] ITurnContext turnContext, [ActionParameters] Dictionary<string, object> args)
{
// Try to parse entities returned by the model.
// Expecting "time" to be a number of milliseconds to pause.
if (args.TryGetValue("time", out object? time))
{
if (time != null && time is string timeString)
{
if (int.TryParse(timeString, out int timeInt))
{
await turnContext.SendActivityAsync(MessageFactory.Text($"[pausing for {timeInt / 1000} seconds]"));
await Task.Delay(timeInt);
}
}
}
return "done pausing";
}
[Action("LightStatus")]
public async Task<string> LightStatus([ActionTurnContext] ITurnContext turnContext, [ActionTurnState] AppState turnState)
{
await turnContext.SendActivityAsync(ResponseGenerator.LightStatus(turnState.Conversation!.LightsOn));
return turnState.Conversation!.LightsOn ? "the lights are on" : "the lights are off";
}
[Action(AIConstants.UnknownActionName)]
public async Task<string> UnknownAction([ActionTurnContext] TurnContext turnContext, [ActionName] string action)
{
await turnContext.SendActivityAsync(ResponseGenerator.UnknownAction(action ?? "Unknown"));
return "unknown action";
}
}
}
シーケンス、モノローグ、またはツールの拡張を使用すると、モデルが無効な関数名、アクション名、またはパラメーターを幻覚できなくなります。 アクション ファイルを作成して、次の操作を行います。
- プロンプト拡張のアクションを定義します。
- アクションを実行するタイミングを指定します。
たとえば、ライト ボットでは、 actions.json
ファイルに次のようなアクションが一覧表示される場合があります。
[
{
"name": "LightsOn",
"description": "Turns on the lights"
},
{
"name": "LightsOff",
"description": "Turns off the lights"
},
{
"name": "Pause",
"description": "Delays for a period of time",
"parameters": {
"type": "object",
"properties": {
"time": {
"type": "number",
"description": "The amount of time to delay in milliseconds"
}
},
"required": [
"time"
]
}
}
]
-
name
: アクションの名前 (必須)。 -
description
: アクションの説明 (省略可能)。 -
parameters
: 必要なパラメーターを定義する JSON スキーマ。
フィードバック ループは、ボットの相互作用を検証、修正、および調整するのに役立ちます。
sequence
拡張の場合は、AIOptions
で allow_looping?
を false
に設定するか、実装で max_repair_attempts
を 0
に設定して、ループを無効にします。
履歴の管理
MaxHistoryMessages
とMaxConversationHistoryTokens
の設定を使用して、AI ライブラリが会話履歴を自動的に管理できるようにします。
フィードバック ループ
フィードバック ループは、ボットの相互作用を監視し、改善します。 内容は以下のとおりです。
- 修復Loop: 応答が代替ソリューションを試すには不十分な場合に会話履歴をフォークします。
- 検証: 修正された応答を会話にマージする前に検証します。
- 学習: 正しい動作の例に基づいてボットのパフォーマンスを調整します。
- 複雑なコマンド処理: 時間の経過と同時に複雑なコマンドを処理するモデルの機能を強化します。
従来のボットをカスタム エンジン エージェントにアップグレードする
Teams にボットが既にある場合は、ストリーミング、引用、AI ラベルをサポートするカスタム エンジン エージェントにアップグレードできます。 このアップグレードは、ボットを会話型 AI UX パラダイムに合わせ、宣言型エージェントとの一貫性のあるエクスペリエンスを提供します。
注:
カスタム エンジン エージェントは Python ではサポートされていません。
アップグレード手順:
To-Do リスト | ドキュメントのサポート |
---|---|
AI SDK のバージョンを更新する | • JavaScript の場合は、 v1.6.1 に更新します。 • C# の場合は、 v1.8.1 に更新します。 |
ボットのストリーミングを有効にします。 | ボット メッセージをStreamする |
AI ラベルを使用して、AI によって生成されたメッセージを示します。 | AI ラベル |
ソース参照には引用文献を使用します。 | 引用 |
Microsoft 365 Copilot Chatのサポートを追加する
カスタム エンジン エージェントのサポートは、Microsoft 365 Copilot Chatで追加できます。 これには、フォローアップ メッセージや実行時間の長いタスクなどの非同期パターンのサポートが含まれます。 詳細については、「 非同期パターン」を参照してください。
Microsoft 365 Copilot Chatをサポートするには、アプリ マニフェストを更新します。
サブプロパティ
customEngineAgents
を持つcopilotAgents
プロパティをアプリ マニフェストに追加します。"copilotAgents": { "customEngineAgents": [ { "type": "bot", "id": "<Bot-Id-Guid>" } ] }
アプリ マニフェストで
bots
とcommandLists
のpersonal
にscopes
を設定します。"bots": [ { "botId": "<Bot-Id-Guid>", "scopes": [ "personal", "team", "groupChat" ], "commandLists": [ { "scopes": ["personal"], "commands": [ { "title": "Sample prompt title", "description": "Description of sample prompt" } ] }, { "scopes": ["personal"], "commands": [ { "title": "Sample prompt title", "description": "Description of sample prompt" } ] } ], } ],
注:
- Microsoft 365 Copilot Chatは、すべてのカスタム エンジン エージェント応答に AI によって生成されたラベルを追加します。
- Microsoft 365 Agents Toolkit (旧称 Teams Toolkit) を使用して構築されたボットで、Microsoft 365 Copilot Chatをサポートする場合は、ステップバイステップ ガイドに従ってください。
- カスタム エンジン エージェントのシングル サインオン (SSO) は使用できますが、Outlook クライアントではサポートされていません。 SSO のアプリ登録Microsoft Entra更新に関するページを参照してください。
AI を使用するように従来のボットを昇格させる
AI を利用できるように、既存の従来のボットを更新できます。 AI レイヤーを追加すると、LLM 主導の機能を使用してボットが強化されます。 Bot Framework アダプターと app
オブジェクトを使用して AI レイヤーを統合する例を次に示します。
JavaScript コード: AI を使用するための従来のボットの昇格
// Create AI components
const model = new OpenAIModel({
// OpenAI Support
apiKey: process.env.OPENAI_KEY!,
defaultModel: 'gpt-4o',
// Azure OpenAI Support
azureApiKey: process.env.AZURE_OPENAI_KEY!,
azureDefaultDeployment: 'gpt-4o',
azureEndpoint: process.env.AZURE_OPENAI_ENDPOINT!,
azureApiVersion: '2023-03-15-preview',
// Request logging
logRequests: true
});
const prompts = new PromptManager({
promptsFolder: path.join(__dirname, '../src/prompts')
});
// Define a prompt function for getting the current status of the lights
prompts.addFunction('getLightStatus', async (context: TurnContext, memory: Memory) => {
return memory.getValue('conversation.lightsOn') ? 'on' : 'off';
});
const planner = new ActionPlanner({
model,
prompts,
defaultPrompt: 'tools'
});
// Define storage and application
const storage = new MemoryStorage();
const app = new Application<ApplicationTurnState>({
storage,
ai: {
planner
}
});
app.ai.action('LightStatus', async (context: TurnContext, state: ApplicationTurnState) => {
const status = state.conversation.lightsOn ? 'on' : 'off';
return `the lights are ${status}`;
});
// Register action handlers
app.ai.action('LightsOn', async (context: TurnContext, state: ApplicationTurnState) => {
state.conversation.lightsOn = true;
await context.sendActivity(`[lights on]`);
return `the lights are now on`;
});
app.ai.action('LightsOff', async (context: TurnContext, state: ApplicationTurnState) => {
state.conversation.lightsOn = false;
await context.sendActivity(`[lights off]`);
return `the lights are now off`;
});
interface PauseParameters {
time: number;
}
app.ai.action('Pause', async (context: TurnContext, state: ApplicationTurnState, parameters: PauseParameters) => {
await context.sendActivity(`[pausing for ${parameters.time / 1000} seconds]`);
await new Promise((resolve) => setTimeout(resolve, parameters.time));
return `done pausing`;
});
// Listen for incoming server requests.
server.post('/api/messages', async (req, res) => {
// Route received a request to adapter for processing
await adapter.process(req, res as any, async (context) => {
// Dispatch to application for routing
await app.run(context);
});
});
Teams AI ライブラリを使用するようにボットを移行する
Bot Framework SDK を使用してボットを構築した場合は、Teams AI ライブラリに移行して高度な AI 機能のロックを解除できます。 移行には、次の利点があります。
- LLM を利用した複雑な Teams アプリケーションを構築するための高度な AI システム。
- サード パーティのユーザー データにアクセスするための統合ユーザー認証。
- 使い慣れた Bot Framework SDK のツールと概念を活用します。
- 最新の LLM ツールと API をサポートします。
ボットの言語に関連する移行ガイドを選択します。
Bot Framework SDK アプリを移行する ... | Teams AI ライブラリを使用するには ... |
---|---|
JavaScript を使用して構築されたボット アプリ | 移行 |
C を使用して構築されたボット アプリ# | 移行 |
Python を使用したボット アプリ | 移行 |
コード サンプル
サンプルの名前 | 説明 | .NET | Node.js |
---|---|---|---|
アクション マッピングライトボット | LightBot がユーザーの意図を理解し、コマンドに基づいてライト ボットを制御する方法を示します。 | 表示 | 表示 |
次の手順
エージェント ツールキットと Teams AI ライブラリを使用してシナリオ ベースのカスタム エンジン エージェントを作成する場合は、次を選択します。
詳細なステップ バイ ステップ ガイド
Teams AI ライブラリのコア機能について学習する場合は、次を選択します。
Teams AI ライブラリについて
Platform Docs