How to Integrate DeepSeek API for Advanced AI Functionalities in LazyOwn

To integrate the DeepSeek API in LazyOwn, configure the DEEPSEEK_API_URL and DEEPSEEK_MODEL constants, construct a structured JSON prompt, and send HTTP POST requests to the Ollama endpoint using the analyze_with_deepseek helper function.

LazyOwn is an open-source security automation framework that leverages local large language models for real-time data analysis. Integrating the DeepSeek API enables advanced AI functionalities such as automated log inspection, network traffic anomaly detection, and source code security auditing without requiring external cloud dependencies.

Architectural Overview of DeepSeek API Integration

The integration follows a consistent five-step pipeline across all LazyOwn modules: configuration, prompt construction, HTTP transmission, streaming chunk handling, and result validation.

Configuration Constants

Centralize endpoint settings in modules/lilsplunky.py to enable single-point updates:

DEEPSEEK_API_URL = "http://localhost:11434/api/generate"
DEEPSEEK_MODEL = "deepseek-r1:1.5b"

These constants point to the local Ollama instance serving the DeepSeek model, ensuring no external API keys are required.

Prompt Construction Strategy

Each module crafts a multi-line f-string that embeds the raw data and enforces a strict JSON output schema. In modules/lilsplunky.py, the analyze_with_deepseek function builds prompts requiring specific keys: suspicious, reason, severity, and confidence.

HTTP Client Implementation

The requests library transmits the payload with a 60-second timeout and optional streaming:

response = requests.post(
    DEEPSEEK_API_URL,
    json={"model": DEEPSEEK_MODEL, "prompt": prompt, "stream": True},
    timeout=60,
    stream=True
)

This pattern appears in modules/ia_logs_analysis.py at lines 90-108.

Streaming Response Handling

For real-time analysis, iterate over response.iter_content(chunk_size=1024) as implemented in modules/ia_network_analysis.py (lines 60-68):

for chunk in response.iter_content(chunk_size=1024):
    if chunk:
        json_chunk = json.loads(chunk.decode('utf-8'))
        full_response += json_chunk.get("response", "")

Result Validation

Before acting on the output, verify the JSON contains all required fields:

if not all(k in analysis_result for k in ["suspicious", "reason", "severity", "confidence"]):
    logging.warning("Invalid response structure from DeepSeek API")

This validation logic resides in modules/lilsplunky.py at lines 84-88.

Key Implementation Files

LazyOwn distributes DeepSeek integration across specialized modules, each targeting a specific data source.

modules/lilsplunky.py

This file implements per-log-line analysis. It monitors log files, parses individual entries, and invokes analyze_with_deepseek for each line, storing the structured results for further action.

modules/ia_network_analysis.py

Handles real-time network traffic capture using Scapy. It intercepts packets, extracts metadata (source IP, destination IP, ports), and streams them to DeepSeek for anomaly detection.

modules/ia_logs_analysis.py

Processes bulk log files in streaming mode. Unlike the line-by-line approach in lilsplunky.py, this module handles large log volumes by reading chunks and sending them to the DeepSeek API with streaming enabled.

modules/ia_code_analysis.py

Sends source code snippets to DeepSeek for security review. It constructs prompts that ask the model to identify vulnerabilities, code smells, or style violations in the provided code.

lazy_sentinel4.py

A generic LLM sentinel component that abstracts the DeepSeek integration. It includes caching mechanisms (cache_size parameter) and model-loading helpers, allowing other modules to reuse the connection logic without reimplementing the HTTP client.

Practical Code Examples

The following snippets demonstrate the integration pattern for common security analysis tasks.

Analyzing Single Log Entries

Use this pattern in modules/lilsplunky.py to evaluate individual log lines for suspicious activity:

import json
import requests
import logging
from rich.console import Console

DEEPSEEK_API_URL = "http://localhost:11434/api/generate"
DEEPSEEK_MODEL = "deepseek-r1:1.5b"
console = Console()

def analyze_log_line(log_line: str):
    prompt = f"""
    Analyze the following log entry and determine if it indicates suspicious activity.
    Respond ONLY with a valid JSON object containing:
      - "suspicious": boolean
      - "reason": string (if suspicious)
      - "severity": string (low/medium/high/critical, if suspicious)
      - "confidence": float (0.0‑1.0, if suspicious)

    Log entry:
    ```{log_line}```

    """
    response = requests.post(
        DEEPSEEK_API_URL,
        json={"model": DEEPSEEK_MODEL, "prompt": prompt, "stream": False},
        timeout=60,
    )
    response.raise_for_status()
    result = json.loads(response.text)
    # Ollama may nest the JSON inside “response”

    if isinstance(result.get("response"), str):
        result = json.loads(result["response"])
    return result

# Example usage

log = "Oct 12 08:22:01 host sshd[12345]: Failed password for root from 203.0.113.5 port 54321 ssh2"
analysis = analyze_log_line(log)
console.print(analysis)

Real-Time Network Traffic Analysis

Implement streaming analysis for live packet capture as shown in modules/ia_network_analysis.py:

import json
import requests
import logging
from scapy.all import sniff, IP, TCP, UDP
from rich.console import Console

