File size: 9,431 Bytes
da00ae1
 
 
 
 
 
 
c114add
da00ae1
 
 
 
 
c114add
da00ae1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c114add
 
 
 
da00ae1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c114add
da00ae1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f9e56a
 
da00ae1
1f9e56a
 
da00ae1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f96e73c
 
 
da00ae1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
# This app allows users to ask questions about a codebase.
# It uses:
# - Panel for the UI
# - Langchain for the chain
# - Chroma for the vectorstore

# For local dev env : install the following packages
#!pip install langchain openai chromadb panel gitpython python-dotenv

import os 
import panel as pn
from typing import List
from urllib.parse import urlparse
from dotenv import load_dotenv

from langchain.chains import RetrievalQA
from langchain.llms import OpenAI
from langchain.document_loaders import GitLoader
from langchain.indexes import VectorstoreIndexCreator
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.embeddings import OpenAIEmbeddings
from langchain.embeddings import HuggingFaceInstructEmbeddings
from langchain.vectorstores import Chroma
from langchain.chat_models import ChatOpenAI
from langchain.vectorstores import Chroma
from langchain.docstore.document import Document
from langchain.schema import BaseRetriever

#------------------------------------------------------------------------------
# Utils

def get_repo_name_from_url(url):
    url_parsed = urlparse(url)
    return os.path.basename(url_parsed.path).replace(".git", "")

def get_names_subdirs(path_dir):
    return [f.name for f in os.scandir(path_dir) if f.is_dir()]

def remove_empty_subdirs(path_dir):
    for root, dirs, files in os.walk(path_dir, topdown=False):
        for name in dirs:
            dir_path = os.path.join(root, name)
            if len(os.listdir(dir_path)) == 0:
                os.rmdir(dir_path)

def get_names_repos_already_checkout():
    path_checkout = "checkout"
    remove_empty_subdirs(path_checkout)
    return get_names_subdirs(path_checkout)

def get_env(key):
    load_dotenv()
    return os.getenv(key)

#------------------------------------------------------------------------------
# Panel setup
pn.extension(
    'texteditor', 
    template = "bootstrap", 
    sizing_mode = 'stretch_width'
)

pn.state.template.param.update(
    main_max_width = "690px",
    header_background = "#F08080",
    title = "Squirrel : Semantic code search and question answering"
)

#------------------------------------------------------------------------------
# User inputs

input_key_openai = pn.widgets.PasswordInput(
    value = get_env("OPENAI_API_KEY"),
    placeholder = "Enter your OpenAI API Key here...", 
    width = 300
)

select_repo = pn.widgets.RadioBoxGroup(
    options = get_names_repos_already_checkout() + ["Custom"], 
    inline = False
)

input_url_repo = pn.widgets.TextInput(
    value = "", 
    placeholder = "Enter your GitHub repo URL here...", 
    width = 300
)

input_branch_repo = pn.widgets.TextInput(
    value="", 
    placeholder="Enter the GitHub repo branch here...", 
    width=300
)

select_embedding = pn.widgets.RadioBoxGroup(
    options=['openai', 'instruct'],
    inline=False
)

input_question = pn.widgets.TextEditor(
    value="", 
    placeholder="Enter your questions here...", 
    height=200, 
    toolbar=False
)

run_button = pn.widgets.Button(
    name="Run",
    button_type="primary"
)

select_k = pn.widgets.IntSlider(
    name="Number of relevant chunks", 
    start=1, 
    end=10, 
    step=1, 
    value=3
)

select_chain_type = pn.widgets.RadioButtonGroup(
    name='Chain type', 
    options=['stuff', 'map_reduce', "refine", "map_rerank"]
)

def toggle_github_inputs(event):
    if event.new == "Custom":
        input_url_repo.disabled = False
        input_branch_repo.disabled = False
    else: 
        input_url_repo.disabled = True 
        input_branch_repo.disabled = True

select_repo.param.watch(toggle_github_inputs, 'value')

#------------------------------------------------------------------------------
def init_embedding_openai():
    return OpenAIEmbeddings(
        model = "text-embedding-ada-002",
        openai_api_key=input_key_openai.value
    )

def init_embedding_instruct():
    # Default model: instructor-large
    return HuggingFaceInstructEmbeddings(
        query_instruction="Represent the query for retrival:"
    )

embedding_functions = {
    "openai": init_embedding_openai,
    "instruct": init_embedding_instruct
}

result_panel_objects = [] 

