DeepSwiftSeek 开源软件 |用于 DeepSeek LLM 模子的 Swift 客户端 |轻量级和高效的 DeepSeek 核心功能通讯

[复制链接]
发表于 2025-6-10 20:17:56 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
DeepSwiftSeek 是一款轻量且高效的 Swift 客户端,用于对接 DeepSeek API,支持聊天完成、FIM 中间填充、流式响应、错误处理,以及模型列表与余额查询,并基于 Swift 并发(async/await)实现网络调用。本文给出集成方式、完整代码示例与可用参数集,帮助 Swift/iOS 开发者快速接入 DeepSeek 模型。

软件介绍与下载

文末提供程序和源码下载。

DeepSeek Swift SDK 是一个轻量级且高效的基于 Swift 的客户端,用于与 DeepSeek API 进行交互。它支持聊天消息完成、流式处理、错误处理以及使用高级参数配置 DeepSeekLLM。

(配图:DeepSwiftSeek Swift 客户端的项目示意)



核心特性 Features


  • Supports chat completion requests
    支持聊天完成请求
  • Supports fill in the middle completion requests
    支持填充中间(FIM)完成请求
  • Handles error responses with detailed error descriptions and recovery suggestions.
    使用详细的错误描述和恢复建议处理错误响应。
  • streaming responses both for chat completion and as well fill in the middle responses
    用于聊天完成的流式处理响应,以及填充中间响应
  • Built-in support for different models and advanced parameters
    内置对不同模型和高级参数的支持
  • User balance fetching and available LLM models fetching
    用户余额获取和可用 LLM 模型获取
  • Uses Swift concurrency (async/await) for network calls
    使用 Swift 并发(async/await)进行网络调用


安装与集成方式

要将 DeepSwiftSeek 集成到你的项目中,可以使用 Swift Package Manager(SPM):
  1. let package = Package(
  2.     dependencies: [
  3.         .package(url: "https://github.com/tornikegomareli/DeepSwiftSeek.git", exact: "0.0.2")
  4.     ]
  5. )
复制代码

或者通过 Xcode 添加它:


  • Open your project in Xcode.
    在 Xcode 中打开你的项目。
  • Navigate to File > Swift Packages > Add Package Dependency.
    导航到 File > Swift Packages > Add Package Dependency。
  • Enter the repository URL.
    输入存储库 URL。
  • Choose the latest version and click Next.
    选择最新版本,然后单击 Next(下一步)。


用法 Usage

1. 初始化客户端 Initialize the Client
  1. import DeepSwiftSeek
  2. let configuration = Configuration(apiKey: "YOUR_API_KEY")
  3. let deepSeekClient = DeepSeekClient(configuration: configuration)
复制代码

2. 发送聊天完成请求 Sending a Chat Completion Request
  1. Task {
  2.     do {
  3.         let response = try await deepSeekClient.chatCompletions(
  4.             messages: {
  5.                 ChatMessageRequest(role: .user, content: "Tell me a joke.", name: "User")
  6.             },
  7.             model: .deepSeekChat,
  8.             parameters: .creative
  9.         )
  10.         print(response.choices.first?.message.content ?? "No response")
  11.     } catch {
  12.         print("Error: \(error.localizedDescription)")
  13.     }
  14. }
复制代码

3. 流式聊天完成 Streaming Chat Completions
  1. Task {
  2.     do {
  3.         let stream = try await deepSeekClient.chatCompletionStream(
  4.             messages: {
  5.                 ChatMessageRequest(role: .user, content: "Write a poem.", name: "User")
  6.             },
  7.             model: .deepSeekChat,
  8.             parameters: .streaming
  9.         )
  10.         for try await chunk in stream {
  11.             print(chunk) // Prints streamed responses
  12.         }
  13.     } catch {
  14.         print("Streaming error: \(error.localizedDescription)")
  15.     }
  16. }
复制代码

4. 流式 FIM 完成 Streaming FIM Completion
  1. Task {
  2.     do {
  3.         let stream = try await deepSeekClient.fimCompletionStream(
  4.             messages: {
  5.                 [
  6.                     ChatMessageRequest(
  7.                       role: .user,
  8.                       content: "function greet() {
  9.   /* FIM_START */
  10.   /* FIM_END */
  11.   return 'Hello world';
  12. }",
  13.                       name: "User"
  14.                     )
  15.                 ]
  16.             },
  17.             model: .deepSeekReasoner,
  18.             parameters: .streaming
  19.         )
  20.         
  21.         for try await chunk in stream {
  22.             // Each chunk is a streamed part of the fill-in-the-middle response.
  23.             print("FIM Stream Chunk:
  24. \(chunk)")
  25.         }
  26.     } catch {
  27.         print("FIM Streaming Error: \(error.localizedDescription)")
  28.     }
  29. }
复制代码

