Contents
Tauri: Python, LangGraph and the Sidecar Pattern — an AI Brain in Rust (Part 2)

Tauri: When Rust Meets Python and LangGraph

In the previous part, we looked at why Tauri can be faster and smaller than Electron, and how a Rust backend works with a web frontend. Now for the interesting question: what if you need AI, ML or LangGraph?

Rust is excellent for fast operations, while Python has an extensive AI/ML ecosystem. Tauri offers an elegant way to combine them: the sidecar pattern.

Architecture with a Python backend

Tauri application
├── Frontend (React)
│   ├── invoke() → Tauri IPC → Rust backend
│   └── fetch()  → HTTP → Python sidecar
├── Rust backend: file operations, system APIs, performance, process management
│   └── Starts and manages the Python process
└── Python sidecar: LangGraph agent, ML inference, AI pipelines, data processing
    └── FastAPI server on localhost:8000

The principle is simple: Rust starts Python as a separate sidecar process. The frontend communicates with Rust through IPC and with Python over HTTP. Each language handles the work it is best suited to.

Step 1: Python backend with FastAPI and LangGraph

python
# python-backend/main.py
from fastapi import FastAPI
from langgraph.graph import StateGraph, END
from langchain_openai import ChatOpenAI
import uvicorn

app = FastAPI()

# LangGraph agent definition
def create_agent():
    llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)

    def analyze_node(state):
        """The agent analyzes the input and decides what to do next."""
        response = llm.invoke(state["messages"])
        return {"messages": state["messages"] + [response]}

    def should_continue(state):
        last_message = state["messages"][-1]
        if hasattr(last_message, "tool_calls") and last_message.tool_calls:
            return "tools"
        return END

    graph = StateGraph(dict)
    graph.add_node("analyze", analyze_node)
    graph.add_conditional_edges("analyze", should_continue)
    graph.set_entry_point("analyze")

    return graph.compile()

agent = create_agent()

@app.post("/api/chat")
async def chat(request: dict):
    """Endpoint for the LangGraph agent."""
    result = agent.invoke({
        "messages": [("human", request["message"])]
    })
    return {"response": result["messages"][-1].content}

@app.post("/api/analyze-document")
async def analyze_document(request: dict):
    """AI document analysis."""
    result = agent.invoke({
        "messages": [("human", f"Analyzuj tento dokument: {request['content']}")]
    })
    return {"analysis": result["messages"][-1].content}

@app.get("/health")
async def health():
    return {"status": "ok"}

if __name__ == "__main__":
    uvicorn.run(app, host="127.0.0.1", port=8000)

Step 2: Rust starts the Python sidecar

rust
// src-tauri/src/lib.rs
use tauri::Manager;

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    tauri::Builder::default()
        .setup(|app| {
            // Start the Python sidecar as an external binary
            let sidecar_command = app
                .shell()
                .sidecar("python-backend")
                .expect("Failed to create sidecar command")
                .env("PYTHONUTF8", "1");

            let (mut _rx, _child) = sidecar_command
                .spawn()
                .expect("Failed to spawn python backend");

            println!("Python sidecar started on localhost:8000");
            Ok(())
        })
        .invoke_handler(tauri::generate_handler![
            process_large_file,
            get_system_info,
        ])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}

// Fast Rust operations
#[tauri::command]
fn process_large_file(path: String) -> Result<String, String> {
    let content = std::fs::read_to_string(&path)
        .map_err(|e| e.to_string())?;
    Ok(content)
}

Step 3: Tauri configuration

json
{
  "bundle": {
    "externalBin": [
      "binaries/python-backend"
    ]
  },
  "app": {
    "security": {
      "csp": "default-src 'self'; connect-src 'self' http://localhost:8000"
    }
  }
}

Step 4: The frontend uses both sides

tsx
// src/App.tsx
import { invoke } from '@tauri-apps/api/core';

function App() {
  // Rust for fast file operations
  const loadFile = async (path: string) => {
    const content = await invoke<string>('process_large_file', { path });
    return content;
  };

  // Python for AI analysis
  const analyzeWithAI = async (content: string) => {
    const response = await fetch('http://localhost:8000/api/analyze-document', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ content }),
    });
    return response.json();
  };

  // Combine them: Rust reads the file, Python analyzes it
  const handleAnalyze = async () => {
    // 1. Rust: fast file loading
    const content = await loadFile(selectedFile);

    // 2. Python + LangGraph: AI analysis of the content
    const analysis = await analyzeWithAI(content);

    setResult(analysis);
  };

  return (
    <div>
      <button onClick={handleAnalyze}>
        Analyze document with AI
      </button>
    </div>
  );
}

Each language does what it does best

RUST: THE FAST ENGINE             PYTHON: THE AI BRAIN
• File I/O                        • LangGraph agent
• System APIs                     • ML models
• Cryptography                    • Data science
• Parallel processing             • NLP pipelines
• Process management              • RAG systems
• Network operations              • Prompt chaining

Rust: performance around C/C++ level, minimal RAM
Python: a large ecosystem of AI/ML libraries

Practical use cases

1. Local AI document analyzer

  • Rust: fast loading and parsing of PDF/DOCX files
  • Python + LangGraph: summarization, key information extraction and Q&A

2. Offline code assistant

  • Rust: filesystem navigation and syntax highlighting
  • Python + a local LLM: code review, test generation and refactoring suggestions

3. Data pipeline builder (GUI)

  • Rust: drag-and-drop UI operations and real-time preview
  • Python + pandas/polars: data transformations and visualizations

4. Privacy-first chat app

  • Rust: encryption, key management and system notifications
  • Python + LangGraph: conversational agent, memory and tool calling

Packaging: one installer, everything inside

The common question is: “How do I distribute Python with a Tauri app?”

PyInstaller packages Python into one executable

bash
# Build the Python backend as a standalone executable
pyinstaller --onefile \
  --name python-backend \
  --hidden-import=uvicorn \
  --hidden-import=langgraph \
  python-backend/main.py

# Result: dist/python-backend.exe (~50-80 MB)
# Copy it into the Tauri binaries directory
cp dist/python-backend src-tauri/binaries/python-backend-x86_64-pc-windows-msvc
bash
# Build the Tauri app, including the Python sidecar
npm run tauri build

# Result:
# src-tauri/target/release/bundle/
# ├── msi/YourApp_1.0.0_x64.msi     (~60-90 MB)
# └── nsis/YourApp_1.0.0_x64-setup.exe

Size comparison:

  • Electron + Python: ~350 MB
  • Tauri + Python sidecar: ~60–90 MB
  • Tauri without Python: ~3–5 MB

Conclusion

Tauri is like a Formula 1 team. Rust is the engine: fast, efficient and reliable. Python is the strategist, with access to a vast ecosystem of AI tools. And the web frontend is the bodywork, familiar to web developers.

The result is a desktop application that combines native speed with LangGraph's intelligence, at a fraction of the size of an Electron-based alternative.

All articles