This tutorial provides a hands-on guide to implementing a custom, local AI chat interface powered by Ollama. While many turnkey solutions exist, this guide is intended for developers who want to move beyond high-level wrappers and gain granular control over how they interact with a raw Large Language Model (LLM). By the end of this article, you will understand how to manage HTTP requests, encapsulate connection logic, and maintain conversation state manually. **Prerequisites**: A working knowledge of Python and the fundamentals of asynchronous programming (`asyncio`). ## Preparation ### Step 1. Install Ollama First, you need to install the Ollama engine. Visit the [official Ollama website](https://ollama.com/download) and follow the installation instructions for your operating system. Once installed, verify the installation by checking the version in your terminal: ``` ollama --version ``` ### Step 2. Pull a Model You can explore the available model library at https://ollama.com/search. When selecting a model for local execution, it is crucial to consider your hardware constraints. Ensure your system has sufficient RAM (or VRAM if using a GPU) to hold the model weights, plus a few extra gigabytes to accommodate the context window. For this tutorial, we will use a lightweight model that runs efficiently on most modern hardware: [LFM3](https://ollama.com/library/lfm3). ``` ollama pull lfm3 ``` Once the download is complete, you can test it immediately in your terminal: ``` ollama run lfm3 ``` ### Step 3. Set Up the Python Environment We will intentionally avoid using the official [Ollama Python wrapper](https://pypi.org/project/ollama/). While convenient, wrappers often abstract away the underlying HTTP mechanics. To truly understand the interaction, we will use `aiohttp` to make raw asynchronous requests. Install the dependency via pip: ``` pip install aiohttp ``` ## Development ### 1. The Single Request Pattern Our first objective is to design the simplest possible application: a script that sends a single query to the LLM and prints the response, without any memory or conversation history. Before writing Python code, we can verify the Ollama API endpoint using `curl`. This ensures the service is reachable and the JSON structure is correct: ``` curl -X POST http://localhost:11434/api/chat \ -H 'content-type: application/json' \ -d '{"model": "lfm3", "stream": false, "messages": [{"role": "user", "content": "hi"}]}' ``` If the service is running, you will receive a JSON response. A typical response looks like this: ```json { "model": "lfm3", "created_at": "2026-11-13T13:59:36.434841537Z", "message": { "role": "assistant", "content": "Hello! How can I help you today?", "thinking": "The user says \"hi\". We need to respond in a friendly manner. There's no request for content, just greeting. So we can say hello and ask how we can help.\n\nWe should follow the policies: no disallowed content. It's fine.\n\nThus answer: \"Hello! How can I help you today?\" Possibly add something about being an AI assistant.\n\nProceed." }, "done": true, "done_reason": "stop", "total_duration": 678263079, "load_duration": 1708613, "prompt_eval_count": 11, "prompt_eval_cached_count": 0, "prompt_eval_duration": 21343000, "eval_count": 88, "eval_duration": 641932000 } ``` Now, let's replicate this behavior in Python using `aiohttp`: ```python import asyncio import aiohttp async def main(): url = 'http://localhost:11434/api/chat' data = { 'model': 'lfm3', 'stream': False, 'messages': [ { 'role': 'user', 'content': 'hi', }, ], } async with aiohttp.ClientSession() as session: async with session.post(url, json=data) as resp: result = await resp.json() print(result['message']['content']) if __name__ == "__main__": asyncio.run(main()) ``` ### 2. Implementing a Request Wrapper (The Connector) In a production-grade application, you wouldn't want to manage raw URLs and JSON payloads every time you want to talk to the AI. Instead, you should encapsulate this logic within a "Connector" class. This abstraction allows you to manage authentication, connection pooling, and error handling in one place. ```python import asyncio import aiohttp class Connector: def __init__(self, chat_url: str, model: str): self._session = None self._chat_url = chat_url self._model = model async def init(self): self._session = aiohttp.ClientSession() async def close(self): if self._session: await self._session.close() async def request(self, messages: list) -> str: data = { 'model': self._model, 'stream': False, 'messages': messages, } async with self._session.post(self._chat_url, json=data) as resp: result = await resp.json() return result['message']['content'] async def main(): conn = Connector(chat_url='http://localhost:11434/api/chat', model='lfm3') await conn.init() try: result = await conn.request([{'role': 'user', 'content': 'hi'}]) print(result) finally: await conn.close() if __name__ == "__main__": asyncio.run(main()) ``` ### 3. Managing Conversation Context A true "chat" requires memory. To achieve this, we must accumulate the history of the conversation (the "context") and send the entire thread back to the model with every new request. In this implementation, we create a `Context` class to manage the list of messages. While professional implementations might include advanced features like context window management (summarization or truncation), our basic version will focus on maintaining the message history. ```python import asyncio import aiohttp class Connector: def __init__(self, chat_url: str, model: str): self._session = None self._chat_url = chat_url self._model = model async def init(self): self._session = aiohttp.ClientSession() async def close(self): if self._session: await self._session.close() async def request(self, messages: list) -> str: data = { 'model': self._model, 'stream': False, 'messages': messages, } async with self._session.post(self._chat_url, json=data) as resp: result = await resp.json() return result['message']['content'] class Context: def __init__(self, system_prompt: str = ""): self._messages = [] if system_prompt: self._messages.append({'role': 'system', 'content': system_prompt}) @property def messages(self) -> list: return self._messages def add_user_message(self, content: str): self._messages.append({'role': 'user', 'content': content}) def add_assistant_message(self, content: str): self._messages.append({'role': 'assistant', 'content': content}) async def main(): conn = Connector(chat_url='http://localhost:11434/api/chat', model='lfm3') await conn.init() ctx = Context( system_prompt="Your name is WALL-E. Reply as this well-known robot." ) try: while True: query = input(">>> ").strip() if query == "/exit": break if query: ctx.add_user_message(query) resp = await conn.request(ctx.messages) ctx.add_assistant_message(resp) print(resp) finally: await conn.close() if __name__ == "__main__": asyncio.run(main()) ``` ## Conclusion You now have a functional, asynchronous chat client built from the ground up. By bypassing high-level libraries, you've gained the ability to manipulate the exact structure of your API calls - a skill that is essential when moving toward more complex implementations like tool-calling, streaming responses, or custom RAG (Retrieval-Augmented Generation) pipelines. Happy coding!