MAZHARMIK/python-ai-agent-ollama
Tentang
A local AI agent built from scratch in Python with Ollama: conversation memory, system prompts, and multi-step tool calling.
AI dan pembelajaran mesinYang dapat Anda lakukan
- 🧠 - Conversation memory - The full history is sent on every call, because the model itself has no memory
- 💬 - Saved chats - Every chat is saved as its own JSON file in chat_history/, after every completed turn. Close the agent, come back later, and continue
- ▶️ - Continue or start fresh - At start the agent asks "Continue your last chat?". Fresh is the default, and resuming is a choice
- ⌨️ - Chat commands - /new starts a fresh chat, /chats lists saved chats, /resume picks one. These are handled by our code, so the model never sees them
Pertumbuhan bintang terukur
- dalam 24 jam
- 0
- dalam 7 hari
- +2
- dalam 15 hari
- +2
- dalam 1 bulan
- +13
Perubahan bersih pada periode yang tumpang tindih, bukan total harian. Pengukuran yang belum tersedia dibiarkan kosong. Bintang menunjukkan perhatian, bukan kualitas.
README.md
Asli
| Playlist | What it covers |
|---|---|
| Tokens, embeddings, vector databases and RAG. Watch this first if the basics are new to you | |
| This project, built step by step |
🚀 What is this?

