Restore env and CLI model configuration
This commit is contained in:
1 parent
7c80500280
commit
fd8e0ddea5
5 files changed
+77
-384
No files matched your search
+51
-202
@@ -18,7 +18,7 @@ from rich.console import Group
|
||||
from rich.text import Text
|
||||
from rich.markdown import Markdown
|
||||
from textual.containers import Container, Horizontal, VerticalScroll
|
||||
from textual.widgets import Header, Footer, Static, Button, Input, Select, Label
|
||||
from textual.widgets import Header, Footer, Static, Button
|
||||
from textual.binding import Binding
|
||||
from textual.screen import ModalScreen
|
||||
|
||||
@@ -66,7 +66,7 @@ class SquareLoadingIndicator(Static):
|
||||
|
||||
class MessageBubble(Static):
|
||||
"""A chat message bubble that supports streaming updates."""
|
||||
|
||||
|
||||
def __init__(self, message: ChatMessage, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
self.message = message
|
||||
@@ -218,133 +218,12 @@ class ScreenshotOptions(ModalScreen[str | None]):
|
||||
self.dismiss(None if event.button.id == "cancel" else event.button.id)
|
||||
|
||||
|
||||
class ModelSettings(ModalScreen[tuple[AIConfig, AIConfig] | None]):
|
||||
"""Choose the two speakers and maintain saved OpenAI-compatible connections."""
|
||||
|
||||
BINDINGS = [Binding("escape", "dismiss(None)", "Close")]
|
||||
DEFAULT_CSS = """
|
||||
ModelSettings { align: center middle; }
|
||||
#model-settings { width: 76; max-width: 95%; height: auto; max-height: 95%;
|
||||
padding: 1 2; border: round $primary; background: $surface; overflow-y: auto; }
|
||||
#model-settings Input, #model-settings Select { margin-bottom: 1; }
|
||||
#model-actions Button { margin-right: 1; }
|
||||
"""
|
||||
|
||||
def __init__(self, path: Path, initial_ai1: AIConfig, initial_ai2: AIConfig):
|
||||
super().__init__()
|
||||
self.path = path
|
||||
self.initial = (initial_ai1, initial_ai2)
|
||||
from settings import load_settings
|
||||
self.settings = load_settings(path)
|
||||
|
||||
def compose(self) -> ComposeResult:
|
||||
with VerticalScroll(id="model-settings"):
|
||||
yield Static("[bold]Models and connections[/bold] • saved in sloppy.json")
|
||||
yield Button("Back (Esc)", id="back-models")
|
||||
yield Label("AI 1")
|
||||
yield Select([], id="ai1-select", allow_blank=True)
|
||||
yield Label("AI 2")
|
||||
yield Select([], id="ai2-select", allow_blank=True)
|
||||
yield Static("[bold]Add or edit a connection[/bold]")
|
||||
yield Input(placeholder="Connection ID (e.g. local-llama)", id="connection-id")
|
||||
yield Input(placeholder="Display name", id="model-name")
|
||||
yield Input(placeholder="Base URL, e.g. http://localhost:11434/v1", id="base-url")
|
||||
yield Input(placeholder="API key (or env:VARIABLE)", id="api-key", password=True)
|
||||
yield Input(placeholder="Model ID", id="model-id")
|
||||
yield Input(placeholder="System prompt", id="system-prompt")
|
||||
with Horizontal(id="model-actions"):
|
||||
yield Button("Save connection", id="save-model", variant="primary")
|
||||
yield Button("Delete connection", id="delete-model")
|
||||
yield Button("Use selected models", id="use-models", variant="success")
|
||||
|
||||
def on_mount(self) -> None:
|
||||
self.refresh_choices()
|
||||
|
||||
def refresh_choices(self) -> None:
|
||||
options = [(f"{key}: {value.get('name', key)} ({value.get('model', '')})", key)
|
||||
for key, value in self.settings['models'].items()]
|
||||
for slot, config in zip(('ai1', 'ai2'), self.initial):
|
||||
if config.base_url and config.api_key:
|
||||
options.append((f"{slot.upper()} from .env ({config.model})", f"env:{slot}"))
|
||||
for slot in ('ai1', 'ai2'):
|
||||
select = self.query_one(f"#{slot}-select", Select)
|
||||
select.set_options(options)
|
||||
chosen = self.settings['selected'].get(slot)
|
||||
if chosen in self.settings['models'] or (chosen == f"env:{slot}" and chosen in [value for _, value in options]):
|
||||
select.value = chosen
|
||||
elif f"env:{slot}" in [value for _, value in options]:
|
||||
select.value = f"env:{slot}"
|
||||
|
||||
def on_select_changed(self, event: Select.Changed) -> None:
|
||||
if event.select.id not in ('ai1-select', 'ai2-select'):
|
||||
return
|
||||
identifier = event.value
|
||||
if not isinstance(identifier, str) or identifier not in self.settings['models']:
|
||||
return
|
||||
from settings import model_from_settings
|
||||
values = model_from_settings(self.settings, identifier)
|
||||
for widget_id, value in (('connection-id', identifier), ('model-name', values['name']),
|
||||
('base-url', values['base_url']), ('api-key', values['api_key']),
|
||||
('model-id', values['model']), ('system-prompt', values['system_prompt'])):
|
||||
self.query_one(f"#{widget_id}", Input).value = value
|
||||
|
||||
def on_button_pressed(self, event: Button.Pressed) -> None:
|
||||
from settings import model_from_settings, save_settings, store_model
|
||||
action = event.button.id
|
||||
if action == 'back-models':
|
||||
self.dismiss(None)
|
||||
return
|
||||
identifier = self.query_one('#connection-id', Input).value.strip()
|
||||
try:
|
||||
if action == 'save-model':
|
||||
config = AIConfig(
|
||||
self.query_one('#model-name', Input).value.strip(),
|
||||
self.query_one('#base-url', Input).value.strip(),
|
||||
self.query_one('#api-key', Input).value.strip(),
|
||||
self.query_one('#model-id', Input).value.strip(),
|
||||
self.query_one('#system-prompt', Input).value or 'You are a helpful assistant.',
|
||||
)
|
||||
store_model(self.settings, identifier, config)
|
||||
save_settings(self.settings, self.path)
|
||||
self.refresh_choices()
|
||||
self.notify(f"Saved {identifier}")
|
||||
elif action == 'delete-model':
|
||||
if identifier not in self.settings['models']:
|
||||
raise ValueError('Select or enter an existing connection ID')
|
||||
del self.settings['models'][identifier]
|
||||
for slot in ('ai1', 'ai2'):
|
||||
if self.settings['selected'].get(slot) == identifier:
|
||||
self.settings['selected'][slot] = ''
|
||||
save_settings(self.settings, self.path)
|
||||
self.refresh_choices()
|
||||
self.notify(f"Deleted {identifier}")
|
||||
elif action == 'use-models':
|
||||
identifiers = [self.query_one(f'#{slot}-select', Select).value for slot in ('ai1', 'ai2')]
|
||||
valid = [set(self.settings['models']) | ({f'env:{slot}'} if config.base_url and config.api_key else set())
|
||||
for slot, config in zip(('ai1', 'ai2'), self.initial)]
|
||||
if any(value not in choices for value, choices in zip(identifiers, valid)):
|
||||
raise ValueError('Select a connection for each AI')
|
||||
self.settings['selected'] = dict(zip(('ai1', 'ai2'), identifiers))
|
||||
save_settings(self.settings, self.path)
|
||||
models = [self.initial[index] if value == f'env:ai{index + 1}'
|
||||
else AIConfig(**model_from_settings(self.settings, value))
|
||||
for index, value in enumerate(identifiers)]
|
||||
for model in models:
|
||||
if model.api_key.startswith('env:'):
|
||||
model.api_key = os.getenv(model.api_key[4:], '')
|
||||
if not model.api_key:
|
||||
raise ValueError(f'API key missing for {model.name}')
|
||||
self.dismiss((models[0], models[1]))
|
||||
except (OSError, ValueError) as error:
|
||||
self.notify(str(error), severity='error')
|
||||
|
||||
|
||||
class AIChatApp(App):
|
||||
CSS = """
|
||||
Screen {
|
||||
background: $surface;
|
||||
}
|
||||
|
||||
|
||||
#elapsed-time {
|
||||
height: 1;
|
||||
padding: 0 1;
|
||||
@@ -358,12 +237,12 @@ class AIChatApp(App):
|
||||
margin: 1;
|
||||
padding: 1;
|
||||
}
|
||||
|
||||
|
||||
.bubble-content {
|
||||
padding: 1;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
|
||||
.response-waiting {
|
||||
height: 3;
|
||||
align-vertical: middle;
|
||||
@@ -387,7 +266,7 @@ class AIChatApp(App):
|
||||
width: 100%;
|
||||
min-height: 3;
|
||||
}
|
||||
|
||||
|
||||
#conversation-stats {
|
||||
height: auto;
|
||||
padding: 0 1;
|
||||
@@ -412,8 +291,6 @@ class AIChatApp(App):
|
||||
|
||||
BINDINGS = [
|
||||
Binding("ctrl+c", "quit", "Quit"),
|
||||
Binding("ctrl+p", "command_palette", "Commands"),
|
||||
Binding("ctrl+m", "model_settings", "Models"),
|
||||
Binding("f1", "controls_help", "Help / Zoom"),
|
||||
Binding("s", "screenshot_options", "Screenshot", priority=True),
|
||||
Binding("f2", "screenshot_options", show=False, priority=True),
|
||||
@@ -431,16 +308,10 @@ class AIChatApp(App):
|
||||
ai2_config: AIConfig,
|
||||
initial_prompt: str,
|
||||
max_turns: int = 20,
|
||||
settings_path: Path | None = None,
|
||||
choose_models: bool = False,
|
||||
env_models: tuple[AIConfig, AIConfig] | None = None,
|
||||
):
|
||||
super().__init__()
|
||||
if max_turns < 1:
|
||||
raise ValueError("max_turns must be positive")
|
||||
self.settings_path = settings_path
|
||||
self.choose_models = choose_models
|
||||
self.env_models = env_models or (ai1_config, ai2_config)
|
||||
self.ai1 = ai1_config
|
||||
self.ai2 = ai2_config
|
||||
self.initial_prompt = initial_prompt
|
||||
@@ -483,31 +354,7 @@ class AIChatApp(App):
|
||||
self.elapsed_time = self.query_one("#elapsed-time", Static)
|
||||
self.chat_container.focus()
|
||||
self.chat_container.anchor()
|
||||
if self.choose_models and self.settings_path:
|
||||
self.action_model_settings()
|
||||
else:
|
||||
self.run_worker(self.start_conversation(), exclusive=True)
|
||||
|
||||
def action_model_settings(self) -> None:
|
||||
if self.settings_path and not isinstance(self.screen, ModelSettings):
|
||||
try:
|
||||
self.push_screen(ModelSettings(self.settings_path, *self.env_models), self._models_selected)
|
||||
except (OSError, ValueError, json.JSONDecodeError) as error:
|
||||
self.notify(f"Could not load settings: {error}", severity="error")
|
||||
|
||||
def _models_selected(self, models: tuple[AIConfig, AIConfig] | None) -> None:
|
||||
if models is None:
|
||||
if not self.messages:
|
||||
self.update_status("No conversation started. Press Ctrl+M to choose models.")
|
||||
return
|
||||
if self._is_running:
|
||||
self.notify("Saved selection applies to the next conversation")
|
||||
return
|
||||
self.ai1, self.ai2 = models
|
||||
if not self.messages:
|
||||
self.run_worker(self.start_conversation(), exclusive=True)
|
||||
else:
|
||||
self.notify("Saved selection applies to the next conversation")
|
||||
self.run_worker(self.start_conversation(), exclusive=True)
|
||||
|
||||
def action_screenshot_options(self) -> None:
|
||||
if not isinstance(self.screen, ScreenshotOptions):
|
||||
@@ -599,7 +446,7 @@ class AIChatApp(App):
|
||||
self._ended_at = None
|
||||
elapsed_timer = self.set_interval(1, self.update_elapsed_time)
|
||||
self.update_status(f"Starting conversation... AI 1 ({self.ai1.name}) begins")
|
||||
|
||||
|
||||
self.chat_container.messages = self.messages
|
||||
self.chat_container.add_message(ChatMessage("user", self.initial_prompt, "System"))
|
||||
try:
|
||||
@@ -812,21 +659,21 @@ class AIChatApp(App):
|
||||
async def call_ai(self, ai: AIConfig, history: list[dict]) -> str:
|
||||
"""Non-streaming fallback."""
|
||||
messages = [{"role": "system", "content": ai.system_prompt}] + history
|
||||
|
||||
|
||||
payload = {
|
||||
"model": ai.model,
|
||||
"messages": messages,
|
||||
"temperature": 0.7,
|
||||
"max_tokens": 2000,
|
||||
}
|
||||
|
||||
|
||||
headers = {
|
||||
"Authorization": f"Bearer {ai.api_key}",
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
|
||||
|
||||
url = f"{ai.base_url.rstrip('/')}/chat/completions"
|
||||
|
||||
|
||||
self.begin_response_metrics()
|
||||
try:
|
||||
return await self._call_ai_response(url, payload, headers)
|
||||
@@ -837,7 +684,7 @@ class AIChatApp(App):
|
||||
response = await self.client.post(url, json=payload, headers=headers)
|
||||
if response.status_code != 200:
|
||||
raise Exception(f"API Error {response.status_code}: {response.text}")
|
||||
|
||||
|
||||
data = response.json()
|
||||
self.record_usage(data.get("usage"))
|
||||
if "error" in data:
|
||||
@@ -851,7 +698,7 @@ class AIChatApp(App):
|
||||
async def stream_ai(self, ai: AIConfig, history: list[dict]):
|
||||
"""Stream response from AI using SSE."""
|
||||
messages = [{"role": "system", "content": ai.system_prompt}] + history
|
||||
|
||||
|
||||
payload = {
|
||||
"model": ai.model,
|
||||
"messages": messages,
|
||||
@@ -860,23 +707,23 @@ class AIChatApp(App):
|
||||
"stream": True,
|
||||
"stream_options": {"include_usage": True},
|
||||
}
|
||||
|
||||
|
||||
headers = {
|
||||
"Authorization": f"Bearer {ai.api_key}",
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "text/event-stream",
|
||||
}
|
||||
|
||||
|
||||
url = f"{ai.base_url.rstrip('/')}/chat/completions"
|
||||
|
||||
|
||||
log.debug(f"Streaming request to {url} with model {ai.model}")
|
||||
|
||||
|
||||
async with self.client.stream("POST", url, json=payload, headers=headers) as response:
|
||||
log.debug(f"Response status: {response.status_code}")
|
||||
if response.status_code != 200:
|
||||
error_body = await response.aread()
|
||||
raise Exception(f"API Error {response.status_code}: {error_body.decode(errors='replace')}")
|
||||
|
||||
|
||||
done = False
|
||||
async for line in response.aiter_lines():
|
||||
if not line.startswith("data:"):
|
||||
@@ -911,10 +758,10 @@ class AIChatApp(App):
|
||||
|
||||
def load_config() -> tuple[AIConfig, AIConfig, str, str]:
|
||||
load_dotenv()
|
||||
|
||||
|
||||
def get_env(key: str, default: str = "") -> str:
|
||||
return os.getenv(key, default)
|
||||
|
||||
|
||||
ai1 = AIConfig(
|
||||
name=get_env("AI1_NAME", "AI 1"),
|
||||
base_url=get_env("AI1_BASE_URL", ""),
|
||||
@@ -922,7 +769,7 @@ def load_config() -> tuple[AIConfig, AIConfig, str, str]:
|
||||
model=get_env("AI1_MODEL", "gpt-3.5-turbo"),
|
||||
system_prompt=get_env("AI1_SYSTEM_PROMPT", "You are a helpful assistant."),
|
||||
)
|
||||
|
||||
|
||||
ai2 = AIConfig(
|
||||
name=get_env("AI2_NAME", "AI 2"),
|
||||
base_url=get_env("AI2_BASE_URL", ""),
|
||||
@@ -930,61 +777,63 @@ def load_config() -> tuple[AIConfig, AIConfig, str, str]:
|
||||
model=get_env("AI2_MODEL", "gpt-3.5-turbo"),
|
||||
system_prompt=get_env("AI2_SYSTEM_PROMPT", "You are a helpful assistant."),
|
||||
)
|
||||
|
||||
|
||||
prompt = get_env("INITIAL_PROMPT", "")
|
||||
turns = get_env("MAX_TURNS", "20")
|
||||
|
||||
|
||||
return ai1, ai2, prompt, turns
|
||||
|
||||
|
||||
def main():
|
||||
import argparse
|
||||
|
||||
|
||||
# Load from .env first
|
||||
ai1_env, ai2_env, prompt_env, turns_env = load_config()
|
||||
|
||||
|
||||
parser = argparse.ArgumentParser(description="Two AI models conversation TUI with streaming")
|
||||
parser.add_argument("--ai1-name", default=ai1_env.name, help="Name for AI 1")
|
||||
parser.add_argument("--ai1-url", default=ai1_env.base_url, help="Base URL for AI 1 (OpenAI-compatible)")
|
||||
parser.add_argument("--ai1-key", default=ai1_env.api_key, help="API key for AI 1")
|
||||
parser.add_argument("--ai1-model", default=ai1_env.model, help="Model for AI 1")
|
||||
parser.add_argument("--ai1-prompt", default=ai1_env.system_prompt, help="System prompt for AI 1")
|
||||
|
||||
|
||||
parser.add_argument("--ai2-name", default=ai2_env.name, help="Name for AI 2")
|
||||
parser.add_argument("--ai2-url", default=ai2_env.base_url, help="Base URL for AI 2 (OpenAI-compatible)")
|
||||
parser.add_argument("--ai2-key", default=ai2_env.api_key, help="API key for AI 2")
|
||||
parser.add_argument("--ai2-model", default=ai2_env.model, help="Model for AI 2")
|
||||
parser.add_argument("--ai2-prompt", default=ai2_env.system_prompt, help="System prompt for AI 2")
|
||||
|
||||
|
||||
parser.add_argument("--prompt", default=prompt_env, help="Initial prompt for AI 1 to start")
|
||||
parser.add_argument("--turns", type=int, default=turns_env, help="Maximum conversation turns")
|
||||
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
|
||||
if not args.ai1_url or not args.ai1_key:
|
||||
parser.error("AI1_BASE_URL and AI1_API_KEY required (set in .env or via --ai1-url/--ai1-key)")
|
||||
if not args.ai2_url or not args.ai2_key:
|
||||
parser.error("AI2_BASE_URL and AI2_API_KEY required (set in .env or via --ai2-url/--ai2-key)")
|
||||
if args.turns < 1:
|
||||
parser.error("--turns / MAX_TURNS must be positive")
|
||||
if not args.prompt.strip():
|
||||
parser.error("INITIAL_PROMPT required (set in .env or via --prompt)")
|
||||
|
||||
ai1 = AIConfig(args.ai1_name, args.ai1_url, args.ai1_key, args.ai1_model, args.ai1_prompt)
|
||||
ai2 = AIConfig(args.ai2_name, args.ai2_url, args.ai2_key, args.ai2_model, args.ai2_prompt)
|
||||
from settings import DEFAULT_PATH, load_settings
|
||||
try:
|
||||
load_settings(DEFAULT_PATH)
|
||||
except (OSError, ValueError, json.JSONDecodeError) as error:
|
||||
parser.error(f"Could not load sloppy.json: {error}")
|
||||
import sys
|
||||
explicit_models = any(arg.startswith(("--ai1-", "--ai2-")) for arg in sys.argv[1:])
|
||||
if explicit_models:
|
||||
ai1 = AIConfig(args.ai1_name, args.ai1_url, args.ai1_key, args.ai1_model, args.ai1_prompt)
|
||||
ai2 = AIConfig(args.ai2_name, args.ai2_url, args.ai2_key, args.ai2_model, args.ai2_prompt)
|
||||
if not all((ai1.base_url, ai1.api_key, ai2.base_url, ai2.api_key)):
|
||||
parser.error("Both AI connections need a base URL and API key")
|
||||
env_ready = all((ai1.base_url, ai1.api_key, ai2.base_url, ai2.api_key))
|
||||
app = AIChatApp(ai1, ai2, args.prompt, args.turns,
|
||||
settings_path=DEFAULT_PATH,
|
||||
choose_models=not explicit_models and (DEFAULT_PATH.exists() or not env_ready),
|
||||
env_models=(ai1_env, ai2_env))
|
||||
ai1 = AIConfig(
|
||||
name=args.ai1_name,
|
||||
base_url=args.ai1_url,
|
||||
api_key=args.ai1_key,
|
||||
model=args.ai1_model,
|
||||
system_prompt=args.ai1_prompt,
|
||||
)
|
||||
|
||||
ai2 = AIConfig(
|
||||
name=args.ai2_name,
|
||||
base_url=args.ai2_url,
|
||||
api_key=args.ai2_key,
|
||||
model=args.ai2_model,
|
||||
system_prompt=args.ai2_prompt,
|
||||
)
|
||||
|
||||
app = AIChatApp(ai1, ai2, args.prompt, args.turns)
|
||||
app.run()
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user