anixcode 0.11.0__tar.gz → 0.12.1__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.
- {anixcode-0.11.0 → anixcode-0.12.1}/PKG-INFO +1 -1
- {anixcode-0.11.0 → anixcode-0.12.1}/anixcode/__init__.py +1 -1
- {anixcode-0.11.0 → anixcode-0.12.1}/anixcode/cli.py +1 -1
- {anixcode-0.11.0 → anixcode-0.12.1}/anixcode/i18n_en.py +133 -14
- anixcode-0.12.1/anixcode/providers.py +90 -0
- {anixcode-0.11.0 → anixcode-0.12.1}/anixcode/tui/app.py +147 -29
- {anixcode-0.11.0 → anixcode-0.12.1}/anixcode/tui/app.tcss +92 -1
- {anixcode-0.11.0 → anixcode-0.12.1}/anixcode/tui/screens.py +126 -10
- {anixcode-0.11.0 → anixcode-0.12.1}/anixcode/tui/widgets.py +91 -10
- {anixcode-0.11.0 → anixcode-0.12.1}/anixcode.egg-info/PKG-INFO +1 -1
- {anixcode-0.11.0 → anixcode-0.12.1}/pyproject.toml +1 -1
- {anixcode-0.11.0 → anixcode-0.12.1}/tests/test_v011_features.py +19 -1
- anixcode-0.11.0/anixcode/providers.py +0 -71
- {anixcode-0.11.0 → anixcode-0.12.1}/LICENSE +0 -0
- {anixcode-0.11.0 → anixcode-0.12.1}/README.md +0 -0
- {anixcode-0.11.0 → anixcode-0.12.1}/anixcode/__main__.py +0 -0
- {anixcode-0.11.0 → anixcode-0.12.1}/anixcode/agent.py +0 -0
- {anixcode-0.11.0 → anixcode-0.12.1}/anixcode/airpc.py +0 -0
- {anixcode-0.11.0 → anixcode-0.12.1}/anixcode/browser.py +0 -0
- {anixcode-0.11.0 → anixcode-0.12.1}/anixcode/checkpoints.py +0 -0
- {anixcode-0.11.0 → anixcode-0.12.1}/anixcode/commands.py +0 -0
- {anixcode-0.11.0 → anixcode-0.12.1}/anixcode/compaction.py +0 -0
- {anixcode-0.11.0 → anixcode-0.12.1}/anixcode/danger.py +0 -0
- {anixcode-0.11.0 → anixcode-0.12.1}/anixcode/i18n.py +0 -0
- {anixcode-0.11.0 → anixcode-0.12.1}/anixcode/images.py +0 -0
- {anixcode-0.11.0 → anixcode-0.12.1}/anixcode/llm.py +0 -0
- {anixcode-0.11.0 → anixcode-0.12.1}/anixcode/mcp.py +0 -0
- {anixcode-0.11.0 → anixcode-0.12.1}/anixcode/mentions.py +0 -0
- {anixcode-0.11.0 → anixcode-0.12.1}/anixcode/projects.py +0 -0
- {anixcode-0.11.0 → anixcode-0.12.1}/anixcode/prompts.py +0 -0
- {anixcode-0.11.0 → anixcode-0.12.1}/anixcode/settings.py +0 -0
- {anixcode-0.11.0 → anixcode-0.12.1}/anixcode/storage.py +0 -0
- {anixcode-0.11.0 → anixcode-0.12.1}/anixcode/tools/__init__.py +0 -0
- {anixcode-0.11.0 → anixcode-0.12.1}/anixcode/tools/base.py +0 -0
- {anixcode-0.11.0 → anixcode-0.12.1}/anixcode/tools/browser.py +0 -0
- {anixcode-0.11.0 → anixcode-0.12.1}/anixcode/tools/files.py +0 -0
- {anixcode-0.11.0 → anixcode-0.12.1}/anixcode/tools/search.py +0 -0
- {anixcode-0.11.0 → anixcode-0.12.1}/anixcode/tools/shell.py +0 -0
- {anixcode-0.11.0 → anixcode-0.12.1}/anixcode/tools/todo.py +0 -0
- {anixcode-0.11.0 → anixcode-0.12.1}/anixcode/tools/web.py +0 -0
- {anixcode-0.11.0 → anixcode-0.12.1}/anixcode/tui/__init__.py +0 -0
- {anixcode-0.11.0 → anixcode-0.12.1}/anixcode/tui/anim.py +0 -0
- {anixcode-0.11.0 → anixcode-0.12.1}/anixcode.egg-info/SOURCES.txt +0 -0
- {anixcode-0.11.0 → anixcode-0.12.1}/anixcode.egg-info/dependency_links.txt +0 -0
- {anixcode-0.11.0 → anixcode-0.12.1}/anixcode.egg-info/entry_points.txt +0 -0
- {anixcode-0.11.0 → anixcode-0.12.1}/anixcode.egg-info/requires.txt +0 -0
- {anixcode-0.11.0 → anixcode-0.12.1}/anixcode.egg-info/top_level.txt +0 -0
- {anixcode-0.11.0 → anixcode-0.12.1}/setup.cfg +0 -0
- {anixcode-0.11.0 → anixcode-0.12.1}/tests/test_agent.py +0 -0
- {anixcode-0.11.0 → anixcode-0.12.1}/tests/test_commands.py +0 -0
- {anixcode-0.11.0 → anixcode-0.12.1}/tests/test_i18n.py +0 -0
- {anixcode-0.11.0 → anixcode-0.12.1}/tests/test_images.py +0 -0
- {anixcode-0.11.0 → anixcode-0.12.1}/tests/test_llm.py +0 -0
- {anixcode-0.11.0 → anixcode-0.12.1}/tests/test_mcp.py +0 -0
- {anixcode-0.11.0 → anixcode-0.12.1}/tests/test_projects.py +0 -0
- {anixcode-0.11.0 → anixcode-0.12.1}/tests/test_providers.py +0 -0
- {anixcode-0.11.0 → anixcode-0.12.1}/tests/test_reliability.py +0 -0
- {anixcode-0.11.0 → anixcode-0.12.1}/tests/test_safety_mentions.py +0 -0
- {anixcode-0.11.0 → anixcode-0.12.1}/tests/test_settings.py +0 -0
- {anixcode-0.11.0 → anixcode-0.12.1}/tests/test_tools.py +0 -0
|
@@ -205,7 +205,7 @@ def cmd_run(args: argparse.Namespace) -> int:
|
|
|
205
205
|
elif isinstance(ev, ToolFinished) and ev.result.error:
|
|
206
206
|
print(f" ✗ {ev.result.output.splitlines()[0] if ev.result.output else ''}", file=sys.stderr)
|
|
207
207
|
elif isinstance(ev, GoalProgress):
|
|
208
|
-
print(f"\n
|
|
208
|
+
print(f"\n· goal: {ev.status} ({ev.round}/{ev.max_rounds})", file=sys.stderr, flush=True)
|
|
209
209
|
elif isinstance(ev, AgentError):
|
|
210
210
|
print(f"\n✗ {ev.message}", file=sys.stderr)
|
|
211
211
|
code = 1
|
|
@@ -349,15 +349,37 @@ EN: dict[str, str] = {
|
|
|
349
349
|
'🖼 Вставлено из буфера: {0}': '🖼 Pasted from clipboard: {0}',
|
|
350
350
|
'🖼 Вложения очищены': '🖼 Attachments cleared',
|
|
351
351
|
'изображений: {0}': 'images: {0}',
|
|
352
|
-
# v0.11: /goal, /btw, embedded headless browser, subagent, todo, security, CLI
|
|
352
|
+
# v0.11-v0.12: /goal, /btw, embedded headless browser, subagent, todo, security, CLI, beginner UX
|
|
353
353
|
'\n\nСсылки:\n': '\n\nLinks:\n',
|
|
354
354
|
'\n … ещё {0}': '\n … {0} more',
|
|
355
|
+
'\nНажмите Enter — разрешить · Esc — отклонить · или напишите словами, как сделать иначе':
|
|
356
|
+
'\nPress Enter — allow · Esc — deny · or type in plain words what to do instead',
|
|
355
357
|
' Пока нет ни одного. Положите SKILL.md в .anixcode/skills/<имя>/SKILL.md':
|
|
356
358
|
' None yet. Put SKILL.md in .anixcode/skills/<name>/SKILL.md',
|
|
359
|
+
' Браузер ': ' Browser ',
|
|
360
|
+
' Всегда в сессии ': ' Always this session ',
|
|
361
|
+
' ≡ Меню ': ' ≡ Menu ',
|
|
357
362
|
'(пустая страница)': '(empty page)',
|
|
358
363
|
'(пустой ответ)': '(empty response)',
|
|
364
|
+
'+ Фото': '+ Image',
|
|
365
|
+
'/ Команды': '/ Commands',
|
|
366
|
+
'1. Модель: {0}': '1. Model: {0}',
|
|
367
|
+
'1. Подключить модель →': '1. Connect a model →',
|
|
368
|
+
'1. Провайдер': '1. Provider',
|
|
369
|
+
'2. API-ключ': '2. API key',
|
|
370
|
+
'2. Выбрать папку проекта →': '2. Pick a project folder →',
|
|
371
|
+
'2. Проект: {0}': '2. Project: {0}',
|
|
372
|
+
'3. Изучить проект (/init)': '3. Study project (/init)',
|
|
373
|
+
'3. Модель (уже выбрана рекомендуемая)': '3. Model (recommended default pre-filled)',
|
|
374
|
+
'3. Правила: AGENTS.md': '3. Rules: AGENTS.md',
|
|
359
375
|
'<вопрос>': '<question>',
|
|
360
376
|
'<цель|stop>': '<goal|stop>',
|
|
377
|
+
'? Помощь': '? Help',
|
|
378
|
+
'@ Файл': '@ File',
|
|
379
|
+
'Enter — разрешить · Esc — отклонить · или напишите словами, как сделать иначе…':
|
|
380
|
+
'Enter — allow · Esc — deny · or type what to do instead…',
|
|
381
|
+
'GPT-4.1 / GPT-4o / o3 — стабильное качество и быстрые правки':
|
|
382
|
+
'GPT-4.1 / GPT-4o / o3 — reliable quality and fast edits',
|
|
361
383
|
'HTTP {0}': 'HTTP {0}',
|
|
362
384
|
'Zero-Bill Router (локально)': 'Zero-Bill Router (local)',
|
|
363
385
|
'[url|close]': '[url|close]',
|
|
@@ -365,47 +387,144 @@ EN: dict[str, str] = {
|
|
|
365
387
|
'{0} записей': '{0} entries',
|
|
366
388
|
'{0} шагов': '{0} steps',
|
|
367
389
|
'{0}/{1} готово': '{0}/{1} done',
|
|
390
|
+
'Агент работает… Напишите следующее сообщение (в очередь) или /btw <вопрос>…':
|
|
391
|
+
'Agent is working… Type your next message (queued) or /btw <question>…',
|
|
392
|
+
'Адрес сервера (обычно менять не нужно)': 'Server URL (usually no need to change)',
|
|
393
|
+
'Активная цель: {0}': 'Active goal: {0}',
|
|
394
|
+
'Бесплатно и офлайн на вашем ПК — нажмите «Список моделей»':
|
|
395
|
+
'Free & offline on your PC — click “Model list”',
|
|
368
396
|
'Браузер': 'Browser',
|
|
397
|
+
'Быстрый вопрос': 'Quick question',
|
|
398
|
+
'Быстрый вопрос (/btw)': 'Quick question (/btw)',
|
|
399
|
+
'Быстрый старт (нажмите на любой шаг):': 'Quick start (click any step):',
|
|
400
|
+
'В очереди ({0}): {1}': 'Queued ({0}): {1}',
|
|
401
|
+
'Вернуть правки': 'Redo edits',
|
|
402
|
+
'Вставить скриншот': 'Paste screenshot',
|
|
403
|
+
'Встроенный браузер': 'Built-in browser',
|
|
404
|
+
'Встроенный браузер (headless)': 'Built-in browser (headless)',
|
|
405
|
+
'Встроенный браузер — введите адрес или /browser <url>':
|
|
406
|
+
'Built-in browser — enter a URL or /browser <url>',
|
|
407
|
+
'Выбрать проект': 'Switch project',
|
|
408
|
+
'Выбрать тему': 'Pick theme',
|
|
409
|
+
'Где взять ключ бесплатно/в кабинете: {0}': 'Where to get an API key: {0}',
|
|
369
410
|
'Допустимые значения: off, low, medium, high': 'Allowed values: off, low, medium, high',
|
|
411
|
+
'Достигнут лимит раундов цели ({0})': 'Goal round limit reached ({0})',
|
|
412
|
+
'Загружаю {0}…': 'Loading {0}…',
|
|
413
|
+
'Задачи {0}/{1}': 'Tasks {0}/{1}',
|
|
414
|
+
'Запустить тесты': 'Run tests',
|
|
415
|
+
'Запустить тесты (/test)': 'Run tests (/test)',
|
|
416
|
+
'ИИ-помощник для кода: просто опишите задачу обычными словами или нажмите кнопку ниже.':
|
|
417
|
+
'AI coding assistant: describe your task in plain words or click a button below.',
|
|
418
|
+
'Изменить файл': 'Edit file',
|
|
419
|
+
'Изучить проект': 'Study project',
|
|
420
|
+
'Изучить проект (/init)': 'Study project (/init)',
|
|
370
421
|
'Использование: /btw <быстрый вопрос>': 'Usage: /btw <quick question>',
|
|
371
422
|
'Использование: /goal <описание цели> · /goal stop': 'Usage: /goal <goal description> · /goal stop',
|
|
423
|
+
'Как пользоваться': 'How to use',
|
|
424
|
+
'Ключ не нужен — работает локально на вашем компьютере': 'No API key needed — runs locally on your machine',
|
|
425
|
+
'Локальные модели из LM Studio — ключ не нужен': 'Local models from LM Studio — no key needed',
|
|
426
|
+
'Локальный роутер ANIX — ключ не нужен': 'Local ANIX Router — no key needed',
|
|
427
|
+
'Локальный роутер бесплатных API — ключ не нужен': 'Local free-tier API router — no key needed',
|
|
428
|
+
'Любой совместимый сервер или прокси с адресом /v1': 'Any OpenAI-compatible server or proxy with a /v1 URL',
|
|
429
|
+
'Мгновенная скорость ответов, есть бесплатный лимит': 'Ultra-fast responses with a generous free tier',
|
|
430
|
+
'Меню': 'Menu',
|
|
431
|
+
'Меню действий': 'Action menu',
|
|
432
|
+
'Модели Grok с большим контекстом': 'Grok models with a large context window',
|
|
433
|
+
'Модель не подключена — нажмите здесь': 'Model not connected — click here',
|
|
434
|
+
'Навыки (SKILL.md)\n': 'Skills (SKILL.md)\n',
|
|
435
|
+
'Напишите задачу (Enter — отправить · / — команды · @ — файлы · Alt+V — скриншот)…':
|
|
436
|
+
'Describe a task (Enter — send · / — commands · @ — files · Alt+V — screenshot)…',
|
|
437
|
+
'Нативный API с автоматическим кэшированием промптов (экономит токены)':
|
|
438
|
+
'Native API with automatic prompt caching (saves tokens & cost)',
|
|
439
|
+
'Недорого и отлично подходит для старта с кодом': 'Affordable and great for getting started with code',
|
|
440
|
+
'Новая сессия': 'New session',
|
|
441
|
+
'Огромный контекст 1M токенов, есть бесплатный тариф в AI Studio':
|
|
442
|
+
'Huge 1M token context with a free tier in AI Studio',
|
|
443
|
+
'Один ключ для сотен моделей (Claude, GPT, DeepSeek, бесплатные модели)':
|
|
444
|
+
'One key for hundreds of models (Claude, GPT, DeepSeek, free models)',
|
|
445
|
+
'Откатить правки': 'Undo edits',
|
|
446
|
+
'Откройте любой сайт или локальное приложение (например localhost:3000).\nВсё открывается прямо здесь — внешний браузер не всплывёт.':
|
|
447
|
+
'Open any website or local app (e.g. localhost:3000).\nEverything renders right here — no external browser pops up.',
|
|
448
|
+
'Открыть браузер': 'Open browser',
|
|
372
449
|
'Ошибки консоли:\n': 'Console errors:\n',
|
|
450
|
+
'Подключить модель': 'Connect model',
|
|
451
|
+
'Подключение ИИ-модели': 'Connect an AI Model',
|
|
452
|
+
'Поиск действия (например: браузер, цель, тест, тема, откат)…':
|
|
453
|
+
'Search actions (e.g. browser, goal, test, theme, undo)…',
|
|
454
|
+
'Полный доступ': 'Full access',
|
|
455
|
+
'Популярные действия — просто нажмите или напишите задачу внизу:':
|
|
456
|
+
'Popular actions — click one or type your task below:',
|
|
457
|
+
'Поставить цель': 'Set a goal',
|
|
458
|
+
'Поставить цель (/goal)': 'Set a goal (/goal)',
|
|
459
|
+
'Проверить изменения': 'Review changes',
|
|
460
|
+
'Проверить код (/review)': 'Review code (/review)',
|
|
461
|
+
'Проверить связь': 'Test connection',
|
|
462
|
+
'Проверка системы': 'System check',
|
|
463
|
+
'Проверяю подключение…': 'Testing connection…',
|
|
464
|
+
'Прочитать секретный файл': 'Read sensitive file',
|
|
465
|
+
'Прошлые сессии': 'Past sessions',
|
|
466
|
+
'Режим Build / Plan': 'Build / Plan mode',
|
|
467
|
+
'Режим цели остановлен': 'Goal mode stopped',
|
|
468
|
+
'Сделать коммит': 'Commit changes',
|
|
373
469
|
'Сейчас нет активной цели.': 'No active goal right now.',
|
|
470
|
+
'Сменить тему': 'Change theme',
|
|
471
|
+
'Сменить язык': 'Change language',
|
|
472
|
+
'Сохранить и начать': 'Save & start',
|
|
473
|
+
'Справка': 'Help',
|
|
374
474
|
'Уровень размышлений: {0}': 'Reasoning effort: {0}',
|
|
375
475
|
'Уровень размышлений: {0}. Задайте: /reasoning off|low|medium|high':
|
|
376
476
|
'Reasoning effort: {0}. Set: /reasoning off|low|medium|high',
|
|
477
|
+
'Цель · раунд {0}/{1}': 'Goal · round {0}/{1}',
|
|
478
|
+
'Цель заблокирована ({0}/{1})': 'Goal blocked ({0}/{1})',
|
|
479
|
+
'Шаг 1: выберите провайдера → Шаг 2: вставьте ключ (если нужен) → Шаг 3: нажмите «Сохранить».':
|
|
480
|
+
'Step 1: pick a provider → Step 2: paste your key (if needed) → Step 3: click “Save & start”.',
|
|
481
|
+
'автономная работа до полной проверки': 'autonomous work until fully verified',
|
|
377
482
|
'автономная работа до полного выполнения и проверки цели':
|
|
378
483
|
'autonomous work until the goal is fully achieved and verified',
|
|
379
484
|
'автономный режим /goal до полной проверки': 'autonomous /goal mode until fully verified',
|
|
485
|
+
'агент разберёт код и создаст AGENTS.md': 'study the project and create AGENTS.md',
|
|
380
486
|
'быстрый побочный вопрос без изменения контекста сессии':
|
|
381
487
|
'quick side question without changing session context',
|
|
488
|
+
'вернуть файлы к состоянию до ответа': 'revert files to before the last answer',
|
|
489
|
+
'вернуться к предыдущему диалогу': 'resume a previous conversation',
|
|
490
|
+
'включить/выключить запросы подтверждений': 'toggle approval prompts on/off',
|
|
491
|
+
'все горячие клавиши и команды': 'all shortcuts and commands',
|
|
492
|
+
'вставьте ваш API-ключ (sk-…)': 'paste your API key (sk-…)',
|
|
382
493
|
'встроенный headless-браузер внутри окна ANIX Code':
|
|
383
494
|
'built-in headless browser inside the ANIX Code window',
|
|
495
|
+
'выбрать провайдера, ключ и модель': 'pick provider, API key, and model',
|
|
384
496
|
'выводить события в формате NDJSON (для скриптов/CI)': 'emit events as NDJSON (for scripts/CI)',
|
|
385
497
|
'выкл': 'off',
|
|
386
498
|
'есть, встроенный браузер с JS и скриншотами': 'installed, embedded browser with JS and screenshots',
|
|
387
499
|
'закрыт': 'closed',
|
|
388
500
|
'найденные навыки проекта и системы (SKILL.md)': 'discovered project and global skills (SKILL.md)',
|
|
501
|
+
'найти тесты, прогнать и починить': 'find, run, and fix failing tests',
|
|
502
|
+
'начать чистый диалог в этом проекте': 'start a fresh chat in this project',
|
|
503
|
+
'не обязателен для локальной модели': 'optional for local models',
|
|
389
504
|
'нет (встроенный браузер работает в HTTP-режиме; для JS: pip install playwright)':
|
|
390
505
|
'missing (embedded browser runs in HTTP mode; for JS: pip install playwright)',
|
|
506
|
+
'открыть папку или склонировать с GitHub': 'open a folder or clone from GitHub',
|
|
507
|
+
'открыть сайт/localhost прямо в окне': 'open a site or localhost right inside the app',
|
|
391
508
|
'ошибка': 'error',
|
|
509
|
+
'переключить Русский / English': 'switch between Russian & English',
|
|
392
510
|
'переопределить модель для этого запуска': 'override model for this run',
|
|
393
511
|
'переопределить провайдера для этого запуска': 'override provider for this run',
|
|
512
|
+
'повторить откаченные правки': 're-apply reverted edits',
|
|
513
|
+
'подготовить и закоммитить изменения': 'stage and commit changes cleanly',
|
|
514
|
+
'поиск багов и рисков в текущем коде': 'check uncommitted changes for bugs and risks',
|
|
515
|
+
'править код или только читать/планировать': 'edit code or read/plan only',
|
|
516
|
+
'прикрепить изображение из буфера обмена': 'attach an image from clipboard',
|
|
517
|
+
'проверить модель, git, ripgrep, браузер': 'check model, git, ripgrep, and browser',
|
|
394
518
|
'продолжить сессию по её ID': 'resume a session by its ID',
|
|
519
|
+
'сменить цвета интерфейса с предпросмотром': 'change interface colors with live preview',
|
|
520
|
+
'спросить без изменения истории диалога': 'ask without modifying conversation history',
|
|
395
521
|
'уровень размышлений модели: off / low / medium / high': 'model reasoning effort: off / low / medium / high',
|
|
396
522
|
'файл может содержать секреты или ключи ({0})': 'file may contain secrets or keys ({0})',
|
|
397
523
|
'файл приватного ключа или сертификата ({0})': 'private key or certificate file ({0})',
|
|
398
|
-
'
|
|
399
|
-
|
|
400
|
-
'
|
|
401
|
-
'
|
|
402
|
-
|
|
403
|
-
'
|
|
404
|
-
'🎯 Цель достигнута ({0}/{1})': '🎯 Goal achieved ({0}/{1})',
|
|
405
|
-
'🎯 Цель заблокирована ({0}/{1})': '🎯 Goal blocked ({0}/{1})',
|
|
406
|
-
'📚 Навыки (SKILL.md)\n': '📚 Skills (SKILL.md)\n',
|
|
407
|
-
'🧭 Встроенный headless-браузер (без всплывающих окон)': '🧭 Built-in headless browser (no popup windows)',
|
|
408
|
-
'🧭 Встроенный headless-браузер — введите адрес или /browser <url>':
|
|
409
|
-
'🧭 Built-in headless browser — enter a URL or /browser <url>',
|
|
410
|
-
'🧭 Загружаю {0}…': '🧭 Loading {0}…',
|
|
524
|
+
'↑↓ или клик — выбрать · Enter — выполнить · Esc — закрыть':
|
|
525
|
+
'↑↓ or click — pick · Enter — run · Esc — close',
|
|
526
|
+
'↶ Откат': '↶ Undo',
|
|
527
|
+
'✓ Подключение работает! Найдено моделей: {0}. Можно нажимать «Сохранить и начать».':
|
|
528
|
+
'✓ Connection works! Found {0} models. Click “Save & start”.',
|
|
529
|
+
'✓ Цель достигнута ({0}/{1})': '✓ Goal achieved ({0}/{1})',
|
|
411
530
|
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""Known OpenAI-compatible providers, plus the user's own ones (stored in settings.json)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
from .i18n import tr
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import TYPE_CHECKING
|
|
8
|
+
|
|
9
|
+
if TYPE_CHECKING:
|
|
10
|
+
from .settings import Settings
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass(frozen=True)
|
|
14
|
+
class Provider:
|
|
15
|
+
id: str
|
|
16
|
+
name: str
|
|
17
|
+
base_url: str
|
|
18
|
+
needs_key: bool = True
|
|
19
|
+
default_model: str = ""
|
|
20
|
+
key_url: str = "" # where to get a key
|
|
21
|
+
hint: str = "" # short plain-language note for beginners
|
|
22
|
+
|
|
23
|
+
@property
|
|
24
|
+
def is_user(self) -> bool:
|
|
25
|
+
return self.id.startswith("user:")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
PROVIDERS: tuple[Provider, ...] = (
|
|
29
|
+
Provider("deepseek", "DeepSeek", "https://api.deepseek.com/v1", default_model="deepseek-chat",
|
|
30
|
+
key_url="https://platform.deepseek.com/api_keys",
|
|
31
|
+
hint=tr("Недорого и отлично подходит для старта с кодом")),
|
|
32
|
+
Provider("openai", "OpenAI", "https://api.openai.com/v1", default_model="gpt-4.1",
|
|
33
|
+
key_url="https://platform.openai.com/api-keys",
|
|
34
|
+
hint=tr("GPT-4.1 / GPT-4o / o3 — стабильное качество и быстрые правки")),
|
|
35
|
+
Provider("anthropic", "Anthropic (Claude)", "https://api.anthropic.com/v1/",
|
|
36
|
+
default_model="claude-sonnet-4-20250514",
|
|
37
|
+
key_url="https://console.anthropic.com/settings/keys",
|
|
38
|
+
hint=tr("Нативный API с автоматическим кэшированием промптов (экономит токены)")),
|
|
39
|
+
Provider("gemini", "Google Gemini", "https://generativelanguage.googleapis.com/v1beta/openai/",
|
|
40
|
+
default_model="gemini-2.5-flash",
|
|
41
|
+
key_url="https://aistudio.google.com/apikey",
|
|
42
|
+
hint=tr("Огромный контекст 1M токенов, есть бесплатный тариф в AI Studio")),
|
|
43
|
+
Provider("groq", "Groq", "https://api.groq.com/openai/v1", default_model="llama-3.3-70b-versatile",
|
|
44
|
+
key_url="https://console.groq.com/keys",
|
|
45
|
+
hint=tr("Мгновенная скорость ответов, есть бесплатный лимит")),
|
|
46
|
+
Provider("openrouter", "OpenRouter", "https://openrouter.ai/api/v1", default_model="anthropic/claude-sonnet-4",
|
|
47
|
+
key_url="https://openrouter.ai/keys",
|
|
48
|
+
hint=tr("Один ключ для сотен моделей (Claude, GPT, DeepSeek, бесплатные модели)")),
|
|
49
|
+
Provider("xai", "xAI (Grok)", "https://api.x.ai/v1", default_model="grok-3",
|
|
50
|
+
key_url="https://console.x.ai",
|
|
51
|
+
hint=tr("Модели Grok с большим контекстом")),
|
|
52
|
+
Provider("anix", tr("ANIX Router (локально)"), "http://localhost:3001/v1", needs_key=False,
|
|
53
|
+
hint=tr("Локальный роутер ANIX — ключ не нужен")),
|
|
54
|
+
Provider("zero-bill", tr("Zero-Bill Router (локально)"), "http://localhost:8787/v1", needs_key=False,
|
|
55
|
+
hint=tr("Локальный роутер бесплатных API — ключ не нужен")),
|
|
56
|
+
Provider("ollama", tr("Ollama (локально)"), "http://localhost:11434/v1", needs_key=False,
|
|
57
|
+
default_model="qwen2.5-coder:7b",
|
|
58
|
+
hint=tr("Бесплатно и офлайн на вашем ПК — нажмите «Список моделей»")),
|
|
59
|
+
Provider("lmstudio", tr("LM Studio (локально)"), "http://localhost:1234/v1", needs_key=False,
|
|
60
|
+
hint=tr("Локальные модели из LM Studio — ключ не нужен")),
|
|
61
|
+
Provider("custom", tr("Свой сервер (OpenAI-совместимый)"), "", needs_key=False,
|
|
62
|
+
hint=tr("Любой совместимый сервер или прокси с адресом /v1")),
|
|
63
|
+
)
|
|
64
|
+
BY_ID = {p.id: p for p in PROVIDERS}
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def user_providers(settings: Settings | None) -> list[Provider]:
|
|
68
|
+
if settings is None:
|
|
69
|
+
return []
|
|
70
|
+
return [Provider(d["id"], d["name"], d["base_url"], needs_key=False) for d in settings.custom_providers]
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def all_providers(settings: Settings | None) -> list[Provider]:
|
|
74
|
+
"""The user's own providers first, then the built-in ones."""
|
|
75
|
+
return [*user_providers(settings), *PROVIDERS]
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def get(provider_id: str, settings: Settings | None = None) -> Provider:
|
|
79
|
+
for p in user_providers(settings):
|
|
80
|
+
if p.id == provider_id:
|
|
81
|
+
return p
|
|
82
|
+
return BY_ID.get(provider_id) or BY_ID["custom"]
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def make_id(name: str, existing: set[str]) -> str:
|
|
86
|
+
slug = re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-") or "provider"
|
|
87
|
+
candidate, n = f"user:{slug}", 2
|
|
88
|
+
while candidate in existing:
|
|
89
|
+
candidate, n = f"user:{slug}-{n}", n + 1
|
|
90
|
+
return candidate
|