nn-rag 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
nn_rag-0.1.0/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024- ABrain One and contributors
4
+ All rights reserved.
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
@@ -0,0 +1,5 @@
1
+ recursive-include ab *.py *.json *.md
2
+ include requirements.txt
3
+ include README.md
4
+ include LICENSE
5
+ include version
nn_rag-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,27 @@
1
+ Metadata-Version: 2.4
2
+ Name: nn-rag
3
+ Version: 0.1.0
4
+ Summary: Neural Retrieval-Augmented Generation for GitHub Search
5
+ Home-page: https://github.com/ABrain-One/nn-rag
6
+ Author: ABrain One and contributors
7
+ Author-email: AI@ABrain.one
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.6
12
+ License-File: LICENSE
13
+ Requires-Dist: PyGithub>=1.55
14
+ Requires-Dist: sentence-transformers>=2.2.2
15
+ Requires-Dist: scikit-learn>=1.0.2
16
+ Requires-Dist: transformers>=4.26.1
17
+ Requires-Dist: python-dotenv>=1.0.0
18
+ Requires-Dist: pandas>=1.5.3
19
+ Requires-Dist: dotenv
20
+ Dynamic: author
21
+ Dynamic: author-email
22
+ Dynamic: classifier
23
+ Dynamic: home-page
24
+ Dynamic: license-file
25
+ Dynamic: requires-dist
26
+ Dynamic: requires-python
27
+ Dynamic: summary
nn_rag-0.1.0/README.md ADDED
@@ -0,0 +1,28 @@
1
+ # <img src='https://abrain.one/img/lemur-nn-icon-64x64.png' width='32px'/> LLM Retrieval Augmented Generation
2
+
3
+ # nn-rag
4
+
5
+ A minimal Retrieval-Augmented Generation (RAG) pipeline for code and dataset details.
6
+ This project aims to provide LLMs with additional context from the internet or local repos,
7
+ then optionally fine-tune the LLM for specific tasks.
8
+
9
+ ## Requirements
10
+
11
+ - **Python** 3.8+ recommended
12
+ - **Pip** or **Conda** for installing dependencies
13
+ - (Optional) **GPU** with CUDA if you plan to use `faiss-gpu` or do large-scale training
14
+
15
+ ### Installing Dependencies
16
+
17
+ 1. Create and activate a virtual environment (recommended):
18
+ ```bash
19
+ python -m venv venv
20
+ source venv/bin/activate # Linux/Mac
21
+ venv\Scripts\activate # Windows
22
+
23
+ 2. ### Latest Development Version
24
+
25
+ Install the latest version directly from GitHub:
26
+
27
+ ```bash
28
+ pip install git+https://github.com/ABrain-One/nn-rag --upgrade
File without changes
File without changes
@@ -0,0 +1,63 @@
1
+ from pandas import DataFrame
2
+ from utils.github_utils import build_query, search_repositories_with_cache
3
+ from utils.neural_utils import neural_rank_repositories, generate_response_from_results
4
+
5
+ def retrieve_and_generate(
6
+ keyword: str,
7
+ language: str = None,
8
+ owner: str = None,
9
+ stars: str = None,
10
+ max_results: int = 100,
11
+ num_top: int = 3
12
+ ) -> dict:
13
+ """
14
+ Retrieve GitHub repositories based on search parameters, perform neural ranking,
15
+ and generate a final response using a generative model.
16
+
17
+ Parameters:
18
+ - keyword: Base search keyword.
19
+ - language: (Optional) Filter by programming language.
20
+ - owner: (Optional) Restrict search to a specific repository owner.
21
+ - stars: (Optional) Filter by stars (e.g., ">100", "<50").
22
+ - max_results: Maximum number of repositories to retrieve.
23
+ - num_top: Number of top results to use for generation.
24
+
25
+ Returns:
26
+ A dictionary with the built query, top-ranked results, and generated response.
27
+ """
28
+ qualifiers = {}
29
+ if language:
30
+ qualifiers["language"] = language
31
+ if owner:
32
+ qualifiers["user"] = owner
33
+ if stars:
34
+ qualifiers["stars"] = stars
35
+
36
+ query = build_query(keyword, qualifiers)
37
+ repo_results = search_repositories_with_cache(query, max_results=max_results)
38
+ if not repo_results:
39
+ return {"error": "No results found."}
40
+ ranked_repos = neural_rank_repositories(repo_results, keyword)
41
+ generated_response = generate_response_from_results(keyword, ranked_repos, num_results=num_top)
42
+ return {
43
+ "query": query,
44
+ "results": ranked_repos[:10],
45
+ "generated_response": generated_response
46
+ }
47
+
48
+ def retrieve_and_generate_df(
49
+ keyword: str,
50
+ language: str = None,
51
+ owner: str = None,
52
+ stars: str = None,
53
+ max_results: int = 100,
54
+ num_top: int = 3
55
+ ) -> DataFrame:
56
+ """
57
+ Return the top repository results as a pandas DataFrame.
58
+ """
59
+ data = retrieve_and_generate(keyword, language, owner, stars, max_results, num_top)
60
+ if "error" in data:
61
+ return DataFrame()
62
+ from pandas import DataFrame
63
+ return DataFrame(data["results"])
File without changes
@@ -0,0 +1,9 @@
1
+ import os
2
+ from dotenv import load_dotenv
3
+
4
+ load_dotenv() # Loads variables from .env
5
+
6
+ GITHUB_TOKEN = os.getenv("GITHUB_TOKEN")
7
+ CACHE_FILE = "search_cache.db"
8
+ MODEL_NAME = "all-MiniLM-L6-v2"
9
+ GENERATOR_MODEL = "gpt2"
@@ -0,0 +1,19 @@
1
+ # For running the application from the command line (local testing)
2
+ from api import retrieve_and_generate
3
+
4
+ if __name__ == "__main__":
5
+ keyword = input("Enter search keyword: ").strip()
6
+ language = input("Filter by language (press enter to skip): ").strip() or None
7
+ owner = input("Restrict search to a specific owner (press enter to skip): ").strip() or None
8
+ stars = input("Filter by stars (e.g., >100, <50) (press enter to skip): ").strip() or None
9
+
10
+ result = retrieve_and_generate(keyword, language, owner, stars)
11
+
12
+ if "error" in result:
13
+ print("Error:", result["error"])
14
+ else:
15
+ print("\nFinal Generated Response:")
16
+ print(result.get("generated_response"))
17
+ print("\nTop Ranked Repositories:")
18
+ for repo in result.get("results", []):
19
+ print(f"{repo['full_name']} - {repo['stars']} stars - Neural Score: {repo['neural_score']:.4f} - URL: {repo['url']}")
File without changes
@@ -0,0 +1,52 @@
1
+ import time
2
+ import shelve
3
+ from github import Github, Auth, RateLimitExceededException, GithubException
4
+ from config.config import GITHUB_TOKEN, CACHE_FILE
5
+
6
+ # Create a GitHub instance using the token from config
7
+ g = Github(auth=Auth.Token(GITHUB_TOKEN))
8
+
9
+ def wait_for_rate_limit():
10
+ core_limit = g.get_rate_limit().core
11
+ reset_timestamp = core_limit.reset.timestamp()
12
+ current_timestamp = time.time()
13
+ wait_time = reset_timestamp - current_timestamp + 5 # extra buffer
14
+ print(f"Rate limit exceeded. Waiting for {wait_time:.0f} seconds...")
15
+ time.sleep(wait_time)
16
+
17
+ def build_query(base_keyword: str, qualifiers: dict) -> str:
18
+ query = f"{base_keyword} in:readme in:description"
19
+ for key, value in qualifiers.items():
20
+ if value:
21
+ query += f" {key}:{value}"
22
+ return query
23
+
24
+ def search_repositories_with_cache(query: str, max_results: int = 100) -> list[dict]:
25
+ with shelve.open(CACHE_FILE) as cache:
26
+ if query in cache:
27
+ print("Using cached repository results.")
28
+ return cache[query]
29
+ else:
30
+ while True:
31
+ try:
32
+ repos = g.search_repositories(query, sort="stars", order="desc")
33
+ break
34
+ except RateLimitExceededException:
35
+ wait_for_rate_limit()
36
+ except GithubException as e:
37
+ print("GitHub Exception:", e)
38
+ return []
39
+ repo_list = []
40
+ count = 0
41
+ for repo in repos:
42
+ repo_list.append({
43
+ "full_name": repo.full_name,
44
+ "stars": repo.stargazers_count,
45
+ "url": repo.html_url,
46
+ "description": repo.description or ""
47
+ })
48
+ count += 1
49
+ if count >= max_results:
50
+ break
51
+ cache[query] = repo_list
52
+ return repo_list
@@ -0,0 +1,75 @@
1
+ import time
2
+ import logging
3
+ from sentence_transformers import SentenceTransformer
4
+ from sklearn.metrics.pairwise import cosine_similarity
5
+ from transformers import pipeline
6
+ from config.config import MODEL_NAME, GENERATOR_MODEL
7
+
8
+ logging.basicConfig(level=logging.INFO)
9
+ logger = logging.getLogger(__name__)
10
+
11
+ model = SentenceTransformer(MODEL_NAME)
12
+ generator = pipeline("text-generation", model=GENERATOR_MODEL)
13
+
14
+ def neural_rank_repositories(repo_results: list[dict], search_query: str) -> list[dict]:
15
+ logger.info("Starting neural ranking for query: '%s'", search_query)
16
+ start_time = time.time()
17
+ query_embedding = model.encode([search_query])
18
+ texts = [f"{repo['full_name']}. {repo['description']}" for repo in repo_results]
19
+ embeddings = model.encode(texts)
20
+ similarities = cosine_similarity(query_embedding, embeddings)[0]
21
+ for repo, score in zip(repo_results, similarities):
22
+ repo["neural_score"] = score
23
+ ranked = sorted(repo_results, key=lambda x: x["neural_score"], reverse=True)
24
+ elapsed = time.time() - start_time
25
+ logger.info("Neural ranking completed in %.2f seconds.", elapsed)
26
+ return ranked
27
+
28
+ def generate_response_from_results(
29
+ search_query: str,
30
+ ranked_results: list[dict],
31
+ num_results: int = 3,
32
+ temperature: float = 0.6,
33
+ top_k: int = 40,
34
+ top_p: float = 0.8,
35
+ max_new_tokens: int = 120
36
+ ) -> str:
37
+ """
38
+ Build a detailed prompt from the top-ranked results and generate a final response using
39
+ the generative model. The prompt now instructs the model to provide:
40
+ - A concise technical summary on implementing dynamic filtering.
41
+ - A simple pseudo-code example.
42
+ - Key design decisions highlighted.
43
+
44
+ Generation parameters are adjusted for a bit less randomness (lower temperature) and
45
+ more focused sampling (top_k, top_p).
46
+ """
47
+ context = f"Search Query: {search_query}\n\nTop relevant repositories:\n"
48
+ for repo in ranked_results[:num_results]:
49
+ context += (
50
+ f"- {repo['full_name']} (Stars: {repo['stars']})\n"
51
+ f" Description: {repo['description']}\n"
52
+ f" URL: {repo['url']}\n\n"
53
+ )
54
+ # Updated prompt instructing for a concise summary and pseudo-code
55
+ context += (
56
+ "Based on the above information, provide a concise technical summary that explains "
57
+ "how one might implement dynamic filtering in a software project. Include a simple pseudo-code "
58
+ "example and explicitly mention key design decisions (such as choice of data structures, performance considerations, "
59
+ "and modular design)."
60
+ )
61
+
62
+ # Log prompt length for debugging
63
+ logger.info("Prompt built with length: %d characters", len(context))
64
+
65
+ response = generator(
66
+ context,
67
+ max_new_tokens=max_new_tokens,
68
+ truncation=True,
69
+ do_sample=True,
70
+ temperature=temperature,
71
+ top_k=top_k,
72
+ top_p=top_p
73
+ )[0]['generated_text']
74
+
75
+ return response
@@ -0,0 +1,27 @@
1
+ Metadata-Version: 2.4
2
+ Name: nn-rag
3
+ Version: 0.1.0
4
+ Summary: Neural Retrieval-Augmented Generation for GitHub Search
5
+ Home-page: https://github.com/ABrain-One/nn-rag
6
+ Author: ABrain One and contributors
7
+ Author-email: AI@ABrain.one
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.6
12
+ License-File: LICENSE
13
+ Requires-Dist: PyGithub>=1.55
14
+ Requires-Dist: sentence-transformers>=2.2.2
15
+ Requires-Dist: scikit-learn>=1.0.2
16
+ Requires-Dist: transformers>=4.26.1
17
+ Requires-Dist: python-dotenv>=1.0.0
18
+ Requires-Dist: pandas>=1.5.3
19
+ Requires-Dist: dotenv
20
+ Dynamic: author
21
+ Dynamic: author-email
22
+ Dynamic: classifier
23
+ Dynamic: home-page
24
+ Dynamic: license-file
25
+ Dynamic: requires-dist
26
+ Dynamic: requires-python
27
+ Dynamic: summary
@@ -0,0 +1,20 @@
1
+ LICENSE
2
+ MANIFEST.in
3
+ README.md
4
+ requirements.txt
5
+ setup.py
6
+ version
7
+ ab/__init__.py
8
+ ab/rag/__init__.py
9
+ ab/rag/api.py
10
+ ab/rag/main.py
11
+ ab/rag/config/__init__.py
12
+ ab/rag/config/config.py
13
+ ab/rag/utils/__init__.py
14
+ ab/rag/utils/github_utils.py
15
+ ab/rag/utils/neural_utils.py
16
+ nn_rag.egg-info/PKG-INFO
17
+ nn_rag.egg-info/SOURCES.txt
18
+ nn_rag.egg-info/dependency_links.txt
19
+ nn_rag.egg-info/requires.txt
20
+ nn_rag.egg-info/top_level.txt
@@ -0,0 +1,7 @@
1
+ PyGithub>=1.55
2
+ sentence-transformers>=2.2.2
3
+ scikit-learn>=1.0.2
4
+ transformers>=4.26.1
5
+ python-dotenv>=1.0.0
6
+ pandas>=1.5.3
7
+ dotenv
@@ -0,0 +1 @@
1
+ ab
@@ -0,0 +1,7 @@
1
+ PyGithub>=1.55
2
+ sentence-transformers>=2.2.2
3
+ scikit-learn>=1.0.2
4
+ transformers>=4.26.1
5
+ python-dotenv>=1.0.0
6
+ pandas>=1.5.3
7
+ dotenv
nn_rag-0.1.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
nn_rag-0.1.0/setup.py ADDED
@@ -0,0 +1,28 @@
1
+ from setuptools import setup, find_packages
2
+ from pathlib import Path
3
+
4
+ # Read the dependencies from requirements.txt
5
+ with open("requirements.txt") as f:
6
+ required = f.read().splitlines()
7
+
8
+ def version():
9
+ with open(Path(__file__).parent / 'version', 'r') as file:
10
+ v = file.readline()
11
+ return v
12
+
13
+ setup(
14
+ name="nn-rag",
15
+ version=version(),
16
+ description="Neural Retrieval-Augmented Generation for GitHub Search",
17
+ author="ABrain One and contributors",
18
+ author_email="AI@ABrain.one",
19
+ url="https://github.com/ABrain-One/nn-rag",
20
+ packages=find_packages(),
21
+ install_requires=required,
22
+ classifiers=[
23
+ "Programming Language :: Python :: 3",
24
+ "License :: OSI Approved :: MIT License",
25
+ "Operating System :: OS Independent",
26
+ ],
27
+ python_requires=">=3.6",
28
+ )
nn_rag-0.1.0/version ADDED
@@ -0,0 +1 @@
1
+ 0.1.0