一部のエージェントを試験段階からリリース候補ステージに移行するにつれて、API を更新して、使用を簡素化および合理化しました。 使用可能な最新の API を使用するように既存のコードを更新する方法については、特定のシナリオ ガイドを参照してください。
共通エージェント呼び出し API
バージョン 1.43.0 では、新しい共通エージェント呼び出し API をリリースしています。これにより、すべてのエージェントの種類を共通 API 経由で呼び出すことができます。
この新しい API を有効にするために、会話スレッドを表し、さまざまなエージェントの種類のさまざまなスレッド管理要件を抽象化する AgentThreadの概念を導入します。 一部のエージェントの種類では、今後、同じエージェントで異なるスレッド実装を使用できるようになります。
紹介する一般的な Invoke メソッドを使用すると、エージェントに渡すメッセージとオプションの AgentThreadを指定できます。
AgentThread が指定されている場合は、AgentThreadで既に会話が続行されます。
AgentThread が指定されていない場合は、新しい既定のスレッドが作成され、応答の一部として返されます。
基になるエージェント サービスのスレッド ID があり、そのスレッドを続行する場合など、AgentThread インスタンスを手動で作成することもできます。 また、スレッドのオプション (ツールの関連付けなど) をカスタマイズすることもできます。
エージェントに依存しないコードで任意のエージェントを使用する方法の簡単な例を次に示します。
private async Task UseAgentAsync(Agent agent, AgentThread? agentThread = null)
{
// Invoke the agent, and continue the existing thread if provided.
var responses = agent.InvokeAsync(new ChatMessageContent(AuthorRole.User, "Hi"), agentThread);
// Output results.
await foreach (AgentResponseItem<ChatMessageContent> response in responses)
{
Console.WriteLine(response);
agentThread = response.Thread;
}
// Delete the thread if required.
if (agentThread is not null)
{
await agentThread.DeleteAsync();
}
}
次の変更が適用されました。
Azure AI エージェントのスレッド オプション
AzureAIAgent は現在、AzureAIAgentThread型のスレッドのみをサポートしています。
エージェントの呼び出し時にスレッドを自動的に作成できるだけでなく、AzureAIAgentThreadのインスタンスを手動で作成することもできます。
AzureAIAgentThread では、カスタマイズされたツールとメタデータを用いた作成が可能であり、さらに会話を始めるためのメッセージをサポートします。
AgentThread thread = new AzureAIAgentThread(
agentsClient,
messages: seedMessages,
toolResources: tools,
metadata: metadata);
既存の会話を続行する AzureAIAgentThread のインスタンスを構築することもできます。
AgentThread thread = new AzureAIAgentThread(
agentsClient,
id: "my-existing-thread-id");
Bedrock エージェント スレッド オプション
BedrockAgent は現在、BedrockAgentThread型のスレッドのみをサポートしています。
エージェントの呼び出し時にスレッドを自動的に作成できるだけでなく、BedrockAgentThreadのインスタンスを手動で作成することもできます。
AgentThread thread = new BedrockAgentThread(amazonBedrockAgentRuntimeClient);
既存の会話を続行する BedrockAgentThread のインスタンスを構築することもできます。
AgentThread thread = new BedrockAgentThread(
amazonBedrockAgentRuntimeClient,
sessionId: "my-existing-session-id");
チャット完了エージェントのスレッド オプション
ChatCompletionAgent は現在、ChatHistoryAgentThread型のスレッドのみをサポートしています。
ChatHistoryAgentThread は、メモリ内の ChatHistory オブジェクトを使用して、スレッドにメッセージを格納します。
エージェントの呼び出し時にスレッドを自動的に作成できるだけでなく、ChatHistoryAgentThreadのインスタンスを手動で作成することもできます。
AgentThread thread = new ChatHistoryAgentThread();
既存のメッセージと共に ChatHistoryAgentThread オブジェクトを渡すことで、既存の会話を続行する ChatHistory のインスタンスを構築することもできます。
ChatHistory chatHistory = new([new ChatMessageContent(AuthorRole.User, "Hi")]);
AgentThread thread = new ChatHistoryAgentThread(chatHistory: chatHistory);
OpenAI アシスタントのスレッド オプション
OpenAIAssistantAgent は現在、OpenAIAssistantAgentThread型のスレッドのみをサポートしています。
エージェントの呼び出し時にスレッドを自動的に作成できるだけでなく、OpenAIAssistantAgentThreadのインスタンスを手動で作成することもできます。
OpenAIAssistantAgentThread では、カスタマイズされたツールとメタデータを用いた作成が可能であり、さらに会話を始めるためのメッセージをサポートします。
AgentThread thread = new OpenAIAssistantAgentThread(
assistantClient,
messages: seedMessages,
codeInterpreterFileIds: fileIds,
vectorStoreId: "my-vector-store",
metadata: metadata);
既存の会話を続行する OpenAIAssistantAgentThread のインスタンスを構築することもできます。
AgentThread thread = new OpenAIAssistantAgentThread(
assistantClient,
id: "my-existing-thread-id");
OpenAIAssistantAgent C# 移行ガイド
最近、OpenAIAssistantAgentで、 の周りに大きな変化が適用されました。
次の変更が適用されました。
これらの変更は、次の目的で行われます。
-
AzureAIAgentに使用するパターンに合わせて設定します。 - 静的初期化パターンに関するバグを修正しました。
- 基になる SDK の抽象化に基づいて機能を制限しないでください。
このガイドでは、C# コードを古い実装から新しい実装に移行する手順について説明します。 変更には、アシスタントの作成、アシスタントのライフサイクルの管理、スレッド、ファイル、ベクター ストアの処理に関する更新が含まれます。
1. クライアントのインスタンス化
以前は、OpenAIClientProviderを作成するために OpenAIAssistantAgent が必要でした。 この依存関係は簡略化されました。
新しい方法
OpenAIClient client = OpenAIAssistantAgent.CreateAzureOpenAIClient(new AzureCliCredential(), new Uri(endpointUrl));
AssistantClient assistantClient = client.GetAssistantClient();
Old Way (非推奨)
var clientProvider = new OpenAIClientProvider(...);
2. アシスタントライフサイクル
アシスタント の作成
OpenAIAssistantAgentの既存または新しい Assistant 定義を使用して、AssistantClient を直接インスタンス化できるようになりました。
新しい方法
Assistant definition = await assistantClient.GetAssistantAsync(assistantId);
OpenAIAssistantAgent agent = new(definition, client);
プラグインは、初期化中に直接含めることができます。
KernelPlugin plugin = KernelPluginFactory.CreateFromType<YourPlugin>();
Assistant definition = await assistantClient.GetAssistantAsync(assistantId);
OpenAIAssistantAgent agent = new(definition, client, [plugin]);
拡張メソッドを使用した新しいアシスタント定義の作成:
Assistant assistant = await assistantClient.CreateAssistantAsync(
model,
name,
instructions: instructions,
enableCodeInterpreter: true);
Old Way (非推奨)
以前は、アシスタント定義は間接的に管理されていました。
3. エージェントの呼び出し
RunCreationOptions を直接指定して、基になる SDK 機能へのフル アクセスを有効にできます。
新しい方法
RunCreationOptions options = new(); // configure as needed
var result = await agent.InvokeAsync(options);
Old Way (非推奨)
var options = new OpenAIAssistantInvocationOptions();
4. アシスタントの削除
AssistantClientを使用してアシスタントの削除を直接管理できます。
await assistantClient.DeleteAssistantAsync(agent.Id);
5. スレッドのライフサイクル
スレッド の作成
スレッドは、AssistantAgentThreadを使用して管理されるようになりました。
新しい方法
var thread = new AssistantAgentThread(assistantClient);
// Calling CreateAsync is an optional step.
// A thread will be created automatically on first use if CreateAsync was not called.
// Note that CreateAsync is not on the AgentThread base implementation since not all
// agent services support explicit thread creation.
await thread.CreateAsync();
Old Way (非推奨)
以前は、スレッド管理は間接またはエージェントバインドでした。
スレッド削除
var thread = new AssistantAgentThread(assistantClient, "existing-thread-id");
await thread.DeleteAsync();
6. ファイルのライフサイクル
ファイルの作成と削除で OpenAIFileClientを利用できるようになりました。
ファイルのアップロード
string fileId = await client.UploadAssistantFileAsync(stream, "<filename>");
ファイルの削除
await client.DeleteFileAsync(fileId);
7. ベクター ストアのライフサイクル
ベクター ストアは、便利な拡張メソッドを使用して VectorStoreClient を介して直接管理されます。
ベクター ストアの作成
string vectorStoreId = await client.CreateVectorStoreAsync([fileId1, fileId2], waitUntilCompleted: true);
ベクトル ストアの削除
await client.DeleteVectorStoreAsync(vectorStoreId);
下位互換性
非推奨のパターンは、[Obsolete]でマークされます。 古い警告 (CS0618) を抑制するには、プロジェクト ファイルを次のように更新します。
<PropertyGroup>
<NoWarn>$(NoWarn);CS0618</NoWarn>
</PropertyGroup>
この移行ガイドは、新しい実装にスムーズに移行し、クライアントの初期化、リソース管理、セマンティック カーネル .NET SDKとの統合を簡素化するのに役立ちます。
重要
セマンティック カーネル Python 1.26.1 以降にアップグレードする開発者向けに、GA に近づくにつれてエージェント フレームワークを改善するための重要な更新と破壊的変更が導入されています。
次の変更が適用されました。
以前の変更は次で適用されました。
このガイドでは、Python コードを古い実装から新しい実装に移行する手順について説明します。
エージェントインポート
すべてのエージェント インポート パスは、semantic_kernel.agentsに統合されています。
更新されたインポート スタイル
from semantic_kernel.agents import (
AutoGenConversableAgent,
AzureAIAgent,
AzureAssistantAgent,
BedrockAgent,
ChatCompletionAgent,
OpenAIAssistantAgent,
)
以前のインポート スタイル (非推奨):
from semantic_kernel.agents import ChatCompletionAgent
from semantic_kernel.agents.autogen import AutoGenConversableAgent
from semantic_kernel.agents.azure_ai import AzureAIAgent
from semantic_kernel.agents.bedrock import BedrockAgent
from semantic_kernel.agents.open_ai import AzureAssistantAgent, OpenAIAssistantAgent
共通エージェント呼び出し API
セマンティック カーネル Python 1.26.0 以降では、すべてのエージェントのスレッドを管理するための新しい一般的な抽象化が導入されました。 各エージェントについて、AgentThread 基底クラスを実装するスレッド クラスを公開し、create() や delete()などのメソッドを使用したコンテキスト管理を可能にします。
エージェントの応答 get_response(...)、invoke(...)invoke_stream(...)、次の 2 つの属性を持つ AgentResponseItem[ChatMessageContent]が返されるようになりました。
message: TMessage # Usually ChatMessageContent
thread: AgentThread # Contains the concrete type for the given agent
スレッドへのメッセージの追加
メッセージは、エージェントの messages、get_response(...)、または invoke(...) メソッドの一部として、invoke_stream(...) 引数を使用してスレッドに追加する必要があります。
Azure AI エージェント スレッド
AzureAIAgentThread は次のように作成できます。
from semantic_kernel.agents import AzureAIAgentThread
thread = AzureAIAgentThread(
client: AIProjectClient, # required
messages: list[ThreadMessageOptions] | None = None, # optional
metadata: dict[str, str] | None = None, # optional
thread_id: str | None = None, # optional
tool_resources: "ToolResources | None" = None, # optional
)
thread_id (文字列) を指定すると、既存の会話を続行できます。 省略すると、新しいスレッドが作成され、エージェントの応答の一部として返されます。
完全な実装例:
import asyncio
from azure.identity.aio import DefaultAzureCredential
from semantic_kernel.agents import AzureAIAgent, AzureAIAgentSettings, AzureAIAgentThread
USER_INPUTS = [
"Why is the sky blue?",
"What are we talking about?",
]
async def main() -> None:
ai_agent_settings = AzureAIAgentSettings.create()
async with (
DefaultAzureCredential() as creds,
AzureAIAgent.create_client(credential=creds) as client,
):
# 1. Create an agent on the Azure AI agent service
agent_definition = await client.agents.create_agent(
model=ai_agent_settings.model_deployment_name,
name="Assistant",
instructions="Answer the user's questions.",
)
# 2. Create a Semantic Kernel agent for the Azure AI agent
agent = AzureAIAgent(
client=client,
definition=agent_definition,
)
# 3. Create a thread for the agent
# If no thread is provided, a new thread will be
# created and returned with the initial response
thread: AzureAIAgentThread = None
try:
for user_input in USER_INPUTS:
print(f"# User: {user_input}")
# 4. Invoke the agent with the specified message for response
response = await agent.get_response(messages=user_input, thread=thread)
print(f"# {response.content}: {response}")
thread = response.thread
finally:
# 6. Cleanup: Delete the thread and agent
await thread.delete() if thread else None
await client.agents.delete_agent(agent.id)
if __name__ == "__main__":
asyncio.run(main())
Bedrock エージェント スレッド
BedrockAgent では、BedrockAgentThread を使用して会話の履歴とコンテキストを管理します。 新しい会話コンテキストを続行または開始するための session_id を提供できます。
from semantic_kernel.agents import BedrockAgentThread
thread = BedrockAgentThread(
bedrock_runtime_client: Any,
session_id: str | None = None,
)
session_id が指定されていない場合は、新しいコンテキストが自動的に作成されます。
完全な実装例:
import asyncio
from semantic_kernel.agents import BedrockAgent, BedrockAgentThread
async def main():
bedrock_agent = await BedrockAgent.create_and_prepare_agent(
"semantic-kernel-bedrock-agent",
instructions="You are a friendly assistant. You help people find information.",
)
# Create a thread for the agent
# If no thread is provided, a new thread will be
# created and returned with the initial response
thread: BedrockAgentThread = None
try:
while True:
user_input = input("User:> ")
if user_input == "exit":
print("\n\nExiting chat...")
break
# Invoke the agent
# The chat history is maintained in the session
response = await bedrock_agent.get_response(
input_text=user_input,
thread=thread,
)
print(f"Bedrock agent: {response}")
thread = response.thread
except KeyboardInterrupt:
print("\n\nExiting chat...")
return False
except EOFError:
print("\n\nExiting chat...")
return False
finally:
# Delete the agent
await bedrock_agent.delete_agent()
await thread.delete() if thread else None
if __name__ == "__main__":
asyncio.run(main())
チャット履歴エージェント スレッド
ChatCompletionAgent は ChatHistoryAgentThread を使用して会話履歴を管理します。 次のように初期化できます。
from semantic_kernel.agents import ChatHistoryAgentThread
thread = ChatHistoryAgentThread(
chat_history: ChatHistory | None = None,
thread_id: str | None = None
)
thread_id を提供すると、既存の会話を継続できます。 省略すると、新しいスレッドが作成されます。 永続的な会話コンテキストでは、スレッド状態のシリアル化とリハイドレートがサポートされています。
完全な実装例:
import asyncio
from semantic_kernel.agents import ChatCompletionAgent, ChatHistoryAgentThread
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
# Simulate a conversation with the agent
USER_INPUTS = [
"Hello, I am John Doe.",
"What is your name?",
"What is my name?",
]
async def main():
# 1. Create the agent by specifying the service
agent = ChatCompletionAgent(
service=AzureChatCompletion(),
name="Assistant",
instructions="Answer the user's questions.",
)
# 2. Create a thread to hold the conversation
# If no thread is provided, a new thread will be
# created and returned with the initial response
thread: ChatHistoryAgentThread = None
for user_input in USER_INPUTS:
print(f"# User: {user_input}")
# 3. Invoke the agent for a response
response = await agent.get_response(
messages=user_input,
thread=thread,
)
print(f"# {response.name}: {response}")
# 4. Store the thread, which allows the agent to
# maintain conversation history across multiple messages.
thread = response.thread
# 5. Cleanup: Clear the thread
await thread.delete() if thread else None
if __name__ == "__main__":
asyncio.run(main())
OpenAI アシスタント スレッド
AzureAssistantAgent と OpenAIAssistantAgent は、AssistantAgentThread を使用して会話の履歴とコンテキストを管理します。
from semantic_kernel.agents import ChatHistoryAgentThread
thread = AssistantAgentThread(
client: AsyncOpenAI,
thread_id: str | None = None,
messages: Iterable["ThreadCreateMessage"] | NotGiven = NOT_GIVEN,
metadata: dict[str, Any] | NotGiven = NOT_GIVEN,
tool_resources: ToolResources | NotGiven = NOT_GIVEN,
)
thread_id を提供すると、既存の会話が続行されます。それ以外の場合は、新しいスレッドが作成されます。
完全な実装例:
# Copyright (c) Microsoft. All rights reserved.
import asyncio
from semantic_kernel.agents import AzureAssistantAgent
# Simulate a conversation with the agent
USER_INPUTS = [
"Why is the sky blue?",
"What is the speed of light?",
"What have we been talking about?",
]
async def main():
# 1. Create the client using Azure OpenAI resources and configuration
client, model = AzureAssistantAgent.setup_resources()
# 2. Create the assistant on the Azure OpenAI service
definition = await client.beta.assistants.create(
model=model,
instructions="Answer questions about the world in one sentence.",
name="Assistant",
)
# 3. Create a Semantic Kernel agent for the Azure OpenAI assistant
agent = AzureAssistantAgent(
client=client,
definition=definition,
)
# 4. Create a new thread for use with the assistant
# If no thread is provided, a new thread will be
# created and returned with the initial response
thread = None
try:
for user_input in USER_INPUTS:
print(f"# User: '{user_input}'")
# 6. Invoke the agent for the current thread and print the response
response = await agent.get_response(messages=user_input, thread=thread)
print(f"# {response.name}: {response}")
thread = response.thread
finally:
# 7. Clean up the resources
await thread.delete() if thread else None
await agent.client.beta.assistants.delete(assistant_id=agent.id)
if __name__ == "__main__":
asyncio.run(main())
エージェント呼び出しのメッセージ入力
以前の実装では、get_response(...)、invoke(...)、invoke_stream(...)などのメソッドへの 1 つのメッセージ入力のみが許可されました。 複数の messages (str | ChatMessageContent | list[str | ChatMessageContent])をサポートするようにこれらのメソッドを更新しました。 メッセージ入力は、messagesやagent.get_response(messages="user input")など、agent.invoke(messages="user input")キーワード引数と共に渡す必要があります。
エージェント呼び出しメソッドには、次のような更新が必要です。
古い方法
response = await agent.get_response(message="some user input", thread=thread)
新しい方法
response = await agent.get_response(messages=["some initial inputer", "other input"], thread=thread)
AzureAIAgent
セマンティック カーネル Python 1.26.0 以降では、AzureAIAgent スレッドの作成は、クライアント上で直接ではなく、AzureAIAgentThread オブジェクトを介して管理されるようになりました。
古い方法
thread = await client.agents.create_thread()
新しい方法
from semantic_kernel.agents import AzureAIAgentThread
thread = AzureAIAgentThread(
client: AIProjectClient, # required
messages: list[ThreadMessageOptions] | None = None, # optional
metadata: dict[str, str] | None = None, # optional
thread_id: str | None = None, # optional
tool_resources: "ToolResources | None" = None, # optional
)
最初に thread_id が指定されていない場合は、新しいスレッドが作成され、エージェントの応答で返されます。
ChatCompletionAgent
ChatCompletionAgent が更新され、サービスの構成、プラグインの処理、関数呼び出しの動作が簡略化されました。 移行時に考慮する必要がある主な変更を次に示します。
1. サービスの指定
エージェント コンストラクターの一部としてサービスを直接指定できるようになりました。
新しい方法
from semantic_kernel.agents import ChatCompletionAgent
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
agent = ChatCompletionAgent(
service=AzureChatCompletion(),
name="<name>",
instructions="<instructions>",
)
注: カーネルとサービスの両方が提供されている場合、同じservice_idまたはai_model_idを共有している場合、サービスが優先されます。 それ以外の場合、それらが別々の場合は、カーネルに登録された最初の AI サービスが使用されます。
古い方法 (引き続き有効)
以前は、まずカーネルにサービスを追加してから、カーネルをエージェントに渡しました。
from semantic_kernel.agents import ChatCompletionAgent
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
kernel = Kernel()
kernel.add_service(AzureChatCompletion())
agent = ChatCompletionAgent(
kernel=kernel,
name="<name>",
instructions="<instructions>",
)
2. プラグインの追加
プラグインは、コンストラクターを介して直接指定できるようになりました。
新しい方法
from semantic_kernel.agents import ChatCompletionAgent
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
agent = ChatCompletionAgent(
service=AzureChatCompletion(),
name="<name>",
instructions="<instructions>",
plugins=[SamplePlugin()],
)
古い方法 (引き続き有効)
プラグインは、以前はカーネルに個別に追加する必要がありました。
from semantic_kernel.agents import ChatCompletionAgent
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
kernel = Kernel()
kernel.add_plugin(SamplePlugin())
agent = ChatCompletionAgent(
kernel=kernel,
name="<name>",
instructions="<instructions>",
)
注: どちらの方法も有効ですが、プラグインを直接指定すると初期化が簡単になります。
3. エージェントの呼び出し
これで、エージェントを呼び出す方法が 2 つあります。 新しいメソッドは 1 つの応答を直接取得しますが、古いメソッドはストリーミングをサポートします。
新しい方法 (会話スレッド/コンテキストなし)
response = await agent.get_response(messages="user input")
# response is of type AgentResponseItem[ChatMessageContent]
注: 次の応答が返されたスレッドを使用しない場合、会話は新しいスレッドを使用するため、前のコンテキストでは続行されません。
新しい方法 (コンテキストを使用した単一の応答)
thread = ChatHistoryAgentThread()
for user_input in ["First user input", "Second User Input"]:
response = await agent.get_response(messages=user_input, thread=thread)
# response is of type AgentResponseItem[ChatMessageContent]
thread = response.thread
古い方法 (無効)
chat_history = ChatHistory()
chat_history.add_user_message("<user_input>")
response = agent.get_response(message="user input", chat_history=chat_history)
4. 関数呼び出しの制御
エージェント コンストラクター内でサービスを指定するときに、関数呼び出し動作を直接制御できるようになりました。
agent = ChatCompletionAgent(
service=AzureChatCompletion(),
name="<name>",
instructions="<instructions>",
plugins=[MenuPlugin()],
function_choice_behavior=FunctionChoiceBehavior.Auto(
filters={"included_functions": ["get_specials", "get_item_price"]}
),
)
注: 以前は、関数呼び出し構成では、カーネルまたはサービス オブジェクトに個別のセットアップが必要です。 実行設定で AI サービス構成と同じ service_id または ai_model_id が指定されている場合、(KernelArgumentsを介して) 実行設定で定義された関数呼び出し動作が、コンストラクターで設定された関数の選択動作よりも優先されます。
これらの更新により、シンプルさと構成性が向上し、ChatCompletionAgent の統合と保守が容易になります。
OpenAIAssistantAgent
AzureAssistantAgent と OpenAIAssistantAgent の変更には、アシスタントの作成、スレッドの作成、プラグインの処理、コード インタープリター ツールの使用、ファイル検索ツールの操作、スレッドへのチャット メッセージの追加に関する更新が含まれます。
リソースの設定
古い方法
AsyncAzureOpenAI クライアントは、エージェント オブジェクトの作成の一環として作成されました。
agent = await AzureAssistantAgent.create(
deployment_name="optional-deployment-name",
api_key="optional-api-key",
endpoint="optional-endpoint",
ad_token="optional-ad-token",
ad_token_provider=optional_callable,
default_headers={"optional_header": "optional-header-value"},
env_file_path="optional-env-file-path",
env_file_encoding="optional-env-file-encoding",
...,
)
新しい方法
エージェントは、指定されたリソースに必要なクライアントを作成するための静的メソッドを提供します。メソッド レベルのキーワード引数は、既存の .env ファイル内の環境変数と値よりも優先されます。
client, model = AzureAssistantAgent.setup_resources(
ad_token="optional-ad-token",
ad_token_provider=optional_callable,
api_key="optional-api-key",
api_version="optional-api-version",
base_url="optional-base-url",
default_headers="optional-default-headers",
deployment_name="optional-deployment-name",
endpoint="optional-endpoint",
env_file_path="optional-env-file-path",
env_file_encoding="optional-env-file-encoding",
token_scope="optional-token-scope",
)
1. アシスタントの作成
古い方法
agent = await AzureAssistantAgent.create(
kernel=kernel,
service_id=service_id,
name=AGENT_NAME,
instructions=AGENT_INSTRUCTIONS,
enable_code_interpreter=True,
)
又は
agent = await OpenAIAssistantAgent.create(
kernel=kernel,
service_id=service_id,
name=<name>,
instructions=<instructions>,
enable_code_interpreter=True,
)
新しい方法
# Azure AssistantAgent
# Create the client using Azure OpenAI resources and configuration
client, model = AzureAssistantAgent.setup_resources()
# Create the assistant definition
definition = await client.beta.assistants.create(
model=model,
instructions="<instructions>",
name="<name>",
)
# Create the agent using the client and the assistant definition
agent = AzureAssistantAgent(
client=client,
definition=definition,
)
又は
# OpenAI Assistant Agent
# Create the client using OpenAI resources and configuration
client, model = OpenAIAssistantAgent.setup_resources()
# Create the assistant definition
definition = await client.beta.assistants.create(
model=model,
instructions="<instructions>",
name="<name>",
)
# Create the agent using the client and the assistant definition
agent = OpenAIAssistantAgent(
client=client,
definition=definition,
)
2. スレッドの作成
古い方法
thread_id = await agent.create_thread()
新しい方法
from semantic_kernel.agents AssistantAgentThread, AzureAssistantAgent
client, model = AzureAssistantAgent.setup_resources()
# You may create a thread based on an existing thread id
# thread = AssistantAgentThread(client=client, thread_id="existing-thread-id")
# Otherwise, if not specified, a thread will be created during the first invocation
# and returned as part of the response
thread = None
async for response in agent.invoke(messages="user input", thread=thread):
# handle response
print(response)
thread = response.thread
3. プラグインの処理
古い方法
# Create the instance of the Kernel
kernel = Kernel()
# Add the sample plugin to the kernel
kernel.add_plugin(plugin=MenuPlugin(), plugin_name="menu")
agent = await AzureAssistantAgent.create(
kernel=kernel,
name="<name>",
instructions="<instructions>"
)
注: カーネルを介してプラグインを管理することは引き続き可能です。 カーネルを指定しないと、エージェント作成時にカーネルが自動的に作成され、プラグインがそのインスタンスに追加されます。
新しい方法
# Create the client using Azure OpenAI resources and configuration
client, model = AzureAssistantAgent.setup_resources()
# Create the assistant definition
definition = await client.beta.assistants.create(
model=model,
instructions="<instructions>",
name="<name>",
)
# Create the agent with plugins passed in as a list
agent = AzureAssistantAgent(
client=client,
definition=definition,
plugins=[MenuPlugin()],
)
詳細については、サンプル実装 を参照してください。
4. コード インタープリター ツールの使用
古い方法
csv_file_path = ...
agent = await AzureAssistantAgent.create(
kernel=kernel,
name="<name>",
instructions="<instructions>",
enable_code_interpreter=True,
code_interpreter_filenames=[csv_file_path],
)
新しい方法
# Create the client using Azure OpenAI resources and configuration
client, model = AzureAssistantAgent.setup_resources()
csv_file_path = ...
# Load the CSV file as a FileObject
with open(csv_file_path, "rb") as file:
file = await client.files.create(file=file, purpose="assistants")
# Get the code interpreter tool and resources
code_interpreter_tool, code_interpreter_tool_resource = AzureAssistantAgent.configure_code_interpreter_tool(file.id)
# Create the assistant definition
definition = await client.beta.assistants.create(
model=model,
name="<name>",
instructions="<instructions>.",
tools=code_interpreter_tool,
tool_resources=code_interpreter_tool_resource,
)
# Create the AzureAssistantAgent instance using the client and the assistant definition
agent = AzureAssistantAgent(
client=client,
definition=definition,
)
詳細については、サンプル実装 を参照してください。
5. ファイル検索ツールの操作
古い方法
pdf_file_path = ...
agent = await AzureAssistantAgent.create(
kernel=kernel,
service_id=service_id,
name=AGENT_NAME,
instructions=AGENT_INSTRUCTIONS,
enable_file_search=True,
vector_store_filenames=[pdf_file_path],
)
新しい方法
# Create the client using Azure OpenAI resources and configuration
client, model = AzureAssistantAgent.setup_resources()
pdf_file_path = ...
# Load the employees PDF file as a FileObject
with open(pdf_file_path, "rb") as file:
file = await client.files.create(file=file, purpose="assistants")
# Create a vector store specifying the file ID to be used for file search
vector_store = await client.beta.vector_stores.create(
name="step4_assistant_file_search",
file_ids=[file.id],
)
file_search_tool, file_search_tool_resources = AzureAssistantAgent.configure_file_search_tool(vector_store.id)
# Create the assistant definition
definition = await client.beta.assistants.create(
model=model,
instructions="Find answers to the user's questions in the provided file.",
name="FileSearch",
tools=file_search_tool,
tool_resources=file_search_tool_resources,
)
# Create the AzureAssistantAgent instance using the client and the assistant definition
agent = AzureAssistantAgent(
client=client,
definition=definition,
)
詳細については、サンプル実装 を参照してください。
6. スレッドへのチャット メッセージの追加
古い方法
await agent.add_chat_message(
thread_id=thread_id,
message=ChatMessageContent(role=AuthorRole.USER, content=user_input)
)
新しい方法
注: ChatMessageContentを渡しても古いメソッドは機能しますが、単純な文字列を渡すこともできます。
await agent.add_chat_message(
thread_id=thread_id,
message=user_input,
)
7. リソースのクリーンアップ
古い方法
await agent.delete_file(file_id)
await agent.delete_thread(thread_id)
await agent.delete()
新しい方法
await client.files.delete(file_id)
await thread.delete()
await client.beta.assistants.delete(agent.id)
構造化された出力の処理
古い方法
以前の方法では使用できません
新しい方法
# Define a Pydantic model that represents the structured output from the OpenAI service
class ResponseModel(BaseModel):
response: str
items: list[str]
# Create the client using Azure OpenAI resources and configuration
client, model = AzureAssistantAgent.setup_resources()
# Create the assistant definition
definition = await client.beta.assistants.create(
model=model,
name="<name>",
instructions="<instructions>",
response_format=AzureAssistantAgent.configure_response_format(ResponseModel),
)
# Create the AzureAssistantAgent instance using the client and the assistant definition
agent = AzureAssistantAgent(
client=client,
definition=definition,
)
詳細については、サンプル実装 を参照してください。
この移行ガイドは、クライアント ベースの構成と強化された機能を利用して、コードを新しい実装に更新するのに役立ちます。
エージェントは Java では使用できません。