Skip to content

Commit 72bfdd0

Browse files
committed
Add reasoning level control and script glossary with editor
- ReasoningLevel (low/medium/high) per role, mapped per provider: GLM thinking on/off, OpenAI-compat reasoning_effort, Gemini thinkingConfig budget, Ollama think flag — medium = provider default - Glossary (term/pronunciation/note) injected as few-shot block at the TOP of the script instruction (above base rules — verified placement from repo's own gemma experiment), with editor sheet in settings - Seed only when settings key absent; corrupt key keeps empty glossary - Review fixes (claude): unsupported models send no thinking params instead of risking 400s, glossary placement reversed to match empirically verified ordering, search-filtered add-row fix
1 parent 0c3defb commit 72bfdd0

7 files changed

Lines changed: 386 additions & 41 deletions

File tree

‎Sources/App/AppState.swift‎

Lines changed: 115 additions & 19 deletions
Large diffs are not rendered by default.

‎Sources/TTS/TextNormalizer.swift‎

Lines changed: 118 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,67 @@ func normalizationPrompt(_ instruction: String, _ text: String) -> String {
1414
return "\(instr)\n\n원문:\n\(text)\n\n변환:"
1515
}
1616

17+
/// 사용자 친화적 3단 reasoning(thinking) 수준. 공급자별 파라미터로 변환된다:
18+
/// OpenAI 호환 = reasoning_effort, GLM = thinking on/off, Gemini = thinkingBudget,
19+
/// Ollama = think.
20+
///
21+
/// 핵심 규칙: **"보통"은 어떤 파라미터도 싣지 않는다** (전부 nil). 공급자 기본값이
22+
/// 곧 "보통"이기 때문이다 — Gemini 2.5는 동적 thinking, GLM은 thinking on, Ollama
23+
/// thinking 모델은 think on, OpenAI reasoning 모델은 effort medium이 기본이다.
24+
/// 덕분에 기본 설정(=보통)의 요청 본문은 이 기능 도입 전과 완전히 동일하고,
25+
/// thinking을 모르는 모델(gemini-2.0-flash, gemma 계열 등 — 이 저장소의 기본
26+
/// 모델들이다)에 낯선 필드를 보내 400을 맞는 일이 없다. 낮음/높음은 사용자가
27+
/// 명시적으로 고른 경우에만 실린다.
28+
enum ReasoningLevel: String, CaseIterable, Identifiable {
29+
case low, medium, high
30+
var id: String { rawValue }
31+
var label: String {
32+
switch self {
33+
case .low: return "낮음"
34+
case .medium: return "보통"
35+
case .high: return "높음"
36+
}
37+
}
38+
/// "보통" = 공급자 기본값에 맡김 (파라미터 미전송).
39+
var isProviderDefault: Bool { self == .medium }
40+
41+
/// NormalizationCache 키에 덧붙이는 조각 — 수준을 바꾸면 요청이 달라지므로
42+
/// 같은 텍스트라도 캐시 적중 없이 다시 생성돼야 한다. 기본값(보통)에서는 빈
43+
/// 문자열이라 이 기능 이전에 쌓인 캐시가 그대로 유효하다.
44+
var cacheSuffix: String { isProviderDefault ? "" : "\u{1F}reasoning=\(rawValue)" }
45+
46+
/// OpenAI 호환 reasoning_effort 값. 보통이면 nil(미전송).
47+
var openAIEffort: String? { isProviderDefault ? nil : rawValue }
48+
49+
/// GLM은 effort 단계가 없어 on/off만: 낮음=disabled, 높음=enabled.
50+
/// 보통이면 nil(미전송 → GLM 기본 thinking on).
51+
var glmThinkingEnabled: Bool? { isProviderDefault ? nil : self != .low }
52+
53+
/// Ollama `think`. **끄는 쪽(false)만 보낸다** — thinking 미지원 모델에
54+
/// `think:true`를 보내면 Ollama가 "does not support thinking"으로 요청을
55+
/// 거절하지만, `false`는 어떤 모델에도 능력을 요구하지 않아 안전하다.
56+
/// 보통·높음은 미전송 → thinking 모델은 기본대로 켜진 채 동작한다.
57+
var ollamaThink: Bool? { self == .low ? false : nil }
58+
59+
/// Gemini `generationConfig.thinkingConfig` (없으면 nil).
60+
/// thinkingConfig를 이해하지 못하는 세대(1.5 / 2.0 / Gemini API가 서빙하는
61+
/// gemma 등)에 실으면 400 INVALID_ARGUMENT가 나므로, thinking 지원이 확실한
62+
/// 이름에만 붙인다. 2.5 pro는 thinking을 완전히 끌 수 없어(budget 0 거부)
63+
/// 낮음을 최소 budget 128로 낮춘다.
64+
func geminiThinkingConfig(model: String) -> [String: Any]? {
65+
guard !isProviderDefault, Self.geminiSupportsThinking(model) else { return nil }
66+
if self == .high { return ["thinkingBudget": 8192] }
67+
return ["thinkingBudget": model.lowercased().contains("pro") ? 128 : 0]
68+
}
69+
70+
/// 이름만으로 thinking 지원을 단정할 수 있는 세대(2.5 / 3.x)만 허용한다.
71+
/// 모르는 이름은 보수적으로 미전송 — 기능이 안 걸리는 쪽이 400보다 낫다.
72+
private static func geminiSupportsThinking(_ model: String) -> Bool {
73+
let m = model.lowercased()
74+
return m.contains("2.5") || m.contains("gemini-3")
75+
}
76+
}
77+
1778
/// Shared LLM HTTP plumbing. Both the normalizer (원문→변환) and the explainer
1879
/// (코드→해설) build their own prompt and call these — the prompt scaffold is
1980
/// the caller's job, NOT baked in here.
@@ -23,7 +84,8 @@ enum LLM {
2384
/// is the increment. Cancelling the consuming task tears down the request.
2485
static func geminiStream(baseURL: String = GeminiNormalizer.defaultBaseURL,
2586
apiKey: String, model: String, prompt: String,
26-
images: [Data] = [], temperature: Double = 0.2) -> AsyncThrowingStream<String, Error> {
87+
images: [Data] = [], temperature: Double = 0.2,
88+
reasoningLevel: ReasoningLevel = .medium) -> AsyncThrowingStream<String, Error> {
2789
AsyncThrowingStream { continuation in
2890
let work = Task {
2991
do {
@@ -43,9 +105,13 @@ enum LLM {
43105
parts.append(["inline_data": ["mime_type": "image/png",
44106
"data": img.base64EncodedString()]])
45107
}
108+
var generationConfig: [String: Any] = ["temperature": temperature]
109+
if let thinking = reasoningLevel.geminiThinkingConfig(model: model) {
110+
generationConfig["thinkingConfig"] = thinking
111+
}
46112
req.httpBody = try JSONSerialization.data(withJSONObject: [
47113
"contents": [["parts": parts]],
48-
"generationConfig": ["temperature": temperature],
114+
"generationConfig": generationConfig,
49115
])
50116
let (bytes, response) = try await URLSession.shared.bytes(for: req)
51117
guard let http = response as? HTTPURLResponse, http.statusCode == 200 else {
@@ -82,7 +148,8 @@ enum LLM {
82148
/// Images ride as `image_url` content parts (data: URLs) for vision models.
83149
static func openAIChatStream(baseURL: String, model: String, apiKey: String,
84150
prompt: String, images: [Data] = [],
85-
temperature: Double = 0.2) -> AsyncThrowingStream<String, Error> {
151+
temperature: Double = 0.2,
152+
reasoningLevel: ReasoningLevel = .medium) -> AsyncThrowingStream<String, Error> {
86153
AsyncThrowingStream { continuation in
87154
let work = Task {
88155
do {
@@ -105,12 +172,25 @@ enum LLM {
105172
}
106173
content = parts
107174
}
108-
req.httpBody = try JSONSerialization.data(withJSONObject: [
175+
// GLM 계열은 effort 단계가 없어 thinking on/off로, 그 외 OpenAI
176+
// 호환은 reasoning_effort로 보낸다 — 배타적 분기라 두 필드가 한
177+
// 요청에 함께 실리는 일은 없다. "보통"이면 어느 쪽도 싣지 않아
178+
// 요청 본문이 기존과 동일하다 (임의의 OpenAI 호환 서버가 모르는
179+
// 필드에 400을 내는 위험을 기본 경로에서 없앤다).
180+
var payload: [String: Any] = [
109181
"model": model,
110182
"messages": [["role": "user", "content": content]],
111183
"stream": true,
112184
"temperature": temperature,
113-
])
185+
]
186+
if model.lowercased().contains("glm") {
187+
if let on = reasoningLevel.glmThinkingEnabled {
188+
payload["thinking"] = ["type": on ? "enabled" : "disabled"]
189+
}
190+
} else if let effort = reasoningLevel.openAIEffort {
191+
payload["reasoning_effort"] = effort
192+
}
193+
req.httpBody = try JSONSerialization.data(withJSONObject: payload)
114194
let (bytes, response) = try await URLSession.shared.bytes(for: req)
115195
guard let http = response as? HTTPURLResponse, http.statusCode == 200 else {
116196
throw NSError(domain: "OpenAI-compat",
@@ -143,17 +223,20 @@ enum LLM {
143223
/// Ollama streaming (`api/generate`, stream:true → JSONL). Yields each
144224
/// `response` delta; stops at the `done:true` line. Cancellation tears down.
145225
static func ollamaStream(baseURL: URL, model: String, prompt: String,
146-
temperature: Double = 0.2) -> AsyncThrowingStream<String, Error> {
226+
temperature: Double = 0.2,
227+
reasoningLevel: ReasoningLevel = .medium) -> AsyncThrowingStream<String, Error> {
147228
AsyncThrowingStream { continuation in
148229
let work = Task {
149230
do {
150231
var req = URLRequest(url: baseURL.appendingPathComponent("api/generate"))
151232
req.httpMethod = "POST"
152233
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
153-
req.httpBody = try JSONSerialization.data(withJSONObject: [
234+
var payload: [String: Any] = [
154235
"model": model, "prompt": prompt, "stream": true,
155236
"options": ["temperature": temperature],
156-
])
237+
]
238+
if let think = reasoningLevel.ollamaThink { payload["think"] = think }
239+
req.httpBody = try JSONSerialization.data(withJSONObject: payload)
157240
let (bytes, response) = try await URLSession.shared.bytes(for: req)
158241
guard let http = response as? HTTPURLResponse, http.statusCode == 200 else {
159242
throw NSError(domain: "Ollama",
@@ -183,7 +266,8 @@ enum LLM {
183266
/// vision: image input is delivered via the chat message's `images` (base64),
184267
/// not `api/generate`. Yields each `message.content` delta.
185268
static func ollamaChatStream(baseURL: URL, model: String, prompt: String,
186-
images: [Data], temperature: Double = 0.2) -> AsyncThrowingStream<String, Error> {
269+
images: [Data], temperature: Double = 0.2,
270+
reasoningLevel: ReasoningLevel = .medium) -> AsyncThrowingStream<String, Error> {
187271
AsyncThrowingStream { continuation in
188272
let work = Task {
189273
do {
@@ -192,10 +276,12 @@ enum LLM {
192276
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
193277
var message: [String: Any] = ["role": "user", "content": prompt]
194278
if !images.isEmpty { message["images"] = images.map { $0.base64EncodedString() } }
195-
req.httpBody = try JSONSerialization.data(withJSONObject: [
279+
var payload: [String: Any] = [
196280
"model": model, "messages": [message], "stream": true,
197281
"options": ["temperature": temperature],
198-
])
282+
]
283+
if let think = reasoningLevel.ollamaThink { payload["think"] = think }
284+
req.httpBody = try JSONSerialization.data(withJSONObject: payload)
199285
let (bytes, response) = try await URLSession.shared.bytes(for: req)
200286
guard let http = response as? HTTPURLResponse, http.statusCode == 200 else {
201287
throw NSError(domain: "Ollama",
@@ -255,9 +341,11 @@ struct TextNormalizer: Normalizing {
255341
"""
256342

257343
var temperature: Double = 0.2
344+
var reasoningLevel: ReasoningLevel = .medium
258345
func normalizeStream(_ text: String) -> AsyncThrowingStream<String, Error> {
259346
LLM.ollamaStream(baseURL: baseURL, model: model,
260-
prompt: normalizationPrompt(instruction, text), temperature: temperature)
347+
prompt: normalizationPrompt(instruction, text), temperature: temperature,
348+
reasoningLevel: reasoningLevel)
261349
}
262350
}
263351

@@ -272,9 +360,11 @@ struct GeminiNormalizer: Normalizing {
272360
static let defaultBaseURL = "https://generativelanguage.googleapis.com/v1beta"
273361

274362
var temperature: Double = 0.2
363+
var reasoningLevel: ReasoningLevel = .medium
275364
func normalizeStream(_ text: String) -> AsyncThrowingStream<String, Error> {
276365
LLM.geminiStream(baseURL: baseURL, apiKey: apiKey, model: model,
277-
prompt: normalizationPrompt(instruction, text), temperature: temperature)
366+
prompt: normalizationPrompt(instruction, text), temperature: temperature,
367+
reasoningLevel: reasoningLevel)
278368
}
279369
}
280370

@@ -290,9 +380,11 @@ struct ZAINormalizer: Normalizing {
290380
static let fallbackModels = ["glm-5.3"]
291381

292382
var temperature: Double = 0.2
383+
var reasoningLevel: ReasoningLevel = .medium
293384
func normalizeStream(_ text: String) -> AsyncThrowingStream<String, Error> {
294385
LLM.openAIChatStream(baseURL: baseURL, model: model, apiKey: apiKey,
295-
prompt: normalizationPrompt(instruction, text), temperature: temperature)
386+
prompt: normalizationPrompt(instruction, text), temperature: temperature,
387+
reasoningLevel: reasoningLevel)
296388
}
297389
}
298390

@@ -409,14 +501,16 @@ struct GeminiExplainer: Explaining {
409501
let model: String
410502
let instruction: String
411503
var temperature: Double = 0.4
504+
var reasoningLevel: ReasoningLevel = .medium
412505
func stream(_ code: String, hint: String) -> AsyncThrowingStream<String, Error> {
413506
LLM.geminiStream(baseURL: baseURL, apiKey: apiKey, model: model,
414-
prompt: CodeExplanation.prompt(instruction, code, hint: hint), temperature: temperature)
507+
prompt: CodeExplanation.prompt(instruction, code, hint: hint), temperature: temperature,
508+
reasoningLevel: reasoningLevel)
415509
}
416510
func streamContinuing(previous: String, current: String, hint: String) -> AsyncThrowingStream<String, Error> {
417511
LLM.geminiStream(baseURL: baseURL, apiKey: apiKey, model: model,
418512
prompt: CodeExplanation.continuePrompt(previous: previous, current: current, hint: hint),
419-
temperature: temperature)
513+
temperature: temperature, reasoningLevel: reasoningLevel)
420514
}
421515
}
422516

@@ -427,14 +521,16 @@ struct ZAIExplainer: Explaining {
427521
let model: String
428522
let instruction: String
429523
var temperature: Double = 0.4
524+
var reasoningLevel: ReasoningLevel = .medium
430525
func stream(_ code: String, hint: String) -> AsyncThrowingStream<String, Error> {
431526
LLM.openAIChatStream(baseURL: baseURL, model: model, apiKey: apiKey,
432-
prompt: CodeExplanation.prompt(instruction, code, hint: hint), temperature: temperature)
527+
prompt: CodeExplanation.prompt(instruction, code, hint: hint), temperature: temperature,
528+
reasoningLevel: reasoningLevel)
433529
}
434530
func streamContinuing(previous: String, current: String, hint: String) -> AsyncThrowingStream<String, Error> {
435531
LLM.openAIChatStream(baseURL: baseURL, model: model, apiKey: apiKey,
436532
prompt: CodeExplanation.continuePrompt(previous: previous, current: current, hint: hint),
437-
temperature: temperature)
533+
temperature: temperature, reasoningLevel: reasoningLevel)
438534
}
439535
}
440536

@@ -444,14 +540,16 @@ struct OllamaExplainer: Explaining {
444540
let model: String
445541
let instruction: String
446542
var temperature: Double = 0.4
543+
var reasoningLevel: ReasoningLevel = .medium
447544
func stream(_ code: String, hint: String) -> AsyncThrowingStream<String, Error> {
448545
LLM.ollamaStream(baseURL: baseURL, model: model,
449-
prompt: CodeExplanation.prompt(instruction, code, hint: hint), temperature: temperature)
546+
prompt: CodeExplanation.prompt(instruction, code, hint: hint), temperature: temperature,
547+
reasoningLevel: reasoningLevel)
450548
}
451549
func streamContinuing(previous: String, current: String, hint: String) -> AsyncThrowingStream<String, Error> {
452550
LLM.ollamaStream(baseURL: baseURL, model: model,
453551
prompt: CodeExplanation.continuePrompt(previous: previous, current: current, hint: hint),
454-
temperature: temperature)
552+
temperature: temperature, reasoningLevel: reasoningLevel)
455553
}
456554
}
457555

‎Sources/UI/CommentaryView.swift‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,9 @@ struct CommentaryView: View {
3535
if showPrompt {
3636
StageInspector(title: "해설 설정",
3737
temperature: $app.explainTemperature,
38+
reasoningLevel: $app.explainReasoningLevel,
39+
visionLevelTitle: "비전 생성 수준",
40+
visionReasoningLevel: $app.visionReasoningLevel,
3841
prompt: $app.explainPrompt,
3942
promptCaption: "해설 지시문 — 코드를 어떻게 해설할지 LLM에게 주는 규칙",
4043
restore: { app.explainPrompt = CodeExplanation.defaultInstruction },

‎Sources/UI/GenerateView.swift‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ struct GenerateView: View {
2121
if showPrompt {
2222
StageInspector(title: "대본 설정",
2323
temperature: $app.scriptTemperature,
24+
reasoningLevel: $app.scriptReasoningLevel,
2425
prompt: $app.normalizePrompt,
2526
promptCaption: "정규화 지시문 — 대본을 어떻게 다듬을지 LLM에게 주는 규칙",
2627
restore: { app.normalizePrompt = TextNormalizer.defaultInstruction },

0 commit comments

Comments
 (0)