How-To: 파일 검색 활용법
중요하다
이 기능은 릴리스 후보 단계에 있습니다. 이 단계의 기능은 거의 완전하고 일반적으로 안정적이지만 전체 일반 공급에 도달하기 전에 약간의 개선 또는 최적화가 필요할 수 있습니다.
개요
이 샘플에서는 파일 검색 도구를 OpenAIAssistantAgent 사용하여 이해 작업을 완료하는 방법을 살펴봅니다. 이 방법은 단계별로 수행되어 프로세스 전체에서 명확성과 정밀도를 보장합니다. 작업의 일부로 에이전트는 응답 내에서 문서 인용을 제공합니다.
스트리밍은 에이전트의 응답을 전달하는 데 사용됩니다. 그러면 작업이 진행됨에 따라 실시간 업데이트가 제공됩니다.
시작하기
기능 코딩을 계속하기 전에 개발 환경이 완전히 설정되고 구성되었는지 확인합니다.
명령줄에서 패키지 종속성을 추가하려면 다음 명령을 사용합니다 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에서 NuGet 패키지를 관리하는 경우 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>
Agent Framework 실험적이며 경고 억제가 필요합니다. 프로젝트 파일.csproj()의 속성으로 이 문제를 해결할 수 있습니다.
<PropertyGroup>
<NoWarn>$(NoWarn);CA2007;IDE1006;SKEXP0001;SKEXP0110;OPENAI001</NoWarn>
</PropertyGroup>
또한 Grimms-The-King-of-the-Golden-Mountain.txt에서 퍼블릭 도메인 콘텐츠를 Grimms-The-Water-of-Life.txt, Grimms-The-White-Snake.txt 및 LearnResources 복사하십시오. 프로젝트 폴더에 다음 파일을 추가하고 출력 디렉터리에 복사하도록 구성합니다.
<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>
먼저 스크립트(.py 파일) 및 샘플 리소스를 보관할 폴더를 만듭니다. 파일 맨 위에 다음의 가져오기를 추가하세요: .py.
import asyncio
import os
from semantic_kernel.agents import AssistantAgentThread, AzureAssistantAgent
from semantic_kernel.contents import StreamingAnnotationContent
또한 Grimms-The-King-of-the-Golden-Mountain.txt에서 퍼블릭 도메인 콘텐츠를 Grimms-The-Water-of-Life.txt, Grimms-The-White-Snake.txt 및 LearnResources 복사하십시오. 프로젝트 폴더에 이러한 파일을 추가합니다.
현재 Java에서 기능을 사용할 수 없습니다.
구성
이 샘플에서는 원격 서비스에 연결하기 위해 구성 설정이 필요합니다. OpenAI 또는 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" "https://lightspeed-team-shared-openai-eastus.openai.azure.com/"
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=""
팁
Azure Assistants에는 2024-05-01-preview 이상의 API 버전이 필요합니다. 새 기능이 도입되면 API 버전이 그에 따라 업데이트됩니다. 이 글을 쓰는 시점에서 최신 버전은 2025-01-01-preview입니다. 최신 up-to버전 관리 세부 정보는 Azure OpenAI API 미리 보기 수명 주기를 참조하세요.
구성되면 각 AI 서비스 클래스는 필요한 변수를 선택하고 인스턴스화 중에 사용합니다.
현재 Java에서 기능을 사용할 수 없습니다.
코딩
이 샘플의 코딩 프로세스는 다음과 같습니다.
- 설치 - 설정 및 플러그 인 초기화
-
에이전트 정의 - 템플릿 명령 및 플러그 인을 사용하여 _Chat_Completion
Agent만듭니다. - 채팅 루프 - 사용자/에이전트 상호 작용을 구동하는 루프를 작성합니다.
전체 예제 코드는 최종 섹션에 제공됩니다. 전체 구현은 해당 섹션을 참조하세요.
설정
OpenAIAssistantAgent만들기 전에 구성 설정을 사용할 수 있는지 확인하고 파일 리소스를 준비합니다.
이전 구성 섹션에서 참조된 클래스를 인스턴스화 Settings 합니다. 설정을 사용하여 AzureOpenAIClient 항목을 만들고, 이는 에이전트 정의뿐만 아니라 파일 업로드 및 VectorStore 생성에 사용됩니다.
Settings settings = new();
AzureOpenAIClient client = OpenAIAssistantAgent.CreateAzureOpenAIClient(new AzureCliCredential(), new Uri(settings.AzureOpenAI.Endpoint));
도우미 에이전트의 정적 메서드 create_client() 는 클라이언트를 만들고 원하는 구성에 따라 반환하는 작업을 처리합니다. Pydantic 설정은 먼저 환경 변수 또는 .env 파일에서 환경 변수를 로드하는 데 사용됩니다. 구성된 환경 변수보다 우선하는 api_key, api_version, deployment_name 또는 endpoint전달할 수 있습니다.
# Create the client using Azure OpenAI resources and configuration
client = AzureAssistantAgent.create_client()
현재 Java에서 기능을 사용할 수 없습니다.
이제 파일 검색 도구에 사용할 빈 _Vector 스토어를 만듭니다.
AzureOpenAIClient를 이용하여 VectorStoreClient에 액세스하고 VectorStore를 만듭니다.
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
)
현재 Java에서 기능을 사용할 수 없습니다.
이전 구성 섹션에서 설명한 세 가지 콘텐츠 파일을 선언해 보겠습니다.
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",
]
현재 Java에서 기능을 사용할 수 없습니다.
이제 이전에 만든 클라이언트를 사용하여 해당 파일을 업로드하고, 각 파일을 VectorStoreClient에 추가하여 결과 OpenAIFileClient를 유지합니다.
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);
}
현재 Java에서 기능을 사용할 수 없습니다.
에이전트 정의
이제 OpenAIAssistantAgent을 생성할 준비가 되었습니다. 에이전트는 대상 모델, 지침 및 파일 검색 도구를 사용하도록 설정하여 구성됩니다. 또한 벡터 저장소를 파일 검색 도구와 명시적으로 연결합니다.
다음을 AzureOpenAIClient 만드는 과정의 일부로 다시 활용하겠습니다.OpenAIAssistantAgent
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,
)
현재 Java에서 기능을 사용할 수 없습니다.
채팅 루프
마침내 사용자와 Agent간의 상호 작용을 조정할 수 있습니다. 먼저 대화 상태를 유지하는 AgentThread를 만들고 빈 루프를 만듭니다.
또한 불필요한 요금을 최소화하기 위해 실행이 끝날 때 리소스가 제거되는지 확인해 보겠습니다.
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)
현재 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;
}
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
현재 Java에서 기능을 사용할 수 없습니다.
Agent 응답을 호출하기 전에 도우미 메서드를 추가하여 유니코드 주석 대괄호를 ANSI 대괄호로 다시 포맷해 보겠습니다.
private static string ReplaceUnicodeBrackets(this string content) =>
content?.Replace('【', '[').Replace('】', ']');
# No special handling required.
현재 Java에서 기능을 사용할 수 없습니다.
사용자 입력에 Agent 대한 응답을 생성하려면 메시지 및 에이전트 스레드를 지정하여 에이전트를 호출합니다. 이 예제에서는 스트리밍된 응답을 선택하고 응답 주기가 끝날 때 표시할 관련 인용 주석을 캡처합니다 . 스트리밍된 각 청크는 이전 도우미 메서드를 사용하여 다시 포맷됩니다.
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})"
)
현재 Java에서 기능을 사용할 수 없습니다.
최종
모든 단계를 함께 가져오면 이 예제의 최종 코드가 있습니다. 전체 구현은 아래에 제공됩니다.
다음과 같은 제안된 입력을 사용해 보세요.
- 각 스토리의 단락 개수는 무엇인가요?
- 각 스토리의 주인공과 적대자를 식별하는 테이블을 만듭니다.
- 흰 뱀의 도덕은 무엇입니까?
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())
위에 표시된 것처럼 리포지토리에서 전체 코드찾을 수 있습니다.
현재 Java에서 기능을 사용할 수 없습니다.