TLDR

In questo articolo esploriamo il nuovissimo modello GPT-4-Turbo di OpenAI, utilizzando la sua finestra di contesto del token aumentata a 128k per passare un corpus di documenti completo per il recupero delle informazioni. Questo metodo di forza bruta, possibile solo con finestre di contesto più grandi, è semplice da implementare e non richiede incorporamenti di documenti e ricerca semantica come quelli utilizzati in Retrieval Augmented Generation (RAG). Applicato ai rapporti sulle situazioni dei disastri umanitari pubblicati sulla straordinaria piattaforma ReliefWeb – compressi utilizzando Sparse Priming Representations (SPR) – mostriamo che GPT-4-Turbo è in grado di rispondere a domande fondamentali sui recenti disastri. Tuttavia, anche con la recente diminuzione dei costi dei token di OpenAI, questo approccio è proibitivamente costoso e la richiesta dell’anteprima del modello GPT-4-Turbo è molto lenta, a volte impiegando fino a un minuto per rispondere. Come per tutti i modelli di recupero delle informazioni LLM, è ovviamente fondamentale implementare un quadro di validazione per garantire che le allucinazioni e l’omissione di informazioni siano controllate. Detto questo, GPT-4-Turbo offre un grande passo avanti in termini di capacità, soprattutto quando le prestazioni migliorano e i costi diminuiscono, aggiungendosi al kit di strumenti LLM in rapida espansione.

Il nuovo GPT-4-Turbo ha una finestra di contesto più ampia di 128k token. Immagine generata da GPT-4 + Dall-E-3.

Dato il ritmo frenetico degli sviluppi negli ultimi due mesi con il rilascio di autogeno, memgpt, Kernal semanticoE GPT di OpenAI e GPT-4-TurboHo pensato di scrivere una serie di articoli che mettono a confronto alcune delle tecniche offerte da questi nuovi strumenti per il recupero delle informazioni conversazionali. Ognuno ha i suoi vantaggi e svantaggi e alcuni presentano un potenziale cambiamento di paradigma nel modo in cui utilizziamo i Large Language Models (LLM). È un momento davvero sorprendente, ma utilizzare queste nuove tecniche in applicazioni del mondo reale non è sempre così facile come a volte suggerisce l’esplorazione iniziale.

OpenAI recente annuncio al DevDay includeva alcune nuove funzionalità che potrebbero potenzialmente cambiare il panorama dell’intelligenza artificiale generativa. Uno di questi è stata l’uscita (in anteprima) di GPT-4-Turbo con un limite della finestra di contesto (prompt) aumentato di 128.000 token, rispetto ai 32.000 precedenti. In precedenza Claudio AI offriva il limite di contesto commerciale più ampio di 100.000 token, quindi GPT-4-Turbo è un passo oltre. Inoltre, OpenAI sostiene che il loro nuovo modello è più abile nel seguire le istruzioni e sarà 3 volte più economico di GPT-4. Essendo leader in molti benchmark LLM, qualsiasi progresso di GPT-4 è importante.

Allora perché l’aumento dei limiti dei token è un grosso problema? Quando richiedi un LLM puoi includere le conversazioni passate, quindi un vantaggio immediato è che ricorda di cosa stavi parlando in precedenza se fornisci la cronologia delle conversazioni in ogni richiesta. Ciò è utile per fare riferimento a fatti nelle conversazioni precedenti che potrebbero essere importanti in questo momento. Una finestra di contesto più ampia significa che puoi anche “precaricare” la chat con informazioni di supporto, come contenuto e dati del documento.

Ma c’è un aspetto negativo.

Più token significano costi più elevati e prestazioni più lente perché con l’architettura del trasformatore la memoria e i requisiti computazionali aumentano quadraticamente (molto più velocemente di una semplice linea retta). Inoltre, alcune ricerche suggeriscono che finestre di contesto più lunghe riducono l’accuratezza LLM (Liu et al, 2023).

Al momento in cui scrivo, GPT-4-Turbo è solo in modalità anteprima, disponibile come modello “gpt-4–1106-preview”. Per chiamarlo utilizzeremo il pacchetto openai Python così…

import openai

openai.api_key = '<YOUR KEY GOES KEY>'

def run_llm(query, system_prompt, reference_content):

llm_query = {
"temperature": 1.0,
"max_tokens": 2000,
"top_p": 0.95,
"frequency_penalty": 0,
"presence_penalty": 0,
}

