Skip to content

Commit 4b6ffca

Browse files
authored
Merge pull request #19 from sam43/dev-refactor-codebase-ph1
Dev refactor codebase ph1
2 parents 724a50a + b0374cb commit 4b6ffca

File tree

14 files changed

+488
-140
lines changed

14 files changed

+488
-140
lines changed

.gitignore

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
venv/
22
build/
3-
*.egg-info/
3+
.egg-info/
44
sessions/
55
__pycache__/
66
.pytest_cache/
@@ -9,16 +9,17 @@ core/__pycache__/
99
node_modules/
1010
codechat/tree-sitter-c
1111
codechat/tree-sitter-swift
12-
codechat/__pycache__
13-
codechat/events/__pycache__
14-
codechat/domain/__pycache__
15-
codechat/data/__pycache__
16-
codechat/interface/__pycache__
17-
tests/core/__pycache__
18-
tests/interface/__pycache__
19-
tests/data/__pycache__
20-
tests/domain/__pycache__
21-
tests/events/__pycache__
12+
codechat/__pycache__/
13+
codechat/events/__pycache__/
14+
codechat/domain/__pycache__/
15+
codechat/data/__pycache__/
16+
codechat/interface/__pycache__/
17+
tests/core/__pycache__/
18+
tests/interface/__pycache__/
19+
tests/data/__pycache__/
20+
tests/domain/__pycache__/
21+
tests/events/__pycache__/
22+
tests/__pycache__/
2223
dist/
2324
codez_cli.egg-info/
2425
vendor/java-tree-sitter

README.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,12 @@ Whether you're learning a new language, need a quick code snippet, or want to un
1818
* 🌐 **Web-Savvy (Optional):** Enable a web search tool to pull in external knowledge.
1919
* 🧐 **Code Analysis (Swift/C):** Uses `tree-sitter` for deeper insights into Swift and C codebases (requires a small helper library).
2020

21+
## There'sMore :
22+
- **Model Management**: Easily switch between local LLMs using `/models` or `/model` commands at any time.
23+
- **Automatic Model Download**: If no Ollama models are found, the CLI will prompt you to download and run the default model (`qwen2.5-coder:1.5b-instruct`).
24+
- **Session Memory**: Save, resume, and manage your coding conversations.
25+
- **Extensible & Open Source**: Built for privacy, hackability, and your workflow.
26+
2127
---
2228

2329
## 🚀 Getting Started: Your First Chat in Minutes! 🚀

codechat/cli.py

