本指南提供了为 智能 智能 Microsoft 365 Copilot 副驾驶® 副驾驶® 创建 TypeSpec 代理的完整示例,从简单的基本代理到具有多种功能和身份验证方法的复杂实现。
没有功能的基本代理
用例:一个简单的代理,提供基本信息和问候语,无需任何外部集成或特殊功能。
它的作用: 该代理可以回答简单的问题、提供一般信息并进行基本对话。 无需访问外部 API、搜索 Web 或访问任何 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
}
具有多种功能的代理
用例:知识工作者助手,可在 Web 上搜索信息、访问组织的 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">;
}
卡.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 代理的进展:
每个示例都基于前几个示例,展示了如何添加功能、身份验证和自定义操作,以便为真实场景创建更复杂的代理。
相关内容