mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
Support reasoning_content
This commit is contained in:
5 files changed
+169
-8
No files matched your search
@@ -1,24 +1,32 @@
|
||||
import { memo, useState } from 'react';
|
||||
import { Streamdown } from 'streamdown';
|
||||
import { Wrench, Eye, FileText, Edit, Package, PackageMinus, GitCommit, BookOpen, Download, Hash, Tag, Network, List, Plus, Terminal, Globe, CheckCircle } from 'lucide-react';
|
||||
import { Wrench, Eye, FileText, Edit, Package, PackageMinus, GitCommit, BookOpen, Download, Hash, Tag, Network, List, Plus, Terminal, Globe, CheckCircle, Brain } from 'lucide-react';
|
||||
import type { AIMessage } from '@/lib/SessionManager';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { UserMessage } from '@/components/UserMessage';
|
||||
import OpenAI from 'openai';
|
||||
import { useTheme } from '@/hooks/useTheme';
|
||||
|
||||
// Type guard to check if message has reasoning content
|
||||
function hasReasoningContent(message: AIMessage): message is AIMessage & { reasoning_content: string } {
|
||||
return message.role === 'assistant' && 'reasoning_content' in message && typeof (message as { reasoning_content?: unknown }).reasoning_content === 'string';
|
||||
}
|
||||
|
||||
interface AIMessageItemProps {
|
||||
message: AIMessage;
|
||||
isCurrentlyLoading?: boolean;
|
||||
toolCall?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall | undefined; // Tool call data passed from the assistant message
|
||||
reasoningContent?: string; // Reasoning content for streaming messages
|
||||
}
|
||||
|
||||
export const AIMessageItem = memo(({
|
||||
message,
|
||||
isCurrentlyLoading = false,
|
||||
toolCall
|
||||
toolCall,
|
||||
reasoningContent
|
||||
}: AIMessageItemProps) => {
|
||||
const [isToolExpanded, setIsToolExpanded] = useState(false);
|
||||
const [isReasoningExpanded, setIsReasoningExpanded] = useState(false);
|
||||
const { displayTheme } = useTheme();
|
||||
|
||||
// Get content to display
|
||||
@@ -230,6 +238,39 @@ export const AIMessageItem = memo(({
|
||||
<div className="flex">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-sm">
|
||||
{/* Reasoning content display */}
|
||||
{((reasoningContent && reasoningContent.trim()) ||
|
||||
(hasReasoningContent(message) && message.reasoning_content.trim())) && (
|
||||
<div className="mb-3">
|
||||
<button
|
||||
onClick={() => setIsReasoningExpanded(!isReasoningExpanded)}
|
||||
className={cn(
|
||||
"w-full flex items-center gap-2 px-2 py-1 text-xs",
|
||||
"hover:bg-muted/30 rounded transition-colors duration-200"
|
||||
)}
|
||||
>
|
||||
<Brain className="h-3 w-3 text-muted-foreground flex-shrink-0" />
|
||||
<span className="text-muted-foreground font-medium flex-1 text-left">
|
||||
Thinking
|
||||
</span>
|
||||
</button>
|
||||
|
||||
{isReasoningExpanded && (
|
||||
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs">
|
||||
<div className="whitespace-pre-wrap break-words">
|
||||
<Streamdown
|
||||
className='size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0'
|
||||
parseIncompleteMarkdown={isCurrentlyLoading}
|
||||
shikiTheme={displayTheme === 'dark' ? 'github-dark' : 'github-light'}
|
||||
>
|
||||
{reasoningContent || (hasReasoningContent(message) ? message.reasoning_content : '') || ''}
|
||||
</Streamdown>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="break-words">
|
||||
<Streamdown
|
||||
className='size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0'
|
||||
|
||||
@@ -491,11 +491,12 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
);
|
||||
})}
|
||||
{streamingMessage && (
|
||||
streamingMessage.content ? (
|
||||
streamingMessage.content || streamingMessage.reasoning_content ? (
|
||||
<AIMessageItem
|
||||
key="streaming-message"
|
||||
message={streamingMessage}
|
||||
isCurrentlyLoading={isLoading}
|
||||
reasoningContent={streamingMessage.reasoning_content}
|
||||
/>
|
||||
) : (
|
||||
!(streamingMessage?.tool_calls?.[0]?.type === 'function') && (
|
||||
|
||||
@@ -18,6 +18,7 @@ interface UseAIChatSessionOptions {
|
||||
interface StreamingMessage {
|
||||
role: 'assistant';
|
||||
content: string;
|
||||
reasoning_content?: string;
|
||||
tool_calls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[];
|
||||
}
|
||||
|
||||
@@ -68,16 +69,18 @@ export function useAIChat({
|
||||
setStreamingMessage({
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
reasoning_content: '',
|
||||
});
|
||||
}
|
||||
}
|
||||
}, [projectId]);
|
||||
|
||||
useSessionSubscription('streamingUpdate', (updatedProjectId: string, content: string, toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => {
|
||||
useSessionSubscription('streamingUpdate', (updatedProjectId: string, content: string, reasoningContent?: string, toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => {
|
||||
if (updatedProjectId === projectId) {
|
||||
setStreamingMessage({
|
||||
role: 'assistant',
|
||||
content,
|
||||
reasoning_content: reasoningContent,
|
||||
tool_calls: toolCalls
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { SessionManager, type AIMessage } from './SessionManager';
|
||||
import type { JSRuntimeFS } from './JSRuntime';
|
||||
|
||||
// Mock the filesystem
|
||||
const mockFS: JSRuntimeFS = {
|
||||
readFile: vi.fn(),
|
||||
writeFile: vi.fn(),
|
||||
readdir: vi.fn(),
|
||||
mkdir: vi.fn(),
|
||||
rmdir: vi.fn(),
|
||||
unlink: vi.fn(),
|
||||
stat: vi.fn(),
|
||||
exists: vi.fn(),
|
||||
copyFile: vi.fn(),
|
||||
rename: vi.fn(),
|
||||
symlink: vi.fn(),
|
||||
readlink: vi.fn(),
|
||||
chmod: vi.fn(),
|
||||
chown: vi.fn(),
|
||||
utimes: vi.fn(),
|
||||
realpath: vi.fn(),
|
||||
} as unknown as JSRuntimeFS;
|
||||
|
||||
describe('SessionManager', () => {
|
||||
let sessionManager: SessionManager;
|
||||
const mockAISettings = {
|
||||
providers: {
|
||||
'test-provider': {
|
||||
baseURL: 'https://api.test.com',
|
||||
apiKey: 'test-key'
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
sessionManager = new SessionManager(mockFS, mockAISettings);
|
||||
});
|
||||
|
||||
it('should initialize streaming message with reasoning content', async () => {
|
||||
const projectId = 'test-project';
|
||||
const tools = {};
|
||||
const customTools = {};
|
||||
|
||||
const session = await sessionManager.loadSession(projectId, tools, customTools);
|
||||
|
||||
expect(session.projectId).toBe(projectId);
|
||||
expect(session.streamingMessage).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should emit streamingUpdate events with reasoning content', () => {
|
||||
const projectId = 'test-project';
|
||||
const mockListener = vi.fn();
|
||||
|
||||
sessionManager.on('streamingUpdate', mockListener);
|
||||
|
||||
// Simulate a streaming update with reasoning content
|
||||
sessionManager.emit('streamingUpdate', projectId, 'content', 'reasoning', undefined);
|
||||
|
||||
expect(mockListener).toHaveBeenCalledWith(projectId, 'content', 'reasoning', undefined);
|
||||
});
|
||||
|
||||
it('should handle streaming message with reasoning content', async () => {
|
||||
const projectId = 'test-project';
|
||||
const tools = {};
|
||||
const customTools = {};
|
||||
|
||||
const session = await sessionManager.loadSession(projectId, tools, customTools);
|
||||
|
||||
// Manually set a streaming message to test the structure
|
||||
session.streamingMessage = {
|
||||
role: 'assistant',
|
||||
content: 'test content',
|
||||
reasoning_content: 'test reasoning',
|
||||
tool_calls: undefined
|
||||
};
|
||||
|
||||
expect(session.streamingMessage.reasoning_content).toBe('test reasoning');
|
||||
expect(session.streamingMessage.content).toBe('test content');
|
||||
});
|
||||
|
||||
it('should support assistant messages with reasoning content', () => {
|
||||
// Test that AIMessage type supports reasoning content
|
||||
const messageWithReasoning: AIMessage = {
|
||||
role: 'assistant',
|
||||
content: 'Here is my response',
|
||||
reasoning_content: 'Let me think about this step by step...'
|
||||
};
|
||||
|
||||
expect(messageWithReasoning.role).toBe('assistant');
|
||||
expect(messageWithReasoning.content).toBe('Here is my response');
|
||||
expect('reasoning_content' in messageWithReasoning).toBe(true);
|
||||
if ('reasoning_content' in messageWithReasoning) {
|
||||
expect(messageWithReasoning.reasoning_content).toBe('Let me think about this step by step...');
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -6,7 +6,12 @@ import { createAIClient } from './ai-client';
|
||||
import type { Tool } from './tools/Tool';
|
||||
import type { NUser } from '@nostrify/react/login';
|
||||
|
||||
export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam;
|
||||
export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam | {
|
||||
role: 'assistant';
|
||||
content: string;
|
||||
reasoning_content?: string;
|
||||
tool_calls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[];
|
||||
};
|
||||
|
||||
export interface SessionState {
|
||||
projectId: string;
|
||||
@@ -18,6 +23,7 @@ export interface SessionState {
|
||||
streamingMessage?: {
|
||||
role: 'assistant';
|
||||
content: string;
|
||||
reasoning_content?: string;
|
||||
tool_calls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[];
|
||||
};
|
||||
isLoading: boolean;
|
||||
@@ -32,7 +38,7 @@ export interface SessionManagerEvents {
|
||||
sessionCreated: (projectId: string) => void;
|
||||
sessionDeleted: (projectId: string) => void;
|
||||
messageAdded: (projectId: string, message: AIMessage) => void;
|
||||
streamingUpdate: (projectId: string, content: string, toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => void;
|
||||
streamingUpdate: (projectId: string, content: string, reasoningContent?: string, toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => void;
|
||||
loadingChanged: (projectId: string, isLoading: boolean) => void;
|
||||
costUpdated: (projectId: string, totalCost: number) => void;
|
||||
contextUsageUpdated: (projectId: string, inputTokens: number) => void;
|
||||
@@ -219,6 +225,7 @@ export class SessionManager {
|
||||
session.streamingMessage = {
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
reasoning_content: '',
|
||||
tool_calls: undefined
|
||||
};
|
||||
|
||||
@@ -245,6 +252,7 @@ export class SessionManager {
|
||||
});
|
||||
|
||||
let accumulatedContent = '';
|
||||
let accumulatedReasoningContent = '';
|
||||
const accumulatedToolCalls: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[] = [];
|
||||
let finishReason: string | null = null;
|
||||
|
||||
@@ -260,7 +268,17 @@ export class SessionManager {
|
||||
accumulatedContent += delta.content;
|
||||
if (session.streamingMessage) {
|
||||
session.streamingMessage.content += delta.content;
|
||||
this.emit('streamingUpdate', projectId, session.streamingMessage.content, session.streamingMessage.tool_calls);
|
||||
this.emit('streamingUpdate', projectId, session.streamingMessage.content, session.streamingMessage.reasoning_content, session.streamingMessage.tool_calls);
|
||||
}
|
||||
}
|
||||
|
||||
// Handle reasoning content if present (some providers may include this)
|
||||
const deltaWithReasoning = delta as { reasoning_content?: string };
|
||||
if (deltaWithReasoning?.reasoning_content) {
|
||||
accumulatedReasoningContent += deltaWithReasoning.reasoning_content;
|
||||
if (session.streamingMessage) {
|
||||
session.streamingMessage.reasoning_content += deltaWithReasoning.reasoning_content;
|
||||
this.emit('streamingUpdate', projectId, session.streamingMessage.content, session.streamingMessage.reasoning_content, session.streamingMessage.tool_calls);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -283,7 +301,7 @@ export class SessionManager {
|
||||
|
||||
if (session.streamingMessage) {
|
||||
session.streamingMessage.tool_calls = accumulatedToolCalls.length > 0 ? accumulatedToolCalls : undefined;
|
||||
this.emit('streamingUpdate', projectId, session.streamingMessage.content, session.streamingMessage.tool_calls);
|
||||
this.emit('streamingUpdate', projectId, session.streamingMessage.content, session.streamingMessage.reasoning_content, session.streamingMessage.tool_calls);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -304,6 +322,7 @@ export class SessionManager {
|
||||
const assistantMessage: AIMessage = {
|
||||
role: 'assistant',
|
||||
content: accumulatedContent,
|
||||
...(accumulatedReasoningContent && { reasoning_content: accumulatedReasoningContent }),
|
||||
...(accumulatedToolCalls.length > 0 && { tool_calls: accumulatedToolCalls })
|
||||
};
|
||||
|
||||
|
||||
Reference in new issue
Block a user