Catatan
Akses ke halaman ini memerlukan otorisasi. Anda dapat mencoba masuk atau mengubah direktori.
Akses ke halaman ini memerlukan otorisasi. Anda dapat mencoba mengubah direktori.
Panduan:
Penting
Fitur ini sedang dalam tahap kandidat rilis. Fitur pada tahap ini hampir lengkap dan umumnya stabil, meskipun mungkin mengalami penyempurnaan atau pengoptimalan kecil sebelum mencapai ketersediaan umum penuh.
Gambaran Umum
Dalam sampel ini, kita akan mengeksplorasi cara menggunakan alat penerjemah kode dari OpenAIAssistantAgent untuk menyelesaikan tugas analisis data. Pendekatan akan dibagi menjadi langkah-langkah untuk menyoroti bagian-bagian utama dari proses pengodean. Sebagai bagian dari tugas, agen akan menghasilkan respons gambar dan teks. Ini akan menunjukkan fleksibilitas alat ini dalam melakukan analisis kuantitatif.
Respons agen akan disampaikan melalui streaming. Ini akan memberikan pembaruan real-time saat tugas berlangsung.
Memulai
Sebelum melanjutkan pengkodian fitur, pastikan lingkungan pengembangan Anda sepenuhnya disiapkan dan dikonfigurasi.
Mulailah dengan membuat proyek Konsol. Kemudian, sertakan referensi paket berikut untuk memastikan semua dependensi yang diperlukan tersedia.
Untuk menambahkan dependensi paket dari baris perintah, gunakan dotnet perintah :
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
Penting
Jika mengelola paket NuGet di Visual Studio, pastikan Include prerelease dicentang.
File proyek (.csproj) harus berisi definisi berikut 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>
Agent Framework bersifat eksperimental dan memerlukan pemadaman peringatan. Ini dapat diatasi sebagai properti dalam file proyek (.csproj):
<PropertyGroup>
<NoWarn>$(NoWarn);CA2007;IDE1006;SKEXP0001;SKEXP0110;OPENAI001</NoWarn>
</PropertyGroup>
Selain itu, salin file data PopulationByAdmin1.csv dan PopulationByCountry.csv dari Proyek Kernel LearnResources Semantik. Tambahkan file ini di folder proyek Anda dan konfigurasikan agar disalin ke direktori output:
<ItemGroup>
<None Include="PopulationByAdmin1.csv">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="PopulationByCountry.csv">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
Mulailah dengan membuat folder yang akan menyimpan skrip (.py file) dan sumber daya sampel Anda. Sertakan impor berikut di bagian atas file Anda .py :
import asyncio
import os
from semantic_kernel.agents import AssistantAgentThread, AzureAssistantAgent
from semantic_kernel.contents import StreamingFileReferenceContent
Selain itu, salin file data PopulationByAdmin1.csv dan PopulationByCountry.csv dari direktori Kernel Semantik learn_resources/resources. Tambahkan file ini ke direktori kerja Anda.
Fitur saat ini tidak tersedia di Java.
Konfigurasi
Sampel ini memerlukan pengaturan konfigurasi untuk terhubung ke layanan jarak jauh. Anda harus menentukan pengaturan untuk OpenAI atau Azure OpenAI.
# OpenAI
dotnet user-secrets set "OpenAISettings:ApiKey" "<api-key>"
dotnet user-secrets set "OpenAISettings:ChatModel" "gpt-4o"
# Azure OpenAI
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"
Kelas berikut digunakan dalam semua contoh Agen. Pastikan untuk menyertakannya dalam proyek Anda untuk memastikan fungsionalitas yang tepat. Kelas ini berfungsi sebagai komponen dasar untuk contoh berikut.
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();
}
}
Cara tercepat untuk memulai konfigurasi yang tepat untuk menjalankan kode sampel adalah dengan membuat .env file di akar proyek Anda (tempat skrip Anda dijalankan).
Konfigurasikanlah pengaturan berikut dalam file Anda .env untuk Azure OpenAI atau OpenAI:
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=""
Petunjuk / Saran
Azure Assistants memerlukan versi API setidaknya 2024-05-01-preview. Saat fitur baru diperkenalkan, versi API diperbarui dengan sesuai. Pada penulisan ini, versi terbaru adalah 2025-01-01-preview. Untuk detail versi terbaru, lihat siklus hidup pratinjau Azure OpenAI API.
Setelah dikonfigurasi, masing-masing kelas layanan AI akan mengambil variabel yang diperlukan dan menggunakannya selama instansiasi.
Fitur saat ini tidak tersedia di Java.
Pengkodean
Proses pengkodian untuk sampel ini melibatkan:
- Penyiapan - Menginisialisasi pengaturan dan plug-in.
-
Definisi Agen - Buat _OpenAI_Assistant
Agentdengan instruksi dan plug-in yang ditemplatisasi. - The Chat Loop - Tulis perulangan yang mendorong interaksi pengguna dan agen.
Contoh lengkap kode disediakan di bagian Akhir . Lihat bagian tersebut untuk implementasi lengkap.
Pengaturan
Sebelum membuat OpenAIAssistantAgent, pastikan pengaturan konfigurasi tersedia dan siapkan sumber daya file.
Instansiasi kelas Settings yang dirujuk di bagian Konfigurasi sebelumnya. Gunakan pengaturan untuk juga membuat AzureOpenAIClient yang akan digunakan untuk Definisi Agen serta pengunggahan file.
Settings settings = new();
AzureOpenAIClient client = OpenAIAssistantAgent.CreateAzureOpenAIClient(new AzureCliCredential(), new Uri(settings.AzureOpenAI.Endpoint));
Fitur saat ini tidak tersedia di Java.
Gunakan AzureOpenAIClient untuk mengakses OpenAIFileClient dan mengunggah dua file data yang dijelaskan di bagian Konfigurasi sebelumnya, sambil mempertahankan Referensi File untuk pembersihan akhir.
Console.WriteLine("Uploading files...");
OpenAIFileClient fileClient = client.GetOpenAIFileClient();
OpenAIFile fileDataCountryDetail = await fileClient.UploadFileAsync("PopulationByAdmin1.csv", FileUploadPurpose.Assistants);
OpenAIFile fileDataCountryList = await fileClient.UploadFileAsync("PopulationByCountry.csv", FileUploadPurpose.Assistants);
Sebelum membuat AzureAssistantAgent atau OpenAIAssistantAgent, pastikan pengaturan konfigurasi tersedia dan siapkan sumber daya file.
Petunjuk / Saran
Anda mungkin perlu menyesuaikan jalur file tergantung di mana file Anda berada.
# Let's form the file paths that we will use as part of file upload
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",
)
# Create the client using Azure OpenAI resources and configuration
client, model = AzureAssistantAgent.setup_resources()
# Upload the files to the client
file_ids: list[str] = []
for path in [csv_file_path_1, csv_file_path_2]:
with open(path, "rb") as file:
file = await client.files.create(file=file, purpose="assistants")
file_ids.append(file.id)
# Get the code interpreter tool and resources
code_interpreter_tools, code_interpreter_tool_resources = AzureAssistantAgent.configure_code_interpreter_tool(
file_ids=file_ids
)
# Create the assistant definition
definition = await client.beta.assistants.create(
model=model,
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.
""",
name="SampleAssistantAgent",
tools=code_interpreter_tools,
tool_resources=code_interpreter_tool_resources,
)
Pertama-tama, kami menyiapkan sumber daya Azure OpenAI untuk mendapatkan klien dan model. Selanjutnya, kami mengunggah file CSV dari jalur yang ditentukan menggunakan FILES API klien. Kemudian, kami mengonfigurasi code_interpreter_tool dengan menggunakan ID file yang diunggah, yang dihubungkan ke asisten saat dibuat, beserta model, instruksi, dan nama.
Fitur saat ini tidak tersedia di Java.
Definisi Agen
Kami sekarang siap untuk menginstansiasi OpenAIAssistantAgent dengan terlebih dahulu membuat definisi pembantu. Asisten dikonfigurasi dengan model targetnya, Instruksi, dan alat Code Interpreter diaktifkan. Selain itu, kami secara eksplisit mengaitkan dua file data dengan alat Penerjemah Kode.
Console.WriteLine("Defining agent...");
AssistantClient assistantClient = client.GetAssistantClient();
Assistant assistant =
await assistantClient.CreateAssistantAsync(
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]);
// Create agent
OpenAIAssistantAgent agent = new(assistant, assistantClient);
Kami sekarang siap untuk menginisialisasi AzureAssistantAgent. Agen dikonfigurasi dengan definisi klien dan asisten.
# Create the agent using the client and the assistant definition
agent = AzureAssistantAgent(
client=client,
definition=definition,
)
Fitur saat ini tidak tersedia di Java.
Perulangan Obrolan
Akhirnya, kita dapat mengoordinasikan interaksi antara pengguna dan Agent. Dimulai dengan membuat AgentThread untuk menjaga status percakapan dan membentuk perulangan kosong.
Mari kita pastikan juga sumber daya dihapus di akhir eksekusi untuk meminimalkan biaya yang tidak perlu.
Console.WriteLine("Creating thread...");
AssistantAgentThread agentThread = new();
Console.WriteLine("Ready!");
try
{
bool isComplete = false;
List<string> fileIds = [];
do
{
} while (!isComplete);
}
finally
{
Console.WriteLine();
Console.WriteLine("Cleaning-up...");
await Task.WhenAll(
[
agentThread.DeleteAsync(),
assistantClient.DeleteAssistantAsync(assistant.Id),
fileClient.DeleteFileAsync(fileDataCountryList.Id),
fileClient.DeleteFileAsync(fileDataCountryDetail.Id),
]);
}
thread: AssistantAgentThread = None
try:
is_complete: bool = False
file_ids: list[str] = []
while not is_complete:
# agent interaction logic here
finally:
print("\nCleaning up resources...")
[await client.files.delete(file_id) for file_id in file_ids]
await thread.delete() if thread else None
await client.beta.assistants.delete(agent.id)
Fitur saat ini tidak tersedia di Java.
Sekarang mari kita menangkap input pengguna dalam perulangan sebelumnya. Dalam hal ini, input kosong akan diabaikan dan istilah EXIT akan memberi sinyal bahwa percakapan selesai.
Console.WriteLine();
Console.Write("> ");
string input = Console.ReadLine();
if (string.IsNullOrWhiteSpace(input))
{
continue;
}
if (input.Trim().Equals("EXIT", StringComparison.OrdinalIgnoreCase))
{
isComplete = true;
break;
}
var message = 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
Fitur saat ini tidak tersedia di Java.
Sebelum memanggil respons Agent, mari kita tambahkan beberapa metode pembantu untuk mengunduh file apa pun yang mungkin diproduksi oleh Agent.
Di sini kita menempatkan konten file dalam direktori sementara yang ditentukan sistem lalu meluncurkan aplikasi penampil yang ditentukan sistem.
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)
Fitur saat ini tidak tersedia di Java.
Untuk menghasilkan respons Agent terhadap input pengguna, aktifkan agen dengan memberikan pesan dan AgentThread. Dalam contoh ini, kami memilih respons yang dialirkan dan mengambil Referensi File yang dihasilkan untuk diunduh dan ditinjau di akhir siklus respons. Penting untuk dicatat bahwa kode yang dihasilkan diidentifikasi dengan adanya kunci Metadata dalam pesan respons, membedakannya dari balasan percakapan.
bool isCode = false;
await foreach (StreamingChatMessageContent response in agent.InvokeStreamingAsync(message, agentThread))
{
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 = False
last_role = None
async for response in agent.invoke_stream(messages=user_input, thread=thread):
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)
])
thread = response.thread
if is_code:
print("```\n")
print()
await download_response_image(agent, file_ids)
file_ids.clear()
Fitur saat ini tidak tersedia di Java.
Akhir
Menggabungkan semua langkah, berikut adalah kode akhir untuk contoh ini. Implementasi lengkap disediakan di bawah ini.
Coba gunakan input yang disarankan ini:
- Bandingkan file untuk menentukan jumlah negara tidak memiliki negara bagian atau provinsi yang ditentukan dibandingkan dengan jumlah total
- Buat tabel untuk negara dengan negara bagian atau provinsi yang ditentukan. Sertakan jumlah negara bagian atau provinsi dan total populasi
- Berikan bagan batang untuk negara yang namanya dimulai dengan huruf yang sama dan urutkan sumbu x menurut jumlah tertinggi ke terendah (termasuk semua negara)
using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Agents.OpenAI;
using Microsoft.SemanticKernel.ChatCompletion;
using OpenAI.Assistants;
using OpenAI.Files;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace AgentsSample;
public static class Program
{
public static async Task Main()
{
// Load configuration from environment variables or user secrets.
Settings settings = new();
// Initialize the clients
AzureOpenAIClient client = OpenAIAssistantAgent.CreateAzureOpenAIClient(new AzureCliCredential(), new Uri(settings.AzureOpenAI.Endpoint));
//OpenAIClient client = OpenAIAssistantAgent.CreateOpenAIClient(new ApiKeyCredential(settings.OpenAI.ApiKey)));
AssistantClient assistantClient = client.GetAssistantClient();
OpenAIFileClient fileClient = client.GetOpenAIFileClient();
// Upload files
Console.WriteLine("Uploading files...");
OpenAIFile fileDataCountryDetail = await fileClient.UploadFileAsync("PopulationByAdmin1.csv", FileUploadPurpose.Assistants);
OpenAIFile fileDataCountryList = await fileClient.UploadFileAsync("PopulationByCountry.csv", FileUploadPurpose.Assistants);
// Define assistant
Console.WriteLine("Defining assistant...");
Assistant assistant =
await assistantClient.CreateAssistantAsync(
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]);
// Create agent
OpenAIAssistantAgent agent = new(assistant, assistantClient);
// Create the conversation thread
Console.WriteLine("Creating thread...");
AssistantAgentThread agentThread = new();
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;
}
var message = new ChatMessageContent(AuthorRole.User, input);
Console.WriteLine();
bool isCode = false;
await foreach (StreamingChatMessageContent response in agent.InvokeStreamingAsync(message, agentThread))
{
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(
[
agentThread.DeleteAsync(),
assistantClient.DeleteAssistantAsync(assistant.Id),
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}"
});
}
}
}
}
import asyncio
import logging
import os
from semantic_kernel.agents import AssistantAgentThread, AzureAssistantAgent
from semantic_kernel.contents import StreamingFileReferenceContent
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():
# Create the client using Azure OpenAI resources and configuration
client, model = AzureAssistantAgent.setup_resources()
# Upload the files to the client
file_ids: list[str] = []
for path in [csv_file_path_1, csv_file_path_2]:
with open(path, "rb") as file:
file = await client.files.create(file=file, purpose="assistants")
file_ids.append(file.id)
# Get the code interpreter tool and resources
code_interpreter_tools, code_interpreter_tool_resources = AzureAssistantAgent.configure_code_interpreter_tool(
file_ids=file_ids
)
# Create the assistant definition
definition = await client.beta.assistants.create(
model=model,
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.
""",
name="SampleAssistantAgent",
tools=code_interpreter_tools,
tool_resources=code_interpreter_tool_resources,
)
# Create the agent using the client and the assistant definition
agent = AzureAssistantAgent(
client=client,
definition=definition,
)
thread: AssistantAgentThread = None
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
break
is_code = False
last_role = None
async for response in agent.invoke_stream(messages=user_input, thread=thread):
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)
])
thread = response.thread
if is_code:
print("```\n")
print()
await download_response_image(agent, file_ids)
file_ids.clear()
finally:
print("\nCleaning up resources...")
[await client.files.delete(file_id) for file_id in file_ids]
await thread.delete() if thread else None
await client.beta.assistants.delete(agent.id)
if __name__ == "__main__":
asyncio.run(main())
Anda mungkin menemukan kode lengkap, seperti yang ditunjukkan di atas, dalam repositori kami.
Fitur saat ini tidak tersedia di Java.
Langkah selanjutnya
Bagaimana cara mencari File Kode