feat 修改usn类型为string

This commit is contained in:
2026-01-11 16:16:27 +08:00
parent 1b893cad87
commit 11141edcda
17 changed files with 1019 additions and 43 deletions

View File

@@ -0,0 +1,11 @@
package server
import (
"fmt"
"testing"
)
func TestName(t *testing.T) {
t.Logf("step: %v", fmt.Sprintf("aa %v bb", []string{"1", "2"}))
}

View File

@@ -24,7 +24,7 @@ func (s *Server) Login(ctx context.Context, req *grpc_pb.LoginReq) (*grpc_pb.Log
if err := userDao.Create(user); err != nil {
return nil, err
}
user.Name = fmt.Sprintf("user_%d", user.Sn)
user.Name = fmt.Sprintf("user_%v", user.Sn)
_ = userDao.Updates(user)
} else {
return nil, err

View File

@@ -0,0 +1,156 @@
package server
import (
"context"
"encoding/json"
"fmt"
"git.hlsq.asia/mmorpg/service-common/db/redis"
"git.hlsq.asia/mmorpg/service-common/log"
"git.hlsq.asia/mmorpg/service-common/proto/ss/grpc_pb"
"git.hlsq.asia/mmorpg/service-user/internal/ai"
"git.hlsq.asia/mmorpg/service-user/internal/dao/model"
"git.hlsq.asia/mmorpg/service-user/internal/dao/repository"
"time"
)
//var prompt = []string{`
//你是一个微信小游戏的内容策划,请生成 %v 道“每日趣味题”,要求:
//- 避免敏感、争议或超纲内容
//- 每次从 [动物冷知识, 科学趣理, 语言陷阱, 历史轶事, 地理奇观, 数学谜题, 艺术人文, 综合杂学] 中**随机选一个类型**
//- 确保选项有迷惑性,解析有趣
//- 绝对要避免重复,现在的时间是:%v
//- 输出格式为 JSON 数组不要任何解释、不要Markdown、不要任何其他字符
// [{
// "question": "题目文本", // 简洁30字以内
// "options": ["A. 选项1", "B. 选项2", "C. 选项3", "D. 选项4"], // 提供4个选项A/B/C/D其中仅1个正确
// "answer": "C", // 答案
// "explanation": "解析文本", // 200字以内尽量幽默有趣
// "category": "分类", // 只能从上面列出的类型中选择
// "difficulty": 100, // 难度分 0 - 100
// }]
//`}
var prompt = []string{`
你是一个微信小游戏的内容策划,我需要生成“每日趣味题”,要求:
- 避免敏感、争议或超纲内容
- 确保选项有迷惑性,解析有趣
- 绝对要避免重复,现在的时间是:%v
- 这些是我目前的分类:%v
- 输出格式为 JSON 数组不要任何解释、不要Markdown、不要任何其他字符
[{
"question": "题目文本", // 简洁30字以内
"options": ["A. 选项1", "B. 选项2", "C. 选项3", "D. 选项4"], // 提供4个选项A/B/C/D其中仅1个正确
"answer": "C", // 答案
"explanation": "解析文本", // 200字以内尽量幽默有趣
"category": "分类", // 尽量从上述分类中选择,你也可以增加,但是命名风格要类似
"difficulty": 100, // 难度分 0 - 100
}]
如果你准备好了,请回答”好的“,不要有其他任何字符
`, `
请帮我生成 %v 道,只允许回答 JSON 数组:
`, `
请继续生成 %v 道,只允许回答 JSON 数组:
`, `
请继续生成 %v 道,只允许回答 JSON 数组:
`, `
请继续生成 %v 道,只允许回答 JSON 数组:
`, `
请继续生成 %v 道,只允许回答 JSON 数组:
`}
type Question struct {
Question string `json:"question"` // 题干
Options []string `json:"options"` // 选项
Answer string `json:"answer"` // 答案
Explanation string `json:"explanation"` // 解析
Category string `json:"category"` // 分类
Difficulty int32 `json:"difficulty"` // 难度分
}
func (s *Server) GenerateQuestion(ctx context.Context, req *grpc_pb.GenerateQuestionReq) (*grpc_pb.GenerateQuestionResp, error) {
category, err := repository.NewQuestionDao(ctx).FindCategory()
if err != nil {
log.Errorf("GenerateQuestion FindCategory error: %v", err)
return nil, err
}
question := make([]*Question, 0)
err = ai.NewAIClient(false, "", 0.9).
RequestAI(
[]string{
fmt.Sprintf(prompt[0], time.Now().Format("2006-01-02 15:04:05"), category),
fmt.Sprintf(prompt[1], req.Num, req.Category),
fmt.Sprintf(prompt[2], req.Num),
fmt.Sprintf(prompt[3], req.Num),
fmt.Sprintf(prompt[4], req.Num),
fmt.Sprintf(prompt[5], req.Num),
},
func(content string, i int) error {
if i == 0 {
return nil
}
step := make([]*Question, 0)
if err := json.Unmarshal([]byte(content), &step); err != nil {
log.Errorf("RequestAI json.Unmarshal error: %v, data: %v", err, content)
return err
}
question = append(question, step...)
return nil
},
)
if err != nil {
log.Errorf("RequestAI error: %v", err)
return nil, err
}
questionDao := repository.NewQuestionDao(ctx, redis.GetCacheClient())
for _, q := range question {
marshal, _ := json.Marshal(q.Options)
if err = questionDao.Create(&model.Question{
Question: q.Question,
Options: string(marshal),
Answer: q.Answer,
Explanation: q.Explanation,
Category: q.Category,
Difficulty: q.Difficulty,
}); err != nil {
log.Errorf("GenerateQuestion Create error: %v", err)
return nil, err
}
}
return nil, nil
}
func (s *Server) GetQuestion(ctx context.Context, req *grpc_pb.GetQuestionReq) (*grpc_pb.GetQuestionResp, error) {
question, err := repository.NewQuestionDao(ctx).FindByRandom()
if err != nil {
log.Errorf("GetQuestion error: %v", err)
return nil, err
}
options := make([]string, 0)
if err = json.Unmarshal([]byte(question.Options), &options); err != nil {
log.Errorf("GetQuestion json.Unmarshal error: %v, data: %v", err, question.Options)
return nil, err
}
return &grpc_pb.GetQuestionResp{
Sn: question.Sn,
Question: question.Question,
Options: options,
}, nil
}
func (s *Server) AnswerQuestion(ctx context.Context, req *grpc_pb.AnswerQuestionReq) (*grpc_pb.AnswerQuestionResp, error) {
question, err := repository.NewQuestionDao(ctx).FindBySn(req.Sn)
if err != nil {
log.Errorf("AnswerQuestion error: %v", err)
return nil, err
}
options := make([]string, 0)
if err = json.Unmarshal([]byte(question.Options), &options); err != nil {
log.Errorf("AnswerQuestion json.Unmarshal error: %v, data: %v", err, question.Options)
return nil, err
}
return &grpc_pb.AnswerQuestionResp{
Answer: question.Answer,
Explanation: question.Explanation,
}, nil
}

View File

@@ -0,0 +1,161 @@
package server
//
//import (
// "bytes"
// "context"
// "encoding/json"
// "git.hlsq.asia/mmorpg/service-common/log"
// "git.hlsq.asia/mmorpg/service-common/proto/ss/grpc_pb"
// "io"
// "net/http"
//)
//
//var question = []string{
// "本次对话 数据来源必须:东方财富,巨潮资讯,官网,数据截止:自上市至2025年第3季度\n帮我查询一下京东方科技集团股份有限公司公司的所有财报数量",
// "帮我从东方财富 / 巨潮资讯 / 官网这三个来源整理一下重大事项公告的数量,按照三个维度划分( 并购重组公告披露,关联交易公告,对外投资公告)",
// "帮我从东方财富 / 巨潮资讯 / 官网这三个来源整理一下投资者关系活动,按照三个维度划分( 年度业绩说明次数, 投资者调研次数,接待机构数量)",
// "帮我查询一下ESG与治理的信息各个维度评分评级",
// "帮我查询一下这个公司监管合规信息,综合评估一下本年度监管合规(信披评分,公司治理,内控合规,ESG表现,财务合规,业务运营合规,股东与投资者权益保护合规,合规风险管理)百分制",
// "将本次对话的所有内容总结和完整的装入这个结构体生成json对象数据返回,注意必须以json(markdown代码)的形式返回,并且只输出json即可不用输出其它说明,下面内容就是结构体: \n// CompanyComplianceScore 公司合规评分\ntype CompanyComplianceScore struct {\n\tInformationDisclosureRating string `json:\"informationDisclosureRating\" bson:\"information_disclosure_rating\" comment:\"信息披露评级\"`//获取交易所的信披评级如A/B/C等\n\tRegularReportFrequencyCount *RegularReportFrequency `json:\"regularReportFrequency\" bson:\"regular_report_frequency\" comment:\"定期报告披露频次\"`\n\tMajorAnnouncementCount *MajorAnnouncementCount `json:\"majorAnnouncementCount\" bson:\"major_announcement_count\" comment:\"重大事项公告\"`\n\tInvestorRelationsActivity *InvestorRelationsActivity `json:\"InvestorRelationsActivity\" bson:\"investor_relations_activity\" comment:\"投资者关系活动\"`\n\tEsgReport *EsgReport `json:\"esgReport\" bson:\"esg_report\" comment:\"ESG与治理\"`\n\tDisclosureScore float64 `json:\"disclosureScore\" bson:\"disclosure_score\" comment:\"信息披露专项评分\"`\n\tCorporateGovernanceScore float64 `json:\"corporateGovernanceScore\" bson:\"corporate_governance_score\" comment:\"公司治理评分\"`\n\tInternalControlCompliance float64 `json:\"internalControlCompliance\" bson:\"internal_control_compliance\" comment:\"内控合规评分\"`\n\tEsgPerformanceScore float64 `json:\"esgPerformanceScore\" bson:\"esg_performance_score\" comment:\"ESG表现评分\"`\n\tFinancialComplianceScore float64 `json:\"financialComplianceScore\" bson:\"financial_compliance_score\" comment:\"财务合规评分\"`\n\tBusinessOperationCompliance float64 `json:\"businessOperationCompliance\" bson:\"business_operation_compliance\" comment:\"业务运营合规评分\"`\n\tShareholderRightsCompliance float64 `json:\"shareholderRightsCompliance\" bson:\"shareholder_rights_compliance\" comment:\"股东权益保护合规评分\"`\n\tComplianceRiskManagement float64 `json:\"complianceRiskManagement\" bson:\"compliance_risk_management\" comment:\"合规风险管理评分\"`\n\tOverallComprehensiveScore float64 `json:\"overallComprehensiveScore\" bson:\"overall_comprehensive_score\" comment:\"综合评分\"`\n}\n\n// RegularReportFrequency 定期报告披露频次\ntype RegularReportFrequency struct {\n\tAnnualReportCount int `json:\"annualReportCount\" bson:\"annual_report_count\" comment:\"年报数量\"`\n\tSemiAnnualReportCount int `json:\"semiAnnualReportCount\" bson:\"semi_annual_report_count\" comment:\"半年报数量\"`\n\tQuarterlyReportCount int `json:\"quarterlyReportCount\" bson:\"quarterly_report_count\" comment:\"季度报告数量\"`\n\tTotalReportCount int `json:\"totalReportCount\" bson:\"total_report_count\" comment:\"报告总数\"`\n}\n\n// MajorAnnouncementCount 重大事项公告\ntype MajorAnnouncementCount struct {\n\tMnaAnnouncementCount int `json:\"mnaAnnouncementCount\" bson:\"mna_announcement_count\" comment:\"并购重组公告数量\"`\n\tRelatedTransactionCount int `json:\"relatedTransactionCount\" bson:\"related_transaction_count\" comment:\"关联交易公告数量\"`\n\tForeignInvestmentCount int `json:\"foreignInvestmentCount\" bson:\"foreign_investment_count\" comment:\"对外投资公告数量\"`\n}\n\n// InvestorRelationsActivity 投资者关系活动\ntype InvestorRelationsActivity struct {\n\tAnnualPerformanceBriefings int `json:\"annualPerformanceBriefings\" bson:\"annual_performance_briefings\" comment:\"年度业绩说明次数\"`\n\tInvestorResearchCount int `json:\"investorResearchCount\" bson:\"investor_research_count\" comment:\"投资者调研次数\"`\n\tInstitutionsReceivedCount int `json:\"institutionsReceivedCount\" bson:\"institutions_received_count\" comment:\"接待机构数量\"`\n}\n\n// EsgReport ESG与治理\ntype EsgReport struct {\n\tEsgOverallScore float64 `json:\"esgOverallScore\" bson:\"esg_overall_score\" comment:\"ESG综合评分\"`//通过【上海华证指数信息服务有限公司】披露的公司ESG评级例如BBB不允许返回分数\n\tEnvironmentalScore float64 `json:\"environmentalScore\" bson:\"environmental_score\" comment:\"环境评分\"`\n\tSocialScore float64 `json:\"socialScore\" bson:\"social_score\" comment:\"社会评分\"`\n\tGovernanceScore float64 `json:\"governanceScore\" bson:\"governance_score\" comment:\"治理评分\"`\n}",
//}
//
//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"`
// ResultFormat string `json:"result_format"`
// SearchOptions SearchOptions `json:"search_options"`
//}
//
//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 (s *Server) GenerateQuestion(ctx context.Context, req *grpc_pb.GenerateQuestionReq) (*grpc_pb.GenerateQuestionResp, error) {
// inToken, outToken := int32(0), int32(0)
//
// messages := make([]Message, 0)
// for i, step := range question {
// messages = append(messages, newUserMessage(step))
//
// //chatCompletion, err := client.Chat.Completions.New(
// // context.Background(), openai.ChatCompletionNewParams{
// // Messages: messages,
// // Model: "qwen3-max",
// // },
// //)
// //if err != nil {
// // return nil, err
// //}
// r, err := request(messages)
// if err != nil {
// return nil, err
// }
// inToken += r.Usage.InputTokens
// outToken += r.Usage.OutputTokens
// log.Infof("回答 %v%v", i, r)
// //break
// messages = append(messages, r.Output.Choices[0].Message)
//
// //log.Infof("回答 %v%v", i, chatCompletion.Choices[0].Message.Content)
// //messages = append(messages, openai.AssistantMessage(chatCompletion.Choices[0].Message.Content))
// }
// log.Infof("返回:%v", messages[len(messages)-1].Content)
// //log.Infof("消耗token%v %v, 费用:%v", inToken, outToken, float64(inToken)/1000*0.0032+float64(outToken)/1000*0.0128)
// log.Infof("消耗token%v %v, 费用:%v", inToken, outToken, float64(inToken)/1000*0.002+float64(outToken)/1000*0.003)
//
// //chatCompletion, err := client.Chat.Completions.New(
// // context.Background(), openai.ChatCompletionNewParams{
// // Messages: []openai.ChatCompletionMessageParamUnion{
// // openai.UserMessage("你能做什么"),
// // },
// // Model: "qwen3-max",
// // },
// //)
// //if err != nil {
// // return nil, err
// //}
// //for i, choice := range chatCompletion.Choices {
// // log.Infof("chatCompletion %v: %#+v \n", i, choice)
// //}
// //log.Infof("返回:%v", chatCompletion.Choices[0].Message.Content)
// return nil, nil
//}
//
//func newUserMessage(content string) Message {
// return Message{
// Role: "user",
// Content: content,
// }
//}
//
//func request(messages []Message) (*ResponseBody, error) {
// client := &http.Client{}
// requestBody := RequestBody{
// //Model: "qwen3-max",
// Model: "deepseek-v3.2",
// Input: Input{
// Messages: messages,
// },
// Parameters: Parameters{
// EnableSearch: true,
// SearchOptions: SearchOptions{
// SearchStrategy: "max",
// },
//
// ResultFormat: "message",
// },
// }
// 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 := 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
//}