### Start Interactive Mode (PyPI)
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/README.md
Launch the DeepSeek CLI in interactive mode after installation from PyPI.
```bash
deepseek
```
--------------------------------
### Development Installation
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/README.md
Install the package in editable mode for development purposes. Ensure you are in the correct project directory.
```bash
pip install -e . --upgrade
```
--------------------------------
### Install DeepSeek CLI from Source
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/README.md
Clone the repository and install the DeepSeek CLI in development mode for local modifications.
```bash
git clone https://github.com/PierrunoYT/deepseek-cli.git
cd deepseek-cli
pip install -e .
```
--------------------------------
### Start Interactive Mode (Source)
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/README.md
Launch the DeepSeek CLI in interactive mode when installed from source, using either the direct command or the module path.
```bash
deepseek
# or
python -m deepseek_cli
```
--------------------------------
### Programmatic Entry Point Example
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/module-graph.md
Demonstrates how to instantiate and run the DeepSeekCLI programmatically. Ensure necessary imports are available.
```python
from src.cli.deepseek_cli import DeepSeekCLI
from src.api.client import APIClient
from src.handlers.chat_handler import ChatHandler
# Direct instantiation
cli = DeepSeekCLI()
cli.run()
```
--------------------------------
### Example ModelConfig Dictionary
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/types.md
An example of how to structure the model_config dictionary, including name, version, context length, and feature support flags.
```python
model_config = {
"name": "deepseek-chat",
"version": "DeepSeek-V3.2",
"mode": "Non-thinking Mode",
"context_length": 128000,
"max_tokens": 8192,
"default_max_tokens": 4096,
"supports_json": True,
"supports_function_calling": True,
"supports_prefix_completion": True,
"supports_fim": True
}
```
--------------------------------
### Multiline Example with Code
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/README.md
Illustrates using multiline input mode to provide a code snippet as part of the query.
```bash
deepseek --multiline -q "
def calculate_sum(a, b):
return a + b
print(calculate_sum(2, 3))
"
```
--------------------------------
### Example Settings File Structure
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/configuration.md
Shows the JSON format for Deepseek CLI settings, including model parameters, limits, and file configurations.
```json
{
"settings": {
"model": "deepseek-chat",
"temperature": 1.0,
"frequency_penalty": 0.0,
"presence_penalty": 0.0,
"top_p": 1.0,
"json_mode": false,
"prefix_mode": false,
"fim_mode": false,
"stop_sequences": [],
"functions": []
},
"last_updated": "2025-01-15T14:30:45.123456",
"version": "1.0"
}
```
--------------------------------
### Install and Use Deepseek CLI in Python
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/INDEX.md
Shows how to install the Deepseek CLI package and use its API client and chat handler for creating chat completions in your Python code. Ensure the package is installed via pip.
```python
# Install
pip install deepseek-cli
# Import
from src.api.client import APIClient
from src.handlers.chat_handler import ChatHandler
# Use
api = APIClient()
chat = ChatHandler()
chat.add_message("user", "Hello!")
response = api.create_chat_completion(**chat.prepare_chat_request())
chat.handle_response(response)
```
--------------------------------
### Install DeepSeek CLI from PyPI
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/README.md
Use this command to install the latest stable version of the DeepSeek CLI from the Python Package Index.
```bash
pip install deepseek-cli
```
--------------------------------
### Exponential Backoff Example
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/errors.md
Illustrates the sequence of waits and retries during exponential backoff. The maximum number of retries can be configured.
```text
Attempt 1: Fail
Attempt 2: Wait 1s → Retry
Attempt 3: Wait 2s → Retry
Attempt 4: Wait 4s → Retry
Attempt 5: Wait 8s → Retry
Attempt 6: Wait 16s (capped) → Retry
Max: 3 attempts by default
```
--------------------------------
### REPL Mode: Prefix Completion and Low Temperature
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/README.md
Start the REPL with prefix completion enabled and a low temperature for more deterministic output.
```bash
deepseek --prefix --temp 0.0
```
--------------------------------
### Check Package Installation
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/README.md
Verify if the deepseek-cli package is installed on your system. This command is for Unix-like systems.
```bash
pip list | grep deepseek-cli
```
--------------------------------
### Initialize FileHandler
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/file-handler.md
Initializes an empty attachment list for the FileHandler. No setup is required beyond importing the class.
```python
from handlers.file_handler import FileHandler
handler = FileHandler()
```
--------------------------------
### Deepseek-CLI Command-Line Usage
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/README.md
Examples of using the Deepseek-CLI from the command line, including interactive sessions, inline queries, and file attachments.
```bash
# Interactive session
deepseek
# Inline query
deepseek -q "What is Python?" -m deepseek-chat
# With options
deepseek --temp creative --json -s
# Read from file/pipe
cat myfile.txt | deepseek --read -
# Attach files
deepseek --file src/*.py --file docs/**/*.md
```
--------------------------------
### Example Function Definition
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/types.md
An example of a function definition for tool calling, specifying the function name, a description, and its parameters using JSON Schema.
```python
func = {
"name": "get_weather",
"description": "Get current weather",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string"}
},
"required": ["city"]
}
}
```
--------------------------------
### Combined Inline Options Example
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/README.md
Demonstrates combining multiple inline mode options for a specific query, including model, raw output, and system message.
```bash
deepseek -q "Write a Python function to calculate factorial" -m deepseek-coder -r -S "You are an expert Python developer."
```
--------------------------------
### Get Completion with Streaming Enabled
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/README.md
Initialize the CLI with streaming enabled to receive responses as they are generated. This is useful for long-running tasks.
```python
cli = DeepSeekCLI(stream=True)
content = cli.get_completion("Generate a poem")
```
--------------------------------
### Get Help Message
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/command-handler.md
Returns the formatted help message containing all available commands and options. This is useful for displaying usage instructions to the user.
```python
def get_help_message(self) -> str
```
--------------------------------
### run
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/deepseek-cli.md
Starts the interactive session (REPL mode), allowing users to input commands or queries. It handles command execution, API responses, and graceful exit.
```APIDOC
## run
### Description
Starts the interactive session (REPL mode), allowing users to input commands or queries. It handles command execution, API responses, and graceful exit.
### Method
This is a method of the `DeepSeekCLI` class.
### Endpoint
N/A (This is an SDK method, not an HTTP endpoint)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Method Signature
```python
def run(self, system_message: str = "You are a helpful assistant.") -> None
```
#### Parameters
- **system_message** (str) - Optional - Initial system message
### Example
```python
cli = DeepSeekCLI()
cli.run("You are a Python expert.")
```
```
--------------------------------
### Initialize DeepSeekCLI with Streaming and Multiline
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/deepseek-cli.md
Instantiate the DeepSeekCLI with streaming responses and multiline input enabled. This setup is useful for interactive chat sessions where continuous output and multi-line user inputs are desired.
```python
from cli.deepseek_cli import DeepSeekCLI
cli = DeepSeekCLI(stream=True, multiline=True)
```
--------------------------------
### Get About Message
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/command-handler.md
Returns formatted API information and contact details. Use this to provide users with information about the API and how to get in touch.
```python
def get_about_message(self) -> str
```
--------------------------------
### Import and Print Package Version
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/module-graph.md
Demonstrates how to import the deepseek_cli package and access its version attribute. This is a common pattern for verifying installed package versions.
```python
import deepseek_cli
print(deepseek_cli.__version__) # "0.7.0"
```
--------------------------------
### Exponential Backoff Strategy Example
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/error-handler.md
Illustrates the sequence of retries with increasing delays, capped at a maximum. This strategy is applied to non-rate-limit errors.
```text
Attempt 1: Fails
Attempt 2: Wait 1s, retry
Attempt 3: Wait 2s, retry
Attempt 4: Wait 4s, retry
Attempt 5: Wait 8s, retry
Attempt 6: Wait 16s (capped), retry
```
--------------------------------
### Running Deepseek CLI
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/deepseek-cli.md
The Deepseek CLI module can be executed directly from the command line. Use 'python -m cli.deepseek_cli' for development or 'deepseek' after installation.
```bash
python -m cli.deepseek_cli # Development mode
```
```bash
deepseek # Installed via pip/pipx
```
--------------------------------
### Python SDK Example for Anthropic API
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/README.md
Use the Anthropic Python SDK to interact with the DeepSeek API. Replace 'your-deepseek-api-key' with your actual API key.
```python
import anthropic
client = anthropic.Anthropic(
base_url="https://api.deepseek.com/anthropic",
api_key="your-deepseek-api-key"
)
message = client.messages.create(
model="deepseek-chat",
max_tokens=1000,
system="You are a helpful assistant.",
messages=[
{
"role": "user",
"content": [{"type": "text", "text": "Hi, how are you?"}]
}
]
)
print(message.content)
```
--------------------------------
### Example Chat History File Structure
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/configuration.md
Illustrates the JSON structure for storing chat history, including messages, last updated timestamp, and version.
```json
{
"messages": [
{"role": "system", "content": "..."},
{"role": "user", "content": "..."}
],
"last_updated": "2025-01-15T14:30:45.123456",
"version": "1.0"
}
```
--------------------------------
### Get XDG Config Home Directory
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/persistence-manager.md
Returns the path to the XDG configuration home directory. Uses `$XDG_CONFIG_HOME` if set, otherwise defaults to `~/.config`.
```python
def _xdg_config_home() -> Path:
```
--------------------------------
### Get XDG Data Home Directory
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/persistence-manager.md
Returns the path to the XDG data home directory. Uses `$XDG_DATA_HOME` if set, otherwise defaults to `~/.local/share`.
```python
def _xdg_data_home() -> Path:
```
--------------------------------
### Inline Mode: Basic Query
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/README.md
Get a quick answer using inline mode by providing a query directly via the -q flag.
```bash
deepseek -q "What is the capital of France?"
```
--------------------------------
### JSON Mode Output Example
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/README.md
Force the model to output valid JSON by using JSON mode. This is useful for structured data generation.
```json
{
"response": "structured output",
"data": {
"field1": "value1",
"field2": "value2"
}
}
```
--------------------------------
### Run DeepSeekCLI in Interactive Mode
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/deepseek-cli.md
Start the DeepSeekCLI in interactive REPL mode. This method manages the user prompt, command execution, API calls, and response display within an infinite loop. It gracefully handles interruptions and saves state on exit.
```python
cli = DeepSeekCLI()
cli.run("You are a Python expert.")
```
--------------------------------
### Fill-in-the-Middle (FIM) Example
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/README.md
Use XML-style tags to define the gap for FIM prompts. This allows the model to complete code or text within a specified context.
```text
def calculate_sum(a, b): return result
```
--------------------------------
### Python _apply_cli_args Method
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/deepseek-cli.md
Applies command-line flags to chat/API state before the session starts. Supports various arguments like JSON mode, beta endpoint, prefix completion, FIM, temperature, frequency/presence penalties, top-p, stop sequences, and file attachments.
```python
def _apply_cli_args(self, args: argparse.Namespace) -> None
```
--------------------------------
### Run DeepSeek CLI as a Module
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/README.md
Execute the DeepSeek CLI directly as a Python module. This command is useful for running the CLI after installation without needing to call it as an executable.
```bash
python -m deepseek_cli
```
--------------------------------
### Get Current Chat Handler Settings
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/chat-handler.md
Returns a dictionary containing all current settings, suitable for persistence. Includes model, temperature, penalties, top_p, json_mode, prefix_mode, fim_mode, stop_sequences, and functions.
```python
def get_current_settings(self) -> Dict[str, Any]
```
--------------------------------
### Setup Anthropic API Compatibility for Claude Code
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/README.md
Configure environment variables to use the DeepSeek API with Anthropic's Claude Code. Ensure you have the DeepSeek API key set.
```bash
# Install Claude Code
npm install -g @anthropic-ai/claude-code
# Configure environment variables
export ANTHROPIC_BASE_URL=https://api.deepseek.com/anthropic
export ANTHROPIC_AUTH_TOKEN=${DEEPSEEK_API_KEY}
export ANTHROPIC_MODEL=deepseek-chat
export ANTHROPIC_SMALL_FAST_MODEL=deepseek-chat
# Run in your project
cd my-project
claude
```
--------------------------------
### Python _print_welcome Method
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/deepseek-cli.md
Displays the welcome banner. Accepts a 'style' parameter to control the banner's appearance, with 'simple' for a minimal banner and 'fancy' for ASCII art.
```python
def _print_welcome(self, style: str = "simple") -> None
```
--------------------------------
### Attach Files with Path Pattern
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/file-handler.md
Attaches files to the handler based on a provided path pattern, which can be a literal path, a glob pattern (e.g., `src/*.py`), or a path starting with `~`. It handles `~` expansion, glob matching, and falls back to literal paths. Binary, non-UTF-8, and oversized files are skipped, and duplicates are rejected. Errors are returned in a list, not raised as exceptions.
```python
handler = FileHandler()
# Attach single file
attached, errors = handler.attach("src/main.py")
if errors:
print("Errors:", errors)
# Attach with glob
attached, errors = handler.attach("src/*.py")
# Attach with tilde expansion
attached, errors = handler.attach("~/notes/todo.txt")
```
--------------------------------
### Configure Input/Output and Model via CLI
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/configuration.md
Combine flags to set input query, model, and output format. Use -q for inline queries, -m for model selection, and --raw to suppress token usage display.
```bash
deepseek -q "Hello" -m deepseek-coder --raw
```
--------------------------------
### Update DeepSeek CLI Package
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/README.md
Update the installed DeepSeek CLI to the latest version from PyPI. For development installations, pull changes and reinstall.
```bash
pip install --upgrade deepseek-cli
```
```bash
git pull
pip install -e . --upgrade
```
--------------------------------
### Deepseek CLI Entry Point
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/deepseek-cli.md
The main function serves as the entry point for the CLI. It parses arguments, initializes the CLI instance, applies flags, and manages the session lifecycle, including interactive or inline query execution.
```python
def main() -> None
```
--------------------------------
### Get Current Provider
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/chat-handler.md
Retrieves the provider of the currently active model. This method always returns 'deepseek'.
```python
handler = ChatHandler()
provider = handler.get_current_provider()
print(provider) # deepseek
```
--------------------------------
### Initialize CommandHandler
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/command-handler.md
Instantiate the CommandHandler with necessary clients. The file handler is optional.
```python
from api.client import APIClient
from handlers.chat_handler import ChatHandler
from handlers.command_handler import CommandHandler
api = APIClient()
chat = ChatHandler()
cmd = CommandHandler(api, chat)
```
--------------------------------
### Initialize and Use APIClient
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/README.md
Instantiate the APIClient for DeepSeek communication. Use create_chat_completion for sending messages and receiving responses.
```python
client = APIClient(use_anthropic=False)
response = client.create_chat_completion(
model="deepseek-chat",
messages=[{"role": "user", "content": "Hi"}],
max_tokens=1000
)
```
--------------------------------
### Run DeepSeek CLI Application
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/README.md
Initialize DeepSeekCLI for top-level application coordination. Use run for interactive sessions or run_inline_query for single queries.
```python
cli = DeepSeekCLI(stream=True, multiline=True)
cli.run("You are a Python expert.")
# or
response = cli.run_inline_query("What is Python?")
```
--------------------------------
### Catch DeepSeekError Exception
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/errors.md
Catch DeepSeekError to handle general configuration or API errors gracefully. This example shows how to print a user-friendly message.
```python
from utils.exceptions import DeepSeekError
try:
client = APIClient()
except DeepSeekError as e:
print(f"Configuration error: {e}")
```
--------------------------------
### Programmatic Chat Completion
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/README.md
Use the APIClient and ChatHandler to send messages and get chat completions programmatically. Ensure necessary imports are present.
```python
from src.api.client import APIClient
from src.handlers.chat_handler import ChatHandler
# Initialize client and handler
api_client = APIClient()
chat_handler = ChatHandler()
# Send a message
chat_handler.add_message("user", "What is Python?")
request = chat_handler.prepare_chat_request()
response = api_client.create_chat_completion(**request)
content = chat_handler.handle_response(response)
print(content)
```
--------------------------------
### Initialize APIClient
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/api-client.md
Instantiate the APIClient for standard DeepSeek API or Anthropic API compatibility.
```python
from api.client import APIClient
# Standard DeepSeek API
client = APIClient()
# Anthropic API compatibility
client = APIClient(use_anthropic=True)
```
--------------------------------
### Initialize ChatHandler
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/chat-handler.md
Create an instance of ChatHandler. Set `stream=True` to enable streaming responses by default.
```python
from handlers.chat_handler import ChatHandler
# Create handler with streaming disabled
handler = ChatHandler(stream=False)
# Create handler with streaming enabled
handler = ChatHandler(stream=True)
```
--------------------------------
### Initialize PersistenceManager
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/persistence-manager.md
Instantiate PersistenceManager using default XDG/legacy paths or a custom directory for testing.
```python
from utils.persistence import PersistenceManager
# Default behavior (uses XDG or legacy)
pm = PersistenceManager()
# Legacy test mode (custom directory)
pm = PersistenceManager(config_dir="/tmp/deepseek-test")
```
--------------------------------
### Load User Settings
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/persistence-manager.md
Loads user settings from disk. Returns a dictionary of settings or None if the settings file is not found or invalid.
```python
pm = PersistenceManager()
settings = pm.load_settings()
if settings:
print(f"Model: {settings.get('model')}")
else:
print("No settings found")
```
--------------------------------
### Configure XDG Base Directories
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/configuration.md
Optionally set XDG_CONFIG_HOME and XDG_DATA_HOME environment variables to customize configuration and data file locations. These are used if the legacy ~/.deepseek-cli/ directory does not exist.
```bash
export XDG_CONFIG_HOME="$HOME/.config"
export XDG_DATA_HOME="$HOME/.local/share"
```
--------------------------------
### Main Entry Point for Module Execution
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/module-graph.md
This snippet shows the standard Python entry point for executing a module as a script using `python -m deepseek_cli`. It imports and calls the main function from the CLI module.
```python
from src.cli.deepseek_cli import main
if __name__ == "__main__":
main()
```
--------------------------------
### Enable Multiline Input and Creative Mode via CLI
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/configuration.md
Enable multiline input mode and set the temperature to a creative value using command-line flags.
```bash
deepseek --multiline --temp creative
```
--------------------------------
### Get Total Size of Attached Files
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/file-handler.md
Returns the total size in bytes of all files currently attached to the handler. Ensure files are attached before calling.
```python
handler = FileHandler()
handler.attach("file.txt")
print(handler.total_size()) # e.g., 1234
```
--------------------------------
### Recommended Imports for Library Use
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/module-graph.md
Provides a comprehensive list of imports for utilizing Deepseek CLI components as a library. This includes core clients, handlers, persistence utilities, exceptions, and configuration settings.
```python
# Core client
from src.api.client import APIClient
# Handlers
from src.handlers.chat_handler import ChatHandler
from src.handlers.command_handler import CommandHandler
from src.handlers.error_handler import ErrorHandler
from src.handlers.file_handler import FileHandler, pick_files
# Persistence
from src.utils.persistence import PersistenceManager
# Exceptions
from src.utils.exceptions import DeepSeekError, RateLimitExceeded
# Configuration
from src.config.settings import (
MODEL_CONFIGS,
TEMPERATURE_PRESETS,
DEFAULT_MAX_TOKENS,
MAX_FUNCTIONS,
MAX_STOP_SEQUENCES
)
# Main CLI
from src.cli.deepseek_cli import DeepSeekCLI, parse_arguments, main
```
--------------------------------
### API Client Initialization
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/module-graph.md
Initializes the API client, optionally using Anthropic's base URL. It requires API keys to be set in the environment or provided directly.
```python
class APIClient:
def __init__(self, use_anthropic: bool = False) -> None:
```
--------------------------------
### run_inline_query
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/deepseek-cli.md
Runs a single query and returns the response in an inline, one-shot mode. This method is suitable for executing a single command without starting an interactive session.
```APIDOC
## run_inline_query
### Description
Runs a single query and returns the response in an inline, one-shot mode. This method is suitable for executing a single command without starting an interactive session.
### Method
This is a method of the `DeepSeekCLI` class.
### Endpoint
N/A (This is an SDK method, not an HTTP endpoint)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Method Signature
```python
def run_inline_query(
self,
query: str,
model: Optional[str] = None,
raw: bool = False,
system_message: str = "You are a helpful assistant."
) -> str
```
#### Parameters
- **query** (str) - Required - The query to send
- **model** (str) - Optional - Model to use (overrides current)
- **raw** (bool) - Optional - Suppress token info display
- **system_message** (str) - Optional - System message (only if no history)
### Returns
Response content as string
### Example
```python
cli = DeepSeekCLI()
response = cli.run_inline_query(
"Write a Python function to calculate factorial",
model="deepseek-coder",
raw=True
)
print(response)
```
```
--------------------------------
### API Client Static Methods
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/module-graph.md
Provides static methods for retrieving API keys and creating the underlying OpenAI client instance.
```python
@staticmethod
def _get_api_key() -> str:
...
def _create_client(self) -> OpenAI:
```
--------------------------------
### Inline Mode: Custom System Message
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/README.md
Set a custom system message using the -S flag to guide the assistant's behavior for a specific query.
```bash
deepseek -S "You are a Rust expert." -q "Explain lifetimes"
```
--------------------------------
### load_settings
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/persistence-manager.md
Loads user settings from a JSON file on disk. It validates the file to ensure it's valid JSON and contains the expected 'settings' key.
```APIDOC
## load_settings
### Description
Loads settings from disk.
### Method Signature
```python
def load_settings(self) -> Optional[Dict[str, Any]]
```
### Returns
- **Optional[Dict[str, Any]]** - Settings dict, or None if file doesn't exist or is invalid
### Validation
Checks that file is valid JSON with `settings` key
### Example
```python
pm = PersistenceManager()
settings = pm.load_settings()
if settings:
print(f"Model: {settings.get('model')}")
else:
print("No settings found")
```
```
--------------------------------
### API Error Format
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/errors.md
This format is used for API-related errors handled by ErrorHandler. It includes an error code and a suggested solution, with specific examples like rate limiting.
```text
[red]Error (CODE): message[/red]
[cyan]Solution: suggestion[/cyan]
```
```text
[yellow]Rate limit exceeded. Retrying in 60 seconds...[/yellow]
```
--------------------------------
### Command Error Responses
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/command-handler.md
Illustrates example error responses for commands that fail due to invalid values or API errors. The handler communicates errors via status tuples, not exceptions.
```python
(True, "Invalid temperature value or preset")
```
```python
(True, "Invalid model")
```
```python
(True, "Maximum number of functions reached")
```
```python
(True, "Error fetching models: ")
```
--------------------------------
### Combine File/Pipe Input with Query Text
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/README.md
Use the DeepSeek CLI with both a query string provided via -q and content read from a file or stdin. The -q text will precede the piped/file content.
```bash
git diff HEAD | deepseek --read - -q "Review this diff:"
cat report.md | deepseek --read - -q "Summarise in one paragraph:"
```
--------------------------------
### Python multiline_input Function
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/deepseek-cli.md
Gets multiline input from the user with configurable submit behavior. Supports 'empty-line' or 'shift-enter' submit modes. Note: 'shift-enter' mode requires terminal support.
```python
def multiline_input(prompt: str, submit_mode: str = "shift-enter") -> str
```
--------------------------------
### Package Structure Overview
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/module-graph.md
This outlines the directory and file structure of the deepseek-cli project, showing the organization of source code into subpackages and modules.
```tree
deepseek-cli/
├── src/
│ ├── __init__.py (version, package re-exports)
│ ├── __main__.py (entry point: python -m deepseek_cli)
│ ├── api/
│ │ ├── __init__.py
│ │ └── client.py (APIClient)
│ ├── cli/
│ │ ├── __init__.py
│ │ └── deepseek_cli.py (DeepSeekCLI, main, parse_arguments)
│ ├── config/
│ │ ├── __init__.py
│ │ └── settings.py (constants, configs)
│ ├── handlers/
│ │ ├── __init__.py
│ │ ├── chat_handler.py (ChatHandler)
│ │ ├── command_handler.py (CommandHandler)
│ │ ├── error_handler.py (ErrorHandler)
│ │ └── file_handler.py (FileHandler, pick_files)
│ └── utils/
│ ├── __init__.py
│ ├── exceptions.py (DeepSeekError, RateLimitExceeded)
│ ├── persistence.py (PersistenceManager)
│ └── version_checker.py (check_version, get_current_version)
```
--------------------------------
### Read Query from File
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/README.md
Provide the query text by reading from a specified file using the --read flag. Use '-' to read from standard input.
```bash
deepseek --read prompt.txt
```
--------------------------------
### Fallback Import Strategy in Python
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/module-graph.md
This Python code demonstrates a two-stage import fallback strategy. It allows modules to be imported correctly whether the package is installed via pip or being run from source during development.
```python
try:
# When installed via pip (package_dir={"": "src"})
from config.settings import ...
from utils.exceptions import ...
except ImportError:
# When running from source (development mode)
from src.config.settings import ...
from src.utils.exceptions import ...
```
--------------------------------
### Initialize Chat Handler with Persistence
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/README.md
Instantiate ChatHandler to automatically load persisted history and settings from the previous session.
```python
chat = ChatHandler()
```
--------------------------------
### Handle API Errors with Retries
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/error-handler.md
Use the handle_error method to process exceptions from API calls. It determines if an error is retryable and returns 'retry' if so. This example shows handling RateLimitError and AuthenticationError, with specific logic for each.
```python
from openai import RateLimitError, AuthenticationError
handler = ErrorHandler()
try:
# Make API call
response = api_client.create_chat_completion(...)
except RateLimitError as e:
result = handler.handle_error(e)
if result == "retry":
# Retry after sleeping
response = api_client.create_chat_completion(...)
except AuthenticationError as e:
result = handler.handle_error(e, api_client)
if result == "retry":
# Retry with updated key
response = api_client.create_chat_completion(...)
```
--------------------------------
### DeepSeekCLI Constructor
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/deepseek-cli.md
Initializes the DeepSeekCLI application, managing interactive sessions or inline query execution. It allows configuration of streaming, multiline input, and submission modes.
```APIDOC
## DeepSeekCLI Constructor
### Description
Initializes the DeepSeekCLI application, managing interactive sessions or inline query execution. It allows configuration of streaming, multiline input, and submission modes.
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Method Signature
```python
def __init__(
self,
*,
stream: bool = False,
multiline: bool = False,
multiline_submit: str = "empty-line"
) -> None
```
#### Parameters
- **stream** (bool) - Optional - Enable streaming responses
- **multiline** (bool) - Optional - Enable multiline input mode
- **multiline_submit** (str) - Optional - Multiline submit mode (empty-line or shift-enter)
### Example
```python
from cli.deepseek_cli import DeepSeekCLI
cli = DeepSeekCLI(stream=True, multiline=True)
```
```
--------------------------------
### Get Completion from DeepSeekCLI
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/deepseek-cli.md
Send a user message to the DeepSeekCLI and retrieve the API response. This method handles conversation history, API calls, and response extraction. Set `raw=True` to bypass response formatting.
```python
cli = DeepSeekCLI()
response = cli.get_completion("What is Python?")
print(response)
```
--------------------------------
### Multiline Input Mode: Combined Options
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/README.md
Combine multiline input with other options like prefix completion and temperature settings.
```bash
deepseek --multiline --prefix --temp 0.0
```
--------------------------------
### APIClient Constructor
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/api-client.md
Initializes the APIClient. It can be configured to use either the standard DeepSeek API or the Anthropic API compatibility mode.
```APIDOC
## APIClient Constructor
### Description
Initializes the APIClient. It can be configured to use either the standard DeepSeek API or the Anthropic API compatibility mode.
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Method Signature
```python
def __init__(self, use_anthropic: bool = False) -> None
```
#### Parameters
- **use_anthropic** (bool) - Optional - If True, uses Anthropic API endpoint instead of standard DeepSeek API. Defaults to False.
### Returns
APIClient instance
### Throws
`DeepSeekError` if API key is not set and user input is empty
### Example
```python
from api.client import APIClient
# Standard DeepSeek API
client = APIClient()
# Anthropic API compatibility
client = APIClient(use_anthropic=True)
```
```
--------------------------------
### Attach and Summarize Files
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/command-handler.md
Runs FileHandler.attach() over specified paths or glob patterns and generates a status report. Use this to attach multiple files or files matching a pattern.
```python
def _attach_and_summarize(self, patterns: list) -> str
```
--------------------------------
### Specify Input Files via CLI
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/configuration.md
Attach multiple files for processing by using the --file flag repeatedly. Supports glob patterns for selecting files.
```bash
deepseek --file src/*.py --file docs/*.md
```
--------------------------------
### Set DeepSeek API Key (Windows)
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/README.md
Configure your DeepSeek API key by setting the DEEPSEEK_API_KEY environment variable on Windows systems.
```cmd
set DEEPSEEK_API_KEY="your-api-key"
```
--------------------------------
### Check API Key (Windows)
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/README.md
Verify your DEEPSEEK_API_KEY environment variable is set correctly. Use this command in Windows Command Prompt.
```batch
echo %DEEPSEEK_API_KEY%
```
--------------------------------
### PersistenceManager Constructor
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/persistence-manager.md
Initializes the PersistenceManager. It can be configured to use a specific directory for all persistence files or rely on the XDG Base Directory specification with a legacy fallback.
```APIDOC
## PersistenceManager Constructor
### Description
Initializes the PersistenceManager, managing persistent storage of chat history and settings across sessions with automatic XDG Base Directory compliance.
### Method
__init__
### Parameters
#### Path Parameters
- **config_dir** (Optional[str]) - Optional - Directory for ALL persistence files (legacy/test mode). If provided, both config and data use this directory. If omitted, uses XDG Base Directory spec with legacy fallback.
### Request Example
```python
from utils.persistence import PersistenceManager
# Default behavior (uses XDG or legacy)
pm = PersistenceManager()
# Legacy test mode (custom directory)
pm = PersistenceManager(config_dir="/tmp/deepseek-test")
```
### Response
#### Success Response
Initializes the PersistenceManager object.
#### Response Example
(No explicit response body for constructor, object is initialized in place)
```
--------------------------------
### Initialize Package Version
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/module-graph.md
Defines the package version for the deepseek_cli package. This is typically used for version checking and dependency management.
```python
__version__ = "0.7.0"
```
--------------------------------
### Model Configurations
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/module-graph.md
A dictionary specifying configurations for different Deepseek models, including chat, coder, and reasoner models.
```python
MODEL_CONFIGS: Dict[str, Dict[str, Any]]
```
--------------------------------
### Combined Piped Input with Options
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/README.md
Integrate piped input with inline query text, a specific model, and a custom system message for complex workflows.
```bash
git diff HEAD | deepseek --read - -q "Review this diff:" -S "You are a code reviewer."
```
--------------------------------
### Feature Configurations
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/module-graph.md
A dictionary defining configurations for various features, such as prefix completion, fine-tuned model completion, JSON mode, and context caching.
```python
FEATURE_CONFIGS: Dict[str, Dict[str, Any]]
```
--------------------------------
### Check API Key
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/README.md
Verify your DEEPSEEK_API_KEY environment variable is set correctly. Use this command in Unix-like terminals.
```bash
echo $DEEPSEEK_API_KEY
```
--------------------------------
### Chat Request Preparation and Handling
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/module-graph.md
Methods for preparing a chat request and handling the response, including displaying token information and adding messages to the conversation history.
```python
def prepare_chat_request(self) -> Dict[str, Any]:
pass
def handle_response(self, response: Any) -> Optional[str]:
pass
def stream_response(self, response: Any) -> str:
pass
def display_token_info(self, usage: Dict[str, int]) -> None:
pass
def add_message(self, role: str, content: str) -> None:
pass
```
--------------------------------
### prepare_chat_request
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/chat-handler.md
Prepares and returns a dictionary containing all necessary arguments for a chat completion API request.
```APIDOC
## prepare_chat_request
### Description
Prepares the complete chat completion request kwargs dict.
### Method
`prepare_chat_request(self) -> Dict[str, Any]`
### Returns
- Dict[str, Any] - Dictionary with keys: model, messages, stream, max_tokens, temperature, frequency_penalty, presence_penalty, top_p, response_format, tools, stop, stream_options
### Special Behavior
- In prefix mode, converts the last user message to an assistant prefix without modifying message history
- Excludes temperature/penalties/functions for deepseek-reasoner model
- Adds response_format only in json_mode
- Converts functions to tools format
### Example
```python
handler = ChatHandler()
handler.add_message("user", "Hello!")
kwargs = handler.prepare_chat_request()
response = api_client.create_chat_completion(**kwargs)
```
```
--------------------------------
### API Client Toggle Methods
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/module-graph.md
Methods to toggle between beta and standard API endpoints, and to switch between Deepseek and Anthropic base URLs.
```python
def toggle_beta(self) -> None:
...
def toggle_anthropic(self) -> None:
```
--------------------------------
### Save User Settings
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/persistence-manager.md
Saves user-defined settings to a JSON file. The input should be a dictionary containing various configuration parameters.
```python
pm = PersistenceManager()
settings = {
"model": "deepseek-chat",
"temperature": 0.5,
"json_mode": True
}
success = pm.save_settings(settings)
```
--------------------------------
### Read Input from Source
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/deepseek-cli.md
Reads input content from a specified file path or standard input. Throws SystemExit on errors such as file not found or encoding issues. Use '-' as the source for stdin.
```python
def _read_input(source: str) -> str
```
--------------------------------
### Interactive File Picker with Tab Completion
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/file-handler.md
Use this function to open an interactive file picker that supports tab completion, multi-select, glob patterns, and tilde expansion. Press Ctrl+C or an empty line to cancel. Requires `prompt_toolkit`.
```python
from handlers.file_handler import pick_files
tokens = pick_files()
# User enters: "src/*.py docs/readme.md"
# Returns: ["src/*.py", "docs/readme.md"]
for pattern in tokens:
attached, errors = handler.attach(pattern)
```
--------------------------------
### DeepSeekCLI Class
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/MANIFEST.txt
Documentation for the DeepSeekCLI main class, covering interactive and inline modes, and argument parsing.
```APIDOC
## DeepSeekCLI Class
### Description
The main class for the DeepSeek CLI application, responsible for managing the overall application lifecycle, handling different modes of operation (interactive and inline), and parsing command-line arguments.
### Methods
- **Interactive mode**: Manages the REPL interface for user interaction.
- **Inline mode**: Handles single-command execution from the command line.
- **Argument parsing**: Processes command-line arguments to configure the CLI's behavior.
- **Session lifecycle**: Manages the start, execution, and termination of CLI sessions.
### Parameters
Details on parameters for each method are available in the `deepseek-cli.md` file.
```
--------------------------------
### FileHandler Constructor
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/file-handler.md
Initializes an empty attachment list for the FileHandler.
```APIDOC
## FileHandler Constructor
### Description
Initializes an empty attachment list.
### Method
__init__
### Parameters
None
### Example
```python
from handlers.file_handler import FileHandler
handler = FileHandler()
```
```
--------------------------------
### Enable Prefix Completion Mode
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/README.md
Set prefix_mode to True to use the last user message as a prefix for the assistant's completion. This is useful for code generation or continuing a thought.
```python
chat = ChatHandler()
chat.prefix_mode = True
chat.add_message("user", "def factorial(")
# API will complete from this prefix
```
--------------------------------
### Command Handling Logic
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/module-graph.md
The core method for handling incoming commands, parsing them, and executing the corresponding actions. It returns a tuple indicating success and a message.
```python
def handle_command(self, command: str) -> Tuple[Optional[bool], Optional[str]]:
pass
```
--------------------------------
### Manage File Attachments
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/README.md
Instantiate FileHandler to manage file attachments, including size limits and rejection of binary files. Format files for inclusion in messages.
```python
files = FileHandler()
attached, errors = files.attach("src/*.py")
formatted_message = files.format_for_message("Analyze this code")
```
--------------------------------
### Helper Functions for Persistence
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/module-graph.md
Internal helper functions for resolving configuration and data directories based on XDG specifications.
```python
def _xdg_config_home() -> Path:
# ... implementation details ...
pass
def _xdg_data_home() -> Path:
# ... implementation details ...
pass
def _resolve_dirs() -> tuple:
# ... implementation details ...
pass
```
--------------------------------
### Display Token Usage Information
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/chat-handler.md
Displays formatted token usage statistics, including prompt tokens, completion tokens, and total tokens.
```python
def display_token_info(self, usage: Dict[str, int]) -> None
```
--------------------------------
### Instantiate ErrorHandler
Source: https://github.com/pierrunoyt/deepseek-cli/blob/main/_autodocs/error-handler.md
Create an instance of the ErrorHandler, specifying the maximum number of retry attempts.
```python
from handlers.error_handler import ErrorHandler
handler = ErrorHandler(max_retries=5)
```