방법: Open AI Assistant Agent Code Interpreter
Warning
의미 체계 커널 에이전트 프레임워크 미리 보기 상태이며 변경될 수 있습니다.
개요
이 샘플에서는 Open AI Assistant 에이전트의 코드 인터프리터 도구를 사용하여 데이터 분석 작업을 완료하는 방법을 살펴봅니다. 이 방법은 코딩 프로세스의 핵심 부분을 밝게 하기 위해 단계별로 세분화됩니다. 작업의 일부로 에이전트는 이미지 및 텍스트 응답을 모두 생성합니다. 이는 양적 분석을 수행하는 이 도구의 다양성을 보여 줍니다.
스트리밍은 에이전트의 응답을 전달하는 데 사용됩니다. 그러면 작업이 진행됨에 따라 실시간 업데이트가 제공됩니다.
시작하기
기능 코딩을 계속하기 전에 개발 환경이 완전히 설정되고 구성되었는지 확인합니다.
먼저 콘솔 프로젝트를 만듭니다. 그런 다음 필요한 모든 종속성을 사용할 수 있도록 다음 패키지 참조를 포함합니다.
명령줄에서 패키지 종속성을 추가하려면 다음 명령을 사용합니다 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
dotnet add package Microsoft.SemanticKernel.Agents.OpenAI --prerelease
Visual Studio
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" Version="<latest>" />
<PackageReference Include="Microsoft.SemanticKernel.Agents.OpenAI" Version="<latest>" />
</ItemGroup>
에이전트 프레임워크는 실험적이며 경고 표시 안 함이 필요합니다. 프로젝트 파일.csproj
()의 속성으로 이 문제를 해결할 수 있습니다.
<PropertyGroup>
<NoWarn>$(NoWarn);CA2007;IDE1006;SKEXP0001;SKEXP0110;OPENAI001</NoWarn>
</PropertyGroup>
또한 의미 체계 커널PopulationByAdmin1.csv
프로젝트에서PopulationByCountry.csv
복사 LearnResources
합니다. 프로젝트 폴더에 다음 파일을 추가하고 출력 디렉터리에 복사하도록 구성합니다.
<ItemGroup>
<None Include="PopulationByAdmin1.csv">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="PopulationByCountry.csv">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
먼저 스크립트(.py
파일) 및 샘플 리소스를 보관할 폴더를 만듭니다. 파일 맨 위에 .py
다음 가져오기를 포함합니다.
import asyncio
import os
from semantic_kernel.agents.open_ai.azure_assistant_agent import AzureAssistantAgent
from semantic_kernel.contents.chat_message_content import ChatMessageContent
from semantic_kernel.contents.streaming_file_reference_content import StreamingFileReferenceContent
from semantic_kernel.contents.utils.author_role import AuthorRole
from semantic_kernel.kernel import Kernel
또한 의미 체계 커널learn_resources/resources
디렉터리에서 PopulationByAdmin1.csv
및 PopulationByCountry.csv
데이터 파일을 복사하십시오. 작업 디렉터리에 이러한 파일을 추가합니다.
에이전트는 현재 Java에서 사용할 수 없습니다.
구성
이 샘플에서는 원격 서비스에 연결하기 위해 구성 설정이 필요합니다. Open AI 또는 Azure Open AI에 대한 설정을 정의해야 합니다.
# 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"
다음 클래스는 모든 에이전트 예제에서 사용됩니다. 적절한 기능을 보장하려면 프로젝트에 포함해야 합니다. 이 클래스는 다음 예제의 기본 구성 요소 역할을 합니다.
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
것입니다.
Azure OpenAI 또는 OpenAI에 대해 파일에서 다음 설정을 구성합니다 .env
.
AZURE_OPENAI_API_KEY="..."
AZURE_OPENAI_ENDPOINT="https://<resource-name>.openai.azure.com/"
AZURE_OPENAI_CHAT_DEPLOYMENT_NAME="..."
AZURE_OPENAI_API_VERSION="..."
OPENAI_API_KEY="sk-..."
OPENAI_ORG_ID=""
OPENAI_CHAT_MODEL_ID=""
[! TIP] Azure Assistants에는 2024-05-01-preview 이상의 API 버전이 필요합니다. 새 기능이 도입되면 API 버전이 그에 따라 업데이트됩니다. 이 글을 쓰는 시점에서 최신 버전은 2025-01-01-preview입니다. 최신 up-to버전 관리 세부 정보는 Azure OpenAI API 미리 보기 수명 주기를 참조하세요.
구성되면 각 AI 서비스 클래스는 필요한 변수를 선택하고 인스턴스화 중에 사용합니다.
에이전트는 현재 Java에서 사용할 수 없습니다.
코딩
이 샘플의 코딩 프로세스는 다음과 같습니다.
- 설치 - 설정 및 플러그 인 초기화
- 에이전트 정의 - 템플릿 명령 및 플러그 인을 사용하여 OpenAI_Assistant_Agent 만듭니다.
- 채팅 루프 - 사용자/에이전트 상호 작용을 구동하는 루프를 작성합니다.
전체 예제 코드는 최종 섹션에 제공됩니다. 전체 구현은 해당 섹션을 참조하세요.
설정
Open AI Assistant 에이전트를 만들기 전에 구성 설정을 사용할 수 있는지 확인하고 파일 리소스를 준비합니다.
이전 구성 섹션에서 참조된 클래스를 인스턴스화 Settings
합니다. 또한 이 설정을 사용하여 에이전트 정의OpenAIClientProvider
사용할 설정을 만듭니 다.
Settings settings = new();
OpenAIClientProvider clientProvider =
OpenAIClientProvider.ForAzureOpenAI(new AzureCliCredential(), new Uri(settings.AzureOpenAI.Endpoint));
에이전트는 현재 Java에서 사용할 수 없습니다.
OpenAIClientProvider
마지막 정리를 위해 파일 참조를 OpenAIFileClient
유지하면서 이전 구성 섹션에 설명된 두 데이터 파일에 액세스하고 업로드할 수 있습니다.
Console.WriteLine("Uploading files...");
OpenAIFileClient fileClient = clientProvider.Client.GetOpenAIFileClient();
OpenAIFile fileDataCountryDetail = await fileClient.UploadFileAsync("PopulationByAdmin1.csv", FileUploadPurpose.Assistants);
OpenAIFile fileDataCountryList = await fileClient.UploadFileAsync("PopulationByCountry.csv", FileUploadPurpose.Assistants);
팁
파일이 있는 위치에 따라 파일 경로를 조정해야 할 수 있습니다.
# Let's form the file paths that we will later pass to the assistant
csv_file_path_1 = os.path.join(
os.path.dirname(os.path.dirname(os.path.realpath(__file__))),
"resources",
"PopulationByAdmin1.csv",
)
csv_file_path_2 = os.path.join(
os.path.dirname(os.path.dirname(os.path.realpath(__file__))),
"resources",
"PopulationByCountry.csv",
)
CSV 파일의 스토리지 위치에 따라 경로 만들기 코드를 수정해야 할 수 있습니다.
에이전트는 현재 Java에서 사용할 수 없습니다.
에이전트 정의
이제 OpenAI 도우미 에이전트를 인스턴스화할 준비가 되었습니다. 에이전트는 대상 모델, 지침 및 코드 인터프리터 도구를 사용하도록 설정하여 구성됩니다. 또한 두 데이터 파일을 코드 인터프리터 도구와 명시적으로 연결합니다.
Console.WriteLine("Defining agent...");
OpenAIAssistantAgent agent =
await OpenAIAssistantAgent.CreateAsync(
clientProvider,
new OpenAIAssistantDefinition(settings.AzureOpenAI.ChatModelDeployment)
{
Name = "SampleAssistantAgent",
Instructions =
"""
Analyze the available data to provide an answer to the user's question.
Always format response using markdown.
Always include a numerical index that starts at 1 for any lists or tables.
Always sort lists in ascending order.
""",
EnableCodeInterpreter = true,
CodeInterpreterFileIds = [fileDataCountryList.Id, fileDataCountryDetail.Id],
},
new Kernel());
이제 Azure Assistant 에이전트 을 인스턴스화할 준비가 되었습니다. 에이전트는 대상 모델, 지침 및 코드 인터프리터 도구를 사용하도록 설정하여 구성됩니다. 또한 두 데이터 파일을 코드 인터프리터 도구와 명시적으로 연결합니다.
agent = await AzureAssistantAgent.create(
kernel=Kernel(),
service_id="agent",
name="SampleAssistantAgent",
instructions="""
Analyze the available data to provide an answer to the user's question.
Always format response using markdown.
Always include a numerical index that starts at 1 for any lists or tables.
Always sort lists in ascending order.
""",
enable_code_interpreter=True,
code_interpreter_filenames=[csv_file_path_1, csv_file_path_2],
)
에이전트는 현재 Java에서 사용할 수 없습니다.
채팅 루프
마침내 사용자와 에이전트 간의 상호 작용을 조정할 수 있습니다. 먼저 대화 상태를 유지 관리하는 도우미 스레드를 만들고 빈 루프를 만듭니다.
또한 불필요한 요금을 최소화하기 위해 실행이 끝날 때 리소스가 제거되는지 확인해 보겠습니다.
Console.WriteLine("Creating thread...");
string threadId = await agent.CreateThreadAsync();
Console.WriteLine("Ready!");
try
{
bool isComplete = false;
List<string> fileIds = [];
do
{
} while (!isComplete);
}
finally
{
Console.WriteLine();
Console.WriteLine("Cleaning-up...");
await Task.WhenAll(
[
agent.DeleteThreadAsync(threadId),
agent.DeleteAsync(),
fileClient.DeleteFileAsync(fileDataCountryList.Id),
fileClient.DeleteFileAsync(fileDataCountryDetail.Id),
]);
}
print("Creating thread...")
thread_id = await agent.create_thread()
try:
is_complete: bool = False
file_ids: list[str] = []
while not is_complete:
# agent interaction logic here
finally:
print("Cleaning up resources...")
if agent is not None:
[await agent.delete_file(file_id) for file_id in agent.code_interpreter_file_ids]
await agent.delete_thread(thread_id)
await agent.delete()
에이전트는 현재 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;
}
await agent.AddChatMessageAsync(threadId, 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
await agent.add_chat_message(thread_id=thread_id, message=ChatMessageContent(role=AuthorRole.USER, content=user_input))
에이전트는 현재 Java에서 사용할 수 없습니다.
에이전트 응답을 호출하기 전에 에이전트에서 생성할 수 있는 파일을 다운로드하는 몇 가지 도우미 메서드를 추가해 보겠습니다.
여기서는 시스템 정의 임시 디렉터리에 파일 콘텐츠를 배치한 다음 시스템 정의 뷰어 애플리케이션을 시작합니다.
private static async Task DownloadResponseImageAsync(OpenAIFileClient client, ICollection<string> fileIds)
{
if (fileIds.Count > 0)
{
Console.WriteLine();
foreach (string fileId in fileIds)
{
await DownloadFileContentAsync(client, fileId, launchViewer: true);
}
}
}
private static async Task DownloadFileContentAsync(OpenAIFileClient client, string fileId, bool launchViewer = false)
{
OpenAIFile fileInfo = client.GetFile(fileId);
if (fileInfo.Purpose == FilePurpose.AssistantsOutput)
{
string filePath =
Path.Combine(
Path.GetTempPath(),
Path.GetFileName(Path.ChangeExtension(fileInfo.Filename, ".png")));
BinaryData content = await client.DownloadFileAsync(fileId);
await using FileStream fileStream = new(filePath, FileMode.CreateNew);
await content.ToStream().CopyToAsync(fileStream);
Console.WriteLine($"File saved to: {filePath}.");
if (launchViewer)
{
Process.Start(
new ProcessStartInfo
{
FileName = "cmd.exe",
Arguments = $"/C start {filePath}"
});
}
}
}
import os
async def download_file_content(agent, file_id: str):
try:
# Fetch the content of the file using the provided method
response_content = await agent.client.files.content(file_id)
# Get the current working directory of the file
current_directory = os.path.dirname(os.path.abspath(__file__))
# Define the path to save the image in the current directory
file_path = os.path.join(
current_directory, # Use the current directory of the file
f"{file_id}.png" # You can modify this to use the actual filename with proper extension
)
# Save content to a file asynchronously
with open(file_path, "wb") as file:
file.write(response_content.content)
print(f"File saved to: {file_path}")
except Exception as e:
print(f"An error occurred while downloading file {file_id}: {str(e)}")
async def download_response_image(agent, file_ids: list[str]):
if file_ids:
# Iterate over file_ids and download each one
for file_id in file_ids:
await download_file_content(agent, file_id)
에이전트는 현재 Java에서 사용할 수 없습니다.
사용자 입력에 대한 에이전트 응답을 생성하려면 보조 스레드를 지정하여 에이전트를 호출합니다. 이 예제에서는 스트리밍된 응답을 선택하고 응답 주기가 끝날 때 다운로드 및 검토를 위해 생성된 모든 파일 참조를 캡처합니다 . 생성된 코드는 응답 메시지에 메타데이터 키가 있어 대화형 회신과 구분하여 식별된다는 점에 유의해야 합니다.
bool isCode = false;
await foreach (StreamingChatMessageContent response in agent.InvokeStreamingAsync(threadId))
{
if (isCode != (response.Metadata?.ContainsKey(OpenAIAssistantAgent.CodeInterpreterMetadataKey) ?? false))
{
Console.WriteLine();
isCode = !isCode;
}
// Display response.
Console.Write($"{response.Content}");
// Capture file IDs for downloading.
fileIds.AddRange(response.Items.OfType<StreamingFileReferenceContent>().Select(item => item.FileId));
}
Console.WriteLine();
// Download any files referenced in the response.
await DownloadResponseImageAsync(fileClient, fileIds);
fileIds.Clear();
is_code: bool = False
async for response in agent.invoke(stream(thread_id=thread_id):
if is_code != metadata.get("code"):
print()
is_code = not is_code
print(f"{response.content})
file_ids.extend(
[item.file_id for item in response.items if isinstance(item, StreamingFileReferenceContent)]
)
print()
await download_response_image(agent, file_ids)
file_ids.clear()
에이전트는 현재 Java에서 사용할 수 없습니다.
최종
모든 단계를 함께 가져오면 이 예제의 최종 코드가 있습니다. 전체 구현은 아래에 제공됩니다.
다음과 같은 제안된 입력을 사용해 보세요.
- 파일을 비교하여 총 수에 비해 국가 또는 지방이 정의되지 않은 국가 수를 확인합니다.
- 주 또는 지방이 정의된 국가에 대한 테이블을 만듭니다. 주 또는 지방의 수와 총 인구 포함
- 이름이 같은 문자로 시작하는 국가의 가로 막대형 차트를 제공하고 x축을 가장 높은 개수에서 가장 낮은 값으로 정렬합니다(모든 국가 포함).
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Azure.Identity;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Agents.OpenAI;
using Microsoft.SemanticKernel.ChatCompletion;
using OpenAI.Files;
namespace AgentsSample;
public static class Program
{
public static async Task Main()
{
// Load configuration from environment variables or user secrets.
Settings settings = new();
OpenAIClientProvider clientProvider =
OpenAIClientProvider.ForAzureOpenAI(new AzureCliCredential(), new Uri(settings.AzureOpenAI.Endpoint));
Console.WriteLine("Uploading files...");
OpenAIFileClient fileClient = clientProvider.Client.GetOpenAIFileClient();
OpenAIFile fileDataCountryDetail = await fileClient.UploadFileAsync("PopulationByAdmin1.csv", FileUploadPurpose.Assistants);
OpenAIFile fileDataCountryList = await fileClient.UploadFileAsync("PopulationByCountry.csv", FileUploadPurpose.Assistants);
Console.WriteLine("Defining agent...");
OpenAIAssistantAgent agent =
await OpenAIAssistantAgent.CreateAsync(
clientProvider,
new OpenAIAssistantDefinition(settings.AzureOpenAI.ChatModelDeployment)
{
Name = "SampleAssistantAgent",
Instructions =
"""
Analyze the available data to provide an answer to the user's question.
Always format response using markdown.
Always include a numerical index that starts at 1 for any lists or tables.
Always sort lists in ascending order.
""",
EnableCodeInterpreter = true,
CodeInterpreterFileIds = [fileDataCountryList.Id, fileDataCountryDetail.Id],
},
new Kernel());
Console.WriteLine("Creating thread...");
string threadId = await agent.CreateThreadAsync();
Console.WriteLine("Ready!");
try
{
bool isComplete = false;
List<string> fileIds = [];
do
{
Console.WriteLine();
Console.Write("> ");
string input = Console.ReadLine();
if (string.IsNullOrWhiteSpace(input))
{
continue;
}
if (input.Trim().Equals("EXIT", StringComparison.OrdinalIgnoreCase))
{
isComplete = true;
break;
}
await agent.AddChatMessageAsync(threadId, new ChatMessageContent(AuthorRole.User, input));
Console.WriteLine();
bool isCode = false;
await foreach (StreamingChatMessageContent response in agent.InvokeStreamingAsync(threadId))
{
if (isCode != (response.Metadata?.ContainsKey(OpenAIAssistantAgent.CodeInterpreterMetadataKey) ?? false))
{
Console.WriteLine();
isCode = !isCode;
}
// Display response.
Console.Write($"{response.Content}");
// Capture file IDs for downloading.
fileIds.AddRange(response.Items.OfType<StreamingFileReferenceContent>().Select(item => item.FileId));
}
Console.WriteLine();
// Download any files referenced in the response.
await DownloadResponseImageAsync(fileClient, fileIds);
fileIds.Clear();
} while (!isComplete);
}
finally
{
Console.WriteLine();
Console.WriteLine("Cleaning-up...");
await Task.WhenAll(
[
agent.DeleteThreadAsync(threadId),
agent.DeleteAsync(),
fileClient.DeleteFileAsync(fileDataCountryList.Id),
fileClient.DeleteFileAsync(fileDataCountryDetail.Id),
]);
}
}
private static async Task DownloadResponseImageAsync(OpenAIFileClient client, ICollection<string> fileIds)
{
if (fileIds.Count > 0)
{
Console.WriteLine();
foreach (string fileId in fileIds)
{
await DownloadFileContentAsync(client, fileId, launchViewer: true);
}
}
}
private static async Task DownloadFileContentAsync(OpenAIFileClient client, string fileId, bool launchViewer = false)
{
OpenAIFile fileInfo = client.GetFile(fileId);
if (fileInfo.Purpose == FilePurpose.AssistantsOutput)
{
string filePath =
Path.Combine(
Path.GetTempPath(),
Path.GetFileName(Path.ChangeExtension(fileInfo.Filename, ".png")));
BinaryData content = await client.DownloadFileAsync(fileId);
await using FileStream fileStream = new(filePath, FileMode.CreateNew);
await content.ToStream().CopyToAsync(fileStream);
Console.WriteLine($"File saved to: {filePath}.");
if (launchViewer)
{
Process.Start(
new ProcessStartInfo
{
FileName = "cmd.exe",
Arguments = $"/C start {filePath}"
});
}
}
}
}
# Copyright (c) Microsoft. All rights reserved.
import asyncio
import logging
import os
from semantic_kernel.agents.open_ai.azure_assistant_agent import AzureAssistantAgent
from semantic_kernel.contents.chat_message_content import ChatMessageContent
from semantic_kernel.contents.streaming_file_reference_content import StreamingFileReferenceContent
from semantic_kernel.contents.utils.author_role import AuthorRole
from semantic_kernel.kernel import Kernel
logging.basicConfig(level=logging.ERROR)
###################################################################
# The following sample demonstrates how to create a simple, #
# OpenAI assistant agent that utilizes the code interpreter #
# to analyze uploaded files. #
###################################################################
# Let's form the file paths that we will later pass to the assistant
csv_file_path_1 = os.path.join(
os.path.dirname(os.path.dirname(os.path.realpath(__file__))),
"resources",
"PopulationByAdmin1.csv",
)
csv_file_path_2 = os.path.join(
os.path.dirname(os.path.dirname(os.path.realpath(__file__))),
"resources",
"PopulationByCountry.csv",
)
async def download_file_content(agent: AzureAssistantAgent, file_id: str):
try:
# Fetch the content of the file using the provided method
response_content = await agent.client.files.content(file_id)
# Get the current working directory of the file
current_directory = os.path.dirname(os.path.abspath(__file__))
# Define the path to save the image in the current directory
file_path = os.path.join(
current_directory, # Use the current directory of the file
f"{file_id}.png", # You can modify this to use the actual filename with proper extension
)
# Save content to a file asynchronously
with open(file_path, "wb") as file:
file.write(response_content.content)
print(f"File saved to: {file_path}")
except Exception as e:
print(f"An error occurred while downloading file {file_id}: {str(e)}")
async def download_response_image(agent: AzureAssistantAgent, file_ids: list[str]):
if file_ids:
# Iterate over file_ids and download each one
for file_id in file_ids:
await download_file_content(agent, file_id)
async def main():
agent = await AzureAssistantAgent.create(
kernel=Kernel(),
service_id="agent",
name="SampleAssistantAgent",
instructions="""
Analyze the available data to provide an answer to the user's question.
Always format response using markdown.
Always include a numerical index that starts at 1 for any lists or tables.
Always sort lists in ascending order.
""",
enable_code_interpreter=True,
code_interpreter_filenames=[csv_file_path_1, csv_file_path_2],
)
print("Creating thread...")
thread_id = await agent.create_thread()
try:
is_complete: bool = False
file_ids: list[str] = []
while not is_complete:
user_input = input("User:> ")
if not user_input:
continue
if user_input.lower() == "exit":
is_complete = True
await agent.add_chat_message(
thread_id=thread_id, message=ChatMessageContent(role=AuthorRole.USER, content=user_input)
)
is_code = False
last_role = None
async for response in agent.invoke_stream(thread_id=thread_id):
current_is_code = response.metadata.get("code", False)
if current_is_code:
if not is_code:
print("\n\n```python")
is_code = True
print(response.content, end="", flush=True)
else:
if is_code:
print("\n```")
is_code = False
last_role = None
if hasattr(response, "role") and response.role is not None and last_role != response.role:
print(f"\n# {response.role}: ", end="", flush=True)
last_role = response.role
print(response.content, end="", flush=True)
file_ids.extend([
item.file_id for item in response.items if isinstance(item, StreamingFileReferenceContent)
])
if is_code:
print("```\n")
await download_response_image(agent, file_ids)
file_ids.clear()
finally:
print("\nCleaning up resources...")
if agent is not None:
[await agent.delete_file(file_id) for file_id in agent.code_interpreter_file_ids]
await agent.delete_thread(thread_id)
await agent.delete()
if __name__ == "__main__":
asyncio.run(main())
위에 표시된 것처럼 리포지토리에서 전체 코드찾을 수 있습니다.
에이전트는 현재 Java에서 사용할 수 없습니다.