Postupy: interpret kódu OpenAIAssistantAgent
Důležité
Tato funkce je ve fázi kandidáta pro vydání. Funkce v této fázi jsou téměř dokončené a obecně stabilní, i když mohou před dosažením úplné obecné dostupnosti projít menší vylepšení nebo optimalizace.
Přehled
V této ukázce prozkoumáme, jak využít nástroj interpretu kódu od OpenAIAssistantAgent
k dokončení úloh analýzy dat. Přístup bude systematicky rozdělen krok za krokem, aby byly zvýrazněny klíčové části procesu kódování. V rámci úlohy agent vygeneruje jak obrázky, tak textové odpovědi. To předvede všestrannost tohoto nástroje při provádění kvantitativní analýzy.
Streamování se použije k doručování odpovědí agenta. To bude poskytovat aktualizace v reálném čase při průběhu úkolu.
Začínáme
Než budete pokračovat v kódování funkcí, ujistěte se, že je vaše vývojové prostředí plně nastavené a nakonfigurované.
Začněte vytvořením projektu konzoly . Pak zahrňte následující odkazy na balíčky, abyste zajistili, že jsou k dispozici všechny požadované závislosti.
Pokud chcete přidat závislosti balíčků z příkazového řádku, použijte tento dotnet
příkaz:
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
Pokud spravujete balíčky NuGet v sadě Visual Studio, zkontrolujte, jestli
Include prerelease
je zaškrtnuté.
Soubor projektu (.csproj
) by měl obsahovat následující PackageReference
definice:
<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
je experimentální a vyžaduje potlačení upozornění. To se může vyřešit jako vlastnost v souboru projektu (.csproj
):
<PropertyGroup>
<NoWarn>$(NoWarn);CA2007;IDE1006;SKEXP0001;SKEXP0110;OPENAI001</NoWarn>
</PropertyGroup>
Kromě toho zkopírujte datové soubory
<ItemGroup>
<None Include="PopulationByAdmin1.csv">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="PopulationByCountry.csv">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
Začněte vytvořením složky, která bude obsahovat váš skript (.py
soubor) a ukázkové prostředky. Do horní části souboru .py
vložte následující importy:
import asyncio
import os
from semantic_kernel.agents.open_ai import AzureAssistantAgent
from semantic_kernel.contents import StreamingFileReferenceContent
Dále zkopírujte datové soubory PopulationByAdmin1.csv
a PopulationByCountry.csv
ze složky Semantic Kernellearn_resources/resources
do adresáře. Přidejte tyto soubory do pracovního adresáře.
Agenti momentálně nejsou v Javě k dispozici.
Konfigurace
Tato ukázka vyžaduje nastavení konfigurace pro připojení ke vzdáleným službám. Budete muset definovat nastavení pro OpenAI nebo 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"
Následující třída se používá ve všech příkladech agenta. Nezapomeňte ho zahrnout do projektu, abyste zajistili správné funkce. Tato třída slouží jako základní komponenta pro následující příklady.
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();
}
}
Nejrychlejší způsob, jak začít se správnou konfigurací pro spuštění ukázkového kódu, je vytvořit .env
soubor v kořenovém adresáři projektu (kde se spouští váš skript).
Nakonfigurujte následující nastavení ve svém souboru .env
pro Azure OpenAI nebo 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=""
[! TIP] Azure Assistants vyžadují verzi rozhraní API minimálně 2024-05-01-preview. Při zavádění nových funkcí se odpovídajícím způsobem aktualizují verze rozhraní API. K datu psaní tohoto textu je nejnovější verze 2025-01-01-preview. Nejnovější podrobnosti o verzích najdete v náhledovém životním cyklu rozhraní Azure OpenAI API.
Po nakonfigurování příslušné třídy služeb AI vyberou požadované proměnné a použijí je při instanciaci.
Agenti momentálně nejsou v Javě k dispozici.
Kódování
Proces kódování pro tuto ukázku zahrnuje:
- Nastavení – Inicializace nastavení a modulu plug-in.
-
definice agenta – vytvořte _OpenAI_Assistant
Agent
se šablonovanými pokyny a plug-in modulu. - Smyčka chatu – napište smyčku, která řídí interakci mezi uživatelem a agentem.
Úplný ukázkový kód je k dispozici v části Konečný . Kompletní implementaci najdete v této části.
Nastavení
Před vytvořením OpenAIAssistantAgent
se ujistěte, že jsou dostupná všechna konfigurační nastavení, a připravte souborové prostředky.
Vytvořte instanci třídy Settings
, na kterou bylo odkazováno v předchozí části Konfigurace. Pomocí nastavení můžete také vytvořit AzureOpenAIClient
, která se použije pro Definici agenta a také pro nahrání souboru.
Settings settings = new();
AzureOpenAIClient client = OpenAIAssistantAgent.CreateAzureOpenAIClient(new AzureCliCredential(), new Uri(settings.AzureOpenAI.Endpoint));
Agenti momentálně nejsou v Javě k dispozici.
AzureOpenAIClient
Použijte k přístupu k OpenAIFileClient
a nahrání dvou datových souborů popsaných v předchozí části Konfigurace a zachování odkazu na soubor pro konečné vyčištění.
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);
Před vytvořením AzureAssistantAgent
nebo OpenAIAssistantAgent
se ujistěte, že jsou k dispozici konfigurační nastavení a připravte souborové prostředky.
Doporučení
Možná budete muset upravit cesty k souborům v závislosti na umístění souborů.
# 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,
)
Nejprve nastavíme prostředky Azure OpenAI pro získání klienta a modelu. Dále nahrajeme soubory CSV ze zadaných cest pomocí rozhraní API souborů klienta. Potom nakonfigurujeme code_interpreter_tool
pomocí id nahraných souborů, které jsou při vytváření propojeny s asistentem spolu s modelem, pokyny a názvem.
Agenti momentálně nejsou v Javě k dispozici.
Definice agenta
Teď jsme připraveni vytvořit instanci OpenAIAssistantAgent
, nejprve vytvoříme definici asistenta. Pomocník je nakonfigurován s cílovým modelem, Pokyny, a nástrojem Interpret kódu povoleným. Kromě toho explicitně přidružíme dva datové soubory k nástroji Interpret kódu .
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);
Nyní jsme připraveni vytvořit instanci AzureAssistantAgent
. Agent je nakonfigurovaný s klientem a definicí pomocníka.
# Create the agent using the client and the assistant definition
agent = AzureAssistantAgent(
client=client,
definition=definition,
)
Agenti momentálně nejsou v Javě k dispozici.
Chatová smyčka
Nakonec můžeme koordinovat interakci mezi uživatelem a Agent
. Začněte vytvořením vlákna pomocníka, které udržuje stav konverzace a vytváří prázdnou smyčku.
Pojďme se také ujistit, že se prostředky na konci provádění odeberou, aby se minimalizovaly zbytečné poplatky.
Console.WriteLine("Creating thread...");
AssistantThread thread = await assistantClient.CreateThreadAsync();
Console.WriteLine("Ready!");
try
{
bool isComplete = false;
List<string> fileIds = [];
do
{
} while (!isComplete);
}
finally
{
Console.WriteLine();
Console.WriteLine("Cleaning-up...");
await Task.WhenAll(
[
assistantClient.DeleteThreadAsync(thread.Id),
assistantClient.DeleteAssistantAsync(assistant.Id),
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("\nCleaning up resources...")
[await client.files.delete(file_id) for file_id in file_ids]
await client.beta.threads.delete(thread.id)
await client.beta.assistants.delete(agent.id)
Agenti momentálně nejsou v Javě k dispozici.
Teď zachytáme vstup uživatele v rámci předchozí smyčky. V tomto případě se prázdný vstup ignoruje a termín EXIT
bude signalizovat, že konverzace je dokončená. Platný vstup se přidá do vlákna pomocníka jako zpráva uživatele.
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(thread.Id, 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))
Agenti momentálně nejsou v Javě k dispozici.
Než vyvoláme odpověď Agent
, přidáme některé pomocné metody ke stažení všech souborů, které mohou být vytvořeny Agent
.
Tady umístíme obsah souboru do dočasného adresáře definovaného systémem a pak spustíme aplikaci prohlížeče definovanou systémem.
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)
Agenti momentálně nejsou v Javě k dispozici.
Chcete-li vygenerovat odpověď Agent
na vstup uživatele, spusťte agenta zadáním Assistant Thread. V tomto příkladu zvolíme streamovanou odpověď a zaznamenáme všechny vygenerované odkazy na soubory ke stažení a kontrole na konci cyklu odpovědi. Je důležité si uvědomit, že vygenerovaný kód je identifikován přítomností klíče metadat ve zprávě odpovědi a odlišením od konverzační odpovědi.
bool isCode = false;
await foreach (StreamingChatMessageContent response in agent.InvokeStreamingAsync(thread.Id))
{
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()
Agenti momentálně nejsou v Javě k dispozici.
Finální
Spojte všechny kroky dohromady, máme pro tento příklad konečný kód. Kompletní implementace je uvedená níže.
Zkuste použít tyto navrhované vstupy:
- Porovnejte soubory a určete počet zemí, které nemají definovaný stát nebo provincii, v porovnání s celkovým počtem zemí.
- Vytvořte tabulku pro země s definovaným státem nebo provincií. Zahrnout počet států nebo provincií a celkový počet obyvatel
- Zadejte pruhový graf pro země, jejichž názvy začínají stejným písmenem, a seřaďte osu x podle nejvyššího počtu na nejnižší (včetně všech zemí).
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...");
AssistantThread thread = await assistantClient.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(thread.Id, new ChatMessageContent(AuthorRole.User, input));
Console.WriteLine();
bool isCode = false;
await foreach (StreamingChatMessageContent response in agent.InvokeStreamingAsync(thread.Id))
{
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(
[
assistantClient.DeleteThreadAsync(thread.Id),
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.open_ai import 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,
)
print("Creating thread...")
thread = await client.beta.threads.create()
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
await agent.add_chat_message(thread_id=thread.id, message=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")
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 client.beta.threads.delete(thread.id)
await client.beta.assistants.delete(agent.id)
if __name__ == "__main__":
asyncio.run(main())
Úplný kód , jak je znázorněno výše, najdete v našem úložišti.
Agenti momentálně nejsou v Javě k dispozici.
Návod: OpenAIAssistantAgent
Vyhledávání souborů s kódem