15、Chat Completion Agent

15、Chat Completion Agent

Chat Completion Agent (聊天补全智能体)

聊天补全服务是任何LLM提供的最基础服务之一,SK 通过对聊天补全服务的抽象提供了统一的接口IChatCompletionService以实现不同大模型的统一调用,例如,开发者只需通过AddAzureOpenAIChatCompletion或AddOpenAIChatCompletion方法注册服务,无需关注底层API细节(如请求格式、鉴权方式)。

既然有了统一接口的聊天补全服务,为什么还要SK中还要在其基础之提供了一个Chat Completion Agent 呢?

  1. 在混合使用多个LLM(如GPT-4处理创意任务、Deepseek处理逻辑推理)的场景下,Agent需要根据任务类型自动选择最佳模型。
  2. Agent支持预定义Prompt Template,标准化输入格式。例如,检测用户意图时,可强制模型从固定选项(如“发送邮件”“创建文档”)中选择,避免自由文本导致的不可控结果。
  3. Agent可集成Plugins(如本地代码插件、API接口插件),扩展模型的实际能力。例如,通过添加“天气查询插件”,Agent可将用户请求“明天会下雨吗”转换为调用天气API的动作,虽然利用Function Calling也能实现,但是Agent更像是一组集合。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#pragma warning disable SKEXP0001 

using Microsoft.SemanticKernel.Agents;
using Microsoft.SemanticKernel.Connectors.OpenAI;

IKernelBuilder builder = Kernel.CreateBuilder();

// 初始化多个AIChatCompletion.
builder.AddAzureOpenAIChatCompletion(/*<...service configuration>*/, serviceId: "service-1");
builder.AddAzureOpenAIChatCompletion(/*<...service configuration>*/, serviceId: "service-2");

Kernel kernel = builder.Build();

// 使用指定的服务标识符创建一个聊天补全智能体.
ChatCompletionAgent agent =
new()
{
Name = "<agent name>",
Instructions = "<agent instructions>", //作为system的描述词
Kernel = kernel,
Arguments = // 通过内核参数指定服务标识符
new KernelArguments(
new OpenAIPromptExecutionSettings()
{
ServiceId = "service-2" // The target service-identifier.
})
};

// 导入插件
KernelPlugin plugin = KernelPluginFactory.CreateFromType<MathPlugin>();
agent.Kernel.Plugins.Add(plugin);

ChatHistory chat = [];
var userRequest = "user request";
ChatMessageContent message = new(AuthorRole.User, userRequest);
chat.Add(message);

// Invoke agent
await foreach (ChatMessageContent message in agent.InvokeAsync(chat))
{
chat.Add(message);
}

示例演示

准备工作:

1
2
3
4
5
using PolyglotKernel= Microsoft.DotNet.Interactive.Kernel;// 引入交互式的内核命名空间,以便用户输入
var aiProviderCode = await PolyglotKernel.GetInputAsync("请输入AI服务提供商编码:");

var kernel = GetKernel(aiProviderCode);
var chatCompletionService = kernel.GetRequiredService<IChatCompletionService>();

使用SK的Chat Completion Agent 需要按照Microsoft.SemanticKernel.Agents.Core Nuget包。

1
#r "nuget: Microsoft.SemanticKernel.Agents.Core, *-*"

简单的问答Agent

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using Microsoft.SemanticKernel.Agents;
using PolyglotKernel = Microsoft.DotNet.Interactive.Kernel;// 引入交互式的内核命名空间,以便用户输入

ChatCompletionAgent agent =
new()
{
Name = "QA-Agent",
Instructions = "Ask me anything!",
Kernel = kernel
};

ChatHistory chat = [];

// Add a user request to the chat history
var userRequest = await PolyglotKernel.GetInputAsync("请输入您的问题:");
ChatMessageContent message = new(AuthorRole.User, userRequest);
chat.Add(message);

await foreach (ChatMessageContent message in agent.InvokeAsync(chat))
{
chat.Add(message);
}
chat.Display();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
"messages": [
{
"role": "system",
"content": "Ask me anything!",
"name": "QA-Agent"
},
{
"role": "user",
"content": "what's ai agent?"
}
],
"model": "gpt-4o"
}

使用插件的Agent

由于需要使用Microsoft.SemanticKernel.Plugins.Core NuGet包中定义的Plugin,当前包还处于Alpha版本,请谨慎使用。

1
#r "nuget: Microsoft.SemanticKernel.Plugins.Core, *-*"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#pragma warning disable SKEXP0001 
// 由于该插件还在演进当中,不建议在正式环境中使用,包含了一些警告,我们需要禁用警告
#pragma warning disable SKEXP0050
using Microsoft.SemanticKernel.Plugins.Core;

using Microsoft.SemanticKernel.Agents;
using Microsoft.SemanticKernel.Connectors.OpenAI;
using PolyglotKernel = Microsoft.DotNet.Interactive.Kernel;// 引入交互式的内核命名空间,以便用户输入

ChatCompletionAgent agent =
new()
{
Name = "Math-Agent",
Instructions = "You can answer math question!",
Kernel = kernel,
Arguments = new KernelArguments(
new PromptExecutionSettings()
{ FunctionChoiceBehavior = FunctionChoiceBehavior.Auto() }
) // 配置自动调用插件
};

// 导入插件
var plugin = KernelPluginFactory.CreateFromType<MathPlugin>();
agent.Kernel.Plugins.Add(plugin);

