-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathask_code.py
More file actions
65 lines (50 loc) · 1.93 KB
/
Copy pathask_code.py
File metadata and controls
65 lines (50 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import sys
from langchain_ollama import OllamaEmbeddings, ChatOllama
from langchain_chroma import Chroma
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough
from langchain_core.documents import Document
CHROMA_PATH = "./chroma_db"
EMBED_MODEL = "nomic-embed-text"
LLM_MODEL = "phi3:mini"
PROMPT_TEMPLATE = """
You are a senior engineer helping a developer understand a codebase.
Answer using only the code context provided. Always mention the source file.
If the answer isn't in the context, say so.
Context:
{context}
Question: {question}
Answer:"""
def format_docs(docs):
return "\n\n---\n\n".join(
f"# {doc.metadata.get('source', 'unknown')}\n{doc.page_content}"
for doc in docs
)
def _get_retriever(collection_name: str, k: int):
embeddings = OllamaEmbeddings(model=EMBED_MODEL)
db = Chroma(
persist_directory=CHROMA_PATH,
embedding_function=embeddings,
collection_name=collection_name,
)
return db.as_retriever(search_kwargs={"k": k})
def get_sources(question: str, collection_name: str = "codebase", k: int = 5) -> list[Document]:
return _get_retriever(collection_name, k).invoke(question)
def build_chain(collection_name: str = "codebase", temperature: float = 0.0, k: int = 5):
retriever = _get_retriever(collection_name, k)
llm = ChatOllama(model=LLM_MODEL, temperature=temperature)
prompt = ChatPromptTemplate.from_template(PROMPT_TEMPLATE)
return (
{"context": retriever | format_docs, "question": RunnablePassthrough()}
| prompt
| llm
| StrOutputParser()
)
if __name__ == "__main__":
question = " ".join(sys.argv[1:])
if not question:
print("Usage: uv run python ask_code.py \"how does auth work?\"")
sys.exit(1)
print(f"\nQ: {question}\n")
print(build_chain().invoke(question))