5. 发送 FIM 完成请求 Sending FIM Completion Request
  1. Task {
  2.     do {
  3.         let response = try await deepSeekClient.fimCompletions(
  4.             messages: {
  5.                 [
  6.                     ChatMessageRequest(
  7.                       role: .user,
  8.                       content: "function greet() {
  9.   // FIM_START
  10.   // FIM_END
  11.   return 'Hello world';
  12. }",
  13.                       name: "User"
  14.                     )
  15.                 ]
  16.             },
  17.             model: .deepSeekReasoner,
  18.             parameters: .creative
  19.         )
  20.         if let content = response.choices.first?.message.content {
  21.             print("FIM Completion:
  22. \(content)")
  23.         }
  24.     } catch {
  25.         print("FIM Error: \(error.localizedDescription)")
  26.     }
  27. }
复制代码

6. 获取模型列表 Getting List of Models
  1. Task {
  2.     do {
  3.         let response = try await deepSeekClient.listModels()
  4.     } catch {
  5.         print("ListModels Error: \(error.localizedDescription)")
  6.     }
  7. }
复制代码

7. 获取用户余额 Getting Balance of the user
  1. Task {
  2.     do {
  3.         let response = try await deepSeekClient.fetchUserBalance()
  4.     } catch {
  5.         print("UserBalance Error: \(error.localizedDescription)")
  6.     }
  7. }
复制代码

8. 处理错误 Handling Errors

SDK 提供了详细的错误处理:
  1. catch let error as DeepSeekError {
  2.     print("DeepSeek API Error: \(error.localizedDescription)")
  3.     print("Recovery Suggestion: \(error.recoverySuggestion ?? "None")")
  4. } catch {
  5.     print("Unexpected error: \(error)")
  6. }
复制代码

支持的模型与参数

DeepSeek SDK 支持多种模型:
  1. public enum DeepSeekModel: String {
  2.     case deepSeekChat = "deepseek-chat"
  3.     case deepSeekReasoner = "deepseek-reasoner"
  4. }
复制代码

可用参数 Available Parameters

你可以配置聊天完成参数:
  1. let parameters = ChatParameters(
  2.     frequencyPenalty: 0.5,
  3.     maxTokens: 512,
  4.     presencePenalty: 0.5,
  5.     temperature: 0.7,
  6.     topP: 0.9
  7. )
复制代码

预定义参数集 Predefined Parameter Sets

模式 Mode温度 Temperature最大令牌数 Max Tokens前 P Top PCreative 创造性0.920480.9Focused 集中0.320480.3Streaming 流0.740960.9Code Generation 代码生成0.220480.95Concise 简明0.52560.5

创建自定义预定义参数 Creating Custom Predefined Parameters

如果你需要特定配置,可以定义自己的参数预设:
  1. extension ChatParameters {
  2.     static let myCustomPreset = ChatParameters(
  3.         frequencyPenalty: 0.4,
  4.         maxTokens: 1024,
  5.         presencePenalty: 0.6,
  6.         temperature: 0.8,
  7.         topP: 0.85
  8.     )
  9. }
复制代码

然后在你的请求中使用它:
  1. let parameters = ChatParameters.myCustomPreset
复制代码

此方法允许你维护针对不同需求量身定制的可复用配置。

错误处理 Error Handling

DeepSeek SDK 内置了针对各种 API 故障的错误处理功能:

错误类型 Error Type描述 DescriptioninvalidFormatInvalid request body format.
请求正文格式无效。authenticationFailedIncorrect API key.
API 密钥不正确。insufficientBalanceNo balance remaining.
没有余额。rateLimitReachedToo many requests sent.
发送的请求过多。serverOverloadedHigh traffic on server.
服务器上的高流量。encodingErrorFailed to encode request body.
无法对请求正文进行编码。

待办 TODOs


  • Improve documentation with more examples
    通过更多示例改进文档
  • SwiftUI full demo based on chat, history and reasoning
    基于聊天、历史记录和推理的 SwiftUI 完整演示
  • Reasoning model + OpenAI SDK
    推理模型 + OpenAI SDK


软件下载

迅雷云盘
本文信息来源于 GitHub 作者地址:GitHub - tornikegomareli/DeepSwiftSeek: DeepSwiftSeek

小结与易踩坑

- 接入时务必把 `YOUR_API_KEY` 替换为真实密钥,并避免硬编码到仓库中,建议通过配置或环境变量注入。
- 流式接口(chatCompletionStream / fimCompletionStream)需使用 `for try await` 消费异步序列,错误请用 `DeepSeekError` 细粒度捕获并处理 `recoverySuggestion`。
- FIM(填充中间)接口配合 `deepseek-reasoner` 模型使用时,注意 `/* FIM_START */` 与 `/* FIM_END */` 标记的位置,模型会补全二者之间的内容。
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表