A local AI agent built from scratch in Python. It talks to a model running on Ollama through the OpenAI-compatible API, so there is no paid key and no framework hiding the logic.
It remembers the conversation, saves every chat to disk so you can resume it later, follows a system prompt, streams its answers, and can use tools in several steps. It can also answer from your own documents (RAG): it searches a small knowledge base, answers only from what it finds, cites the source, and says so when the documents do not contain the answer.
🎬 Built as part of the Advanced AI series on codestorywithMIK.
📚 New to AI? Start with the AI Fundamentals playlist (tokens, embeddings, vector databases, RAG), then follow the Advanced AI playlist where this project is built step by step.
[!NOTE] 🌱 Work in progress: This project keeps evolving as the Advanced AI playlist moves ahead. RAG and saved chats are already inside the agent, and the videos also cover vector databases (Chroma). Next on the list: trimming and summarizing long chats, and more tools.
🎥 See it in action
✨ Features
| Feature | Details | |
|---|---|---|
| 🧠 | Conversation memory | The full history is sent on every call, because the model itself has no memory |
| 💬 | Saved chats | Every chat is saved as its own JSON file in chat_history/, after every completed turn. Close the agent, come back later, and continue |
| ▶️ | Continue or start fresh | At start the agent asks "Continue your last chat?". Fresh is the default, and resuming is a choice |
| ⌨️ | Chat commands | /new starts a fresh chat, /chats lists saved chats, /resume picks one. These are handled by our code, so the model never sees them |
| 🧷 | Safe writes | A chat is written to a temporary file first and then swapped in with os.replace, so a crash while writing cannot destroy the saved chat |
| 🚫 | System prompt is never saved | It is built from code on every start, so editing the prompt applies to old chats too |
| 🎭 | System prompt | Sets the agent's behavior and style |
| 🔧 | Tool calling | Tools are described with JSON schema and run by our own code |
| 🔗 | Chained tool calls | A loop with a step limit (MAX_STEPS = 5) so it can never run forever |
| 📝 | Required parameters | get_city_weather needs a city, declared in the schema |
| 🛡️ | Safe errors | Tool failures go back to the model as text, so the program does not crash |
| 🪲 | Debug trace | Grey step-by-step logs, switched on with DEBUG=True |
| ⚡ | Streaming responses | The reply is printed token by token as the model generates it, so you do not wait for the full answer |
| ⏹️ | Stop with Ctrl+C | Press Ctrl+C while the assistant is answering to stop the stream. The partial reply is kept in the history and you can ask the next question |
| 🧵 | Streamed tool calls | Tool requests arrive in small chunks while streaming. The code stitches them together, including several tool calls in one step |
| 🚧 | Step-limit fallback | If the model has not given a final answer after MAX_STEPS, you get a clear "could not finish" message instead of a hang |
| 📚 | Agentic RAG | The model decides when to call search_knowledge_base. Our code runs the search, so the model never touches the vector store |
| ✂️ | Chunking with metadata | Each document is split at blank lines, one section per chunk, with the heading kept inside. Every chunk carries source and chunk_id |
| 💾 | Saved vector store | Chunks are embedded once and saved to vector_store.json, so the next start loads instantly with no re-embedding |
| 📎 | Grounded answers with citations | Company answers come only from the retrieved text, with a source like (leave_policy.txt #3) |
| 🧪 | Chroma example | One standalone script in Code Snippets/ shows a vector database with our own embeddings and persistence. Not wired into the agent |
🧩 How it works
The model never runs code. It only asks for a tool. Our Python code runs it, sends the result back, and the loop repeats until the model answers in plain text.
flowchart LR
U([You]) --> M[simple_ai_assistant.py]
M <-->|save and load chats| MEM[memory.py]
MEM --> CH[chat_history/*.json]
M -->|history and tool list| L{{LLM on Ollama}}
L -->|tool request| R[tools.run_tool]
R --> T1[get_current_time]
R --> T2[get_city_weather]
R --> T3[get_user_city]
R --> T4[search_knowledge_base]
T4 --> K[rag.py]
K --> V[vector_store.json]
T1 -->|result as text| M
T2 -->|result as text| M
T3 -->|result as text| M
T4 -->|top 3 chunks| M
L -->|final answer| A([Assistant])
📖 The 4-step loop in words (click to expand)
- We send the conversation plus the list of tools to the model.
- The model replies with a request such as
get_city_weather(city="Bangalore"), not an answer. - Our code runs the real function and sends the result back with the
toolrole. - The model reads the result and either asks for another tool or writes the final answer.
This repeats up to MAX_STEPS times per question.
⚡ Streaming: each call to the model is made with
stream=True. Text is printed as soon as it arrives, while any tool request is collected piece by piece and run only after the stream ends.
💬 Saved chats (persistent memory)
Memory is just the messages list. So saving memory means saving that list to a file, and loading memory means reading it back. memory.py does exactly that, with one JSON file per chat.
chat_history/
├── 2026-11-14_10-30-05.json
└── 2026-11-15_09-12-41.json
Each file looks like this:
{
"title": "My name is Mazhar",
"updated": "2026-11-14 10:32:05",
"messages": [ ...the conversation, without the system message... ]
}
How it behaves
| Moment | What happens |
|---|---|
| Start | If saved chats exist, the agent asks Continue your last chat "..."? (y/n). Answer y to resume, anything else starts a fresh chat |
| After every completed turn | The whole conversation is saved. A new chat gets a new file named by the time it started |
/new |
Starts a fresh chat. The old chat stays saved |
/chats |
Lists saved chats, most recently updated first, with title, message count and last updated time |
/resume |
Shows the list and asks for a chat number to continue |
Commands are not case sensitive, and they are handled by our code, so the model never sees them.
Design choices
- Only complete turns are saved. A tool request is never written without its result, so a saved chat is always a valid history.
- The system prompt is not saved. It is rebuilt from code on every start, so editing the prompt in
simple_ai_assistant.pyalso applies to old chats. - Safe write.
memory.pywrites to a.tmpfile first, then replaces the real file in one step. - The title is the first message of the chat, cut to 40 characters.
This is short-term memory: one conversation at a time. Remembering facts across all chats would be a separate feature.
📚 How RAG works here
RAG (Retrieval-Augmented Generation) means: find the relevant text from our own data first, and give it to the model, so it answers from that text. Three workers do three different jobs:
| Worker | Job |
|---|---|
Embedding model (nomic-embed-text) |
Turns text into vectors. It does not search |
Our Python code (rag.py) |
Compares vectors with cosine similarity, ranks the chunks, returns the top 3 |
Chat model (qwen3:4b) |
Reads the returned chunks and writes the answer |
The LLM never searches. Our Python code does.
| Phase | When | What happens |
|---|---|---|
| Indexing | Once, on the first start | Load the .txt files, split into chunks, embed every chunk, save to knowledge_base/vector_store.json |
| Querying | Every company question | The model calls search_knowledge_base, our code embeds the question, finds the top 3 chunks and returns them as a tool message. The model answers from them |
The retrieved chunks are the "augmented" part: they are added to what the model reads, only for that one call. RAG teaches the model nothing permanently.
💡 When you add a tool, update the system prompt too. If the system prompt says tools are only for time and weather, the model may never call the knowledge base tool.
🗂️ Knowledge base
The sample knowledge base is a fake company, Zorvex Technologies, so the model cannot know its facts from training. It lives in knowledge_base/:
| File | Topic |
|---|---|
leave_policy.txt |
Casual, earned, sick, maternity, paternity, bereavement leave |
medical_policy.txt |
Insurance, claims, long medical leave, maternity cover |
hr_docs.txt |
Working hours, work from home, onboarding, reviews, notice period |
hiring_process.txt |
Interview stages, offer, referral bonus, joining |
tech_docs.txt |
Code review, deployments, branches, on-call |
rca_docs.txt |
A root cause analysis report (INC-4021) |
travel_expense.txt |
Reimbursement, flights, daily allowance, receipts |
To add your own document:
- Create a
.txtfile inknowledge_base/. - Write a heading line first, then the text, with one blank line between sections. Each section becomes one chunk.
- Delete
knowledge_base/vector_store.jsonand run the agent. It rebuilds the store.
Try these questions:
How many weeks of maternity leave do I get?How do I get my money back after a business trip?How much sick leave do I get, and what if I need more?What are the core working hours at Zorvex, and what time is it now?What was the root cause of INC-4021?What is the company's policy on pet insurance?(not in any document)What is Python?(general question, no search)
🧪 Vector database example (Chroma)
The agent keeps its vectors in a simple JSON file, vector_store.json, so you can see exactly what is inside. A vector database does the same job with more features: saving to disk, fast approximate search, update and delete by ID, metadata filtering and scale.
Code Snippets/chroma_simple.py is a small standalone example of Chroma, a free vector database that runs on your laptop. It:
- embeds four sample chunks with our own
nomic-embed-textmodel, - stores them with
PersistentClient(saved to thechromadbStorage/folder), - uses cosine distance,
- and searches with
query_embeddings, so the question and the chunks use the same embedding model.
upsert makes the script safe to re-run, because it updates an ID that already exists instead of failing.
pip install chromadb
python3 "Code Snippets/chroma_simple.py"
The agent itself does not use Chroma yet. Only
rag.pywould need to change, because the tool just callssearch().chromadbis not inrequirements.txt, because the agent does not need it.
🛠️ Available tools
| Tool | What it does |
|---|---|
get_current_time |
Returns the current local date and time |
get_city_weather(city) |
One-line weather from the free wttr.in service |
get_user_city |
Returns the user's city (hard-coded to Bangalore as a demo value) |
search_knowledge_base(query) |
Searches the company documents and returns the top 3 matching chunks, each labelled with its source |
⚡ Quick start
Prerequisites: Python 3.10+ and Ollama installed and running.
# 1. Download the chat model and the embedding model
ollama pull qwen3:4b
ollama pull nomic-embed-text
# 2. Get the code
git clone https://github.com/MAZHARMIK/python-ai-agent-ollama.git
cd python-ai-agent-ollama
# 3. Create and activate a virtual environment
python -m venv .venv
# Windows: .venv\Scripts\activate
# Mac/Linux: source .venv/bin/activate
# 4. Install dependencies
pip install -r requirements.txt
# 5. Create your settings file
cp .env.example .env # Windows: copy .env.example .env
# 6. Run (from the project root)
python simple_ai_assistant.py
Type exit, quit, bye or goodbye to stop. Chat commands: /new, /chats, /resume.
⏳ First start: the agent builds the vector store once (it embeds every chunk), so expect a short pause before the first prompt. Later starts load
vector_store.jsoninstantly.
💬 Next starts: if you have saved chats, the agent asks whether to continue the last one. Your chats are saved in
chat_history/.
📂 Always run the agent from the project root, because paths in
.envare relative.
⚙️ Configuration
Settings live in .env (see .env.example):
| Name | Meaning |
|---|---|
BASE_URL |
OpenAI-compatible endpoint. For Ollama: http://127.0.0.1:11434/v1 |
API_KEY |
Required by the client, ignored by Ollama. Any dummy value works |
MODEL |
Exact model name from ollama list. It must support tool calling |
DEBUG |
Set to True (capital T) to show the grey debug trace |
EMBED_MODEL |
The embedding model, for example nomic-embed-text. This is not the chat model |
KB_FOLDER |
Folder with your .txt documents. Default: knowledge_base |
VECTOR_STORE_FILE |
Where the embedded chunks are saved. Default: knowledge_base/vector_store.json |
CHAT_FOLDER |
Folder where saved chats go, one JSON file per chat. Set it to chat_history |
💡 Rules for
.env:NAME=value, no spaces around=, no quotes. Restart the program after editing it.
➕ Add your own tool
Three changes in tools.py, and the chat loop stays untouched:
- ✍️ Write the Python function.
- 📋 Add its description to the
TOOLSlist (name, description, parameters,required). - 🗺️ Register it in
FUNCTION_NAME_TO_FUNCTION_MAP.
The
descriptionmatters: the model reads it to decide when to use the tool.
Also check the system prompt in simple_ai_assistant.py, so it does not tell the model to avoid your new tool.
📁 Project structure
python-ai-agent-ollama/
├── simple_ai_assistant.py chat loop, streaming, the agent loop and the /new /chats /resume commands
├── tools.py tool functions, TOOLS schema, run_tool()
├── rag.py chunking, embeddings, vector store and search()
├── memory.py save_chat(), load_chat(), list_chats() for saved chats
├── knowledge_base/
│ ├── *.txt the 7 sample documents (Zorvex Technologies)
│ └── vector_store.json generated on the first run (not committed)
├── chat_history/ one JSON file per saved chat (generated, not committed)
├── Utilities/
│ └── utilities.py grey debug log() helper
├── Code Snippets/ scratch experiments from the videos, including a Chroma example (not imported by the agent)
├── .env.example settings template
├── requirements.txt dependencies
└── LICENSE MIT
⚠️ Honest limitations
- Saved chats keep growing and the history is not trimmed. Resuming a very long chat can exceed the model's context window, and nothing warns you yet.
- Chats are saved as plain text on disk, including tool results and retrieved document chunks.
chat_history/is git-ignored, but nothing is encrypted. Chat titles are your first message, so they can contain private text. - A saved chat can hold old tool results. If a document changes later, the old answer in that chat still quotes the old text.
- This is short-term memory only: one conversation at a time. The agent does not carry facts from one chat to another.
- A damaged chat file can stop the agent at startup. If that happens, delete that file from
chat_history/. - Two copies of the agent running at once can overwrite each other's chat file.
- Small local models can pick the wrong tool or skip arguments. A larger model is more reliable.
get_user_cityis a hard-coded demo value. In a real app it would come from a profile or database.- The weather tool needs internet, and
wttr.inis a free service that can be slow or down. - Tool output is not treated as untrusted, which is why the tools are read-only. Only put documents you trust in the knowledge base.
- If you press
Ctrl+Cwhile the model is answering, any half-received tool request is dropped and only the partial text is kept in the history. PressingCtrl+Cat theMIK:prompt ends the program, and your last completed turn is already saved. - The vector store can go stale. Editing a document or changing
EMBED_MODELdoes not rebuild it automatically. Deletevector_store.jsonto rebuild. - There is no score threshold. The search always returns the top 3 chunks, even when none is relevant. Saying “I could not find this” depends on the model following the system prompt, and a small model may ignore it.
- Retrieval can return the wrong chunk, and the model may then answer confidently from it. Turn on
DEBUG=Trueto check which chunks were retrieved. - Embeddings are weaker on exact strings such as IDs and error codes. Real systems often add keyword search too (hybrid search).
- Search compares the question with every chunk (brute force). Fine for a small knowledge base, too slow for millions. Vector databases (see the Chroma example) solve that, but the agent does not use one yet.
- Splitting by blank-line sections works because the sample documents are written in sections. Other documents may need other chunking strategies.
🙌 If this helped you, a ⭐ goes a long way. Thank you!
Licensed under MIT
☕ Support codestorywithMIK (No Pressure)
Education here is 100% free and always will be. 💙 If the content helped you and you'd like to support the channel with a coffee:
UPI: imammazhar4@ybl
Jelajahi proyek terkait
Memuat…