Fix AI edit mode: strip code fences, stronger prompt

This commit is contained in:
2026-05-27 10:55:47 +02:00
parent 0b0f917694
commit b2b454c563
+17 -4
View File
@@ -157,10 +157,11 @@ func (s *Server) handleAIChat(w http.ResponseWriter, r *http.Request) {
var userMsg string var userMsg string
if req.Mode == "edit" { if req.Mode == "edit" {
systemPrompt = `You are a document editor. The user will give you a markdown document and an instruction. systemPrompt = "You are a document editor. The user will give you a markdown document and an instruction. " +
Apply the instruction to the document and return ONLY the complete updated document. "Apply the instruction to the document and return ONLY the complete updated document. " +
Do not add explanations, comments, or markdown code fences around the output. "Do not add explanations, comments, or wrap the output in code fences. " +
Preserve the document's existing style and formatting.` "Do not prefix with any markers. Preserve the document's existing style and formatting. " +
"Return the raw markdown content only."
userMsg = "Document:\n\n" + req.Content + "\n\nInstruction: " + req.Message userMsg = "Document:\n\n" + req.Content + "\n\nInstruction: " + req.Message
} else { } else {
systemPrompt = `You are a helpful writing assistant. The user has a markdown document open and is asking a question about it. systemPrompt = `You are a helpful writing assistant. The user has a markdown document open and is asking a question about it.
@@ -175,6 +176,18 @@ Answer concisely in markdown. Reference the document content when relevant.`
} }
if req.Mode == "edit" { if req.Mode == "edit" {
// Strip markdown code fences if AI wrapped the output
response = strings.TrimSpace(response)
if strings.HasPrefix(response, "```") {
lines := strings.Split(response, "\n")
if len(lines) > 2 {
lines = lines[1:] // remove opening fence
if strings.TrimSpace(lines[len(lines)-1]) == "```" {
lines = lines[:len(lines)-1] // remove closing fence
}
response = strings.Join(lines, "\n")
}
}
writeJSON(w, 200, map[string]string{"content": response}) writeJSON(w, 200, map[string]string{"content": response})
} else { } else {
writeJSON(w, 200, map[string]string{"result": response}) writeJSON(w, 200, map[string]string{"result": response})