diff --git a/docs/AI_CHAT.md b/docs/AI_CHAT.md index 66759d1..b7019e1 100644 --- a/docs/AI_CHAT.md +++ b/docs/AI_CHAT.md @@ -1,11 +1,82 @@ ### AI Integration with Shakespeare API -Use the `useShakespeare` hook for AI chat completions with Nostr authentication. +Use the `useShakespeare` hook for AI chat completions with Nostr authentication. The API dynamically provides available models, so you should query them at runtime rather than hardcoding model names. ```tsx -import { useShakespeare, type ChatMessage } from '@/hooks/useShakespeare'; +import { useShakespeare, type ChatMessage, type Model } from '@/hooks/useShakespeare'; -const { sendChatMessage, sendStreamingMessage, isLoading, error, isAuthenticated } = useShakespeare(); +const { + sendChatMessage, + sendStreamingMessage, + getAvailableModels, + isLoading, + error, + isAuthenticated +} = useShakespeare(); +``` + +#### Model Selector Component + +```tsx +function ModelSelector({ onModelSelect }: { onModelSelect: (modelId: string) => void }) { + const { getAvailableModels, isLoading } = useShakespeare(); + const [models, setModels] = useState([]); + const [selectedModel, setSelectedModel] = useState(''); + + useEffect(() => { + const fetchModels = async () => { + try { + const response = await getAvailableModels(); + // Sort models by total cost (cheapest first) + const sortedModels = response.data.sort((a, b) => { + const costA = parseFloat(a.pricing.prompt) + parseFloat(a.pricing.completion); + const costB = parseFloat(b.pricing.prompt) + parseFloat(b.pricing.completion); + return costA - costB; + }); + setModels(sortedModels); + + // Select the cheapest model by default + if (sortedModels.length > 0) { + const cheapestModel = sortedModels[0]; + setSelectedModel(cheapestModel.id); + onModelSelect(cheapestModel.id); + } + } catch (err) { + console.error('Failed to fetch models:', err); + } + }; + + fetchModels(); + }, [getAvailableModels, onModelSelect]); + + const handleModelChange = (modelId: string) => { + setSelectedModel(modelId); + onModelSelect(modelId); + }; + + return ( +
+ + +
+ ); +} ``` #### Basic Chat Example @@ -15,19 +86,24 @@ function AIChat() { const { sendChatMessage, isLoading, error, isAuthenticated } = useShakespeare(); const [messages, setMessages] = useState([]); const [input, setInput] = useState(''); + const [selectedModel, setSelectedModel] = useState(''); const handleSend = async () => { - if (!input.trim()) return; + if (!input.trim() || !selectedModel) return; const newMessages = [...messages, { role: 'user', content: input }]; setMessages(newMessages); setInput(''); - const response = await sendChatMessage(newMessages, 'tybalt'); // Free model - setMessages(prev => [...prev, { - role: 'assistant', - content: response.choices[0].message.content as string - }]); + try { + const response = await sendChatMessage(newMessages, selectedModel); + setMessages(prev => [...prev, { + role: 'assistant', + content: response.choices[0].message.content as string + }]); + } catch (err) { + console.error('Chat error:', err); + } }; if (!isAuthenticated) return
Please log in to use AI
; @@ -36,6 +112,11 @@ function AIChat() {
{error &&
{error}
} + {/* Model Selection */} +
+ +
+
{messages.map((msg, i) => (
@@ -50,9 +131,14 @@ function AIChat() { onChange={(e) => setInput(e.target.value)} onKeyPress={(e) => e.key === 'Enter' && handleSend()} className="flex-1 p-2 border rounded" - disabled={isLoading} + disabled={isLoading || !selectedModel} + placeholder={!selectedModel ? "Select a model first..." : "Type your message..."} /> -
@@ -61,30 +147,73 @@ function AIChat() { } ``` -#### Streaming Chat +#### Streaming Chat Example ```tsx -const [currentResponse, setCurrentResponse] = useState(''); +function StreamingChat() { + const { sendStreamingMessage } = useShakespeare(); + const [messages, setMessages] = useState([]); + const [currentResponse, setCurrentResponse] = useState(''); + const [selectedModel, setSelectedModel] = useState(''); -const handleStreaming = async (content: string) => { - setCurrentResponse(''); - await sendStreamingMessage(messages, 'shakespeare', (chunk) => { - setCurrentResponse(prev => prev + chunk); - }); -}; + const handleStreaming = async (content: string) => { + if (!selectedModel) return; + + setCurrentResponse(''); + const newMessages = [...messages, { role: 'user', content }]; + setMessages(newMessages); + + try { + await sendStreamingMessage(newMessages, selectedModel, (chunk) => { + setCurrentResponse(prev => prev + chunk); + }); + + // Add the complete response to messages + if (currentResponse.trim()) { + setMessages(prev => [...prev, { + role: 'assistant', + content: currentResponse + }]); + } + } catch (err) { + console.error('Streaming error:', err); + } finally { + setCurrentResponse(''); + } + }; + + return ( +
+ {/* Model selection UI */} +
+ +
+ + {/* Chat interface */} + {/* ... rest of your chat UI */} +
+ ); +} ``` -#### Models +#### Model Information -- **`tybalt`**: Free model for development -- **`shakespeare`**: Premium model (requires credits) +Models are dynamically fetched from the Shakespeare API and include: + +- **Model ID**: Unique identifier for the model +- **Name**: Human-readable model name +- **Description**: Model capabilities and use cases +- **Context Window**: Maximum token limit for conversations +- **Pricing**: Cost per token for prompt and completion +- **Free Models**: Models with `pricing.prompt === "0"` and `pricing.completion === "0"` #### Key Points -- User must be logged in with Nostr account -- Use `tybalt` for free testing -- Handle `isLoading` and `error` states -- Check `isAuthenticated` before API calls +- **Dynamic Model Discovery**: Always fetch available models using `getAvailableModels()` +- **Authentication Required**: User must be logged in with Nostr account +- **Free vs Premium**: Check pricing to determine if model requires credits +- **Error Handling**: Handle `isLoading` and `error` states appropriately +- **Model Selection**: Provide UI for users to choose between available models ## Implementation Patterns and Best Practices @@ -182,9 +311,9 @@ function AIChatWithErrorBoundary() { function useAIWithErrorHandling() { const { sendChatMessage, error, clearError } = useShakespeare(); - const sendMessage = async (messages: ChatMessage[]) => { + const sendMessage = async (messages: ChatMessage[], modelId: string) => { try { - await sendChatMessage(messages, 'tybalt'); + await sendChatMessage(messages, modelId); } catch (err) { // Handle specific error types with user-friendly messages if (err.message.includes('401')) {