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')) { diff --git a/docs/NOSTR_INFINITE_SCROLL.md b/docs/NOSTR_INFINITE_SCROLL.md index d183f26..becee36 100644 --- a/docs/NOSTR_INFINITE_SCROLL.md +++ b/docs/NOSTR_INFINITE_SCROLL.md @@ -34,18 +34,27 @@ Example usage with intersection observer for automatic loading: ```tsx import { useInView } from 'react-intersection-observer'; +import { useMemo } from 'react'; function GlobalFeed() { const { data, fetchNextPage, hasNextPage, isFetchingNextPage } = useGlobalFeed(); const { ref, inView } = useInView(); useEffect(() => { - if (inView && hasNextPage) { + if (inView && hasNextPage && !isFetchingNextPage) { fetchNextPage(); } - }, [inView, hasNextPage, fetchNextPage]); + }, [inView, hasNextPage, isFetchingNextPage, fetchNextPage]); - const posts = data?.pages.flat() || []; + // Remove duplicate events by ID + const posts = useMemo(() => { + const seen = new Set(); + return data?.pages.flat().filter(event => { + if (!event.id || seen.has(event.id)) return false; + seen.add(event.id); + return true; + }) || []; + }, [data?.pages]); return (
diff --git a/package-lock.json b/package-lock.json index 3e7b594..5aad45d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -63,7 +63,6 @@ "tailwind-merge": "^2.5.2", "tailwindcss-animate": "^1.0.7", "vaul": "^0.9.3", - "webln": "^0.3.2", "zod": "^3.25.71" }, "devDependencies": { @@ -78,6 +77,7 @@ "@types/react": "^18.3.1", "@types/react-dom": "^18.3.1", "@vitejs/plugin-react-swc": "^3.5.0", + "@webbtc/webln-types": "^3.0.0", "autoprefixer": "^10.4.20", "eslint": "^9.9.0", "eslint-plugin-react-hooks": "^5.1.0-rc.0", @@ -3416,15 +3416,6 @@ "license": "MIT", "peer": true }, - "node_modules/@types/chrome": { - "version": "0.0.74", - "resolved": "https://registry.npmjs.org/@types/chrome/-/chrome-0.0.74.tgz", - "integrity": "sha512-hzosS5CkQcIKCgxcsV2AzbJ36KNxG/Db2YEN/erEu7Boprg+KpMDLBQqKFmSo+JkQMGqRcicUyqCowJpuT+C6A==", - "license": "MIT", - "dependencies": { - "@types/filesystem": "*" - } - }, "node_modules/@types/d3-array": { "version": "3.2.1", "resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.2.1.tgz", @@ -3494,21 +3485,6 @@ "integrity": "sha512-w28IoSUCJpidD/TGviZwwMJckNESJZXFu7NBZ5YJ4mEUnNraUn9Pm8HSZm/jDF1pDWYKspWE7oVphigUPRakIQ==", "license": "MIT" }, - "node_modules/@types/filesystem": { - "version": "0.0.36", - "resolved": "https://registry.npmjs.org/@types/filesystem/-/filesystem-0.0.36.tgz", - "integrity": "sha512-vPDXOZuannb9FZdxgHnqSwAG/jvdGM8Wq+6N4D/d80z+D4HWH+bItqsZaVRQykAn6WEVeEkLm2oQigyHtgb0RA==", - "license": "MIT", - "dependencies": { - "@types/filewriter": "*" - } - }, - "node_modules/@types/filewriter": { - "version": "0.0.33", - "resolved": "https://registry.npmjs.org/@types/filewriter/-/filewriter-0.0.33.tgz", - "integrity": "sha512-xFU8ZXTw4gd358lb2jw25nxY9QAgqn2+bKKjKOYfNCzN4DKCFetK7sPtrlpg66Ywe3vWY9FNxprZawAh9wfJ3g==", - "license": "MIT" - }, "node_modules/@types/json-schema": { "version": "7.0.15", "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", @@ -3929,6 +3905,17 @@ "url": "https://opencollective.com/vitest" } }, + "node_modules/@webbtc/webln-types": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@webbtc/webln-types/-/webln-types-3.0.0.tgz", + "integrity": "sha512-aXfTHLKz5lysd+6xTeWl+qHNh/p3qVYbeLo+yDN5cUDmhie2ZoGvkppfWxzbGkcFBzb6dJyQ2/i2cbmDHas+zQ==", + "dev": true, + "license": "MIT", + "funding": { + "type": "lightning", + "url": "lightning:hello@getalby.com" + } + }, "node_modules/acorn": { "version": "8.15.0", "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz", @@ -8011,15 +7998,6 @@ "node": ">=12" } }, - "node_modules/webln": { - "version": "0.3.2", - "resolved": "https://registry.npmjs.org/webln/-/webln-0.3.2.tgz", - "integrity": "sha512-YYT83aOCLup2AmqvJdKtdeBTaZpjC6/JDMe8o6x1kbTYWwiwrtWHyO//PAsPixF3jwFsAkj5DmiceB6w/QSe7Q==", - "license": "MIT", - "dependencies": { - "@types/chrome": "^0.0.74" - } - }, "node_modules/webpack-virtual-modules": { "version": "0.6.2", "resolved": "https://registry.npmjs.org/webpack-virtual-modules/-/webpack-virtual-modules-0.6.2.tgz", diff --git a/package.json b/package.json index cfa97dd..a2b34ac 100644 --- a/package.json +++ b/package.json @@ -65,7 +65,6 @@ "tailwind-merge": "^2.5.2", "tailwindcss-animate": "^1.0.7", "vaul": "^0.9.3", - "webln": "^0.3.2", "zod": "^3.25.71" }, "devDependencies": { @@ -80,6 +79,7 @@ "@types/react": "^18.3.1", "@types/react-dom": "^18.3.1", "@vitejs/plugin-react-swc": "^3.5.0", + "@webbtc/webln-types": "^3.0.0", "autoprefixer": "^10.4.20", "eslint": "^9.9.0", "eslint-plugin-react-hooks": "^5.1.0-rc.0", diff --git a/src/components/WalletModal.tsx b/src/components/WalletModal.tsx index 7643ea5..280052c 100644 --- a/src/components/WalletModal.tsx +++ b/src/components/WalletModal.tsx @@ -29,6 +29,7 @@ import { useWallet } from '@/hooks/useWallet'; import { useToast } from '@/hooks/useToast'; import { useIsMobile } from '@/hooks/useIsMobile'; import type { NWCConnection, NWCInfo } from '@/hooks/useNWC'; +import type { WebLNProvider } from "@webbtc/webln-types"; interface WalletModalProps { children?: React.ReactNode; @@ -68,8 +69,7 @@ AddWalletContent.displayName = 'AddWalletContent'; // Extracted WalletContent to prevent re-renders const WalletContent = forwardRef; @@ -78,8 +78,7 @@ const WalletContent = forwardRef void; setAddDialogOpen: (open: boolean) => void; }>(({ - hasWebLN, - isDetecting, + webln, hasNWC, connections, connectionInfo, @@ -103,9 +102,9 @@ const WalletContent = forwardRef
- {hasWebLN && } - - {isDetecting ? "..." : hasWebLN ? "Ready" : "Not Found"} + {webln && } + + {webln ? "Ready" : "Not Found"}
@@ -191,7 +190,7 @@ const WalletContent = forwardRef {/* Help */} - {!hasWebLN && connections.length === 0 && ( + {!webln && connections.length === 0 && ( <>
@@ -222,7 +221,7 @@ export function WalletModal({ children, className }: WalletModalProps) { setActiveConnection } = useNWC(); - const { hasWebLN, isDetecting } = useWallet(); + const { webln } = useWallet(); const hasNWC = connections.length > 0 && connections.some(c => c.isConnected); const { toast } = useToast(); @@ -263,8 +262,7 @@ export function WalletModal({ children, className }: WalletModalProps) { }; const walletContentProps = { - hasWebLN, - isDetecting, + webln, hasNWC, connections, connectionInfo, diff --git a/src/components/ZapDialog.tsx b/src/components/ZapDialog.tsx index 39e4207..c50bf20 100644 --- a/src/components/ZapDialog.tsx +++ b/src/components/ZapDialog.tsx @@ -33,6 +33,7 @@ import { useWallet } from '@/hooks/useWallet'; import { useIsMobile } from '@/hooks/useIsMobile'; import type { Event } from 'nostr-tools'; import QRCode from 'qrcode'; +import type { WebLNProvider } from "@webbtc/webln-types"; interface ZapDialogProps { target: Event; @@ -55,7 +56,7 @@ interface ZapContentProps { isZapping: boolean; qrCodeUrl: string; copied: boolean; - hasWebLN: boolean; + webln: WebLNProvider | null; handleZap: () => void; handleCopy: () => void; openInWallet: () => void; @@ -73,7 +74,7 @@ const ZapContent = forwardRef(({ isZapping, qrCodeUrl, copied, - hasWebLN, + webln, handleZap, handleCopy, openInWallet, @@ -138,7 +139,7 @@ const ZapContent = forwardRef(({ {/* Payment buttons */}
- {hasWebLN && ( + {webln && (