def load_repo(name_repo):
    print(f"Name repo: {name_repo}")
    path_checkout = os.path.join("checkout", name_repo)
    print(f"Path checkout: {path_checkout}")
    is_repo_already_checkout = os.path.exists(path_checkout) and len(os.listdir(path_checkout)) > 0
    print(f"Is repo already checkout: {is_repo_already_checkout}")
    print(f"Repo URL: {input_url_repo.value}")
    print(f"Branch: {input_branch_repo.value}")

    file_filter = lambda file_path: file_path.endswith(".swift") or file_path.endswith(".h") or file_path.endswith(".m")
    
    if is_repo_already_checkout:
        print("Repo already checkout")
        print("Loading documents...")
        loader = GitLoader(
            repo_path=path_checkout,
            branch=input_branch_repo.value,
            file_filter=file_filter
        )
    else:
        print("Repo not checkout")
        print("Cloning repo and loading documents...")
        loader = GitLoader(
            repo_path=path_checkout,
            clone_url=input_url_repo.value,
            branch=input_branch_repo.value,
            file_filter=file_filter
        )

    documents = loader.load()
    return documents
    
def get_result_qa_chain():
    os.environ["OPENAI_API_KEY"] = input_key_openai.value
    if select_repo.value == "Custom":
        name_repo = get_repo_name_from_url(input_url_repo.value)
    else:
        name_repo = select_repo.value
    name_embedding = select_embedding.value
    embedding_function = embedding_functions[name_embedding]()
    path_dir_db = f"dbs/{name_repo}/{name_embedding}"
    is_repo_already_indexed = os.path.exists(path_dir_db)

    result_panel_objects.clear()

    if not is_repo_already_indexed:
        print("Repo not indexed. Starting indexing...")
        documents = load_repo(name_repo)
        texts = RecursiveCharacterTextSplitter(chunk_size=3000, chunk_overlap=0).split_documents(documents)
        db = Chroma.from_documents(
            documents=texts,
            embedding=embedding_function, 
            persist_directory=path_dir_db
        )
    else:
        print("Repo already indexed")
        db = Chroma(
            embedding_function=embedding_function,
            persist_directory=path_dir_db, 
        )
    db.persist()

    retriever = db.as_retriever(
        search_type = "similarity", 
        search_kwargs = { "k": select_k.value }
    )

    # llm=OpenAI(temperature=0, model_name="text-davinci-002")
    llm = ChatOpenAI(
        model_name = "gpt-3.5-turbo", 
        temperature=0.7, 
        max_tokens=1000)

    # create a chain to answer questions 
    qa = RetrievalQA.from_chain_type(
        llm=llm, 
        chain_type=select_chain_type.value, 
        retriever=retriever, 
        return_source_documents=True
    )
    
    final_prompt = f"You are a coder 'Bot' that helps the 'User' reading, understanding and writing code, being proactive and as verbose as necessary. Propose code and refactor sources when needed. User: {input_question.value} Bot:"
    result = qa({"query": final_prompt})

    return result

def result_box(_):
    if input_question.value:
        result = get_result_qa_chain()

        result_panel_objects.extend([
            pn.Row(
                pn.panel("\U0001F60A", width=10),
                input_question.value
            ),
            pn.Row(
                pn.panel("\U0001F916", width=10),
                pn.Column(
                    result["result"],
                    "<hr>",
                    pn.pane.Markdown(f"### Retrieved sources\n"),
                    pn.Column(
                        *[pn.pane.Markdown(f"#####{i+1}\n```\n{doc.page_content}\n```", width=600) for i, doc in enumerate(result["source_documents"])]
                    )
                )
            )
        ])


    return pn.Column(
        *result_panel_objects, 
        min_height=400,
        min_width=600,
    )

# -----------------------------------------------------------------------------
# Layout
config_section = pn.Column(
    pn.Column(
        input_key_openai
    ),
    pn.Card(
        pn.Column(
            select_repo, 
            input_url_repo, 
            input_branch_repo
        ),
        title="Load codebase"
    ),
    pn.Card(
        pn.Column(
            select_embedding
        ),
        title="Select embedding"
    ),
    pn.Card(
        "Chain type:",
        pn.Column(
            select_chain_type, 
            select_k
        ),
        title="Advanced settings", 
        collapsed=True
    )
)

input_section = pn.Card(
    pn.Row(input_question),
    run_button,
    title="Ask a question"
)

# show time elapsed
output_section = pn.Card(
    pn.panel(
        pn.bind(
            result_box, 
            run_button
        ),
        loading_indicator=True,
    ),
    title="Output"
)

pn.Column(
    pn.pane.Markdown("""
    ### \U0001F60A Ask Squirrel a question about your codebase
    
    1. Enter the url of a github repo and a branch (swift / objc)
    2. Enter OpenAI API key. This costs $. Set up billing at [OpenAI](https://platform.openai.com/account).
    3. Type a question and click "Run".
    
    """),
    config_section,
    input_section,
    output_section
).servable()