Tauri: Python, LangGraph a Sidecar pattern — AI mozog v Ruste (Časť 2)
Tauri: Keď Rust stretne Python a LangGraph
V predchádzajúcej časti sme si ukázali, prečo je Tauri rýchlejší a menší ako Electron a ako funguje Rust backend s webovým frontendom. Teraz prichádza to najzaujímavejšie — čo ak potrebujete AI, ML alebo LangGraph?
Rust je fantastický na rýchle operácie, ale Python ekosystém pre AI/ML je neprekonateľný. Tauri má na to elegantné riešenie — Sidecar pattern.
Architektúra s Python backendom
┌─────────────────────────────────────────────────┐
│ Tauri Application │
│ │
│ ┌───────────────────────────────────────────┐ │
│ │ Frontend (React) │ │
│ │ │ │
│ │ invoke() ─── Tauri IPC ──▶ Rust Backend │ │
│ │ fetch() ─── HTTP ──────▶ Python Sidecar │ │
│ └───────────────────────────────────────────┘ │
│ │
│ ┌─────────────────┐ ┌────────────────────┐ │
│ │ Rust Backend │ │ Python Sidecar │ │
│ │ │ │ │ │
│ │ • File ops │ │ • LangGraph agent │ │
│ │ • System APIs │ │ • ML inference │ │
│ │ • Performance │◄──▶│ • AI pipelines │ │
│ │ • Process mgmt │ │ • Data processing │ │
│ │ │ │ │ │
│ │ Spúšťa a riadi │ │ FastAPI server │ │
│ │ Python proces │ │ localhost:8000 │ │
│ └─────────────────┘ └────────────────────┘ │
└─────────────────────────────────────────────────┘Princíp je jednoduchý: Rust spúšťa Python ako samostatný proces (sidecar). Frontend komunikuje s Rustom cez IPC a s Pythonom cez HTTP. Každý jazyk robí to, v čom je najlepší.
Krok 1: Python backend s FastAPI + LangGraph
# 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):
"""Agent analyzuje vstup a rozhodne sa, čo ďalej"""
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 pre LangGraph agenta"""
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 analýza dokumentu"""
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)Krok 2: Rust spúšťa Python sidecar
// src-tauri/src/lib.rs
use tauri::Manager;
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
tauri::Builder::default()
.setup(|app| {
// Spustenie Python sidecar ako externý binárny súbor
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");
}
// Rýchle Rust operácie
#[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)
}Krok 3: Tauri konfigurácia
{
"bundle": {
"externalBin": [
"binaries/python-backend"
]
},
"app": {
"security": {
"csp": "default-src 'self'; connect-src 'self' http://localhost:8000"
}
}
}Krok 4: Frontend využíva obe strany
// src/App.tsx
import { invoke } from '@tauri-apps/api/core';
function App() {
// Rust pre rýchle file operácie
const loadFile = async (path: string) => {
const content = await invoke<string>('process_large_file', { path });
return content;
};
// Python pre AI analýzu
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();
};
// Kombinácia: Rust číta súbor → Python analyzuje
const handleAnalyze = async () => {
// 1. Rust: Bleskové načítanie súboru
const content = await loadFile(selectedFile);
// 2. Python + LangGraph: AI analýza obsahu
const analysis = await analyzeWithAI(content);
setResult(analysis);
};
return (
<div>
<button onClick={handleAnalyze}>
Analyzuj dokument s AI
</button>
</div>
);
}Každý jazyk robí to, v čom je najlepší
┌──────────────────────────────────────────────────┐
│ │
│ RUST (rýchly kôň) PYTHON (AI mozog) │
│ ───────────────── ──────────────── │
│ • File I/O • LangGraph agent │
│ • System APIs • ML modely │
│ • Kryptografia • Data science │
│ • Paralelné spracovanie • NLP pipelines │
│ • Process management • RAG systémy │
│ • Sieťové operácie • Prompt chaining │
│ │
│ Výkon: ~C/C++ level Ekosystém: 500k+ │
│ RAM: minimálna knižníc pre AI/ML │
│ │
└──────────────────────────────────────────────────┘Reálne use-casy
1. Lokálny AI Document Analyzer
- Rust: Rýchle načítanie a parsovanie PDF/DOCX
- Python + LangGraph: Sumarizácia, extrakcia kľúčových informácií, Q&A
2. Offline Code Assistant
- Rust: Navigácia v súborovom systéme, syntax highlighting
- Python + lokálny LLM: Code review, generovanie testov, refactoring návrhy
3. Data Pipeline Builder (GUI)
- Rust: Drag-and-drop UI operácie, real-time preview
- Python + pandas/polars: Transformácie dát, vizualizácie
4. Privacy-first Chat App
- Rust: Šifrovanie, key management, systémové notifikácie
- Python + LangGraph: Konverzačný agent, pamäť, tool calling
Packaging: Jeden inštalátor, všetko vnútri
Najčastejšia otázka: "Ale ako distribuujem Python s Tauri appkou?"
PyInstaller zabalia Python do jedného exe
# Zbuildujte Python backend do standalone executable
pyinstaller --onefile \
--name python-backend \
--hidden-import=uvicorn \
--hidden-import=langgraph \
python-backend/main.py
# Výsledok: dist/python-backend.exe (~50-80 MB)
# Skopírujte do Tauri binaries
cp dist/python-backend src-tauri/binaries/python-backend-x86_64-pc-windows-msvc# Build Tauri appky (vrátane Python sidecar)
npm run tauri build
# Výsledok:
# src-tauri/target/release/bundle/
# ├── msi/YourApp_1.0.0_x64.msi (~60-90 MB)
# └── nsis/YourApp_1.0.0_x64-setup.exePorovnanie veľkosti:
- Electron + Python: ~350 MB
- Tauri + Python (sidecar): ~60-90 MB
- Tauri bez Pythonu: ~3-5 MB
Záver
Tauri je ako závodný tím Formuly 1. Rust je motor — rýchly, efektívny, spoľahlivý. Python je stratég — inteligentný, s prístupom k obrovskému ekosystému AI nástrojov. A webový frontend je karoséria — krásna, známa každému web developerovi.
Výsledok? Desktopová aplikácia, ktorá je rýchla ako natívna, inteligentná vďaka LangGraphu a stojí zlomok toho, čo by vás stál Electron. Za málo peňazí, veľa muziky.