-
-
Save mouredev/58abfbcef017efaf3852e8821564c011 to your computer and use it in GitHub Desktop.
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) |
funciono a la primera, gracias :)
Muy buena app
Esta perfecto, es un muy buen programa para crearnos un asistente personalizado,
Muchas Gracias por tu trabajo....
Gracias Brais!!!
Genial Brais!!! Me ha gustado mucho. Sería genial que hicieras la continuación para hablarle y que nos responda a viva voz.
De maravilla 🚀
Muchas gracias que gran aporte👑
¿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.
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.
10/10
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??
Me ha pasado exactamente igual.
@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.
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
Funciona perfecto!!!
Interesante