added error handling and more instruction

This commit is contained in:
lemonknowsall committed 2025-09-27 21:29:00 -07:00
1 parent 6980497532
commit c669dd3604
2 files changed
+166 -62

No files matched your search

+61 -36
View File
@@ -845,66 +845,91 @@ const decrypted = await user.signer.nip44.decrypt(user.pubkey, encrypted) // "he
### AI Integration with Shakespeare API ### AI Integration with Shakespeare API
The project includes `useShakespeare` hook for AI chat completions using the Shakespeare AI API. This provides access to premium AI models with Nostr-based authentication. Use the `useShakespeare` hook for AI chat completions with Nostr authentication.
#### Basic Usage
```tsx ```tsx
import { useShakespeare } from '@/hooks/useShakespeare'; import { useShakespeare, type ChatMessage } from '@/hooks/useShakespeare';
const { sendChatMessage, sendStreamingMessage, isLoading, error, isAuthenticated } = useShakespeare();
```
#### Basic Chat Example
```tsx
function AIChat() { function AIChat() {
const { sendChatMessage, sendStreamingMessage, isLoading, error } = useShakespeare(); const { sendChatMessage, isLoading, error, isAuthenticated } = useShakespeare();
const [messages, setMessages] = useState([]); const [messages, setMessages] = useState<ChatMessage[]>([]);
const [input, setInput] = useState('');
const handleSendMessage = async (content: string) => { const handleSend = async () => {
try { if (!input.trim()) return;
const response = await sendChatMessage([
...messages,
{ role: 'user', content }
], 'shakespeare'); // or 'tybalt' for free model
setMessages(prev => [...prev, const newMessages = [...messages, { role: 'user', content: input }];
{ role: 'user', content }, setMessages(newMessages);
{ role: 'assistant', content: response.choices[0].message.content } setInput('');
]);
} catch (err) { const response = await sendChatMessage(newMessages, 'tybalt'); // Free model
console.error('AI request failed:', err); setMessages(prev => [...prev, {
} role: 'assistant',
content: response.choices[0].message.content as string
}]);
}; };
if (!isAuthenticated) return <div>Please log in to use AI</div>;
return ( return (
<div> <div className="max-w-2xl mx-auto p-4">
{error && <div className="text-red-500">{error}</div>} {error && <div className="text-red-500 mb-4">{error}</div>}
{/* Chat UI */}
<div className="space-y-2 mb-4">
{messages.map((msg, i) => (
<div key={i} className={`p-2 rounded ${msg.role === 'user' ? 'bg-blue-100' : 'bg-gray-100'}`}>
<strong>{msg.role}:</strong> {msg.content}
</div>
))}
</div>
<div className="flex gap-2">
<input
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyPress={(e) => e.key === 'Enter' && handleSend()}
className="flex-1 p-2 border rounded"
disabled={isLoading}
/>
<button onClick={handleSend} disabled={isLoading} className="px-4 py-2 bg-blue-500 text-white rounded">
Send
</button>
</div>
</div> </div>
); );
} }
``` ```
#### Streaming Responses #### Streaming Chat
```tsx ```tsx
const handleStreamingMessage = async (content: string) => { const [currentResponse, setCurrentResponse] = useState('');
let fullResponse = '';
await sendStreamingMessage([ const handleStreaming = async (content: string) => {
...messages, setCurrentResponse('');
{ role: 'user', content } await sendStreamingMessage(messages, 'shakespeare', (chunk) => {
], 'shakespeare', (chunk) => { setCurrentResponse(prev => prev + chunk);
fullResponse += chunk;
// Update UI with streaming content
}); });
}; };
``` ```
#### Available Models #### Models
- **`shakespeare`**: Premium model - **`tybalt`**: Free model for development
- **`tybalt`**: Free model for testing (no cost) - **`shakespeare`**: Premium model (requires credits)
#### Authentication #### Key Points
The hook automatically handles NIP-98 authentication using the current user's Nostr signer. Users must be logged in to use AI features. - User must be logged in with Nostr account
- Use `tybalt` for free testing
- Handle `isLoading` and `error` states
- Check `isAuthenticated` before API calls
### Rendering Rich Text Content ### Rendering Rich Text Content
+105 -26
View File
@@ -1,5 +1,6 @@
import { useCallback, useState } from 'react'; import { useCallback, useState } from 'react';
import { useCurrentUser } from './useCurrentUser'; import { useCurrentUser } from './useCurrentUser';
import type { NUser } from '@nostrify/react/login';
// Types for Shakespeare API (compatible with OpenAI ChatCompletionMessageParam) // Types for Shakespeare API (compatible with OpenAI ChatCompletionMessageParam)
export interface ChatMessage { export interface ChatMessage {
@@ -65,21 +66,35 @@ async function createNIP98Token(
method: string, method: string,
url: string, url: string,
body?: unknown, body?: unknown,
user?: { signer: { signEvent: (event: { kind: number; content: string; tags: string[][]; created_at: number }) => Promise<{ id: string; pubkey: string; created_at: number; kind: number; tags: string[][]; content: string; sig: string }> } } user?: NUser
): Promise<string> { ): Promise<string> {
if (!user?.signer) { if (!user?.signer) {
throw new Error('User signer is required for NIP-98 authentication'); throw new Error('User signer is required for NIP-98 authentication');
} }
// Create the tags array
const tags: string[][] = [
['u', url],
['method', method]
];
// Add payload hash for requests with body (following NIP-98 spec)
if (body && (method === 'POST' || method === 'PUT' || method === 'PATCH')) {
const bodyString = JSON.stringify(body);
const encoder = new TextEncoder();
const data = encoder.encode(bodyString);
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
const payloadHash = Array.from(new Uint8Array(hashBuffer))
.map(b => b.toString(16).padStart(2, '0'))
.join('');
tags.push(['payload', payloadHash]);
}
// Create the HTTP request event // Create the HTTP request event
const event = await user.signer.signEvent({ const event = await user.signer.signEvent({
kind: 27235, // NIP-98 HTTP Auth kind: 27235, // NIP-98 HTTP Auth
content: '', content: '',
tags: [ tags,
['u', url],
['method', method],
...(body ? [['payload', JSON.stringify(body)]] : [])
],
created_at: Math.floor(Date.now() / 1000) created_at: Math.floor(Date.now() / 1000)
}); });
@@ -87,18 +102,40 @@ async function createNIP98Token(
return btoa(JSON.stringify(event)); return btoa(JSON.stringify(event));
} }
// Helper function to handle API errors // Helper function to handle API errors with user-friendly messages
async function handleAPIError(response: Response) { async function handleAPIError(response: Response) {
if (response.status === 401) { if (response.status === 401) {
throw new Error('Authentication failed. Please check your Nostr credentials.'); throw new Error('Authentication failed. Please make sure you are logged in with a Nostr account.');
} else if (response.status === 402) { } else if (response.status === 402) {
throw new Error('Insufficient credits. Please add credits to your account.'); throw new Error('Insufficient credits. Please add credits to your account to use premium models, or use the free "tybalt" model.');
} else if (response.status === 400) { } else if (response.status === 400) {
const error = await response.json(); try {
throw new Error(`Invalid request: ${error.details || error.error}`); const error = await response.json();
if (error.error?.type === 'invalid_request_error') {
// Handle specific validation errors
if (error.error.code === 'minimum_amount_not_met') {
throw new Error(`Minimum credit amount is $${error.error.minimum_amount}. Please increase your payment amount.`);
} else if (error.error.code === 'unsupported_method') {
throw new Error('Payment method not supported. Please use "stripe" or "lightning".');
} else if (error.error.code === 'invalid_url') {
throw new Error('Invalid redirect URL provided for Stripe payment.');
}
}
throw new Error(`Invalid request: ${error.error?.message || error.details || error.error || 'Please check your request parameters.'}`);
} catch (parseError) {
throw new Error('Invalid request. Please check your parameters and try again.');
}
} else if (response.status === 404) {
throw new Error('Resource not found. Please check the payment ID or try again.');
} else if (response.status >= 500) {
throw new Error('Server error. Please try again in a few moments.');
} else if (!response.ok) { } else if (!response.ok) {
const errorData = await response.json().catch(() => ({})); try {
throw new Error(`API error: ${errorData.error || errorData.details || response.statusText}`); const errorData = await response.json();
throw new Error(`API error: ${errorData.error?.message || errorData.details || errorData.error || response.statusText}`);
} catch (parseError) {
throw new Error(`Network error: ${response.statusText}. Please check your connection and try again.`);
}
} }
} }
@@ -118,8 +155,8 @@ export function useShakespeare() {
model: string = 'shakespeare', model: string = 'shakespeare',
options?: Partial<ChatCompletionRequest> options?: Partial<ChatCompletionRequest>
): Promise<ChatCompletionResponse> => { ): Promise<ChatCompletionResponse> => {
if (!user?.signer) { if (!user) {
throw new Error('User must be logged in with signer'); throw new Error('User must be logged in to use AI features');
} }
setIsLoading(true); setIsLoading(true);
@@ -151,9 +188,23 @@ export function useShakespeare() {
await handleAPIError(response); await handleAPIError(response);
return await response.json(); return await response.json();
} catch (err) { } catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Unknown error occurred'; let errorMessage = 'An unexpected error occurred';
if (err instanceof Error) {
errorMessage = err.message;
} else if (typeof err === 'string') {
errorMessage = err;
}
// Add context for common issues
if (errorMessage.includes('Failed to fetch') || errorMessage.includes('Network')) {
errorMessage = 'Network error: Please check your internet connection and try again.';
} else if (errorMessage.includes('signer')) {
errorMessage = 'Authentication error: Please make sure you are logged in with a Nostr account that supports signing.';
}
setError(errorMessage); setError(errorMessage);
throw err; throw new Error(errorMessage);
} finally { } finally {
setIsLoading(false); setIsLoading(false);
} }
@@ -166,8 +217,8 @@ export function useShakespeare() {
onChunk: (chunk: string) => void, onChunk: (chunk: string) => void,
options?: Partial<ChatCompletionRequest> options?: Partial<ChatCompletionRequest>
): Promise<void> => { ): Promise<void> => {
if (!user?.signer) { if (!user) {
throw new Error('User must be logged in with signer'); throw new Error('User must be logged in to use AI features');
} }
setIsLoading(true); setIsLoading(true);
@@ -235,9 +286,23 @@ export function useShakespeare() {
reader.releaseLock(); reader.releaseLock();
} }
} catch (err) { } catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Unknown error occurred'; let errorMessage = 'An unexpected error occurred';
if (err instanceof Error) {
errorMessage = err.message;
} else if (typeof err === 'string') {
errorMessage = err;
}
// Add context for common issues
if (errorMessage.includes('Failed to fetch') || errorMessage.includes('Network')) {
errorMessage = 'Network error: Please check your internet connection and try again.';
} else if (errorMessage.includes('signer')) {
errorMessage = 'Authentication error: Please make sure you are logged in with a Nostr account that supports signing.';
}
setError(errorMessage); setError(errorMessage);
throw err; throw new Error(errorMessage);
} finally { } finally {
setIsLoading(false); setIsLoading(false);
} }
@@ -245,8 +310,8 @@ export function useShakespeare() {
// Get available models // Get available models
const getAvailableModels = useCallback(async (): Promise<ModelsResponse> => { const getAvailableModels = useCallback(async (): Promise<ModelsResponse> => {
if (!user?.signer) { if (!user) {
throw new Error('User must be logged in with signer'); throw new Error('User must be logged in to use AI features');
} }
setIsLoading(true); setIsLoading(true);
@@ -270,9 +335,23 @@ export function useShakespeare() {
await handleAPIError(response); await handleAPIError(response);
return await response.json(); return await response.json();
} catch (err) { } catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Unknown error occurred'; let errorMessage = 'An unexpected error occurred';
if (err instanceof Error) {
errorMessage = err.message;
} else if (typeof err === 'string') {
errorMessage = err;
}
// Add context for common issues
if (errorMessage.includes('Failed to fetch') || errorMessage.includes('Network')) {
errorMessage = 'Network error: Please check your internet connection and try again.';
} else if (errorMessage.includes('signer')) {
errorMessage = 'Authentication error: Please make sure you are logged in with a Nostr account that supports signing.';
}
setError(errorMessage); setError(errorMessage);
throw err; throw new Error(errorMessage);
} finally { } finally {
setIsLoading(false); setIsLoading(false);
} }
@@ -282,7 +361,7 @@ export function useShakespeare() {
// State // State
isLoading, isLoading,
error, error,
isAuthenticated: !!user?.signer, isAuthenticated: !!user,
// Actions // Actions
sendChatMessage, sendChatMessage,