-
Notifications
You must be signed in to change notification settings - Fork 249
[Prototype] AI-based formula bar #3442
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
luke-quadratic
wants to merge
15
commits into
qa
Choose a base branch
from
cell-based-ai
base: qa
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 8 commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
9d12199
init
luke-quadratic d4e54c3
updates
luke-quadratic e9d3e80
updates
luke-quadratic 168fe19
update
luke-quadratic 3030154
updates
luke-quadratic 4de89c5
update
luke-quadratic 6d53040
update
luke-quadratic 9facd3f
update
luke-quadratic 4808a62
small
luke-quadratic faf4d03
graphite
luke-quadratic 80cdb75
graphite
luke-quadratic b7ea9f9
update
luke-quadratic f2547db
dseign
luke-quadratic fed2748
update
luke-quadratic 514e051
graphite
luke-quadratic File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
152 changes: 152 additions & 0 deletions
152
quadratic-client/src/app/ai/utils/aiCodeCellSummaryStore.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,152 @@ | ||
/** | ||
* Client-side storage for AI-generated code cell summaries | ||
* This stores summaries in memory and optionally persists them to localStorage | ||
*/ | ||
|
||
interface CodeCellSummary { | ||
sheetId: string; | ||
x: number; | ||
y: number; | ||
summary: string; | ||
codeString: string; // Store code string to detect changes | ||
timestamp: number; | ||
} | ||
|
||
class AICodeCellSummaryStore { | ||
private summaries = new Map<string, CodeCellSummary>(); | ||
private readonly STORAGE_KEY = 'quadratic_ai_code_cell_summaries'; | ||
private readonly MAX_SUMMARIES = 1000; // Limit to prevent memory issues | ||
|
||
constructor() { | ||
this.loadFromStorage(); | ||
} | ||
|
||
private getKey(sheetId: string, x: number, y: number): string { | ||
return `${sheetId}:${x}:${y}`; | ||
} | ||
|
||
/** | ||
* Store a summary for an AI-generated code cell | ||
*/ | ||
setSummary(sheetId: string, x: number, y: number, summary: string, codeString: string): void { | ||
const key = this.getKey(sheetId, x, y); | ||
console.log('[aiCodeCellSummaryStore] Storing summary for key:', key, 'summary:', summary); | ||
|
||
this.summaries.set(key, { | ||
sheetId, | ||
x, | ||
y, | ||
summary, | ||
codeString, | ||
timestamp: Date.now(), | ||
}); | ||
|
||
// Limit the number of stored summaries | ||
if (this.summaries.size > this.MAX_SUMMARIES) { | ||
this.cleanupOldSummaries(); | ||
} | ||
|
||
this.saveToStorage(); | ||
console.log('[aiCodeCellSummaryStore] Total summaries stored:', this.summaries.size); | ||
} | ||
|
||
/** | ||
* Get a summary for a code cell | ||
* Returns null if no summary exists or if the code has changed | ||
*/ | ||
getSummary(sheetId: string, x: number, y: number, currentCodeString?: string): string | null { | ||
const key = this.getKey(sheetId, x, y); | ||
const summary = this.summaries.get(key); | ||
console.log('[aiCodeCellSummaryStore] Getting summary for key:', key, 'found:', !!summary); | ||
|
||
if (!summary) { | ||
console.log('[aiCodeCellSummaryStore] No summary found for key:', key); | ||
return null; | ||
} | ||
|
||
// If code has changed, remove the outdated summary | ||
if (currentCodeString && summary.codeString !== currentCodeString) { | ||
console.log('[aiCodeCellSummaryStore] Code changed, removing outdated summary for key:', key); | ||
this.summaries.delete(key); | ||
this.saveToStorage(); | ||
return null; | ||
} | ||
|
||
console.log('[aiCodeCellSummaryStore] Returning summary for key:', key, 'summary:', summary.summary); | ||
return summary.summary; | ||
} | ||
|
||
/** | ||
* Check if a code cell has an AI summary | ||
*/ | ||
hasSummary(sheetId: string, x: number, y: number): boolean { | ||
const key = this.getKey(sheetId, x, y); | ||
return this.summaries.has(key); | ||
} | ||
|
||
/** | ||
* Remove a summary for a code cell | ||
*/ | ||
removeSummary(sheetId: string, x: number, y: number): void { | ||
const key = this.getKey(sheetId, x, y); | ||
this.summaries.delete(key); | ||
this.saveToStorage(); | ||
} | ||
|
||
/** | ||
* Clear all summaries for a sheet | ||
*/ | ||
clearSheet(sheetId: string): void { | ||
for (const [key, summary] of this.summaries.entries()) { | ||
if (summary.sheetId === sheetId) { | ||
this.summaries.delete(key); | ||
} | ||
} | ||
this.saveToStorage(); | ||
} | ||
|
||
/** | ||
* Clean up old summaries to prevent memory issues | ||
*/ | ||
private cleanupOldSummaries(): void { | ||
const entries = Array.from(this.summaries.entries()); | ||
entries.sort((a, b) => a[1].timestamp - b[1].timestamp); | ||
|
||
// Remove oldest 20% of summaries | ||
const toRemove = Math.floor(entries.length * 0.2); | ||
for (let i = 0; i < toRemove; i++) { | ||
this.summaries.delete(entries[i][0]); | ||
} | ||
} | ||
|
||
/** | ||
* Save summaries to localStorage | ||
*/ | ||
private saveToStorage(): void { | ||
try { | ||
const data = Array.from(this.summaries.entries()); | ||
localStorage.setItem(this.STORAGE_KEY, JSON.stringify(data)); | ||
} catch (error) { | ||
console.warn('Failed to save AI code cell summaries to localStorage:', error); | ||
} | ||
} | ||
|
||
/** | ||
* Load summaries from localStorage | ||
*/ | ||
private loadFromStorage(): void { | ||
try { | ||
const data = localStorage.getItem(this.STORAGE_KEY); | ||
if (data) { | ||
const entries: [string, CodeCellSummary][] = JSON.parse(data); | ||
this.summaries = new Map(entries); | ||
} | ||
} catch (error) { | ||
console.warn('Failed to load AI code cell summaries from localStorage:', error); | ||
this.summaries.clear(); | ||
} | ||
} | ||
} | ||
|
||
// Export a singleton instance | ||
export const aiCodeCellSummaryStore = new AICodeCellSummaryStore(); |
167 changes: 167 additions & 0 deletions
167
quadratic-client/src/app/ai/utils/generateCodeCellSummary.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,167 @@ | ||
import { pixiAppSettings } from '@/app/gridGL/pixiApp/PixiAppSettings'; | ||
import { xyToA1 } from '@/app/quadratic-core/quadratic_core'; | ||
import { authClient } from '@/auth/auth'; | ||
import { apiClient } from '@/shared/api/apiClient'; | ||
import { createTextContent } from 'quadratic-shared/ai/helpers/message.helper'; | ||
import { v4 as uuidv4 } from 'uuid'; | ||
|
||
/** | ||
* Generates a concise summary of what a code cell does using AI | ||
*/ | ||
export const generateCodeCellSummary = async ( | ||
codeString: string, | ||
language: string, | ||
x?: number, | ||
y?: number, | ||
signal?: AbortSignal | ||
): Promise<string> => { | ||
try { | ||
console.log('[generateCodeCellSummary] Generating AI summary for:', language, codeString.substring(0, 100) + '...'); | ||
|
||
// Get file UUID from pixiAppSettings | ||
const fileUuid = pixiAppSettings.editorInteractionState.fileUuid; | ||
if (!fileUuid) { | ||
console.warn('[generateCodeCellSummary] No file UUID available, falling back to simple summary'); | ||
return getFallbackSummary(codeString, language); | ||
} | ||
|
||
// Generate cell reference if coordinates are provided | ||
const cellRef = x !== undefined && y !== undefined ? xyToA1(x, y) : null; | ||
const cellLocationText = cellRef ? ` at ${cellRef}` : ''; | ||
|
||
// Prepare AI request following the same pattern as useAIRequestToAPI | ||
const chatId = uuidv4(); | ||
const messages = [ | ||
{ | ||
role: 'user' as const, | ||
content: [ | ||
createTextContent(`Analyze this ${language} code and provide a response in this exact format: | ||
|
||
[One concise sentence describing what the code does${cellLocationText} - LIMIT THIS FIRST LINE TO EXACTLY 12 WORDS OR FEWER] | ||
|
||
1. [First key step or operation] | ||
2. [Second key step or operation] | ||
3. [Continue with additional steps as needed] | ||
|
||
Code to analyze: | ||
\`\`\`${language.toLowerCase()} | ||
${codeString} | ||
\`\`\` | ||
|
||
Start with the summary sentence${cellLocationText ? ` (include the cell location ${cellRef} in the sentence)` : ''}, then provide numbered steps. Be concise but informative. IMPORTANT: The first line summary sentence must be 12 words or fewer.`), | ||
], | ||
contextType: 'userPrompt' as const, | ||
}, | ||
]; | ||
|
||
// Make AI request using the same structure as handleAIRequestToAPI | ||
const endpoint = `${apiClient.getApiUrl()}/v0/ai/chat`; | ||
const token = await authClient.getTokenOrRedirect(); | ||
|
||
const requestBody = { | ||
chatId, | ||
fileUuid, | ||
messageSource: 'CodeCellSummary', | ||
modelKey: 'vertexai:gemini-2.5-flash:thinking-toggle-off' as const, | ||
source: 'AIAssistant' as const, | ||
messages, | ||
useToolsPrompt: false, | ||
useQuadraticContext: false, | ||
useStream: false, | ||
toolName: undefined, | ||
language: undefined, | ||
}; | ||
|
||
const response = await fetch(endpoint, { | ||
method: 'POST', | ||
signal, | ||
headers: { | ||
Authorization: `Bearer ${token}`, | ||
'Content-Type': 'application/json', | ||
}, | ||
body: JSON.stringify(requestBody), | ||
}); | ||
|
||
if (!response.ok) { | ||
console.warn('[generateCodeCellSummary] AI request failed, falling back to simple summary'); | ||
return getFallbackSummary(codeString, language); | ||
} | ||
|
||
const aiResponse = await response.json(); | ||
|
||
// Extract text content from AI response | ||
if (aiResponse.content && aiResponse.content.length > 0) { | ||
const textContent = aiResponse.content.find((c: any) => c.type === 'text'); | ||
if (textContent && textContent.text) { | ||
const fullResponse = textContent.text.trim(); | ||
console.log('[generateCodeCellSummary] AI generated response:', fullResponse); | ||
|
||
// Parse the response to extract summary and explanation | ||
const lines = fullResponse.split('\n'); | ||
const summaryLine = lines[0]?.trim(); | ||
|
||
// If we have a multi-line response, store both parts | ||
if (lines.length > 1) { | ||
const explanation = lines.slice(1).join('\n').trim(); | ||
// Store the full response for the expanded view | ||
return JSON.stringify({ | ||
summary: summaryLine, | ||
explanation: explanation, | ||
fullText: fullResponse, | ||
}); | ||
} | ||
|
||
// Fallback to just the summary if no explanation | ||
return summaryLine || fullResponse; | ||
} | ||
} | ||
|
||
console.warn('[generateCodeCellSummary] No valid content in AI response, falling back to simple summary'); | ||
return getFallbackSummary(codeString, language); | ||
} catch (error) { | ||
console.error('[generateCodeCellSummary] Error in AI summary generation:', error); | ||
return getFallbackSummary(codeString, language); | ||
} | ||
}; | ||
|
||
/** | ||
* Fallback summary generation for when AI is unavailable | ||
*/ | ||
function getFallbackSummary(codeString: string, language: string): string { | ||
const lowerCode = codeString.toLowerCase(); | ||
|
||
// Quick pattern matching for common cases | ||
if ( | ||
lowerCode.includes('plot') || | ||
lowerCode.includes('chart') || | ||
lowerCode.includes('matplotlib') || | ||
lowerCode.includes('plotly') | ||
) { | ||
return 'Creates a data visualization'; | ||
} | ||
|
||
if (lowerCode.includes('pandas') || lowerCode.includes('dataframe')) { | ||
return 'Processes data using pandas'; | ||
} | ||
|
||
if (lowerCode.includes('sum(') || lowerCode.includes('.sum()')) { | ||
return 'Calculates sum of values'; | ||
} | ||
|
||
if (lowerCode.includes('mean(') || lowerCode.includes('.mean()')) { | ||
return 'Calculates average of values'; | ||
} | ||
|
||
if (lowerCode.includes('read_csv') || lowerCode.includes('read_excel')) { | ||
return 'Loads data from file'; | ||
} | ||
|
||
// Generic fallbacks | ||
if (language === 'Python') { | ||
return 'Executes Python code'; | ||
} else if (language === 'Javascript') { | ||
return 'Executes JavaScript code'; | ||
} else { | ||
return `Executes ${language} code`; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
import { atom } from 'recoil'; | ||
|
||
export const formulaBarExpandedAtom = atom({ | ||
key: 'formulaBarExpanded', | ||
default: false, | ||
}); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.