response = openai.ChatCompletion.create(
model=model,
messages=( {
"role":"system",
"content": system_prompt
},
{
"role":"user",
"content": query
}
),
temperature=llm_query('temperature'),
max_tokens=llm_query('max_tokens'),
top_p=llm_query('top_p'),
frequency_penalty=llm_query('frequency_penalty'),
presence_penalty=llm_query('presence_penalty'),
stop=None
)

answer = response('choices')(0)('message')('content')
return answer

Esploreremo il limite di token aumentato di GPT-4-Turbo utilizzandolo per analizzare Rapporti sulla situazione dei disastri umanitari sullo straordinario ReliefWeb piattaforma. Questi rapporti (noti come “Sitreps”) sono vitali per monitorare e reagire ai disastri umanitari in tutto il mondo. Forniscono inoltre un corpus testuale di dati che può essere compresso (riassunto) per adattarsi alla finestra di contesto di GPT-4-Turbo per la nostra analisi.

ReliefWeb ha un API davvero eccezionale per accedere ai contenuti, quindi lo useremo per estrarre un elenco di disastri e rapporti sulla situazione…

import requests  
import os
from bs4 import BeautifulSoup
import re
import pandas as pd
import PyPDF2
import traceback
import json
import ast
from langchain.text_splitter import RecursiveCharacterTextSplitter
import tiktoken

def auto_translate(text):
"""
This function automatically detects language and translates to english

Parameters:
text(str): The text to be translated

Returns:
text (str): Translated text if in another language, otherwise
input text
"""
try:
lang = translator.detect(text)
lang = lang.lang
print(f"Language detected: {lang}")
q = translator.translate(text, dest='en')
text = q.text
except Exception as e:
print("An exception occurred trying to translate")
return text

def get_safe_name(name):
"""
This function takes a string and returns a version of it that is
safe to use as a filename.

Parameters:
name (str): The string to be converted to a safe filename.

Returns:
name (str): The safe filename.
"""
name = str(name)
name = re.sub("(^0-9a-zA-Z)+", "_", name)
name = re.sub(r"_$","", name)
if len(name) == 0:
name = 'Unknown'
return name

def download_pdf(url, download_path):
"""
Function to download a PDF from a URL and save locally

Parameters:
url (str): Location of online PDF file
download_path (str): Folder where to save PDF

"""
response = requests.get(url)
with open(download_path, 'wb') as f:
f.write(response.content)

def save_text(content, file_path):
"""
Function to save text to local file

Parameters:
content (str): Text to save
file_path (str): Folder where to save
"""
with open(file_path, 'w') as file:
print(f'Saving {file_path}')
file.write(content)

def extract_text_from_pdf(pdf_path):
"""
Function to extract text from PDF file

Parameters:
pdf_path (str): Path to PDF file

Returns:
text (str): Text extracted from PDF file
"""
print(pdf_path)
pdf_reader = PyPDF2.PdfReader(pdf_path)
text = ''
for page_num in range(len(pdf_reader.pages)):
page_obj = pdf_reader.pages(page_num)
text += page_obj.extract_text()
return text

def get_rw_data(keyword, filter, sort, fields, endpoint, limit=10, \
save_body_to_text=False):
"""
Function to extract data from ReliefWeb API. For API details see:

https://apidoc.rwlabs.org/?utm_medium=blog&utm_source=reliefweb+website&utm_campaign=api+doc+launching+2016_06

Parameters:
keyword (str): Search string
filter (dict): ReliefWeb filter json
sort (dict): ReliefWeb sort json
fields (list): List of fields to return
endpoint (str): API Endpoint, eg reports, disasters
limit (int): Maximum records to return
save_body_to_text (bool) : Flag to save body to text file, including any PDFs on page

Returns:
all_data (pandas dataframe): Dataframe of data from API
"""
query = {
"appname": "myapp",
"query": {
"value": keyword
},
"filter":filter,
"sort": sort,
"limit": limit,
"fields": fields
}
endpoint = f"{reliefweb_api_url}/{endpoint}?appname=apidoc&query(value)="
print(f"Getting {endpoint} ...")

