generated from kyegomez/Python-Package-Template
-
-
Notifications
You must be signed in to change notification settings - Fork 13
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[PAYMENT COLLECTION SYSTEM] [FUNCTION API WRAPPER SYSTEM][+++]
- Loading branch information
Kye
committed
Dec 8, 2023
1 parent
35a3734
commit 6071d99
Showing
18 changed files
with
935 additions
and
71 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. | ||
[32mINFO[0m: Started server process [[36m46156[0m] | ||
[32mINFO[0m: Waiting for application startup. | ||
[32mINFO[0m: Application startup complete. | ||
[32mINFO[0m: Uvicorn running on [1mhttp://0.0.0.0:8000[0m (Press CTRL+C to quit) | ||
[32mINFO[0m: Shutting down | ||
[32mINFO[0m: Waiting for application shutdown. | ||
[32mINFO[0m: Application shutdown complete. | ||
[32mINFO[0m: Finished server process [[36m46156[0m] |
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,4 @@ | ||
swarms | ||
skypilot | ||
fastapi | ||
supabase |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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", | ||
] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Oops, something went wrong.