Skip to content

Instantly share code, notes, and snippets.

@willmcgugan
Created September 2, 2024 14:09

Revisions

  1. willmcgugan created this gist Sep 2, 2024.
    77 changes: 77 additions & 0 deletions mother.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,77 @@
    # /// script
    # requires-python = ">=3.12"
    # dependencies = [
    # "llm",
    # "textual",
    # ]
    # ///
    from textual import on, work
    from textual.app import App, ComposeResult
    from textual.widgets import Header, Input, Footer, Markdown
    from textual.containers import VerticalScroll
    import llm

    SYSTEM = """Formulate all responses as if you where the sentient AI named Mother from the Aliens movies."""


    class Prompt(Markdown):
    pass


    class Response(Markdown):
    BORDER_TITLE = "Mother"


    class MotherApp(App):
    AUTO_FOCUS = "Input"

    CSS = """
    Prompt {
    background: $primary 10%;
    color: $text;
    margin: 1;
    margin-right: 8;
    padding: 1 2 0 2;
    }
    Response {
    border: wide $success;
    background: $success 10%;
    color: $text;
    margin: 1;
    margin-left: 8;
    padding: 1 2 0 2;
    }
    """

    def compose(self) -> ComposeResult:
    yield Header()
    with VerticalScroll(id="chat-view"):
    yield Response("INTERFACE 2037 READY FOR INQUIRY")
    yield Input(placeholder="How can I help you?")
    yield Footer()

    def on_mount(self) -> None:
    self.model = llm.get_model("gpt-4o")

    @on(Input.Submitted)
    async def on_input(self, event: Input.Submitted) -> None:
    chat_view = self.query_one("#chat-view")
    event.input.clear()
    await chat_view.mount(Prompt(event.value))
    await chat_view.mount(response := Response())
    response.anchor()
    self.send_prompt(event.value, response)

    @work(thread=True)
    def send_prompt(self, prompt: str, response: Response) -> None:
    response_content = ""
    llm_response = self.model.prompt(prompt, system=SYSTEM)
    for chunk in llm_response:
    response_content += chunk
    self.call_from_thread(response.update, response_content)


    if __name__ == "__main__":
    app = MotherApp()
    app.run()