all_data =()
response = requests.post(endpoint, json=query)
if response.status_code == 200:
data = response.json()
for article in data("data"):
article_url = article('fields')('url')
try:
r = article('fields')
print(article_url)
article_response = requests.get(article_url)
if save_body_to_text:
soup = BeautifulSoup(article_response.text, 'html.parser')
main_content = (p.text for p in soup.find_all('p'))
article_text = ' '.join(main_content)
save_text(article_text, docs_folder + '/{}.txt'.format(get_safe_name(article('fields')('title'))))
for link in soup.find_all('a'):
href = link.get('href')
if href.endswith('.pdf'):
download_path = os.path.join(docs_folder, href.split('/')(-1))
if href.startswith('/attachments'):
pdf_url = f'{reliefweb_pdf_url}{href}'
else:
pdf_url = href
download_pdf(pdf_url, download_path)
print(f". Downloaded PDF {download_path} from {pdf_url}")
article_text = extract_text_from_pdf(download_path)
r('article_text') = article_text
r('reliefweb_query') = keyword
all_data.append(r)
except Exception as e:
print(f"An exception occurred trying to extract {article_url}")
tb_str = ''.join(traceback.format_exception(None, e, e.__traceback__))
print(tb_str)

all_data = pd.DataFrame(all_data)
for f in ('disaster','theme'):
if f in list(all_data.columns):
all_data(f) = all_data(f).astype(str)
return all_data
else:
print(f"Request failed with status {response.status_code} {response.text}")
return None

Nelle funzioni di cui sopra, alcuni punti di interesse…

  1. Se il contenuto di ReliefWeb fa riferimento a un PDF, estraiamo il testo da quello
  2. Qualsiasi testo viene tradotto automaticamente in inglese utilizzando l’API di Google Translate
  3. Catturiamo sempre le fonti per l’attribuzione
  4. Non ci siamo preoccupati dell’impaginazione delle risposte API per questa rapida analisi

Ecco come chiamiamo la funzione per ottenere rapporti sulla situazione dei disastri dal 1° novembre 2023…

filter = {
"operator": "AND",
"conditions": (
{
"field": "disaster.status",
"value": "ongoing"
},
{
"field": "format.name",
"value": "Situation Report"
},
{
"field": "date.created",
"value": {
"from": "2023-11-01T00:00:00+00:00",
"to": "2023-11-30T23:59:59+00:00"
}
}
)
}
sort = ("date.created:desc")
endpoint = "reports"
fields = {
"include": ("title", "body", "url", "source", "date", "format", "theme",
"country", "status", "primary_country", "disaster", "language", "id")
}
reliefweb_query = ""
articles = get_rw_data(reliefweb_query, filter, sort, fields, endpoint, 1000, True)

I rapporti sulla situazione vengono salvati nel file system come file di testo…

for index, row in articles.iterrows():
date = row('date')('created')
source = row('source')(0)('name')
title = row('title')
id = row('id')
filename = f'{get_safe_name(title)}__{id}_{get_safe_name(date)}.txt'

text = f'''
title: {title}
source: {source}
date: {date}
id: {id}

{row('article_text')}
'''
text = text.encode('utf-8','ignore').decode('utf-8','ignore')
print(text)

save_text(text, docs_folder + '/' + filename)

Potremmo semplicemente richiedere a GPT-4-Turbo il testo grezzo dei rapporti sulla situazione. Tuttavia, gran parte di quel testo è irrilevante, come parole di stop, intestazioni e piè di pagina, quindi includerlo tutto supererebbe molto rapidamente anche i limiti di token aumentati di GPT-4-Turbo. Utilizzeremo invece una tecnica chiamata Rappresentazioni di priming sparse (SPR) per comprimere i documenti nei loro fatti principali, leggermente modificati per cercare di preservare le informazioni quantitative.

Ecco la richiesta di sistema che forniremo a GPT-4-Turbo per comprimere i nostri documenti…

# MISSION
You are a Sparse Priming Representation (SPR) writer. An SPR is a
particular kind of use of language for advanced NLP, NLU, and NLG
tasks, particularly useful for the latest generation of Large Language
Models (LLMs). You will be given information by the USER which you
are to render as an SPR.

# THEORY
LLMs are a kind of deep neural network. They have been demonstrated
to embed knowledge, abilities, and concepts, ranging from reasoning
to planning, and even to theory of mind. These are called latent abilities and latent content, collectively referred to as latent space. The latent space of an LLM can be activated with the correct series of words as inputs, which will create a useful internal state of the neural network. This is not unlike how the right shorthand cues can prime a human mind to think in a certain way. Like human minds, LLMs are associative, meaning you only need to use the correct associations to "prime" another model to think in the same way. The exception are quantitative metrics, which you MUST preserve.

