操作說明: 聊天完成代理程式 (實驗性)
警告
語意核心代理程式架構是實驗性的,仍在開發中,而且可能會變更。
概觀
在此範例中,我們將探索設定外掛程式以存取 GitHub API,並提供聊天完成代理程式的範本化指示,以回答 GitHub 存放庫的相關問題。 此方法會逐步細分,以高光撰寫程序的關鍵部分。 在工作中,代理程式會在回應中提供檔引文。
串流將用來傳遞代理程序的回應。 這會在工作進行時提供即時更新。
快速入門
繼續進行功能程式代碼撰寫之前,請確定您的開發環境已完全設定和設定。
從建立 主控台 項目開始。 然後,請包含下列套件參考,以確保所有必要的相依性都可供使用。
若要從命令行新增套件相依性, dotnet
請使用 下列命令:
dotnet add package Azure.Identity
dotnet add package Microsoft.Extensions.Configuration
dotnet add package Microsoft.Extensions.Configuration.Binder
dotnet add package Microsoft.Extensions.Configuration.UserSecrets
dotnet add package Microsoft.Extensions.Configuration.EnvironmentVariables
dotnet add package Microsoft.SemanticKernel.Connectors.AzureOpenAI
dotnet add package Microsoft.SemanticKernel.Agents.Core --prerelease
如果在 Visual Studio 中管理 NuGet 套件,請確定
Include prerelease
已核取 。
項目檔 (.csproj
) 應包含下列 PackageReference
定義:
<ItemGroup>
<PackageReference Include="Azure.Identity" Version="<stable>" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="<stable>" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="<stable>" />
<PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="<stable>" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="<stable>" />
<PackageReference Include="Microsoft.SemanticKernel.Agents.Core" Version="<latest>" />
<PackageReference Include="Microsoft.SemanticKernel.Connectors.AzureOpenAI" Version="<latest>" />
</ItemGroup>
Agent Framework 是實驗性的,需要警告隱藏。 這可能會在 中當做項目檔中的 屬性來尋址 (.csproj
):
<PropertyGroup>
<NoWarn>$(NoWarn);CA2007;IDE1006;SKEXP0001;SKEXP0110;OPENAI001</NoWarn>
</PropertyGroup>
此外,請從語意核心LearnResources
項目複製 GitHub 外掛程式和模型 (GitHubPlugin.cs
和 GitHubModels.cs
) 。 在項目資料夾中新增這些檔案。
首先,建立一個資料夾來保存您的腳本(.py
檔案)和範例資源。 在檔案頂端 .py
包含下列匯入:
import asyncio
import os
import sys
from datetime import datetime
from semantic_kernel.agents import ChatCompletionAgent
from semantic_kernel.connectors.ai.function_choice_behavior import FunctionChoiceBehavior
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
from semantic_kernel.contents.chat_history import ChatHistory
from semantic_kernel.contents.chat_message_content import ChatMessageContent
from semantic_kernel.contents.utils.author_role import AuthorRole
from semantic_kernel.kernel import Kernel
# Adjust the sys.path so we can use the GitHubPlugin and GitHubSettings classes
# This is so we can run the code from the samples/learn_resources/agent_docs directory
# If you are running code from your own project, you may not need need to do this.
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
from plugins.GithubPlugin.github import GitHubPlugin, GitHubSettings # noqa: E402
此外,從語意核心LearnResources
項目複製 GitHub 外掛程式和模型 (github.py
)。 在項目資料夾中新增這些檔案。
代理程式目前無法在Java中使用。
組態
此範例需要組態設定,才能連線到遠端服務。 您必須定義 Open AI 或 Azure Open AI 以及 GitHub 的設定。
注意:如需 GitHub 個人存取令牌的相關信息,請參閱: 管理您的個人存取令牌。
# Open AI
dotnet user-secrets set "OpenAISettings:ApiKey" "<api-key>"
dotnet user-secrets set "OpenAISettings:ChatModel" "gpt-4o"
# Azure Open AI
dotnet user-secrets set "AzureOpenAISettings:ApiKey" "<api-key>" # Not required if using token-credential
dotnet user-secrets set "AzureOpenAISettings:Endpoint" "<model-endpoint>"
dotnet user-secrets set "AzureOpenAISettings:ChatModelDeployment" "gpt-4o"
# GitHub
dotnet user-secrets set "GitHubSettings:BaseUrl" "https://api.github.com"
dotnet user-secrets set "GitHubSettings:Token" "<personal access token>"
下列類別用於所有 Agent 範例中。 請務必將它包含在專案中,以確保適當的功能。 這個類別可作為後續範例的基礎元件。
using System.Reflection;
using Microsoft.Extensions.Configuration;
namespace AgentsSample;
public class Settings
{
private readonly IConfigurationRoot configRoot;
private AzureOpenAISettings azureOpenAI;
private OpenAISettings openAI;
public AzureOpenAISettings AzureOpenAI => this.azureOpenAI ??= this.GetSettings<Settings.AzureOpenAISettings>();
public OpenAISettings OpenAI => this.openAI ??= this.GetSettings<Settings.OpenAISettings>();
public class OpenAISettings
{
public string ChatModel { get; set; } = string.Empty;
public string ApiKey { get; set; } = string.Empty;
}
public class AzureOpenAISettings
{
public string ChatModelDeployment { get; set; } = string.Empty;
public string Endpoint { get; set; } = string.Empty;
public string ApiKey { get; set; } = string.Empty;
}
public TSettings GetSettings<TSettings>() =>
this.configRoot.GetRequiredSection(typeof(TSettings).Name).Get<TSettings>()!;
public Settings()
{
this.configRoot =
new ConfigurationBuilder()
.AddEnvironmentVariables()
.AddUserSecrets(Assembly.GetExecutingAssembly(), optional: true)
.Build();
}
}
若要開始使用適當的組態來執行範例程序代碼,最快的方式是在專案的根目錄建立 .env
檔案(執行腳本的位置)。
在 .env
Azure OpenAI 或 OpenAI 的檔案中設定下列設定:
AZURE_OPENAI_API_KEY="..."
AZURE_OPENAI_ENDPOINT="https://..."
AZURE_OPENAI_CHAT_DEPLOYMENT_NAME="..."
AZURE_OPENAI_API_VERSION="..."
OPENAI_API_KEY="sk-..."
OPENAI_ORG_ID=""
OPENAI_CHAT_MODEL_ID=""
設定之後,個別的 AI 服務類別會挑選必要的變數,並在具現化期間使用這些變數。
代理程式目前無法在Java中使用。
撰寫程式碼
這個範例的編碼程式牽涉到:
完整範例程式代碼會在 Final 區段中提供。 如需完整的實作,請參閱該區段。
設定
建立 聊天完成代理程式之前,必須初始化組態設定、外掛程式和 核心 。
代理程式目前無法在Java中使用。
使用外掛程式的設定來初始化外掛程式。
在這裡,會顯示訊息以指出進度。
Console.WriteLine("Initialize plugins...");
GitHubSettings githubSettings = settings.GetSettings<GitHubSettings>();
GitHubPlugin githubPlugin = new(githubSettings);
gh_settings = GitHubSettings(
token="<PAT value>"
)
kernel.add_plugin(GitHubPlugin(settings=gh_settings), plugin_name="github")
代理程式目前無法在Java中使用。
現在,使用 Kernel
IChatCompletionService
和先前建立的 GitHubPlugin
,初始化 實例。
Console.WriteLine("Creating kernel...");
IKernelBuilder builder = Kernel.CreateBuilder();
builder.AddAzureOpenAIChatCompletion(
settings.AzureOpenAI.ChatModelDeployment,
settings.AzureOpenAI.Endpoint,
new AzureCliCredential());
builder.Plugins.AddFromObject(githubPlugin);
Kernel kernel = builder.Build();
kernel = Kernel()
# Add the AzureChatCompletion AI Service to the Kernel
service_id = "agent"
kernel.add_service(AzureChatCompletion(service_id=service_id))
settings = kernel.get_prompt_execution_settings_from_service_id(service_id=service_id)
# Configure the function choice behavior to auto invoke kernel functions
settings.function_choice_behavior = FunctionChoiceBehavior.Auto()
代理程式目前無法在Java中使用。
代理程式定義
最後,我們已準備好使用聊天完成代理程式及其指示、相關聯的核心,以及預設的自變數和執行設定來具現化聊天完成代理程式。 在此情況下,我們想要自動執行任何外掛程式函式。
Console.WriteLine("Defining agent...");
ChatCompletionAgent agent =
new()
{
Name = "SampleAssistantAgent",
Instructions =
"""
You are an agent designed to query and retrieve information from a single GitHub repository in a read-only manner.
You are also able to access the profile of the active user.
Use the current date and time to provide up-to-date details or time-sensitive responses.
The repository you are querying is a public repository with the following name: {{$repository}}
The current date and time is: {{$now}}.
""",
Kernel = kernel,
Arguments =
new KernelArguments(new AzureOpenAIPromptExecutionSettings() { FunctionChoiceBehavior = FunctionChoiceBehavior.Auto() })
{
{ "repository", "microsoft/semantic-kernel" }
}
};
Console.WriteLine("Ready!");
agent = ChatCompletionAgent(
service_id="agent",
kernel=kernel,
name="SampleAssistantAgent",
instructions=f"""
You are an agent designed to query and retrieve information from a single GitHub repository in a read-only
manner.
You are also able to access the profile of the active user.
Use the current date and time to provide up-to-date details or time-sensitive responses.
The repository you are querying is a public repository with the following name: microsoft/semantic-kernel
The current date and time is: {current_time}.
""",
execution_settings=settings,
)
代理程式目前無法在Java中使用。
聊天迴圈
最後,我們能夠協調使用者與 代理程式之間的互動。 首先,建立 Chat History 對象來維護交談狀態,並建立空迴圈。
ChatHistory history = [];
bool isComplete = false;
do
{
// processing logic here
} while (!isComplete);
history = ChatHistory()
is_complete: bool = False
while not is_complete:
# processing logic here
代理程式目前無法在Java中使用。
現在讓我們在上一個迴圈中擷取用戶輸入。 在此情況下,將會忽略空的輸入,而字詞 EXIT
會發出交談已完成的訊號。 有效的輸入將會新增至 聊天記錄 作為 使用者 訊息。
Console.WriteLine();
Console.Write("> ");
string input = Console.ReadLine();
if (string.IsNullOrWhiteSpace(input))
{
continue;
}
if (input.Trim().Equals("EXIT", StringComparison.OrdinalIgnoreCase))
{
isComplete = true;
break;
}
history.Add(new ChatMessageContent(AuthorRole.User, input));
Console.WriteLine();
user_input = input("User:> ")
if not user_input:
continue
if user_input.lower() == "exit":
is_complete = True
break
history.add_message(ChatMessageContent(role=AuthorRole.USER, content=user_input))
代理程式目前無法在Java中使用。
若要產生對使用者輸入的 Agent 回應,請使用 Arguments 叫用代理程式,以提供指定目前日期和時間的最終範本參數。
然後,代理程式回應會顯示給使用者。
DateTime now = DateTime.Now;
KernelArguments arguments =
new()
{
{ "now", $"{now.ToShortDateString()} {now.ToShortTimeString()}" }
};
await foreach (ChatMessageContent response in agent.InvokeAsync(history, arguments))
{
Console.WriteLine($"{response.Content}");
}
即將推出
代理程式目前無法在Java中使用。
完成
將所有步驟結合在一起,我們有此範例的最終程序代碼。 以下提供完整的實作。
using System;
using System.Threading.Tasks;
using Azure.Identity;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Agents;
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel.Connectors.AzureOpenAI;
using Plugins;
namespace AgentsSample;
public static class Program
{
public static async Task Main()
{
// Load configuration from environment variables or user secrets.
Settings settings = new();
Console.WriteLine("Initialize plugins...");
GitHubSettings githubSettings = settings.GetSettings<GitHubSettings>();
GitHubPlugin githubPlugin = new(githubSettings);
Console.WriteLine("Creating kernel...");
IKernelBuilder builder = Kernel.CreateBuilder();
builder.AddAzureOpenAIChatCompletion(
settings.AzureOpenAI.ChatModelDeployment,
settings.AzureOpenAI.Endpoint,
new AzureCliCredential());
builder.Plugins.AddFromObject(githubPlugin);
Kernel kernel = builder.Build();
Console.WriteLine("Defining agent...");
ChatCompletionAgent agent =
new()
{
Name = "SampleAssistantAgent",
Instructions =
"""
You are an agent designed to query and retrieve information from a single GitHub repository in a read-only manner.
You are also able to access the profile of the active user.
Use the current date and time to provide up-to-date details or time-sensitive responses.
The repository you are querying is a public repository with the following name: {{$repository}}
The current date and time is: {{$now}}.
""",
Kernel = kernel,
Arguments =
new KernelArguments(new AzureOpenAIPromptExecutionSettings() { FunctionChoiceBehavior = FunctionChoiceBehavior.Auto() })
{
{ "repository", "microsoft/semantic-kernel" }
}
};
Console.WriteLine("Ready!");
ChatHistory history = [];
bool isComplete = false;
do
{
Console.WriteLine();
Console.Write("> ");
string input = Console.ReadLine();
if (string.IsNullOrWhiteSpace(input))
{
continue;
}
if (input.Trim().Equals("EXIT", StringComparison.OrdinalIgnoreCase))
{
isComplete = true;
break;
}
history.Add(new ChatMessageContent(AuthorRole.User, input));
Console.WriteLine();
DateTime now = DateTime.Now;
KernelArguments arguments =
new()
{
{ "now", $"{now.ToShortDateString()} {now.ToShortTimeString()}" }
};
await foreach (ChatMessageContent response in agent.InvokeAsync(history, arguments))
{
// Display response.
Console.WriteLine($"{response.Content}");
}
} while (!isComplete);
}
}
import asyncio
import os
import sys
from datetime import datetime
from semantic_kernel.agents import ChatCompletionAgent
from semantic_kernel.connectors.ai.function_choice_behavior import FunctionChoiceBehavior
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
from semantic_kernel.contents.chat_history import ChatHistory
from semantic_kernel.contents.chat_message_content import ChatMessageContent
from semantic_kernel.contents.utils.author_role import AuthorRole
from semantic_kernel.kernel import Kernel
# Adjust the sys.path so we can use the GitHubPlugin and GitHubSettings classes
# This is so we can run the code from the samples/learn_resources/agent_docs directory
# If you are running code from your own project, you may not need need to do this.
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
from plugins.GithubPlugin.github import GitHubPlugin, GitHubSettings # noqa: E402
###################################################################
# The following sample demonstrates how to create a simple, #
# ChatCompletionAgent to use a GitHub plugin to interact #
# with the GitHub API. #
###################################################################
async def main():
kernel = Kernel()
# Add the AzureChatCompletion AI Service to the Kernel
service_id = "agent"
kernel.add_service(AzureChatCompletion(service_id=service_id))
settings = kernel.get_prompt_execution_settings_from_service_id(service_id=service_id)
# Configure the function choice behavior to auto invoke kernel functions
settings.function_choice_behavior = FunctionChoiceBehavior.Auto()
# Set your GitHub Personal Access Token (PAT) value here
gh_settings = GitHubSettings(token="<PAT value>")
kernel.add_plugin(plugin=GitHubPlugin(gh_settings), plugin_name="GithubPlugin")
current_time = datetime.now().isoformat()
# Create the agent
agent = ChatCompletionAgent(
service_id="agent",
kernel=kernel,
name="SampleAssistantAgent",
instructions=f"""
You are an agent designed to query and retrieve information from a single GitHub repository in a read-only
manner.
You are also able to access the profile of the active user.
Use the current date and time to provide up-to-date details or time-sensitive responses.
The repository you are querying is a public repository with the following name: microsoft/semantic-kernel
The current date and time is: {current_time}.
""",
execution_settings=settings,
)
history = ChatHistory()
is_complete: bool = False
while not is_complete:
user_input = input("User:> ")
if not user_input:
continue
if user_input.lower() == "exit":
is_complete = True
break
history.add_message(ChatMessageContent(role=AuthorRole.USER, content=user_input))
async for response in agent.invoke(history=history):
print(f"{response.content}")
if __name__ == "__main__":
asyncio.run(main())
代理程式目前無法在Java中使用。