-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenrate_article_handler.go
More file actions
80 lines (67 loc) · 2.01 KB
/
genrate_article_handler.go
File metadata and controls
80 lines (67 loc) · 2.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
func GenerateArticleHandler(w http.ResponseWriter, r *http.Request) {
var req ArticleReq
decodeErr := json.NewDecoder(r.Body).Decode(&req)
if decodeErr != nil {
http.Error(w, decodeErr.Error(), http.StatusBadRequest)
return
}
//prompt building
prompt := buildPrompt(req)
//call api
reqBody, marshalErr := json.Marshal(prompt)
if marshalErr != nil {
http.Error(w, "marshal error", http.StatusInternalServerError)
return
}
resp, reqErr := http.Post("http://0.0.0.0:9090/v1/chat/completions", "application/json", bytes.NewReader(reqBody))
if reqErr != nil {
http.Error(w, "request error", http.StatusInternalServerError)
return
}
defer resp.Body.Close()
body, readErr := io.ReadAll(resp.Body)
if readErr != nil {
http.Error(w, "request read error", http.StatusInternalServerError)
return
}
var response ResponseModel
err := json.Unmarshal(body, &response)
if err != nil {
http.Error(w, "unmarshal error", http.StatusInternalServerError)
return
}
var articleJson ArticleJson
err2 := json.Unmarshal([]byte(response.Choices[0].Message.Content), &articleJson)
if err2 != nil {
http.Error(w, "unmarshal error", http.StatusInternalServerError)
return
}
article := Article{
SeoKeywords: articleJson.SeoKeywords,
Article: articleJson,
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(article)
}
func buildPrompt(req ArticleReq) ChatReq {
var chatReq ChatReq
prompt := fmt.Sprintf(`Write a blog post with the following requirements: Topic: %s, keywords: %s, word count: %d. Output must be in the following format: {'title": "","introduction": "","sections": [{"heading": "","content": ""}],"conclusion": "","seo_keywords": []}. and return only raw json.`, req.Title, req.Keywords, req.WordCount)
msg := ChatMsg{
Role: "user",
Content: prompt,
}
chatReq = ChatReq{
Model: "Qwen3-4B-Q4_K_M.gguf",
Messages: []ChatMsg{msg},
}
return chatReq
}