# Building LLM-Powered Coding Assistant for GitHub: RAG with Gemini and Redis

> How I build a GitHub repository assistant capable of answering user issues

![A nerd who loves to explore and assist people. (Generated using Canva)](../../Images/github-rag-gemini-redis/01-cover.png)

## Introduction

Since you are reading this article, you are likely into data science, machine learning, or AI; Ultimately, you are up to programming. Programmers more often experience bugs, issues, and errors. That's where things are getting serious, especially when working on a relatively new framework or library. At that moment, I always consider the benefits of having an intelligent assistant who possesses knowledge of various subjects and can effectively provide instruction. Once tasked, my assistant could go through the entire code repository, scan each line of code, and remember all logic for quick fixes.

![Image by Author via Canva](../../Images/github-rag-gemini-redis/02-assistant-concept.jpg)

That sounds quite fancy, right? Creating such a system used to seem like something out of science fiction, but it's achievable these days, requiring only a few well-focused evenings.

Let's gear up and do some coding to achieve our task. As I described above, our assistant has the following functionalities:

- Read the entire code base and store it.
- Understand each member's use within the code base (Map class/function dependencies).
- Pull up all the **required** codes when the user asks a question and provide concise instructions to solve the issue.

## Read the entire code base and store it.

We must provide a related code base to give our agent context. But the way it stores is a matter. Storing additional metadata such as docstring and function/class level dependencies will add value to the data. Because the more data we have, the more intelligent our agents become. One aspect I am concerned about here is not picking only the most relevant code pieces. But also dependent code pieces. For example, the user may have an issue with a *Tokenizer* class. Still, we aren't fully confident the required fix can be given only by inspecting *Tokenizer* because each class/function uses the others interchangeably. That's why we need to understand those dependencies when building such systems.

Let's break down the steps we might need to achieve this.

- Clone the GitHub repository.
- Read each `.py` file it has and store details in memory.
- Derive function/class usage and map dependencies between them.

This sounds straightforward, but when we recall our end goal, we can see that a few pieces are missing.

Yet, we have not thought about a way to pull up necessary code pieces for user questions. The solution is combining information retrieval with vector search. But there is a catch. In most cases, we can use appropriate text columns for vector search functionality. Here, the situation is different as we are dealing with codebase. Therefore, I decided to try a few options and pick the one with decent performance. The selected workaround for this issue is,

- First, generate a description for each code piece using LLM.
- Then, create a new field combining code definition and LLM-generated code description. (You may obtain a Gemini API key for this)
- Calculate vector embeddings for newly created columns and store them in the database.

At the end of these steps, our data structure will be something like this:

```json
{
  "name": "warpBox",                        // Object name
  "type": "function",                       // Object type
  "description": "test description",        // LLM-generated description
  "uses": "save, detector",                 // Other functions/classes used by this function
  "file": "warp.py",                        // Containing file name
  "code": "def warpBox:\n  width = ...",    // Function definition
  "docstring": "",                          // Extracted docstring from function
  "embedding": [0.87, -0.15, 0.55, 0.03]    // Calculated embedding vector
}
```

