DeepSeek4Free

repository·main·Indexed 43 days ago

https://github.com/xtekky/deepseek4free

A Python library that interfaces with the DeepSeek AI chat API by reverse-engineering private endpoints. It supports streaming, reasoning visibility, web search, and session management via the DeepSeekAPI class. The library includes tools to handle Cloudflare challenges, capture cf_clearance cookies, and a FastAPI server for retrieving session cookies and HTML content.

Tokens
2.5K
Snippets
10
Records
11
Agent score
7%

What's inside DeepSeek4Free

  1. Obtain a DeepSeek Authentication Token

    main

    You must provide a DeepSeek auth token to initialize the API. You can retrieve this from chat.deepseek.com using one of two methods:

    1. Log in to chat.deepseek.com.
    2. Open browser developer tools (F12).
    3. Go to the Application tab.
    4. In the left sidebar, expand Local Storage and select https://chat.deepseek.com.
    5. Find the key userToken and copy its value.

    Alternatively, run this in the browser console:

    JSON.parse(localStorage.getItem("userToken")).value

    Method 2: From Network Tab

    1. Log in to chat.deepseek.com.
    2. Open developer tools (F12) and go to the Network tab.
    3. Perform any action in the chat.
    4. Inspect the request headers of the requests and copy the authorization token (remove the Bearer prefix).
  2. Handle Cloudflare Challenges

    main

    If you encounter Cloudflare challenges (e.g., "Just a moment..." page) or receive the error "Please wait a few minutes before trying again", you need to capture a cf_clearance cookie.

    Run the following command to open an undetected browser, solve the challenge, and save the cookie to dsk/cookies.json:

    python -m dsk.bypass

    The API will automatically use the captured cookie in future requests.

  3. Implement Threaded Conversations

    main

    You can create threaded conversations by tracking the message_id from a previous response and passing it as parent_message_id in the next call.

    # 1. Start session
    chat_id = api.create_chat_session()
    parent_id = None
    
    # 2. Send initial message and capture message_id
    for chunk in api.chat_completion(chat_id, "Tell me about neural networks"):
        if 'message_id' in chunk:
            parent_id = chunk['message_id']
    
    # 3. Send follow-up in the same thread
    for chunk in api.chat_completion(
        chat_id, 
        "How do they compare to other ML models?",
        parent_message_id=parent_id
    ):
        if chunk['type'] == 'text':
            print(chunk['content'], end='', flush=True)
    chat_id = api.create_chat_session()
    parent_id = None
    
    for chunk in api.chat_completion(chat_id, "Tell me about neural networks"):
        if 'message_id' in chunk:
            parent_id = chunk['message_id']
    
    for chunk in api.chat_completion(
        chat_id, 
        "How do they compare to other ML models?",
        parent_message_id=parent_id
    ):
        if chunk['type'] == 'text':
            print(chunk['content'], end='', flush=True)
  4. Enable Thinking Process and Web Search

    main

    The chat_completion method supports optional parameters to view the model's reasoning or enable web search.

    • thinking_enabled=True: Enables visibility into the model's reasoning steps. Chunks will have type == 'thinking'.
    • search_enabled=True: Enables web search integration for up-to-date information.
    # Example with both enabled
    for chunk in api.chat_completion(
        chat_id,
        "Explain quantum computing",
        thinking_enabled=True,
        search_enabled=True
    ):
        if chunk['type'] == 'thinking':
            print(f"🤔 Thinking/Searching: {chunk['content']}")
        elif chunk['type'] == 'text':
            print(chunk['content'], end='', flush=True)
    for chunk in api.chat_completion(
        chat_id,
        "Explain quantum computing",
        thinking_enabled=True,
        search_enabled=True
    ):
        if chunk['type'] == 'thinking':
            print(f"🤔 Thinking: {chunk['content']}")
        elif chunk['type'] == 'text':
            print(chunk['content'], end='', flush=True)
  5. Use the DeepSeekAPI for Chat Completions

    main

    The core interface is DeepSeekAPI. You initialize it with your auth token, create a session, and then iterate over the streaming response from chat_completion.

    from dsk.api import DeepSeekAPI
    
    # Initialize with your auth token
    api = DeepSeekAPI("YOUR_AUTH_TOKEN")
    
    # Create a new chat session
    chat_id = api.create_chat_session()
    
    # Simple chat completion
    prompt = "What is Python?"
    for chunk in api.chat_completion(chat_id, prompt):
        if chunk['type'] == 'text':
            print(chunk['content'], end='', flush=True)
    from dsk.api import DeepSeekAPI
    
    api = DeepSeekAPI("YOUR_AUTH_TOKEN")
    chat_id = api.create_chat_session()
    
    prompt = "What is Python?"
    for chunk in api.chat_completion(chat_id, prompt):
        if chunk['type'] == 'text':
            print(chunk['content'], end='', flush=True)
  6. Handle API and Network Errors

    main

    The package provides specific exceptions to handle different failure modes:

    • AuthenticationError: Invalid or expired token.
    • RateLimitError: Too many requests.
    • CloudflareError: Encountered Cloudflare protection.
    • NetworkError: Connectivity issues.
    • APIError: General API failures.
    from dsk.api import (
        DeepSeekAPI, 
        AuthenticationError,
        RateLimitError,
        NetworkError,
        CloudflareError,
        APIError
    )
    
    try:
        api = DeepSeekAPI("YOUR_AUTH_TOKEN")
        chat_id = api.create_chat_session()
        for chunk in api.chat_completion(chat_id, "Prompt"):
            pass
    except AuthenticationError:
        print("Authentication failed.")
    except RateLimitError:
        print("Rate limit exceeded.")
    except CloudflareError as e:
        print(f"Cloudflare protection: {e}")
    except NetworkError:
        print("Network error.")
    except APIError as e:
        print(f"API error: {e}")
    from dsk.api import (
        DeepSeekAPI, 
        AuthenticationError,
        RateLimitError,
        NetworkError,
        CloudflareError,
        APIError
    )
    
    try:
        api = DeepSeekAPI("YOUR_AUTH_TOKEN")
        chat_id = api.create_chat_session()
        
        for chunk in api.chat_completion(chat_id, "Your prompt here"):
            if chunk['type'] == 'text':
                print(chunk['content'], end='', flush=True)
                
    except AuthenticationError:
        print("Authentication failed. Please check your token.")
    except RateLimitError:
        print("Rate limit exceeded. Please wait before making more requests.")
    except CloudflareError as e:
        print(f"Cloudflare protection encountered: {str(e)}")
    except NetworkError:
        print("Network error occurred. Check your internet connection.")
    except APIError as e:
        print(f"API error occurred: {str(e)}")
  7. Retrieve HTML content and cookies via `/html` endpoint

    main

    The /html GET endpoint visits a URL, bypasses Cloudflare, and returns the full HTML content of the page. In addition to the HTML body, it provides the session cookies and User-Agent via HTTP response headers.

    Query Parameters:

    • url (string, required): The target URL to visit.
    • retries (integer, default: 5): Number of attempts to bypass Cloudflare.
    • proxy (string, optional): A proxy string to use for the browser session.

    Response Details:

    • Body: The raw HTML content of the page (text/html).
    • Headers:
      • cookies: A JSON-encoded string of the session cookies (e.g., {"name": "value"}).
      • user_agent: The User-Agent string used by the browser.
    GET /html?url=https%3A%2F%2Fexample.com
  8. Retrieve session cookies and User-Agent via `/cookies` endpoint

    main

    The /cookies GET endpoint allows you to bypass Cloudflare protection for a specific URL and retrieve the resulting session cookies and the browser's User-Agent. This is useful for authenticating subsequent requests to a protected API.

    Query Parameters:

    • url (string, required): The target URL to visit.
    • retries (integer, default: 5): Number of attempts to bypass Cloudflare.
    • proxy (string, optional): A proxy string to use for the browser session.

    Response Format: Returns a CookieResponse object containing:

    • cookies: A dictionary of cookie names and values.
    • user_agent: The User-Agent string used by the browser.
    GET /cookies?url=https%3A%2F%2Fexample.com&retries=5&proxy=http%3A%2F%2Fproxy%3A8080
  9. Run the Cloudflare bypass server via CLI

    main

    The server can be started from the command line using Python. It uses uvicorn to host the FastAPI application.

    Environment Variables:

    • DOCKERMODE: Set to true to enable Docker-specific Chromium configurations (e.g., --no-sandbox, --remote-debugging-port=9222).
    • SERVER_PORT: The port the server will listen on (default: 8000).

    CLI Arguments:

    • --nolog: Disables logging during the bypass process.
    • --headless: Runs the browser in headless mode (note: if DOCKERMODE is true, it will use pyvirtualdisplay to simulate a display).
    python dsk/server.py --headless --nolog