内容
# AgentKit
一款用于构建 AI 代理的 Swift 框架,支持 Amazon Bedrock 和 Model Context Protocol (MCP)。AgentKit 简化了创建可使用工具和与 MCP 服务器集成的对话式 AI 代理的过程。
## 概述
AgentKit 提供了一个高级别的 API,用于构建 AI 代理,可以:
- 使用 Amazon Bedrock 模型进行对话
- 使用本地工具执行操作
- 连接到远程 MCP 服务器以扩展功能
- 无缝处理身份验证和配置
## 要求
- macOS 15 或更高版本
- Swift 6.2 或更高版本
- 已配置 AWS 凭证
## 安装
将 AgentKit 添加到您的 Swift 包中:
```swift
dependencies: [
.package(url: "https://github.com/sebsto/AgentKit", from: "1.0.0")
]
```
## 1. 简单代理
使用最小化设置创建基本对话代理:
```swift
import AgentKit
// 简单的一行代码 - 代理响应 stdout
try await Agent("告诉我关于 Swift 6")
// 两步法
let agent = try await Agent()
try await agent("告诉我关于 Swift 6")
// 自定义身份验证和区域
try await Agent(
"告诉我关于 Swift 6",
auth: .sso("my-profile"),
region: .eucentral1
)
// 自定义输出处理回调
let agent = try await Agent()
try await agent("告诉我关于 Swift 6") { event in
print(event, terminator: "")
}
// 流式方法
let agent = try await Agent()
for try await event in agent.streamAsync("告诉我关于 Swift 6") {
switch event {
case .text(let text):
print(text, terminator: "")
default:
break
}
}
```
## 2. 工具
创建代理可以使用的工具来执行特定操作。工具使用 `@Tool` 宏定义。
**重要**:`handle` 函数参数和 `@SchemaDefinition` 结构体属性的 Swift DocC 注释至关重要 - 它们成为 AI 模型理解如何正确调用工具的工具描述。
### 简单字符串工具
```swift
import AgentKit
@Tool(
name: "weather",
description: "获取城市的详细天气信息。"
)
struct WeatherTool {
/// 获取特定城市的天气信息
/// - 参数 input: 获取天气的城市名称
func handle(input city: String) async throws -> String {
let weatherURL = "http://wttr.in/\(city)?format=j1"
let url = URL(string: weatherURL)!
let (data, _) = try await URLSession.shared.data(from: url)
return String(decoding: data, as: UTF8.self)
}
}
```
### 复杂结构化工具
```swift
import AgentKit
@SchemaDefinition
struct CalculatorInput: Codable {
/// 操作的第一个操作数
let a: Double
/// 操作的第二个操作数
let b: Double
/// 算术操作: "add", "subtract", "multiply", "divide"
let operation: String
}
@Tool(
name: "calculator",
description: "执行基本算术操作",
schema: CalculatorInput.self
)
struct CalculatorTool {
func handle(input: CalculatorInput) async throws -> Double {
switch input.operation {
case "add":
return input.a + input.b
case "subtract":
return input.a - input.b
case "multiply":
return input.a * input.b
case "divide":
guard input.b != 0 else {
throw MCPServerError.invalidParam("b", "不能除以零")
}
return input.a / input.b
default:
throw MCPServerError.invalidParam("operation", "未知操作:\(input.operation)")
}
}
}
```
### 货币兑换工具
```swift
import AgentKit
@SchemaDefinition
struct FXRatesInput: Codable {
/// 源货币代码(例如,USD,EUR,GBP)
let sourceCurrency: String
/// 目标货币代码(例如,USD,EUR,GBP)
let targetCurrency: String
}
@Tool(
name: "foreign_exchange_rates",
description: "获取两种货币之间的当前外汇汇率",
schema: FXRatesInput.self
)
struct FXRateTool {
func handle(input: FXRatesInput) async throws -> String {
let fxURL = "https://hexarate.paikama.co/api/rates/latest/\(input.sourceCurrency)?target=\(input.targetCurrency)"
let url = URL(string: fxURL)!
let (data, _) = try await URLSession.shared.data(from: url)
return String(decoding: data, as: UTF8.self)
}
}
```
## 3. 代理 + 工具
将代理与本地工具结合使用以增强功能:
```swift
import AgentKit
// 创建具有多个工具的代理
let agent = try await Agent(tools: [
WeatherTool(),
FXRateTool(),
CalculatorTool()
])
// 通过自然对话使用工具
try await agent("今天巴黎的天气怎么样?")
try await agent("100 美元兑换欧元是多少?")
try await agent("15 * 23 等于多少?")
```
## 4. 将工具暴露为 MCP 服务器
通过创建 MCP 服务器与其他应用程序共享工具:
### STDIO 服务器
```swift
import AgentKit
@main
struct MyMCPServer {
static func main() async throws {
try await MCPServer.withMCPServer(
name: "MyToolServer",
version: "1.0.0",
transport: .stdio,
tools: [
WeatherTool(),
CalculatorTool(),
FXRateTool()
]
) { server in
try await server.run()
}
}
}
```
### HTTP 服务器
```swift
import AgentKit
@main
struct MyHTTPServer {
static func main() async throws {
try await MCPServer.withMCPServer(
name: "MyToolServer",
version: "1.0.0",
transport: .http(port: 8080),
tools: [
WeatherTool(),
CalculatorTool(),
FXRateTool()
]
) { server in
try await server.run()
}
}
}
```
### 带有提示的服务器
```swift
import AgentKit
let weatherPrompt = try! MCPPrompt.build { builder in
builder.name = "current-weather"
builder.description = "获取城市的当前天气"
builder.text("今天\(city)的天气怎么样?")
builder.parameter("city", description: "城市名称")
}
@main
struct MyServerWithPrompts {
static func main() async throws {
try await MCPServer.withMCPServer(
name: "MyToolServer",
version: "1.0.0",
transport: .stdio,
tools: [WeatherTool()],
prompts: [weatherPrompt]
) { server in
try await server.run()
}
}
}
```
## 5. 代理 + MCP 服务器
将代理连接到远程 MCP 服务器以扩展功能:
### 使用配置文件
创建 JSON 配置文件(`mcp-config.json`):
```json
{
"mcpServers": {
"weather-server": {
"command": "./weather-server",
"args": [],
"disabled": false,
"timeout": 60000
},
"calculator-server": {
"url": "http://127.0.0.1:8080/mcp",
"disabled": false,
"timeout": 60000
}
}
}
```
使用配置文件:
```swift
import AgentKit
let configFile = URL(fileURLWithPath: "./mcp-config.json")
let agent = try await Agent(mcpConfigFile: configFile)
print("代理有 \(agent.tools.count) 个可用工具")
agent.tools.forEach { tool in
print("- \(tool.toolName)")
}
try await agent("伦敦的天气怎么样?25 * 4 等于多少?")
```
### 使用 MCPServerConfiguration
```swift
import AgentKit
let config = MCPServerConfiguration()
config.addServer(
name: "weather-server",
command: "./weather-server",
args: []
)
config.addServer(
name: "calculator-server",
url: "http://127.0.0.1:8080/mcp"
)
let agent = try await Agent(mcpConfig: config)
try await agent("获取柏林的天气并计算 100 * 1.2")
```
### 直接使用 MCPClient
```swift
import AgentKit
// 创建单个 MCP 客户端
let weatherClient = try await MCPClient(
command: "./weather-server",
args: [],
name: "weather-server"
)
let calculatorClient = try await MCPClient(
url: "http://127.0.0.1:8080/mcp",
name: "calculator-server"
)
// 将客户端与代理一起使用
let agent = try await Agent(mcpTools: [weatherClient, calculatorClient])
try await agent("东京的天气怎么样?50 除以 2 等于多少?")
```
### 混合本地和远程工具
```swift
import AgentKit
let agent = try await Agent(
tools: [WeatherTool()], // 本地工具
mcpConfigFile: URL(fileURLWithPath: "./remote-servers.json") // 远程工具
)
try await agent("比较巴黎的天气和欧元汇率")
```
## 6. 身份验证
AgentKit 支持多种 AWS 身份验证方法:
### 默认凭证链
```swift
let agent = try await Agent(auth: .default)
```
### AWS SSO
```swift
let agent = try await Agent(auth: .sso("my-sso-profile"))
// 或使用默认配置文件
let agent = try await Agent(auth: .sso(nil))
```
### 命名配置文件
```swift
let agent = try await Agent(auth: .profile("my-aws-profile"))
```
### 临时凭证
```swift
let agent = try await Agent(auth: .tempCredentials("/path/to/credentials.json"))
```
临时凭证文件应包含:
```json
{
"accessKeyId": "AKIA...",
"secretAccessKey": "...",
"sessionToken": "...",
"expiration": "2024-01-01T00:00:00Z"
}
```
### 自定义区域
```swift
let agent = try await Agent(
auth: .sso("my-profile"),
region: .eucentral1
)
```
## 高级配置
### 自定义模型
```swift
let agent = try await Agent(
model: .claude_haiku_v3,
auth: .sso("my-profile")
)
```
### 系统提示
```swift
let agent = try await Agent(
systemPrompt: "您是一个专门研究天气和金融的 helpful assistant。",
tools: [WeatherTool(), FXRateTool()]
)
```
### 自定义日志记录
```swift
import Logging
var logger = Logger(label: "MyAgent")
logger.logLevel = .debug
let agent = try await Agent(
tools: [WeatherTool()],
logger: logger
)
```
## 示例
`Example` 目录包含完整的示例:
- **AgentClient**:演示各种代理用法模式
- **MCPServer**:展示如何创建带有工具的 MCP 服务器
- **MCPClient**:说明如何连接到远程 MCP 服务器
构建和运行示例:
```bash
cd Example
swift build
.build/debug/AgentClient
.build/debug/MCPServer
.build/debug/MCPClient
```
## 许可证
该项目根据 MIT 许可证授权 - 有关详细信息,请参见 [LICENSE](LICENSE) 文件。
连接信息
猜你喜欢
暂无推荐服务器