At this point, we have to finalize the vector database we have to use. We can use vector databases like Faiss, Milvus, or any other. But this time, I decided to go ahead with the database I never used. I intended to explore something new and add that to my day-to-day toolbox. So, I ended up choosing [Redis](https://redis.io/kb/doc/28x16buszr/can-i-use-redis-as-a-vector-database#:~:text=Answer,Redis%20as%20a%20Vector%20Database.). If you continue with Redis, follow [these instructions](https://redis.io/docs/latest/operate/oss_and_stack/install/install-redis/) to set up a Redis instance on your local machine. If you prefer a simple solution, sign up for a Redis free account and create a database by following the instructions listed on their [website](https://redis.io/docs/latest/operate/oss_and_stack/install/). Nevertheless, all you want for this step is a Redis host, port, and password.

We're all set to take our first step. To help us understand, let's visualize what we've described so far.

![Data Ingestion Pipeline](../../Images/github-rag-gemini-redis/03-data-ingestion-pipeline.png)

Let's see how we can build this. As a first step, we need to convert the given GitHub repository into a knowledge graph. When searching for a suitable library for this purpose, I found a few overcomplicated (For my use case) solutions. Therefore, I planned to build a more straightforward library for this use case. You can install it using `pip install sourcegraph`. You can check the repository using the link below.

[!ref target="blank" text="GitHub - Ransaka/sourcegraph"](https://github.com/Ransaka/sourcegraph)

This Python library allows you to convert a given Python GitHub repository into a NetworkX graph. Its use is simple and requires only a few steps.

Let's jump into the coding part.

```python
import os
import time
from copy import deepcopy
from typing import List
from sourcegraph import Sourcegraph

import numpy as np
import redis
import google.generativeai as genai
from dotenv import load_dotenv
from tqdm import tqdm

from redis.commands.search.field import (
    TagField,
    TextField,
    VectorField,
)
from redis.commands.search.indexDefinition import IndexDefinition, IndexType
from redis.commands.search.query import Query

load_dotenv()

client = redis.Redis(
    host=os.environ['REDIS_HOST'],
    port=12305,
    password=os.environ['REDIS_PASSWORD']
)

genai.configure(api_key=os.environ["GEMINI_API_KEY"])

generation_config = {
    "temperature": 1,
    "top_p": 0.95,
    "top_k": 64,
    "max_output_tokens": 8192,
    "response_mime_type": "text/plain",
}

model = genai.GenerativeModel(
    model_name="gemini-1.5-flash",
    generation_config=generation_config,
    system_instruction="You are optimized to generate accurate descriptions for given Python codes. When the user inputs the code, you must return the description according to its goal and functionality.  You are not allowed to generate additional details. The user expects at least 5 sentence-long descriptions.",
)

def fetch_data(url):
    def get_description(code):
        chat_session = model.start_chat(
            history=[
                {
                    "role": "user",
                    "parts": [
                        f"Code: {code}",
                    ],
                },
            ]
        )
        response = chat_session.send_message("INSERT_INPUT_HERE")

        return response.text

    gihub_repository = Sourcegraph(url)
    gihub_repository.run()
    data = dict(gihub_repository.node_data)
    for key, value in tqdm(data.items()):
        data[key]['description'] = get_description(value['definition'])
        data[key]['uses'] = ", ".join(list(gihub_repository.get_dependencies(key)))
    return data

data = fetch_data("https://github.com/Ransaka/sinlib.git")
```

After executing the above step, we have obtained a dataset with the below schema.

```python
{
 'type': 'class',
 'name': 'Romanizer',
 'definition': "class Romanizer:\n\n    def __init__( ...",
 'file_name': 'romanize.py',
 'docstring': '',
 'description': 'The provided Python code defines a class named `Romanizer` ...',
 'uses': 'Tokenizer, load_char_mapper, load_default_vocab_map, process_text, remove_non_printable'
}
```

In the above code snippet, we did a bunch of things.

- We fetch the GitHub repository data.
- Generate descriptions for each code piece.
- Mapped each function's dependencies and stored them as JSON objects.

Okay, our next goal is to build a pipeline to,

- Store these data in the database
- Retrieve data relevant to user queries.

Let's dive into that. First, we must implement a step to store data in the database. After that, we can add an embedding field to the records. Finally, we need to add indexes to search for elements from the database. One of the searchable fields should be the embedding field we have planned above. As with other vector searches, we must specify the indexing algorithm here. Since we are dealing with a relatively small dataset, I am picking the indexing method as *FLAT* here in vector search.

Let's replicate the same with codes quickly.

```python
import os
from typing import List
import numpy as np
import redis
import google.generativeai as genai
from dotenv import load_dotenv
from tqdm import tqdm

from redis.commands.search.field import (
    TagField,
    TextField,
    VectorField,
)
from redis.commands.search.indexDefinition import IndexDefinition, IndexType
from redis.commands.search.query import Query

INDEX_NAME = "idx:codes_vss"

def get_embeddings(content: List):
    return genai.embed_content(model='models/text-embedding-004', content=content)['embedding']

def ingest_data(data):
    pipeline = client.pipeline()
    for i, code_metadata in enumerate(data.values(), start=1):
        redis_key = f"code:{i:03}"
        pipeline.json().set(redis_key, "$", code_metadata)
    _ = pipeline.execute()
    keys = sorted(client.keys("code:*"))
    defs = client.json().mget(keys, "$.definition")
    descs = client.json().mget(keys, "$.description")
    embed_inputs = []

    for i in range(1, len(keys)+1):
        embed_inputs.append(
            f"""{defs[i-1][0]}\n\n{descs[i-1][0]}"""
        )
    embeddings = get_embeddings(embed_inputs)
    VECTOR_DIMENSION = len(embeddings[0])
    pipeline = client.pipeline()
    for key, embedding in zip(keys, embeddings):
        pipeline.json().set(key, "$.embeddings", embedding)
    pipeline.execute()

    schema = (
        TextField("$.name", no_stem=True, as_name="name"),
        TagField("$.type", as_name="type"),
        TextField("$.definition", no_stem=True, as_name="definition"),
        TextField("$.file_name", no_stem=True, as_name="file_name"),
        TextField("$.description", no_stem=True, as_name="description"),
        TextField("$.uses", no_stem=True, as_name="uses"),
        VectorField(
            "$.embeddings",
            "FLAT",
            {
                "TYPE": "FLOAT32",
                "DIM": VECTOR_DIMENSION,
                "DISTANCE_METRIC": "COSINE",
            },
            as_name="vector",
        ),
    )
    definition = IndexDefinition(prefix=["code:"], index_type=IndexType.JSON)
    _ = client.ft(INDEX_NAME).create_index(fields=schema, definition=definition)

    info = client.ft(INDEX_NAME).info()
    num_docs = info["num_docs"]
    indexing_failures = info["hash_indexing_failures"]
    print(f"{num_docs} documents indexed with {indexing_failures} failures")
```

Let's check out the sample data beforehand. It will ensure that everything is as expected and that we are good to go with the rest of the processes.

```python
client.json().get("code:010")
# {'type': 'function',
#  'name': 'load_default_vocab_map',
#  'definition': "def load_default_vocab_map():\n    ...",
#  'file_name': 'preprocessing.py',
#  'docstring': '',
#  'description': 'The `load_default_vocab_map()` function is responsible for ...',
#  'uses': '',
#  'embeddings': [0.0044830255,
#   -0.007266335,
#   -0.012937576,
#  ...
#   -0.003363073]}
```

Everything is going as planned; we're in a safe area. Let's proceed.

Our next objective should be to build a mechanism to retrieve relevant documents based on the given issues. In other words, we have to implement vector search capability there. Let's add that piece of code as well.

```python
def get_related_functions(query: str) -> str:
    """
    Perform a vector similarity search and retrieve related functions.

    Args:
        query (str): The input query to encode.

    Returns:
        str: A formatted string containing details of related functions.
    """
    vector_search_query = (
        Query('(*)=>[KNN 2 @vector $query_vector AS vector_score]')
        .sort_by('vector_score')
        .return_fields('vector_score', 'id', 'name', 'definition', 'file_name', 'type', 'uses')
        .dialect(2)
    )

    encoded_query = get_embeddings(query)
    vector_params = {
        "query_vector": np.array(encoded_query, dtype=np.float32).tobytes()
    }

    # Perform initial vector search
    result_docs = client.ft(INDEX_NAME).search(vector_search_query, vector_params).docs

    return result_docs
```

In the code above, we first calculate text embeddings for a given user query. Then, we perform a KNN search over the elements in the database. In KNN, you could also define a search range. You can accomplish that using the code below.

```python
def get_embeddings(content: List):
    return genai.embed_content(model='models/text-embedding-004', content=content)['embedding']

query = ["Training a new tokenizer takes a lot of time to complete. Also, memory consumption seems pretty high."]
encoded_queries = get_embeddings(query)

vector_search_query_with_range = (
    Query("@vector:[VECTOR_RANGE $range $query_vector]=>{$YIELD_DISTANCE_AS: score}")
    .sort_by('score')
    .return_fields('score', 'id', 'name', 'definition', 'file_name', 'type', 'uses')
    .dialect(2)
)

client.ft(INDEX_NAME).search(
    vector_search_query_with_range,
    {
        'query_vector': np.array(encoded_queries[0], dtype=np.float32).tobytes(),
        'range': 1.0
    }
).docs

# [Document {'id': 'code:002', 'payload': None, 'score': '0.402300059795', 'name': 'Tokenizer', 'definition': 'class Tokenizer:\n\n    ...', 'file_name': 'tokenizer.py', 'type': 'class', 'uses': 'process_text, load_default_vocab_map'},
#  Document {'id': 'code:004', 'payload': None, 'score': '0.467481791973', 'name': 'load_tokenizer', 'definition': 'def load_tokenizer():\n    ...', 'file_name': 'dataset_utils.py', 'type': 'function', 'uses': 'Tokenizer, process_text, load_default_vocab_map'},
#  Document {'id': 'code:006', 'payload': None, 'score': '0.49214309454', 'name': 'load_transliterator_model', 'definition': 'def load_transliterator_model():\n    ...', 'file_name': 'model_utils.py', 'type': 'function', 'uses': 'Tokenizer, detect_device, load_default_vocab_map, process_text, BiLSTMTranslator, load_tokenizer'},
#  Document {'id': 'code:007', 'payload': None, 'score': '0.499140918255', 'name': 'inference', 'definition': 'def inference(model, tokenizer, input_text):\n    ...', 'file_name': 'model_utils.py', 'type': 'function', 'uses': 'detect_device'},
# ]
```

Note the score attribute in each document we retrieved. It represents the distance to the provided query. The lower the distance, the more relevant the documents are. With that step, we completed the first component of our coding assistant.

## Building Retrieval Pipeline and Integrate with LLM

In this step, we must combine a previously built data store with a large language model. The ideal workflow can then be split into two steps.

- The user asks questions; the retrieval pipeline retrieves related code snippets and draft prompts to feed LLM.
- Based on prompts, LLM generates responses. The application front end sends these responses back to the user.

For better clarity, let's visualize the steps we discussed earlier.

![The user asks a question, and then the retrieval pipeline fetches the required data and sends it to the application. The application compiles the codes, drafts a prompt, and sends it back to LLM. Afterward, the LLM response is delivered to the user.](../../Images/github-rag-gemini-redis/04-retrieval-flow.png)

That's quite a lot of work. First, we must find a suitable LLM orchestration framework, so I am picking Haystack [this time](https://medium.com/towards-data-science/using-llama-3-for-building-ai-agents-7e74f79d1ccc), too.

I am expanding our previous vector search function to meet the requirements described above first point.

```python
def draft_prompt(query: str) -> str:
    """
    Perform a vector similarity search and retrieve related functions.

    Args:
        query (str): The input query to encode.

    Returns:
        str: A formatted string containing details of related functions.
    """
    INDEX_NAME = "idx:codes_vss"

    vector_search_query = (
        Query('(*)=>[KNN 2 @vector $query_vector AS vector_score]')
        .sort_by('vector_score')
        .return_fields('vector_score', 'id', 'name', 'definition', 'file_name', 'type', 'uses')
        .dialect(2)
    )

    encoded_query = get_embeddings(query)
    vector_params = {
        "query_vector": np.array(encoded_query, dtype=np.float32).tobytes()
    }

    result_docs = client.ft(INDEX_NAME).search(vector_search_query, vector_params).docs

    related_items: List[str] = []
    dependencies: List[str] = []
    for doc in result_docs:
        related_items.append(doc.name)
        dependencies.extend(use for use in doc.uses.split(", ") if use)
    dependencies = list(set(dependencies) - set(related_items))

    def get_query(item_list):
        return Query(f"@name:({' | '.join(item_list)})").return_fields(
            'id', 'name', 'definition', 'file_name', 'type'
        )

    related_docs = client.ft(INDEX_NAME).search(get_query(related_items)).docs
    dependency_docs = client.ft(INDEX_NAME).search(get_query(dependencies)).docs

    def format_doc(doc):
        return (
            f"{'*' * 28} CODE SNIPPET {doc.id} {'*' * 28}\n"
            f"* Name: {doc.name}\n"
            f"* File: {doc.file_name}\n"
            f"* {doc.type.capitalize()} definition:\n"
            f"```python\n{doc.definition}\n```\n"
        )

    formatted_results_main = [format_doc(doc) for doc in related_docs]
    formatted_results_support = [format_doc(doc) for doc in dependency_docs]

    return (
        f"User Question: {query}\n\n"
        f"{'USE BELOW CODES TO ANSWER USER QUESTIONS.'}\n"
        f"{'\n\n'.join(formatted_results_main)}"
        f"{'SOME SUPPORTING FUNCTIONS AND CLASS YOU MAY WANT.'}\n"
        f"{'\n\n'.join(formatted_results_support)}"
    )
```

Okay, let's try out what we have just built.

```python
query = "Training new tokenizer takes a lot time to complete. Also memory consumption seems pretty high"
prompt = draft_prompt(query)
print(prompt)
# User Question: Training new tokenizer takes a lot time to complete. Also memory consumption seems pretty high

# USE BELOW CODES TO ANSWER USER QUESTIONS.
# **************************** CODE SNIPPET code:004 ****************************
# * Name: load_tokenizer
# * File: dataset_utils.py
# * Function definition:
# ```python
# def load_tokenizer():
#     tokenizer = Tokenizer(max_length=MAX_LENGTH)
#     tokenizer.load_from_pretrained(DUMMY_FILE_NAME)
#     return tokenizer
# ```

# **************************** CODE SNIPPET code:002 ****************************
# * Name: Tokenizer
# * File: tokenizer.py
# * Class definition:
# ```python
# class Tokenizer:
```

The next step is to provide this prompt to LLM and get a response from LLM. Let's use the Haystack framework to streamline this process. One of the tricky points here is to convert the above `draft_prompt` function into the Haystack component. Let's see how we can implement that.

## Building a retriever component and prompt template

```python
from haystack import Pipeline
from haystack import component
from haystack.utils import Secret
from haystack.components.builders import PromptBuilder
from haystack_integrations.components.generators.google_ai import GoogleAIGeminiGenerator

# convert draft_prompt function as Haystack pipeline component
@component
class RedisRetreiver:
    @component.output_types(context=str)
    def run(self, query: str):
        return {"context": draft_prompt(query)}

# Large language model
gemini = GoogleAIGeminiGenerator(api_key=Secret.from_env_var("GEMINI_API_KEY"), model='gemini-1.5-pro')

# Prompt template with instructions
template = """
You are a helpful agent optimized to resolve GitHub issues for your organization's libraries. Users will ask questions when they encounter problems with the code repository.
You have access to all the necessary code for addressing these issues. 
First, you should understand the user's question and identify the relevant code blocks. 
Then, craft a precise and targeted response that allows the user to find an exact solution to their problem. 
You must provide code snippets rather than just opinions.
You should always assume user has installed this python package in their system and raised question raised while they are using the library.

In addition to the above tasks, you are free to:
 * Greet the user.
 * [ONLY IF THE QUESTION IS INSUFFICIENT] Request additional clarity.
 * Politely decline irrelevant queries.
 * Inform the user if their query cannot be processed or accomplished.

By any chance you should NOT,
 * Ask or recommend user to use different library. Or code snipits related to other similar libraies.
 * Provide inaccurate explnations.
 * Provide sugestions without code examples.

{{context}}
"""

prompt_builder = PromptBuilder(template=template)
```

Perfect, now we have all the necessary components to finish our code assistant. Let's define the steps and connections we require to connect these processes.

```python
pipeline = Pipeline()
pipeline.add_component(name="retriever", instance=RedisRetreiver())
pipeline.add_component("prompt_builder", prompt_builder)
pipeline.add_component("llm", gemini)
pipeline.connect("retriever.context", "prompt_builder")
pipeline.connect("prompt_builder", "llm")

# Additionally we can plot the pipeline as well
pipeline.draw(path='pipeline.png')
```

Here's the pipeline formation to ensure everything aligns with our intent.

![Haystack Pipeline](../../Images/github-rag-gemini-redis/05-haystack-pipeline.png)

Now, we have a fully functional pipeline to handle user issues related to the target codebase. Let's try asking a simple question.

![Response to Sample User Question](../../Images/github-rag-gemini-redis/06-sample-response.png)

It worked as expected. Let's wrap this up as a streamlit application as a final step.

```python
import redis
import os
from dotenv import load_dotenv
import google.generativeai as genai
from typing import List
import numpy as np
from redis.commands.search.query import Query
from haystack import Pipeline, component
from haystack.utils import Secret
from haystack_integrations.components.generators.google_ai import GoogleAIGeminiChatGenerator, GoogleAIGeminiGenerator
from haystack.components.builders import PromptBuilder
import streamlit as st
from haystack.components.generators import OpenAIGenerator

load_dotenv()

# Initialize Streamlit app
st.title("Code Assistant Chat")

# Initialize session state for chat history
if "messages" not in st.session_state:
    st.session_state.messages = []

# Display chat messages
for message in st.session_state.messages:
    with st.chat_message(message["role"]):
        st.markdown(message["content"])

genai.configure(api_key=os.environ["GEMINI_API_KEY"])

client = redis.Redis(
    host=os.environ['REDIS_HOST'],
    port=12305,
    password=os.environ['REDIS_PASSWORD']
)

generation_config = {
    "temperature": 1,
    "top_p": 0.95,
    "top_k": 64,
    "max_output_tokens": 8192,
    "response_mime_type": "text/plain",
}

model = genai.GenerativeModel(
    model_name="gemini-1.5-flash",
    generation_config=generation_config,
    system_instruction="You are optimized to generate accurate descriptions for given Python codes. When the user inputs the code, you must return the description according to its goal and functionality.  You are not allowed to generate additional details. The user expects at least 5 sentence-long descriptions.",
)

gemini = GoogleAIGeminiGenerator(api_key=Secret.from_env_var("GEMINI_API_KEY"), model='gemini-1.5-flash')

def get_embeddings(content: List):
    return genai.embed_content(model='models/text-embedding-004', content=content)['embedding']


def draft_prompt(query: str) -> str:
    """
    Perform a vector similarity search and retrieve related functions.

    Args:
        query (str): The input query to encode.

    Returns:
        str: A formatted string containing details of related functions.
    """
    INDEX_NAME = "idx:codes_vss"

    vector_search_query = (
        Query('(*)=>[KNN 2 @vector $query_vector AS vector_score]')
        .sort_by('vector_score')
        .return_fields('vector_score', 'id', 'name', 'definition', 'file_name', 'type', 'uses')
        .dialect(2)
    )

    encoded_query = get_embeddings(query)
    vector_params = {
        "query_vector": np.array(encoded_query, dtype=np.float32).tobytes()
    }

    result_docs = client.ft(INDEX_NAME).search(vector_search_query, vector_params).docs

    related_items: List[str] = []
    dependencies: List[str] = []
    for doc in result_docs:
        related_items.append(doc.name)
        if doc.uses:
            dependencies.extend(use for use in doc.uses.split(", ") if use)

    dependencies = list(set(dependencies) - set(related_items))

    def get_query(item_list):
        return Query(f"@name:({' | '.join(item_list)})").return_fields(
            'id', 'name', 'definition', 'file_name', 'type'
        )

    related_docs = client.ft(INDEX_NAME).search(get_query(related_items)).docs
    dependency_docs = client.ft(INDEX_NAME).search(get_query(dependencies)).docs

    def format_doc(doc):
        return (
            f"{'*' * 28} CODE SNIPPET {doc.id} {'*' * 28}\n"
            f"* Name: {doc.name}\n"
            f"* File: {doc.file_name}\n"
            f"* {doc.type.capitalize()} definition:\n"
            f"```python\n{doc.definition}\n```\n"
        )

    formatted_results_main = [format_doc(doc) for doc in related_docs]
    formatted_results_support = [format_doc(doc) for doc in dependency_docs]

    return (
        f"User Question: {query}\n\n"
        f"USE BELOW CODES TO ANSWER USER QUESTIONS.\n"
        f"{chr(10).join(formatted_results_main)}\n\n"
        f"SOME SUPPORTING FUNCTIONS AND CLASS YOU MAY WANT.\n"
        f"{chr(10).join(formatted_results_support)}"
    )

@component
class RedisRetreiver:
    @component.output_types(context=str)
    def run(self, query: str):
        return {"context": draft_prompt(query)}

# llm = GoogleAIGeminiGenerator(api_key=Secret.from_env_var("GEMINI_API_KEY"), model='gemini-1.5-pro')
llm = OpenAIGenerator()

template = """
You are a helpful agent optimized to resolve GitHub issues for your organization's libraries. Users will ask questions when they encounter problems with the code repository.
You have access to all the necessary code for addressing these issues. 
First, you should understand the user's question and identify the relevant code blocks. 
Then, craft a precise and targeted response that allows the user to find an exact solution to their problem. 
You must provide code snippets rather than just opinions.
You should always assume user has installed this python package in their system and raised question raised while they are using the library.

In addition to the above tasks, you are free to:
 * Greet the user.
 * [ONLY IF THE QUESTION IS INSUFFICIENT] Request additional clarity.
 * Politely decline irrelevant queries.
 * Inform the user if their query cannot be processed or accomplished.

By any chance you should NOT,
 * Ask or recommend user to use different library. Or code snipits related to other similar libraies.
 * Provide inaccurate explnations.
 * Provide sugestions without code examples.

{{context}}
"""

prompt_builder = PromptBuilder(template=template)

pipeline = Pipeline()
pipeline.add_component(name="retriever", instance=RedisRetreiver())
pipeline.add_component("prompt_builder", prompt_builder)
pipeline.add_component("llm", llm)
pipeline.connect("retriever.context", "prompt_builder")
pipeline.connect("prompt_builder", "llm")


if prompt := st.chat_input("What's your question?"):
    st.session_state.messages.append({"role": "user", "content": prompt})
    with st.chat_message("user"):
        st.markdown(prompt)

    with st.chat_message("assistant"):
        response_placeholder = st.empty()
        response_placeholder.markdown("Thinking...")

        try:
            response = pipeline.run({"retriever": {"query": prompt}})
            llm_response = response["llm"]["replies"][0]

            response_placeholder.markdown(llm_response)
            st.session_state.messages.append({"role": "assistant", "content": llm_response})
        except Exception as e:
            response_placeholder.markdown(f"An error occurred: {str(e)}")

if st.button("Clear Chat History"):
    st.session_state.messages = []
    st.experimental_rerun()

with st.expander("See Chat History"):
    st.markdown(st.session_state.messages)
```

![Our Assistant UI](../../Images/github-rag-gemini-redis/07-streamlit-ui.png)

I have hosted this code repository in a HuggingFace space so that you can also try the application there.

[!ref target="blank" text="Hugging Face Space - Code Assistant"](https://huggingface.co/spaces/Ransaka/Code-Assistant)

## Conclusion

In this tutorial, I aimed to guide the readers through building a code assistant application powered by a large language model. During the testing phase, I noticed some issues. For the reader's concern, I am adding those known limitations here.

- Chat memory can be appropriately handled in the pipeline steps. In the current implementation, if you ask a follow-up question, this agent won't be able to recognize the context properly. Therefore, you can try a few possible ways to overcome this challenge. You could try adding memory into the pipeline using custom [routing](https://docs.haystack.deepset.ai/reference/routers-api) in the application or a combination of both.
- Even for simple greetings, the current implementation will run whole pipeline steps (including the retriever step) to generate an answer (a simple greeting message). I see that as a resource abuse. A suitable workaround would be [to add a custom route](https://docs.haystack.deepset.ai/reference/routers-api) to classify queries and add necessary steps to the pipeline.
- The current pipeline is only suitable for Python GitHub repositories. For repositories in other languages, the reader may want some workaround with data fetching steps.

_All images, unless otherwise noted, are by the author._

## Resources

- All codes related to this tutorial can be accessed via [this GitHub repository](https://github.com/Ransaka/code_assistant).
- The GitHub repository used for data fetching can be seen in [this link](https://github.com/Ransaka/sinlib).
- I found [this Redis helpful resource](https://redis.io/learn/howtos/solutions/vector/getting-started-vector) for someone with minimal knowledge of Redis vector search.

*This article was originally published in [TDS Archive](https://medium.com/data-science/building-llm-powered-coding-assitant-for-github-rag-with-gemini-and-redis-b88beeb42f2d) on Medium.*