Lines changed: 1 addition & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -3,32 +3,10 @@
33
"""
44

55
import typer
6-
from core import repl, summarizer
6+
from core import repl
77

88
app = typer.Typer()
99

10-
@app.command("explain")
11-
def explain(path: str, function: str = None):
12-
"""
13-
Explain the content of a file or a specific function within that file.
14-
15-
Args:
16-
path (str): The file path to explain.
17-
function (str, optional): The specific function name to explain. If None, explain the whole file.
18-
19-
This function calls the summarizer to generate a detailed explanation,
20-
handles errors gracefully, and outputs the result to the CLI.
21-
"""
22-
try:
23-
result = summarizer.explain(path, function)
24-
if not result:
25-
typer.echo("No explanation could be generated. Please check the file path and function name.")
26-
else:
27-
typer.echo(result)
28-
except FileNotFoundError:
29-
typer.echo(f"Error: File not found at path '{path}'. Please provide a valid file path.")
30-
except Exception as e:
31-
typer.echo(f"An unexpected error occurred: {e}")
3210

3311
@app.command("chat")
3412
def chat():

core/io_utils.py

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
"""
2+
Input/output utilities for CodeZ CLI REPL.
3+
"""
4+
from rich.console import Console
5+
from rich.syntax import Syntax
6+
from rich.panel import Panel
7+
from rich.markdown import Markdown
8+
from rich.text import Text
9+
10+
def print_code_snippet(snippet: str, language: str = ""):
11+
"""Print code or text as a formatted snippet in the terminal using Rich."""
12+
console = Console()
13+
if not language:
14+
language = "text"
15+
try:
16+
syntax = Syntax(snippet, language, theme="monokai", line_numbers=False, word_wrap=True)
17+
console.print(Panel(syntax, title="Code Snippet"))
18+
except Exception:
19+
# Fallback to plain panel if syntax highlighting fails
20+
console.print(Panel(snippet, title="Snippet"))
21+
22+
def multiline_code_input(prompt_session=None):
23+
instruction_text = Markdown("""\
24+
Enter your code snippet below.
25+
- Type ` ``` ` on a new line to **start** the block.
26+
- Paste or type your code.
27+
- Use **Shift+Enter** for new lines within the block if using the default console input.
28+
- Type ` ``` ` on a new line again to **finish** the block.
29+
""")
30+
console = Console()
31+
console.print(Panel(instruction_text, title="[bold cyan]Multiline Code Input[/bold cyan]", border_style="cyan", expand=False))
32+
33+
lines = []
34+
in_block = False
35+
36+
# Use a consistent prompt style
37+
input_prompt_style = "[bold sky_blue1]>>> (code)[/bold sky_blue1] " if prompt_session else "[bold sky_blue1]> (code)[/bold sky_blue1] "
38+
39+
while True:
40+
if prompt_session:
41+
# Prompt toolkit's prompt doesn't directly take Rich ConsoleMarkup for the prompt string
42+
# For simplicity, keeping the prompt session's default prompt look here
43+
line = prompt_session.prompt(">>> (code) ", multiline=True) # Simple text prompt
44+
else:
45+
line = console.input(input_prompt_style)
46+
47+
if line.strip() == "```":
48+
if in_block:
49+
break
50+
else:
51+
in_block = True
52+
continue
53+
if in_block:
54+
lines.append(line)
55+
return "\n".join(lines)

core/model.py

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,13 @@
33
import re
44

55
OLLAMA_GITHUB_URL = "https://github.com/ollama/ollama"
6+
DEFAULT_MODEL = "qwen2.5-coder:1.5b-instruct"
67

7-
def query_ollama(prompt: str, model: str = "deepseek-r1:latest"):
8+
def query_ollama(prompt: str, model: str = DEFAULT_MODEL):
9+
"""
10+
Query the Ollama LLM with the given prompt and model.
11+
You can change the model at any time using the /models or /model command in the CLI.
12+
"""
813
result = subprocess.run(
914
["ollama", "run", model, prompt],
1015
capture_output=True,
@@ -17,6 +22,10 @@ def query_ollama(prompt: str, model: str = "deepseek-r1:latest"):
1722
return output
1823

1924
def get_ollama_models():
25+
"""
26+
Returns a tuple: (list_of_models, error_message)
27+
If no models are found, prompts the user to download the default model.
28+
"""
2029
try:
2130
result = subprocess.run([
2231
"ollama", "list"
@@ -27,9 +36,38 @@ def get_ollama_models():
2736
for line in result.stdout.strip().split('\n'):
2837
if line and not line.startswith('NAME'):
2938
models.append(line.split()[0])
39+
# If no models found, prompt user to download the default model
40+
if not models:
41+
print(
42+
f"[CodeZ CLI] No Ollama models found on your system.\n"
43+
f"Would you like to download and run the default model ([bold]{DEFAULT_MODEL}[/bold]) now? [y/N]"
44+
)
45+
try:
46+
user_input = input("Download and run default model? [y/N]: ").strip().lower()
47+
except EOFError:
48+
user_input = "n"
49+
if user_input in ["y", "yes"]:
50+
print(f"[CodeZ CLI] Downloading and running default model: {DEFAULT_MODEL} ...")
51+
try:
52+
pull_result = subprocess.run(
53+
["ollama", "run", DEFAULT_MODEL, "Hello!"],
54+
capture_output=True,
55+
text=True
56+
)
57+
if pull_result.returncode == 0:
58+
print(f"[CodeZ CLI] Model '{DEFAULT_MODEL}' downloaded and ready.")
59+
# Try listing again
60+
return get_ollama_models()
61+
else:
62+
return None, f"Failed to download model '{DEFAULT_MODEL}'. Please try manually: ollama run {DEFAULT_MODEL}"
63+
except Exception as e:
64+
return None, f"Error downloading model '{DEFAULT_MODEL}': {e}"
65+
else:
66+
return None, f"No models found. Please download a model using: ollama run {DEFAULT_MODEL}"
3067
return models, None
3168
except FileNotFoundError:
3269
return None, f"Ollama not found. Please install it from {OLLAMA_GITHUB_URL}"
3370

71+
3472
def fetch_webpage(query, urls):
3573
return {"content": f"[Web search not available in this environment. Simulated result for: {query}]"}

0 commit comments

Comments
 (0)