Skip to content

Instantly share code, notes, and snippets.

@mouredev
Created March 7, 2023 19:31
Show Gist options
  • Save mouredev/58abfbcef017efaf3852e8821564c011 to your computer and use it in GitHub Desktop.
Save mouredev/58abfbcef017efaf3852e8821564c011 to your computer and use it in GitHub Desktop.
Ejemplo de uso del API de ChatGPT desde Python
import openai # pip install openai
import typer # pip install "typer[all]"
from rich import print # pip install rich
from rich.table import Table
"""
Webs de interés:
- Módulo OpenAI: https://github.com/openai/openai-python
- Documentación API ChatGPT: https://platform.openai.com/docs/api-reference/chat
- Typer: https://typer.tiangolo.com
- Rich: https://rich.readthedocs.io/en/stable/
"""
def main():
openai.api_key = "TU_API_KEY creada en https://platform.openai.com"
print("💬 [bold green]ChatGPT API en Python[/bold green]")
table = Table("Comando", "Descripción")
table.add_row("exit", "Salir de la aplicación")
table.add_row("new", "Crear una nueva conversación")
print(table)
# Contexto del asistente
context = {"role": "system",
"content": "Eres un asistente muy útil."}
messages = [context]
while True:
content = __prompt()
if content == "new":
print("🆕 Nueva conversación creada")
messages = [context]
content = __prompt()
messages.append({"role": "user", "content": content})
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo", messages=messages)
response_content = response.choices[0].message.content
messages.append({"role": "assistant", "content": response_content})
print(f"[bold green]> [/bold green] [green]{response_content}[/green]")
def __prompt() -> str:
prompt = typer.prompt("\n¿Sobre qué quieres hablar? ")
if prompt == "exit":
exit = typer.confirm("✋ ¿Estás seguro?")
if exit:
print("👋 ¡Hasta luego!")
raise typer.Abort()
return __prompt()
return prompt
if __name__ == "__main__":
typer.run(main)
@AlfredAndreOs
Copy link

Interesante

@JaimeVeraSobino
Copy link

funciono a la primera, gracias :)

@VikusS3
Copy link

VikusS3 commented Apr 18, 2023

Muy buena app

@oscar80-os
Copy link

Esta perfecto, es un muy buen programa para crearnos un asistente personalizado,

@anuzcan
Copy link

anuzcan commented Apr 21, 2023

Muchas Gracias por tu trabajo....

@jcdm60
Copy link

jcdm60 commented Apr 28, 2023

Gracias Brais!!!

@cainfoxy
Copy link

Genial Brais!!! Me ha gustado mucho. Sería genial que hicieras la continuación para hablarle y que nos responda a viva voz.

@EdwardTorresoficial
Copy link

De maravilla 🚀
Muchas gracias que gran aporte👑

@johnathanMorales
Copy link

¿Hola, estoy recibiendo esta respuesta desde el primer intento, saben qué tipo de suscripción debo tener o pagar?

You exceeded your current quota, please check your plan and billing details.

@ppsantiago
Copy link

You exceeded your current quota, please check your plan and billing details

Tu API no tiene saldo, bien se acabo la prueba gratis de 18usd o paso el tiempo para consumir ese credito.

@DiegoJimenez14
Copy link

10/10

@MuskingCl
Copy link

Use este código:
import openai

openai.api_key="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"

#Contexto del asistente
messages=[{"role":"system","content":"Eres un asistente muy util en el campo de las inversiones y negocios"}]

print("Estamos probando ChatGPT con Python")
while True:
content=input("Sobre que quieres saber?")
if content=="Terminamos":
break

messages.append({"role":"user","content":content})
response=openai.ChatCompletion.create(model="gpt-3.5-turbo",messages=messages)
response_content=response.choises[0].message.content
messages.append({"role":"assistant","content":response_content})
print(response_content)

