Un assistente virtuale molto preparato con python
In questo breve articolo vediamo come si possono utilizzare l’API di OpenAI per creare con python un assistente virtuale che può cercare informazioni in un file specifico e rispondere alle domande dell’utente.
Per prima cosa è necessario che il modulo di openai sia installato.
Per farlo è sufficiente inviare la seguente istruzione mediante il prompt di Windows
pip install openai
nel momento in cui stiamo scrivendo questo articolo l’ultima versione è la 1.33.0 ed è quella compatibile con il codice python sottoindicato.
per installare questa versione è sufficiente inviare mediante il prompt di Windows l’istruzione:
pip install openai==1.33.0
Creiamo un file txt o pdf contenente le informazioni a cui il modello dovrà attingere per fornire le risposte.
Lo chiamiamo conoscenza.txt
Il codice python utile per creare e far funzionare l’assistente è il seguente:
from openai import OpenAI
from typing_extensions import override
from openai import AssistantEventHandler, OpenAI
# Configura l'API key di OpenAI
client = OpenAI(api_key = '<CHIAVE OPENAI>')
assistant = client.beta.assistants.create(
name="Assistant",
instructions="Tu sei un utile assistente che fornisce informazioni che trovi sul file indicato",
model="gpt-4o",
tools=[{"type": "file_search"}],
)
# Create a vector store caled assistente 1
vector_store = client.beta.vector_stores.create(name="assistente 1")
# Ready the files for upload to OpenAI
file_paths = ["conoscenza.txt"]
file_streams = [open(path, "rb") for path in file_paths]
# Use the upload and poll SDK helper to upload the files, add them to the vector store,
# and poll the status of the file batch for completion.
file_batch = client.beta.vector_stores.file_batches.upload_and_poll(
vector_store_id=vector_store.id, files=file_streams
)
# You can print the status and the file counts of the batch to see the result of this operation.
print(file_batch.status)
print(file_batch.file_counts)
assistant = client.beta.assistants.update(
assistant_id=assistant.id,
tool_resources={"file_search": {"vector_store_ids": [vector_store.id]}},
)
# Upload the user provided file to OpenAI
message_file = client.files.create(
file=open("conoscenza.txt", "rb"), purpose="assistants"
)
# Create a thread and attach the file to the message
thread = client.beta.threads.create(
messages=[
{
"role": "user",
"content": "Quali servizi include la versione business?",
# Attach the new file to the message.
"attachments": [
{ "file_id": message_file.id, "tools": [{"type": "file_search"}] }
],
}
]
)
# The thread now has a vector store with that file in its tool resources.
print(thread.tool_resources.file_search)
class EventHandler(AssistantEventHandler):
@override
def on_text_created(self, text) -> None:
print(f"\nassistant > ", end="", flush=True)
@override
def on_tool_call_created(self, tool_call):
print(f"\nassistant > {tool_call.type}\n", flush=True)
@override
def on_message_done(self, message) -> None:
# print a citation to the file searched
message_content = message.content[0].text
annotations = message_content.annotations
citations = []
for index, annotation in enumerate(annotations):
message_content.value = message_content.value.replace(
annotation.text, f"[{index}]"
)
if file_citation := getattr(annotation, "file_citation", None):
cited_file = client.files.retrieve(file_citation.file_id)
citations.append(f"[{index}] {cited_file.filename}")
print(message_content.value)
print("\n".join(citations))
# Then, we use the stream SDK helper
# with the EventHandler class to create the Run
# and stream the response.
with client.beta.threads.runs.stream(
thread_id=thread.id,
assistant_id=assistant.id,
instructions="Rivolgiti all'utente con l'espressione Caro cliente",
event_handler=EventHandler(),
) as stream:
stream.until_done()
Analisi del codice
