Quickstart & Execution Recipes
Practical production patterns for local LLMs, StateGraph agents, memory, and multimodal tools
Recipe 1: 1-Line LCEL Pipe Chaining
Compose deterministic prompt templates, local model inferencing, and JSON output parsing using the standard pipe operator (|):
from termux_aichain import PromptTemplate, JsonOutputParser, OpenAICompatibleChat
# 1. Define prompt template and JSON parser
prompt = PromptTemplate.from_template(
"Extract structured system status from log:\n{log}\nRespond in JSON with fields 'level', 'code', 'message'."
)
parser = JsonOutputParser()
# 2. Connect to local llama-server / BitNet endpoint
llm = OpenAICompatibleChat(base_url="http://127.0.0.1:8080/v1", temperature=0.1)
# 3. Assemble LCEL pipe chain
chain = prompt | llm | parser
# 4. Execute synchronously
result = chain.invoke({"log": "CRITICAL: Kernel thermal throttling triggered at 48C (Code 104)"})
print("Parsed JSON Result:", result)
Recipe 2: Autonomous ReAct Multi-Agent with StateGraph
Assemble autonomous reasoning and tool-calling agents with cyclic routing and safety iteration limits:
from termux_aichain import (
create_react_agent,
BitNetChat,
HumanMessage,
get_battery_status,
vibrate_device,
transcribe_speech
)
# 1. Initialize local brain
model = BitNetChat(base_url="http://127.0.0.1:8080/v1", temperature=0.1)
# 2. Construct autonomous ReAct agent with hardware tools
agent = create_react_agent(
model=model,
tools=[get_battery_status, transcribe_speech, vibrate_device],
system_prompt="You are a sovereign mobile agent running on Android Termux."
)
# 3. Execute multi-step reasoning and acting loop
state = agent.invoke({
"messages": [HumanMessage(content="Check battery percentage and vibrate device for 500ms if battery > 50%.")]
})
print("Agent Final Response:", state["messages"][-1].content)
Recipe 3: SQLite Long-Term Memory & Pure Cosine Vector RAG
Persistent ACID key-value storage and vector similarity search without ChromaDB, FAISS, or NumPy:
from termux_aichain import SQLiteEntityMemory, SQLiteVectorStore
# 1. Persistent Key-Value Entity Memory
memory = SQLiteEntityMemory(db_path="mobile_agent.db")
memory.save_entity("device_owner", "Dr. Uno Kim")
memory.save_entity("preferred_model", "BitNet-3B-1.58b")
print("Retrieved Owner:", memory.get_entity("device_owner"))
# 2. Pure Cosine Vector Store (No NumPy / ChromaDB needed)
vector_store = SQLiteVectorStore(db_path="vector_rag.db")
vector_store.add_texts(
texts=["Android Bionic Subsystem Architecture", "WebGPU Neural Compute Shaders"],
embeddings=[[0.92, 0.38, 0.05], [0.12, 0.44, 0.89]],
metadatas=[{"source": "os_doc"}, {"source": "gpu_doc"}]
)
matches = vector_store.similarity_search_by_vector([0.90, 0.40, 0.00], k=1)
print("Top RAG Match:", matches[0].page_content, f"(Score: {matches[0].score:.4f})")
Recipe 4: 1-Line REST, SSE Streaming Server & Web Dashboard
from termux_aichain import create_react_agent, OpenAICompatibleChat, serve, get_battery_status
llm = OpenAICompatibleChat(base_url="http://127.0.0.1:8080/v1")
agent = create_react_agent(model=llm, tools=[get_battery_status])
# Starts REST API (POST /v1/agent/invoke, POST /v1/agent/stream) and Web Dashboard UI
serve(agent, host="0.0.0.0", port=8000)
Recipe 5: Node.js ESM Native Autonomous Agent
import {
PromptTemplate,
JsonOutputParser,
OpenAICompatibleChat,
StateGraph,
START,
END,
MicroVectorStore,
getDefaultDeviceTools
} from "termux-aichain";
// 1. In-Memory Micro Vector Store
const vectorStore = new MicroVectorStore();
vectorStore.addTexts(
["Linux Kernel Bionic", "ARM NEON SIMD"],
[[1.0, 0.0], [0.0, 1.0]]
);
const matches = vectorStore.similaritySearchByVector([0.98, 0.02], 1);
console.log("Vector Match:", matches[0].content, `(Score: ${matches[0].score.toFixed(4)})`);
// 2. Cyclic StateGraph Compilation
const workflow = new StateGraph();
workflow.addNode("counter", (state) => ({ step: (state.step || 0) + 1 }));
workflow.setEntryPoint("counter");
workflow.addConditionalEdges("counter", (state) => (state.step >= 3 ? END : "counter"));
const app = workflow.compile();
const result = await app.invoke({ step: 0 });
console.log("Graph Execution Result:", result);