This repository (oterm) provides a terminal-based chat interface for interacting with local language models using the Ollama server. The CLI functionalities are built using Typer for command-line interface management and Textual for building the terminal UI. Here's a breakdown of how the repository integrates CLI features to create a chat interface:
1. CLI Commands and Entry Point
The CLI interface for oterm is implemented in the file ./repos/oterm/src/oterm/cli/oterm.py.
Key Components:
Typer for CLI Commands:
The typer.Typer() object (cli) is used to define CLI commands. The oterm command is the main entry point.
py
cli = typer.Typer()
CLI Command Options:
Several command-line options are defined to handle different tasks:
--version: Displays the version of oterm.
--upgrade: Upgrades the database.
--config: Prints environment configuration.
--db: Displays the location of the SQLite database.
Running the Chat Application:
If none of the CLI options (--version, --upgrade, etc.) are provided, the app.run() method is called to launch the chat interface:
py
app.run()
Asynchronous Database Upgrades:
The upgrade_db function ensures the database schema is up-to-date using the Store module:
py
async def upgrade_db():
await Store.get_store()
The CLI acts as a gateway that either performs management tasks or launches the chat interface.
2. Terminal User Interface (TUI)
The core chat functionality is implemented in the ./repos/oterm/src/oterm/app/oterm.py file using Textual, a Python framework for creating terminal applications with rich UI components.
Key Components:
Textual App Class:
The OTerm class extends Textual.app.App and serves as the main application class for the terminal UI. It defines the application's layout, behavior, and interaction with the language model.
py
class OTerm(App):
TITLE = "oTerm"
SUB_TITLE = "A terminal-based Ollama client."
UI Layout:
The layout includes:
A header (Header).
A tabbed content area (TabbedContent) for managing multiple chat sessions.
Tabbed Chats:
The TabbedContent widget allows switching between multiple chat sessions. Each session corresponds to a TabPane, and when a tab is activated, it loads the respective chat messages.
Command Palette:
Users can invoke commands like creating a new chat, editing parameters, exporting chat history, etc., via a command palette. These commands are registered as SystemCommand actions.
Example commands:
py
def get_system_commands(self, screen: Screen) -> Iterable[SystemCommand]:
yield SystemCommand("New chat", "Creates a new chat", self.action_new_chat)
yield SystemCommand("Export chat", "Exports the current chat as Markdown", self.action_export_chat)
```
Theme Customization:
Users can toggle between light and dark themes, and the theme preference is persisted in the configuration file managed by .
3. Chat Logic
The chat logic is handled by the ChatContainer class in ./repos/oterm/src/oterm/app/widgets/chat.py. This class represents an individual chat session.
Key Components:
Chat History:
The messages property holds a list of messages exchanged between the user and the model. These messages are displayed in the messageContainer widget.
User Input Handling:
The FlexibleInput widget captures user input. When a user submits a message, it's processed by the on_submit method. This method sends the message to the language model (via the ollama client) and displays the response.
py
@on(FlexibleInput.Submitted)
async def on_submit(self, event: FlexibleInput.Submitted) -> None:
message = event.value
async for text in self.ollama.stream(message):
response_chat_item.text = text
Model Integration:
The OllamaLLM client (from ollamaclient.py) handles communication with the local language model server. It supports streaming responses and additional features like "tools".
py
response = await self.ollama.completion(prompt=message, images=[img for _, img in self.images])
Multi-Modal Support:
Users can include images with chat messages. The ImageAdded event allows users to attach images to the next message.
Tools API:
The application supports tools (e.g., fetching current weather) via the tools parameter. These tools are external functions that augment the model's capabilities.
4. Persistent Storage
The application uses an SQLite database to store chat sessions, messages, and configurations. The Store module handles all database interactions.
Key Features:
Saving Messages:
Chat messages are saved in the database using the save_message method. This ensures that chat history is persistent.
py
id = await store.save_message(
id=None,
chat_id=self.db_id,
author=Author.USER.value,
text=message,
)
Loading Chats:
When the app starts, it loads all saved chat sessions from the database and populates the tabs.
py
saved_chats = await store.get_chats()
Upgrading Database Schema:
The v0_6_0.py file includes functions for upgrading the database schema, such as adding new columns for tools.
The application uses AppConfig (from config.py) to manage user-specific settings like themes, splash screens, and key bindings. These settings are stored in a JSON file in the data directory.
6. Key Bindings and Shortcuts
Keyboard shortcuts enhance usability:
Ctrl+Tab / Ctrl+Shift+Tab: Cycle through chats.
Ctrl+Q: Quit the application.
Esc: Cancel message generation.
↑: Navigate through prompt history.
Custom key bindings can be defined in the config.json file.
Summary
The repository combines Typer for CLI commands, Textual for the terminal UI, and SQLite for persistent storage to create a robust terminal-based chat interface for local language models. It supports multi-session chat, model customization, multi-modal inputs, and experimental tooling, all accessible via an intuitive command-line interface.
AppConfig
py
theme = appConfig.get("theme")
if theme == "dark":
self.theme = "textual-dark"