Token导航 LogoToken导航TokenDH.com
Swift Open AI Agentic logo
AI代理未说明官方级别未说明来源级核验

Swift Open AI Agentic

MCP Server

SwiftOpenAIAgentic是一个用于构建支持工具调用的AI代理的Swift SDK,提供生产就绪的API,支持MCP集成和自定义工具开发。

工具数

0

提示词数

0

GitHub Stars

4

资源数

0
AI代理Swift本地部署

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

作者 / 组织

mfreiwald

提供方

mfreiwald

最后核验

2026/5/17 20:21

快速接入

先看主来源和安装命令,再打开仓库或文档;下面只保留这个条目的关键接入事实。

详细介绍

SwiftOpenAIAgentic(可译为“Swift OpenAI 代理系统”或根据具体上下文简化为“Swift OpenAI 代理”)

一个用于构建支持工具调用的AI代理的Swift SDK。SwiftOpenAIAgentic提供了一个简洁、可投入生产的API,用于创建集成MCP(模型上下文协议)和自定义工具支持的LLM(大型语言模型)驱动应用程序。

特点/特性

  • OpenAI 工具调用 - 完全支持GPT-4、GPT-5及其他模型的功能调用
  • MCP集成 - 原生支持模型上下文协议服务器(HTTP传输)
  • 本地工具 - 作为工具执行shell命令和脚本
  • 自定义工具 - 便于实施的协议,用于自定义工具开发
  • 流媒体支持 - 实时流式传输最终响应以提升用户体验
  • 多轮对话 - 在多轮对话中保持对话历史记录
  • 事件委托 - 跟踪工具执行和代理事件
  • 线程安全 - 使用 Swift 并发功能(异步/等待,actor)构建
  • 已准备好投入生产 - 错误处理、取消支持和资源清理

要求

  • Swift 6.1及以上版本
  • macOS 15及以上版本 / iOS 18及以上版本
  • OpenAI API密钥

安装

Swift 包管理器

将 SwiftOpenAIAgentic 添加到您的 Package.swift:

dependencies: [
    .package(url: "https://github.com/mfreiwald/SwiftOpenAIAgentic.git", from: "1.0.0")
]

快速入门

基础聊天(无工具)

import SwiftOpenAIAgentic

let agenticAI = AgenticAI(apiKey: "your-openai-api-key")

let conversation = try await agenticAI.chat(
    message: "What is 2 + 2?",
    model: "gpt-4o-mini"
)

print(conversation.last?.content ?? "")

配备MCP工具的代理

import SwiftOpenAIAgentic

// Configure MCP server
let mcpServer = MCPServerConfig(
    name: "filesystem",
    transport: "http",
    url: "https://your-mcp-server.com/mcp"
)

let config = AgenticConfiguration(
    mcpServers: [mcpServer]
)

let agenticAI = AgenticAI(apiKey: "your-api-key", configuration: config)

// Initialize (connects to MCP servers)
await agenticAI.initialize()

// Chat with tools enabled
let conversation = try await agenticAI.chat(
    message: "List files in the current directory",
    model: "gpt-4o",
    enabledTools: ["mcp__*"] // Enable all MCP tools
)

print(conversation.last?.content ?? "")

await agenticAI.cleanup()

使用委托进行事件处理

class MyDelegate: AgentServiceDelegate {
    func agentService(_ service: AgentService, willExecuteTool toolName: String, arguments: String, toolCallId: String) {
        print("🔧 Executing: \(toolName)")
    }

    func agentService(_ service: AgentService, didExecuteTool toolName: String, result: String, toolCallId: String) {
        print("✅ Completed: \(toolName)")
    }

    func agentService(_ service: AgentService, didReceiveFinalResponse response: String) {
        print("💬 Response: \(response)")
    }

    func agentService(_ service: AgentService, didReceiveStreamContent content: String) {
        print(content, terminator: "")
    }

    func agentService(_ service: AgentService, didEncounterError error: Error) {
        print("❌ Error: \(error)")
    }
}

let agenticAI = AgenticAI(apiKey: "your-api-key")
let delegate = MyDelegate()
agenticAI.setAgentDelegate(delegate)

_ = try await agenticAI.chat(
    message: "Your message here",
    model: "gpt-4o",
    enableStreaming: true
)

多轮对话

var conversation: [ChatCompletionParameters.Message] = []

// First turn
conversation = try await agenticAI.chat(
    message: "What is the capital of France?",
    model: "gpt-4o-mini"
)

// Second turn - pass conversation history
conversation = try await agenticAI.chat(
    message: "What is its population?",
    model: "gpt-4o-mini",
    conversationHistory: conversation
)

自定义工具

import SwiftOpenAIAgentic
import SwiftOpenAI

class CalculatorTool: Tool {
    let name = "local__calculator"
    let description = "Perform basic arithmetic"

    var parameters: JSONSchema {
        JSONSchema(
            type: .object,
            properties: [
                "operation": JSONSchema(type: .string),
                "a": JSONSchema(type: .number),
                "b": JSONSchema(type: .number)
            ],
            required: ["operation", "a", "b"]
        )
    }

