Not
Bu sayfaya erişim yetkilendirme gerektiriyor. Oturum açmayı veya dizinleri değiştirmeyi deneyebilirsiniz.
Bu sayfaya erişim yetkilendirme gerektiriyor. Dizinleri değiştirmeyi deneyebilirsiniz.
Nasıl Yapılır:
Önemli
Bu özellik, sürüm adayı aşamasındadır. Bu aşamadaki özellikler neredeyse eksiksiz ve genel olarak kararlıdır, ancak genel kullanıma ulaşmadan önce küçük iyileştirmeler veya iyileştirmeler yapabilir.
Genel bakış
Bu örnekte, kavrama görevlerini tamamlamak için bir OpenAIAssistantAgent dosyasının dosya arama aracının nasıl kullanılacağını keşfedeceğiz. Yaklaşım adım adım olacak ve süreç boyunca netlik ve duyarlık sağlayacaktır. Görevin bir parçası olarak, ajan yanıtında belge alıntıları sağlayacaktır.
Akış, temsilcinin yanıtlarını iletmek için kullanılacak. Bu, görev ilerledikçe gerçek zamanlı güncelleştirmeler sağlar.
Kullanmaya Başlama
Özellik kodlamaya devam etmeden önce geliştirme ortamınızın tam olarak ayarlandığından ve yapılandırıldığından emin olun.
Komut satırından paket bağımlılıkları eklemek için komutunu dotnet kullanın:
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
Önemli
Visual Studio'da NuGet paketlerini yönetiyorsanız, Include prerelease işaretli olduğundan emin olun.
Proje dosyası (.csproj) aşağıdaki PackageReference tanımları içermelidir:
<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 deneyseldir ve uyarı gizleme gerektirir. Bu, proje dosyasında bir özellik olarak ele alınabilir (.csproj):
<PropertyGroup>
<NoWarn>$(NoWarn);CA2007;IDE1006;SKEXP0001;SKEXP0110;OPENAI001</NoWarn>
</PropertyGroup>
Ayrıca, Grimms-The-King-of-the-Golden-Mountain.txtGrimms-The-Water-of-Life.txt ve Grimms-The-White-Snake.txtLearnResources ortak etki alanı içeriğini kopyalayın. Bu dosyaları proje klasörünüze ekleyin ve çıkış dizinine kopyalanmalarını sağlamak için yapılandırın.
<ItemGroup>
<None Include="Grimms-The-King-of-the-Golden-Mountain.txt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="Grimms-The-Water-of-Life.txt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="Grimms-The-White-Snake.txt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
Betiğinizi (.py dosya) ve örnek kaynakları barındıracak bir klasör oluşturarak başlayın. Dosyanızın .py dosyasının en üstüne aşağıdaki import'ları ekleyin:
import asyncio
import os
from semantic_kernel.agents import AssistantAgentThread, AzureAssistantAgent
from semantic_kernel.contents import StreamingAnnotationContent
Ayrıca, Grimms-The-King-of-the-Golden-Mountain.txtGrimms-The-Water-of-Life.txt ve Grimms-The-White-Snake.txtLearnResources ortak etki alanı içeriğini kopyalayın. Bu dosyaları proje klasörünüzde ekleyin.
Özellik şu anda Java'da kullanılamıyor.
Yapılandırma
Bu örnek, uzak hizmetlere bağlanmak için yapılandırma ayarı gerektirir. OpenAI veya Azure OpenAI ayarlarını tanımlamanız gerekir.
# 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" "https://lightspeed-team-shared-openai-eastus.openai.azure.com/"
dotnet user-secrets set "AzureOpenAISettings:ChatModelDeployment" "gpt-4o"
Aşağıdaki sınıf tüm Agent örneklerinde kullanılır. Düzgün işlevsellik sağlamak için bunu projenize eklediğinizden emin olun. Bu sınıf, aşağıdaki örnekler için temel bir bileşen olarak hizmet eder.
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();
}
}
Örnek kodu çalıştırmak için uygun yapılandırmayı kullanmaya başlamanın en hızlı yolu, projenizin kökünde (betiğinizin çalıştırıldığı) bir .env dosya oluşturmaktır.
Azure OpenAI veya OpenAI için dosyanızda .env aşağıdaki ayarları yapılandırın:
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=""
Bahşiş
Azure Yardımcıları için en az 2024-05-01-preview API sürümü gerekir. Yeni özellikler kullanıma sunulduğunda API sürümleri uygun şekilde güncelleştirilir. Bu yazıdan itibaren en son sürüm 2025-01-01-preview sürümüdür. Güncel sürüm detayları için Azure OpenAI API önizleme yaşam döngüsüne başvurun.
Yapılandırıldıktan sonra ilgili yapay zeka hizmet sınıfları gerekli değişkenleri alır ve örnekleme sırasında kullanır.
Özellik şu anda Java'da kullanılamıyor.
Kodlama
Bu örnek için kodlama işlemi şunları içerir:
- Kurulum - Ayarları ve eklentiyi başlatma.
- Aracı Tanımı - Şablonlu yönergeler ve eklenti ile _Chat_Completion
Agentoluşturun. - Sohbet Döngüsü - Kullanıcı/aracı etkileşimini yönlendiren döngüleri yazın.
Örnek kodun tamamı Final bölümünde verilmiştir. Tam uygulama için bu bölüme bakın.
Ayarlama
OpenAIAssistantAgentoluşturmadan önce yapılandırma ayarlarının kullanılabilir olduğundan emin olun ve dosya kaynaklarını hazırlayın.
Settings Önceki Yapılandırma bölümünde başvurulan sınıfın örneğini oluşturun. Ayarları kullanarak, dosya yükleme ve AzureOpenAIClient oluşturma işlemlerinin yanı sıra Aracı Tanımı için de kullanılacak bir VectorStore oluşturun.
Settings settings = new();
AzureOpenAIClient client = OpenAIAssistantAgent.CreateAzureOpenAIClient(new AzureCliCredential(), new Uri(settings.AzureOpenAI.Endpoint));
Yardımcı Aracı üzerindeki statik yöntem create_client() , istemciyi oluşturmayı ve istenen yapılandırmaya göre döndürmeyi işler. Pydantic ayarları, ortam değişkenlerini önce ortam değişkenlerinden veya .env dosyasından yüklemek için kullanılır.
api_key, api_version, deployment_name veya endpoint, yapılandırılmış ortam değişkenlerinden herhangi birine kıyasla öncelik kazanacaktır.
# Create the client using Azure OpenAI resources and configuration
client = AzureAssistantAgent.create_client()
Özellik şu anda Java'da kullanılamıyor.
Şimdi Dosya Arama aracıyla kullanmak üzere boş bir _Vector Deposu oluşturun:
Bir AzureOpenAIClient öğesine erişmek ve bir VectorStoreClient oluşturmak için VectorStore kullanın.
Console.WriteLine("Creating store...");
VectorStoreClient storeClient = client.GetVectorStoreClient();
CreateVectorStoreOperation operation = await storeClient.CreateVectorStoreAsync(waitUntilCompleted: true);
string storeId = operation.VectorStoreId;
# Upload the files to the client
file_ids: list[str] = []
for path in [get_filepath_for_filename(filename) for filename in filenames]:
with open(path, "rb") as file:
file = await client.files.create(file=file, purpose="assistants")
file_ids.append(file.id)
vector_store = await client.vector_stores.create(
name="assistant_search",
file_ids=file_ids,
)
# Get the file search tool and resources
file_search_tools, file_search_tool_resources = AzureAssistantAgent.configure_file_search_tool(
vector_store_ids=vector_store.id
)
Özellik şu anda Java'da kullanılamıyor.
Önceki Yapılandırma bölümünde açıklanan üç içerik dosyasını bildirelim:
private static readonly string[] _fileNames =
[
"Grimms-The-King-of-the-Golden-Mountain.txt",
"Grimms-The-Water-of-Life.txt",
"Grimms-The-White-Snake.txt",
];
filenames = [
"Grimms-The-King-of-the-Golden-Mountain.txt",
"Grimms-The-Water-of-Life.txt",
"Grimms-The-White-Snake.txt",
]
Özellik şu anda Java'da kullanılamıyor.
Şimdi bu dosyaları daha önce oluşturulan istemcileri kullanarak yükleyin ve her dosyayı VectorStoreClient parametresiyle OpenAIFileClient'na ekleyin, böylece elde edilen Dosya Referanslarını koruyun.
Dictionary<string, OpenAIFile> fileReferences = [];
Console.WriteLine("Uploading files...");
OpenAIFileClient fileClient = client.GetOpenAIFileClient();
foreach (string fileName in _fileNames)
{
OpenAIFile fileInfo = await fileClient.UploadFileAsync(fileName, FileUploadPurpose.Assistants);
await storeClient.AddFileToVectorStoreAsync(storeId, fileInfo.Id, waitUntilCompleted: true);
fileReferences.Add(fileInfo.Id, fileInfo);
}
Özellik şu anda Java'da kullanılamıyor.
Ajan Tanımı
Artık bir OpenAIAssistantAgent örneğini oluşturmaya hazırız. Aracı hedef modeli, Yönergeler ve Dosya Arama aracı etkin olarak yapılandırılır. Ayrıca, Vektör Deposu'nı Dosya Arama aracıyla açıkça ilişkilendiririz.
AzureOpenAIClient öğesini oluşturma işleminin bir parçası olarak OpenAIAssistantAgent yeniden kullanacağız.
Console.WriteLine("Defining assistant...");
Assistant assistant =
await assistantClient.CreateAssistantAsync(
settings.AzureOpenAI.ChatModelDeployment,
name: "SampleAssistantAgent",
instructions:
"""
The document store contains the text of fictional stories.
Always analyze the document store to provide an answer to the user's question.
Never rely on your knowledge of stories not included in the document store.
Always format response using markdown.
""",
enableFileSearch: true,
vectorStoreId: storeId);
// Create agent
OpenAIAssistantAgent agent = new(assistant, assistantClient);
# Create the assistant definition
definition = await client.beta.assistants.create(
model=AzureOpenAISettings().chat_deployment_name,
instructions="""
The document store contains the text of fictional stories.
Always analyze the document store to provide an answer to the user's question.
Never rely on your knowledge of stories not included in the document store.
Always format response using markdown.
""",
name="SampleAssistantAgent",
tools=file_search_tools,
tool_resources=file_search_tool_resources,
)
# Create the agent using the client and the assistant definition
agent = AzureAssistantAgent(
client=client,
definition=definition,
)
Özellik şu anda Java'da kullanılamıyor.
Sohbet Döngüsü
Sonunda kullanıcı ile Agentarasındaki etkileşimi koordine edebiliyoruz. Konuşma durumunu korumak için bir AgentThread oluşturarak ve boş bir döngü oluşturarak başlayın.
Yürütme sonunda kaynakların kaldırılacağından emin olalım ki gereksiz ücretleri en aza indirelim.
Console.WriteLine("Creating thread...");
OpenAIAssistantAgent agentThread = new();
Console.WriteLine("Ready!");
try
{
bool isComplete = false;
do
{
// Processing occurs here
} while (!isComplete);
}
finally
{
Console.WriteLine();
Console.WriteLine("Cleaning-up...");
await Task.WhenAll(
[
agentThread.DeleteAsync();
assistantClient.DeleteAssistantAsync(assistant.Id),
storeClient.DeleteVectorStoreAsync(storeId),
..fileReferences.Select(fileReference => fileClient.DeleteFileAsync(fileReference.Key))
]);
}
# If no thread is provided, a new thread will be
# created and returned with the initial response
thread: AssistantAgentThread = None
try:
is_complete: bool = False
while not is_complete:
# Processing occurs here
finally:
print("\nCleaning up resources...")
[await client.files.delete(file_id) for file_id in file_ids]
await client.vector_stores.delete(vector_store.id)
await thread.delete() if thread else None
await client.beta.assistants.delete(agent.id)
Özellik şu anda Java'da kullanılamıyor.
Şimdi önceki döngüde kullanıcı girişini yakalayalım. Bu durumda boş giriş yoksayılır ve terim EXIT konuşmanın tamamlandığını gösterir.
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
Özellik şu anda Java'da kullanılamıyor.
Agent yanıtını çağırmadan önce, unicode köşeli ayraçlarını ANSI köşeli ayraçlarına dönüştürmek için yardımcı bir yöntem ekleyelim.
private static string ReplaceUnicodeBrackets(this string content) =>
content?.Replace('【', '[').Replace('】', ']');
# No special handling required.
Özellik şu anda Java'da kullanılamıyor.
Kullanıcı girdisine yanıt oluşturmak için, iletiyi ve aracı iş parçacığını belirterek aracıyı etkinleştirin. Bu örnekte, akış formatında bir yanıt seçeriz ve yanıt döngüsünün sonunda görüntülenmek üzere ilişkili Alıntı Ek Açıklamalarını kaydederiz. Akıtılan her veri parçası, önceden tanımlanmış yardımcı yöntem kullanılarak yeniden biçimlendiriliyor.
List<StreamingAnnotationContent> footnotes = [];
await foreach (StreamingChatMessageContent chunk in agent.InvokeStreamingAsync(message, agentThread))
{
// Capture annotations for footnotes
footnotes.AddRange(chunk.Items.OfType<StreamingAnnotationContent>());
// Render chunk with replacements for unicode brackets.
Console.Write(chunk.Content.ReplaceUnicodeBrackets());
}
Console.WriteLine();
// Render footnotes for captured annotations.
if (footnotes.Count > 0)
{
Console.WriteLine();
foreach (StreamingAnnotationContent footnote in footnotes)
{
Console.WriteLine($"#{footnote.Quote.ReplaceUnicodeBrackets()} - {fileReferences[footnote.FileId!].Filename} (Index: {footnote.StartIndex} - {footnote.EndIndex})");
}
}
footnotes: list[StreamingAnnotationContent] = []
async for response in agent.invoke_stream(messages=user_input, thread=thread):
thread = response.thread
footnotes.extend([item for item in response.items if isinstance(item, StreamingAnnotationContent)])
print(f"{response.content}", end="", flush=True)
print()
if len(footnotes) > 0:
for footnote in footnotes:
print(
f"\n`{footnote.quote}` => {footnote.file_id} "
f"(Index: {footnote.start_index} - {footnote.end_index})"
)
Özellik şu anda Java'da kullanılamıyor.
Nihai
Tüm adımları bir araya getirdiğimizde, bu örneğin son koduna sahibiz. Uygulamanın tamamı aşağıda verilmiştir.
Şu önerilen girişleri kullanmayı deneyin:
- Öykülerin her biri için paragraf sayısı nedir?
- Her hikaye için kahramanı ve antagonisti tanımlayan bir tablo oluşturun.
- Beyaz Yılan'ın ahlakı nedir?
using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Agents;
using Microsoft.SemanticKernel.Agents.OpenAI;
using Microsoft.SemanticKernel.ChatCompletion;
using OpenAI.Assistants;
using OpenAI.Files;
using OpenAI.VectorStores;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AgentsSample;
public static class Program
{
private static readonly string[] _fileNames =
[
"Grimms-The-King-of-the-Golden-Mountain.txt",
"Grimms-The-Water-of-Life.txt",
"Grimms-The-White-Snake.txt",
];
/// <summary>
/// The main entry point for the application.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
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();
VectorStoreClient storeClient = client.GetVectorStoreClient();
// Create the vector store
Console.WriteLine("Creating store...");
CreateVectorStoreOperation operation = await storeClient.CreateVectorStoreAsync(waitUntilCompleted: true);
string storeId = operation.VectorStoreId;
// Upload files and retain file references.
Console.WriteLine("Uploading files...");
Dictionary<string, OpenAIFile> fileReferences = [];
foreach (string fileName in _fileNames)
{
OpenAIFile fileInfo = await fileClient.UploadFileAsync(fileName, FileUploadPurpose.Assistants);
await storeClient.AddFileToVectorStoreAsync(storeId, fileInfo.Id, waitUntilCompleted: true);
fileReferences.Add(fileInfo.Id, fileInfo);
}
// Define assistant
Console.WriteLine("Defining assistant...");
Assistant assistant =
await assistantClient.CreateAssistantAsync(
settings.AzureOpenAI.ChatModelDeployment,
name: "SampleAssistantAgent",
instructions:
"""
The document store contains the text of fictional stories.
Always analyze the document store to provide an answer to the user's question.
Never rely on your knowledge of stories not included in the document store.
Always format response using markdown.
""",
enableFileSearch: true,
vectorStoreId: storeId);
// 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;
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();
List<StreamingAnnotationContent> footnotes = [];
await foreach (StreamingChatMessageContent chunk in agent.InvokeStreamingAsync(message, agentThread))
{
// Capture annotations for footnotes
footnotes.AddRange(chunk.Items.OfType<StreamingAnnotationContent>());
// Render chunk with replacements for unicode brackets.
Console.Write(chunk.Content.ReplaceUnicodeBrackets());
}
Console.WriteLine();
// Render footnotes for captured annotations.
if (footnotes.Count > 0)
{
Console.WriteLine();
foreach (StreamingAnnotationContent footnote in footnotes)
{
Console.WriteLine($"#{footnote.Quote.ReplaceUnicodeBrackets()} - {fileReferences[footnote.FileId!].Filename} (Index: {footnote.StartIndex} - {footnote.EndIndex})");
}
}
} while (!isComplete);
}
finally
{
Console.WriteLine();
Console.WriteLine("Cleaning-up...");
await Task.WhenAll(
[
agentThread.DeleteAsync(),
assistantClient.DeleteAssistantAsync(assistant.Id),
storeClient.DeleteVectorStoreAsync(storeId),
..fileReferences.Select(fileReference => fileClient.DeleteFileAsync(fileReference.Key))
]);
}
}
private static string ReplaceUnicodeBrackets(this string content) =>
content?.Replace('【', '[').Replace('】', ']');
}
# Copyright (c) Microsoft. All rights reserved.
import asyncio
import os
from semantic_kernel.agents import AssistantAgentThread, AzureAssistantAgent
from semantic_kernel.connectors.ai.open_ai import AzureOpenAISettings
from semantic_kernel.contents import StreamingAnnotationContent
"""
The following sample demonstrates how to create a simple,
OpenAI assistant agent that utilizes the vector store
to answer questions based on the uploaded documents.
This is the full code sample for the Semantic Kernel Learn Site: How-To: Open AI Assistant Agent File Search
https://learn.microsoft.com/semantic-kernel/frameworks/agent/examples/example-assistant-search?pivots=programming-language-python
"""
def get_filepath_for_filename(filename: str) -> str:
base_directory = os.path.join(
os.path.dirname(os.path.dirname(os.path.realpath(__file__))),
"resources",
)
return os.path.join(base_directory, filename)
filenames = [
"Grimms-The-King-of-the-Golden-Mountain.txt",
"Grimms-The-Water-of-Life.txt",
"Grimms-The-White-Snake.txt",
]
async def main():
# Create the client using Azure OpenAI resources and configuration
client = AzureAssistantAgent.create_client()
# Upload the files to the client
file_ids: list[str] = []
for path in [get_filepath_for_filename(filename) for filename in filenames]:
with open(path, "rb") as file:
file = await client.files.create(file=file, purpose="assistants")
file_ids.append(file.id)
vector_store = await client.vector_stores.create(
name="assistant_search",
file_ids=file_ids,
)
# Get the file search tool and resources
file_search_tools, file_search_tool_resources = AzureAssistantAgent.configure_file_search_tool(
vector_store_ids=vector_store.id
)
# Create the assistant definition
definition = await client.beta.assistants.create(
model=AzureOpenAISettings().chat_deployment_name,
instructions="""
The document store contains the text of fictional stories.
Always analyze the document store to provide an answer to the user's question.
Never rely on your knowledge of stories not included in the document store.
Always format response using markdown.
""",
name="SampleAssistantAgent",
tools=file_search_tools,
tool_resources=file_search_tool_resources,
)
# Create the agent using the client and the assistant definition
agent = AzureAssistantAgent(
client=client,
definition=definition,
)
thread: AssistantAgentThread | None = None
try:
is_complete: bool = False
while not is_complete:
user_input = input("User:> ")
if not user_input:
continue
if user_input.lower() == "exit":
is_complete = True
break
footnotes: list[StreamingAnnotationContent] = []
async for response in agent.invoke_stream(messages=user_input, thread=thread):
footnotes.extend([item for item in response.items if isinstance(item, StreamingAnnotationContent)])
print(f"{response.content}", end="", flush=True)
thread = response.thread
print()
if len(footnotes) > 0:
for footnote in footnotes:
print(
f"\n`{footnote.quote}` => {footnote.file_id} "
f"(Index: {footnote.start_index} - {footnote.end_index})"
)
finally:
print("\nCleaning up resources...")
[await client.files.delete(file_id) for file_id in file_ids]
await client.vector_stores.delete(vector_store.id)
await thread.delete() if thread else None
await client.beta.assistants.delete(agent.id)
if __name__ == "__main__":
asyncio.run(main())
Yukarıda belirtildiği gibi tam kodu'i depomuzda bulabilirsiniz.
Özellik şu anda Java'da kullanılamıyor.