你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
在本教程中,你将生成一个完全在设备上运行的交互式聊天助手。 助手在多个交换中维护对话上下文,因此它会记住你在对话前面讨论的内容。 使用 Foundry 本地 SDK 选择模型、定义系统提示,并逐个令牌流式输出响应。
本教程中,您将学习如何:
- 设置项目并安装 Foundry 本地 SDK
- 浏览模型目录并选择模型
- 定义用于塑造助理行为的系统提示
- 使用消息历史记录实现多轮次对话
- 流式传输响应以提升响应体验
- 在会话结束时清理资源
先决条件
- 至少具有 8 GB RAM 的 Windows、macOS 或 Linux 计算机。
示例存储库
可以在 Foundry 示例GitHub存储库中找到本文的完整示例代码。 若要克隆存储库并导航到示例,请使用:
git clone https://github.com/microsoft-foundry/foundry-samples.git
cd foundry-samples/samples/csharp/foundry-local/tutorial-chat-assistant
安装软件包
dotnet add package Microsoft.AI.Foundry.Local
dotnet add package OpenAI
GitHub存储库中的 C# 示例是预配置项目。 如果要从头开始生成,则应阅读 Foundry Local SDK 参考 ,详细了解如何使用 Foundry Local 设置 C# 项目。
浏览目录并选择模型
Foundry Local SDK 提供了一个模型目录,其中列出了所有可用的模型。 在此步骤中,将初始化 SDK 并为聊天助手选择模型。
打开
Program.cs并将其内容替换为以下代码来初始化 SDK 并选择模型:CancellationToken ct = CancellationToken.None; var config = new Configuration { AppName = "foundry_local_samples", LogLevel = Microsoft.AI.Foundry.Local.LogLevel.Information }; using var loggerFactory = LoggerFactory.Create(builder => { builder.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Information); }); var logger = loggerFactory.CreateLogger<Program>(); // Initialize the singleton instance await FoundryLocalManager.CreateAsync(config, logger); var mgr = FoundryLocalManager.Instance; // Download and register all execution providers. var currentEp = ""; await mgr.DownloadAndRegisterEpsAsync((epName, percent) => { if (epName != currentEp) { if (currentEp != "") Console.WriteLine(); currentEp = epName; } Console.Write($"\r {epName.PadRight(30)} {percent,6:F1}%"); }); if (currentEp != "") Console.WriteLine(); // Select and load a model from the catalog var catalog = await mgr.GetCatalogAsync(); var model = await catalog.GetModelAsync("qwen2.5-0.5b") ?? throw new Exception("Model not found"); await model.DownloadAsync(progress => { Console.Write($"\rDownloading model: {progress:F2}%"); if (progress >= 100f) Console.WriteLine(); }); await model.LoadAsync(); Console.WriteLine("Model loaded and ready."); // Create one stateful native chat session for the conversation. using var chatSession = new ChatSession(model); chatSession.SetStreaming(true);该方法
GetModelAsync接受模型别名,该别名是映射到目录中特定模型的短友好名称。 该方法DownloadAsync将模型权重提取到本地缓存,并使LoadAsync模型准备好进行推理。
定义系统提示
系统提示设置助手的个性和行为。 它是对话历史记录中的第一条消息,模型在整个对话中引用它。
添加系统提示以调整助手的响应方式:
// Start the conversation with a system prompt
var systemPrompt = "You are a helpful, friendly assistant. Keep your responses " +
"concise and conversational. If you don't know something, say so.";
小窍门
尝试使用不同的系统提示来更改助手的行为。 例如,可以指示它作为海盗、教师或域专家做出响应。
实现多回合对话
聊天助手需要在多轮对话中保持上下文。 通过保留所有消息的列表(系统、用户和助理),并发送包含每个请求的完整列表来实现此目的。 模型使用此历史记录生成上下文相关的响应。
添加一个对话循环,该循环:
- 从控制台读取用户输入。
- 将用户消息追加到历史记录。
- 将完整历史记录发送到模型。
- 将助手的响应追加到历史记录中以供下一轮使用。
while (true)
{
Console.Write("You: ");
var userInput = Console.ReadLine();
if (string.IsNullOrWhiteSpace(userInput) ||
userInput.Equals("quit", StringComparison.OrdinalIgnoreCase) ||
userInput.Equals("exit", StringComparison.OrdinalIgnoreCase))
{
break;
}
using var request = new Request();
if (chatSession.TurnCount == 0)
{
request.AddItem(MessageItem.System(systemPrompt));
}
request.AddItem(MessageItem.User(userInput));
// Stream the response token by token
Console.Write("Assistant: ");
await using var streamingResponse = chatSession.ProcessStreamingRequestAsync(request, ct);
await foreach (var item in streamingResponse)
{
using (item)
{
if (item is TextItem { Type: TextItemType.Default } text)
{
Console.Write(text.Text);
Console.Out.Flush();
}
}
}
using var finalResponse = await streamingResponse.FinalResponse;
Console.WriteLine("\n");
}
每次调用CompleteChatAsync 都会接收完整的消息历史记录。 这就是模型“记住”之前轮次的方式 , 它不会在调用之间存储状态。
添加流响应
流式输出在生成每个令牌时进行打印,从而让助手显得更具响应性。 将 CompleteChatAsync 调用替换为 CompleteChatStreamingAsync 以逐个令牌流式传输响应。
更新对话循环以使用流式输出:
// Stream the response token by token
Console.Write("Assistant: ");
await using var streamingResponse = chatSession.ProcessStreamingRequestAsync(request, ct);
await foreach (var item in streamingResponse)
{
using (item)
{
if (item is TextItem { Type: TextItemType.Default } text)
{
Console.Write(text.Text);
Console.Out.Flush();
}
}
}
using var finalResponse = await streamingResponse.FinalResponse;
Console.WriteLine("\n");
流版本会累积完整响应,以便在流完成后将其添加到聊天历史记录中。
完整代码
将 Program.cs 的内容替换为完整的代码:
using Microsoft.AI.Foundry.Local;
using Microsoft.Extensions.Logging;
CancellationToken ct = CancellationToken.None;
var config = new Configuration
{
AppName = "foundry_local_samples",
LogLevel = Microsoft.AI.Foundry.Local.LogLevel.Information
};
using var loggerFactory = LoggerFactory.Create(builder =>
{
builder.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Information);
});
var logger = loggerFactory.CreateLogger<Program>();
// Initialize the singleton instance
await FoundryLocalManager.CreateAsync(config, logger);
var mgr = FoundryLocalManager.Instance;
// Download and register all execution providers.
var currentEp = "";
await mgr.DownloadAndRegisterEpsAsync((epName, percent) =>
{
if (epName != currentEp)
{
if (currentEp != "") Console.WriteLine();
currentEp = epName;
}
Console.Write($"\r {epName.PadRight(30)} {percent,6:F1}%");
});
if (currentEp != "") Console.WriteLine();
// Select and load a model from the catalog
var catalog = await mgr.GetCatalogAsync();
var model = await catalog.GetModelAsync("qwen2.5-0.5b")
?? throw new Exception("Model not found");
await model.DownloadAsync(progress =>
{
Console.Write($"\rDownloading model: {progress:F2}%");
if (progress >= 100f) Console.WriteLine();
});
await model.LoadAsync();
Console.WriteLine("Model loaded and ready.");
// Create one stateful native chat session for the conversation.
using var chatSession = new ChatSession(model);
chatSession.SetStreaming(true);
// Start the conversation with a system prompt
var systemPrompt = "You are a helpful, friendly assistant. Keep your responses " +
"concise and conversational. If you don't know something, say so.";
Console.WriteLine("\nChat assistant ready! Type 'quit' to exit.\n");
while (true)
{
Console.Write("You: ");
var userInput = Console.ReadLine();
if (string.IsNullOrWhiteSpace(userInput) ||
userInput.Equals("quit", StringComparison.OrdinalIgnoreCase) ||
userInput.Equals("exit", StringComparison.OrdinalIgnoreCase))
{
break;
}
using var request = new Request();
if (chatSession.TurnCount == 0)
{
request.AddItem(MessageItem.System(systemPrompt));
}
request.AddItem(MessageItem.User(userInput));
// Stream the response token by token
Console.Write("Assistant: ");
await using var streamingResponse = chatSession.ProcessStreamingRequestAsync(request, ct);
await foreach (var item in streamingResponse)
{
using (item)
{
if (item is TextItem { Type: TextItemType.Default } text)
{
Console.Write(text.Text);
Console.Out.Flush();
}
}
}
using var finalResponse = await streamingResponse.FinalResponse;
Console.WriteLine("\n");
}
// Clean up - unload the model
chatSession.Dispose();
await model.UnloadAsync();
Console.WriteLine("Model unloaded. Goodbye!");
运行聊天助理:
dotnet run
会看到类似于以下内容的输出:
Downloading model: 100.00%
Model loaded and ready.
Chat assistant ready! Type 'quit' to exit.
You: What is photosynthesis?
Assistant: Photosynthesis is the process plants use to convert sunlight, water, and carbon
dioxide into glucose and oxygen. It mainly happens in the leaves, inside structures
called chloroplasts.
You: Why is it important for other living things?
Assistant: It's essential because photosynthesis produces the oxygen that most living things
breathe. It also forms the base of the food chain — animals eat plants or eat other
animals that depend on plants for energy.
You: quit
Model unloaded. Goodbye!
请注意助手如何记住先前轮次的上下文 — 当你问 “为什么对其他活物很重要?” 时, 它知道你仍在谈论光合作用。
示例存储库
本文的完整示例代码在 foundry-samples GitHub 存储库中提供。 若要克隆存储库并导航到示例,请使用:
git clone https://github.com/microsoft-foundry/foundry-samples.git
cd foundry-samples/samples/javascript/foundry-local/tutorial-chat-assistant
安装软件包
npm install foundry-local-sdk openai
浏览目录并选择模型
Foundry Local SDK 提供了一个模型目录,其中列出了所有可用的模型。 在此步骤中,将初始化 SDK 并为聊天助手选择模型。
创建名为 的文件
index.js。添加以下代码以初始化 SDK 并选择模型:
// Initialize the Foundry Local SDK const manager = FoundryLocalManager.create({ appName: 'foundry_local_samples', logLevel: 'info' }); // Download and register all execution providers. let currentEp = ''; await manager.downloadAndRegisterEps((epName, percent) => { if (epName !== currentEp) { if (currentEp !== '') process.stdout.write('\n'); currentEp = epName; } process.stdout.write(`\r ${epName.padEnd(30)} ${percent.toFixed(1).padStart(5)}%`); }); if (currentEp !== '') process.stdout.write('\n'); // Select and load a model from the catalog const model = await manager.catalog.getModel('qwen2.5-0.5b'); await model.download((progress) => { process.stdout.write(`\rDownloading model: ${progress.toFixed(2)}%`); }); console.log('\nModel downloaded.'); await model.load(); console.log('Model loaded and ready.'); // Create a stateful native chat session const chatSession = new ChatSession(model); chatSession.setOptions({ search: { temperature: 0.7, maxOutputTokens: 512 } });该方法
getModel接受模型别名,该别名是映射到目录中特定模型的短友好名称。 该方法download将模型权重提取到本地缓存,并使load模型准备好进行推理。
定义系统提示
系统提示设置助手的个性和行为。 它是对话历史记录中的第一条消息,模型在整个对话中引用它。
添加系统提示以调整助手的响应方式:
// Start the conversation with a system prompt
const systemPrompt =
'You are a helpful, friendly assistant. Keep your responses ' +
'concise and conversational. If you don\'t know something, say so.';
let firstTurn = true;
小窍门
尝试使用不同的系统提示来更改助手的行为。 例如,可以指示它作为海盗、教师或域专家做出响应。
实现多回合对话
聊天助手需要在多轮对话中保持上下文。 通过保留所有消息的列表(系统、用户和助理),并发送包含每个请求的完整列表来实现此目的。 模型使用此历史记录生成上下文相关的响应。
添加一个对话循环,该循环:
- 从控制台读取用户输入。
- 将用户消息追加到历史记录。
- 将完整历史记录发送到模型。
- 将助手的响应追加到历史记录中以供下一轮使用。
while (true) {
const userInput = await askQuestion('You: ');
if (userInput.trim().toLowerCase() === 'quit' ||
userInput.trim().toLowerCase() === 'exit') {
break;
}
const request = new Request();
if (firstTurn) {
request.addItem(Item.systemMessage(systemPrompt));
firstTurn = false;
}
request.addItem(Item.userMessage(userInput));
// Stream the response token by token
process.stdout.write('Assistant: ');
const stream = chatSession.processStreamingRequest(request);
for await (const item of stream) {
if (item.type === 'text' && item.textType === 'default') {
process.stdout.write(item.text);
}
}
await stream.response;
console.log('\n');
}
每次调用completeChat 都会接收完整的消息历史记录。 这就是模型“记住”之前轮次的方式 , 它不会在调用之间存储状态。
添加流响应
流式输出在生成每个令牌时进行打印,从而让助手显得更具响应性。 将 completeChat 调用替换为 completeStreamingChat 以逐个令牌流式传输响应。
更新对话循环以使用流式输出:
// Stream the response token by token
process.stdout.write('Assistant: ');
const stream = chatSession.processStreamingRequest(request);
for await (const item of stream) {
if (item.type === 'text' && item.textType === 'default') {
process.stdout.write(item.text);
}
}
await stream.response;
console.log('\n');
流版本会累积完整响应,以便在流完成后将其添加到聊天历史记录中。
完整代码
创建一个名为 index.js 并添加以下完整代码的文件:
import {
ChatSession,
FoundryLocalManager,
Item,
Request
} from 'foundry-local-sdk';
import * as readline from 'readline';
// Initialize the Foundry Local SDK
const manager = FoundryLocalManager.create({
appName: 'foundry_local_samples',
logLevel: 'info'
});
// Download and register all execution providers.
let currentEp = '';
await manager.downloadAndRegisterEps((epName, percent) => {
if (epName !== currentEp) {
if (currentEp !== '') process.stdout.write('\n');
currentEp = epName;
}
process.stdout.write(`\r ${epName.padEnd(30)} ${percent.toFixed(1).padStart(5)}%`);
});
if (currentEp !== '') process.stdout.write('\n');
// Select and load a model from the catalog
const model = await manager.catalog.getModel('qwen2.5-0.5b');
await model.download((progress) => {
process.stdout.write(`\rDownloading model: ${progress.toFixed(2)}%`);
});
console.log('\nModel downloaded.');
await model.load();
console.log('Model loaded and ready.');
// Create a stateful native chat session
const chatSession = new ChatSession(model);
chatSession.setOptions({
search: { temperature: 0.7, maxOutputTokens: 512 }
});
// Start the conversation with a system prompt
const systemPrompt =
'You are a helpful, friendly assistant. Keep your responses ' +
'concise and conversational. If you don\'t know something, say so.';
let firstTurn = true;
// Set up readline for console input
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const askQuestion = (prompt) => new Promise((resolve) => {
if (rl.closed) return resolve('quit');
const onClose = () => resolve('quit');
rl.once('close', onClose);
try {
rl.question(prompt, (answer) => {
rl.off('close', onClose);
resolve(answer);
});
} catch {
rl.off('close', onClose);
resolve('quit');
}
});
console.log('\nChat assistant ready! Type \'quit\' to exit.\n');
while (true) {
const userInput = await askQuestion('You: ');
if (userInput.trim().toLowerCase() === 'quit' ||
userInput.trim().toLowerCase() === 'exit') {
break;
}
const request = new Request();
if (firstTurn) {
request.addItem(Item.systemMessage(systemPrompt));
firstTurn = false;
}
request.addItem(Item.userMessage(userInput));
// Stream the response token by token
process.stdout.write('Assistant: ');
const stream = chatSession.processStreamingRequest(request);
for await (const item of stream) {
if (item.type === 'text' && item.textType === 'default') {
process.stdout.write(item.text);
}
}
await stream.response;
console.log('\n');
}
// Clean up - unload the model
chatSession.dispose();
await model.unload();
console.log('Model unloaded. Goodbye!');
rl.close();
运行聊天助理:
node index.js
会看到类似于以下内容的输出:
Downloading model: 100.00%
Model downloaded.
Model loaded and ready.
Chat assistant ready! Type 'quit' to exit.
You: What is photosynthesis?
Assistant: Photosynthesis is the process plants use to convert sunlight, water, and carbon
dioxide into glucose and oxygen. It mainly happens in the leaves, inside structures
called chloroplasts.
You: Why is it important for other living things?
Assistant: It's essential because photosynthesis produces the oxygen that most living things
breathe. It also forms the base of the food chain — animals eat plants or eat other
animals that depend on plants for energy.
You: quit
Model unloaded. Goodbye!
请注意助手如何记住先前轮次的上下文 — 当你问 “为什么对其他活物很重要?” 时, 它知道你仍在谈论光合作用。
示例存储库
本文的完整示例代码在 foundry-samples GitHub 存储库中提供。 若要克隆存储库并导航到示例,请使用:
git clone https://github.com/microsoft-foundry/foundry-samples.git
cd foundry-samples/samples/python/foundry-local/tutorial-chat-assistant
安装软件包
pip install foundry-local-sdk openai
浏览目录并选择模型
Foundry Local SDK 提供了一个模型目录,其中列出了所有可用的模型。 在此步骤中,将初始化 SDK 并为聊天助手选择模型。
创建名为 的文件
main.py。添加以下代码以初始化 SDK 并选择模型:
# Initialize the Foundry Local SDK config = Configuration(app_name="foundry_local_samples") FoundryLocalManager.initialize(config) manager = FoundryLocalManager.instance # Discover and register execution providers that are not already available. missing_eps = [ep.name for ep in manager.discover_eps() if not ep.is_registered] if missing_eps: manager.download_and_register_eps(missing_eps) # Select and load a model from the catalog. model = manager.catalog.get_model("qwen2.5-0.5b") if model is None: raise RuntimeError("Model 'qwen2.5-0.5b' was not found in the catalog.") if not model.is_cached: model.download( lambda progress: print( f"\rDownloading model: {progress:.2f}%", end="", flush=True ) ) print() model.load() print("Model loaded and ready.")该方法
get_model接受模型别名,该别名是映射到目录中特定模型的短友好名称。 该方法download将模型权重提取到本地缓存,并使load模型准备好进行推理。
定义系统提示
系统提示设置助手的个性和行为。 它是对话历史记录中的第一条消息,模型在整个对话中引用它。
添加系统提示以调整助手的响应方式:
# Start the conversation with a system prompt.
system_prompt = (
"You are a helpful, friendly assistant. Keep your responses "
"concise and conversational. If you don't know something, say so."
)
小窍门
尝试使用不同的系统提示来更改助手的行为。 例如,可以指示它作为海盗、教师或域专家做出响应。
实现多回合对话
聊天助手需要在多轮对话中保持上下文。 通过保留所有消息的列表(系统、用户和助理),并发送包含每个请求的完整列表来实现此目的。 模型使用此历史记录生成上下文相关的响应。
添加一个对话循环,该循环:
- 从控制台读取用户输入。
- 将用户消息追加到历史记录。
- 将完整历史记录发送到模型。
- 将助手的响应追加到历史记录中以供下一轮使用。
while True:
user_input = input("You: ")
if user_input.strip().lower() in ("quit", "exit"):
break
# The stateful session retains earlier turns automatically.
with Request() as request:
if first_turn:
request.add_item(MessageItem.system(system_prompt))
first_turn = False
request.add_item(MessageItem.user(user_input))
print("Assistant: ", end="", flush=True)
with session.process_streaming_request(request) as stream:
for item in stream:
if (
isinstance(item, TextItem)
and item.type == TextItemType.DEFAULT
):
print(item.text, end="", flush=True)
print("\n")
每次调用complete_chat 都会接收完整的消息历史记录。 这就是模型“记住”之前轮次的方式 , 它不会在调用之间存储状态。
添加流响应
流式输出在生成每个令牌时进行打印,从而让助手显得更具响应性。 将 complete_chat 调用替换为 complete_streaming_chat 以逐个令牌流式传输响应。
更新对话循环以使用流式输出:
# The stateful session retains earlier turns automatically.
with Request() as request:
if first_turn:
request.add_item(MessageItem.system(system_prompt))
first_turn = False
request.add_item(MessageItem.user(user_input))
print("Assistant: ", end="", flush=True)
with session.process_streaming_request(request) as stream:
for item in stream:
if (
isinstance(item, TextItem)
and item.type == TextItemType.DEFAULT
):
print(item.text, end="", flush=True)
print("\n")
流版本会累积完整响应,以便在流完成后将其添加到聊天历史记录中。
完整代码
创建一个名为 main.py 并添加以下完整代码的文件:
from foundry_local_sdk import (
ChatSession,
Configuration,
FoundryLocalManager,
MessageItem,
Request,
RequestOptions,
SearchOptions,
TextItem,
TextItemType,
)
def main():
# Initialize the Foundry Local SDK
config = Configuration(app_name="foundry_local_samples")
FoundryLocalManager.initialize(config)
manager = FoundryLocalManager.instance
# Discover and register execution providers that are not already available.
missing_eps = [ep.name for ep in manager.discover_eps() if not ep.is_registered]
if missing_eps:
manager.download_and_register_eps(missing_eps)
# Select and load a model from the catalog.
model = manager.catalog.get_model("qwen2.5-0.5b")
if model is None:
raise RuntimeError("Model 'qwen2.5-0.5b' was not found in the catalog.")
if not model.is_cached:
model.download(
lambda progress: print(
f"\rDownloading model: {progress:.2f}%", end="", flush=True
)
)
print()
model.load()
print("Model loaded and ready.")
try:
# Start the conversation with a system prompt.
system_prompt = (
"You are a helpful, friendly assistant. Keep your responses "
"concise and conversational. If you don't know something, say so."
)
print("\nChat assistant ready! Type 'quit' to exit.\n")
with ChatSession(model) as session:
session.set_options(
RequestOptions(
search=SearchOptions(temperature=0.7, max_output_tokens=512)
)
)
session.set_streaming(True)
first_turn = True
while True:
user_input = input("You: ")
if user_input.strip().lower() in ("quit", "exit"):
break
# The stateful session retains earlier turns automatically.
with Request() as request:
if first_turn:
request.add_item(MessageItem.system(system_prompt))
first_turn = False
request.add_item(MessageItem.user(user_input))
print("Assistant: ", end="", flush=True)
with session.process_streaming_request(request) as stream:
for item in stream:
if (
isinstance(item, TextItem)
and item.type == TextItemType.DEFAULT
):
print(item.text, end="", flush=True)
print("\n")
finally:
# Clean up - unload the model
if model.is_loaded:
model.unload()
manager.close()
print("Model unloaded. Goodbye!")
if __name__ == "__main__":
main()
运行聊天助理:
python main.py
会看到类似于以下内容的输出:
Downloading model: 100.00%
Model loaded and ready.
Chat assistant ready! Type 'quit' to exit.
You: What is photosynthesis?
Assistant: Photosynthesis is the process plants use to convert sunlight, water, and carbon
dioxide into glucose and oxygen. It mainly happens in the leaves, inside structures
called chloroplasts.
You: Why is it important for other living things?
Assistant: It's essential because photosynthesis produces the oxygen that most living things
breathe. It also forms the base of the food chain — animals eat plants or eat other
animals that depend on plants for energy.
You: quit
Model unloaded. Goodbye!
请注意助手如何记住先前轮次的上下文 — 当你问 “为什么对其他活物很重要?” 时, 它知道你仍在谈论光合作用。
示例存储库
本文的完整示例代码在 foundry-samples GitHub 存储库中提供。 若要克隆存储库并导航到示例,请使用:
git clone https://github.com/microsoft-foundry/foundry-samples.git
cd foundry-samples/samples/rust/foundry-local/tutorial-chat-assistant
安装软件包
cargo add foundry-local-sdk
cargo add tokio --features full
cargo add tokio-stream anyhow
浏览目录并选择模型
Foundry Local SDK 提供了一个模型目录,其中列出了所有可用的模型。 在此步骤中,将初始化 SDK 并为聊天助手选择模型。
打开
src/main.rs并将其内容替换为以下代码来初始化 SDK 并选择模型:// Initialize the Foundry Local SDK let manager = FoundryLocalManager::create(FoundryLocalConfig::new("foundry_local_samples"))?; manager .download_and_register_eps_with_progress(None, { let mut current_ep = String::new(); move |ep_name: &str, percent: f64| { if ep_name != current_ep { if !current_ep.is_empty() { println!(); } current_ep = ep_name.to_string(); } print!("\r {ep_name:<30} {percent:5.1}%"); io::stdout().flush().ok(); } }) .await?; println!(); let model = manager.catalog().get_model("qwen2.5-0.5b").await?; if !model.is_cached().await? { println!("Downloading model..."); model .download(Some(|progress: f64| { print!("\r {progress:.1}%"); io::stdout().flush().ok(); })) .await?; println!(); } model.load().await?; let session = ChatSession::new(&model).await?; session .set_options(RequestOptions { search: SearchOptions { temperature: Some(0.7), max_output_tokens: Some(512), ..Default::default() }, ..Default::default() }) .await?; println!("Model loaded and ready.");该方法
get_model接受模型别名,该别名是映射到目录中特定模型的短友好名称。 该方法download将模型权重提取到本地缓存,并使load模型准备好进行推理。
定义系统提示
系统提示设置助手的个性和行为。 它是对话历史记录中的第一条消息,模型在整个对话中引用它。
添加系统提示以调整助手的响应方式:
let system_prompt = "You are a helpful, friendly assistant. Keep your responses concise and \
conversational. If you don't know something, say so.";
小窍门
尝试使用不同的系统提示来更改助手的行为。 例如,可以指示它作为海盗、教师或域专家做出响应。
实现多回合对话
聊天助手需要在多轮对话中保持上下文。 通过保留所有消息(系统、用户和助理)的向量并发送包含每个请求的完整列表来实现此目的。 模型使用此历史记录生成上下文相关的响应。
添加一个对话循环,该循环:
- 从控制台读取用户输入。
- 将用户消息追加到历史记录。
- 将完整历史记录发送到模型。
- 将助手的响应追加到历史记录中以供下一轮使用。
loop {
print!("You: ");
io::stdout().flush()?;
let mut input = String::new();
stdin.lock().read_line(&mut input)?;
let input = input.trim();
if input.eq_ignore_ascii_case("quit") || input.eq_ignore_ascii_case("exit") {
break;
}
if input.is_empty() {
continue;
}
let mut items = Vec::new();
if session.turn_count() == 0 {
items.push(Item::system_message(vec![Item::text(system_prompt)]));
}
items.push(Item::user_message(vec![Item::text(input)]));
print!("Assistant: ");
io::stdout().flush()?;
let mut stream = session.process_streaming_request(Request::from_items(items));
while let Some(item) = stream.next().await {
if let Item::Text {
text,
kind: TextKind::Default,
} = item?
{
print!("{text}");
io::stdout().flush()?;
}
}
println!("\n");
}
每次调用complete_chat 都会接收完整的消息历史记录。 这就是模型“记住”之前轮次的方式 , 它不会在调用之间存储状态。
添加流响应
流式输出在生成每个令牌时进行打印,从而让助手显得更具响应性。 将 complete_chat 调用替换为 complete_streaming_chat 以逐个令牌流式传输响应。
更新对话循环以使用流式输出:
print!("Assistant: ");
io::stdout().flush()?;
let mut stream = session.process_streaming_request(Request::from_items(items));
while let Some(item) = stream.next().await {
if let Item::Text {
text,
kind: TextKind::Default,
} = item?
{
print!("{text}");
io::stdout().flush()?;
}
}
println!("\n");
流版本会累积完整响应,以便在流完成后将其添加到聊天历史记录中。
完整代码
将 src/main.rs 的内容替换为完整的代码:
use foundry_local_sdk::{
ChatSession, FoundryLocalConfig, FoundryLocalManager, Item, Request, RequestOptions,
SearchOptions, TextKind,
};
use std::io::{self, BufRead, Write};
use tokio_stream::StreamExt;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Initialize the Foundry Local SDK
let manager = FoundryLocalManager::create(FoundryLocalConfig::new("foundry_local_samples"))?;
manager
.download_and_register_eps_with_progress(None, {
let mut current_ep = String::new();
move |ep_name: &str, percent: f64| {
if ep_name != current_ep {
if !current_ep.is_empty() {
println!();
}
current_ep = ep_name.to_string();
}
print!("\r {ep_name:<30} {percent:5.1}%");
io::stdout().flush().ok();
}
})
.await?;
println!();
let model = manager.catalog().get_model("qwen2.5-0.5b").await?;
if !model.is_cached().await? {
println!("Downloading model...");
model
.download(Some(|progress: f64| {
print!("\r {progress:.1}%");
io::stdout().flush().ok();
}))
.await?;
println!();
}
model.load().await?;
let session = ChatSession::new(&model).await?;
session
.set_options(RequestOptions {
search: SearchOptions {
temperature: Some(0.7),
max_output_tokens: Some(512),
..Default::default()
},
..Default::default()
})
.await?;
println!("Model loaded and ready.");
let system_prompt = "You are a helpful, friendly assistant. Keep your responses concise and \
conversational. If you don't know something, say so.";
println!("\nChat assistant ready! Type 'quit' to exit.\n");
let stdin = io::stdin();
loop {
print!("You: ");
io::stdout().flush()?;
let mut input = String::new();
stdin.lock().read_line(&mut input)?;
let input = input.trim();
if input.eq_ignore_ascii_case("quit") || input.eq_ignore_ascii_case("exit") {
break;
}
if input.is_empty() {
continue;
}
let mut items = Vec::new();
if session.turn_count() == 0 {
items.push(Item::system_message(vec![Item::text(system_prompt)]));
}
items.push(Item::user_message(vec![Item::text(input)]));
print!("Assistant: ");
io::stdout().flush()?;
let mut stream = session.process_streaming_request(Request::from_items(items));
while let Some(item) = stream.next().await {
if let Item::Text {
text,
kind: TextKind::Default,
} = item?
{
print!("{text}");
io::stdout().flush()?;
}
}
println!("\n");
}
drop(session);
model.unload().await?;
println!("Model unloaded. Goodbye!");
Ok(())
}
运行聊天助理:
cargo run
会看到类似于以下内容的输出:
Downloading model: 100.00%
Model loaded and ready.
Chat assistant ready! Type 'quit' to exit.
You: What is photosynthesis?
Assistant: Photosynthesis is the process plants use to convert sunlight, water, and carbon
dioxide into glucose and oxygen. It mainly happens in the leaves, inside structures
called chloroplasts.
You: Why is it important for other living things?
Assistant: It's essential because photosynthesis produces the oxygen that most living things
breathe. It also forms the base of the food chain — animals eat plants or eat other
animals that depend on plants for energy.
You: quit
Model unloaded. Goodbye!
请注意助手如何记住先前轮次的上下文 — 当你问 “为什么对其他活物很重要?” 时, 它知道你仍在谈论光合作用。
示例存储库
克隆 Foundry 示例GitHub存储库并转到 C++ 示例:
git clone https://github.com/microsoft-foundry/foundry-samples.git
cd foundry-samples/samples/cpp/foundry-local/tutorial-chat-assistant
安装软件包
C++ 示例需要:
配置并生成示例:
cmake -S . -B build
cmake --build build --config Release
在配置期间,示例将版本 2.2.1 的 Microsoft.AI.Foundry.Local.Runtime NuGet 包还原到 build/_packages。 该包包含用于 Windows、Linux 和 macOS 的 C++ 标头和本机库。 不需要单独的 WinML 包。
CMake 配置会根据您的操作系统和架构选择运行时资源,并将所需的本机库复制到可执行文件旁边。 在 macOS 和 Linux 上,从 build中运行可执行文件。 在 Windows 上,运行位于 .exe 的 build 文件。
浏览目录并选择模型
初始化 SDK,从目录中选择模型,然后下载并加载它:
Configuration config("foundry_local_cpp_tutorial_chat");
Manager manager(std::move(config));
auto model = SelectChatModel(manager.GetCatalog());
if (!model) {
throw std::runtime_error("No supported CPU chat model was found.");
}
if (!model->IsCached()) {
model->Download([](float progress) {
std::cout << "\rDownloading model: " << static_cast<int>(progress) << "%" << std::flush;
return 0;
});
std::cout << "\n";
}
model->Load();
定义系统提示
添加系统提示以调整助手的响应方式:
Request system_prompt{
SystemMessage(
"You are a concise, friendly local assistant. State when you are unsure."),
};
session.ProcessRequest(system_prompt);
实现多回合对话
维护会话历史记录,并随每个请求一起发送它:
std::cout << "Enter a message, or type 'exit'.\n";
for (std::string input; std::cout << "You: " && std::getline(std::cin, input);) {
if (input == "exit" || input == "quit") {
break;
}
if (input.empty()) {
continue;
}
EnableStreaming(session);
Request request{UserMessage(input)};
std::cout << "Assistant: ";
session.ProcessRequest(request);
std::cout << "\n";
}
添加流响应
在模型生成响应文本时流式传输响应文本:
void EnableStreaming(ChatSession& session) {
session.SetStreamingCallback([](Item item) {
if (item.GetType() == FOUNDRY_LOCAL_ITEM_TEXT &&
item.GetText().type == FOUNDRY_LOCAL_TEXT_ITEM_TYPE_DEFAULT) {
std::cout << item.GetText().text << std::flush;
}
return 0;
});
}
完整代码
#include <foundry_local/foundry_local_cpp.h>
#include <iostream>
#include <memory>
#include <string>
using namespace foundry_local;
std::unique_ptr<IModel> SelectChatModel(ICatalog& catalog) {
for (const std::string alias : {"qwen2.5-0.5b", "qwen3.5-0.8b"}) {
auto model = catalog.GetModel(alias);
if (!model) {
continue;
}
for (const auto& variant : model->GetVariants()) {
const auto info = variant->GetInfo();
if (info.DeviceType() == FOUNDRY_LOCAL_DEVICE_CPU &&
(info.Task() == "chat-completion" || info.Task() == "coding")) {
model->SelectVariant(*variant);
return model;
}
}
}
return nullptr;
}
void EnableStreaming(ChatSession& session);
int main() {
try {
Configuration config("foundry_local_cpp_tutorial_chat");
Manager manager(std::move(config));
auto model = SelectChatModel(manager.GetCatalog());
if (!model) {
throw std::runtime_error("No supported CPU chat model was found.");
}
if (!model->IsCached()) {
model->Download([](float progress) {
std::cout << "\rDownloading model: " << static_cast<int>(progress) << "%" << std::flush;
return 0;
});
std::cout << "\n";
}
model->Load();
{
ChatSession session(*model);
session.SetOptions({
.search = {.temperature = 0.2F, .max_output_tokens = 512, .seed = 42},
});
Request system_prompt{
SystemMessage(
"You are a concise, friendly local assistant. State when you are unsure."),
};
session.ProcessRequest(system_prompt);
std::cout << "Enter a message, or type 'exit'.\n";
for (std::string input; std::cout << "You: " && std::getline(std::cin, input);) {
if (input == "exit" || input == "quit") {
break;
}
if (input.empty()) {
continue;
}
EnableStreaming(session);
Request request{UserMessage(input)};
std::cout << "Assistant: ";
session.ProcessRequest(request);
std::cout << "\n";
}
}
model->Unload();
manager.Shutdown();
} catch (const Error& error) {
std::cerr << "Foundry Local error [" << error.Code() << "]: " << error.what() << "\n";
return 1;
} catch (const std::exception& error) {
std::cerr << "Error: " << error.what() << "\n";
return 1;
}
return 0;
}
void EnableStreaming(ChatSession& session) {
session.SetStreamingCallback([](Item item) {
if (item.GetType() == FOUNDRY_LOCAL_ITEM_TEXT &&
item.GetText().type == FOUNDRY_LOCAL_TEXT_ITEM_TYPE_DEFAULT) {
std::cout << item.GetText().text << std::flush;
}
return 0;
});
}
运行聊天助理:
./build/tutorial-chat-assistant
清理资源
卸载模型后,模型权重将保留在本地缓存中。 这意味着下次运行应用程序时,将跳过下载步骤,模型加载速度更快。 除非需要回收磁盘空间,否则不需要进行额外的清理。