pocket-tutor 1.0.0 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -0
- package/bin/pocket-tutor.js +71 -1
- package/package.json +1 -1
- package/src/main.js +37 -1
- package/src/setup.js +60 -0
- package/src/tools.js +102 -0
package/README.md
CHANGED
|
@@ -76,6 +76,20 @@ With a workspace, the model gets a short overview (the project name, its depende
|
|
|
76
76
|
|
|
77
77
|
It also keeps a small graph of what you looked up before (idea names, one-sentence summaries, file paths), so a later answer can build on an earlier one. The graph lives in `%USERPROFILE%\.pocket-tutor\graph.json`. Choose **Forget saved context** in the tray menu to delete it.
|
|
78
78
|
|
|
79
|
+
## In the terminal
|
|
80
|
+
|
|
81
|
+
These work on any system, with the same model settings. No tray app is needed.
|
|
82
|
+
|
|
83
|
+
```
|
|
84
|
+
pocket-tutor setup pick a model, paste a key, test it, save it
|
|
85
|
+
pocket-tutor diff explain your uncommitted changes and what could break
|
|
86
|
+
pocket-tutor diff HEAD~1 the same for the last commit (any git diff arguments work)
|
|
87
|
+
pocket-tutor review a short quiz on the things you keep looking up
|
|
88
|
+
pocket-tutor explain --image shot.png "what is this?"
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
`diff` drops secret files such as `.env` and masks keys before anything leaves your laptop. It only knows what is in the diff, so check its claims against the code. `review` uses the lookups saved in `~/.pocket-tutor/graph.json`. `--image` needs a model that reads images, such as gpt-4o-mini or Gemini. The free Nemotron model does not, and says so.
|
|
92
|
+
|
|
79
93
|
## Math animations with ManimGL
|
|
80
94
|
|
|
81
95
|
For a formula, Pocket Tutor can draw a short animation: the formula is typeset, built piece by piece, and each part gets a colour and a plain-English note. It uses [ManimGL](https://github.com/3b1b/manim), the animation engine Grant Sanderson (3Blue1Brown) wrote for his videos. It is MIT licensed, and it is not the separate Manim Community Edition.
|
package/bin/pocket-tutor.js
CHANGED
|
@@ -2,6 +2,10 @@
|
|
|
2
2
|
// pocket-tutor: the command line for the package.
|
|
3
3
|
// pocket-tutor start the tray app (Windows): select text anywhere, press the hotkey
|
|
4
4
|
// pocket-tutor explain [text] explain text in the terminal (any OS); reads stdin when no text is given
|
|
5
|
+
// pocket-tutor setup pick a model and save it (no JSON editing)
|
|
6
|
+
// pocket-tutor diff [git args] what a code change does and what could break
|
|
7
|
+
// pocket-tutor review a short quiz on what you keep looking up
|
|
8
|
+
// pocket-tutor explain --image file.png explain a screenshot (needs a model that reads images)
|
|
5
9
|
// pocket-tutor doctor check the model, web search, math clips and git
|
|
6
10
|
// pocket-tutor setup-visuals optional: install ManimGL for math animations
|
|
7
11
|
const path = require('path')
|
|
@@ -12,6 +16,10 @@ const HELP = `Pocket Tutor: select any text, get a short explanation in plain En
|
|
|
12
16
|
|
|
13
17
|
pocket-tutor start the tray app (Windows). Select text, press Ctrl+Alt+Space
|
|
14
18
|
pocket-tutor explain [text] explain text here in the terminal; reads stdin if no text is given
|
|
19
|
+
pocket-tutor setup pick a model and save it, no JSON editing
|
|
20
|
+
pocket-tutor diff [git args] explain a code change and what could break (default: all uncommitted changes)
|
|
21
|
+
pocket-tutor review a short quiz on the things you keep looking up
|
|
22
|
+
pocket-tutor explain --image file.png explain a screenshot or chart (needs a model that reads images)
|
|
15
23
|
pocket-tutor doctor check the model, web search, math animations and git
|
|
16
24
|
pocket-tutor setup-visuals optional: install ManimGL, which draws math animations
|
|
17
25
|
|
|
@@ -21,15 +29,74 @@ Model: any OpenAI-compatible server. Examples (PowerShell):
|
|
|
21
29
|
$env:AI_GATEWAY_API_KEY="..." free Nemotron through Vercel
|
|
22
30
|
More: https://github.com/advaithsarva/pocket-tutor`
|
|
23
31
|
|
|
32
|
+
function stream(model, cfg, messages, maxTokens = 1200) {
|
|
33
|
+
let shown = 0
|
|
34
|
+
return model.chat(cfg, cfg.model, messages, { maxTokens, onChunk: (t) => { process.stdout.write(t.slice(shown)); shown = t.length } })
|
|
35
|
+
.then((out) => { process.stdout.write(out.slice(shown) + '\n'); return 0 })
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function ready() {
|
|
39
|
+
const cfg = require('../src/config').load()
|
|
40
|
+
if (!cfg.llm_key) { console.error('No model set up. Run: pocket-tutor setup'); return null }
|
|
41
|
+
return cfg
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async function diff(args) {
|
|
45
|
+
const model = require('../src/model'), tools = require('../src/tools')
|
|
46
|
+
const cfg = ready(); if (!cfg) return 2
|
|
47
|
+
let d
|
|
48
|
+
try { d = tools.readDiff(args) } catch (e) { console.error(`Could not read the diff: ${e.stderr ? String(e.stderr).trim() : e.message}`); return 2 }
|
|
49
|
+
if (!d.trim()) { console.error('No changes to explain.'); return 2 }
|
|
50
|
+
try { return await stream(model, cfg, tools.diffMessages(d, require('../src/project').profile(process.cwd()))) }
|
|
51
|
+
catch (e) { console.error(`Could not explain this: ${e.message}`); return 1 }
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async function review() {
|
|
55
|
+
const model = require('../src/model'), tools = require('../src/tools'), config = require('../src/config'), graph = require('../src/graph')
|
|
56
|
+
const cfg = ready(); if (!cfg) return 2
|
|
57
|
+
const concepts = tools.pickConcepts(graph.load(config.GRAPH))
|
|
58
|
+
if (!concepts.length) { console.error('Nothing to review yet. Look a few things up first, then run this again.'); return 2 }
|
|
59
|
+
const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout })
|
|
60
|
+
// read lines from a queue made up front, so piped input that ends early still works
|
|
61
|
+
const lines = rl[Symbol.asyncIterator]()
|
|
62
|
+
const ask = async (q) => { process.stdout.write(q); const l = await lines.next(); return l.done ? '' : l.value }
|
|
63
|
+
try {
|
|
64
|
+
const quiz = tools.parseQuiz(await model.chat(cfg, cfg.model, tools.quizMessages(concepts), { json: true, maxTokens: 600 }), concepts)
|
|
65
|
+
let n = 0
|
|
66
|
+
for (const q of quiz) {
|
|
67
|
+
const a = (await ask(`
|
|
68
|
+
${q.concept}: ${q.question}
|
|
69
|
+
> `)).trim()
|
|
70
|
+
const g = await model.chat(cfg, cfg.model, tools.gradeMessages(q, a), { maxTokens: 120 })
|
|
71
|
+
console.log(g); if (/^right/i.test(g)) n++
|
|
72
|
+
}
|
|
73
|
+
console.log(`
|
|
74
|
+
${n} of ${quiz.length} right.`)
|
|
75
|
+
return 0
|
|
76
|
+
} catch (e) { console.error(`Could not run the review: ${e.message}`); return 1 }
|
|
77
|
+
finally { rl.close() }
|
|
78
|
+
}
|
|
79
|
+
|
|
24
80
|
async function explain(args) {
|
|
25
81
|
const config = require('../src/config')
|
|
26
82
|
const model = require('../src/model')
|
|
27
83
|
const { mask } = require('../src/privacy')
|
|
84
|
+
const at = args.indexOf('--image')
|
|
85
|
+
if (at >= 0) {
|
|
86
|
+
const tools = require('../src/tools')
|
|
87
|
+
const file = args[at + 1]
|
|
88
|
+
if (!file) { console.error('Pass the image: pocket-tutor explain --image screenshot.png ["a question"]'); return 2 }
|
|
89
|
+
const cfg = ready(); if (!cfg) return 2
|
|
90
|
+
try {
|
|
91
|
+
const q = mask(args.filter((_, i) => i !== at && i !== at + 1).join(' ').trim())
|
|
92
|
+
return await stream(model, cfg, tools.imageMessages(tools.imageDataUrl(file), q))
|
|
93
|
+
} catch (e) { console.error(`Could not explain this image: ${String(e.message).replace(/\.$/, '')}. This model may not read images; try a vision model such as gpt-4o-mini or gemini.`); return 1 }
|
|
94
|
+
}
|
|
28
95
|
let text = args.join(' ').trim()
|
|
29
96
|
if (!text && !process.stdin.isTTY) { let s = ''; for await (const c of process.stdin) s += c; text = s.trim() }
|
|
30
97
|
if (!text) { console.error('Nothing to explain. Pass some text, or pipe it in: echo "RMSNorm" | pocket-tutor explain'); return 2 }
|
|
31
98
|
const cfg = config.load()
|
|
32
|
-
if (!cfg.llm_key) { console.error('No model set up. Run: pocket-tutor
|
|
99
|
+
if (!cfg.llm_key) { console.error('No model set up. Run: pocket-tutor setup'); return 2 }
|
|
33
100
|
const selection = mask(text).slice(0, model.MAX_SELECTION)
|
|
34
101
|
let shown = 0
|
|
35
102
|
try {
|
|
@@ -44,6 +111,9 @@ async function main() {
|
|
|
44
111
|
const [cmd, ...rest] = process.argv.slice(2)
|
|
45
112
|
if (cmd === 'help' || cmd === '--help' || cmd === '-h') return console.log(HELP)
|
|
46
113
|
if (cmd === 'explain') return process.exit(await explain(rest))
|
|
114
|
+
if (cmd === 'setup') return process.exit(await require('../src/setup').run())
|
|
115
|
+
if (cmd === 'diff') return process.exit(await diff(rest))
|
|
116
|
+
if (cmd === 'review') return process.exit(await review())
|
|
47
117
|
if (cmd === 'doctor') return require('../scripts/doctor.js')
|
|
48
118
|
if (cmd === 'setup-visuals') return require('../scripts/setup-visuals.js')
|
|
49
119
|
if (cmd && cmd !== 'start') { console.error(`Unknown command "${cmd}".\n\n${HELP}`); return process.exit(2) }
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pocket-tutor",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.1.0",
|
|
4
4
|
"description": "Select any text, press a hotkey, get a plain-English explanation. Works with any OpenAI-compatible model, including local Ollama. Windows tray app plus a terminal command.",
|
|
5
5
|
"main": "src/main.js",
|
|
6
6
|
"scripts": {
|
package/src/main.js
CHANGED
|
@@ -84,6 +84,42 @@ function selfTest(out) {
|
|
|
84
84
|
fs.writeFileSync(out, (await popup.webContents.capturePage()).toPNG())
|
|
85
85
|
return app.exit(0)
|
|
86
86
|
}
|
|
87
|
+
// POCKET_TUTOR_SELFTEST_SHAKE=1: stream a long answer into the detail window in small chunks and measure, after
|
|
88
|
+
// every chunk, whether any block that was already on screen moved or vanished. Appending text must never do that.
|
|
89
|
+
if (process.env.POCKET_TUTOR_SELFTEST_SHAKE) {
|
|
90
|
+
last = { id: 1, selection: 'RMSNorm', where: {}, plan: { concept: 'RMSNorm', related: ['LayerNorm'] }, snippets: [], web: [], notes: [], video: null, detail: '' }
|
|
91
|
+
await createDetail()
|
|
92
|
+
detail.show()
|
|
93
|
+
sendDetail({ id: 1, phase: 'start', title: 'RMSNorm', snippets: [], web: [], related: ['LayerNorm'], notes: [], video: null })
|
|
94
|
+
const para = 'RMSNorm keeps the numbers in a layer at a steady size, so training stays stable and the next layer sees values it can use. '
|
|
95
|
+
const doc = ['## What it is', para.repeat(3), '## How it works', '1. Square every number in the vector.\n2. Average the squares.\n3. Take the square root and divide.',
|
|
96
|
+
'```python\nclass RMSNorm(nn.Module):\n def forward(self, x):\n return x / x.pow(2).mean(-1, keepdim=True).sqrt()\n```',
|
|
97
|
+
'The scale is $\gamma \cdot \frac{x}{\sqrt{\frac{1}{d}\sum_i x_i^2}}$ for each vector.', '$$y = \frac{x}{\text{RMS}(x)} \cdot g$$',
|
|
98
|
+
'## Why it matters', para.repeat(6), '## Example', para.repeat(4)].join('\n\n')
|
|
99
|
+
const probe = `(() => [...document.querySelectorAll('h1,h2,h3,p,li,pre')].map((e) => [(e.textContent || '').trim().slice(0, 24), Math.round(e.getBoundingClientRect().top + window.scrollY)]))()`
|
|
100
|
+
let prev = [], moved = 0, vanished = 0, frames = 0, shrank = 0, lastH = 0
|
|
101
|
+
const lines = []
|
|
102
|
+
for (let i = 40; i <= doc.length + 40; i += 40) {
|
|
103
|
+
sendDetail({ id: 1, phase: 'answer', text: model.fixHeadings(doc.slice(0, i)) })
|
|
104
|
+
await new Promise((r) => setTimeout(r, 140))
|
|
105
|
+
const now = await detail.webContents.executeJavaScript(probe)
|
|
106
|
+
frames++
|
|
107
|
+
// the page must only grow while text is added: a shrink means something was drawn one way, then redrawn
|
|
108
|
+
const h = await detail.webContents.executeJavaScript('document.documentElement.scrollHeight')
|
|
109
|
+
if (h < lastH - 2) { shrank++; lines.push(`frame ${frames}: page got shorter ${lastH} -> ${h}`) }
|
|
110
|
+
lastH = h
|
|
111
|
+
// every block but the newest one was complete before this chunk: it must still be there, in the same place
|
|
112
|
+
for (let k = 0; k < prev.length - 1; k++) {
|
|
113
|
+
if (!now[k] || now[k][0] !== prev[k][0]) { vanished++; lines.push(`frame ${frames}: block ${k} "${prev[k][0]}" changed or vanished`); break }
|
|
114
|
+
if (now[k][1] !== prev[k][1]) { moved++; lines.push(`frame ${frames}: block ${k} "${prev[k][0]}" moved ${prev[k][1]} -> ${now[k][1]}`) }
|
|
115
|
+
}
|
|
116
|
+
prev = now
|
|
117
|
+
}
|
|
118
|
+
sendDetail({ id: 1, phase: 'answer', text: model.fixHeadings(doc), done: true })
|
|
119
|
+
log(`shake test: ${frames} frames, ${moved} moves of earlier blocks, ${vanished} vanished or rewritten blocks, ${shrank} times the page got shorter`)
|
|
120
|
+
for (const l of lines.slice(0, 12)) log(' ', l)
|
|
121
|
+
return app.exit(moved || vanished || shrank ? 1 : 0)
|
|
122
|
+
}
|
|
87
123
|
send('state', { id: 1, phase: 'start' })
|
|
88
124
|
send('state', { id: 1, phase: 'sources', snippets: [{ file: 'src/model/norm.py', line: 7 }] })
|
|
89
125
|
send('state', { id: 1, phase: 'answer', text: '**RMSNorm** keeps the numbers in a layer at a steady size. It divides each vector by its average size, the *root mean square*, so the $L^2 d$ attention cost is untouched.\n\n$$y = \\frac{x}{\\sqrt{\\mathrm{mean}(x^2) + \\epsilon}} \\cdot g$$\n\nIn your code, `src/model/norm.py:7` defines it as a small module with one learned scale $g$.' })
|
|
@@ -351,7 +387,7 @@ async function grabSelection(terminal) {
|
|
|
351
387
|
|
|
352
388
|
// ---- one lookup -----------------------------------------------------------------------------------
|
|
353
389
|
|
|
354
|
-
const NO_MODEL = 'Pocket Tutor needs a model. Set a key (a free Vercel AI Gateway key works) or point it at any OpenAI-compatible server. Run pocket-tutor
|
|
390
|
+
const NO_MODEL = 'Pocket Tutor needs a model. Set a key (a free Vercel AI Gateway key works) or point it at any OpenAI-compatible server. Run pocket-tutor setup, or see the README.'
|
|
355
391
|
|
|
356
392
|
async function lookup() {
|
|
357
393
|
const id = ++run
|
package/src/setup.js
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
// pocket-tutor setup: ask which model to use, test it, save ~/.pocket-tutor/config.json. No JSON editing.
|
|
2
|
+
const fs = require('fs')
|
|
3
|
+
const readline = require('readline')
|
|
4
|
+
const config = require('./config')
|
|
5
|
+
const model = require('./model')
|
|
6
|
+
|
|
7
|
+
const CHOICES = [
|
|
8
|
+
{ id: 'vercel', label: 'Vercel AI Gateway (free Nemotron model)', key: 'vercel_api_key', hint: 'free key at https://vercel.com/ai-gateway' },
|
|
9
|
+
{ id: 'openai', label: 'OpenAI', key: 'openai_api_key', hint: 'https://platform.openai.com/api-keys' },
|
|
10
|
+
{ id: 'openrouter', label: 'OpenRouter', key: 'openrouter_api_key', hint: 'https://openrouter.ai/keys' },
|
|
11
|
+
{ id: 'gemini', label: 'Google Gemini', key: 'gemini_api_key', hint: 'https://aistudio.google.com/apikey' },
|
|
12
|
+
{ id: 'groq', label: 'Groq', key: 'groq_api_key', hint: 'https://console.groq.com/keys' },
|
|
13
|
+
{ id: 'ollama', label: 'Ollama on this computer (no key)', key: null, hint: 'install from https://ollama.com, then: ollama pull llama3.2' },
|
|
14
|
+
{ id: 'custom', label: 'Another OpenAI-compatible server (you give the address)', key: 'llm_api_key', hint: '' },
|
|
15
|
+
]
|
|
16
|
+
|
|
17
|
+
// the settings file content for an answer, kept pure so it can be tested
|
|
18
|
+
function buildSettings(existing, choice, { key = '', baseUrl = '', modelName = '' } = {}) {
|
|
19
|
+
const next = { ...existing, provider: choice.id }
|
|
20
|
+
if (choice.key && key) next[choice.key] = key
|
|
21
|
+
if (choice.id === 'custom') next.base_url = baseUrl
|
|
22
|
+
if (modelName) next.model = modelName
|
|
23
|
+
return next
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
async function run() {
|
|
27
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
|
|
28
|
+
const ask = (q) => new Promise((res) => rl.question(q, (a) => res(a.trim())))
|
|
29
|
+
try {
|
|
30
|
+
console.log('Pocket Tutor setup\n\nWhich model should answer?')
|
|
31
|
+
CHOICES.forEach((c, i) => console.log(` ${i + 1}. ${c.label}`))
|
|
32
|
+
const pick = CHOICES[Number(await ask('\nNumber: ')) - 1]
|
|
33
|
+
if (!pick) { console.log('No choice made. Run pocket-tutor setup again.'); return 2 }
|
|
34
|
+
if (pick.hint) console.log(`\nKey: ${pick.hint}`)
|
|
35
|
+
const opts = {}
|
|
36
|
+
if (pick.id === 'custom') opts.baseUrl = await ask('Server address (it ends in /v1), for example http://localhost:1234/v1: ')
|
|
37
|
+
if (pick.key) opts.key = await ask('Paste the key (it is saved only in your settings file): ')
|
|
38
|
+
opts.modelName = await ask('Model name (Enter for the default): ')
|
|
39
|
+
let existing = {}
|
|
40
|
+
try { existing = JSON.parse(fs.readFileSync(config.FILE, 'utf8')) } catch { /* new file */ }
|
|
41
|
+
const settings = buildSettings(existing, pick, opts)
|
|
42
|
+
|
|
43
|
+
const cfg = config.resolve(settings, {})
|
|
44
|
+
if (!cfg.llm_key) { console.log('\nThat needs a key. Nothing saved. Run pocket-tutor setup again.'); return 2 }
|
|
45
|
+
process.stdout.write('\nTesting the model... ')
|
|
46
|
+
try {
|
|
47
|
+
await model.chat(cfg, cfg.model, [{ role: 'user', content: 'Reply with the single word: ready' }], { maxTokens: 20, timeoutMs: 30000 })
|
|
48
|
+
console.log('it answered.')
|
|
49
|
+
} catch (e) {
|
|
50
|
+
console.log(`failed: ${e.message}\nNothing saved. Check the key, the address and the model name, then run setup again.`)
|
|
51
|
+
return 1
|
|
52
|
+
}
|
|
53
|
+
fs.mkdirSync(config.HOME, { recursive: true })
|
|
54
|
+
fs.writeFileSync(config.FILE, JSON.stringify(settings, null, 2) + '\n', { mode: 0o600 })
|
|
55
|
+
console.log(`Saved to ${config.FILE}.\nNext: pocket-tutor (then select text anywhere and press Ctrl+Alt+Space)`)
|
|
56
|
+
return 0
|
|
57
|
+
} finally { rl.close() }
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
module.exports = { run, buildSettings, CHOICES }
|
package/src/tools.js
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
// The terminal-only extras (they work on any OS, no tray app needed):
|
|
2
|
+
// diff pocket-tutor diff [git args] what a change does and what could break
|
|
3
|
+
// review pocket-tutor review a short quiz on the things you keep looking up
|
|
4
|
+
// image pocket-tutor explain --image f a screenshot, chart or diagram
|
|
5
|
+
// Pure message builders live here so the tests can check them without a model.
|
|
6
|
+
const fs = require('fs')
|
|
7
|
+
const path = require('path')
|
|
8
|
+
const { execFileSync } = require('child_process')
|
|
9
|
+
const { secretFile, mask } = require('./privacy')
|
|
10
|
+
|
|
11
|
+
const MAX_DIFF = 14000
|
|
12
|
+
|
|
13
|
+
// ---- diff ------------------------------------------------------------------------------------------
|
|
14
|
+
|
|
15
|
+
// Drop the parts of a diff that touch secret files, then mask anything key-shaped, then cut to size.
|
|
16
|
+
function cleanDiff(raw) {
|
|
17
|
+
const parts = String(raw).split(/^(?=diff --git )/m)
|
|
18
|
+
const kept = parts.filter((p) => {
|
|
19
|
+
const m = /^diff --git a\/(.+?) b\//.exec(p)
|
|
20
|
+
return !m || !secretFile(m[1])
|
|
21
|
+
})
|
|
22
|
+
const text = mask(kept.join(''))
|
|
23
|
+
return text.length > MAX_DIFF ? text.slice(0, MAX_DIFF) + '\n[diff cut here: it was longer]' : text
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function readDiff(args = [], cwd = process.cwd()) {
|
|
27
|
+
// no argument: the unstaged and staged changes; "--staged" or a commit/range goes straight to git
|
|
28
|
+
const git = (a) => execFileSync('git', ['--no-pager', 'diff', '--no-color', ...a], { cwd, encoding: 'utf8', maxBuffer: 20 * 1024 * 1024 })
|
|
29
|
+
return cleanDiff(args.length ? git(args) : git(['HEAD']))
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function diffMessages(diff, profile = '') {
|
|
33
|
+
return [
|
|
34
|
+
{ role: 'system', content: [
|
|
35
|
+
'You review a code change for someone who let an AI write much of it and has not read every line.',
|
|
36
|
+
'Plain English, short sentences. At most 170 words, in this order:',
|
|
37
|
+
'1. What this change does, in two sentences.',
|
|
38
|
+
'2. The riskiest parts: up to three bullets, each naming a file and what could break or go wrong.',
|
|
39
|
+
'3. One thing to check by hand before trusting it.',
|
|
40
|
+
'Only use what is in the diff. If the diff is too small or too cut off to judge something, say so in a few words. Do not invent files or behaviour.',
|
|
41
|
+
'Markdown allowed: **bold**, `code`, short lists. No headings.',
|
|
42
|
+
].join('\n') },
|
|
43
|
+
{ role: 'user', content: `${profile ? `Project:\n${profile}\n\n` : ''}Diff:\n\`\`\`diff\n${diff}\n\`\`\`` },
|
|
44
|
+
]
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// ---- review quiz -----------------------------------------------------------------------------------
|
|
48
|
+
|
|
49
|
+
// The concepts worth a quiz: the ones looked up most, with a saved summary, most recent first on a tie.
|
|
50
|
+
function pickConcepts(graph, n = 4) {
|
|
51
|
+
return Object.values(graph.nodes || {})
|
|
52
|
+
.filter((x) => x.type === 'concept' && x.summary)
|
|
53
|
+
.sort((a, b) => (b.count - a.count) || (b.last - a.last))
|
|
54
|
+
.slice(0, n)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function quizMessages(concepts) {
|
|
58
|
+
return [
|
|
59
|
+
{ role: 'system', content: 'You write one short quiz question per concept for a student. Each question must be answerable in one or two sentences, in plain English, and must test understanding, not a definition copied word for word. Reply with only JSON: {"questions":[{"concept":"...","question":"..."}]} in the same order as given.' },
|
|
60
|
+
{ role: 'user', content: concepts.map((c, i) => `${i + 1}. ${c.label}: ${c.summary}`).join('\n') },
|
|
61
|
+
]
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function parseQuiz(text, concepts) {
|
|
65
|
+
const m = /\{[\s\S]*\}/.exec(String(text))
|
|
66
|
+
let qs = []
|
|
67
|
+
try { qs = JSON.parse(m ? m[0] : '{}').questions || [] } catch { /* fall back below */ }
|
|
68
|
+
const byConcept = new Map(qs.filter((q) => q && q.question).map((q) => [String(q.concept).toLowerCase(), q.question]))
|
|
69
|
+
// a missing question becomes a plain one, so the quiz never shrinks because the model stumbled
|
|
70
|
+
return concepts.map((c) => ({ concept: c.label, summary: c.summary, question: byConcept.get(c.label.toLowerCase()) || `In your own words, what is ${c.label}?` }))
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function gradeMessages(q, answer) {
|
|
74
|
+
return [
|
|
75
|
+
{ role: 'system', content: 'You mark a student\'s short answer. Reply in at most 40 words: start with "Right.", "Partly." or "Not yet.", then say what is missing or wrong in plain English. Be kind and specific. Use the reference only to judge.' },
|
|
76
|
+
{ role: 'user', content: `Question: ${q.question}\nReference: ${q.summary}\nStudent answer: ${answer || '(no answer)'}` },
|
|
77
|
+
]
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// ---- image -----------------------------------------------------------------------------------------
|
|
81
|
+
|
|
82
|
+
const MIME = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp' }
|
|
83
|
+
|
|
84
|
+
function imageDataUrl(file) {
|
|
85
|
+
const mime = MIME[path.extname(file).toLowerCase()]
|
|
86
|
+
if (!mime) throw new Error('use a .png, .jpg, .gif or .webp image')
|
|
87
|
+
const buf = fs.readFileSync(file)
|
|
88
|
+
if (buf.length > 8 * 1024 * 1024) throw new Error('the image is over 8 MB. Crop it or save a smaller copy.')
|
|
89
|
+
return `data:${mime};base64,${buf.toString('base64')}`
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function imageMessages(dataUrl, question = '') {
|
|
93
|
+
return [
|
|
94
|
+
{ role: 'system', content: 'You explain what is on a screenshot, chart, error dialog or diagram to a student, in plain English and short sentences, at most 120 words. Say what it shows, what it means, and what to do about it if it is a problem. Do not guess at text you cannot read; say it is unclear. Markdown allowed: **bold**, `code`, short lists. No headings.' },
|
|
95
|
+
{ role: 'user', content: [
|
|
96
|
+
{ type: 'text', text: question || 'Explain this image.' },
|
|
97
|
+
{ type: 'image_url', image_url: { url: dataUrl } },
|
|
98
|
+
] },
|
|
99
|
+
]
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
module.exports = { cleanDiff, readDiff, diffMessages, pickConcepts, quizMessages, parseQuiz, gradeMessages, imageDataUrl, imageMessages, MAX_DIFF }
|