Add Shakespeare AI hook and agent instruction

This commit is contained in:
lemonknowsall committed 2025-09-27 21:29:00 -07:00
1 parent 57c646f919
commit 6980497532
2 files changed
+357

No files matched your search

+293
View File
@@ -0,0 +1,293 @@
import { useCallback, useState } from 'react';
import { useCurrentUser } from './useCurrentUser';
// Types for Shakespeare API (compatible with OpenAI ChatCompletionMessageParam)
export interface ChatMessage {
role: 'user' | 'assistant' | 'system';
content: string | Array<{
type: 'text' | 'image_url';
text?: string;
image_url?: {
url: string;
};
}>;
}
export interface ChatCompletionRequest {
model: string;
messages: ChatMessage[];
stream?: boolean;
temperature?: number;
max_tokens?: number;
}
export interface ChatCompletionResponse {
id: string;
object: string;
created: number;
model: string;
choices: Array<{
index: number;
message: ChatMessage;
finish_reason: string;
}>;
usage: {
prompt_tokens: number;
completion_tokens: number;
total_tokens: number;
};
}
export interface Model {
id: string;
name: string;
description: string;
object: string;
owned_by: string;
created: number;
context_window: number;
pricing: {
prompt: string;
completion: string;
};
}
export interface ModelsResponse {
object: string;
data: Model[];
}
// Configuration
const SHAKESPEARE_API_URL = 'https://ai.shakespeare.diy/v1';
// Helper function to create NIP-98 token
async function createNIP98Token(
method: string,
url: string,
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 }> } }
): Promise<string> {
if (!user?.signer) {
throw new Error('User signer is required for NIP-98 authentication');
}
// Create the HTTP request event
const event = await user.signer.signEvent({
kind: 27235, // NIP-98 HTTP Auth
content: '',
tags: [
['u', url],
['method', method],
...(body ? [['payload', JSON.stringify(body)]] : [])
],
created_at: Math.floor(Date.now() / 1000)
});
// Return the token (base64 encoded event)
return btoa(JSON.stringify(event));
}
// Helper function to handle API errors
async function handleAPIError(response: Response) {
if (response.status === 401) {
throw new Error('Authentication failed. Please check your Nostr credentials.');
} else if (response.status === 402) {
throw new Error('Insufficient credits. Please add credits to your account.');
} else if (response.status === 400) {
const error = await response.json();
throw new Error(`Invalid request: ${error.details || error.error}`);
} else if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(`API error: ${errorData.error || errorData.details || response.statusText}`);
}
}
export function useShakespeare() {
const { user } = useCurrentUser();
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
// Clear error helper
const clearError = useCallback(() => {
setError(null);
}, []);
// Chat completion function
const sendChatMessage = useCallback(async (
messages: ChatMessage[],
model: string = 'shakespeare',
options?: Partial<ChatCompletionRequest>
): Promise<ChatCompletionResponse> => {
if (!user?.signer) {
throw new Error('User must be logged in with signer');
}
setIsLoading(true);
setError(null);
try {
const requestBody: ChatCompletionRequest = {
model,
messages,
...options
};
const token = await createNIP98Token(
'POST',
`${SHAKESPEARE_API_URL}/chat/completions`,
requestBody,
user
);
const response = await fetch(`${SHAKESPEARE_API_URL}/chat/completions`, {
method: 'POST',
headers: {
'Authorization': `Nostr ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(requestBody),
});
await handleAPIError(response);
return await response.json();
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Unknown error occurred';
setError(errorMessage);
throw err;
} finally {
setIsLoading(false);
}
}, [user]);
// Streaming chat completion function
const sendStreamingMessage = useCallback(async (
messages: ChatMessage[],
model: string = 'shakespeare',
onChunk: (chunk: string) => void,
options?: Partial<ChatCompletionRequest>
): Promise<void> => {
if (!user?.signer) {
throw new Error('User must be logged in with signer');
}
setIsLoading(true);
setError(null);
try {
const requestBody: ChatCompletionRequest = {
model,
messages,
stream: true,
...options
};
const token = await createNIP98Token(
'POST',
`${SHAKESPEARE_API_URL}/chat/completions`,
requestBody,
user
);
const response = await fetch(`${SHAKESPEARE_API_URL}/chat/completions`, {
method: 'POST',
headers: {
'Authorization': `Nostr ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(requestBody),
});
await handleAPIError(response);
if (!response.body) {
throw new Error('No response body');
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
const lines = chunk.split('\n');
for (const line of lines) {
if (line.startsWith('data: ')) {
const data = line.slice(6);
if (data === '[DONE]') return;
try {
const parsed = JSON.parse(data);
const content = parsed.choices?.[0]?.delta?.content;
if (content) {
onChunk(content);
}
} catch {
// Ignore parsing errors for incomplete chunks
}
}
}
}
} finally {
reader.releaseLock();
}
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Unknown error occurred';
setError(errorMessage);
throw err;
} finally {
setIsLoading(false);
}
}, [user]);
// Get available models
const getAvailableModels = useCallback(async (): Promise<ModelsResponse> => {
if (!user?.signer) {
throw new Error('User must be logged in with signer');
}
setIsLoading(true);
setError(null);
try {
const token = await createNIP98Token(
'GET',
`${SHAKESPEARE_API_URL}/models`,
undefined,
user
);
const response = await fetch(`${SHAKESPEARE_API_URL}/models`, {
method: 'GET',
headers: {
'Authorization': `Nostr ${token}`,
},
});
await handleAPIError(response);
return await response.json();
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Unknown error occurred';
setError(errorMessage);
throw err;
} finally {
setIsLoading(false);
}
}, [user]);
return {
// State
isLoading,
error,
isAuthenticated: !!user?.signer,
// Actions
sendChatMessage,
sendStreamingMessage,
getAvailableModels,
clearError,
};
}