# METHODOLOGY
Render the input as a distilled list of succinct statements,
assertions, associations, concepts, analogies, and metaphors.
The idea is to capture as much, conceptually, as possible but with
as few words as possible while preserving all quantitative details.
Write it in a way that makes sense to you, as the future audience
will be another language model, not a human.

Questo riassumerà un rapporto sullo stato del testo grezzo in qualcosa di simile a questo per un rapporto sulla situazione intitolato “Bollettino della rete del laboratorio africano sulla polio (settimana 1–42, 2023)”…

- Information comes from World Health Organization. 
- Weekly dengue cases decreasing, 12,634 reported this week.
- 78 dengue-related deaths this week.
- Cumulative cases since January 2023: 267,680, including 1,333 deaths.
- Cases decreasing in all divisions except Sylhet.
- Increase in dengue cases in Faridpur, Khulna, Rajshahi, Rajbari districts.
- WHO orientation session for entomologists in Dhaka occurred on 26 October.
- Overall Case Fatality Rate (CFR) is 0.5%, but 0.62% for this week.
- Dhaka division reports highest number of cases and deaths.
- In this week, 13,430 people released from hospital after treatment.
- Male-to-female death ratio: 43% vs 57%.
- Most deaths among 16-55 years age group.
- Four dengue virus types circulating: DENV-1 (2.2%), DENV-2 (68.1%), DENV-3 (25.4%), DENV-4 (0.2%).
- Dengue prevention & clean-up week launched nationwide from 29 October to 4 November.
- WHO expert entomologist deployed to Bangladesh for technical support in outbreak response.
- In the Rohingya camps, weekly dengue cases continue to decline. Total cumulative cases are 12,969 including 17 deaths (CFR: 0.1%).

Che ovviamente è molto meno testo del documento originale.

Non consiglierei di utilizzare questa compressione senza analisi e controlli significativi per controllare l’omissione di informazioni, ma per i nostri test sarà sufficiente.

Ecco il codice per comprimere i report…

# gpt4 turbo is 128k 
chunk_size = 100000

llm_query = {
"prompt": "",
"temperature": 1.0,
"max_tokens": 2000,
"top_p": 0.95,
"frequency_penalty": 0,
"presence_penalty": 0,
"system_prompt":"""
# MISSION
You are a Sparse Priming Representation (SPR) writer. An SPR is a
particular kind of use of language for advanced NLP, NLU, and NLG
tasks, particularly useful for the latest generation of Large Language
Models (LLMs). You will be given information by the USER which you
are to render as an SPR.

# THEORY
LLMs are a kind of deep neural network. They have been demonstrated
to embed knowledge, abilities, and concepts, ranging from reasoning
to planning, and even to theory of mind. These are called latent abilities and latent content, collectively referred to as latent space. The latent space of an LLM can be activated with the correct series of words as inputs, which will create a useful internal state of the neural network. This is not unlike how the right shorthand cues can prime a human mind to think in a certain way. Like human minds, LLMs are associative, meaning you only need to use the correct associations to "prime" another model to think in the same way. The exception are quantitative metrics, which you MUST preserve.

# METHODOLOGY
Render the input as a distilled list of succinct statements,
assertions, associations, concepts, analogies, and metaphors.
The idea is to capture as much, conceptually, as possible but with
as few words as possible while preserving all quantitative details.
Write it in a way that makes sense to you, as the future audience
will be another language model, not a human.

"""
}

# Save texts
for index, row in articles.iterrows():
date = row('date')('created')
source = row('source')(0)('name')
report = row('title')
id = row('id')
text = row('article_text')
primary_country = row('primary_country')('name')
disaster = ''
disaster_types = ''
for d in ast.literal_eval(row('disaster')):
disaster += f"{d('name')}; "
for t in d('type'):
if 'primary' in t and t('primary') == True:
disaster_types += f"{t('name')}; "
d = {
"disaster": disaster,
"date": date,
"disaster_types": disaster_types
}
prefix = ""
filename = f'{get_safe_name(report)}__{id}_{get_safe_name(date)}.txt'
header = f'- report: "{report}"\n- disaster: "{disaster}"\n' + \
f'- disaster_types: "{disaster_types}"\n' + \
f'- primary_country: "{primary_country}"\n- source: "{source}"\n' + \
f'- date: "{date}"\n- id: "{id}"\n'

