本指南提供為 Microsoft 365 Copilot 建立 TypeSpec 代理程式的完整範例,從簡單的基本代理程式到具有多種功能和驗證方法的複雜實作。
沒有功能的基本代理程式
用例:一個簡單的代理,提供基本資訊和問候語,無需任何外部整合或特殊功能。
它的作用:該代理可以回答簡單的問題、提供一般資訊並進行基本對話。 它不需要存取外部 API、搜尋網路或存取任何 Microsoft 365 資料。
import "@typespec/http";
import "@typespec/openapi3";
import "@microsoft/typespec-m365-copilot";
using TypeSpec.Http;
using TypeSpec.M365.Copilot.Agents;
@agent("Basic Helper Agent", "A simple agent that provides basic information and assistance")
@instructions("""
You are a helpful assistant that provides basic information and support.
Be friendly, professional, and helpful in all interactions. Provide clear,
concise answers to user questions. If you don't know something, be honest
about your limitations and suggest alternative ways to find the information.
""")
namespace BasicHelperAgent {
// No capabilities defined - agent relies only on built-in conversational abilities
}
具有多種功能的代理程式
使用案例:知識工作者助理,可在網路上搜尋資訊、存取組織的 SharePoint 內容,以及尋找組織中同事的相關資訊。
它有什麼作用:此代理透過結合外部資訊的 Web 搜尋、文件檢索的檔案存取以及人員搜尋尋找同事及其聯絡資訊來幫助知識工作者。 此模式適合研究和共同作業案例。
import "@typespec/http";
import "@typespec/openapi3";
import "@microsoft/typespec-m365-copilot";
using TypeSpec.Http;
using TypeSpec.M365.Copilot.Agents;
@agent("Knowledge Worker Assistant", "An intelligent assistant that helps with research, file management, and finding colleagues")
@instructions("""
You are a knowledgeable research assistant specialized in helping knowledge workers
find information efficiently. You can search the web for external research, access
SharePoint documents for organizational content, and help locate colleagues within
the organization. Always provide comprehensive research results, cite your sources,
and suggest additional resources when relevant. When searching for people, respect
privacy and only share publicly available organizational information.
""")
namespace KnowledgeWorkerAgent {
// Web search capability for external research
op webSearch is AgentCapabilities.WebSearch<Sites = [
{
url: "https://learn.microsoft.com";
},
{
url: "https://www.microsoft.com";
}
]>;
// OneDrive and SharePoint access for document retrieval
op oneDriveAndSharePoint is AgentCapabilities.OneDriveAndSharePoint<
ItemsByUrl = [
{ url: "https://contoso.sharepoint.com/sites/IT" }
]
>;
// People search for finding colleagues
op people is AgentCapabilities.People;
}
具有匿名 API 動作的簡單代理程式
用例:一個設施管理代理,幫助用戶使用公共維修 API 報告和跟踪維護問題。
它的作用:該代理允許用戶報告設施問題 (設備損壞、照明問題等 ) 並檢查現有維修請求的狀態。 修復 API 可公開存取且不需要驗證,讓任何人都可以輕鬆回報問題。
import "@typespec/http";
import "@typespec/openapi3";
import "@microsoft/typespec-m365-copilot";
import "./actions.tsp";
using TypeSpec.Http;
using TypeSpec.M365.Copilot.Agents;
using TypeSpec.M365.Copilot.Actions;
@agent("Facilities Repair Agent", "Report and track facility maintenance issues and repair requests")
@instructions("""
You are a facilities management assistant that helps employees report and track
maintenance issues. You can help users submit new repair requests by gathering
all necessary details (description, location, category, priority) and submit
them to the facilities team. You can also check the status of existing repair
tickets and provide updates on progress. Always be helpful in categorizing
issues correctly and setting appropriate priority levels based on safety and
business impact.
""")
namespace FacilitiesRepairAgent {
op reportIssue is RepairsAPI.reportIssue;
op getRepairStatus is RepairsAPI.getRepairStatus;
op getOpenRepairs is RepairsAPI.getOpenRepairs;
}
import "@typespec/http";
import "@microsoft/typespec-m365-copilot";
using TypeSpec.Http;
using TypeSpec.M365.Copilot.Actions;
@service
@actions(#{
nameForHuman: "Facilities Repair API",
descriptionForModel: "API for reporting and tracking facility maintenance issues and repairs",
descriptionForHuman: "Use this API to report facility issues and check repair status"
})
@server("https://repairs.contoso.com", "Facilities Repair API")
namespace RepairsAPI {
@route("/repairs")
@post
@action
op reportIssue(
@body issue: RepairIssueRequest
): RepairIssueResponse;
@route("/repairs/{ticketId}")
@get
@action
op getRepairStatus(
@path ticketId: string
): RepairStatusResponse;
@route("/repairs")
@get
@action
op getOpenRepairs(
@query location?: string,
@query priority?: "low" | "medium" | "high" | "urgent"
): RepairListResponse;
model RepairIssueRequest {
title: string;
description: string;
location: string;
category: "electrical" | "plumbing" | "hvac" | "security" | "cleaning" | "other";
priority: "low" | "medium" | "high" | "urgent";
reportedBy: string;
}
model RepairIssueResponse {
ticketId: string;
status: "submitted" | "assigned" | "in-progress" | "completed" | "cancelled";
estimatedCompletion?: string;
assignedTechnician?: string;
}
model RepairStatusResponse {
ticketId: string;
title: string;
status: "submitted" | "assigned" | "in-progress" | "completed" | "cancelled";
priority: "low" | "medium" | "high" | "urgent";
createdDate: string;
lastUpdated: string;
assignedTechnician?: string;
estimatedCompletion?: string;
completionNotes?: string;
}
model RepairListResponse {
repairs: RepairStatusResponse[];
totalCount: int32;
}
}
具有 API 金鑰驗證的進階代理程式
用例:維修管理代理,可幫助團隊使用具有 API 金鑰身份驗證的公開 API 來追蹤和管理設施維護任務。
它有什麼作用:該代理為維護團隊提供全面的維修管理能力。 它可以列出、建立、更新和刪除維修任務,按受託人或描述篩選維修,並提供帶有圖像的豐富卡片式回應。 API 金鑰驗證可確保對維修管理系統的受控存取,同時展示真實世界的 API 整合模式。
import "@typespec/http";
import "@typespec/openapi3";
import "@microsoft/typespec-m365-copilot";
import "./actions.tsp";
using TypeSpec.Http;
using TypeSpec.M365.Copilot.Agents;
using TypeSpec.M365.Copilot.Actions;
@agent("Repairs Hub Agent", "Smart repair management agent for tracking and coordinating facility maintenance tasks")
@instructions("""
You are a specialized repairs management assistant that helps teams efficiently track,
organize, and coordinate facility maintenance tasks. You excel at managing repair
workflows including creating detailed repair tickets, assigning tasks to team members,
tracking progress, and providing status updates. You can filter repairs by various
criteria such as assignee, keywords in descriptions, or completion status. Always
provide clear, organized information using tables and cards when displaying repair
data. When creating repairs, gather all necessary details and confirm the information
before submission. Help prioritize urgent repairs and ensure proper task assignment
for optimal team productivity.
""")
@conversationStarter(#{
title: "List repairs",
text: "List all repairs"
})
@conversationStarter(#{
title: "List Karin's repairs",
text: "List all repairs assigned to Karin"
})
@conversationStarter(#{
title: "Find oil repairs",
text: "List all repairs that are about oil"
})
@conversationStarter(#{
title: "Create repair",
text: "Create a new repair and assign it to me"
})
namespace RepairsAgent {
// Repair management operations
op listRepairs is RepairsHub.listRepairs;
op createRepair is RepairsHub.createRepair;
op updateRepair is RepairsHub.updateRepair;
op deleteRepair is RepairsHub.deleteRepair;
}
import "@typespec/http";
import "@microsoft/typespec-m365-copilot";
using TypeSpec.Http;
using TypeSpec.M365.Copilot.Actions;
@service
@actions(#{
nameForHuman: "Repairs Hub API",
descriptionForModel: "Comprehensive repair management system for tracking maintenance tasks, assignments, and progress",
descriptionForHuman: "Use this API to manage facility repairs, track assignments, and coordinate maintenance activities"
})
@server("https://repairshub-apikey.contoso.com", "Repairs Hub API")
@useAuth(RepairsHubApiKeyAuth)
namespace RepairsHub {
@route("/repairs")
@get
@action
@card(#{
dataPath: "$",
file: "cards/card.json",
properties: #{
title: "$.title",
url: "$.image"
}
})
op listRepairs(
@query assignedTo?: string
): string;
@route("/repairs")
@post
@action
@capabilities(#{
confirmation: #{
type: "AdaptiveCard",
title: "Create a new repair",
body: """
Creating a new repair with the following details:
* **Title**: {{ function.parameters.title }}
* **Description**: {{ function.parameters.description }}
* **Assigned To**: {{ function.parameters.assignedTo }}
"""
}
})
op createRepair(
@body repair: Repair
): Repair;
@route("/repairs")
@patch
@action
@capabilities(#{
confirmation: #{
type: "AdaptiveCard",
title: "Update repair",
body: """
Updating a repair with the following details:
* **ID**: {{ function.parameters.id }}
* **Title**: {{ function.parameters.title }}
* **Description**: {{ function.parameters.description }}
* **Assigned To**: {{ function.parameters.assignedTo }}
"""
}
})
op updateRepair(
@body repair: Repair
): Repair;
@route("/repairs")
@delete
@action
@capabilities(#{
confirmation: #{
type: "AdaptiveCard",
title: "Delete a repair",
body: """
Deleting a repair with the following details:
* **ID**: {{ function.parameters.id }}
"""
}
})
op deleteRepair(
@body repair: Repair
): Repair;
model Repair {
id?: string;
title: string;
description?: string;
assignedTo?: string;
@format("date-time")
date?: string;
@format("uri")
image?: string;
}
@authReferenceId("${{REPAIRSHUBAPIKEYAUTH_REFERENCE_ID}}")
model RepairsHubApiKeyAuth is ApiKeyAuth<ApiKeyLocation.query, "code">;
}
card.json檔案必須位於 appPackage/cards 資料夾中。
{
"type": "AdaptiveCard",
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"version": "1.5",
"body": [
{
"type": "Container",
"$data": "${$root}",
"items": [
{
"type": "TextBlock",
"text": "id: ${if(id, id, 'N/A')}",
"wrap": true
},
{
"type": "TextBlock",
"text": "title: ${if(title, title, 'N/A')}",
"wrap": true
},
{
"type": "TextBlock",
"text": "description: ${if(description, description, 'N/A')}",
"wrap": true
},
{
"type": "TextBlock",
"text": "assignedTo: ${if(assignedTo, assignedTo, 'N/A')}",
"wrap": true
},
{
"type": "TextBlock",
"text": "date: ${if(date, date, 'N/A')}",
"wrap": true
},
{
"type": "Image",
"url": "${image}",
"$when": "${image != null}"
}
]
}
]
}
具有 OAuth2 和 GitHub API 整合的複雜代理程式
用例:一個專案管理代理,可幫助開發團隊使用 GitHub 的綜合 API 管理其 GitHub 儲存庫、追蹤問題、管理拉取請求和協調專案活動。
它有什麼作用:該代理充當與 GitHub 整合的專案管理助理,以幫助開發團隊簡化其工作流程。 它可以建立和管理問題、審查和合併拉取請求、追蹤專案里程碑並提供有關儲存庫活動的見解。 OAuth2 身份驗證確保以適當的權限安全訪問 GitHub 存儲庫,使團隊能夠通過自然語言交互有效地管理他們的項目。
import "@typespec/http";
import "@typespec/openapi3";
import "@microsoft/typespec-m365-copilot";
import "./actions.tsp";
using TypeSpec.Http;
using TypeSpec.M365.Copilot.Agents;
using TypeSpec.M365.Copilot.Actions;
@agent("GitHub Project Manager", "Smart project management agent with GitHub integration for issue tracking, pull request management, and project coordination")
@instructions("""
You are an intelligent project management assistant specialized in GitHub workflows
and development team coordination. You excel at managing GitHub repositories including
creating and tracking issues, reviewing pull requests, coordinating project milestones,
and providing insights about development activity. You can help prioritize work,
track progress, manage code reviews, and facilitate team collaboration through GitHub's
project management features. Always consider development best practices, help maintain
code quality through proper review processes, and provide actionable insights to
improve team productivity and project delivery.
""")
namespace GitHubProjectManager {
// GitHub API operations for project management
op createIssue is GitHubAPI.createIssue;
op getIssues is GitHubAPI.getIssues;
op updateIssue is GitHubAPI.updateIssue;
op getPullRequests is GitHubAPI.getPullRequests;
op createPullRequest is GitHubAPI.createPullRequest;
op mergePullRequest is GitHubAPI.mergePullRequest;
op getProjectInsights is GitHubAPI.getProjectInsights;
}
import "@typespec/http";
import "@microsoft/typespec-m365-copilot";
using TypeSpec.Http;
using TypeSpec.M365.Copilot.Actions;
@service
@actions(#{
nameForHuman: "GitHub Project Management API",
descriptionForModel: "GitHub API integration for project management including issue tracking, pull request management, and project insights",
descriptionForHuman: "Use this API to manage GitHub repositories, track issues, and coordinate development projects"
})
@server("https://api.github.com", "GitHub API")
@useAuth(OAuth2Auth<[{
type: OAuth2FlowType.authorizationCode;
authorizationUrl: "https://github.com/login/oauth/authorize";
tokenUrl: "https://github.com/login/oauth/access_token";
scopes: ["repo", "issues", "pull_requests", "project"];
}]>)
namespace GitHubAPI {
// Issue Management
@route("/repos/{owner}/{repo}/issues")
@post
@action
op createIssue(
@path owner: string,
@path repo: string,
@body issue: IssueCreateRequest
): IssueResponse;
@route("/repos/{owner}/{repo}/issues")
@get
@action
op getIssues(
@path owner: string,
@path repo: string,
@query state?: "open" | "closed" | "all",
@query labels?: string,
@query assignee?: string,
@query milestone?: string,
@query since?: string
): IssueListResponse;
@route("/repos/{owner}/{repo}/issues/{issue_number}")
@patch
@action
op updateIssue(
@path owner: string,
@path repo: string,
@path issue_number: int32,
@body update: IssueUpdateRequest
): IssueResponse;
// Pull Request Management
@route("/repos/{owner}/{repo}/pulls")
@get
@action
op getPullRequests(
@path owner: string,
@path repo: string,
@query state?: "open" | "closed" | "all",
@query head?: string,
@query base?: string,
@query sort?: "created" | "updated" | "popularity"
): PullRequestListResponse;
// Project Insights
@route("/repos/{owner}/{repo}/stats/contributors")
@get
@action
op getProjectInsights(
@path owner: string,
@path repo: string
): ProjectInsightsResponse;
// Request/Response Models
model IssueCreateRequest {
title: string;
body?: string;
assignees?: string[];
milestone?: int32;
labels?: string[];
}
model IssueUpdateRequest {
title?: string;
body?: string;
state?: "open" | "closed";
assignees?: string[];
milestone?: int32;
labels?: string[];
}
model IssueResponse {
id: int32;
number: int32;
title: string;
body?: string;
state: "open" | "closed";
assignees: User[];
milestone?: Milestone;
labels: Label[];
created_at: string;
updated_at: string;
closed_at?: string;
html_url: string;
}
model IssueListResponse {
issues: IssueResponse[];
total_count: int32;
}
model PullRequestResponse {
id: int32;
number: int32;
title: string;
body?: string;
state: "open" | "closed";
head: BranchInfo;
base: BranchInfo;
user: User;
assignees: User[];
reviewers: User[];
created_at: string;
updated_at: string;
merged_at?: string;
html_url: string;
draft: boolean;
}
model PullRequestListResponse {
pull_requests: PullRequestResponse[];
total_count: int32;
}
model ProjectInsightsResponse {
total_commits: int32;
contributors: ContributorStats[];
top_languages: LanguageStats[];
recent_activity: ActivitySummary;
}
model User {
id: int32;
login: string;
avatar_url: string;
html_url: string;
}
model Milestone {
id: int32;
number: int32;
title: string;
description?: string;
state: "open" | "closed";
due_on?: string;
}
model Label {
id: int32;
name: string;
description?: string;
color: string;
}
model BranchInfo {
label: string;
ref: string;
sha: string;
repo: RepositoryInfo;
}
model RepositoryInfo {
id: int32;
name: string;
full_name: string;
owner: User;
html_url: string;
}
model ContributorStats {
author: User;
total_commits: int32;
weeks: WeeklyStats[];
}
model WeeklyStats {
week: string;
additions: int32;
deletions: int32;
commits: int32;
}
model LanguageStats {
language: string;
bytes: int32;
percentage: float64;
}
model ActivitySummary {
commits_last_week: int32;
issues_opened: int32;
issues_closed: int32;
pull_requests_opened: int32;
pull_requests_merged: int32;
}
}
摘要
這些範例示範了從簡單到複雜的 TypeSpec 代理程式的進展:
每個範例都建立在先前的範例的基礎上,顯示如何新增功能、驗證和自訂動作,以針對實際案例建立更複雜的代理程式。
相關內容