anix-type 0.1.0__py3-none-any.whl
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.
- anix_type/__init__.py +3 -0
- anix_type/__main__.py +4 -0
- anix_type/cli.py +232 -0
- anix_type/engine/ai.py +288 -0
- anix_type/engine/context.py +161 -0
- anix_type/engine/heuristics.py +222 -0
- anix_type/engine/history.py +100 -0
- anix_type/i18n.py +96 -0
- anix_type/integrations/anix-type.ps1 +214 -0
- anix_type/server.py +137 -0
- anix_type/settings.py +51 -0
- anix_type-0.1.0.dist-info/METADATA +207 -0
- anix_type-0.1.0.dist-info/RECORD +17 -0
- anix_type-0.1.0.dist-info/WHEEL +5 -0
- anix_type-0.1.0.dist-info/entry_points.txt +2 -0
- anix_type-0.1.0.dist-info/licenses/LICENSE +21 -0
- anix_type-0.1.0.dist-info/top_level.txt +1 -0
anix_type/__init__.py
ADDED
anix_type/__main__.py
ADDED
anix_type/cli.py
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
"""Command-line interface for anix-type."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import os
|
|
6
|
+
import subprocess
|
|
7
|
+
import sys
|
|
8
|
+
import urllib.request
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from . import __version__
|
|
12
|
+
from .server import run_server
|
|
13
|
+
from .settings import Settings, get_config_dir
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _check_running(port: int = 8766) -> bool:
|
|
17
|
+
try:
|
|
18
|
+
with urllib.request.urlopen(f"http://127.0.0.1:{port}/health", timeout=0.5) as resp:
|
|
19
|
+
return resp.status == 200
|
|
20
|
+
except Exception:
|
|
21
|
+
return False
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def cmd_status(args: argparse.Namespace) -> None:
|
|
25
|
+
settings = Settings.load()
|
|
26
|
+
running = _check_running(settings.port)
|
|
27
|
+
print(f"⚡ ANIX Type v{__version__}")
|
|
28
|
+
print(f" Daemon status: {'🟢 Running' if running else '🔴 Stopped'}")
|
|
29
|
+
print(f" Port: {settings.port}")
|
|
30
|
+
print(f" AI Provider: {settings.ai_provider}")
|
|
31
|
+
print(f" AI Model: {settings.model}")
|
|
32
|
+
if settings.ai_provider == "groq":
|
|
33
|
+
masked = (settings.groq_api_key[:6] + "…" + settings.groq_api_key[-4:]) if len(settings.groq_api_key) > 10 else "(not set)"
|
|
34
|
+
print(f" Groq Key: {masked}")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def cmd_daemon(args: argparse.Namespace) -> None:
|
|
38
|
+
run_server(port=args.port, verbose=args.verbose)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def cmd_start(args: argparse.Namespace) -> None:
|
|
42
|
+
settings = Settings.load()
|
|
43
|
+
if _check_running(settings.port):
|
|
44
|
+
print(f"⚡ ANIX Type is already running on port {settings.port}!")
|
|
45
|
+
return
|
|
46
|
+
|
|
47
|
+
exe = sys.executable
|
|
48
|
+
if sys.platform == "win32":
|
|
49
|
+
pw = Path(sys.executable).parent / "pythonw.exe"
|
|
50
|
+
if pw.is_file():
|
|
51
|
+
exe = str(pw)
|
|
52
|
+
|
|
53
|
+
cmd = [exe, "-m", "anix_type", "daemon", "--port", str(settings.port)]
|
|
54
|
+
creationflags = 0
|
|
55
|
+
if sys.platform == "win32":
|
|
56
|
+
creationflags = subprocess.CREATE_NO_WINDOW | subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP # type: ignore[attr-defined]
|
|
57
|
+
|
|
58
|
+
subprocess.Popen(
|
|
59
|
+
cmd,
|
|
60
|
+
stdin=subprocess.DEVNULL,
|
|
61
|
+
stdout=subprocess.DEVNULL,
|
|
62
|
+
stderr=subprocess.DEVNULL,
|
|
63
|
+
creationflags=creationflags,
|
|
64
|
+
close_fds=True,
|
|
65
|
+
)
|
|
66
|
+
print(f"⚡ ANIX Type started in background on http://127.0.0.1:{settings.port}")
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def cmd_stop(args: argparse.Namespace) -> None:
|
|
70
|
+
settings = Settings.load()
|
|
71
|
+
if not _check_running(settings.port):
|
|
72
|
+
print("ANIX Type is not running.")
|
|
73
|
+
return
|
|
74
|
+
|
|
75
|
+
if sys.platform == "win32":
|
|
76
|
+
try:
|
|
77
|
+
out = subprocess.check_output(f"netstat -ano | findstr :{settings.port}", shell=True, text=True)
|
|
78
|
+
for line in out.splitlines():
|
|
79
|
+
if "LISTENING" in line:
|
|
80
|
+
pid = line.strip().split()[-1]
|
|
81
|
+
subprocess.run(f"taskkill /PID {pid} /F", shell=True, check=False)
|
|
82
|
+
print("⚡ ANIX Type daemon stopped.")
|
|
83
|
+
return
|
|
84
|
+
except Exception:
|
|
85
|
+
pass
|
|
86
|
+
print("Could not automatically stop daemon. Please close the process.")
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def cmd_install(args: argparse.Namespace) -> None:
|
|
90
|
+
"""Install integration hook into PowerShell profile or bash/zsh."""
|
|
91
|
+
if sys.platform == "win32":
|
|
92
|
+
_install_powershell()
|
|
93
|
+
else:
|
|
94
|
+
print("For Linux/macOS, add `eval $(anix-type init zsh)` to your ~/.zshrc or ~/.bashrc.")
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _get_powershell_profile_path() -> Path:
|
|
98
|
+
candidates = [
|
|
99
|
+
Path.home() / "Documents" / "WindowsPowerShell" / "Microsoft.PowerShell_profile.ps1",
|
|
100
|
+
Path.home() / "OneDrive" / "Documents" / "WindowsPowerShell" / "Microsoft.PowerShell_profile.ps1",
|
|
101
|
+
]
|
|
102
|
+
for c in candidates:
|
|
103
|
+
if c.is_file():
|
|
104
|
+
return c
|
|
105
|
+
|
|
106
|
+
try:
|
|
107
|
+
raw = subprocess.check_output(
|
|
108
|
+
["powershell", "-NoProfile", "-Command", "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; Write-Output $PROFILE"],
|
|
109
|
+
)
|
|
110
|
+
path_str = raw.decode("utf-8", errors="replace").strip()
|
|
111
|
+
if path_str:
|
|
112
|
+
return Path(path_str)
|
|
113
|
+
except Exception:
|
|
114
|
+
pass
|
|
115
|
+
|
|
116
|
+
return candidates[0]
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _install_powershell() -> None:
|
|
120
|
+
ps_file = Path(__file__).resolve().parent / "integrations" / "anix-type.ps1"
|
|
121
|
+
if not ps_file.is_file():
|
|
122
|
+
print(f"Error: integration script not found at {ps_file}")
|
|
123
|
+
return
|
|
124
|
+
|
|
125
|
+
profile_path = _get_powershell_profile_path()
|
|
126
|
+
profile_path.parent.mkdir(parents=True, exist_ok=True)
|
|
127
|
+
|
|
128
|
+
hook_line = f'. "{ps_file}"'
|
|
129
|
+
existing = ""
|
|
130
|
+
if profile_path.is_file():
|
|
131
|
+
existing = profile_path.read_text(encoding="utf-8", errors="ignore")
|
|
132
|
+
|
|
133
|
+
if hook_line in existing:
|
|
134
|
+
print("✓ ANIX Type is already hooked into your PowerShell $PROFILE:")
|
|
135
|
+
print(f" {profile_path}")
|
|
136
|
+
else:
|
|
137
|
+
with open(profile_path, "a", encoding="utf-8") as f:
|
|
138
|
+
if existing and not existing.endswith("\n"):
|
|
139
|
+
f.write("\n")
|
|
140
|
+
f.write(f"\n# ANIX Type shell autocompletion\n{hook_line}\n")
|
|
141
|
+
print("🎉 Successfully hooked ANIX Type into PowerShell $PROFILE:")
|
|
142
|
+
print(f" {profile_path}")
|
|
143
|
+
print("\nTo activate immediately, restart PowerShell or run:")
|
|
144
|
+
print(f' . "$PROFILE"')
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def cmd_config(args: argparse.Namespace) -> None:
|
|
148
|
+
settings = Settings.load()
|
|
149
|
+
changed = False
|
|
150
|
+
|
|
151
|
+
if args.groq_key:
|
|
152
|
+
settings.groq_api_key = args.groq_key.strip()
|
|
153
|
+
settings.ai_provider = "groq"
|
|
154
|
+
changed = True
|
|
155
|
+
print("✓ Groq API key saved and activated!")
|
|
156
|
+
|
|
157
|
+
if args.openai_key:
|
|
158
|
+
settings.openai_api_key = args.openai_key.strip()
|
|
159
|
+
settings.ai_provider = "openai"
|
|
160
|
+
changed = True
|
|
161
|
+
print("✓ OpenAI/DeepSeek/Custom API key saved and activated!")
|
|
162
|
+
|
|
163
|
+
if args.base_url:
|
|
164
|
+
settings.openai_base_url = args.base_url.strip()
|
|
165
|
+
changed = True
|
|
166
|
+
print(f"✓ Base URL set to: {settings.openai_base_url}")
|
|
167
|
+
|
|
168
|
+
if args.model:
|
|
169
|
+
settings.model = args.model.strip()
|
|
170
|
+
changed = True
|
|
171
|
+
print(f"✓ Model set to: {settings.model}")
|
|
172
|
+
|
|
173
|
+
if args.ollama:
|
|
174
|
+
settings.ai_provider = "ollama"
|
|
175
|
+
changed = True
|
|
176
|
+
print("✓ Switched AI provider to local Ollama!")
|
|
177
|
+
|
|
178
|
+
if changed:
|
|
179
|
+
settings.save()
|
|
180
|
+
print("Restarting daemon to apply new configuration...")
|
|
181
|
+
cmd_stop(args)
|
|
182
|
+
cmd_start(args)
|
|
183
|
+
else:
|
|
184
|
+
print("Usage:")
|
|
185
|
+
print(" anix-type config --groq-key gsk_...")
|
|
186
|
+
print(" anix-type config --openai-key sk-... [--base-url https://api.deepseek.com/v1] [--model deepseek-chat]")
|
|
187
|
+
print(" anix-type config --ollama [--model qwen2.5-coder:1.5b]")
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def main() -> None:
|
|
191
|
+
parser = argparse.ArgumentParser(prog="anix-type", description="Context-aware AI autocompletion for terminal.")
|
|
192
|
+
subparsers = parser.add_subparsers(dest="command")
|
|
193
|
+
|
|
194
|
+
p_daemon = subparsers.add_parser("daemon", help="Run the daemon in foreground")
|
|
195
|
+
p_daemon.add_argument("--port", type=int, default=8766, help="Port to listen on (default: 8766)")
|
|
196
|
+
p_daemon.add_argument("--verbose", action="store_true", help="Enable debug logging")
|
|
197
|
+
|
|
198
|
+
subparsers.add_parser("start", help="Start the daemon in background")
|
|
199
|
+
subparsers.add_parser("stop", help="Stop the running background daemon")
|
|
200
|
+
subparsers.add_parser("status", help="Show daemon and AI configuration status")
|
|
201
|
+
subparsers.add_parser("install", help="Hook ANIX Type into PowerShell $PROFILE")
|
|
202
|
+
|
|
203
|
+
p_conf = subparsers.add_parser("config", help="Configure AI providers and keys")
|
|
204
|
+
p_conf.add_argument("--groq-key", help="Free Groq API key from console.groq.com")
|
|
205
|
+
p_conf.add_argument("--openai-key", help="OpenAI, DeepSeek, OpenRouter or proxy API key")
|
|
206
|
+
p_conf.add_argument("--base-url", help="Custom OpenAI-compatible base URL (e.g. https://api.deepseek.com/v1)")
|
|
207
|
+
p_conf.add_argument("--ollama", action="store_true", help="Use local Ollama")
|
|
208
|
+
p_conf.add_argument("--model", help="Model name (e.g. deepseek-chat, gpt-4o-mini, llama-3.1-8b-instant)")
|
|
209
|
+
|
|
210
|
+
args = parser.parse_args()
|
|
211
|
+
if not args.command:
|
|
212
|
+
cmd_status(args)
|
|
213
|
+
return
|
|
214
|
+
|
|
215
|
+
commands = {
|
|
216
|
+
"status": cmd_status,
|
|
217
|
+
"daemon": cmd_daemon,
|
|
218
|
+
"start": cmd_start,
|
|
219
|
+
"stop": cmd_stop,
|
|
220
|
+
"install": cmd_install,
|
|
221
|
+
"config": cmd_config,
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
fn = commands.get(args.command)
|
|
225
|
+
if fn:
|
|
226
|
+
fn(args)
|
|
227
|
+
else:
|
|
228
|
+
parser.print_help()
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
if __name__ == "__main__":
|
|
232
|
+
main()
|
anix_type/engine/ai.py
ADDED
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
"""AI Command Forge: turns natural language into exact shell commands via Groq / Ollama / heuristics."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import re
|
|
6
|
+
import urllib.request
|
|
7
|
+
from typing import TYPE_CHECKING
|
|
8
|
+
|
|
9
|
+
if TYPE_CHECKING:
|
|
10
|
+
from ..settings import Settings
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
from ..i18n import t
|
|
14
|
+
|
|
15
|
+
def _forge_offline(prompt: str, shell: str) -> str | None:
|
|
16
|
+
"""Instant offline heuristic forge for high-frequency dev operations (EN + RU)."""
|
|
17
|
+
p = prompt.lower().strip()
|
|
18
|
+
|
|
19
|
+
# 1. Git commit rollback / undo
|
|
20
|
+
if ("откат" in p or "отмен" in p or "вернуть" in p or "undo" in p or "rollback" in p or "revert" in p) and ("коммит" in p or "commit" in p):
|
|
21
|
+
if any(w in p for w in ("оставить", "сохранить", "soft", "файлы", "сохраняя", "keep")):
|
|
22
|
+
return "git reset --soft HEAD~1"
|
|
23
|
+
if any(w in p for w in ("жестк", "полност", "стереть", "удалить", "hard", "чист", "discard")):
|
|
24
|
+
return "git reset --hard HEAD~1"
|
|
25
|
+
return "git reset --soft HEAD~1"
|
|
26
|
+
|
|
27
|
+
# Git amend
|
|
28
|
+
if ("изменить" in p or "переписать" in p or "дополнить" in p or "amend" in p or "change" in p or "update" in p) and ("коммит" in p or "commit" in p):
|
|
29
|
+
return "git commit --amend"
|
|
30
|
+
|
|
31
|
+
# Git stash restore / pop
|
|
32
|
+
if ("вернуть" in p or "достать" in p or "применить" in p or "pop" in p or "restore" in p or "apply" in p) and (
|
|
33
|
+
"изменения" in p or "код" in p or "stash" in p or "стэш" in p or "changes" in p
|
|
34
|
+
):
|
|
35
|
+
return "git stash pop"
|
|
36
|
+
|
|
37
|
+
# Git stash save / list
|
|
38
|
+
if "stash" in p or "спрятать" in p or ("сохранить" in p and "изменения" in p):
|
|
39
|
+
if "список" in p or "list" in p:
|
|
40
|
+
return "git stash list"
|
|
41
|
+
return "git stash"
|
|
42
|
+
|
|
43
|
+
# Git discard changes
|
|
44
|
+
if ("сбросить" in p or "отменить" in p or "discard" in p or "revert" in p) and ("изменения" in p or "changes" in p or "файлы" in p or "files" in p):
|
|
45
|
+
return "git restore ."
|
|
46
|
+
|
|
47
|
+
# Git branch
|
|
48
|
+
if "ветк" in p or "branch" in p:
|
|
49
|
+
words = prompt.split()
|
|
50
|
+
if "создать" in p or "новая" in p or "new" in p or "create" in p:
|
|
51
|
+
name = words[-1] if words and words[-1].isascii() and words[-1].replace("-", "").isalnum() else "feature"
|
|
52
|
+
return f"git checkout -b {name}"
|
|
53
|
+
if "удалить" in p or "delete" in p or "remove" in p:
|
|
54
|
+
name = words[-1] if words and words[-1].isascii() and words[-1].replace("-", "").isalnum() else "<branch>"
|
|
55
|
+
return f"git branch -d {name}"
|
|
56
|
+
if "все" in p or "список" in p or "list" in p or "all" in p:
|
|
57
|
+
return "git branch -a"
|
|
58
|
+
|
|
59
|
+
# Git push / pull
|
|
60
|
+
if ("запушить" in p or "отправить" in p or "push" in p) and ("коммит" in p or "ветк" in p or "main" in p or "origin" in p or "code" in p or "код" in p):
|
|
61
|
+
return "git push origin main"
|
|
62
|
+
if ("скачать" in p or "подтянуть" in p or "стянуть" in p or "pull" in p) and ("изменен" in p or "ветк" in p or "main" in p or "changes" in p):
|
|
63
|
+
return "git pull origin main"
|
|
64
|
+
|
|
65
|
+
# Git logs / commits history
|
|
66
|
+
if ("логи" in p or "история" in p or "коммиты" in p or "log" in p or "history" in p) and ("коммит" in p or "commit" in p or "репо" in p or "git" in p):
|
|
67
|
+
return "git log --oneline -n 10"
|
|
68
|
+
|
|
69
|
+
# Git status
|
|
70
|
+
if p in ("статус", "status", "git status", "что изменилось", "what changed"):
|
|
71
|
+
return "git status"
|
|
72
|
+
|
|
73
|
+
# Kill process by port
|
|
74
|
+
if ("убить" in p or "прибить" in p or "закрыть" in p or "kill" in p or "stop" in p or "free" in p) and ("порт" in p or "port" in p):
|
|
75
|
+
m = re.search(r"\b(\d{2,5})\b", p)
|
|
76
|
+
port = m.group(1) if m else "8080"
|
|
77
|
+
if shell == "powershell":
|
|
78
|
+
return f"Stop-Process -Id (Get-NetTCPConnection -LocalPort {port}).OwningProcess -Force"
|
|
79
|
+
return f"kill -9 $(lsof -t -i:{port})"
|
|
80
|
+
|
|
81
|
+
# Top memory processes
|
|
82
|
+
if ("процесс" in p or "process" in p) and ("памят" in p or "memory" in p or "ram" in p or "working" in p):
|
|
83
|
+
if shell == "powershell":
|
|
84
|
+
return "Get-Process | Sort-Object -Property WorkingSet -Descending | Select-Object -First 5"
|
|
85
|
+
return "ps aux --sort=-%mem | head -n 6"
|
|
86
|
+
|
|
87
|
+
# Folder size
|
|
88
|
+
if ("размер" in p or "size" in p) and ("папк" in p or "директор" in p or "диск" in p or "folder" in p or "directory" in p or "dir" in p):
|
|
89
|
+
if shell == "powershell":
|
|
90
|
+
return "(Get-ChildItem -Recurse -ErrorAction SilentlyContinue | Measure-Object -Property Length -Sum).Sum / 1MB"
|
|
91
|
+
return "du -sh ."
|
|
92
|
+
|
|
93
|
+
# Find file
|
|
94
|
+
if ("найти" in p or "поиск" in p or "find" in p or "search" in p or "locate" in p) and ("файл" in p or "file" in p):
|
|
95
|
+
words = prompt.split()
|
|
96
|
+
target = words[-1] if words else "*.py"
|
|
97
|
+
if shell == "powershell":
|
|
98
|
+
return f'Get-ChildItem -Recurse -Filter "*{target}*"'
|
|
99
|
+
return f'find . -name "*{target}*"'
|
|
100
|
+
|
|
101
|
+
# Python venv
|
|
102
|
+
if "venv" in p or "окружение" in p or "виртуальн" in p or "virtualenv" in p:
|
|
103
|
+
if "создать" in p or "create" in p or "new" in p:
|
|
104
|
+
return "python -m venv .venv"
|
|
105
|
+
if "активир" in p or "activate" in p:
|
|
106
|
+
return r".\.venv\Scripts\Activate.ps1" if shell == "powershell" else "source .venv/bin/activate"
|
|
107
|
+
|
|
108
|
+
# Pip purge / requirements
|
|
109
|
+
if "pip" in p:
|
|
110
|
+
if "очистить" in p or "кэш" in p or "cache" in p or "purge" in p or "clean" in p:
|
|
111
|
+
return "pip cache purge"
|
|
112
|
+
if "заморозить" in p or "freeze" in p or "requirements" in p:
|
|
113
|
+
return "pip freeze > requirements.txt"
|
|
114
|
+
if "обновить" in p or "upgrade" in p or "update" in p:
|
|
115
|
+
return "python -m pip install --upgrade pip"
|
|
116
|
+
|
|
117
|
+
# Pytest
|
|
118
|
+
if "тест" in p or "test" in p or "pytest" in p:
|
|
119
|
+
return "pytest -q"
|
|
120
|
+
|
|
121
|
+
# Docker
|
|
122
|
+
if "docker" in p or "докер" in p:
|
|
123
|
+
if "остановить" in p or "stop" in p:
|
|
124
|
+
return "docker stop $(docker ps -q)"
|
|
125
|
+
if "удалить все" in p or "prune" in p or "clean" in p:
|
|
126
|
+
return "docker system prune -a --volumes"
|
|
127
|
+
if "логи" in p or "logs" in p:
|
|
128
|
+
return "docker compose logs -f"
|
|
129
|
+
|
|
130
|
+
# Clear screen
|
|
131
|
+
if ("очистить" in p and ("экран" in p or "консоль" in p or "терминал" in p)) or p in ("clear", "cls", "clear screen", "clear console"):
|
|
132
|
+
return "Clear-Host"
|
|
133
|
+
|
|
134
|
+
return None
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def forge_command(prompt: str, shell: str = "powershell", settings: Settings | None = None) -> tuple[str, str]:
|
|
138
|
+
"""Convert natural language prompt to a shell command.
|
|
139
|
+
|
|
140
|
+
Returns (command, explanation).
|
|
141
|
+
"""
|
|
142
|
+
if not settings:
|
|
143
|
+
from ..settings import Settings
|
|
144
|
+
settings = Settings.load()
|
|
145
|
+
|
|
146
|
+
lang = settings.language if settings.language != "auto" else None
|
|
147
|
+
|
|
148
|
+
clean = prompt.strip()
|
|
149
|
+
if clean.startswith("??"):
|
|
150
|
+
clean = clean[2:].strip()
|
|
151
|
+
|
|
152
|
+
if not clean:
|
|
153
|
+
return "", ""
|
|
154
|
+
|
|
155
|
+
# 0. Check instant offline heuristic forge (<0.1ms)
|
|
156
|
+
offline = _forge_offline(clean, shell)
|
|
157
|
+
if offline:
|
|
158
|
+
return offline, t("instant_heuristic", lang=lang)
|
|
159
|
+
|
|
160
|
+
# 1. Try Groq (ultra fast free tier)
|
|
161
|
+
if settings.ai_provider == "groq" and settings.groq_api_key:
|
|
162
|
+
try:
|
|
163
|
+
return _call_groq(clean, shell, settings)
|
|
164
|
+
except Exception as e:
|
|
165
|
+
return "", f"Groq error: {e}"
|
|
166
|
+
|
|
167
|
+
# 2. Try OpenAI-compatible API (OpenAI, DeepSeek, OpenRouter, Gemini, proxy)
|
|
168
|
+
if (settings.ai_provider in ("openai", "custom") or settings.openai_api_key) and settings.openai_api_key:
|
|
169
|
+
try:
|
|
170
|
+
return _call_openai_compatible(clean, shell, settings)
|
|
171
|
+
except Exception as e:
|
|
172
|
+
return "", f"AI error: {e}"
|
|
173
|
+
|
|
174
|
+
# 3. Try Ollama (local)
|
|
175
|
+
if settings.ai_provider == "ollama":
|
|
176
|
+
try:
|
|
177
|
+
return _call_ollama(clean, shell, settings)
|
|
178
|
+
except Exception as e:
|
|
179
|
+
return "", f"Ollama error: {e}"
|
|
180
|
+
|
|
181
|
+
# 4. Fallback when no key is set
|
|
182
|
+
return "", t("ai_not_configured", lang=lang)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _call_openai_compatible(prompt: str, shell: str, settings: Settings) -> tuple[str, str]:
|
|
186
|
+
url = f"{settings.openai_base_url.rstrip('/')}/chat/completions"
|
|
187
|
+
model = settings.model if settings.model and "llama-3.1" not in settings.model else "gpt-4o-mini"
|
|
188
|
+
payload = {
|
|
189
|
+
"model": model,
|
|
190
|
+
"messages": [
|
|
191
|
+
{
|
|
192
|
+
"role": "system",
|
|
193
|
+
"content": (
|
|
194
|
+
f"You are a terminal command generator for {shell}. "
|
|
195
|
+
"Output ONLY the single executable command string. "
|
|
196
|
+
"No markdown code blocks, no backticks, no explanations, no prefix. "
|
|
197
|
+
"Just the exact shell command that accomplishes the task."
|
|
198
|
+
),
|
|
199
|
+
},
|
|
200
|
+
{"role": "user", "content": prompt},
|
|
201
|
+
],
|
|
202
|
+
"temperature": 0.1,
|
|
203
|
+
"max_tokens": 128,
|
|
204
|
+
}
|
|
205
|
+
req = urllib.request.Request(
|
|
206
|
+
url,
|
|
207
|
+
data=json.dumps(payload).encode("utf-8"),
|
|
208
|
+
headers={
|
|
209
|
+
"Authorization": f"Bearer {settings.openai_api_key}",
|
|
210
|
+
"Content-Type": "application/json",
|
|
211
|
+
"User-Agent": "anix-type",
|
|
212
|
+
},
|
|
213
|
+
method="POST",
|
|
214
|
+
)
|
|
215
|
+
with urllib.request.urlopen(req, timeout=5.0) as resp:
|
|
216
|
+
data = json.loads(resp.read().decode("utf-8"))
|
|
217
|
+
raw = data["choices"][0]["message"]["content"].strip()
|
|
218
|
+
clean_cmd = raw.replace("```bash", "").replace("```powershell", "").replace("```", "").strip()
|
|
219
|
+
clean_cmd = clean_cmd.splitlines()[0] if clean_cmd.splitlines() else clean_cmd
|
|
220
|
+
return clean_cmd, f"Generated via {settings.ai_provider or 'OpenAI-compatible'}"
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _call_groq(prompt: str, shell: str, settings: Settings) -> tuple[str, str]:
|
|
224
|
+
url = "https://api.groq.com/openai/v1/chat/completions"
|
|
225
|
+
lang = settings.language if settings.language != "auto" else None
|
|
226
|
+
payload = {
|
|
227
|
+
"model": settings.model or "llama-3.1-8b-instant",
|
|
228
|
+
"messages": [
|
|
229
|
+
{
|
|
230
|
+
"role": "system",
|
|
231
|
+
"content": (
|
|
232
|
+
f"You are a terminal command generator for {shell}. "
|
|
233
|
+
"The user request may be in English, Russian, or other languages. "
|
|
234
|
+
"Output ONLY the single executable command string. "
|
|
235
|
+
"No markdown code blocks, no backticks, no explanations, no prefix. "
|
|
236
|
+
"Just the exact shell command that accomplishes the task."
|
|
237
|
+
),
|
|
238
|
+
},
|
|
239
|
+
{"role": "user", "content": prompt},
|
|
240
|
+
],
|
|
241
|
+
"temperature": 0.1,
|
|
242
|
+
"max_tokens": 128,
|
|
243
|
+
}
|
|
244
|
+
req = urllib.request.Request(
|
|
245
|
+
url,
|
|
246
|
+
data=json.dumps(payload).encode("utf-8"),
|
|
247
|
+
headers={
|
|
248
|
+
"Authorization": f"Bearer {settings.groq_api_key}",
|
|
249
|
+
"Content-Type": "application/json",
|
|
250
|
+
"User-Agent": "anix-type",
|
|
251
|
+
},
|
|
252
|
+
method="POST",
|
|
253
|
+
)
|
|
254
|
+
with urllib.request.urlopen(req, timeout=3.5) as resp:
|
|
255
|
+
data = json.loads(resp.read().decode("utf-8"))
|
|
256
|
+
raw = data["choices"][0]["message"]["content"].strip()
|
|
257
|
+
# Clean potential markdown backticks if model ignored instructions
|
|
258
|
+
clean_cmd = raw.replace("```bash", "").replace("```powershell", "").replace("```", "").strip()
|
|
259
|
+
clean_cmd = clean_cmd.splitlines()[0] if clean_cmd.splitlines() else clean_cmd
|
|
260
|
+
return clean_cmd, t("generated_groq", lang=lang)
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def _call_ollama(prompt: str, shell: str, settings: Settings) -> tuple[str, str]:
|
|
264
|
+
url = f"{settings.ollama_url.rstrip('/')}/api/generate"
|
|
265
|
+
lang = settings.language if settings.language != "auto" else None
|
|
266
|
+
payload = {
|
|
267
|
+
"model": settings.model or "qwen2.5-coder:1.5b",
|
|
268
|
+
"prompt": (
|
|
269
|
+
f"You are a command-line expert for {shell}.\n"
|
|
270
|
+
f"Convert the following natural language request (which may be in English, Russian, or any other language) into a single executable {shell} command.\n"
|
|
271
|
+
"Output ONLY the command. Do not use markdown backticks, explanations, or notes.\n"
|
|
272
|
+
f"Request: {prompt}\n"
|
|
273
|
+
"Command:"
|
|
274
|
+
),
|
|
275
|
+
"stream": False,
|
|
276
|
+
}
|
|
277
|
+
req = urllib.request.Request(
|
|
278
|
+
url,
|
|
279
|
+
data=json.dumps(payload).encode("utf-8"),
|
|
280
|
+
headers={"Content-Type": "application/json"},
|
|
281
|
+
method="POST",
|
|
282
|
+
)
|
|
283
|
+
with urllib.request.urlopen(req, timeout=4.0) as resp:
|
|
284
|
+
data = json.loads(resp.read().decode("utf-8"))
|
|
285
|
+
raw = data.get("response", "").strip()
|
|
286
|
+
clean_cmd = raw.replace("```bash", "").replace("```powershell", "").replace("```", "").strip()
|
|
287
|
+
clean_cmd = clean_cmd.splitlines()[0] if clean_cmd.splitlines() else clean_cmd
|
|
288
|
+
return clean_cmd, t("generated_ollama", lang=lang)
|