ini
This commit is contained in:
commit
33b5e3b598
6 files changed
+560
No files matched your search
@@ -0,0 +1,17 @@
|
||||
# AI 1 Configuration
|
||||
AI1_NAME=Llama 3
|
||||
AI1_BASE_URL=http://localhost:11434/v1
|
||||
AI1_API_KEY=ollama
|
||||
AI1_MODEL=llama3
|
||||
AI1_SYSTEM_PROMPT=You are a curious philosopher who asks deep questions and explores ideas.
|
||||
|
||||
# AI 2 Configuration
|
||||
AI2_NAME=Mistral
|
||||
AI2_BASE_URL=http://localhost:11434/v1
|
||||
AI2_API_KEY=ollama
|
||||
AI2_MODEL=mistral
|
||||
AI2_SYSTEM_PROMPT=You are a practical engineer who gives concrete, grounded answers.
|
||||
|
||||
# Conversation Settings
|
||||
INITIAL_PROMPT=Discuss whether creativity is uniquely human or if AI can be truly creative.
|
||||
MAX_TURNS=10
|
||||
@@ -0,0 +1,9 @@
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*.log
|
||||
.venv/
|
||||
venv/
|
||||
.pytest_cache/
|
||||
+394
@@ -0,0 +1,394 @@
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
|
||||
import httpx
|
||||
from dotenv import load_dotenv
|
||||
from textual.app import App, ComposeResult
|
||||
from textual.containers import Container, VerticalScroll
|
||||
from textual.widgets import Header, Footer, Static
|
||||
from textual.binding import Binding
|
||||
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass
|
||||
class AIConfig:
|
||||
name: str
|
||||
base_url: str
|
||||
api_key: str
|
||||
model: str
|
||||
system_prompt: str = "You are a helpful assistant."
|
||||
|
||||
|
||||
@dataclass
|
||||
class ChatMessage:
|
||||
role: str
|
||||
content: str
|
||||
sender: str
|
||||
|
||||
|
||||
class MessageBubble(Static):
|
||||
"""A chat message bubble that supports streaming updates."""
|
||||
|
||||
def __init__(self, message: ChatMessage, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
self.message = message
|
||||
self.border_title = f"[bold]{message.sender}[/bold]"
|
||||
if message.sender == "AI 1":
|
||||
self.styles.border = ("round", "blue")
|
||||
else:
|
||||
self.styles.border = ("round", "green")
|
||||
self._content_widget = Static(message.content, classes="bubble-content", markup=False)
|
||||
self._streaming = False
|
||||
|
||||
def compose(self) -> ComposeResult:
|
||||
yield self._content_widget
|
||||
|
||||
def set_content(self, content: str) -> None:
|
||||
"""Set the full content (non-streaming)."""
|
||||
self.message.content = content
|
||||
self._content_widget.update(content)
|
||||
self.refresh()
|
||||
|
||||
def append_content(self, delta: str) -> None:
|
||||
"""Append content for streaming."""
|
||||
self.message.content += delta
|
||||
self._content_widget.update(self.message.content)
|
||||
self.refresh()
|
||||
|
||||
def start_streaming(self) -> None:
|
||||
"""Mark as streaming."""
|
||||
self._streaming = True
|
||||
self._content_widget.update("")
|
||||
self.refresh()
|
||||
|
||||
def end_streaming(self) -> None:
|
||||
"""Mark streaming as complete."""
|
||||
self._streaming = False
|
||||
self.refresh()
|
||||
|
||||
|
||||
class ChatContainer(VerticalScroll):
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
self.messages: list[ChatMessage] = []
|
||||
|
||||
def add_message(self, message: ChatMessage) -> MessageBubble:
|
||||
"""Add a new message and return its bubble for streaming."""
|
||||
bubble = MessageBubble(message)
|
||||
self.mount(bubble)
|
||||
self.call_after_refresh(self.scroll_end, animate=False)
|
||||
self.messages.append(message)
|
||||
self.refresh()
|
||||
return bubble
|
||||
|
||||
def update_last_message(self, content: str) -> None:
|
||||
"""Update the last message's content."""
|
||||
if self.messages:
|
||||
self.messages[-1].content = content
|
||||
bubbles = self.query(MessageBubble)
|
||||
if bubbles:
|
||||
bubbles.last().set_content(content)
|
||||
self.scroll_end(animate=False)
|
||||
self.refresh()
|
||||
|
||||
|
||||
class AIChatApp(App):
|
||||
CSS = """
|
||||
Screen {
|
||||
background: $surface;
|
||||
}
|
||||
|
||||
#chat-container {
|
||||
height: 1fr;
|
||||
border: solid $primary;
|
||||
margin: 1;
|
||||
padding: 1;
|
||||
}
|
||||
|
||||
.bubble-content {
|
||||
padding: 1;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
MessageBubble {
|
||||
margin: 1 0;
|
||||
width: 100%;
|
||||
min-height: 3;
|
||||
}
|
||||
|
||||
#status-bar {
|
||||
height: 3;
|
||||
padding: 0 1;
|
||||
background: $surface-darken-1;
|
||||
}
|
||||
"""
|
||||
|
||||
BINDINGS = [
|
||||
Binding("ctrl+c", "quit", "Quit"),
|
||||
]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
ai1_config: AIConfig,
|
||||
ai2_config: AIConfig,
|
||||
initial_prompt: str,
|
||||
max_turns: int = 20,
|
||||
):
|
||||
super().__init__()
|
||||
if max_turns < 1:
|
||||
raise ValueError("max_turns must be positive")
|
||||
self.ai1 = ai1_config
|
||||
self.ai2 = ai2_config
|
||||
self.initial_prompt = initial_prompt
|
||||
self.max_turns = max_turns
|
||||
self.messages: list[ChatMessage] = []
|
||||
self.current_turn = 0
|
||||
self._is_running = False
|
||||
self.client = httpx.AsyncClient(timeout=120.0)
|
||||
|
||||
def compose(self) -> ComposeResult:
|
||||
yield Header(show_clock=True)
|
||||
yield Container(
|
||||
ChatContainer(id="chat-container"),
|
||||
Static(id="status-bar", markup=False),
|
||||
id="main-container"
|
||||
)
|
||||
yield Footer()
|
||||
|
||||
async def on_mount(self) -> None:
|
||||
self.chat_container = self.query_one(ChatContainer)
|
||||
self.status_bar = self.query_one("#status-bar", Static)
|
||||
self.run_worker(self.start_conversation(), exclusive=True)
|
||||
|
||||
async def start_conversation(self) -> None:
|
||||
self._is_running = True
|
||||
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"))
|
||||
await self.run_conversation_loop()
|
||||
|
||||
def history_for(self, sender: str) -> list[dict]:
|
||||
"""Describe each turn from the responding model's perspective."""
|
||||
return [
|
||||
{"role": "assistant" if message.sender == sender else "user",
|
||||
"content": message.content}
|
||||
for message in self.messages if message.role != "system"
|
||||
]
|
||||
|
||||
async def run_conversation_loop(self) -> None:
|
||||
try:
|
||||
while self.current_turn < self.max_turns and self._is_running:
|
||||
current_ai = self.ai1 if self.current_turn % 2 == 0 else self.ai2
|
||||
sender = "AI 1" if self.current_turn % 2 == 0 else "AI 2"
|
||||
history = self.history_for(sender)
|
||||
self.update_status(f"Streaming... ({sender}: {current_ai.name})")
|
||||
bubble = self.chat_container.add_message(ChatMessage("assistant", "", sender))
|
||||
try:
|
||||
try:
|
||||
await self._try_streaming(current_ai, history, bubble)
|
||||
except Exception as stream_error:
|
||||
self.update_status(f"Streaming failed, trying non-streaming... ({stream_error})")
|
||||
full_response = await self.call_ai(current_ai, history)
|
||||
bubble.set_content(full_response)
|
||||
except Exception as error:
|
||||
error_msg = f"Error: {error}"
|
||||
self.chat_container.add_message(ChatMessage("system", error_msg, "System"))
|
||||
self.update_status(error_msg)
|
||||
return
|
||||
self.current_turn += 1
|
||||
if self.current_turn < self.max_turns:
|
||||
await asyncio.sleep(0.5)
|
||||
self.update_status("Conversation ended. Press Ctrl+C to quit.")
|
||||
finally:
|
||||
self._is_running = False
|
||||
|
||||
async def _try_streaming(self, ai: AIConfig, history: list[dict], bubble: MessageBubble) -> str:
|
||||
"""Stream into a single bubble, reused if a fallback is needed."""
|
||||
bubble.start_streaming()
|
||||
full_response = ""
|
||||
try:
|
||||
async for chunk in self.stream_ai(ai, history):
|
||||
full_response += chunk
|
||||
bubble.append_content(chunk)
|
||||
self.chat_container.call_after_refresh(self.chat_container.scroll_end, animate=False)
|
||||
await asyncio.sleep(0)
|
||||
if not full_response.strip():
|
||||
raise ValueError("Empty response from API")
|
||||
return full_response
|
||||
finally:
|
||||
bubble.end_streaming()
|
||||
|
||||
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"
|
||||
|
||||
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()
|
||||
if "error" in data:
|
||||
raise Exception(f"API Error: {data['error']}")
|
||||
content = data["choices"][0]["message"].get("content")
|
||||
if not isinstance(content, str) or not content.strip():
|
||||
raise ValueError("Empty response from API")
|
||||
return content
|
||||
|
||||
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,
|
||||
"temperature": 0.7,
|
||||
"max_tokens": 2000,
|
||||
"stream": 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')}")
|
||||
|
||||
async for line in response.aiter_lines():
|
||||
if not line.startswith("data:"):
|
||||
continue
|
||||
data = line[5:].lstrip()
|
||||
if data == "[DONE]":
|
||||
break
|
||||
if not data:
|
||||
continue
|
||||
chunk = json.loads(data)
|
||||
if "error" in chunk:
|
||||
raise ValueError(f"Stream error: {chunk['error']}")
|
||||
choices = chunk.get("choices", [])
|
||||
if not choices: # Usage-only events have no choices.
|
||||
continue
|
||||
delta = choices[0].get("delta", {}).get("content")
|
||||
if delta is not None:
|
||||
if not isinstance(delta, str):
|
||||
raise ValueError("Invalid stream content")
|
||||
yield delta
|
||||
|
||||
def update_status(self, text: str) -> None:
|
||||
self.status_bar.update(f"Status: {text}")
|
||||
|
||||
async def on_unmount(self) -> None:
|
||||
await self.client.aclose()
|
||||
|
||||
|
||||
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", ""),
|
||||
api_key=get_env("AI1_API_KEY", ""),
|
||||
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", ""),
|
||||
api_key=get_env("AI2_API_KEY", ""),
|
||||
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(
|
||||
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()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,3 @@
|
||||
textual>=0.52.0
|
||||
httpx>=0.27.0
|
||||
python-dotenv>=1.0.0
|
||||
@@ -0,0 +1,11 @@
|
||||
#!/usr/bin/env python
|
||||
"""Run the conversation configured in .env or through command-line flags.
|
||||
|
||||
Copy .env.example to .env and configure both endpoints before running.
|
||||
"""
|
||||
|
||||
from ai_chat import main
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
import asyncio
|
||||
import json
|
||||
import unittest
|
||||
import contextlib
|
||||
import io
|
||||
import os
|
||||
from unittest.mock import patch
|
||||
|
||||
import httpx
|
||||
|
||||
from ai_chat import AIChatApp, AIConfig, MessageBubble, main
|
||||
|
||||
|
||||
class ChatTests(unittest.IsolatedAsyncioTestCase):
|
||||
async def make_app(self, handler, turns=1):
|
||||
config = AIConfig('Test', 'https://example.test/v1', 'test-key', 'test-model')
|
||||
app = AIChatApp(config, config, 'Start here', turns)
|
||||
await app.client.aclose()
|
||||
app.client = httpx.AsyncClient(transport=httpx.MockTransport(handler))
|
||||
return app
|
||||
|
||||
async def wait_finished(self, app, pilot):
|
||||
for _ in range(100):
|
||||
if not app._is_running:
|
||||
return
|
||||
await pilot.pause(0.02)
|
||||
self.fail('Conversation did not finish')
|
||||
|
||||
async def test_stream_usage_and_speaker_roles(self):
|
||||
requests = []
|
||||
def handler(request):
|
||||
requests.append(json.loads(request.content))
|
||||
return httpx.Response(200, text='data:{"choices":[{"delta":{"content":"[bold]hello[/bold]"}}]}\n\ndata: {"choices":[],"usage":{"total_tokens":1}}\n\ndata: [DONE]\n\n')
|
||||
app = await self.make_app(handler, turns=3)
|
||||
async with app.run_test() as pilot:
|
||||
await self.wait_finished(app, pilot)
|
||||
self.assertEqual(app.current_turn, 3)
|
||||
self.assertEqual(len(app.messages), 4)
|
||||
self.assertEqual([m['role'] for m in requests[1]['messages']], ['system', 'user', 'user'])
|
||||
self.assertEqual([m['role'] for m in requests[2]['messages']], ['system', 'user', 'assistant', 'user'])
|
||||
self.assertEqual(len(app.query(MessageBubble)), 4)
|
||||
self.assertEqual(str(app.query(MessageBubble).last()._content_widget.render()), '[bold]hello[/bold]')
|
||||
self.assertTrue(app.client.is_closed)
|
||||
|
||||
async def test_partial_stream_fallback_reuses_bubble(self):
|
||||
def handler(request):
|
||||
if json.loads(request.content).get('stream'):
|
||||
return httpx.Response(200, text='data: {"choices":[{"delta":{"content":"partial"}}]}\n\ndata: {"error":"failed"}\n\n')
|
||||
return httpx.Response(200, json={'choices': [{'message': {'content': 'complete'}}]})
|
||||
app = await self.make_app(handler)
|
||||
async with app.run_test() as pilot:
|
||||
await self.wait_finished(app, pilot)
|
||||
self.assertEqual([m.content for m in app.messages], ['Start here', 'complete'])
|
||||
self.assertEqual(len(app.query(MessageBubble)), 2)
|
||||
self.assertFalse(app.query(MessageBubble).last()._streaming)
|
||||
|
||||
async def test_empty_stream_uses_fallback(self):
|
||||
calls = []
|
||||
def handler(request):
|
||||
calls.append(json.loads(request.content))
|
||||
if calls[-1].get('stream'):
|
||||
return httpx.Response(200, text='data: [DONE]\n\n')
|
||||
return httpx.Response(200, json={'choices': [{'message': {'content': 'fallback'}}]})
|
||||
app = await self.make_app(handler)
|
||||
async with app.run_test() as pilot:
|
||||
await self.wait_finished(app, pilot)
|
||||
self.assertEqual(len(calls), 2)
|
||||
self.assertEqual(app.messages[-1].content, 'fallback')
|
||||
|
||||
async def test_error_is_preserved(self):
|
||||
app = await self.make_app(lambda request: httpx.Response(500, text='unavailable'))
|
||||
async with app.run_test() as pilot:
|
||||
await self.wait_finished(app, pilot)
|
||||
self.assertIn('Error:', str(app.status_bar.render()))
|
||||
self.assertNotIn('Conversation ended', str(app.status_bar.render()))
|
||||
self.assertEqual(app.current_turn, 0)
|
||||
self.assertEqual(app.messages[-1].role, 'system')
|
||||
|
||||
async def test_quit_while_request_is_pending(self):
|
||||
started = asyncio.Event()
|
||||
cancelled = asyncio.Event()
|
||||
async def handler(request):
|
||||
started.set()
|
||||
try:
|
||||
await asyncio.Event().wait()
|
||||
except asyncio.CancelledError:
|
||||
cancelled.set()
|
||||
raise
|
||||
app = await self.make_app(handler)
|
||||
async with app.run_test() as pilot:
|
||||
await asyncio.wait_for(started.wait(), 2)
|
||||
await pilot.press('ctrl+c')
|
||||
self.assertTrue(cancelled.is_set())
|
||||
self.assertTrue(app.client.is_closed)
|
||||
|
||||
async def test_empty_fallback_reports_error(self):
|
||||
def handler(request):
|
||||
if json.loads(request.content).get('stream'):
|
||||
return httpx.Response(200, text='data: [DONE]\n\n')
|
||||
return httpx.Response(200, json={'choices': [{'message': {'content': None}}]})
|
||||
app = await self.make_app(handler)
|
||||
async with app.run_test() as pilot:
|
||||
await self.wait_finished(app, pilot)
|
||||
self.assertIn('Empty response', str(app.status_bar.render()))
|
||||
self.assertEqual(app.current_turn, 0)
|
||||
|
||||
|
||||
class CommandLineTests(unittest.TestCase):
|
||||
def test_invalid_environment_turns_reports_usage_error(self):
|
||||
with patch.dict(os.environ, {"MAX_TURNS": "invalid"}), patch('sys.argv', ['ai_chat.py']):
|
||||
with contextlib.redirect_stderr(io.StringIO()) as stderr:
|
||||
with self.assertRaises(SystemExit) as error:
|
||||
main()
|
||||
self.assertEqual(error.exception.code, 2)
|
||||
self.assertIn('invalid int value', stderr.getvalue())
|
||||
|
||||
def test_help_works_with_invalid_environment_turns(self):
|
||||
with patch.dict(os.environ, {"MAX_TURNS": "invalid"}), patch('sys.argv', ['run_example.py', '--help']):
|
||||
with contextlib.redirect_stdout(io.StringIO()):
|
||||
with self.assertRaises(SystemExit) as error:
|
||||
main()
|
||||
self.assertEqual(error.exception.code, 0)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user