    func execute(arguments: String) async throws -> String {
        // Parse arguments and perform calculation
        // Return result as string
        return "Result: 42"
    }
}

let agenticAI = AgenticAI(apiKey: "your-api-key")
agenticAI.registerTool(CalculatorTool())

let conversation = try await agenticAI.chat(
    message: "Calculate 123 * 456",
    model: "gpt-4o-mini",
    enabledTools: ["local__calculator"]
)

建筑

SwiftOpenAIAgentic 基于几个关键组件构建:

核心组件

  • AgenticAI(可译为“代理智能AI”或根据具体语境简化为“智能代理AI”) 主入口点,高级API
  • AgentService(可译为“代理服务”) - 协调工具调用循环
  • 工具执行器 - 工具的中央注册表和执行引擎
  • 工具协议 - 所有工具(MCP、本地、自定义)的接口

MCP 集成

  • MCPClient 翻译成中文是“MCP客户端” - 基于Actor的MCP服务器连接管理器
  • MCP工具适配器 - 将MCP工具桥接到SwiftOpenAIAgentic Tool协议
  • MCPServerConfig 翻译为中文是“MCPServer配置” - MCP服务器的配置

本地工具

  • 本地工具 - 执行Shell命令和脚本
  • LocalToolsConfig 翻译成中文是“本地工具配置” - 基于JSON的工具配置

配置

代理配置

let config = AgenticConfiguration(
    baseURL: "https://api.openai.com/v1", // Optional: Custom base URL
    debugEnabled: false,                   // Enable debug logging
    mcpServers: [mcpServer1, mcpServer2], // MCP servers to connect
    localToolsConfigPath: "tools.json"    // Path to local tools config
)

let agenticAI = AgenticAI(apiKey: "key", configuration: config)

工具过滤

使用名称或通配符模式启用特定工具:

// Enable all MCP tools
enabledTools: ["mcp__*"]

// Enable specific tool
enabledTools: ["mcp__filesystem__read_file"]

// Enable all tools from specific server
enabledTools: ["mcp__github__*"]

// Mix MCP and local tools
enabledTools: ["mcp__*", "local__grep"]

高级用法

取消

let agenticAI = AgenticAI(apiKey: "key")

// Start long-running operation
Task {
    _ = try await agenticAI.chat(message: "Long task", model: "gpt-4o")
}

// Cancel from another context
agenticAI.cancel()

运行时MCP服务器管理

// Connect to server at runtime
try await agenticAI.connectMCPServer(newServerConfig)

// Disconnect from server
await agenticAI.disconnectMCPServer("servername")

// Get available tools
let tools = agenticAI.getAvailableTools()
print("MCP Tools: \(tools.mcpTools.count)")
print("Local Tools: \(tools.localTools.count)")

状态回调

agenticAI.setToolExecutorStatusCallback { message in
    print("📡 \(message)")
}

agenticAI.setToolExecutorEventCallback { event in
    switch event {
    case .executionStarted(let tool, let args):
        print("Starting: \(tool)")
    case .executionCompleted(let tool, let result):
        print("Completed: \(tool)")
    case .executionFailed(let tool, let error):
        print("Failed: \(tool) - \(error)")
    }
}

示例

查看 示例 包含完整、可运行示例的目录:

  • 基本示例 - 所有核心功能均已展示
  • 更多示例即将推出!

MCP服务器支持

SwiftOpenAIAgentic 目前支持:

  • ✅ HTTP传输(包括Zapier MCP服务器)
  • ⏳ 标准I/O传输(即将推出 - 需要进程包装器)

设置MCP服务器

对于基于HTTP的MCP服务器(例如,Zapier):

let server = MCPServerConfig(
    name: "zapier",
    transport: "http",
    url: "https://actions.zapier.com/mcp/v1/servers/YOUR_ID"
)

贡献;助力

欢迎贡献!请随时提交拉取请求。

许可证

\[此处填写您的许可证\]

功劳/贡献

SwiftOpenAIAgentic 从(某事物)中汲取灵感并提取了核心功能 SwiftOpenAICLI(可翻译为“Swift OpenAI 命令行接口”或“Swift OpenAI CLI”,具体根据上下文选择更贴切的表述),已适配为通用SDK使用。

依赖项

目录标签

目录标签

AI代理Swift本地部署工具调用MCP集成Swift开发多轮对话

接入字段

传输方式(transport,传输协议)

未说明

鉴权方式(authType,认证方式)

none

工具数量(toolCount,工具数)

0

资源数量(resourceCount,资源数)

0

提示词数量(promptCount,提示词数)

0

权限和风险

未说明none部署方式未说明

接入前请确认传输方式、认证方式和部署位置,并根据实际工具能力限制访问范围。

安装前确认

不要直接授予不必要的文件、网络或账号权限;先核对安装命令和配置内容。

仍需确认:installCommand

来源信息

继续浏览同类 MCP