Microsoft 365 Agents SDK (TypeScript)
Créez des agents d'entreprise pour Microsoft 365, Teams et Copilot Studio à l'aide du Microsoft 365 Agents SDK avec hébergement Express, routage AgentApplication, réponses en streaming et intégrations client Copilot Studio.
Avant la mise en œuvre
- Utilisez le MCP microsoft-docs pour vérifier les dernières signatures d'API pour AgentApplication, startServer et CopilotStudioClient.
- Confirmez les versions des packages sur npm avant de configurer les exemples ou modèles.
Installation
npm install @microsoft/agents-hosting @microsoft/agents-hosting-express @microsoft/agents-activity
npm install @microsoft/agents-copilotstudio-client
Variables d'environnement
PORT=3978
AZURE_RESOURCE_NAME=<azure-openai-resource>
AZURE_API_KEY=<azure-openai-key>
AZURE_OPENAI_DEPLOYMENT_NAME=gpt-4o-mini
TENANT_ID=<tenant-id>
CLIENT_ID=<client-id>
CLIENT_SECRET=<client-secret>
COPILOT_ENVIRONMENT_ID=<environment-id>
COPILOT_SCHEMA_NAME=<schema-name>
COPILOT_CLIENT_ID=<copilot-app-client-id>
COPILOT_BEARER_TOKEN=<copilot-jwt>
Flux principal : AgentApplication hébergée avec Express
import {
AgentApplication,
TurnContext,
TurnState,
} from "@microsoft/agents-hosting";
import { startServer } from "@microsoft/agents-hosting-express";
const agent = new AgentApplication<TurnState>();
agent.onConversationUpdate("membersAdded", async (context: TurnContext) => {
await context.sendActivity("Welcome to the agent.");
});
agent.onMessage("hello", async (context: TurnContext) => {
await context.sendActivity(`Echo: ${context.activity.text}`);
});
startServer(agent);
Réponses en streaming avec Azure OpenAI
import { azure } from "@ai-sdk/azure";
import {
AgentApplication,
TurnContext,
TurnState,
} from "@microsoft/agents-hosting";
import { startServer } from "@microsoft/agents-hosting-express";
import { streamText } from "ai";
const agent = new AgentApplication<TurnState>();
agent.onMessage("poem", async (context: TurnContext) => {
context.streamingResponse.setFeedbackLoop(true);
context.streamingResponse.setGeneratedByAILabel(true);
context.streamingResponse.setSensitivityLabel({
type: "https://schema.org/Message",
"@type": "CreativeWork",
name: "Internal",
});
await context.streamingResponse.queueInformativeUpdate("starting a poem...");
const { fullStream } = streamText({
model: azure(process.env.AZURE_OPENAI_DEPLOYMENT_NAME || "gpt-4o-mini"),
system: "You are a creative assistant.",
prompt: "Write a poem about Apollo.",
});
try {
for await (const part of fullStream) {
if (part.type === "text-delta" && part.text.length > 0) {
await context.streamingResponse.queueTextChunk(part.text);
}
if (part.type === "error") {
throw new Error(`Streaming error: ${part.error}`);
}
}
} finally {
await context.streamingResponse.endStream();
}
});
startServer(agent);
Gestion des activités invoke
import { Activity, ActivityTypes } from "@microsoft/agents-activity";
import {
AgentApplication,
TurnContext,
TurnState,
} from "@microsoft/agents-hosting";
const agent = new AgentApplication<TurnState>();
agent.onActivity("invoke", async (context: TurnContext) => {
const invokeResponse = Activity.fromObject({
type: ActivityTypes.InvokeResponse,
value: { status: 200 },
});
await context.sendActivity(invokeResponse);
await context.sendActivity("Thanks for submitting your feedback.");
});
Client Copilot Studio (Direct to Engine)
import { CopilotStudioClient } from "@microsoft/agents-copilotstudio-client";
const settings = {
environmentId: process.env.COPILOT_ENVIRONMENT_ID!,
schemaName: process.env.COPILOT_SCHEMA_NAME!,
clientId: process.env.COPILOT_CLIENT_ID!,
};
const tokenProvider = async (): Promise<string> => {
return process.env.COPILOT_BEARER_TOKEN!;
};
const client = new CopilotStudioClient(settings, tokenProvider);
const conversation = await client.startConversationAsync();
const reply = await client.askQuestionAsync("Hello!", conversation.id);
console.log(reply);
Intégration WebChat Copilot Studio
import { CopilotStudioWebChat } from "@microsoft/agents-copilotstudio-client";
const directLine = CopilotStudioWebChat.createConnection(client, {
showTyping: true,
});
window.WebChat.renderWebChat(
{
directLine,
},
document.getElementById("webchat")!,
);
Bonnes pratiques
- Utilisez AgentApplication pour le routage et concentrez les gestionnaires sur une seule responsabilité.
- Préférez streamingResponse pour les complétions longues et appelez endStream dans les blocs finally.
- Gardez les secrets hors du code source ; chargez les jetons depuis les variables d'environnement ou des stockages sécurisés.
- Réutilisez les instances CopilotStudioClient et mettez en cache les jetons dans votre fournisseur de jetons.
- Validez les charges invoke avant de les enregistrer ou de persister les commentaires.
Liens de référence
| Ressource | URL |
|---|---|
| Microsoft 365 Agents SDK | https://learn.microsoft.com/en-us/microsoft-365/agents-sdk/ |
| Aperçu du SDK JavaScript | https://learn.microsoft.com/en-us/javascript/api/overview/agents-overview?view=agents-sdk-js-latest |
| @microsoft/agents-hosting-express | https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting-express?view=agents-sdk-js-latest |
| @microsoft/agents-copilotstudio-client | https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-copilotstudio-client?view=agents-sdk-js-latest |
| Intégrer avec Copilot Studio | https://learn.microsoft.com/en-us/microsoft-365/agents-sdk/integrate-with-mcs |
| Exemples GitHub | https://github.com/microsoft/Agents/tree/main/samples/nodejs |