DEEPSEEK_API_URL = "http://localhost:11434/api/generate"
DEEPSEEK_MODEL = "deepseek-r1:1.5b"
console = Console()

def analyze_packet(packet):
    info = {
        "src": packet[IP].src,
        "dst": packet[IP].dst,
        "proto": packet[IP].proto,
        "details": {}
    }
    if TCP in packet:
        info["details"]["sport"] = packet[TCP].sport
        info["details"]["dport"] = packet[TCP].dport
    elif UDP in packet:
        info["details"]["sport"] = packet[UDP].sport
        info["details"]["dport"] = packet[UDP].dport

    prompt = f"""
    Analyze the following network packet and decide if it is suspicious.
    Respond with a JSON containing "suspicious", "reason", and "details".

    Packet JSON:
    {json.dumps(info, indent=2)}
    """
    resp = requests.post(
        DEEPSEEK_API_URL,
        json={"model": DEEPSEEK_MODEL, "prompt": prompt, "stream": True},
        timeout=60,
        stream=True,
    )
    full = ""
    for chunk in resp.iter_content(chunk_size=1024):
        if chunk:
            try:
                part = json.loads(chunk.decode())
                full += part.get("response", "")
            except json.JSONDecodeError:
                continue
    console.print(full)

sniff(prn=analyze_packet, filter="ip", store=False)

Reusing LazyOwn's Helper Function

For existing LazyOwn installations, import the centralized helper to avoid code duplication:

from modules.lilsplunky import analyze_with_deepseek

log_entry = {"raw_log": "Jan 01 00:00:01 host systemd[1]: Started Session 1 of user root."}
result = analyze_with_deepseek(log_entry)   # Returns the parsed JSON dict or None

print(result)

Quick Integration Checklist

Follow these steps to activate DeepSeek API capabilities in your LazyOwn environment:

  1. Run Ollama locally and pull the DeepSeek model:

    ollama pull deepseek-r1:1.5b
    ollama serve

    The API is served on http://localhost:11434 with no external API keys required.

  2. Adjust constants in your target module (DEEPSEEK_API_URL, DEEPSEEK_MODEL) if hosting Ollama remotely or using a different model variant.

  3. Import or copy the analyze_with_deepseek helper from modules/lilsplunky.py to handle HTTP logistics and JSON parsing.

  4. Provide data (log lines, packet dictionaries, or code snippets) structured as expected by the prompt template.

  5. Handle the JSON response by checking the suspicious key and optional severity and confidence fields to trigger alerts or storage.

  6. Optional: Enable streaming by setting stream: True in the payload and iterating over response.iter_content for progressive output on large payloads.

Extending the Integration

LazyOwn’s modular architecture allows you to expand DeepSeek integration to new data sources:

  • New data sources – Create a module that builds a prompt following the existing pattern, then call requests.post with the same payload structure containing model, prompt, and stream keys.

  • Custom output schema – Modify the prompt instructions to request different JSON keys, then update the result-validation block in modules/lilsplunky.py (lines 84-88) to verify the new fields using all(k in analysis_result for k in [...]).

  • Caching – Reuse the in-memory cache implemented in lazy_sentinel4.py via the cache_size parameter to avoid duplicate API calls for identical inputs, reducing latency and system load.

Summary

  • Configure the DEEPSEEK_API_URL and DEEPSEEK_MODEL constants to point to your local Ollama instance serving DeepSeek.

  • Construct structured prompts that embed raw data and enforce JSON output schemas for consistent parsing.

  • Implement HTTP POST requests using the requests library with timeout=60 and optional stream=True for real-time analysis.

  • Validate responses by checking for required keys (suspicious, reason, severity, confidence) before processing results.

  • Extend functionality by importing analyze_with_deepseek from modules/lilsplunky.py or adapting the pattern in lazy_sentinel4.py for new data sources.

Frequently Asked Questions

What is the default DeepSeek API endpoint in LazyOwn?

The default endpoint is http://localhost:11434/api/generate, defined in modules/lilsplunky.py as the DEEPSEEK_API_URL constant. This assumes you are running Ollama locally on the default port. If you host Ollama on a different machine or port, update this constant before initializing the client.

How do I enable streaming responses from the DeepSeek API?

Set the stream parameter to True in the JSON payload when calling requests.post, then iterate over response.iter_content(chunk_size=1024) to process chunks as they arrive. This pattern is implemented in modules/ia_network_analysis.py (lines 60-68) to handle real-time packet analysis without waiting for the full model response.

Can I use a different DeepSeek model variant?

Yes. Change the DEEPSEEK_MODEL constant from the default "deepseek-r1:1.5b" to any model variant available in your Ollama installation, such as "deepseek-r1:7b" or "deepseek-coder". Ensure you have pulled the desired model using ollama pull <model_name> before running your LazyOwn module.

Where is the response validation logic located?

The validation logic that checks for required JSON keys (suspicious, reason, severity, confidence) is located in modules/lilsplunky.py at lines 84-88. The function uses all(k in analysis_result for k in [...]) to verify schema compliance before returning the result to the caller.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →