### DeepSeekKit CLI Usage Examples Source: https://context7.com/guitaripod/deepseekkit/llms.txt Examples of using the DeepSeekKit command-line tool for various tasks including simple chat, streaming, reasoning, function calling, checking balance, listing models, and Docker usage. ```bash # Build the CLI swift build -c release cp .build/release/deepseek-cli /usr/local/bin/ ``` ```bash # Set API key export DEEPSEEK_API_KEY="your-api-key" ``` ```bash # Simple chat deepseek-cli chat "What is the capital of France?" ``` ```bash # Streaming response deepseek-cli stream "Tell me a story" --temperature 0.8 ``` ```bash # Use reasoning model deepseek-cli reasoning "Prove that sqrt(2) is irrational" --show-tokens ``` ```bash # Function calling deepseek-cli function-call "What's the weather in Tokyo?" --auto ``` ```bash # Check balance deepseek-cli balance ``` ```bash # List models deepseek-cli models ``` ```bash # Docker usage docker build -t deepseek-kit . docker run --rm -e DEEPSEEK_API_KEY="your-key" deepseek-kit chat "Hello from Docker!" ``` -------------------------------- ### Stream Chat Completion Responses Source: https://context7.com/guitaripod/deepseekkit/llms.txt Implement real-time UI updates or long-form content generation by streaming tokens as they are generated. This example shows how to iterate over streaming chunks and print content as it arrives. ```swift import DeepSeekKit let client = DeepSeekClient(apiKey: "your-api-key") let request = ChatCompletionRequest( model: .chat, messages: [ .system("You are a helpful assistant"), .user("Tell me a short story about a robot") ], stream: true ) var fullResponse = "" // Iterate over streaming chunks for try await chunk in client.chat.createStreamingCompletion(request) { if let content = chunk.choices.first?.delta.content { fullResponse += content print(content, terminator: "") // Print without newline for real-time effect fflush(stdout) } // Usage statistics in final chunk if let usage = chunk.usage { print("\n\nTotal tokens used: \(usage.totalTokens)") } } print("\n\nFull response: \(fullResponse)") ``` -------------------------------- ### Manage Multi-Turn Conversations Source: https://context7.com/guitaripod/deepseekkit/llms.txt Build conversational applications by maintaining message history across multiple turns. Includes an example of managing context window by limiting history. ```swift import DeepSeekKit let client = DeepSeekClient(apiKey: "your-api-key") var conversationHistory: [ChatMessage] = [ .system("You are a helpful assistant that remembers our conversation.") ] // First turn conversationHistory.append(.user("My name is Alice")) var response = try await client.chat.createCompletion( ChatCompletionRequest(model: .chat, messages: conversationHistory) ) let assistantReply1 = response.choices.first?.message.content ?? "" conversationHistory.append(.assistant(assistantReply1)) print("Assistant: \(assistantReply1)") // Second turn - assistant remembers context conversationHistory.append(.user("What's my name?")) response = try await client.chat.createCompletion( ChatCompletionRequest(model: .chat, messages: conversationHistory) ) let assistantReply2 = response.choices.first?.message.content ?? "" conversationHistory.append(.assistant(assistantReply2)) print("Assistant: \(assistantReply2)") // Output: Your name is Alice. ``` ```swift // Manage context window by limiting history func trimConversation(_ messages: [ChatMessage], maxMessages: Int) -> [ChatMessage] { guard messages.count > maxMessages else { return messages } // Keep system message and recent messages let systemMessages = messages.filter { $0.role == .system } let recentMessages = Array(messages.suffix(maxMessages - systemMessages.count)) return systemMessages + recentMessages } ``` -------------------------------- ### Create Simple Chat Completion Source: https://context7.com/guitaripod/deepseekkit/llms.txt Send a simple message to the chat model to get an AI-generated response. Ensure you have the 'DEEPSEEK_API_KEY' environment variable set or replace it with your actual API key. ```swift import DeepSeekKit let client = DeepSeekClient(apiKey: "your-api-key") // Simple chat completion let response = try await client.chat.createCompletion( ChatCompletionRequest( model: .chat, messages: [ .system("You are a helpful assistant"), .user("What is the capital of France?") ] ) ) print(response.choices.first?.message.content ?? "") // Output: The capital of France is Paris. // Access usage statistics let usage = response.usage print("Prompt tokens: \(usage.promptTokens)") print("Completion tokens: \(usage.completionTokens)") print("Total tokens: \(usage.totalTokens)") ``` -------------------------------- ### Initialize DeepSeekClient Source: https://context7.com/guitaripod/deepseekkit/llms.txt Initialize the main DeepSeekClient with your API key. You can load the key from environment variables or provide it directly. Custom configurations for base URL and URLSession are also supported. ```swift import DeepSeekKit // Initialize with API key from environment guard let apiKey = ProcessInfo.processInfo.environment["DEEPSEEK_API_KEY"] else { fatalError("Please set DEEPSEEK_API_KEY environment variable") } let client = DeepSeekClient(apiKey: apiKey) // Or with custom configuration let customClient = DeepSeekClient( apiKey: "your-api-key", baseURL: URL(string: "https://api.deepseek.com/v1")!, session: URLSession.shared ) // Access services // client.chat - Chat completions and streaming // client.models - List available models // client.balance - Check account balance ``` -------------------------------- ### Build DeepSeek Docker Image Source: https://github.com/guitaripod/deepseekkit/blob/master/README.md Create a Docker image for the DeepSeekKit project using the provided Dockerfile. ```bash # Build and run docker build -t deepseek-kit . docker run --rm -e DEEPSEEK_API_KEY="your-key" deepseek-kit chat "Hello from Docker!" ``` -------------------------------- ### Initialize DeepSeekClient and Create Basic Chat Completion Source: https://github.com/guitaripod/deepseekkit/blob/master/Sources/DeepSeekKit/DeepSeekKit.docc/DeepSeekKit.md Initialize the DeepSeekClient with your API key and create a basic chat completion request. Ensure you have your API key available. ```swift import DeepSeekKit // Initialize the client let client = DeepSeekClient(apiKey: "your-api-key") // Create a simple chat completion let response = try await client.chat.createCompletion( ChatCompletionRequest( model: .chat, messages: [.user("Hello, DeepSeek!")] ) ) print(response.choices.first?.message.content ?? "") ``` -------------------------------- ### Use DeepSeek CLI for Streaming Source: https://github.com/guitaripod/deepseekkit/blob/master/README.md Initiate a streaming chat session via the CLI. The --show-reasoning flag can be used to see the model's thought process. ```bash deepseek-cli stream "Tell me a story" --show-reasoning ``` -------------------------------- ### Create Reasoning Model Completion Source: https://github.com/guitaripod/deepseekkit/blob/master/README.md Utilize the reasoning model for step-by-step problem-solving. Requires specifying the .reasoner model. ```swift // Reasoning model let reasoning = try await client.chat.createCompletion( ChatCompletionRequest( model: .reasoner, messages: [.user("Solve: 2 + 2 * 3")] ) ) ``` -------------------------------- ### Build DeepSeek CLI Source: https://github.com/guitaripod/deepseekkit/blob/master/README.md Compile the DeepSeekKit CLI tool in release mode and copy the executable to your system's PATH. ```bash # Install swift build -c release cp .build/release/deepseek-cli /usr/local/bin/ ``` -------------------------------- ### Use DeepSeek CLI for Chat Source: https://github.com/guitaripod/deepseekkit/blob/master/README.md Interact with the DeepSeek API using the CLI. Set your API key as an environment variable first. ```bash # Use export DEEPSEEK_API_KEY="your-key" deepseek-cli chat "Hello!" ``` -------------------------------- ### Create Chat Messages with Convenience Methods Source: https://context7.com/guitaripod/deepseekkit/llms.txt Use static factory methods for cleaner message creation in conversations. Supports system, user, assistant, and tool messages. ```swift import DeepSeekKit // Convenience initializers for messages let messages: [ChatMessage] = [ .system("You are a helpful coding assistant"), .user("How do I sort an array in Swift?"), .assistant("You can use the sorted() method. Here's an example..."), .user("Can you show me with custom comparators?") ] ``` ```swift // Tool message for function calling responses let toolMessage = ChatMessage.tool( content: "{\"temperature\": 72, \"condition\": \"sunny\"}", toolCallId: "call_abc123", name: "get_weather" ) ``` ```swift // Full message with all options let fullMessage = ChatMessage( role: .user, content: "Hello!", name: nil, toolCallId: nil, toolCalls: nil, prefix: nil ) ``` -------------------------------- ### Use DeepSeek Reasoner Model Source: https://context7.com/guitaripod/deepseekkit/llms.txt Utilize the DeepSeek Reasoner model for complex problem-solving that requires step-by-step explanations. Ensure sufficient `maxTokens` are allocated for detailed reasoning processes. ```swift import DeepSeekKit let client = DeepSeekClient(apiKey: "your-api-key") // Solve a complex math problem let response = try await client.chat.createCompletion( ChatCompletionRequest( model: .reasoner, // Use reasoning model messages: [.user("Prove that the sum of angles in a triangle is 180 degrees")], maxTokens: 32768 // Reasoning may need more tokens ) ) if let message = response.choices.first?.message { // Access the reasoning process if let reasoning = message.reasoningContent { print("Reasoning Process:") print(reasoning) print("\n---\n") } // Access the final answer if let content = message.content { print("Final Answer:") print(content) } } ``` ```swift // Streaming with reasoning model for try await chunk in client.chat.createStreamingCompletion( ChatCompletionRequest( model: .reasoner, messages: [.user("Solve: If 3x + 7 = 22, what is x?")], stream: true ) ) { if let delta = chunk.choices.first?.delta { // Reasoning content streams separately if let reasoning = delta.reasoningContent { print("[Reasoning: \(reasoning)]", terminator: "") } if let content = delta.content { print(content, terminator: "") } } } ``` -------------------------------- ### List Available Models with DeepSeekKit Source: https://context7.com/guitaripod/deepseekkit/llms.txt Query the API to retrieve a list of available models and their properties, such as ID, owner, and creation date. ```swift import DeepSeekKit let client = DeepSeekClient(apiKey: "your-api-key") let models = try await client.models.listModels() for model in models { print("Model ID: \(model.id)") print("Owned by: \(model.ownedBy)") if let created = model.created { print("Created: \(Date(timeIntervalSince1970: TimeInterval(created)))") } print("---") } // Available models: // - deepseek-chat: Standard chat model for general conversations // - deepseek-reasoner: Advanced reasoning model for complex problems ``` -------------------------------- ### Create Advanced Chat Completion with Parameters Source: https://context7.com/guitaripod/deepseekkit/llms.txt Utilize advanced parameters like temperature, maxTokens, topP, frequencyPenalty, and presencePenalty to fine-tune the AI's response for creative storytelling or specific output requirements. ```swift import DeepSeekKit let client = DeepSeekClient(apiKey: "your-api-key") // Advanced chat with parameters let advancedResponse = try await client.chat.createCompletion( ChatCompletionRequest( model: .chat, messages: [ .system("You are a creative storyteller"), .user("Write a short poem about Swift programming") ], temperature: 0.8, // Higher for more creativity (0-2) maxTokens: 500, // Limit response length topP: 0.9, // Nucleus sampling frequencyPenalty: 0.5, // Reduce repetition presencePenalty: 0.5 // Encourage new topics ) ) ``` -------------------------------- ### Define Function for AI Source: https://github.com/guitaripod/deepseekkit/blob/master/README.md Build a tool definition for function calling, specifying its name, description, and parameters. ```swift // Function calling let weatherTool = FunctionBuilder( name: "get_weather", description: "Get the current weather" ) .addStringParameter("location", description: "City name", required: true) .buildTool() ``` -------------------------------- ### Check DeepSeek CLI Balance Source: https://github.com/guitaripod/deepseekkit/blob/master/README.md Query your DeepSeek API account balance using the CLI command 'balance'. ```bash deepseek-cli balance ``` -------------------------------- ### FIM Code Completion with DeepSeekKit Source: https://context7.com/guitaripod/deepseekkit/llms.txt Utilize the FIM completion API by providing prefix and suffix code for context-aware code generation. Set temperature to 0.0 for deterministic output. ```swift import DeepSeekKit let client = DeepSeekClient(apiKey: "your-api-key") // Code completion with context let response = try await client.chat.createCompletion( CompletionRequest( model: .chat, prompt: "func calculateArea(width: Double, height: Double) -> Double {\n ", suffix: "\n}\n\nlet area = calculateArea(width: 5, height: 3)", maxTokens: 100, temperature: 0.0 // Deterministic for code ) ) if let completion = response.choices.first?.text { print("Generated code:") print("func calculateArea(width: Double, height: Double) -> Double {") print(" \(completion)") print("}") } // Output: return width * height ``` -------------------------------- ### Create Chat Completion Source: https://github.com/guitaripod/deepseekkit/blob/master/README.md Use the DeepSeekClient to create a chat completion request. Ensure you have your API key configured. ```swift import DeepSeekKit let client = DeepSeekClient(apiKey: "your-api-key") // Chat let response = try await client.chat.createCompletion( ChatCompletionRequest( model: .chat, messages: [.user("What is the capital of France?")] ) ) ``` -------------------------------- ### Define Tools with FunctionBuilder Source: https://context7.com/guitaripod/deepseekkit/llms.txt Define external tools for AI agents using FunctionBuilder. This allows for automatic argument parsing and tool selection by the model. ```swift import DeepSeekKit let client = DeepSeekClient(apiKey: "your-api-key") // Define tools using FunctionBuilder let weatherTool = FunctionBuilder( name: "get_weather", description: "Get the current weather in a given location" ) .addStringParameter("location", description: "City and state, e.g. San Francisco, CA", required: true) .addStringParameter("unit", description: "Temperature unit (celsius or fahrenheit)", required: false) .buildTool() let calculatorTool = FunctionBuilder( name: "calculate", description: "Perform mathematical calculations" ) .addStringParameter("expression", description: "The mathematical expression to evaluate", required: true) .buildTool() ``` -------------------------------- ### Use Reasoning Model for Complex Queries Source: https://github.com/guitaripod/deepseekkit/blob/master/Sources/DeepSeekKit/DeepSeekKit.docc/DeepSeekKit.md Utilize the reasoning model for tasks requiring advanced multi-step reasoning. Access both the reasoning process and the final answer from the response. ```swift // Leverage advanced reasoning capabilities let response = try await client.chat.createCompletion( ChatCompletionRequest( model: .reasoner, messages: [.user("Solve: If a train travels 120 km in 2 hours, what is its average speed?")] ) ) // Access reasoning content if let reasoningContent = response.choices.first?.message.reasoningContent { print("Reasoning process: \(reasoningContent)") } print("Answer: \(response.choices.first?.message.content ?? "")") ``` -------------------------------- ### Handle Function Calls with Tool Calls Source: https://context7.com/guitaripod/deepseekkit/llms.txt Process tool calls returned by the model, extract function names and arguments, execute the functions, and continue the conversation with the results. ```swift // Make request with tools let response = try await client.chat.createCompletion( ChatCompletionRequest( model: .chat, messages: [.user("What's the weather in London and what's 15 * 7?")], tools: [weatherTool, calculatorTool], toolChoice: .auto // Let model decide which tools to use ) ) // Handle tool calls if let toolCalls = response.choices.first?.message.toolCalls { for call in toolCalls { print("Function: \(call.function.name)") print("Arguments: \(call.function.arguments)") // Parse arguments and execute function // Then continue conversation with results } // Continue conversation with tool results var messages: [ChatMessage] = [.user("What's the weather in London?")] // Add assistant message with tool calls messages.append(.assistant( response.choices.first?.message.content ?? "", toolCalls: toolCalls )) // Add tool results for call in toolCalls { let result = executeFunction(name: call.function.name, args: call.function.arguments) messages.append(.tool( content: result, toolCallId: call.id, name: call.function.name )) } // Get final response let finalResponse = try await client.chat.createCompletion( ChatCompletionRequest(model: .chat, messages: messages) ) print(finalResponse.choices.first?.message.content ?? "") } ``` ```swift // Tool choice options // .auto - Model decides whether to call functions // .none - Disable function calling // .required - Force the model to call a function // .function(name: "get_weather") - Force specific function ``` -------------------------------- ### Check Account Balance with DeepSeekKit Source: https://context7.com/guitaripod/deepseekkit/llms.txt Monitor your API usage and account balance by fetching balance information, including total, granted, and topped-up amounts. ```swift import DeepSeekKit let client = DeepSeekClient(apiKey: "your-api-key") let balance = try await client.balance.getBalance() print("Balance available: \(balance.isAvailable)") for bal in balance.balanceInfos { print("\(bal.currency):") print(" Total: \(bal.totalBalance)") print(" Granted: \(bal.grantedBalance)") print(" Topped up: \(bal.toppedUpBalance)") } // Output: // CNY: // Total: 100.00 // Granted: 50.00 // Topped up: 50.00 ``` -------------------------------- ### Add DeepSeekKit as Swift Package Dependency Source: https://context7.com/guitaripod/deepseekkit/llms.txt Integrate the DeepSeekKit SDK into your project by adding it as a Swift Package dependency in your Package.swift file and then referencing it in your target. ```swift // Package.swift dependencies: [ .package(url: "https://github.com/guitaripod/DeepSeekKit", from: "1.0.0") ] // Then add to your target: .target( name: "YourApp", dependencies: ["DeepSeekKit"]) ``` -------------------------------- ### Add DeepSeekKit to Package.swift Source: https://github.com/guitaripod/deepseekkit/blob/master/Sources/DeepSeekKit/DeepSeekKit.docc/DeepSeekKit.md Add DeepSeekKit as a dependency in your Swift Package Manager configuration file. ```swift dependencies: [ .package(url: "https://github.com/guitaripod/DeepSeekKit.git", from: "1.0.0") ] ``` -------------------------------- ### Generate JSON Output with DeepSeekKit Source: https://context7.com/guitaripod/deepseekkit/llms.txt Use the `responseFormat` option to ensure the model outputs structured JSON. This is useful for reliable data extraction. ```swift import DeepSeekKit let client = DeepSeekClient(apiKey: "your-api-key") let response = try await client.chat.createCompletion( ChatCompletionRequest( model: .chat, messages: [ .system("You are a helpful assistant that outputs JSON"), .user("Generate a user profile with name, age, email, and interests") ], responseFormat: ResponseFormat(type: .jsonObject) ) ) if let jsonString = response.choices.first?.message.content { print(jsonString) // Output: // { // "name": "Alice Johnson", // "age": 28, // "email": "alice@example.com", // "interests": ["programming", "hiking", "photography"] // } // Parse the JSON if let data = jsonString.data(using: .utf8) { let profile = try JSONDecoder().decode(UserProfile.self, from: data) print("Name: \(profile.name)") } } struct UserProfile: Codable { let name: String let age: Int let email: String let interests: [String] } ``` -------------------------------- ### Add DeepSeekKit Dependency Source: https://github.com/guitaripod/deepseekkit/blob/master/README.md Add the DeepSeekKit package to your project's dependencies. ```swift dependencies: [ .package(url: "https://github.com/guitaripod/DeepSeekKit", from: "1.0.0") ] ``` -------------------------------- ### Stream Chat Completion Responses Source: https://github.com/guitaripod/deepseekkit/blob/master/Sources/DeepSeekKit/DeepSeekKit.docc/DeepSeekKit.md Create a streaming chat completion request to receive tokens as they are generated. This is useful for real-time user interfaces. Set `stream` to `true` in the request. ```swift // Stream tokens as they're generated let stream = client.chat.createStreamingCompletion( ChatCompletionRequest( model: .chat, messages: [.user("Write a short story")], stream: true ) ) for try await chunk in stream { if let content = chunk.choices.first?.delta.content { print(content, terminator: "") } } ``` -------------------------------- ### Handle DeepSeekKit API Errors Source: https://context7.com/guitaripod/deepseekkit/llms.txt Implement robust error handling for various DeepSeek API errors, including invalid API keys, rate limits, insufficient balance, network issues, and timeouts. ```swift import DeepSeekKit let client = DeepSeekClient(apiKey: "your-api-key") do { let response = try await client.chat.createCompletion( ChatCompletionRequest( model: .chat, messages: [.user("Hello!")] ) ) print(response.choices.first?.message.content ?? "") } catch DeepSeekError.invalidAPIKey { print("Invalid API key. Please check your credentials.") } catch DeepSeekError.rateLimitExceeded { print("Rate limit exceeded. Waiting before retry...") try await Task.sleep(nanoseconds: 60_000_000_000) // Wait 60 seconds } catch DeepSeekError.insufficientBalance { print("Insufficient balance. Please top up your account.") } catch DeepSeekError.apiError(let apiError) { print("API error: \(apiError.message)") if let code = apiError.code { print("Error code: \(code)") } } catch DeepSeekError.networkError(let error) { print("Network error: \(error.localizedDescription)") } catch DeepSeekError.timeout { print("Request timed out. Consider using streaming for long responses.") } catch DeepSeekError.streamingError(let message) { print("Streaming error: \(message)") } catch DeepSeekError.httpError(let statusCode) { print("HTTP error with status code: \(statusCode)") } catch { print("Unexpected error: \(error)") } ``` -------------------------------- ### Stream Chat Completion Source: https://github.com/guitaripod/deepseekkit/blob/master/README.md Process chat completion responses as a stream. This is useful for real-time updates. ```swift // Streaming for try await chunk in client.chat.createStreamingCompletion(request) { print(chunk.choices.first?.delta.content ?? "", terminator: "") } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.