什么是 AI Prompt?
- 最简单定义
Prompt 就是你给 AI 的「指令、提示词、问话、要求」。
你跟 AI 说的每一句话、每一段要求,都是 Prompt。
就像:
你给人下任务 = 给 AI 写 Prompt
人能不能做好,看你指令清不清楚
AI 能不能答好,全看 Prompt 写得好不好
任务:
1.修改代码,加入 System Prompt(角色设定)
2.尝试 Few-shot(给几个例子)
3.尝试约束输出格式(JSON/Markdown)
源码:使用下面源码,按顺序修改messages内容后调试,感受变化。
csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace ConsoleApp1.BLL
{
//Prompt工程基础
//加入 System Prompt(角色设定)
//尝试 Few-shot(给几个例子)
//尝试约束输出格式(JSON/Markdown)
public class Day2_Prompt
{
public static async Task Day2(string apiKey, string url)
{
// 替换成你的阿里云百炼 API Key
//const string apiKey = "此处写你申请的API Key";
//const string url = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions";
var client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
var requestBody = new
{
model = "qwen-turbo",
//4. 约束输出位xml格式
messages = new[]
{
new { role = "system", content = "只输出 XML 完整格式,不要有其他内容。" },
new { role = "user", content = "RAG 是一种结合检索和生成的技术,可以解决大模型的幻觉问题。" } //AI 回答:{"summary":"RAG 是一种结合检索和生成的技术,可以解决大模型的幻觉问题。", "keywords":["RAG", "检索", "生成", "大模型", "幻觉问题"]}
}
// 3. 约束输出为 JSON
//messages = new[]
// {
// new { role = "system", content = "只输出 JSON 格式,不要有其他内容。格式:{\"summary\":\"...\", \"keywords\":[\"...\"]}" },
// new { role = "user", content = "RAG 是一种结合检索和生成的技术,可以解决大模型的幻觉问题。" } //AI 回答:{"summary":"RAG 是一种结合检索和生成的技术,可以解决大模型的幻觉问题。", "keywords":["RAG", "检索", "生成", "大模型", "幻觉问题"]}
// }
//2.Few-shot少样本学习
//messages = new[]
//{
// new { role = "system", content = "将用户输入分类为:技术问题、闲聊、其他" },
// new { role = "user", content = "C# 怎么读取文件" },
// new { role = "assistant", content = "技术问题" },
// new { role = "user", content = "今天天气不错" },
// new { role = "assistant", content = "闲聊" },
// //new { role = "user", content = "什么是 RAG" } // 让 AI 分类这个 //AI 回答:技术问题
// new { role = "user", content = "今天吃什么" } // 让 AI 分类这个 //AI 回答:闲聊
//}
//1.加入 System Prompt(角色设定)
//messages = new[]
//{
// new { role="system",content="你是一个.net技术专家,回答要简洁、准确,不超过50个字。"}, //AI 回答:.NET 是由微软开发的跨平台开发框架,用于构建多种类型的应用程序。
// new { role = "user", content = "用一句话说明什么是 .NET" }
//}
};
var json = JsonSerializer.Serialize(requestBody);
var content = new StringContent(json, Encoding.UTF8, "application/json");
Console.WriteLine("正在调用阿里云百炼 AI...\n");
try
{
var response = await client.PostAsync(url, content);
var responseString = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
var doc = JsonDocument.Parse(responseString);
var answer = doc.RootElement
.GetProperty("choices")[0]
.GetProperty("message")
.GetProperty("content")
.GetString();
Console.WriteLine($"AI 回答:{answer}");
}
else
{
Console.WriteLine($"HTTP 错误:{response.StatusCode}");
Console.WriteLine($"响应内容:{responseString}");
}
}
catch (Exception ex)
{
Console.WriteLine($"异常:{ex.Message}");
}
}
}
}
跑通后,试试不同的 System Prompt 和输出格式。