【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)都兼容这种格式,因为它已经成为行业标准。

相关推荐
serve the people16 小时前
Prompt Serialization in LangChain
数据库·langchain·prompt
AI Echoes16 小时前
LangChain 使用语义路由选择不同的Prompt模板
人工智能·python·langchain·prompt·agent
Wilber的技术分享16 小时前
【大模型实战笔记 6】Prompt Engineering 提示词工程
人工智能·笔记·llm·prompt·大语言模型·提示词工程
小高不会迪斯科16 小时前
大话大模型应用(二)--让大模型听话:Prompt Engineering&Context Engineering
人工智能·prompt
serve the people21 小时前
Prompt Composition with LangChain’s PipelinePromptTemplate
java·langchain·prompt
喜欢吃豆21 小时前
从入门到精通:OpenAI Prompt Engineering 与 Prompt Caching 实战详解
prompt
xn123342 天前
Anaconda Prompt系统找不到指定路径
prompt
NEFU AB-IN2 天前
Prompt Gen Desktop 管理和迭代你的 Prompt!
java·jvm·prompt
bulucc2 天前
如何写prompt?prompt收集
prompt
serve the people2 天前
Partial Prompt Templates in LangChain
服务器·langchain·prompt