<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Tarunyash on Medium]]></title>
        <description><![CDATA[Stories by Tarunyash on Medium]]></description>
        <link>https://medium.com/@tarunyash01?source=rss-e96ab604dc35------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*9f0EPIvQTB7r3mdA</url>
            <title>Stories by Tarunyash on Medium</title>
            <link>https://medium.com/@tarunyash01?source=rss-e96ab604dc35------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 19:02:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tarunyash01/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[CodeComp v2: From Understanding Code to Acting on It]]></title>
            <link>https://medium.com/@tarunyash01/codecomp-v2-from-understanding-code-to-acting-on-it-9fffb5bda2be?source=rss-e96ab604dc35------2</link>
            <guid isPermaLink="false">https://medium.com/p/9fffb5bda2be</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Tarunyash]]></dc:creator>
            <pubDate>Sun, 03 May 2026 17:26:36 GMT</pubDate>
            <atom:updated>2026-05-03T17:26:36.492Z</atom:updated>
            <content:encoded><![CDATA[<p>In the first version, the goal was simple:</p><blockquote><em>Give it a repository → ask a question → get a grounded answer.</em></blockquote><p>That worked. But real workflows don’t stop at understanding.</p><p>You don’t just ask: “What does this do?”</p><p>You also want to:</p><ul><li>“Fix this”</li><li>“Add this”</li><li>“Change this”</li></ul><p>So the system needed to evolve.</p><h3>From Q&amp;A to Decisions</h3><p>Every query now falls into two categories:</p><ul><li><strong>Explain</strong> → understand the codebase</li><li><strong>Act</strong> → modify the codebase</li></ul><p>At first, routing was keyword-based.</p><p>That failed quickly.</p><blockquote><em>“create a file” vs “how do I create a file?”</em></blockquote><p>Same words, different intent.</p><p>So routing moved to an LLM.</p><p>Not to generate answers but to decide what kind of system should handle the query.</p><h3>Adding a Debugger Agent</h3><p>Once queries could be classified, the next step was execution.</p><p>A second agent was introduced: <em>the debugger agent</em></p><p>Instead of explaining code, it:</p><ul><li>creates files</li><li>modifies code</li><li>runs commands</li></ul><p>The key difference:</p><pre>Reasoning agent → generates answers  <br>Debugger agent → produces actions</pre><p>For example:</p><pre>{<br>  &quot;action&quot;: &quot;run_command&quot;,<br>  &quot;cmd&quot;: &quot;mkdir -p agents &amp;&amp; touch agents/xyz.py&quot;<br>}</pre><p>The system executes this, not the model.</p><p>This shifts control: <em>from text generation → system state changes</em></p><h3>From Single-Step to Multi-Step (ReAct)</h3><p>Single-step execution wasn’t enough.</p><p>Tasks like <em>“create a file and add code” </em>require multiple steps.</p><p>So the debugger was extended into a loop:</p><pre>Reason → Act → Observe → Repeat</pre><p>Each step:</p><ul><li>decide next action</li><li>execute</li><li>feed result back</li></ul><p>This makes behavior adaptive, not static.</p><p>But it also introduces a problem: <em>the model must reliably choose to act not just explain.</em></p><p>This is still inconsistent.</p><pre>from dotenv import load_dotenv<br>load_dotenv()<br><br>import os<br>import json<br>from openai import OpenAI<br>client = OpenAI()<br><br>def run_command(cmd: str):<br>    result = os.system(cmd)<br>    return result<br><br>history = []<br><br>def debugger_agent(query, context, max_steps = 5):<br>    SYSTEM_PROMPT = f&#39;&#39;&#39;<br>        You are a code debugging agent.<br><br>        You have access to:<br>        - run_command(cmd: str)<br><br>        You must respond in JSON<br><br>        FORMAT:<br><br>        {{<br>            &#39;thought&#39;: &#39;What are you thinking?&#39;,<br>            &#39;action&#39;: &#39;run_command or DONE&#39;,<br>            &#39;cmd&#39;: &#39;shell command if action is run_command&#39;,<br>            &#39;final_answer&#39;: &#39;only if DONE&#39;<br>        }}<br><br>        STRICT RULES:<br>        1. If the query involves ANY file operation (create, delete, modify, write):<br>        → You MUST call run_command<br>        → You are NOT allowed to assume the result<br><br>        2. NEVER say a file does not exist WITHOUT running a command<br><br>        3. ALWAYS attempt the command first, then observe result<br><br>        4. DO NOT return explanations for action queries<br><br>        5. Only use &quot;DONE&quot; after executing the required commands<br>        <br>    &#39;&#39;&#39;<br>    <br>    for step in range(max_steps):<br>        messages = [<br>                {&#39;role&#39;: &#39;system&#39;, &#39;content&#39;: SYSTEM_PROMPT},<br>                {&#39;role&#39;: &#39;user&#39;, &#39;content&#39;: f&#39;Query : {query}\n Context :\n {context}&#39;}<br>            ]<br>        for h in history:<br>            messages.append({&#39;role&#39;: &#39;assistant&#39;, &#39;content&#39;: h})<br>            <br>        response = client.chat.completions.create(<br>            model = &#39;gpt-4.1-mini&#39;,<br>            messages = messages<br>        )<br>        <br>        output = response.choices[0].message.content<br>        <br>        try:<br>            data = json.loads(output)<br>        except:<br>            return output <br><br>        action = data.get(&quot;action&quot;)<br>        <br>        if action == &quot;DONE&quot;:<br>            return data.get(&quot;final_answer&quot;, &quot;Done&quot;)<br><br>        if action == &quot;run_command&quot;:<br>            cmd = data.get(&quot;cmd&quot;)<br>            result = run_command(cmd)<br><br>            history.append(output)<br>            history.append(f&quot;Observation: {result}&quot;)<br><br>        else:<br>            return &quot;Invalid action&quot;<br><br>    return &quot;Max steps reached&quot;</pre><h3>Retrieval Wasn’t the Real Problem</h3><p>Initially, retrieval returned:</p><ul><li>correct functions</li><li>but not always the most useful ones</li></ul><p>The issue wasn’t finding candidates.</p><p>It was choosing between them.</p><h3>Introducing Reranking</h3><p>To improve relevance, I added a reranking step.</p><p>Instead of treating all functions equally, each is scored based on:</p><ul><li>direct retrieval</li><li>graph expansion</li><li>frequency across signals</li></ul><p>Then sorted before being passed to the LLM.</p><p>This changes the system from: <em>“include everything that might help” </em>to: <em>“prioritize what is most likely to help”</em></p><p>Retrieval defines the search space. Reranking defines what actually matters.</p><p>This had a noticeable impact on consistency.</p><pre>results_with_scores = vector_db.similarity_search_with_score(query = user_query, k = 5)<br>    results = [r for r, _ in results_with_scores]<br>    <br>    # Normalize semantic scores<br>    semantic_scores = {}<br><br>    for r, score in results_with_scores:<br>     func = r.metadata[&quot;function&quot;]<br>     semantic_scores[func] = 1 - score<br>        <br>    call_graph, reverse_graph = build_call_graph(repo_path)<br>    expanded_funcs = expand_with_graph(results_with_scores, call_graph, reverse_graph)<br><br>    func_map = {r.metadata[&quot;function&quot;]: r for r in results}<br>    <br>    # graph score (based on depth)<br>    graph_scores = {}<br>    for func, depth in expanded_funcs.items():<br>      graph_scores[func] = 1 / (depth + 1)<br><br>    # importance score<br>    importance_scores = {}<br>    for func in expanded_funcs:<br>     importance_scores[func] = len(reverse_graph.get(func, []))<br><br>    # normalize importance<br>    max_importance = max(importance_scores.values(), default=0)<br>    if max_importance &gt; 0:<br>     for func in importance_scores:<br>          importance_scores[func] /= max_importance<br>    else:<br>       for func in importance_scores:<br>            importance_scores[func] = 0<br><br>    # combine scores<br>    scores = {}<br><br>    all_funcs = set(list(semantic_scores.keys()) + list(expanded_funcs.keys()))<br><br>    for func in all_funcs:<br>      scores[func] = (<br>            semantic_scores.get(func, 0) * 0.6 +<br>            graph_scores.get(func, 0) * 0.3 +<br>            importance_scores.get(func, 0) * 0.1<br>        )<br><br><br>    ranked_funcs = sorted(scores, key=scores.get, reverse=True)</pre><h3>The State Problem</h3><p>Once the debugger started modifying files, a deeper issue appeared.</p><p>There are now two realities:</p><ol><li>Indexed code (used for retrieval)</li><li>Actual filesystem (modified at runtime)</li></ol><p>These can diverge.</p><p>Example:</p><ul><li>file deleted → still exists in index</li><li>file created → not in index</li></ul><p>This breaks assumptions. <em>Retrieval assumes a static world. Agents create a dynamic one</em></p><p>This is still unresolved.</p><h3>Evaluation: Measuring Behavior, Not Output</h3><p>With multiple components in play, it became hard to tell: <em>is the system actually working?</em></p><p>So an evaluation layer was added.</p><p>Two types:</p><h3>1. Explanation evaluation</h3><ul><li>relevance</li><li>groundedness</li><li>correctness</li></ul><p>(using an LLM as judge)</p><pre>def judge_explanation(query, answer, context):<br>    prompt = f&#39;&#39;&#39;<br>    You are evaluating a system that answers questions about a codebase.<br>    <br>    Query:<br>    {query}<br>    <br>    Answer:<br>    {answer}<br>    <br>    Context:<br>    {context}<br>    <br>    Evaluate:<br>    <br>    1. Relevance (0-5)<br>    2. Groundedness (0-5)<br>    3. Correctness (0-5)<br>    <br>    Return STRICT JSON:<br>    <br>    {{<br>        &quot;relevance&quot; : int,<br>        &quot;groundedness&quot; : int,<br>        &quot;correctness&quot; : int,<br>        &quot;reason&quot; : &quot;short explanation&quot;<br>    }}<br>    &#39;&#39;&#39;<br>    <br>    response = client.chat.completions.create(<br>        model = &#39;gpt-4.1-mini&#39;,<br>        messages = [<br>            {&#39;role&#39;: &#39;user&#39;, &#39;content&#39;: prompt}<br>        ]<br>    )<br>    <br>    return json.loads(response.choices[0].message.content)</pre><h3>2. Debugger evaluation</h3><ul><li>did the system actually execute an action?</li></ul><p>This required a shift.</p><p>Initially, evaluation checked output format.</p><p>That failed.</p><p>The debugger worked but the eval didn’t.</p><p>So evaluation was changed to detect: <em>behavior, not wording</em></p><p>This turned eval into a system-level signal, not a formatting check.</p><pre>def judge_debugger(output, expected_action):<br>    if expected_action == &quot;run_command&quot;:<br>        success_signals = [<br>            &quot;created&quot;,<br>            &quot;deleted&quot;,<br>            &quot;written&quot;,<br>            &quot;updated&quot;,<br>            &quot;file&quot;,<br>        ]<br><br>        out = output.lower()<br><br>        if any(word in out for word in success_signals):<br>            return {&quot;score&quot;: 1, &quot;reason&quot;: &quot;Action likely executed&quot;}<br>        else:<br>            return {&quot;score&quot;: 0, &quot;reason&quot;: &quot;No action detected&quot;}<br><br>    return {&quot;score&quot;: 0, &quot;reason&quot;: &quot;Unknown expected action&quot;}</pre><h3>What This Revealed</h3><p>Running evaluation surfaced a few things:</p><ul><li>Retrieval is imperfect, but usable</li><li>Reasoning is strong and consistent</li><li>Debugger is functional, but not fully reliable</li></ul><p>More importantly: <em>The system is no longer just generating answers. It is making decisions and acting on them</em></p><h3>Where It Stands</h3><p>CodeComp is now:</p><pre>Query → Route → Retrieve → Rerank → Reason / Act → Evaluate</pre><p>This is no longer a single pipeline. It’s a system with multiple interacting components.</p><h3>Open Problems</h3><p>Still unresolved:</p><ul><li>memory isolation (user vs codebase)</li><li>function identity collisions</li><li>traversal depth tuning</li><li>routing ambiguity</li><li>tool reliability</li></ul><h3>Final Thought</h3><p>The biggest change wasn’t adding features. It was changing the role of the system.</p><p>From: <em>answering questions t</em>o <em>deciding what to do and doing it</em></p><p>That transition introduces a different class of problems.</p><p>And that’s where things start to get interesting.</p><p>v1 : <a href="https://medium.com/@tarunyash01/v1-codecomp-building-a-system-to-reason-over-a-codebase-0267ca507b9d">https://medium.com/@tarunyash01/v1-codecomp-building-a-system-to-reason-over-a-codebase-0267ca507b9d</a></p><p>Repo: <a href="https://github.com/yashwork-byte/CompCode">https://github.com/yashwork-byte/CompCode</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9fffb5bda2be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[v1.CodeComp : Building a system to reason over a codebase]]></title>
            <link>https://medium.com/@tarunyash01/v1-codecomp-building-a-system-to-reason-over-a-codebase-0267ca507b9d?source=rss-e96ab604dc35------2</link>
            <guid isPermaLink="false">https://medium.com/p/0267ca507b9d</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Tarunyash]]></dc:creator>
            <pubDate>Fri, 03 Apr 2026 20:01:17 GMT</pubDate>
            <atom:updated>2026-04-03T20:01:17.726Z</atom:updated>
            <content:encoded><![CDATA[<p>Most tools for working with code fall into two buckets:</p><ul><li>search (find where something exists)</li><li>generation (write something new)</li></ul><p>What’s missing is a reliable way to understand an entire codebase without manually navigating it, especially when it’s not yours.</p><p>So I built something simple:</p><blockquote><em>Give it a repository → ask any question → get a grounded answer based on the actual code.</em></blockquote><p>No manual exploration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uuvHX3D85_zs46MhqOGmag.png" /></figure><h3>What CodeComp Does</h3><p>At its core, CodeComp takes a repository (currently local, but conceptually extendable to a repo link), and lets you interact with it like this:</p><ul><li>“How does this feature work end-to-end?”</li><li>“Which functions are involved in this flow?”</li><li>“Where could this be breaking?”</li><li>“What calls this function and why?”</li></ul><p>Instead of opening files and tracing logic manually, you can ask a question and get a structured explanation grounded in the codebase.</p><p>To do that, CodeComp combines:</p><ul><li>structural parsing (AST)</li><li>semantic retrieval (embeddings)</li><li>relational context (call graph)</li><li>controlled reasoning (LLM + prompts)</li></ul><p>So instead of returning <em>“here are some files”, </em>it tries to answer <em>“here’s how these parts connect and why they matter”.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XWiFnhaDpM5G2kzHUnPbnQ.png" /></figure><h3>Important Constraint (Current State)</h3><p>Right now, this works best when:</p><ul><li>you provide a local repository path</li><li>the codebase is Python</li></ul><p>So while the idea is <em>“give it a repo and ask anything”, </em>in practice (v1) <em>it’s a </em><strong><em>local-first system. </em></strong>Handling arbitrary GitHub repositories reliably is still an open problem (covered later).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HYgYWpDin4_Gjmr7756vbA.png" /></figure><h3>Why AST: Structure Before Semantics</h3><p>The first decision was how to parse code.</p><p>I used Python’s AST to extract functions.</p><p>This gives:</p><ul><li>reliable boundaries (no string-based parsing)</li><li>consistent structure across files</li><li>access to function calls for graph construction</li><li>also I was introduced to it in my compiler design classes in uni and found it really interesting ;)</li></ul><p>However, AST has a clear limitation “<em>It provides structure, not meaning”.</em></p><p>It can tell you what is a function or what calls what, but not:</p><ul><li>why a function exists</li><li>what it is intended to do</li></ul><p>That semantic layer is handled later by the LLM.</p><p>In practice, AST acts as a <strong>foundation layer “</strong><em>it organizes code well enough for semantic reasoning to happen on top of it”</em></p><pre>def is_valid_path(path: Path):<br>    return not any(part in IGNORE_DIRS for part in path.parts)<br><br>def extract_chunks(repo_path):<br>    chunks = []<br>    <br>    for file in Path(repo_path).rglob(&#39;*.py&#39;):<br>        <br>        if not is_valid_path(file):<br>            continue<br>        <br>        with open(file, &#39;r&#39;, encoding = &#39;utf-8&#39;) as f:<br>            code = f.read()<br>            <br>            try:<br>                tree = ast.parse(code)<br>            except:<br>                continue<br>            <br>            for node in ast.walk(tree):<br>                if isinstance(node, ast.FunctionDef):<br>                    chunk_code = ast.get_source_segment(code, node)<br>                    <br>                    chunk = {<br>                        &#39;file&#39;: str(file),<br>                        &#39;function&#39;: node.name,<br>                        &#39;code&#39;: chunk_code<br>                    }<br>                    <br>                    chunks.append(chunk)<br>                    <br>    return chunks</pre><h3>Challenge: Language Limitation &amp; Chunk Coverage</h3><p>The system is currently Python-specific.</p><p>Everything depends on:</p><ul><li>AST parsing</li><li>FunctionDef extraction</li></ul><p>This creates two limitations:</p><ol><li>Language lock-in; Other languages are ignored entirely.</li><li>Weak coverage in some repos; Not all codebases are function-heavy.</li></ol><p>Examples:</p><ul><li>script-style code</li><li>logic embedded inside classes</li><li>long procedural blocks</li></ul><p>In these cases:</p><ul><li>fewer chunks are generated</li><li>retrieval becomes shallow</li><li>answers degrade</li></ul><p>This exposed a key dependency: <em>The effectiveness of the system depends heavily on how the codebase is structured.</em></p><h3>Cleaning the Input: Filtering Irrelevant Code</h3><p>Initially, the system indexed everything — including:</p><ul><li>venv</li><li>__pycache__</li><li>.git</li><li>dependencies</li></ul><p>This introduced:</p><ul><li>irrelevant functions</li><li>noisy summaries</li><li>degraded retrieval quality</li></ul><p>The fix was straightforward — explicitly ignore non-relevant directories.</p><p>This significantly improved output quality. <em>In retrieval systems, filtering input is as important as processing it.</em></p><pre>IGNORE_DIRS = {&quot;venv&quot;, &quot;__pycache__&quot;, &quot;.git&quot;, &quot;node_modules&quot;, &quot;.idea&quot;}<br><br>def is_valid_path(path: Path):<br>    return not any(part in IGNORE_DIRS for part in path.parts)</pre><h3>Eliminating Built-in Function Noise</h3><p>Another issue appeared in the call graph.</p><p>Functions like:</p><ul><li>print</li><li>len</li></ul><p>were being included.</p><p>These appear frequently, add no meaningful context and distort graph connectivity.</p><p>The solution was to only include calls to functions that exist within the extracted chunks.</p><p>This ensured:</p><ul><li>every node in the graph is relevant</li><li>relationships are meaningful</li></ul><h3>Building the Call Graph</h3><p>To move beyond isolated chunks, I constructed a call graph:</p><ul><li>nodes → functions</li><li>edges → function calls</li></ul><p>This enables <strong>context expansion</strong>:</p><ul><li>retrieving not just relevant functions</li><li>but also related ones</li></ul><pre>import ast<br>from pathlib import Path<br><br>IGNORE_DIRS = {&quot;venv&quot;, &quot;__pycache__&quot;, &quot;.git&quot;, &quot;node_modules&quot;, &quot;.idea&quot;}<br><br>def is_valid_path(path: Path):<br>    return not any(part in IGNORE_DIRS for part in path.parts)<br><br>def get_functions(repo_path):<br>    functions = set()<br>    <br>    for file in Path(repo_path).rglob(&#39;*.py&#39;):<br>        <br>        if not is_valid_path(file):<br>            continue<br>        <br>        code = file.read_text(encoding = &#39;utf-8&#39;)<br>        <br>        try:<br>            tree = ast.parse(code)<br>        except:<br>            continue<br>        <br>        for node in ast.walk(tree):<br>            if isinstance(node, ast.FunctionDef):<br>                functions.add(node.name)<br>                <br>    return functions<br><br><br>def build_call_graph(repo_path):<br>    graph = {}<br>    reverse_graph = {}<br>    functions = get_functions(repo_path)<br>    <br>    for file in Path(repo_path).rglob(&#39;*.py&#39;):<br>        <br>        if not is_valid_path(file):<br>            continue<br>        <br>        with open(file, &#39;r&#39;, encoding = &#39;utf-8&#39;) as f:<br>            code = f.read()<br>            <br>        try:<br>            tree = ast.parse(code)<br>        except:<br>            continue<br>        <br>        for node in ast.walk(tree):<br>            if isinstance(node, ast.FunctionDef):<br>                func_name = node.name<br>                calls = []<br>                <br>                for child in ast.walk(node):<br>                    if isinstance(child, ast.Call):<br>                        name = None<br>                        <br>                        if isinstance(child.func, ast.Name):<br>                            name = child.func.id<br>                            <br>                        elif isinstance(child.func, ast.Attribute):<br>                            name = child.func.attr<br>                            <br>                        if name in functions:<br>                            calls.append(name)<br>                            reverse_graph.setdefault(name, []).append(func_name)<br>                            <br>                graph[func_name] = list(set(calls))<br>                <br>    return graph, reverse_graph</pre><h3>Challenge: Directionality of Traversal</h3><p>The initial implementation only explored <strong>downstream relationships</strong>: functions called by a function.</p><p>This answered what happens next but missed ‘where this function is used?’</p><p>Adding a <strong>reverse graph</strong> enabled upstream traversal: functions that call the current function.</p><p>This made the system more complete: <em>Downstream provides execution context. Upstream provides usage context.</em></p><p>Both are necessary for understanding.</p><h3>Challenge: Choosing Traversal Depth</h3><p>With bidirectional traversal, the next question was: <em>how far should expansion go?</em></p><p>I used a fixed depth of 2.</p><p>This captures:</p><ul><li>immediate relationships</li><li>one additional layer of context</li></ul><p>However, this is heuristic.</p><ul><li>lower depth → incomplete context</li><li>higher depth → increased noise</li></ul><p>There is no universal value. <em>Traversal depth depends on the structure of the codebase.</em></p><p>This remains an open parameter.</p><pre>def expand_with_graph(results, call_graph, reverse_graph, max_depth = 2):<br>    expanded = set()<br>    visited = set()<br>    <br>    def dfs(func, depth):<br>        if depth &gt; max_depth or func in visited:<br>            return<br>        <br>        visited.add(func)<br>        expanded.add(func)<br>        <br>        #downstream<br>        for callee in call_graph.get(func, []):<br>            dfs(callee, depth+1)<br>            <br>        #upstream<br>        for callee in reverse_graph.get(func, []):<br>            dfs(callee, depth+1)<br>            <br>    for r in results:<br>        func_name = r.metadata[&#39;function&#39;]<br>        dfs(func_name, 0)<br>        <br>    return list(expanded)</pre><h3>Challenge: Ranking Retrieved Functions</h3><p>Retrieval produces candidate functions, but ranking determines relevance.</p><p>Current approach:</p><ul><li>direct retrieval results → higher priority</li><li>graph-expanded results → lower priority</li></ul><p>Beyond this, ranking is heuristic.</p><p>This leads to inconsistent relevance and important functions occasionally being missed.</p><p>Using an LLM for ranking was considered, but avoided due to:</p><ul><li>increased latency</li><li>higher cost</li></ul><p><em>Retrieval identifies possibilities. Ranking determines usefulness.</em></p><p>This is still an unresolved area.</p><pre>def search_code(user_query, repo_path):<br>    embedding_model = OpenAIEmbeddings(<br>        model = &#39;text-embedding-3-small&#39;<br>    )<br>    <br>    vector_db = QdrantVectorStore.from_existing_collection(<br>        url = &#39;http://localhost:6333&#39;,<br>        collection_name = &#39;codebase&#39;,<br>        embedding = embedding_model<br>    )<br>    <br>    results = vector_db.similarity_search(query = user_query, k = 3)<br>    <br>    call_graph, reverse_graph = build_call_graph(repo_path)<br>    expanded_funcs = expand_with_graph(results, call_graph, reverse_graph)<br>    expanded_funcs = list(expanded_funcs)[:5]<br><br>    func_map = {r.metadata[&quot;function&quot;]: r for r in results}<br>    <br>    scores = {}<br><br>    for r in results:<br>     func = r.metadata[&quot;function&quot;]<br>     scores[func] = 3<br><br>    for func in expanded_funcs:<br>        if func not in scores:<br>            scores[func] = 2<br><br>    ranked_funcs = sorted(scores, key=scores.get, reverse=True)<br><br>    expanded_funcs = set(ranked_funcs[:6])<br>    <br>    expanded_results = []<br><br>    for func in expanded_funcs:<br>        if func in func_map:<br>            expanded_results.append(func_map[func])<br><br>    all_results = results + expanded_results<br><br>    seen = set()<br>    final_results = []<br><br>    for r in all_results:<br>     func = r.metadata[&quot;function&quot;]<br>     if func not in seen:<br>        seen.add(func)<br>        final_results.append(r)<br>                <br>    return final_results, expanded_funcs</pre><h3>Latency: Moving Work to Index Time</h3><p>Initially, summaries were generated at query time.</p><p>This meant:</p><ul><li>multiple LLM calls per query</li><li>repeated work across queries</li></ul><p>This resulted in:</p><ul><li>high latency</li><li>inconsistent response times</li></ul><p>The solution was to <strong>precompute summaries during indexing</strong>.</p><p>Effectively: <em>O(n × q) → O(q)</em></p><p>Each function is summarized once and reused.</p><p>This significantly improved responsiveness.</p><pre>from openai import OpenAI<br>client = OpenAI()<br><br>def generate_summary(chunk):<br>    prompt = f&#39;&#39;&#39;<br>    You are summarizing a function for comprehension purposes.<br>        <br>        Focus on <br>        - what the function does<br>        - key logic<br>        - important dependencies<br>    <br>    Function Name : {chunk[&#39;function&#39;]}<br>    Code : {chunk[&#39;code&#39;]}<br>    &#39;&#39;&#39;<br><br>    response = client.chat.completions.create(<br>        model = &#39;gpt-4.1-mini&#39;,<br>        messages = [<br>            {&#39;role&#39;: &#39;user&#39;, &#39;content&#39;: prompt}<br>        ]<br>    )<br>    <br>    return response.choices[0].message.content<br><br>def process_chunk(chunk):<br>    summary = generate_summary(chunk)<br><br>    text = f&quot;&quot;&quot;<br>    Function: {chunk[&#39;function&#39;]}<br>    Summary: {summary}<br>    &quot;&quot;&quot;<br><br>    metadata = {<br>        &quot;function&quot;: chunk[&quot;function&quot;],<br>        &quot;file&quot;: chunk[&quot;file&quot;],<br>        &quot;code&quot;: chunk[&quot;code&quot;],<br>        &quot;summary&quot;: summary<br>    }<br><br>    return text, metadata</pre><h3>Optimization: Parallelizing Summary Generation</h3><p>Even during indexing, summary generation was slow.</p><p>This step is I/O-bound (API calls), not CPU-bound.</p><p>Using a thread pool:</p><ul><li>multiple summaries are generated concurrently</li><li>waiting time is overlapped</li></ul><p>This improved indexing throughput without changing logic.</p><pre>def index_repo(repo_path):<br>    chunks = extract_chunks(repo_path)<br><br>    texts = []<br>    metadatas = []<br><br>    with ThreadPoolExecutor(max_workers=5) as executor:<br>        results = list(executor.map(process_chunk, chunks))<br><br>    for text, metadata in results:<br>        texts.append(text)<br>        metadatas.append(metadata)<br>    <br>    embedding_model = OpenAIEmbeddings(<br>        model = &#39;text-embedding-3-small&#39;<br>    )<br>    <br>    vector_store = QdrantVectorStore.from_texts(<br>        texts = texts,<br>        metadatas = metadatas,<br>        embedding = embedding_model,<br>        url = &#39;http://localhost:6333&#39;,<br>        collection_name = &#39;codebase&#39;<br>    )<br>    <br>    print(&#39;Indexing completed&#39;)</pre><h3>Prompt Design as a Control Mechanism</h3><p>Retrieval alone does not guarantee useful answers.</p><p>Without constraints, the model tends to:</p><ul><li>generalize</li><li>ignore relationships</li><li>introduce irrelevant explanations</li></ul><p>To address this, the system prompt enforces:</p><ul><li>step-by-step reasoning</li><li>explicit function references</li><li>grounding in retrieved context</li></ul><p>Prompting acts as a <strong>control layer</strong>, ensuring consistency.</p><pre>def generate_answer(query, compressed_context, expanded_funcs, memory_context):<br>    SYSTEM_PROMPT = f&#39;&#39;&#39;<br>     You are an expert software engineer.<br>    <br>     You are given:<br>     1. Compressed summaries of relevant functions<br>     2. Function call relationships<br>    <br>      Answer the question using the codebase context.<br><br>     Previous conversation:<br>     {memory_context}<br><br>     Question:<br>     {query}<br><br>     Relevant functions and roles:<br>     {compressed_context}<br><br>     Related functions (call graph):<br>     {expanded_funcs}<br>    <br>     Instructions:<br>     - Explain how things work step-by-step<br>     - Connect functions logically<br>     - Identify possible issue<br>     - Do NOT infer personal information from code<br>     - Memory context is only for conversational continuity, not identity inference <br>     - Be precise<br>     - Avoid generic explanations<br>     - Focus on THIS codebase only<br>     - Use function names explicitly<br>    &#39;&#39;&#39;<br>    <br>    response = client.chat.completions.create(<br>        model = &#39;gpt-4.1-mini&#39;,<br>        messages = [<br>            {&#39;role&#39;: &#39;system&#39;, &#39;content&#39;: SYSTEM_PROMPT},<br>            {&#39;role&#39;: &#39;user&#39;, &#39;content&#39;: query}<br>        ]<br>    )<br>    <br>    return response.choices[0].message.content</pre><h3>Adding Memory: Benefits and Issues</h3><p>A memory layer was introduced to:</p><ul><li>preserve conversational context</li><li>support follow-up questions</li></ul><p>This improves usability:</p><ul><li>queries are no longer isolated</li><li>interactions feel continuous</li></ul><p>However, it introduced a problem.</p><pre>def init_memory():<br>    OPEN_API_KEY = os.getenv(&#39;OPEN_API_KEY&#39;)<br>    config = {<br>    &#39;version&#39;: &#39;v1.1&#39;,<br>    &#39;embedder&#39;:{<br>        &#39;provider&#39;: &#39;openai&#39;,<br>        &#39;config&#39;: {&#39;api_key&#39;: OPEN_API_KEY, &#39;model&#39;: &#39;text-embedding-3-small&#39;}<br>        },<br>    &#39;vector_store&#39;:{<br>        &#39;provider&#39;: &#39;qdrant&#39;,<br>        &#39;config&#39;: {<br>            &#39;host&#39;: &#39;localhost&#39;,<br>            &#39;port&#39;: &#39;6333&#39;<br>            }<br>        }<br>    }<br>    return Memory.from_config(config)<br><br>def get_mem_context(mem_client, user_query):<br>    results = mem_client.search(query = user_query, user_id = &#39;user_A&#39;)<br>    memories = [mem.get(&#39;memory&#39;) for mem in results.get(&#39;results&#39;, [])]<br>    return &#39;\n&#39;.join(memories[:5])<br><br>def save_memory(mem_client, user_query, response):<br>    mem_client.add(<br>        user_id = &#39;user_A&#39;,<br>        messages = [<br>            {&#39;role&#39;:&#39;user&#39;,&#39;content&#39;: user_query},<br>            {&#39;role&#39;:&#39;assistant&#39;,&#39;content&#39;: response},<br>        ]<br>    )</pre><h3>Challenge: Memory vs Codebase Context</h3><p>The system combines:</p><ul><li>user memory</li><li>codebase context</li></ul><p>In some cases, this leads to incorrect responses.</p><p>Example:</p><ul><li>asking “What’s my name?”</li><li>returns a name from the codebase</li></ul><p>This happens because:</p><ul><li>both contexts are treated equally</li><li>the model has no explicit prioritization</li></ul><p><em>Not all context should be treated equally.</em></p><p>Separating:</p><ul><li>user identity</li><li>code understanding</li></ul><p>is still unresolved.</p><h3>Bug: Function Name Collisions</h3><p>Functions are currently identified by name.</p><p>This fails when multiple classes define the same method name.</p><p>Example:</p><ul><li>UserService.get()</li><li>OrderService.get()</li></ul><p>This causes:</p><ul><li>incorrect graph edges</li><li>ambiguous retrieval results</li></ul><p>A more robust identity system is needed (e.g., class + file + function).</p><h3>Limitations with External / GitHub Repositories</h3><p>The system works best on local repositories and controlled environments.</p><p>It is not yet reliable for arbitrary GitHub repositories.</p><p>Challenges include:</p><ul><li>mixed languages</li><li>inconsistent structures</li><li>large scale</li><li>parsing failures</li></ul><p>For now: <em>CodeComp is a local-first system.</em></p><p>Extending it to external repositories requires a more robust ingestion layer.</p><h3>Future Direction</h3><h3>1. Transition Towards Debugging</h3><p>Move from <strong>explaining code </strong>to <strong>interacting with code.</strong></p><p>This would involve:</p><ul><li>tool calling (read, search, write)</li><li>tracing execution paths</li><li>assisting with debugging workflows</li></ul><h3>2. Improving Scalability</h3><p>Current pipeline is tightly coupled.</p><p>Potential direction:</p><ul><li>asynchronous job processing (e.g., background workers like RQ)</li><li>better handling of large repositories</li></ul><h3>3. Open Problems</h3><p>Several areas remain unresolved:</p><ul><li>ranking strategy</li><li>traversal depth selection</li><li>multi-language support</li><li>memory isolation</li><li>function identity</li></ul><h3>Open to Feedback</h3><p>If you’ve worked on code search, developer tooling or LLM-based systems, I would value your perspective on:</p><ul><li>retrieval strategies</li><li>graph-based approaches</li><li>system design decisions</li></ul><p>This is v1. There is still a lot to improve.</p><p>Link to my repo : <a href="https://github.com/yashwork-byte/CompCode">https://github.com/yashwork-byte/CompCode</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0267ca507b9d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>