mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
Added cost indicator
This commit is contained in:
4 files changed
+102
-5
No files matched your search
@@ -3,6 +3,7 @@ import { SessionManagerContext } from '@/contexts/SessionManagerContext';
|
||||
import { SessionManager } from '@/lib/SessionManager';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useProviderModels } from '@/hooks/useProviderModels';
|
||||
|
||||
interface SessionManagerProviderProps {
|
||||
children: ReactNode;
|
||||
@@ -14,10 +15,12 @@ interface SessionManagerProviderProps {
|
||||
export function SessionManagerProvider({ children }: SessionManagerProviderProps) {
|
||||
const { fs } = useFS();
|
||||
const { settings } = useAISettings();
|
||||
const { models } = useProviderModels();
|
||||
|
||||
const sessionManager = useMemo(() => {
|
||||
return new SessionManager(fs, settings);
|
||||
}, [fs, settings]);
|
||||
const getProviderModels = () => models;
|
||||
return new SessionManager(fs, settings, getProviderModels);
|
||||
}, [fs, settings, models]);
|
||||
|
||||
// Cleanup on unmount
|
||||
useEffect(() => {
|
||||
|
||||
@@ -3,6 +3,7 @@ import { useSearchParams } from 'react-router-dom';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
|
||||
import { Send, Square, Loader2, ChevronDown } from 'lucide-react';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
@@ -137,6 +138,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
messages,
|
||||
streamingMessage,
|
||||
isLoading: internalIsLoading,
|
||||
totalCost,
|
||||
sendMessage,
|
||||
startGeneration,
|
||||
stopGeneration,
|
||||
@@ -425,6 +427,22 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
|
||||
{/* Bottom Controls Row */}
|
||||
<div className="absolute bottom-2 left-2 right-2 flex items-center gap-2">
|
||||
{/* Cost Display */}
|
||||
{totalCost > 0 && (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<div className="text-xs text-muted-foreground px-2 py-1 bg-muted/50 rounded-md whitespace-nowrap cursor-help">
|
||||
${totalCost < 0.01 ? totalCost.toFixed(6) : totalCost.toFixed(4)}
|
||||
</div>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p>Total cost for this chat session</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
)}
|
||||
|
||||
{/* Model Selector */}
|
||||
<div className="flex-1 max-w-72 ml-auto overflow-hidden">
|
||||
<ModelSelector
|
||||
|
||||
+16
-1
@@ -90,7 +90,7 @@ export function useAIChat({
|
||||
initSession();
|
||||
}, [sessionManager, projectId, projectName, tools, customTools, systemPrompt, maxSteps, generatedSessionId]);
|
||||
|
||||
|
||||
|
||||
|
||||
// Subscribe to session events using shared hook
|
||||
useSessionSubscription('sessionUpdated', (updatedSessionId: string, state: SessionState) => {
|
||||
@@ -147,12 +147,26 @@ export function useAIChat({
|
||||
}
|
||||
}, [sessionId, sessionManager, onUpdateMetadata, projectName]);
|
||||
|
||||
useSessionSubscription('costUpdated', (updatedSessionId: string, _totalCost: number) => {
|
||||
if (updatedSessionId === sessionId) {
|
||||
const session = sessionManager.getSession(sessionId);
|
||||
if (session) {
|
||||
setSessionState({
|
||||
...session,
|
||||
messages: [...session.messages],
|
||||
streamingMessage: session.streamingMessage ? { ...session.streamingMessage } : undefined
|
||||
});
|
||||
}
|
||||
}
|
||||
}, [sessionId, sessionManager]);
|
||||
|
||||
|
||||
|
||||
// Derived state
|
||||
const messages = sessionState?.messages || [];
|
||||
const streamingMessage: StreamingMessage | undefined = sessionState?.streamingMessage;
|
||||
const isLoading = sessionState?.isLoading || false;
|
||||
const totalCost = sessionState?.totalCost || 0;
|
||||
|
||||
// Actions
|
||||
const sendMessage = useCallback(async (content: string, providerModel: string) => {
|
||||
@@ -202,6 +216,7 @@ export function useAIChat({
|
||||
messages,
|
||||
streamingMessage,
|
||||
isLoading,
|
||||
totalCost,
|
||||
sendMessage,
|
||||
startGeneration,
|
||||
stopGeneration,
|
||||
|
||||
@@ -43,6 +43,7 @@ export interface SessionState {
|
||||
sessionName: string;
|
||||
lastActivity: Date;
|
||||
abortController?: AbortController;
|
||||
totalCost?: number; // Total cost in USD for this session
|
||||
}
|
||||
|
||||
export interface SessionManagerEvents {
|
||||
@@ -52,6 +53,7 @@ export interface SessionManagerEvents {
|
||||
messageAdded: (sessionId: string, message: AIMessage) => void;
|
||||
streamingUpdate: (sessionId: string, content: string, toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => void;
|
||||
loadingChanged: (sessionId: string, isLoading: boolean) => void;
|
||||
costUpdated: (sessionId: string, totalCost: number) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -64,6 +66,7 @@ export class SessionManager {
|
||||
private listeners: Partial<Record<keyof SessionManagerEvents, Set<(...args: unknown[]) => void>>> = {};
|
||||
private fs: JSRuntimeFS;
|
||||
private aiSettings: { providers: Record<string, { baseURL: string; apiKey?: string }> };
|
||||
private getProviderModels?: () => Array<{ id: string; provider: string; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>;
|
||||
|
||||
// Performance constants
|
||||
private readonly MAX_SESSIONS = 50;
|
||||
@@ -71,9 +74,14 @@ export class SessionManager {
|
||||
private debouncedPersist = debounce(() => this.persistSessions(), 1000);
|
||||
private dotAI: DotAI;
|
||||
|
||||
constructor(fs: JSRuntimeFS, aiSettings: { providers: Record<string, { baseURL: string; apiKey?: string }> }) {
|
||||
constructor(
|
||||
fs: JSRuntimeFS,
|
||||
aiSettings: { providers: Record<string, { baseURL: string; apiKey?: string }> },
|
||||
getProviderModels?: () => Array<{ id: string; provider: string; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>
|
||||
) {
|
||||
this.fs = fs;
|
||||
this.aiSettings = aiSettings;
|
||||
this.getProviderModels = getProviderModels;
|
||||
this.dotAI = new DotAI(fs, '/');
|
||||
|
||||
// Load persisted sessions on initialization
|
||||
@@ -94,6 +102,7 @@ export class SessionManager {
|
||||
isLoading: false,
|
||||
sessionName: DotAI.generateSessionName(),
|
||||
lastActivity: new Date(),
|
||||
totalCost: 0,
|
||||
};
|
||||
|
||||
// Try to load existing history
|
||||
@@ -273,6 +282,7 @@ export class SessionManager {
|
||||
let finishReason: string | null = null;
|
||||
|
||||
// Process the stream
|
||||
let usage: { prompt_tokens: number; completion_tokens: number } | undefined;
|
||||
for await (const chunk of stream) {
|
||||
// Check if session was cancelled
|
||||
if (!session.isLoading) break;
|
||||
@@ -315,6 +325,14 @@ export class SessionManager {
|
||||
if (chunk.choices[0]?.finish_reason) {
|
||||
finishReason = chunk.choices[0].finish_reason;
|
||||
}
|
||||
|
||||
// Capture usage data if available (some providers include it in the final chunk)
|
||||
if (chunk.usage) {
|
||||
usage = {
|
||||
prompt_tokens: chunk.usage.prompt_tokens || 0,
|
||||
completion_tokens: chunk.usage.completion_tokens || 0
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Create final assistant message
|
||||
@@ -329,6 +347,11 @@ export class SessionManager {
|
||||
await this.addMessage(sessionId, assistantMessage);
|
||||
conversationMessages.push(assistantMessage);
|
||||
|
||||
// Update cost if usage data is available
|
||||
if (usage) {
|
||||
this.updateSessionCost(sessionId, usage, providerModel);
|
||||
}
|
||||
|
||||
// Check if we should stop
|
||||
if (finishReason === 'stop' || !accumulatedToolCalls || accumulatedToolCalls.length === 0) {
|
||||
break;
|
||||
@@ -441,8 +464,10 @@ export class SessionManager {
|
||||
session.streamingMessage = undefined;
|
||||
session.sessionName = DotAI.generateSessionName();
|
||||
session.lastActivity = new Date();
|
||||
session.totalCost = 0;
|
||||
|
||||
this.debouncedPersist();
|
||||
this.emit('costUpdated', sessionId, 0);
|
||||
this.emit('sessionUpdated', sessionId, session);
|
||||
}
|
||||
|
||||
@@ -460,6 +485,41 @@ export class SessionManager {
|
||||
conversationMessages.push(toolMessage);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update session cost based on usage data
|
||||
*/
|
||||
private updateSessionCost(sessionId: string, usage: { prompt_tokens: number; completion_tokens: number }, providerModel: string): void {
|
||||
if (!this.getProviderModels) return;
|
||||
|
||||
const session = this.sessions.get(sessionId);
|
||||
if (!session) return;
|
||||
|
||||
try {
|
||||
const parsed = parseProviderModel(providerModel, this.aiSettings.providers);
|
||||
const modelName = parsed.model;
|
||||
const providerName = parsed.provider;
|
||||
|
||||
// Find the model in provider models to get pricing
|
||||
const models = this.getProviderModels();
|
||||
const model = models.find(m => m.id === modelName && m.provider === providerName);
|
||||
|
||||
if (!model?.pricing) return;
|
||||
|
||||
// Calculate cost for this request
|
||||
const promptCost = model.pricing.prompt.mul(usage.prompt_tokens).div(1000); // pricing is per 1k tokens
|
||||
const completionCost = model.pricing.completion.mul(usage.completion_tokens).div(1000);
|
||||
const requestCost = promptCost.add(completionCost).toNumber();
|
||||
|
||||
// Update session total cost
|
||||
session.totalCost = (session.totalCost || 0) + requestCost;
|
||||
|
||||
this.emit('costUpdated', sessionId, session.totalCost);
|
||||
this.emit('sessionUpdated', sessionId, session);
|
||||
} catch (error) {
|
||||
console.warn('Failed to calculate session cost:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Save session history to file
|
||||
*/
|
||||
@@ -552,7 +612,8 @@ export class SessionManager {
|
||||
sessionData.sessions?.forEach(({ id, session }: { id: string; session: Omit<SessionState, 'lastActivity'> & { lastActivity: string } }) => {
|
||||
this.sessions.set(id, {
|
||||
...session,
|
||||
lastActivity: new Date(session.lastActivity)
|
||||
lastActivity: new Date(session.lastActivity),
|
||||
totalCost: session.totalCost || 0 // Ensure totalCost is set for older sessions
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
Reference in new issue
Block a user