Skip to main content

Crate leptos_ai

Crate leptos_ai 

Source
Expand description

§Leptos AI

AI hooks for Leptos applications - chat, completions, and streaming.

§Features

  • use_chat - Reactive chat with message history and streaming
  • use_completion - Single completion requests
  • Built on llm-client for provider support (OpenAI, Anthropic, OpenRouter)

§Example

use leptos::*;
use leptos_ai::{use_chat, ChatOptions};

#[component]
fn Chat() -> impl IntoView {
    let chat = use_chat(ChatOptions {
        provider: "openai".to_string(),
        api_key: "sk-...".to_string(),
        model: "gpt-4o-mini".to_string(),
        ..Default::default()
    });

    let input = create_node_ref::<html::Input>();

    let on_submit = move |ev: ev::SubmitEvent| {
        ev.prevent_default();
        if let Some(input_el) = input.get() {
            let value = input_el.value();
            if !value.is_empty() {
                chat.send(&value);
                input_el.set_value("");
            }
        }
    };

    view! {
        <div class="chat">
            <For
                each=move || chat.messages.get()
                key=|msg| msg.id.clone()
                children=move |msg| {
                    view! {
                        <div class=format!("message {}", msg.role)>
                            {msg.content.clone()}
                        </div>
                    }
                }
            />
            <Show when=move || chat.is_loading.get()>
                <div class="loading">"Thinking..."</div>
            </Show>
            <form on:submit=on_submit>
                <input type="text" node_ref=input placeholder="Type a message..." />
                <button type="submit">"Send"</button>
            </form>
        </div>
    }
}

Structs§

ChatMessage
A message in the chat conversation
ChatOptions
Options for the chat hook
CompletionOptions
Options for the completion hook
TokenUsage
Token usage information
UseChat
Return type for use_chat hook
UseCompletion
Return type for use_completion hook

Enums§

LeptosAiError
Errors that can occur in leptos-ai
Provider
Supported LLM providers.
Role
Role in a conversation.

Functions§

use_chat
Create a reactive chat interface
use_completion
Create a completion interface for single requests

Type Aliases§

Result