text_splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(
chunk_size=chunk_size, chunk_overlap=100
)
texts = text_splitter.split_text(text)
print(f"\n\n================ {report} =================\n")
print(primary_country)
print(disaster)
print(len(texts))

summarized_text = ''

for i, t in enumerate(texts):
response = openai.ChatCompletion.create(
model=model,
messages=( {
"role":"system",
"content":llm_query('system_prompt')
},
{
"role":"user",
"content":t
}
),
temperature=llm_query('temperature'),
max_tokens=llm_query('max_tokens'),
top_p=llm_query('top_p'),
frequency_penalty=llm_query('frequency_penalty'),
presence_penalty=llm_query('presence_penalty'),
stop=None)

summary = response('choices')(0)('message')('content')
summarized_text += "\n" + summary

summarized_text = auto_translate(summarized_text)
summarized_text = header + summarized_text

summarized_text = summarized_text.split("\n")
summarized_text_prefixed = ''
for s in summarized_text:
summarized_text_prefixed += f"{prefix}{s}\n"

print(summarized_text_prefixed)
save_text(summarized_text_prefixed, docs_folder2 + '/' + filename)

Noterai che sopra abbiamo aggiunto alcuni metadati sul rapporto oltre al riepilogo SPR restituito da GPT-4-Turbo. I report compressi vengono quindi salvati come file di testo.

Estrarremo anche un elenco di alto livello dei disastri da ReliefWeb da utilizzare nel prompt del nostro sistema, come aiuto per le richieste di informazioni…

filter = {
"operator": "AND",
"conditions": (
{
"field": "status",
"value": "ongoing"
},
{
"field": "date.event",
"value": {
"from": "2020-01-01T00:00:00+00:00",
"to": "2023-11-30T23:59:59+00:00"
}
}
)
}
sort = ("date.event:desc")
endpoint = "disasters"
fields = {
"include": ("name", "description", "date", "url", "id","status","glide")
}
reliefweb_query = ""
disasters = get_rw_data(reliefweb_query, filter, sort, fields, endpoint, 1000, False)
display(disasters)
disasters.to_csv('disasters.csv')

Questo ci fornisce un elenco conciso…

Elenco dei disastri estratti utilizzando l’endpoint disastri dell’API ReleiefWeb

Ora disponiamo di un elenco di disastri e di rapporti compressi sulla situazione, dal 1° al 10 novembre, che elencano i fatti principali di tali disastri.

Combiniamoli in un unico file di testo da utilizzare come parte del prompt di sistema per GPT-4-Turbo…

disasters = pd.read_csv('disasters.csv')
concatenated_content = "=========== this section gives a list of DISASTERS =========== \n\n "+ disasters.to_csv()
concatenated_content += "\n\n=========== this section provides disater REPORTS for each disaster =========== "
for f in os.listdir(docs_folder2):
with open(f"{docs_folder2}/{f}", "r") as file:
file_content = file.read()
concatenated_content += f"\n\n----- report: {f} ----- \n\n"
concatenated_content += file_content + "\n\n"

Quanti gettoni e qual è il costo?

def num_tokens_from_string(string: str, encoding_name: str) -> int:
encoding = tiktoken.get_encoding(encoding_name)
num_tokens = len(encoding.encode(string))
gpt4_token_cost_per_1000 = 0.01
cost = (num_tokens/1000.0)*gpt4_token_cost_per_1000
return num_tokens, cost

tokens, cost = num_tokens_from_string(concatenated_content,"cl100k_base")

OpenAI Tokens: 82001 ($0.82001)

Quindi, visto il costo di $ 0,01 per 1.000 token immessiil testo creato sopra esce a $ 0,82 al prompt. C’è anche un costo in token di completamento, $ 0,03 per 1000 token, ma dovrebbe essere molto inferiore al costo di input poiché ci sono molti meno token.

Ahia!

Sapevamo che questa tecnica di forza bruta non era il modo migliore per affrontare il nostro compito particolare, ma il costo elevato è un’altra ragione.

Ora che abbiamo il nostro testo, possiamo creare un prompt di sistema…

def run_llm(query, reference_content):

llm_query = {
"temperature": 1.0,
"max_tokens": 2000,
"top_p": 0.95,
"frequency_penalty": 0,
"presence_penalty": 0,
}

