Lmarena.ai had a mode to ask questions about a github repo. How could i set something like tgat up locally using ollama, an llm tuned for code, and local git repos?
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Here’s one way to build a “ask‐me‐about‐my‐repo” tool locally using Ollama (for both embeddings & chat) + a vector store + your local Git repo. We’ll use Python, Chroma (a lightweight vector DB), and Ollama’s OpenAI-compatible API. Feel free to swap in your favorite LLM (llama2, code-tuned models, etc.) or vector store (Qdrant, Weaviate…).
1. Prereqs
Install Ollama and pull a code-tuned model:
bash
ollama pull llama2-chat # or code-chat-7b, etc.
Start Ollama’s local API server (v1 OpenAI-compatible):
import os, glob, tiktoken, requests
from chromadb import Client
from chromadb.config import Settings
# 1) Load code files & chunk them
def load_and_chunk(path, max_tokens=512):
enc = tiktoken.get_encoding("cl100k_base")
texts, metas = [], []
for filepath in glob.glob(f"{path}/**/*.*", recursive=True):
if any(filepath.endswith(ext) for ext in (".py",".js",".go",".rs",".java",".md")):
with open(filepath, encoding="utf8", errors="ignore") as f:
code = f.read()
tokens = enc.encode(code)
for i in range(0, len(tokens), max_tokens):
chunk = enc.decode(tokens[i : i+max_tokens])
texts.append(chunk)
metas.append({"path": filepath, "chunk_id": i//max_tokens})
return texts, metas
# 2) Embed via Ollama’s embeddings endpoint
OL_API = "http://localhost:11434/v1/embeddings"
def embed_batch(texts, model="llama2-embed-7b"):
data = {"model": model, "input": texts}
r = requests.post(OL_API, json=data)
r.raise_for_status()
# expected: { data: [ { embedding: [...] }, ... ] }
return [d["embedding"] for d in r.json()["data"]]
# 3) Upsert into a Chroma collection
chroma_client = Client(Settings(chroma_api_impl="local"))
col = chroma_client.get_or_create_collection(
name="codebase",
metadata={"repo": "my-local-repo"}
)
def index_repo(path):
texts, metas = load_and_chunk(path)
embs = embed_batch(texts)
col.add(
embeddings=embs,
documents=texts,
metadatas=metas
)
print(f"> Indexed {len(texts)} code chunks.")
if __name__ == "__main__":
index_repo("/path/to/your/repo")
Run this once (or on every update) to populate your local vector DB with chunked code + embeddings.
3. Querying & chat loop
python
import requests, json
# utility: chat completions via Ollama
CHAT_API = "http://localhost:11434/v1/chat/completions"
def ollama_chat(messages, model="llama2-chat"):
payload = {"model": model, "messages": messages}
r = requests.post(CHAT_API, json=payload)
r.raise_for_status()
return r.json()["choices"][0]["message"]["content"]
# 1) Semantic search
def semantic_search(query, k=4, embed_model="llama2-embed-7b"):
q_emb = embed_batch([query], model=embed_model)[0]
hits = col.query(
query_embeddings=[q_emb],
n_results=k,
include=["documents","metadatas","distances"]
)
return hits["documents"][0], hits["metadatas"][0]
# 2) Build a prompt & ask the LLM
def answer_question(question):
snippets, metas = semantic_search(question)
context = "\n\n".join(
f"// {m['path']} [chunk {m['chunk_id']}]\n{txt}"
for txt,m in zip(snippets, metas)
)
sys = {
"role":"system",
"content":
"You are a helpful code assistant. Use the provided code snippets to answer the user’s question."
}
usr = {
"role":"user",
"content": f"QUESTION: {question}\n\nCONTEXT:\n{context}"
}
return ollama_chat([sys, usr])
# 3) REPL
if __name__=="__main__":
print("📚 Loaded vector DB. Ask me about your code!")
while True:
q = input("\nYou: ")
if q.lower() in ("exit","quit"): break
resp = answer_question(q)
print("\n🤖:", resp)
4. How it works
Chunk & embed
We break each file into ~512-token chunks and embed them with your local Ollama embedding model.
Vector store
We use Chroma to store embeddings + text + metadata (file path, chunk id).
Semantic retrieval
On each user question we embed the query, run a k-NN search over the store, grab the top-k chunks.
LLM answer
We stitch those chunks into the system+user prompt and call Ollama’s chat endpoint. The LLM uses only the retrieved context.
🎉 That’s it! You now have a fully offline, local “ask your repo” assistant.
– Swap in any LLM model you like (e.g. code-specific), adjust chunk size, top-k, prompt style, etc.
– Switch to a more advanced retrieval framework (LangChain, LlamaIndex) or vector DB (Qdrant, Pinecone).
– Automate repo-watching or integrate this into a web UI for a more polished experience.
Happy coding! 🚀
User
As the contents of the git repo change, how do i keep the database up to date? How do i handle multiple repos and branches?
Assistant
Below is a pattern you can follow to keep your embeddings up-to-date as your repos (and branches) evolve. At a high level you’ll want to:
Track which files (and chunks) you’ve already indexed (e.g. via hashes).
On each repo change, diff against the previous state to find added/modified/deleted chunks.
Upsert new/modified embeddings and delete the removed ones.
Tag each document with repo- and branch-metadata so you can isolate or search across them.
1. Track file state with hashes
Maintain a small JSON “index state” database that maps
for every chunk you’ve ever added. On each run you:
• Walk the working tree (only the branch you’re on).
• Chunk each file exactly as before.
• For each chunk compute its SHA256.
• Compare against your saved state:
– if new key ⇒ INSERT
– if existing key but hash changed ⇒ DELETE old & INSERT new
– if old key not in this pass ⇒ DELETE
Store back the new state JSON.
python
import hashlib, json, os, glob
STATE_FILE = "index_state.json"
def load_state():
if os.path.exists(STATE_FILE):
return json.load(open(STATE_FILE))
return {}
def save_state(state):
json.dump(state, open(STATE_FILE, "w"), indent=2)
def chunk_hash(text):
return hashlib.sha256(text.encode("utf8")).hexdigest()
def generate_chunks(root, branch):
# yield (doc_id, text, metadata) just like your indexer
for filepath in glob.glob(f"{root}/**/*.*", recursive=True):
# … same chunking logic as before …
# metadata = {"repo": root_name, "branch": branch, "path": filepath, "chunk_id": i}
# yield doc_id, chunk_text, metadata
2. Upsert & Delete in Chroma
Extend your index_repo() routine to:
Load old_state & make a fresh new_state dict
User
Has someone packaged this all together already? Is there an open source project which does this?
Assistant
There isn’t really a single “one-click” tool that bundles Ollama + Chroma + Git hooks + branching logic for you, but there are a handful of open-source frameworks and example repos that cover 90% of what you’d need. You can take one of these, swap in your LLM of choice (Ollama), hook up your vector DB (Chroma, Qdrant, Weaviate, etc.), and drop in the indexing/sync code from above.
LlamaIndex (GPT-Index)
• A lightweight “index over your docs” library with built-in file loaders, vector store wrappers, and chat wrappers.
• Load your repo via SimpleDirectoryReader, build a VectorStoreIndex on Chroma, and call get_qa_chain().
• Repo: https://github.com/jerryjliu/llama_index
Haystack (deepset)
• Enterprise-grade RAG framework (open source) with file converters → document stores → retrievers → readers.
• Comes with a Chroma and Qdrant connector, plus “FARMReader” or any LLM you point at.
• https://github.com/deepset-ai/haystack
Sourcegraph (self-hosted)
• Not LLM-based out of the box, but a battle-tested self-hosted code-search + code-intel platform. You can bolt an LLM on via their extensions.
• https://github.com/sourcegraph/sourcegraph
For each chunk from generate_chunks() compute its key & hash
If key not in old_state ⇒ collect it for insert
If key in old_state but hash differs ⇒ collect it for delete + insert
Always write new_state[key] = hash
Any key in old_state but not in new_state ⇒ collect for delete
Call Chroma’s delete() for all to-delete IDs, then add() for all to-insert
python
from chromadb.utils import embedding_functions
def sync_repo_to_chroma(repo, branch, chroma_col, embed_model):
old_state = load_state()
new_state = {}
to_insert, to_delete = [], []
for doc_id, text, meta in generate_chunks(repo, branch):
key = f"{repo}/{branch}/{meta['path']}#{meta['chunk_id']}"
h = chunk_hash(text)
new_state[key] = h
if key not in old_state:
to_insert.append((doc_id, text, meta))
elif old_state[key] != h:
to_delete.append({"id": doc_id})
to_insert.append((doc_id, text, meta))
# anything removed from working tree?
for key in old_state:
if key not in new_state:
to_delete.append({"id": key})
# delete old
if to_delete:
chroma_col.delete(where={"id": [d["id"] for d in to_delete]})
# embed+insert new
if to_insert:
texts = [t for (_id, t, _m) in to_insert]
metas = [m for (_id, _t, m) in to_insert]
embs = embed_batch(texts, model=embed_model)
chroma_col.add(
embeddings=embs,
documents=texts,
metadatas=metas,
ids=[f"{repo}/{branch}/{m['path']}#{m['chunk_id']}" for m in metas]
)
save_state(new_state)
print(f"Inserted {len(to_insert)}, Deleted {len(to_delete)}")
3. Automate via Git hooks or File Watchers
Option A: Git hooks
• post-checkout, post-commit, post-merge → call a thin wrapper that runs your sync_repo_to_chroma() for the current branch.
Option B: File‐system watcher
Use Python’s watchdog to watch for file‐changes & debounce events for, say, 1 sec, then re-sync.
4. Handling multiple repos & branches
Per-branch isolation
– We tag each chunk’s metadata with "repo" and "branch".
– IDs are namespaced as "<repo>/<branch>/…"
Chroma collections
– You can have one big collection and filter at query time:
Indexing service
– A scheduled job or Git hook that runs sync_repo_to_chroma() for each repo/branch you care about.
Chat service
– When the user picks a repo & branch, pass them through to both your semantic search and your chat prompt.
With this setup you get:
• Incremental updates (no need to re-index from scratch)
• Clean handling of deletes & renames
• Easy scoping across repos & branches
Happy local LLM–powered code browsing! 🚀
RepoLLM (prototype)
• A very lightweight demo combining Qdrant + Llama2 for repo Q&A. Worth poking around if you just want a minimal end-to-end.
• https://github.com/dair-ai/RepoLLM
—
In practice most folks pick LangChain or LlamaIndex, scaffold the directory loaders + splitters + vector store you prefer, then drop in your Ollama endpoint for embeddings/chat. You get:
• 1️⃣ Data ingestion (recursive file loader → chunker)
• 2️⃣ Vector store (Chroma/Qdrant/Weaviate)
• 3️⃣ Retriever (k-NN + optional “where” filters for repo/branch)
• 4️⃣ LLM chain (system+retrieved context → chat or QA)
All of the plumbing (watchers/hooks, branch-tagging, incremental upserts, multi-repo slicing, UI, etc.) is left as “glue code,” but these four libraries give you the heavy lifting for free.