I am trying to create a chatbot in openai which the answer is in a document with this code:
import PyPDF2
import openai
from openai import OpenAI
# Configura tu clave de OpenAI
openai.api_key = "tu_clave_openai"
def extraer_texto_pdf(ruta_pdf):
"""Extrae el texto de un archivo PDF."""
texto = ""
try:
with open(ruta_pdf, 'rb') as archivo:
lector = PyPDF2.PdfReader(archivo)
for pagina in lector.pages:
texto += pagina.extract_text()
except Exception as e:
print(f"Error al leer el PDF: {e}")
return texto
def generar_respuesta(contexto, pregunta):
"""Genera una respuesta basada en el contexto y la pregunta."""
try:
respuesta = openai.ChatCompletion.create(
model="gpt-4", # Puedes usar "gpt-3.5-turbo" si prefieres
messages=[
{"role": "system", "content": "Eres un asistente útil que responde basándote en un documento proporcionado."},
{"role": "user", "content": f"Contexto: {contexto}\n\nPregunta: {pregunta}"}
]
)
return respuesta['choices'][0]['message']['content'].strip()
except Exception as e:
return f"Error al generar respuesta: {e}"
def main():
# Ruta del archivo PDF
ruta_pdf = "C:\\openai_prueba" # Cambia esto por la ruta a tu archivo PDF
# Extraer texto del PDF
contexto = extraer_texto_pdf('Comercial2.pdf')
if not contexto:
print("No se pudo extraer texto del PDF. Verifica el archivo.")
return
print("El chatbot está listo para responder basándose en el documento.")
print("Escribe 'salir' para terminar el programa.")
while True:
pregunta = input("Haz una pregunta: ")
if pregunta.lower() == "salir":
print("¡Adiós!")
break
respuesta = generar_respuesta(contexto, pregunta)
print(f"Respuesta: {respuesta}\n")
if __name__ == "__main__":
main()
But when I execute the python file, this message error appear “‘ChatCompletion’ object is not subscriptable”, what do I have to do?
Install/upgrade the package: pip install --upgrade openai
Verify:
API key is valid/active
PDF file exists at specified path
PDF contains extractable text (not scanned images)
Use this code:
import PyPDF2
from openai import OpenAI
# Configura tu clave de OpenAI
client = OpenAI(api_key="tu_clave_openai")
def extraer_texto_pdf(ruta_pdf):
"""Extrae el texto de un archivo PDF."""
texto = ""
try:
with open(ruta_pdf, 'rb') as archivo:
lector = PyPDF2.PdfReader(archivo)
for pagina in lector.pages:
texto += pagina.extract_text()
except Exception as e:
print(f"Error al leer el PDF: {e}")
return texto
def generar_respuesta(contexto, pregunta):
"""Genera una respuesta basada en el contexto y la pregunta."""
try:
respuesta = client.chat.completions.create(
model="gpt-4",
messages=[
{"role": "system", "content": "Eres un asistente útil que responde basándote en un documento proporcionado."},
{"role": "user", "content": f"Contexto: {contexto}\n\nPregunta: {pregunta}"}
]
)
return respuesta.choices[0].message.content.strip()
except Exception as e:
return f"Error al generar respuesta: {e}"
def main():
# Ruta del archivo PDF
ruta_pdf = "Comercial2.pdf" # Asegúrate que esta ruta es correcta
# Extraer texto del PDF
contexto = extraer_texto_pdf(ruta_pdf)
if not contexto:
print("No se pudo extraer texto del PDF. Verifica el archivo.")
return
print("El chatbot está listo para responder basándose en el documento.")
print("Escribe 'salir' para terminar el programa.")
while True:
pregunta = input("Haz una pregunta: ")
if pregunta.lower() == "salir":
print("¡Adiós!")
break
respuesta = generar_respuesta(contexto, pregunta)
print(f"Respuesta: {respuesta}\n")
if __name__ == "__main__":
main()
Updated API instructions
"Hey! So here’s the deal – OpenAI updated their ‘recipe book’ (their library), and your code was using the old instructions. Here’s what we fixed:
The “Phone Setup”
Before: “Hey OpenAI, my password is XYZ!” (shouting to the whole room).
Now: You create a specific phone (client) with your password: client = OpenAI(api_key="your-key")
The “Ask GPT” Command
Before: “Hey OpenAI, make me a ChatCompletion sandwich!”
Now: You tell your specific phone: client.chat.completions.create(...)
(It’s like using a new app menu structure)
Unboxing the Response
Before: Opening a box with keys['choices'][0]['message']['content']
Now: It’s a matryoshka doll – you open layers with dots: .choices[0].message.content
(No more brackets – just dot-navigation!)
Bonus fixes:
Simplified the PDF path (no more messy C:\\ stuff)
Made sure we’re using the latest OpenAI library (like updating your apps)
Why it works now:
It’s like your code got upgraded from a flip phone to a smartphone – same basic idea, but with newer buttons and menus!
Since I can speak spanish as well I allowed myself to add some comments in Spanish. Hope that helps.
What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. We generally recommend altering this or top_p but not both.