TLDR
En este artículo exploramos el nuevo modelo GPT-4-Turbo de OpenAI, utilizando su ventana de contexto de token aumentada de 128k para pasar un corpus de documentos completo para la recuperación de información. Este método tosco de fuerza bruta (solo posible con ventanas de contexto más grandes) es fácil de implementar y no requiere incrustaciones de documentos ni búsqueda semántica como se usa en la generación aumentada de recuperación (RAG). Aplicado a los informes de situaciones de desastres humanitarios publicados en la increíble plataforma ReliefWeb, comprimidos con Sparse Priming Representations (SPR), demostramos que GPT-4-Turbo es capaz de responder preguntas básicas sobre desastres recientes. Sin embargo, incluso con la reciente disminución en los costos de los tokens de OpenAI, este enfoque es prohibitivamente costoso y provocar que la vista previa del modelo GPT-4-Turbo sea muy lento, y a veces tarda hasta un minuto en responder. Al igual que con todos los patrones de recuperación de información de LLM, por supuesto, es fundamental implementar un marco de validación para garantizar que se controlen las alucinaciones y la omisión de información. Dicho esto, GPT-4-Turbo ofrece un gran paso adelante en capacidades, especialmente a medida que mejora el rendimiento y reducen los costos, lo que se suma al conjunto de herramientas LLM en rápida expansión.
Dado el ritmo frenético de los acontecimientos en los últimos meses con la publicación de autógeno, memgpt, Núcleo semánticoy GPT y GPT-4-Turbo de OpenAIPensé en escribir una serie de artículos que comparen algunas de las técnicas que ofrecen estas nuevas herramientas para la recuperación de información conversacional. Cada uno tiene sus propias ventajas y desventajas, y algunos presentan un posible cambio de paradigma en la forma en que utilizamos los modelos de lenguajes grandes (LLM). Es un momento bastante sorprendente, pero utilizar estas nuevas técnicas en aplicaciones del mundo real no siempre es tan fácil como a veces sugiere la exploración inicial.
OpenAI anuncio reciente en DevDay incluyó algunas características nuevas que potencialmente podrían cambiar el panorama de la IA generativa. Uno de ellos fue el lanzamiento (en vista previa) de GPT-4-Turbo con un límite de ventana de contexto (solicitud) aumentado de 128.000 tokens, en comparación con los 32.000 anteriores. Previamente claudio ai Ofreció el mayor límite de contexto comercial de 100.000 tokens, por lo que GPT-4-Turbo está un paso más allá. Además, OpenAI sostiene que su nuevo modelo es más competente en el seguimiento de instrucciones y será 3 veces más barato que GPT-4. Como líder en muchos puntos de referencia de LLM, cualquier avance de GPT-4 es importante.
Entonces, ¿por qué es tan importante aumentar los límites de tokens? Al solicitar un LLM, puede incluir conversaciones pasadas, por lo que un beneficio inmediato es que recuerda de qué estaba hablando antes si proporciona el historial de conversaciones en cada solicitud. Esto es útil para hacer referencia a hechos de conversaciones anteriores que podrían ser importantes en este momento. Una ventana de contexto más grande significa que también puede «precargar» el chat con información de respaldo, como contenido y datos del documento.
Pero hay un inconveniente.
Más tokens significan un mayor costo y un rendimiento más lento porque con la arquitectura del transformador, la memoria y los requisitos computacionales aumentan cuadráticamente (mucho más rápido que una simple línea recta). Además, hay algunas investigaciones que sugieren que las ventanas de contexto más largas degradan la precisión del LLM (Liu y otros, 2023).
Al momento de escribir este artículo, GPT-4-Turbo está solo en modo de vista previa, disponible como modelo ‘gpt-4–1106-preview’. Para llamarlo usaremos el paquete openai Python como este…
import openaiopenai.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
Exploraremos el límite de token aumentado de GPT-4-Turbo usándolo para analizar Informes de situación de desastres humanitarios en el increíble ReliefWeb plataforma. Estos informes (conocidos como ‘Sitreps’) son vitales para monitorear y reaccionar ante desastres humanitarios en todo el mundo. También proporcionan un corpus de datos de texto que se pueden comprimir (resumir) para que quepan en la ventana contextual de GPT-4-Turbo para nuestro análisis.
ReliefWeb tiene una API realmente genial para acceder al contenido, por lo que usaremos esto para extraer una lista de desastres e informes de situación…
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 tiktokendef 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
En las funciones anteriores, algunos puntos de interés…
- Si el contenido de ReliefWeb hace referencia a un PDF, extraemos el texto de ese
- Cualquier texto se traduce automáticamente al inglés mediante la API del Traductor de Google.
- Siempre capturamos fuentes para atribución.
- No nos hemos molestado con la paginación de respuestas API para este análisis rápido.
Así es como llamamos a la función para obtener informes de situaciones de desastre desde el 1 de noviembre de 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)
Los informes de situación se guardan en el sistema de archivos como archivos de texto…
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)
Podríamos simplemente solicitar a GPT-4-Turbo el texto sin formato de los informes de situación. Sin embargo, gran parte de ese texto es irrelevante, como palabras vacías, encabezados y pies de página, por lo que incluirlo todo superaría muy rápidamente incluso los límites de tokens aumentados de GPT-4-Turbo. En su lugar usaremos una técnica llamada Representaciones de cebado dispersas (SPR) comprimir documentos a sus datos clave, modificados un poco para intentar preservar la información cuantitativa.
Aquí está el mensaje del sistema que le proporcionaremos a GPT-4-Turbo para comprimir nuestros documentos…
# 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.
Esto resumirá un informe de estado en texto sin formato en algo como esto para un informe de situación titulado “Boletín de la Red Africana de Laboratorios de Polio (semana 1 a 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%).
Lo cual, por supuesto, es mucho menos texto que el documento original.
No recomendaría utilizar esta compresión sin análisis y comprobaciones importantes para controlar la omisión de información, pero para nuestras pruebas será suficiente.
Aquí está el código para comprimir informes…
# gpt4 turbo is 128k
chunk_size = 100000llm_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)
Notará que en lo anterior agregamos algunos metadatos sobre el informe más el resumen de SPR devuelto por GPT-4-Turbo. Luego, los informes comprimidos se guardan como archivos de texto.
También extraeremos una lista de alto nivel de desastres de ReliefWeb para usarla en el aviso de nuestro sistema, como ayuda para las solicitudes de información…
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')
Esto nos da una lista concisa…
Ahora tenemos una lista de desastres e informes de situación comprimidos, del 1 al 10 de noviembre, que enumeran los datos clave de esos desastres.
Combinémoslos en un archivo de texto para usarlo como parte del mensaje del sistema para 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"
¿Cuántas fichas y cuál es el 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, costtokens, cost = num_tokens_from_string(concatenated_content,"cl100k_base")
OpenAI Tokens: 82001 ($0.82001)
Entonces, dado el costo de $0.01 por cada 1000 tokens ingresados, el texto creado anteriormente cuesta $ 0,82 por mensaje. También hay un costo de token de finalización, $ 0,03 por 1000 tokens, pero esto debería ser mucho menor que el costo de entrada, ya que hay muchos menos tokens.
¡Ay!
Sabíamos que esta técnica de fuerza bruta no es la mejor manera de abordar nuestra tarea particular, pero el alto costo es otra razón.
Ahora que tenemos nuestro texto, podemos crear un mensaje del 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
Notará que el mensaje del sistema incluye instrucciones sobre qué secciones del texto concatenado usar para diferentes tipos de información. A través de una rápida experimentación (yo realmente no la llamaría «ingeniería») esto produjo mejores resultados.
Vale, aquí va…
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.
En conjunto, éste es un resumen bastante bueno del desastre. Los hechos concuerdan bien comparados con los Página de desastres de ReliefWeb (tenga en cuenta que esta página puede cambiar desde este artículo, a medida que evolucione el desastre) y el último informe de situación utilizado para este estudio.
Sin embargo, un hecho está ligeramente desalineado: los datos decían que trágicamente murieron 153 personas, mientras que el modelo arrojó 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.
Por lo tanto, es «conocido» pero alucinado en la primera indicación. Como ocurre con todas las aplicaciones de LLM, la validación y las comprobaciones son clave para detectar problemas como este.
Obtengamos información sobre las organizaciones que crean informes de situación (para el período del 1 al 10 de noviembre)…
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
En comparación con el misma consulta en ReliefWeb esto parece correcto.
Hagamos algunas preguntas más matizadas…
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.
Al mirar los informes de situación, tampoco pude encontrar esta información. Sin embargo, se requiere una verificación más detallada para establecer que esto es cierto.
Preguntémonos sobre las posibles enfermedades y los impactos en la salud…
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.
Mirando a la informe de unicef En los datos, incluso con nuestro resumen del SPF, lo anterior parece capturar los puntos principales. Sin embargo, solo tenemos el informe número 1 en los datos utilizados aquí, pero lo anterior menciona el informe número 2. Otra alucinación menor, que nuevamente ilustra que cualquier respuesta de LLM necesita una verificación automática.
Este es un análisis muy rápido para tener una idea de qué tan bien se desempeña GPT-4-Turbo, con su ventana de contexto aumentada de 128k y seguimiento de instrucciones mejorado, al incluir todos los datos de texto necesarios para la recuperación de información como un mensaje del sistema, sin ningún otro procesamiento. . ¿Es este enfoque de fuerza bruta la mejor técnica para nuestra tarea?
Probablemente no, al menos no todavía.
El rendimiento es una consideración seria. Las indicaciones tardaban 30 segundos o más, lo que no era bueno para una experiencia de usuario agradable.
El costo también es prohibitivo. Dado que se necesitan más tokens para proporcionar un corpus completo con cada mensaje, el costo aumenta: en este análisis, ¡$ 0,82 por cada mensaje! – por lo que otras técnicas, sin duda, serán más atractivas para muchas organizaciones, al menos mientras los costos de LLM sean elevados. Dicho esto, recuerdo el Costo de almacenamiento a lo largo de los años.y tal vez veamos la misma disminución para los LLM con el tiempo.
Alternativas como generar código para consultar datos, utilizar funciones registradas en el LLM y múltiples agentes para validar resultados pueden ofrecer opciones más económicas y precisas. También eliminarían la necesidad de comprimir documentos para ajustar el corpus a la ventana de contexto, evitando así la pérdida de información.
Dicho esto, pudimos demostrar que el aviso GPT-4-Turbo puede admitir la recuperación de información básica en un corpus de documentos comprimidos proporcionados en el aviso del sistema. Esto tiene algunos beneficios porque es muy sencillo de implementar: simplemente le entrega al LLM todas sus cosas y hace preguntas. A medida que la IA avance y los costos disminuyan, esta puede convertirse en una técnica muy común en el futuro.