response = openai.ChatCompletion.create(
model=model,
messages=( {
"role":"system",
"content": f"""You are a ReliefWeb disasters bot. You
provide information on diasters.

If asked for a list of disasters, just provide the list
ONLY using the 'Disasters' section below.

If asked for details of a disaster, extract that information
from 'Situation Reports' section below.

{reference_content}"""
},
{
"role":"user",
"content": query
}
),
temperature=llm_query('temperature'),
max_tokens=llm_query('max_tokens'),
top_p=llm_query('top_p'),
frequency_penalty=llm_query('frequency_penalty'),
presence_penalty=llm_query('presence_penalty'),
stop=None
)

answer = response('choices')(0)('message')('content')
return answer

Noterai che il prompt del sistema include istruzioni su quali sezioni del testo concatenato utilizzare per diversi tipi di informazioni. Attraverso una rapida sperimentazione tempestiva – non la definirei davvero “ingegneria” – questo ha prodotto risultati migliori.

OK, ecco qui…

answer = run_llm("What's the latest status regaring ther Nepalese earthquake 
this year?", concatenated_content)
print(answer)
The latest status regarding the Nepal earthquake as of November 2023 is as 
follows:

- Earthquake: Western Nepal, 6.4 magnitude, occurred on 3 November 2023,
with an epicenter in Ramidanda, Jajarkot.

- Casualties: 154 deaths, 364+ injuries.

- Displacement: Approximately 250,000 people affected, with significant
numbers of homes damaged or destroyed.

- Infrastructure: Over 62,000 houses across 13 districts sustained
damage (26,557 fully, 35,455 partially). Several government buildings were also damaged.

- Humanitarian Response: The United Nations and other humanitarian
organizations have been active in relief efforts, providing medical tents, child-friendly spaces, WASH supplies, and psychosocial support, among other assistance.

- Recovery and Rehabilitation: The recovery and rehabilitation phase is
in planning, with international reinforcements arriving to aid in coordination and strategy development.

- Education and Health Services: Education has been disrupted for
about 80,000 children due to damaged schools, and health services
have been impacted, increasing the risk of malnutrition and complicating maternal and newborn care.

Please note that this is a condensed summary of the available data up until
10 November 2023, and further updates may follow as the situation evolves
and more assessments are made.

Nel complesso, questo è un buon riassunto del disastro. I fatti concordano bene rispetto al Pagina del disastro di ReliefWeb (nota che questa pagina potrebbe cambiare rispetto a questo articolo, man mano che il disastro si evolve) e il ultimo rapporto sulla situazione utilizzato per questo studio.

Un fatto però è leggermente disallineato: i dati dicono che morirono tragicamente 153 persone, mentre il modello ne riportò 154.

answer = run_llm("How many people died in the Nepal earthquake in 2023 occur?", 
concatenated_content)
print(answer)

In the Nepal Earthquake of November 2023, there were 153 fatalities.

Quindi è “conosciuto” ma ha allucinazioni nel primo suggerimento. Come per tutte le applicazioni LLM, la convalida e i controlli sono fondamentali per individuare problemi come questo.

Cerchiamo di ottenere alcune informazioni sulle organizzazioni che creano rapporti sulla situazione (per il periodo dal 1 al 10 novembre)…

answer = run_llm("List the organizations providing sitreps for the Nepal 
Earthquake", concatenated_content)
print(answer)

The organizations providing situation reports (sitreps) for the Nepal Earthquake include:

- UN Office for the Coordination of Humanitarian Affairs (OCHA)
- Nepal Red Cross Society
- International Federation of Red Cross And Red Crescent Societies (IFRC)
- UN Resident Coordinator in Nepal
- World Health Organization (WHO)
- UN Children's Fund (UNICEF)
- UN Country Team in Nepal

Rispetto al stessa query in ReliefWeb questo sembra corretto.

Facciamo alcune domande più sfumate…

answer = run_llm("How many displaced people are children?", 
concatenated_content)
print(answer)

In the provided data, there are references to children affected by disasters
in different reports, but the specific number of displaced children is not
directly mentioned in any of the excerpts. It would be necessary to review
more detailed reports or data sources that focus specifically on displacement
figures for children to determine the exact number affected by displacement.

Guardando i rapporti sulla situazione, non sono riuscito a trovare neanche questa informazione. Tuttavia, è necessario un controllo a posteriori più dettagliato per stabilire che ciò è vero.

Chiediamo informazioni sulle potenziali malattie e sugli impatti sulla salute…

answer = run_llm("What disease risks are there for the Nepal 2023 earthquake?", 
concatenated_content)
print(answer)

The disease risks for the Nepal 2023 earthquake, as reported by UNICEF in
their Humanitarian Situation Report No. 2, are primarily focused on
malnutrition, particularly among children under five years old, and
psychosocial stress affecting the affected population. The disruption of
healthcare and WASH (Water, Sanitation, and Hygiene) services due to
the earthquake has further exacerbated the health risks.

The key disease risks and health concerns include:

1. Malnutrition: The earthquake and its aftermath have disrupted the food
supply chain, which can lead to an increased risk of malnutrition among
vulnerable populations, especially children.

2. Maternal and Newborn Health: Pregnant women and newborns might face
increased health risks due to the disruption of health care services and
a lack of access to essential medical care and facilities.

3. Psychosocial Stress: The trauma caused by the earthquake, the loss of
loved ones, and the displacement can lead to significant psychosocial
stress and mental health issues.

4. Injuries and Physical Health: With many injured in the aftermath,
there is an increased need for medical treatment for physical injuries
and trauma care.

5. Communicable Diseases: Overcrowding in temporary shelters can lead
to the spread of communicable diseases, particularly in the absence of
proper sanitation and hygiene facilities.

6. Waterborne and Vector-borne Diseases: Lack of clean water and
sanitation increases the risk of waterborne diseases like diarrhea,
cholera, and dysentery. There is also a concern for vector-borne
diseases such as malaria and dengue fever.

7. Non-communicable Diseases: Disruption of routine health services
can affect the management and treatment of chronic non-communicable diseases.

8. Disruption of Routine Immunization: The potential disruption of
routine immunization services can increase the risk of vaccine-preventable
diseases.

In response to these health risks, UNICEF and other health sector partners
have been providing health services, medical supplies, and psychosocial
support, as well as ensuring continued access to nutrition for children
and mothers.

Guardando il Rapporto dell’UNICEF nei dati, anche con il nostro riepilogo SPF, quanto sopra sembra catturare i punti principali. Tuttavia, abbiamo solo il rapporto numero 1 nei dati utilizzati qui, ma quello sopra menziona il rapporto numero 2. Un’altra piccola allucinazione, che illustra ancora una volta che qualsiasi risposta LLM necessita di un controllo a ritroso automatico.

Questa è un’analisi molto rapida per avere un’idea delle prestazioni di GPT-4-Turbo, con la sua finestra di contesto aumentata a 128k e il miglioramento delle istruzioni, includendo tutti i dati di testo necessari per il recupero delle informazioni come prompt di sistema, senza alcuna altra elaborazione . Questo approccio basato sulla forza bruta è la tecnica migliore per il nostro compito?

Probabilmente no, almeno non ancora.

Le prestazioni sono una considerazione seria. Le istruzioni impiegavano 30 secondi o più, il che non era eccezionale per un’esperienza utente piacevole.

Anche il costo è proibitivo. Con più token necessari per fornire un corpus completo con ciascun prompt, i costi aumentano: in questa analisi $ 0,82 per ogni prompt! – quindi altre tecniche saranno senza dubbio più attraenti per molte organizzazioni, almeno mentre i costi LLM sono elevati. Detto questo, mi viene in mente il costo di stoccaggio nel corso degli annie forse nel tempo vedremo la stessa diminuzione per gli LLM.

Alternative come la generazione di codice per interrogare i dati, l’utilizzo di funzioni registrate con LLM e più agenti per la convalida dei risultati possono offrire opzioni più economiche e precise. Eliminerebbero inoltre la necessità di comprimere i documenti per adattare il corpus alla finestra di contesto, evitando così la perdita di informazioni.

Detto questo, siamo stati in grado di dimostrare che il prompt GPT-4-Turbo può supportare il recupero di informazioni di base su un corpus di documenti compressi forniti nel prompt del sistema. Ciò ha alcuni vantaggi nell’essere molto semplice da implementare: basta dare al LLM tutto il tuo materiale e porre domande. Con l’avanzare dell’intelligenza artificiale e la diminuzione dei costi, questa potrebbe diventare una tecnica molto comune in futuro.

Fonte: towardsdatascience.com

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *