Skip to content

Commit

Permalink
[PAYMENT COLLECTION SYSTEM] [FUNCTION API WRAPPER SYSTEM][+++]
Browse files Browse the repository at this point in the history
  • Loading branch information
Kye committed Dec 8, 2023
1 parent 35a3734 commit 6071d99
Show file tree
Hide file tree
Showing 18 changed files with 935 additions and 71 deletions.
11 changes: 11 additions & 0 deletions errors.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,14 @@
DEBUG:jaxlib.mlir._mlir_libs:Initializing MLIR with module: _site_initialize_0
Initializing MLIR with module: _site_initialize_0
DEBUG:jaxlib.mlir._mlir_libs:Registering dialects from initializer <module 'jaxlib.mlir._mlir_libs._site_initialize_0' from '/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/jaxlib/mlir/_mlir_libs/_site_initialize_0.so'>
Registering dialects from initializer <module 'jaxlib.mlir._mlir_libs._site_initialize_0' from '/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/jaxlib/mlir/_mlir_libs/_site_initialize_0.so'>
DEBUG:jax._src.path:etils.epath was not found. Using pathlib for file I/O.
etils.epath was not found. Using pathlib for file I/O.
INFO: Started server process [46156]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
INFO: Shutting down
INFO: Waiting for application shutdown.
INFO: Application shutdown complete.
INFO: Finished server process [46156]
45 changes: 0 additions & 45 deletions example.py

This file was deleted.

18 changes: 1 addition & 17 deletions example_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,31 +6,15 @@
load_dotenv()


# Get the API key from the environment
api_key = os.getenv("OPENAI_API_KEY")

# Define the API endpoint
url = "http://localhost:8000/agent"

# Define the input parameters for the agent
agent_parameters = {
"temperature": 0.5,
"model_name": "gpt-4",
"openai_api_key": api_key,
"max_loops": 1,
"autosave": True,
"dashboard": True,
}

# Define the task for the agent
task = "Generate a 10,000 word blog on health and wellness."

# Define the payload for the POST request
payload = {
"task": task,
"parameters": agent_parameters,
"args": [], # Add your args here
"kwargs": {}, # Add your kwargs here
"msg": task,
}

# Send the POST request to the API
Expand Down
60 changes: 60 additions & 0 deletions func_api_example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import os

from dotenv import load_dotenv

# Import the OpenAIChat model and the Agent struct
from swarms.models import OpenAIChat
from swarms.structs import Agent

from swarms_cloud.func_api_wrapper import FuncAPIWrapper

# Load the environment variables
load_dotenv()

# Get the API key from the environment
api_key = os.environ.get("OPENAI_API_KEY")


# Initialize the API wrapper
api = FuncAPIWrapper(
host = "0.0.0.0",
port = 8000,
)


# Initialize the language model
llm = OpenAIChat(
temperature=0.5,
model_name="gpt-4",
openai_api_key=api_key,
)


## Initialize the workflow
agent = Agent(
llm=llm,
max_loops=1,
autosave=True,
dashboard=True,
)


@api.add("/agent")
def agent_method(task: str):
"""Agent method
Args:
task (str): Task to perform
Returns:
str: Response from the agent
"""
try:
out = agent.run(task=task)
return {"status": "success", "task": task, "response": out}
except Exception as error:
return {"status": "error", "task": task, "response": str(error)}


# Run the API
api.run()
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ python = "^3.9"
swarms = "*"
fastapi = "*"
skypilot = "*"

supabase = "*"


[tool.poetry.dev-dependencies]
Expand Down
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
swarms
skypilot
fastapi
supabase
8 changes: 8 additions & 0 deletions swarms_cloud/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from swarms_cloud.main import agent_api_wrapper
from swarms_cloud.rate_limiter import rate_limiter


__all__ = [
"agent_api_wrapper",
"rate_limiter",
]
52 changes: 52 additions & 0 deletions swarms_cloud/agent_types.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
from pydantic import BaseModel
from typing import Optional, List, Any, Callable


class AgentParameters(BaseModel):
"""Agent Parameters
Args:
BaseModel (_type_): _description_
"""