ChatHistory chat = [];

// Add a user request to the chat history
var userRequest = await PolyglotKernel.GetInputAsync("请输入您的问题:");
ChatMessageContent message = new(AuthorRole.User, userRequest);
chat.Add(message);

await foreach (ChatMessageContent message in agent.InvokeAsync(chat))
{
chat.Add(message);
}
chat.Display();

指定模板的Agent

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
using Microsoft.SemanticKernel.Agents;
using Microsoft.SemanticKernel.Connectors.OpenAI;
using PolyglotKernel = Microsoft.DotNet.Interactive.Kernel;// 引入交互式的内核命名空间,以便用户输入

PromptTemplateConfig templateConfig = new()
{
Template = "Translate into {{$language}}",
TemplateFormat = "semantic-kernel"
};

ChatCompletionAgent agent = new (
templateConfig: templateConfig,
templateFactory : new KernelPromptTemplateFactory())
{
Name = "Translate-Agent",
Kernel = kernel,
Arguments = new KernelArguments(){
{ "language", "Chinese" }
}
};

ChatHistory chat = [];

// Add a user request to the chat history
var userRequest = await PolyglotKernel.GetInputAsync("请输入您的问题:");
ChatMessageContent message = new(AuthorRole.User, userRequest);
chat.Add(message);

await foreach (ChatMessageContent message in agent.InvokeAsync(chat))
{
chat.Add(message);
}
chat.Display();

限定历史记录的Agent

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#pragma warning disable SKEXP0001
#pragma warning disable SKEXP0110

using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Agents;
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel.Connectors.OpenAI;
using PolyglotKernel = Microsoft.DotNet.Interactive.Kernel;// 引入交互式的内核命名空间,以便用户输入

ChatCompletionAgent agent =
new()
{
Name = "QA-Agent",
Instructions = "Ask me anything!",
Kernel = kernel,
HistoryReducer = new ChatHistoryTruncationReducer(3)
};

ChatHistory chat = [];

// Add a user request to the chat history
while(true)
{
var userRequest = await PolyglotKernel.GetInputAsync("请输入您的问题:");
ChatMessageContent userMessage = new(AuthorRole.User, userRequest);
chat.Add(userMessage);
Console.WriteLine("User: " + userRequest);

await agent.ReduceAsync(chat);

await foreach (ChatMessageContent message in agent.InvokeAsync(chat))
{
chat.Add(message);
Console.WriteLine("Agent: " + message.Content);
}
}
User: what's AI?
Agent: Artificial Intelligence (AI) refers to the simulation of human intelligence in machines that are programmed to think and learn like humans. These systems can perform tasks that typically require human intelligence, such as visual perception, speech recognition, decision-making, language translation, and more. AI technologies utilize algorithms and models to process large datasets and improve their performance over time through techniques like machine learning and deep learning. The ultimate goal of AI is to develop systems that can function autonomously and adaptively in complex environments.
User: What's semantci kernel?
Agent: A semantic kernel typically refers to a computational framework or model that focuses on capturing and utilizing semantic meaning from data, particularly in the context of machine learning and natural language processing. The term can have slightly different meanings depending on the context, but here are some general interpretations:

1. **Kernel Methods in Machine Learning**: In the field of machine learning, particularly in support vector machines (SVMs), a "semantic kernel" could refer to a kernel function designed to capture the semantic relationships in the data. Kernel functions transform data into a higher-dimensional space to make it easier to classify. A semantic kernel would aim to maintain the semantic similarity between data points in this transformation.

2. **Semantic Kernel as a Model**: In natural language processing, semantic kernels could be employed to understand and process the semantic content of text. This involves mapping text data into a semantic space where the relationships between different words or concepts are preserved. Techniques like Latent Semantic Analysis (LSA) or using embeddings like Word2Vec or BERT might be involved in creating these semantic representations.

3. **Kernel Functions for Specific Tasks**: In some contexts, semantic kernels are crafted for specific tasks such as text classification, information retrieval, or semantic similarity measurement, where the goal is to improve the performance of algorithms by incorporating semantic understanding.

Overall, the concept centers on enhancing traditional computational methods by integrating semantic understanding, enabling systems to process and understand data at a more meaningful level.
User: What's autogen?
Agent: "Autogen" can refer to different concepts depending on the context in which it is used. Here are some possible interpretations:

1. **Auto-Generated Code**: In software development, "autogen" can refer to automatically generated code. Tools or scripts might autogenerate parts of the code to simplify repetitive tasks, ensure consistency, or conform to certain standards. This is common in scenarios like API client libraries, where the code is generated based on a specification (e.g., OpenAPI).

2. **Autogen in AI/ML**: In the context of artificial intelligence and machine learning, "autogen" could be shorthand for automatically generating outputs, such as generating text, images, or other types of data. For example, text autogeneration could involve using AI models like GPT to create human-like text.

3. **Trademark or Company Name**: "Autogen" may also be a trademark, product, or company name in various industries. A company or service named Autogen might focus on automatic generation processes in a specific field, such as energy systems, data processing, or other technical areas.

4. **General Use in Technology**: In general technology parlance, "autogen" usually implies some form of automation, where a system generates something without manual intervention, often to enhance efficiency or accuracy.

If you have a specific domain or context in mind, please provide more details for a more precise explanation.
作者

步步为营

发布于

2025-04-15

更新于

2025-04-15

许可协议