API Reference & Specifications
Complete Class Signatures, Parameter Specifications & Memory Lifecycles (Termux-AIChain v1.1.4)
Clean Standard Library Contracts vs Constantly Breaking Abstractions
LangChain suffers from constant breaking reorganizations across releases (langchain → langchain-community → langchain-core → langchain-experimental), heavy metaclass hierarchies, and rigid Pydantic v2 validation that breaks on Android Bionic ARM64.
termux-aichain provides clean, deterministic, Python standard-library contracts: All classes (Runnable, PromptTemplate, OpenAICompatibleChat, LocalAgent, SQLiteVectorStore) are zero-dependency, lightweight, and guaranteed backward-compatible.
1. Core Prompt & Message Schema (`termux_aichain.core`)
PromptTemplate
Represents a parameterized prompt string with format variable interpolation.
| Method | Parameters | Return Type | Technical Description |
|---|---|---|---|
from_template(template) |
template: str |
PromptTemplate |
Constructs a template parsing {variable} placeholders. |
format(**kwargs) |
kwargs: dict |
str |
Substitutes variables and produces the final formatted prompt string. |
invoke(input_dict) |
input_dict: dict |
str |
Standard LCEL Runnable invocation method. |
pipe(runnable) / __or__(runnable) |
runnable: Runnable |
RunnableSequence |
Combines the prompt into a pipe chain (e.g. prompt | llm). |
Message Types
HumanMessage(content: str): Represents a message sent from the human user.AIMessage(content: str, tool_calls: list = None): Represents an assistant model response.SystemMessage(content: str): Sets system instructions and role framing.ToolMessage(content: str, name: str, tool_call_id: str = ""): Encapsulates tool execution output.
2. Model Providers (`termux_aichain.core.providers`)
OpenAICompatibleChat
Standard zero-dependency HTTP client connecting to local llama-server, BitNet, or any OpenAI-compatible API.
| Parameter | Type | Default | Description |
|---|---|---|---|
base_url |
str |
"http://127.0.0.1:8080/v1" |
Base URL of the local or remote inference endpoint. |
model |
str |
"default" |
Target model alias or path (e.g. "llama3"). |
temperature |
float |
0.7 |
Sampling temperature (0.0 for deterministic, 1.0 for creative). |
top_p |
float |
0.95 |
Nucleus cumulative probability cutoff. |
top_k |
int |
40 |
Top-K candidate token pool limit. |
repeat_penalty |
float |
1.18 |
Frequency penalty scale to avoid repetition loops. |
max_tokens |
int |
128 |
Upper ceiling on generated tokens per invocation. |
timeout |
float |
20.0 |
Socket read timeout in seconds. |
Methods:
invoke(input_data) -> AIMessage: Executes complete inference and returns the final response.stream(input_data) -> Iterator[StreamChunk]: Yields real-time streaming tokens as they arrive.
3. Enterprise LocalAgent (`termux_aichain.core.local_agent`)
Autonomous agent supervisor supporting 4 execution topologies:
| Factory Method | Configuration Class | Topology Purpose |
|---|---|---|
LocalAgent.local(model, base_url) |
Implicit Connect | Instant 1-line connection to running local llama-server. |
LocalAgent.connect(config) |
ConnectConfig |
Explicit connection to existing port with healthcheck verification. |
LocalAgent.managed(config) |
ManagedConfig |
Spawns background llama-server subprocess and monitors its lifecycle. |
LocalAgent.remote(config) |
RemoteConfig |
Routes requests across distributed mobile cluster nodes. |
4. Output Parsers (`termux_aichain.core.parsers`)
StringOutputParser(): Converts AIMessage or stream chunks into clean raw string.JsonOutputParser(): Parses JSON markdown blocks into native Python dictionaries with auto-repair.RegexOutputParser(pattern: str): Extracts targeted capture groups via regular expressions.
5. Autonomous ReAct Agent (`termux_aichain.graph.agent`)
create_react_agent(model, tools, system_prompt="")
Compiles a cyclic StateGraph reasoning-and-acting loop with tool dispatching.
| Parameter | Type | Description |
|---|---|---|
model |
BaseChatModel |
The underlying LLM provider (e.g. OpenAICompatibleChat). |
tools |
list[Tool | Callable] |
List of tools available for the agent to call. |
system_prompt |
str |
System framing instructions defining agent persona and tool format. |
6. On-Device SQLite Vector Store (`termux_aichain.memory.sqlite`)
SQLiteVectorStore(db_path=":memory:")
Pure-math cosine similarity vector store backed by SQLite without external libraries.
| Method | Parameters | Return Type | Description |
|---|---|---|---|
add_texts(texts, vectors, metadatas=None) |
texts: list[str], vectors: list[list[float]] |
list[str] (IDs) |
Inserts documents and their embedding vectors into SQLite. |
similarity_search_by_vector(query_vector, k=4) |
query_vector: list[float], k: int |
list[Document] |
Calculates dot-product cosine similarity and returns top-K documents. |
7. Native Android Hardware Tools (`termux_aichain.device.tools`)
| Tool Function | Input Arguments | Return Payload (JSON) | Hardware Action |
|---|---|---|---|
get_battery_status() |
None | {"percentage": int, "temperature": float, "status": str} |
Inspects Android kernel sysfs / Termux-API battery state. |
get_sensor_data(sensor) |
sensor: str = "accelerometer" |
{"values": list[float], "timestamp": int} |
Reads accelerometer, ambient light, or gyroscope sensors. |
get_device_location(provider) |
provider: str = "gps" |
{"latitude": float, "longitude": float} |
Queries mobile GPS / Network location provider. |
vibrate_device(duration_ms) |
duration_ms: int = 300 |
{"vibrated": bool, "duration_ms": int} |
Triggers smartphone haptic feedback motor. |
send_notification(title, content) |
title: str, content: str |
{"posted": bool, "id": int} |
Dispatches notification to Android notification tray. |
record_speech_to_text(duration_sec) |
duration_sec: int = 5 |
{"transcript": str, "confidence": float} |
Records microphone and runs on-device speech recognition. |
execute_shell(command, timeout_sec) |
command: str, timeout_sec: float = 10.0 |
{"exit_code": int, "stdout": str, "stderr": str} |
Runs sandboxed Termux bash commands with timeout bounds. |