Y me da estos errores:
Traceback (most recent call last):
File "e:\Proyecto Libros\Documentos Luis\Musking.clSpA\ProyectoMuskingSAT\Proyecto SATKING\PythonyChatGPT\main.py", line 16, in
response=openai.ChatCompletion.create(model="gpt-3.5-turbo",messages=messages)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\dorsi\AppData\Local\Programs\Python\Python311\Lib\site-packages\openai\api_resources\chat_completion.py", line 25, in create
return super().create(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\dorsi\AppData\Local\Programs\Python\Python311\Lib\site-packages\openai\api_resources\abstract\engine_api_resource.py", line 153, in create
response, _, api_key = requestor.request(
^^^^^^^^^^^^^^^^^^
File "C:\Users\dorsi\AppData\Local\Programs\Python\Python311\Lib\site-packages\openai\api_requestor.py", line 298, in request
resp, got_stream = self._interpret_response(result, stream)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\dorsi\AppData\Local\Programs\Python\Python311\Lib\site-packages\openai\api_requestor.py", line 700, in _interpret_response
self._interpret_response_line(
File "C:\Users\dorsi\AppData\Local\Programs\Python\Python311\Lib\site-packages\openai\api_requestor.py", line 763, in _interpret_response_line
raise self.handle_error_response(
openai.error.RateLimitError: You exceeded your current quota, please check your plan and billing details.

me podrías ayudar a saber a que se debe??

@GeorgeOrca
Copy link

Me ha pasado exactamente igual.

@LUS24
Copy link

LUS24 commented Aug 3, 2023

@MuskingCl y @GeorgeOrca , en esta línea tienen la respuesta openai.error.RateLimitError: You exceeded your current quota, please check your plan and billing details..

Significa que para el API Key que están usando se alcanzó el límite de requests que pueden hacer.

Pueden esperar un poco hasta que se les asigne más requests o pasarse a un plan pago.

Copy link

ghost commented Nov 14, 2023

Buenas!
A mi después de realizar una pregunta me sale este error....

¿Sobre qué quieres hablar? : ¿Como puedo aprender Python?
Error in sys.excepthook:
Traceback (most recent call last):
File "C:\Users\Usuario\AppData\Local\Programs\Python\Python311\Lib\site-packages\typer\main.py", line 72, in except_hook
rich_tb = Traceback.from_exception(
^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Usuario\AppData\Local\Programs\Python\Python311\Lib\site-packages\rich\traceback.py", line 335, in from_exception
rich_traceback = cls.extract(
^^^^^^^^^^^^
File "C:\Users\Usuario\AppData\Local\Programs\Python\Python311\Lib\site-packages\rich\traceback.py", line 449, in extract
locals={
^
File "C:\Users\Usuario\AppData\Local\Programs\Python\Python311\Lib\site-packages\rich\traceback.py", line 450, in
key: pretty.traverse(
^^^^^^^^^^^^^^^^
File "C:\Users\Usuario\AppData\Local\Programs\Python\Python311\Lib\site-packages\rich\pretty.py", line 853, in traverse
node = _traverse(_object, root=True)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Usuario\AppData\Local\Programs\Python\Python311\Lib\site-packages\rich\pretty.py", line 745, in _traverse
is_dataclass(obj)
File "C:\Users\Usuario\AppData\Local\Programs\Python\Python311\Lib\dataclasses.py", line 1259, in is_dataclass
cls = obj if isinstance(obj, type) else type(obj)
^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Usuario\AppData\Local\Programs\Python\Python311\Lib\site-packages\openai_utils_proxy.py", line 39, in class
return self.get_proxied().class
^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Usuario\AppData\Local\Programs\Python\Python311\Lib\site-packages\openai_utils_proxy.py", line 43, in get_proxied
return self.load()
^^^^^^^^^^^^^^^
File "C:\Users\Usuario\AppData\Local\Programs\Python\Python311\Lib\site-packages\openai\lib_old_api.py", line 33, in load
raise APIRemovedInV1(symbol=self._symbol)
openai.lib._old_api.APIRemovedInV1:

You tried to access openai.ChatCompletion, but this is no longer supported in openai>=1.0.0 - see the README at https://github.com/openai/openai-python for the API.

You can run openai migrate to automatically upgrade your codebase to use the 1.0.0 interface.

Alternatively, you can pin your installation to the old version, e.g. pip install openai==0.28

A detailed migration guide is available here: openai/openai-python#742

Original exception was:
Traceback (most recent call last):
File "c:\Users\Usuario\Desktop\curso python mouredev\chatgpt_api.py", line 68, in
typer.run(main)
File "C:\Users\Usuario\AppData\Local\Programs\Python\Python311\Lib\site-packages\typer\main.py", line 1056, in run
app()
File "C:\Users\Usuario\AppData\Local\Programs\Python\Python311\Lib\site-packages\typer\main.py", line 328, in call
raise e
File "C:\Users\Usuario\AppData\Local\Programs\Python\Python311\Lib\site-packages\typer\main.py", line 311, in call
return get_command(self)(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Usuario\AppData\Local\Programs\Python\Python311\Lib\site-packages\click\core.py", line 1157, in call
return self.main(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Usuario\AppData\Local\Programs\Python\Python311\Lib\site-packages\typer\core.py", line 716, in main
return _main(
^^^^^^
File "C:\Users\Usuario\AppData\Local\Programs\Python\Python311\Lib\site-packages\typer\core.py", line 216, in _main
rv = self.invoke(ctx)
^^^^^^^^^^^^^^^^
File "C:\Users\Usuario\AppData\Local\Programs\Python\Python311\Lib\site-packages\click\core.py", line 1434, in invoke
return ctx.invoke(self.callback, **ctx.params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Usuario\AppData\Local\Programs\Python\Python311\Lib\site-packages\click\core.py", line 783, in invoke
return __callback(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Usuario\AppData\Local\Programs\Python\Python311\Lib\site-packages\typer\main.py", line 683, in wrapper
return callback(**use_params) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\Usuario\Desktop\curso python mouredev\chatgpt_api.py", line 43, in main
response = openai.ChatCompletion.create(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Usuario\AppData\Local\Programs\Python\Python311\Lib\site-packages\openai_utils_proxy.py", line 22, in getattr
return getattr(self.get_proxied(), attr)
^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Usuario\AppData\Local\Programs\Python\Python311\Lib\site-packages\openai_utils_proxy.py", line 43, in get_proxied
return self.load()
^^^^^^^^^^^^^^^
File "C:\Users\Usuario\AppData\Local\Programs\Python\Python311\Lib\site-packages\openai\lib_old_api.py", line 33, in load
raise APIRemovedInV1(symbol=self._symbol)
openai.lib._old_api.APIRemovedInV1:

You tried to access openai.ChatCompletion, but this is no longer supported in openai>=1.0.0 - see the README at https://github.com/openai/openai-python for the API.

You can run openai migrate to automatically upgrade your codebase to use the 1.0.0 interface.

Alternatively, you can pin your installation to the old version, e.g. pip install openai==0.28

A detailed migration guide is available here: openai/openai-python#742

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment