当前位置: 首页 > news >正文

gig-gitignore工具实战开发(四):使用ai辅助生成gitignore

文章目录

  • gig-gitignore工具实战开发(四):使用ai辅助生成gitignore
    • ai配置
    • 编写promot
    • 流失响应

gig-gitignore工具实战开发(四):使用ai辅助生成gitignore

前言: 在上一篇我们编写了gig add命令基础代码,下面详细介绍ai生成模板代码。

ai配置

由于ai模型众多,这里我们采用最简单的方案,兼容openai的api规范,提供base_url修改,这样无需和一个个模型提供商进行对接。

引导用户进行ai配置输入

func runInteractiveConfig() {fmt.Println("Entering interactive configuration mode...")// Prompt for API KeypromptAPIKey := promptui.Prompt{Label:   "OpenAI API Key",Default: viper.GetString("ai.api_key"),Mask:    '*',}apiKey, err := promptAPIKey.Run()if err != nil {fmt.Printf("Prompt failed %v\n", err)os.Exit(1)}viper.Set("ai.api_key", apiKey)// Prompt for AI URLpromptURL := promptui.Prompt{Label:   "AI Service URL",Default: viper.GetString("ai.url"),}apiURL, err := promptURL.Run()if err != nil {fmt.Printf("Prompt failed %v\n", err)os.Exit(1)}viper.Set("ai.url", apiURL)// Prompt for AI ModelpromptModel := promptui.Prompt{Label:   "AI Model",Default: viper.GetString("ai.model"),}model, err := promptModel.Run()if err != nil {fmt.Printf("Prompt failed %v\n", err)os.Exit(1)}viper.Set("ai.model", model)saveConfig()
}

存储

func saveConfig() {// Get the config file path from vipercfgFile := viper.ConfigFileUsed()if cfgFile == "" {// If no config file is used, create one in the default pathhome, err := os.UserHomeDir()if err != nil {fmt.Println("Error finding home directory:", err)os.Exit(1)}cfgFile = filepath.Join(home, ".ciclebyte", "gig", "config", "config.yaml")}if err := viper.WriteConfigAs(cfgFile); err != nil {fmt.Println("Error writing configuration file:", err)os.Exit(1)}fmt.Println("Configuration saved successfully to", cfgFile)
}

编写promot

编写promot,让ai生成符合要求的gitignore文件

 You are an expert assistant specializing in generating high-quality .gitignore files.Your task is to create a .gitignore file for a project based on the provided languages and frameworks.<instructions>1.  **Content**: The file MUST only contain rules for the following languages/frameworks: %s.2.  **Structure**: Organize the rules into logical categories (e.g., "Dependencies", "Build output", "Logs", "IDE files").3.  **Headers**: Each category MUST start with a header formatted exactly as '# === Category Name ===', followed by a blank line.4.  **Comments**: Add concise comments (starting with '#') to explain the purpose of non-obvious rules or groups of rules.5.  **Exclusivity**: Do NOT include rules for any other languages, frameworks, or tools not specified.6.  **Output Format**: Your response MUST be ONLY the raw text content of the .gitignore file. Do NOT include any introductory text, explanations, or markdown code blocks like ` + "`" + ` ` + "`" + ` or ` + "`" + ` ` + "`" + `gitignore.</instructions>`

流失响应

根据配置的ai模型、promot返回生成的gitignore文件内容

// 通用流式AI请求,返回完整内容
func (AIUtil) StreamChat(promptType string, vars ...string) (string, error) {apiKey := viper.GetString("ai.api_key")if apiKey == "" {fmt.Println("AI API Key is not configured. Please run 'gig config' or设置 GIG_AI_API_KEY.")os.Exit(1)}apiURL := viper.GetString("ai.url")model := viper.GetString("ai.model")promptTpl := models.AppConfig.Prompts[promptType]anyVars := make([]any, len(vars))for i, v := range vars {anyVars[i] = v}prompt := fmt.Sprintf(promptTpl, anyVars...)reqBody, err := json.Marshal(models.OpenAIRequest{Model:    model,Messages: []models.Message{{Role: "user", Content: prompt}},Stream:   true,})if err != nil {return "", err}req, err := http.NewRequest("POST", apiURL, bytes.NewBuffer(reqBody))if err != nil {return "", err}req.Header.Set("Content-Type", "application/json")req.Header.Set("Authorization", "Bearer "+apiKey)client := &http.Client{}resp, err := client.Do(req)if err != nil {return "", err}defer resp.Body.Close()if resp.StatusCode != http.StatusOK {bodyBytes, _ := ioutil.ReadAll(resp.Body)return "", fmt.Errorf("AI service returned %d: %s", resp.StatusCode, string(bodyBytes))}var fullContent strings.Builderreader := bufio.NewReader(resp.Body)for {line, err := reader.ReadString('\n')if err != nil {if err == io.EOF {break}return "", err}if strings.HasPrefix(line, "data: ") {data := strings.TrimPrefix(line, "data: ")if strings.TrimSpace(data) == "[DONE]" {break}var streamResp models.OpenAIStreamResponseif err := json.Unmarshal([]byte(data), &streamResp); err == nil {if len(streamResp.Choices) > 0 {content := streamResp.Choices[0].Delta.Contentfmt.Print(content) // 实时输出fullContent.WriteString(content)}}}}return fullContent.String(), nil
}// 建议流式返回切片
func (AIUtil) StreamSuggestions(promptType string, vars ...string) ([]string, error) {content, err := AI.StreamChat(promptType, vars...)if err != nil {return nil, err}return strings.Split(strings.TrimSpace(content), "\n"), nil
}
http://www.dtcms.com/a/297705.html

相关文章:

  • 开讲啦|MBSE公开课:第二集 MBSE远景设想
  • cocos creator 3.8.6 websocke的一直报错WebSocket is not a constructor
  • Logstash 多表增量同步 MySQL 到 Elasticsearch:支持逻辑删除与热加载,Docker 快速部署实战
  • vue项目创建流程
  • XML的简略知识点
  • PyCharm高效开发全攻略
  • RHCA - CL260 | Day01:Ceph 架构及环境介绍
  • leetcode102:二叉树的层序遍历(队列实现)
  • 栈----1.有效的括号
  • iOS WebView 调试实战,文件上传与权限弹窗异常的排查路径
  • 三维模型驱动下的光伏组件智能排列方案
  • 【深入底层】C++开发简历4+4技能描述6
  • 百特搭AI低代码平台助力企业国际化业务敏捷拓展
  • 《一种采用分布式多模态传感模块的身体尺度机器人皮肤的设计、评估与应用》论文解读
  • 【日志】unity俄罗斯方块——边界限制检测
  • 如何在离线电脑win11上安装VS2022
  • PI 思维升级 PI设计的典范转移:从阻抗思维到谐振控制
  • 在 Ansys CFX Pre 中配置 RGP 表的分步指南
  • C++中的反向迭代器
  • java面试题(中级题汇总)
  • k8s 中的 deployment,statefulset,daemonset 控制器的区别
  • 特征值与特征向量
  • 腾讯云CodeBuddy+微信小程序:5分钟开发番茄小闹钟
  • 电科金仓新一代数据库一体机:国产化方案替换优质选择
  • 本地内网IP映射到公网访问如何实现?内网端口映射外网工具有哪些?
  • python学习DAY22打卡
  • 深入解析Hadoop高频面试题:HDFS读/写流程的RPC调用链
  • yolov8通道级剪枝讲解(超详细思考版)
  • 解密负载均衡:如何轻松提升业务性能
  • JS事件流