feat 临时

This commit is contained in:
2026-03-20 01:12:29 +08:00
parent a0baf2ad7c
commit 21965ef95e
14 changed files with 1186 additions and 98 deletions

59
backend/ai/ai_client.go Normal file
View File

@@ -0,0 +1,59 @@
package ai
import (
"fmt"
)
type Client struct {
enableSearch bool // 是否开启搜索
searchStrategy string // 搜索策略(开了搜索才生效)
temperature float32 // 采样温度
}
func NewAIClient(enableSearch bool, searchStrategy string, temperature float32) *Client {
return &Client{
enableSearch: enableSearch,
searchStrategy: searchStrategy,
temperature: temperature,
}
}
func (c *Client) RequestAI(pre string, prompt []string, cb func(content string, i int) error) error {
inToken, outToken := int32(0), int32(0)
messages := []Message{{
Role: "user",
Content: pre,
}}
for i, step := range prompt {
messages = append(messages, Message{
Role: "user",
Content: step,
})
r, err := request("qwen3-max", Parameters{
//r, err := request("deepseek-v3.2", Parameters{
EnableSearch: c.enableSearch,
SearchOptions: SearchOptions{
SearchStrategy: c.searchStrategy,
},
ResultFormat: "message",
Temperature: c.temperature,
}, messages)
if err != nil {
return err
}
inToken += r.Usage.InputTokens
outToken += r.Usage.OutputTokens
if len(r.Output.Choices) == 0 {
fmt.Printf("AI response err, r: %#+v\n", r)
return err
} else {
messages = append(messages, r.Output.Choices[0].Message)
}
fmt.Printf("AI 回答 %v: %v\n", i, r.Output.Choices[0].Message.Content)
if err = cb(r.Output.Choices[0].Message.Content, i); err != nil {
return err
}
}
fmt.Printf("AI finished, use token: in-%v out-%v\n", inToken, outToken)
return nil
}

82
backend/ai/ai_request.go Normal file
View File

@@ -0,0 +1,82 @@
package ai
import (
"bytes"
"encoding/json"
"io"
"net/http"
)
type Message struct {
Role string `json:"role"`
Content string `json:"content"`
}
type Input struct {
Messages []Message `json:"messages"`
}
type Parameters struct {
EnableSearch bool `json:"enable_search,omitempty"`
SearchOptions SearchOptions `json:"search_options,omitempty"`
ResultFormat string `json:"result_format,omitempty"`
Temperature float32 `json:"temperature,omitempty"`
}
type SearchOptions struct {
SearchStrategy string `json:"search_strategy"`
}
type RequestBody struct {
Model string `json:"model"`
Input Input `json:"input"`
Parameters Parameters `json:"parameters"`
}
type ResponseBody struct {
Output struct {
Choices []struct {
Message Message `json:"message"`
FinishReason string `json:"finish_reason"`
} `json:"choices"`
} `json:"output"`
Usage struct {
InputTokens int32 `json:"input_tokens"`
OutputTokens int32 `json:"output_tokens"`
TotalTokens int32 `json:"total_tokens"`
} `json:"usage"`
}
func request(model string, parameters Parameters, messages []Message) (*ResponseBody, error) {
requestBody := RequestBody{
Model: model,
Input: Input{
Messages: messages,
},
Parameters: parameters,
}
jsonData, _ := json.Marshal(requestBody)
req, err := http.NewRequest("POST", "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation", bytes.NewBuffer(jsonData))
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+"sk-4daf94ad2fa94288b198d2a1d8924cef")
req.Header.Set("Content-Type", "application/json")
resp, err := (&http.Client{}).Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var res ResponseBody
if err = json.Unmarshal(body, &res); err != nil {
return nil, err
}
return &res, nil
}

View File

@@ -2,7 +2,11 @@ package backend
import (
"context"
"encoding/json"
"fiction/backend/ai"
"fmt"
"os"
"path/filepath"
)
// App struct
@@ -19,11 +23,67 @@ func (a *App) Startup(ctx context.Context) {
a.ctx = ctx
}
// Greet returns a greeting for the given name
func (a *App) Greet(name string) string {
return fmt.Sprintf("Hello %s, It's show time!", name)
// GetNovelList returns the list of txt files in the source directory
func (a *App) GetNovelList() []string {
var novels []string
sourceDir := "./source"
files, err := os.ReadDir(sourceDir)
if err != nil {
fmt.Printf("Error reading source directory: %v\n", err)
return novels
}
for _, file := range files {
if !file.IsDir() && filepath.Ext(file.Name()) == ".txt" {
novels = append(novels, file.Name())
}
}
return novels
}
func (a *App) Greet2(name string) string {
return fmt.Sprintf("Hello %s, It's show time!", name)
// GetNovelContent returns the content of a txt file
func (a *App) GetNovelContent(filename string) string {
sourceDir := "./source"
filePath := filepath.Join(sourceDir, filename)
content, err := os.ReadFile(filePath)
if err != nil {
fmt.Printf("Error reading file %s: %v\n", filename, err)
return "Error reading file"
}
return string(content)
}
func (a *App) WriteNovelContent(filename string) string {
filePath := filepath.Join("./config", "config.json")
content, err := os.ReadFile(filePath)
if err != nil {
fmt.Printf("读取提示词文件错误: %v\n", err)
return "Error reading file"
}
var str []string
if err = json.Unmarshal(content, &str); err != nil {
fmt.Printf("读取提示词错误: %v\n", err)
return "Error Unmarshal JSON"
}
resp := ""
err = ai.NewAIClient(false, "", 0.9).
RequestAI(
a.GetNovelContent(filename),
str,
func(content string, i int) error {
resp = content
return nil
},
)
if err != nil {
return err.Error()
}
return resp
}