【GoLang】调用llm时提示词prompt的介绍以及使用方式

介绍

提示词是一种与大模型交互的对话格式, 它以 JSON 格式定义了一个消息列表(messages),包含了系统消息和用户消息。

我们向AI提问时,其实发给AI的都是提示词,别看我们只是简单输入了一句话,但大模型内部其实自动帮我们把这句话转换为提示词的形式了。

但是我们现在如何手动来设置提示词呢?请看下文

设置提示词

总的流程就是:声明 chatTemplate 表示提示词模板,声明 input 用于填充 chatTemplate 模板中的占位符,最终二者结合得到prompt。

Go 复制代码
package main

import (
	"context"
	"fmt"
	"github.com/tmc/langchaingo/llms"
	"github.com/tmc/langchaingo/llms/openai"
	"github.com/tmc/langchaingo/prompts"
)

func main() {
	// 初始化大模型llm
	llm, _ := openai.New(
		openai.WithModel("deepseek-reasoner"),
		openai.WithToken("sk-2c4e9ad917cf48d8ad834dc5b98e7e01"),
		openai.WithBaseURL("https://api.deepseek.com"),
	)

	// 什么提示词模板
	chatTemplate := prompts.NewChatPromptTemplate([]prompts.MessageFormatter{
		prompts.NewSystemMessagePromptTemplate("你是一个有帮助的助手,擅长回答天气相关问题。", nil),
		prompts.NewHumanMessagePromptTemplate("{{.greeting}}!今天{{.city}}的天气怎么样?", []string{"greeting", "city"}),
	})

	// input 用于填充 chatTemplate 模板中的占位符变量
	input := map[string]interface{}{
		"greeting": "早上好",
		"city":     "北京",
	}

	// 根据模板和变量生成为最终的提示词
	prompt, _ := chatTemplate.Format(input)

	// 通过大模型llm调用API
	ctx := context.Background()
	completion, _ := llms.GenerateFromSinglePrompt(
		ctx,
		llm,
		prompt,
	)

	// 输出大模型生成的答复
	fmt.Println(completion)
}

使用提示词的好处

好处1. 支持对话上下文

messages 数组允许你提供多轮对话的历史记录,模型可以根据之前的消息生成更符合上下文的回复。

bash 复制代码
"messages": [
  {"role": "system", "content": "You are a helpful assistant."}, // 开启对话时生成的
  {"role": "user", "content": "What is the capital of France?"}, // 用户生成的
  {"role": "assistant", "content": "The capital of France is Paris."}, // ai生成的
  {"role": "user", "content": "What about Spain?"}    // 用户生成的
]

在这个例子中,模型知道用户之前问了法国的首都,现在问西班牙的首都,可以直接回答:"The capital of Spain is Madrid.",而不需要重复澄清。

好处2. 区分角色

通过 role 字段,模型可以区分不同身份(系统、用户、AI)发送消息,从而采取不同的处理方式。

  • role: "system":设置模型的全局行为或角色,通常只在对话开始时提供一次。
  • role: "user":表示用户的输入,模型会直接回应。
  • role: "assistant":表示模型的回复,通常由模型生成,但也可以手动添加以模拟对话历史。

好处3. 兼容性和标准化

这种 messages 格式是 OpenAI 的 Chat API 标准格式(Chat Completions API),被广泛采用。

许多 LLM 提供商(如 DeepSeek、Anthropic)都兼容这种格式,因为它已经成为行业标准。

相关推荐
alex1002 天前
AI Agent开发学习系列 - langchain之LCEL(5):如何创建一个Agent?
人工智能·python·语言模型·langchain·prompt·向量数据库·ai agent
liliangcsdn2 天前
mac测试ollama llamaindex
数据仓库·人工智能·prompt·llama
旧曲重听14 天前
基于Prompt 的DevOps 与终端重塑
人工智能·prompt·devops
AIGC包拥它5 天前
RAG项目实战:LangChain 0.3集成 Milvus 2.5向量数据库,构建大模型智能应用
人工智能·python·langchain·prompt·个人开发·milvus
so.far_away5 天前
The Survey of Few-shot Prompt Learning on Graph
prompt
Xy-unu6 天前
[Semantic Seg][KD]FreeKD: Knowledge Distillation via Semantic Frequency Prompt
prompt
寒水馨7 天前
构建企业级 AI Agent:不只是 Prompt 工程,更是系统工程
人工智能·ai·prompt·agent·ai agent·ai工程
semantist@语校8 天前
面向向量检索的教育QA建模:九段日本文化研究所日本语学院的Prompt策略分析(6 / 500)
人工智能·支持向量机·百度·ai·开源·prompt·数据集
Chan168 天前
【 SpringAI核心特性 | Prompt工程 】
java·spring boot·后端·spring·prompt·ai编程
喜欢猪猪8 天前
Qwen3-8B 的 TTFT 性能分析:16K 与 32K 输入 Prompt 的推算公式与底层原理详解
prompt