temperature: float = None
model_name: str = None
openai_api_key: str = None
id: str = None
llm: Any = None
template: Optional[str] = None
max_loops = 5
stopping_condition: Optional[Callable] = None
loop_interval: int = 1
retry_attempts: int = 3
retry_interval: int = 1
return_history: bool = False
stopping_token: str = None
dynamic_loops: Optional[bool] = False
interactive: bool = False
dashboard: bool = False
agent_name: str = "Autonomous-Agent-XYZ1B"
agent_description: str = None
system_prompt: str = None
tools: List[Any] = None
dynamic_temperature_enabled: Optional[bool] = False
sop: Optional[str] = None
sop_list: Optional[List[str]] = None
saved_state_path: Optional[str] = None
autosave: Optional[bool] = False
context_length: Optional[int] = 8192
user_name: str = "Human:"
self_healing_enabled: Optional[bool] = False
code_interpreter: Optional[bool] = False
multi_modal: Optional[bool] = None
pdf_path: Optional[str] = None
list_of_pdf: Optional[str] = None
tokenizer: Optional[Any] = None
memory: Optional[Any] = None
preset_stopping_token: Optional[bool] = False


class AgentInput(BaseModel):
task: str
img: str = None
parameters: AgentParameters
2 changes: 1 addition & 1 deletion swarms_cloud/api_key_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import string


def generate_api_key(prefix="sk-", length: int = 50):
def generate_api_key(prefix: str = "sk-", length: int = 50, *args, **kwargs):
"""Generate a random api key
Args:
Expand Down
126 changes: 126 additions & 0 deletions swarms_cloud/func_api_wrapper.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
import logging
from typing import Callable

import uvicorn
from fastapi import FastAPI, HTTPException

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)


# Function API Wrapper for functions: [FUNCTION]
def api_wrapper(
app: FastAPI,
path: str,
http_method: str = "post",
):
"""API Wrapper
Args:
app (FastAPI): _description_
path (str): _description_
http_method (str, optional): _description_. Defaults to "post".
Example:
>>> app = FastAPI()
>>> @api_wrapper(app, "/endpoint")
... def endpoint():
... return "Hello World"
>>> uvicorn.run(app, host="")
"""

def decorator(func: Callable):
try:

async def endpoint_wrapper(*args, **kwargs):
try:
# Call the func with provided args
logger.info(f"Calling method {func.__name__}")
result = func(*args, **kwargs)
return result
except Exception as error:
logger.error(f"Error in {func.__name__}: {error}")
raise HTTPException(status_code=500, detail=str(error))

# Register the endpoint
endpoint_func = getattr(app, http_method)
endpoint_func(path)(endpoint_wrapper)
return func
except Exception as error:
print(f"Error in {func.__name__}: {error}")

return decorator


# Function API Wrapper for functions: [CLASS]
class FuncAPIWrapper:
"""Functional API Wrapper
Args:
host (str, optional): Host to run the API on. Defaults to "
port (int, optional): Port to run the API on. Defaults to 8000.
Methods:
add: Add an endpoint to the API
run: Run the API
Example:
>>> api = FuncAPIWrapper()
>>> @api.add("/endpoint")
... def endpoint():
... return "Hello World"
>>> api.run()
"""

def __init__(self, host: str = "0.0.0.0", port: int = 8000, *args, **kwargs):
self.host = host
self.port = port
self.app = FastAPI()

def add(self, path: str, method: str = "post", *args, **kwargs):
"""Add an endpoint to the API
Args:
path (str): _description_
method (str, optional): _description_. Defaults to "post".
"""

def decorator(func: Callable):
try:

async def endpoint_wrapper(*args, **kwargs):
try:
logger.info(f"Calling method {func.__name__}")
result = func(*args, **kwargs)
return result
except Exception as error:
logger.error(f"Error in {func.__name__}: {error}")
raise HTTPException(status_code=500, detail=str(error))

# Register the endpoint with the hhttp methopd
endpoint_func = getattr(self.app, method.lower())
endpoint_func(path)(endpoint_wrapper)
return func
except Exception as error:
logger.info(f"Error in {func.__name__}: {error}")

return decorator

def run(self, *args, **kwargs):
"""Run the API
Args:
"""
uvicorn.run(self.app, host=self.host, port=self.port)

def __call__(self, *args, **kwargs):
"""Call the run method
Args:
"""
self.run(*args, **kwargs)
Loading

0 comments on commit 6071d99

Please sign in to comment.