Add initial implementation of Prefect flows and random message generator

This commit is contained in:
2025-02-16 23:31:12 +01:00
parent 3359460aa8
commit 9848b6fa51
5 changed files with 151 additions and 0 deletions
+61
View File
@@ -0,0 +1,61 @@
import random
from prefect import flow, task, get_run_logger
from prefect.filesystems import LocalFileSystem
from pathlib import Path
@task
def generar_mensaje_random():
lista_mensajes = ["Hola", "Adios", "Buenos días", "Buenas noches"]
return random.choice(lista_mensajes)
@flow
def otro_flow():
return (324 * 2 + 1) / 2
@flow
def my_flow():
otro_flow()
mensaje1 = generar_mensaje_random()
mensaje2 = generar_mensaje_random()
mensaje3 = generar_mensaje_random()
logger = get_run_logger()
logger.info(f"Mensaje 1: {mensaje1}")
logger.info(f"Mensaje 2: {mensaje2}")
logger.info(f"Mensaje 3: {mensaje3}")
# Configura el almacenamiento local
local_storage = LocalFileSystem(basepath="E:\Proyects\Workers_data\prueba_prefect")
# Codigo para usar con Git
# # Configura y despliega el flujo
# if __name__ == "__main__":
# my_flow.from_source(
# source="http://localhost:3123/egutierrez/prefect_automatizations.git",
# entrypoint="ejemplo_automatizacion_prefect.py:my_flow"
# ).deploy(
# name="Deployment_ejemplo",
# work_pool_name="Workers_pc_torre_Lucas",
# cron="*/1 * * * *"
# )
# Codigo para usar con almacenamiento local
# Configura y despliega el flujo
if __name__ == "__main__":
my_flow.from_source(
source=str(Path(__file__).parent), # code stored in local directory
entrypoint="E:\Proyects\Workers_data\prueba_prefect\primera_prueba.py:my_flow",
).deploy(
name="Deployment_ejemplo",
work_pool_name="Worker_lucas"
)
+3
View File
@@ -0,0 +1,3 @@
from primera_prueba import otro_flow
otro_flow()
+1
View File
@@ -0,0 +1 @@
OPENAI_API=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
+86
View File
@@ -0,0 +1,86 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"ename": "ValueError",
"evalue": "Error en la API: 401, {\n \"error\": {\n \"message\": \"Your request to GET /v1/dashboard/billing/subscription must be made with a session key (that is, it can only be made from the browser). You made it with the following key type: .\",\n \"type\": \"invalid_request_error\",\n \"param\": null,\n \"code\": null\n }\n}\n",
"output_type": "error",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)",
"Cell \u001b[1;32mIn[3], line 40\u001b[0m\n\u001b[0;32m 36\u001b[0m saldo_restante \u001b[38;5;241m=\u001b[39m total_grant \u001b[38;5;241m-\u001b[39m total_usage\n\u001b[0;32m 37\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m saldo_restante\n\u001b[1;32m---> 40\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[43mget_saldo_restante_api\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m)\n",
"Cell \u001b[1;32mIn[3], line 17\u001b[0m, in \u001b[0;36mget_saldo_restante_api\u001b[1;34m()\u001b[0m\n\u001b[0;32m 15\u001b[0m response \u001b[38;5;241m=\u001b[39m requests\u001b[38;5;241m.\u001b[39mget(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;132;01m{\u001b[39;00mBASE_URL\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m/subscription\u001b[39m\u001b[38;5;124m\"\u001b[39m, headers\u001b[38;5;241m=\u001b[39mheaders)\n\u001b[0;32m 16\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m response\u001b[38;5;241m.\u001b[39mstatus_code \u001b[38;5;241m!=\u001b[39m \u001b[38;5;241m200\u001b[39m:\n\u001b[1;32m---> 17\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mValueError\u001b[39;00m(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mError en la API: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mresponse\u001b[38;5;241m.\u001b[39mstatus_code\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m, \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mresponse\u001b[38;5;241m.\u001b[39mtext\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m 19\u001b[0m data \u001b[38;5;241m=\u001b[39m response\u001b[38;5;241m.\u001b[39mjson()\n\u001b[0;32m 20\u001b[0m total_grant \u001b[38;5;241m=\u001b[39m data\u001b[38;5;241m.\u001b[39mget(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mhard_limit_usd\u001b[39m\u001b[38;5;124m\"\u001b[39m, \u001b[38;5;241m0\u001b[39m) \u001b[38;5;66;03m# Límite total en USD\u001b[39;00m\n",
"\u001b[1;31mValueError\u001b[0m: Error en la API: 401, {\n \"error\": {\n \"message\": \"Your request to GET /v1/dashboard/billing/subscription must be made with a session key (that is, it can only be made from the browser). You made it with the following key type: .\",\n \"type\": \"invalid_request_error\",\n \"param\": null,\n \"code\": null\n }\n}\n"
]
}
],
"source": [
"import requests\n",
"from dotenv import load_dotenv\n",
"import os\n",
"from datetime import datetime, timedelta\n",
"\n",
"\n",
"load_dotenv()\n",
"API_KEY = os.getenv(\"OPENAI_API\")\n",
"BASE_URL = \"https://api.openai.com/v1/dashboard/billing\"\n",
"\n",
"def get_saldo_restante_api():\n",
" headers = {\"Authorization\": f\"Bearer {API_KEY}\"}\n",
"\n",
" # Obtener información de la suscripción\n",
" response = requests.get(f\"{BASE_URL}/subscription\", headers=headers)\n",
" if response.status_code != 200:\n",
" raise ValueError(f\"Error en la API: {response.status_code}, {response.text}\")\n",
" \n",
" data = response.json()\n",
" total_grant = data.get(\"hard_limit_usd\", 0) # Límite total en USD\n",
"\n",
" # Obtener el consumo de los últimos 30 días\n",
" end_date = datetime.utcnow().strftime(\"%Y-%m-%d\")\n",
" start_date = (datetime.utcnow() - timedelta(days=30)).strftime(\"%Y-%m-%d\")\n",
"\n",
" usage_response = requests.get(\n",
" f\"{BASE_URL}/usage?start_date={start_date}&end_date={end_date}\",\n",
" headers=headers\n",
" )\n",
" if usage_response.status_code != 200:\n",
" raise ValueError(f\"Error en la API de uso: {usage_response.status_code}, {usage_response.text}\")\n",
"\n",
" usage_data = usage_response.json()\n",
" total_usage = usage_data.get(\"total_usage\", 0) / 100 # OpenAI da el uso en centavos\n",
"\n",
" saldo_restante = total_grant - total_usage\n",
" return saldo_restante\n",
"\n",
"\n",
"print(get_saldo_restante_api())"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "venv",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.13.1"
}
},
"nbformat": 4,
"nbformat_minor": 2
}