mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
Use OpenAI messages format
This commit is contained in:
1 parent
71d385384a
commit
efc4cc8c8d
6 files changed
+345
-42
No files matched your search
@@ -1,6 +1,6 @@
|
||||
import { memo } from 'react';
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||
import { Bot, User, Square } from 'lucide-react';
|
||||
import { Bot, User, Square, Wrench } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { AIMessage } from '@/hooks/useAIChat';
|
||||
|
||||
@@ -19,6 +19,57 @@ export const AIMessageItem = memo(({
|
||||
isCurrentlyLoading = false,
|
||||
onStopGeneration
|
||||
}: AIMessageItemProps) => {
|
||||
// Get display name based on role
|
||||
const getDisplayName = () => {
|
||||
switch (message.role) {
|
||||
case 'user':
|
||||
return userDisplayName;
|
||||
case 'assistant':
|
||||
return 'Assistant';
|
||||
case 'system':
|
||||
return 'System';
|
||||
case 'tool':
|
||||
return 'Tool';
|
||||
default:
|
||||
return 'Unknown';
|
||||
}
|
||||
};
|
||||
|
||||
// Get role label for display
|
||||
const getRoleLabel = () => {
|
||||
switch (message.role) {
|
||||
case 'user':
|
||||
return 'User';
|
||||
case 'assistant':
|
||||
return 'AI';
|
||||
case 'system':
|
||||
return 'System';
|
||||
case 'tool':
|
||||
return 'Tool';
|
||||
default:
|
||||
return message.role;
|
||||
}
|
||||
};
|
||||
|
||||
// Get content to display
|
||||
const getContent = () => {
|
||||
if (typeof message.content === 'string') {
|
||||
return message.content;
|
||||
}
|
||||
if (Array.isArray(message.content)) {
|
||||
// Handle array content (like images, text blocks)
|
||||
return message.content
|
||||
.map(item => {
|
||||
if (typeof item === 'string') return item;
|
||||
if (item.type === 'text') return item.text;
|
||||
if (item.type === 'image_url') return `[Image: ${item.image_url.url}]`;
|
||||
return '[Unknown content]';
|
||||
})
|
||||
.join('\n');
|
||||
}
|
||||
return message.content || '';
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex gap-3">
|
||||
<Avatar className="h-8 w-8 flex-shrink-0">
|
||||
@@ -29,6 +80,12 @@ export const AIMessageItem = memo(({
|
||||
<User className="h-4 w-4" />
|
||||
</AvatarFallback>
|
||||
</>
|
||||
) : message.role === 'tool' ? (
|
||||
<>
|
||||
<AvatarFallback>
|
||||
<Wrench className="h-4 w-4" />
|
||||
</AvatarFallback>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<AvatarFallback>
|
||||
@@ -40,10 +97,10 @@ export const AIMessageItem = memo(({
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<span className="font-medium text-sm">
|
||||
{message.role === 'user' ? userDisplayName : message.role === 'assistant' ? 'Assistant' : 'System'}
|
||||
{getDisplayName()}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{message.role === 'user' ? 'User' : message.role === 'assistant' ? 'AI' : 'System'}
|
||||
{getRoleLabel()}
|
||||
</span>
|
||||
{isCurrentlyLoading && onStopGeneration && (
|
||||
<Button
|
||||
@@ -59,8 +116,24 @@ export const AIMessageItem = memo(({
|
||||
</div>
|
||||
<div className="text-sm">
|
||||
<div className="whitespace-pre-wrap break-words">
|
||||
{message.content}
|
||||
{getContent()}
|
||||
</div>
|
||||
|
||||
{/* Display tool calls if present */}
|
||||
{'tool_calls' in message && message.tool_calls && (
|
||||
<div className="mt-2 space-y-2">
|
||||
{message.tool_calls.map((toolCall, index) => (
|
||||
<div key={index} className="bg-muted p-2 rounded text-xs">
|
||||
<div className="font-medium">
|
||||
Tool Call: {toolCall.type === 'function' ? toolCall.function.name : 'Unknown'}
|
||||
</div>
|
||||
<div className="text-muted-foreground">
|
||||
{toolCall.type === 'function' ? toolCall.function.arguments : 'N/A'}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -18,6 +18,9 @@ import { TextEditorStrReplaceTool } from '@/lib/tools/TextEditorStrReplaceTool';
|
||||
import { NpmAddPackageTool } from '@/lib/tools/NpmAddPackageTool';
|
||||
import { NpmRemovePackageTool } from '@/lib/tools/NpmRemovePackageTool';
|
||||
import { GitCommitTool } from '@/lib/tools/GitCommitTool';
|
||||
import { toolToOpenAI } from '@/lib/tools/openai-adapter';
|
||||
import { Tool } from '@/lib/tools/Tool';
|
||||
import OpenAI from 'openai';
|
||||
import { buildProject } from "@/lib/build";
|
||||
|
||||
interface ChatPaneProps {
|
||||
@@ -36,7 +39,7 @@ export function ChatPane({ projectId, projectName }: ChatPaneProps) {
|
||||
|
||||
// Initialize AI chat with tools
|
||||
const cwd = `/projects/${projectId}`;
|
||||
const tools = {
|
||||
const customTools = {
|
||||
git_commit: new GitCommitTool(browserFS, cwd),
|
||||
text_editor_view: new TextEditorViewTool(browserFS, cwd),
|
||||
text_editor_write: new TextEditorWriteTool(browserFS, cwd),
|
||||
@@ -45,6 +48,12 @@ export function ChatPane({ projectId, projectName }: ChatPaneProps) {
|
||||
npm_remove_package: new NpmRemovePackageTool(browserFS, cwd),
|
||||
};
|
||||
|
||||
// Convert tools to OpenAI format
|
||||
const tools: Record<string, OpenAI.Chat.Completions.ChatCompletionTool> = {};
|
||||
for (const [name, tool] of Object.entries(customTools)) {
|
||||
tools[name] = toolToOpenAI(name, tool as Tool<unknown>);
|
||||
}
|
||||
|
||||
const systemPrompt = `You are an AI assistant helping users build custom Nostr websites. You have access to tools that allow you to read, write, and manage files in the project, as well as build the project and manage npm packages.
|
||||
|
||||
Key capabilities:
|
||||
@@ -84,6 +93,7 @@ When creating new components or pages, follow the existing patterns in the codeb
|
||||
projectId,
|
||||
projectName,
|
||||
tools,
|
||||
customTools,
|
||||
systemPrompt,
|
||||
onUpdateMetadata: (title, description) => {
|
||||
updateMetadata(title, description);
|
||||
@@ -330,9 +340,9 @@ BASE_DOMAIN=nostrdeploy.com`);
|
||||
|
||||
<div className="flex-1 overflow-y-scroll overflow-x-hidden" ref={scrollAreaRef}>
|
||||
<div className="p-4 space-y-4">
|
||||
{messages.map((message) => (
|
||||
{messages.map((message, index) => (
|
||||
<AIMessageItem
|
||||
key={message.id}
|
||||
key={`${index}-${message.role}-${typeof message.content === 'string' ? message.content.slice(0, 50) : 'content'}`}
|
||||
message={message}
|
||||
userDisplayName="You"
|
||||
isCurrentlyLoading={isLoading && message.role === 'assistant'}
|
||||
|
||||
+109
-34
@@ -1,19 +1,15 @@
|
||||
import { useState, useCallback, useRef } from 'react';
|
||||
import { createOpenAICompatible } from '@ai-sdk/openai-compatible';
|
||||
import { generateText, Tool } from 'ai';
|
||||
import OpenAI from 'openai';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
|
||||
export interface AIMessage {
|
||||
id: string;
|
||||
role: 'user' | 'assistant' | 'system';
|
||||
content: string;
|
||||
timestamp: number;
|
||||
}
|
||||
// Use OpenAI's native message type
|
||||
export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam;
|
||||
|
||||
interface UseAIChatOptions {
|
||||
projectId: string;
|
||||
projectName: string;
|
||||
tools?: Record<string, Tool>;
|
||||
tools?: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>;
|
||||
customTools?: Record<string, { execute: (args: unknown) => Promise<unknown> }>;
|
||||
systemPrompt?: string;
|
||||
onUpdateMetadata?: (title: string, description: string) => void;
|
||||
}
|
||||
@@ -22,6 +18,7 @@ export function useAIChat({
|
||||
projectId: _projectId,
|
||||
projectName,
|
||||
tools = {},
|
||||
customTools = {},
|
||||
systemPrompt,
|
||||
onUpdateMetadata
|
||||
}: UseAIChatOptions) {
|
||||
@@ -39,10 +36,8 @@ export function useAIChat({
|
||||
|
||||
// Add user message
|
||||
const userMessage: AIMessage = {
|
||||
id: crypto.randomUUID(),
|
||||
role: 'user',
|
||||
content,
|
||||
timestamp: Date.now()
|
||||
content
|
||||
};
|
||||
|
||||
addMessage(userMessage);
|
||||
@@ -54,53 +49,133 @@ export function useAIChat({
|
||||
|
||||
// Get all messages including the new user message
|
||||
const allMessages = [...messages, userMessage];
|
||||
const modelMessages = allMessages.map(msg => ({
|
||||
role: msg.role,
|
||||
content: msg.content
|
||||
}));
|
||||
|
||||
// Initialize OpenAI provider
|
||||
const openai = createOpenAICompatible({
|
||||
name: 'custom',
|
||||
// Use messages directly as they're already in OpenAI format
|
||||
const modelMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = allMessages;
|
||||
|
||||
// Add system message if provided
|
||||
if (systemPrompt) {
|
||||
modelMessages.unshift({
|
||||
role: 'system',
|
||||
content: systemPrompt
|
||||
});
|
||||
}
|
||||
|
||||
// Initialize OpenAI client
|
||||
const openai = new OpenAI({
|
||||
baseURL: settings.baseUrl,
|
||||
apiKey: settings.apiKey,
|
||||
dangerouslyAllowBrowser: true
|
||||
});
|
||||
|
||||
const provider = openai(settings.model);
|
||||
|
||||
// Update metadata
|
||||
if (onUpdateMetadata) {
|
||||
onUpdateMetadata('Shakespeare', `Working on ${projectName}...`);
|
||||
}
|
||||
|
||||
// Generate response
|
||||
const result = await generateText({
|
||||
model: provider,
|
||||
// Prepare chat completion options
|
||||
const completionOptions: OpenAI.Chat.Completions.ChatCompletionCreateParams = {
|
||||
model: settings.model,
|
||||
messages: modelMessages,
|
||||
tools,
|
||||
system: systemPrompt,
|
||||
abortSignal: abortControllerRef.current.signal,
|
||||
tools: tools ? Object.values(tools) : undefined,
|
||||
tool_choice: tools && Object.keys(tools).length > 0 ? 'auto' : undefined
|
||||
};
|
||||
|
||||
// Generate response
|
||||
const completion = await openai.chat.completions.create(completionOptions, {
|
||||
signal: abortControllerRef.current.signal
|
||||
});
|
||||
|
||||
const response = completion.choices[0];
|
||||
if (!response) {
|
||||
throw new Error('No response from AI');
|
||||
}
|
||||
|
||||
const responseMessage = completion.choices[0].message;
|
||||
|
||||
// Add assistant message
|
||||
const assistantMessage: AIMessage = {
|
||||
id: crypto.randomUUID(),
|
||||
role: 'assistant',
|
||||
content: result.text,
|
||||
timestamp: Date.now()
|
||||
content: responseMessage.content || '',
|
||||
...(responseMessage.tool_calls && { tool_calls: responseMessage.tool_calls })
|
||||
};
|
||||
|
||||
addMessage(assistantMessage);
|
||||
|
||||
// Handle tool calls if present
|
||||
if (responseMessage.tool_calls && responseMessage.tool_calls.length > 0) {
|
||||
for (const toolCall of responseMessage.tool_calls) {
|
||||
if (toolCall.type !== 'function') continue;
|
||||
|
||||
const toolName = toolCall.function.name;
|
||||
let toolArgs;
|
||||
|
||||
try {
|
||||
toolArgs = JSON.parse(toolCall.function.arguments);
|
||||
} catch (parseError) {
|
||||
console.error(`Failed to parse tool arguments for ${toolName}:`, parseError);
|
||||
|
||||
const toolErrorMessage: AIMessage = {
|
||||
role: 'tool',
|
||||
content: `Error parsing arguments for tool ${toolName}: ${parseError instanceof Error ? parseError.message : 'Unknown error'}`,
|
||||
tool_call_id: toolCall.id
|
||||
};
|
||||
|
||||
addMessage(toolErrorMessage);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Execute tool if it exists in customTools
|
||||
if (customTools && customTools[toolName]) {
|
||||
try {
|
||||
console.log(`Executing tool: ${toolName}`, toolArgs);
|
||||
|
||||
// Execute the custom tool
|
||||
const tool = customTools[toolName];
|
||||
const result = await tool.execute(toolArgs);
|
||||
|
||||
// Convert result to string
|
||||
const resultString = typeof result === 'string' ? result : JSON.stringify(result, null, 2);
|
||||
|
||||
// Add tool result message
|
||||
const toolResultMessage: AIMessage = {
|
||||
role: 'tool',
|
||||
content: resultString,
|
||||
tool_call_id: toolCall.id
|
||||
};
|
||||
|
||||
addMessage(toolResultMessage);
|
||||
} catch (toolError) {
|
||||
console.error(`Tool execution error for ${toolName}:`, toolError);
|
||||
|
||||
const toolErrorMessage: AIMessage = {
|
||||
role: 'tool',
|
||||
content: `Error executing tool ${toolName}: ${toolError instanceof Error ? toolError.message : 'Unknown error'}`,
|
||||
tool_call_id: toolCall.id
|
||||
};
|
||||
|
||||
addMessage(toolErrorMessage);
|
||||
}
|
||||
} else {
|
||||
// Tool not found
|
||||
const toolNotFoundMessage: AIMessage = {
|
||||
role: 'tool',
|
||||
content: `Tool ${toolName} not found`,
|
||||
tool_call_id: toolCall.id
|
||||
};
|
||||
|
||||
addMessage(toolNotFoundMessage);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('AI chat error:', error);
|
||||
|
||||
// Add error message
|
||||
const errorMessage: AIMessage = {
|
||||
id: crypto.randomUUID(),
|
||||
role: 'assistant',
|
||||
content: error instanceof Error ? error.message : 'Sorry, I encountered an error. Please try again.',
|
||||
timestamp: Date.now()
|
||||
content: error instanceof Error ? error.message : 'Sorry, I encountered an error. Please try again.'
|
||||
};
|
||||
|
||||
addMessage(errorMessage);
|
||||
@@ -108,7 +183,7 @@ export function useAIChat({
|
||||
setIsLoading(false);
|
||||
abortControllerRef.current = null;
|
||||
}
|
||||
}, [isConfigured, isLoading, addMessage, messages, settings.baseUrl, settings.apiKey, settings.model, tools, systemPrompt, onUpdateMetadata, projectName]);
|
||||
}, [isConfigured, isLoading, addMessage, messages, settings.baseUrl, settings.apiKey, settings.model, tools, customTools, systemPrompt, onUpdateMetadata, projectName]);
|
||||
|
||||
const stopGeneration = useCallback(() => {
|
||||
if (abortControllerRef.current) {
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
import OpenAI from 'openai';
|
||||
import { Tool } from './Tool';
|
||||
|
||||
/**
|
||||
* Convert a custom Tool to OpenAI's ChatCompletionTool format
|
||||
*/
|
||||
export function toolToOpenAI<TParams>(name: string, tool: Tool<TParams>): OpenAI.Chat.Completions.ChatCompletionTool {
|
||||
return {
|
||||
type: 'function',
|
||||
function: {
|
||||
name,
|
||||
description: tool.description,
|
||||
parameters: zodSchemaToJsonSchema(tool.inputSchema)
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a Zod schema to JSON Schema format for OpenAI
|
||||
*/
|
||||
function zodSchemaToJsonSchema(schema: unknown): Record<string, unknown> {
|
||||
// This is a simplified conversion. For a full implementation,
|
||||
// you might want to use a library like zod-to-json-schema
|
||||
const schemaObj = schema as { _def?: { typeName?: string; shape?: () => Record<string, unknown> } };
|
||||
|
||||
if (schemaObj._def?.typeName === 'ZodObject') {
|
||||
const properties: Record<string, unknown> = {};
|
||||
const required: string[] = [];
|
||||
|
||||
const shape = schemaObj._def.shape?.();
|
||||
if (shape) {
|
||||
for (const [key, value] of Object.entries(shape)) {
|
||||
const fieldSchema = value as { _def?: { typeName?: string } };
|
||||
properties[key] = convertZodField(fieldSchema);
|
||||
|
||||
if (!fieldSchema._def?.typeName?.includes('Optional')) {
|
||||
required.push(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
type: 'object',
|
||||
properties,
|
||||
required: required.length > 0 ? required : undefined
|
||||
};
|
||||
}
|
||||
|
||||
return { type: 'object' };
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert individual Zod field to JSON Schema
|
||||
*/
|
||||
function convertZodField(field: unknown): Record<string, unknown> {
|
||||
const fieldObj = field as {
|
||||
_def?: {
|
||||
typeName?: string;
|
||||
description?: string;
|
||||
checks?: Array<{ kind: string; value: unknown }>;
|
||||
innerType?: unknown;
|
||||
type?: unknown;
|
||||
}
|
||||
};
|
||||
|
||||
const typeName = fieldObj._def?.typeName;
|
||||
|
||||
switch (typeName) {
|
||||
case 'ZodString':
|
||||
return {
|
||||
type: 'string',
|
||||
description: fieldObj._def?.description
|
||||
};
|
||||
case 'ZodNumber':
|
||||
return {
|
||||
type: 'number',
|
||||
description: fieldObj._def?.description,
|
||||
minimum: fieldObj._def?.checks?.find((c) => c.kind === 'min')?.value
|
||||
};
|
||||
case 'ZodBoolean':
|
||||
return {
|
||||
type: 'boolean',
|
||||
description: fieldObj._def?.description
|
||||
};
|
||||
case 'ZodOptional':
|
||||
return convertZodField(fieldObj._def?.innerType);
|
||||
case 'ZodArray':
|
||||
return {
|
||||
type: 'array',
|
||||
items: convertZodField(fieldObj._def?.type),
|
||||
description: fieldObj._def?.description
|
||||
};
|
||||
default:
|
||||
return {
|
||||
type: 'string',
|
||||
description: fieldObj._def?.description || ''
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a tool with the given arguments
|
||||
*/
|
||||
export async function executeTool<TParams>(
|
||||
tool: Tool<TParams>,
|
||||
args: unknown
|
||||
): Promise<string> {
|
||||
try {
|
||||
// Parse and validate arguments using the tool's schema
|
||||
const validatedArgs = tool.inputSchema.parse(args);
|
||||
const result = await tool.execute(validatedArgs);
|
||||
|
||||
// Convert result to string for the AI
|
||||
if (typeof result === 'string') {
|
||||
return result;
|
||||
}
|
||||
|
||||
return JSON.stringify(result, null, 2);
|
||||
} catch (error) {
|
||||
throw new Error(`Tool execution failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user