Skip to content

Commit

Permalink
Merge pull request #680 from kyegomez/668
Browse files Browse the repository at this point in the history
668
  • Loading branch information
kyegomez authored Dec 17, 2024
2 parents 95a7d59 + 8018760 commit 80dcab0
Show file tree
Hide file tree
Showing 63 changed files with 4,702 additions and 1,362 deletions.
2 changes: 0 additions & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@

# ==================================
# Use an official Python runtime as a parent image
FROM python:3.11-slim

Expand Down
4 changes: 0 additions & 4 deletions api/skypilot.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,3 @@ run: |
# LOG_LEVEL: "INFO"
# # MAX_WORKERS: "4"

# metadata:
# name: swarms-api-service
# version: "1.0.0"
# environment: production
112 changes: 112 additions & 0 deletions api/test_api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
import requests
import json
from time import sleep

BASE_URL = "http://api.swarms.ai:8000"


def make_request(method, endpoint, data=None):
"""Helper function to make requests with error handling"""
url = f"{BASE_URL}{endpoint}"
try:
if method == "GET":
response = requests.get(url)
elif method == "POST":
response = requests.post(url, json=data)
elif method == "DELETE":
response = requests.delete(url)

response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(
f"Error making {method} request to {endpoint}: {str(e)}"
)
if hasattr(e.response, "text"):
print(f"Response text: {e.response.text}")
return None


def create_agent():
"""Create a test agent"""
data = {
"agent_name": "test_agent",
"model_name": "gpt-4",
"system_prompt": "You are a helpful assistant",
"description": "Test agent",
"temperature": 0.7,
"max_loops": 1,
"tags": ["test"],
}
return make_request("POST", "/v1/agent", data)


def list_agents():
"""List all agents"""
return make_request("GET", "/v1/agents")


def test_completion(agent_id):
"""Test a completion with the agent"""
data = {
"prompt": "Say hello!",
"agent_id": agent_id,
"max_tokens": 100,
}
return make_request("POST", "/v1/agent/completions", data)


def get_agent_metrics(agent_id):
"""Get metrics for an agent"""
return make_request("GET", f"/v1/agent/{agent_id}/metrics")


def delete_agent(agent_id):
"""Delete an agent"""
return make_request("DELETE", f"/v1/agent/{agent_id}")


def run_tests():
print("Starting API tests...")

# Create an agent
print("\n1. Creating agent...")
agent_response = create_agent()
if not agent_response:
print("Failed to create agent")
return

agent_id = agent_response.get("agent_id")
print(f"Created agent with ID: {agent_id}")

# Give the server a moment to process
sleep(2)

# List agents
print("\n2. Listing agents...")
agents = list_agents()
print(f"Found {len(agents)} agents")

# Test completion
if agent_id:
print("\n3. Testing completion...")
completion = test_completion(agent_id)
if completion:
print(
f"Completion response: {completion.get('response')}"
)

print("\n4. Getting agent metrics...")
metrics = get_agent_metrics(agent_id)
if metrics:
print(f"Agent metrics: {json.dumps(metrics, indent=2)}")

# Clean up
# print("\n5. Cleaning up - deleting agent...")
# delete_result = delete_agent(agent_id)
# if delete_result:
# print("Successfully deleted agent")


if __name__ == "__main__":
run_tests()
10 changes: 5 additions & 5 deletions docs/mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -223,11 +223,11 @@ nav:
- BaseMultiModalModel: "swarms/models/base_multimodal_model.md"
- Multi Modal Models Available: "swarms/models/multimodal_models.md"
- GPT4VisionAPI: "swarms/models/gpt4v.md"
- Swarms Cloud API:
# - Overview: "swarms_cloud/main.md"
- Overview: "swarms_cloud/vision.md"
- Swarms Cloud CLI: "swarms_cloud/cli.md"
- Add Agents to Marketplace: "swarms_cloud/add_agent.md"
# - Swarms Cloud API:
# # - Overview: "swarms_cloud/main.md"
# - Overview: "swarms_cloud/vision.md"
# - Swarms Cloud CLI: "swarms_cloud/cli.md"
# # - Add Agents to Marketplace: "swarms_cloud/add_agent.md"
# - Available Models: "swarms_cloud/available_models.md"
# - Agent API: "swarms_cloud/agent_api.md"
# - Migrate from OpenAI to Swarms in 3 lines of code: "swarms_cloud/migrate_openai.md"
Expand Down
49 changes: 15 additions & 34 deletions example.py
Original file line number Diff line number Diff line change
@@ -1,50 +1,31 @@
import os

from dotenv import load_dotenv
from swarm_models import OpenAIChat

from swarms import Agent
from swarms.prompts.finance_agent_sys_prompt import (
FINANCIAL_AGENT_SYS_PROMPT,
)

load_dotenv()

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

# Create an instance of the OpenAIChat class
model = OpenAIChat(
openai_api_key=api_key, model_name="gpt-4o-mini", temperature=0.1
)

# Initialize the agent
agent = Agent(
agent_name="Financial-Analysis-Agent",
system_prompt=FINANCIAL_AGENT_SYS_PROMPT,
llm=model,
max_loops=1,
autosave=True,
dashboard=False,
verbose=True,
agent_description="Personal finance advisor agent",
system_prompt=FINANCIAL_AGENT_SYS_PROMPT
+ "Output the <DONE> token when you're done creating a portfolio of etfs, index, funds, and more for AI",
model_name="gpt-4o", # Use any model from litellm
max_loops="auto",
dynamic_temperature_enabled=True,
saved_state_path="finance_agent.json",
user_name="swarms_corp",
retry_attempts=1,
user_name="Kye",
retry_attempts=3,
streaming_on=True,
context_length=200000,
return_step_meta=True,
output_type="json", # "json", "dict", "csv" OR "string" soon "yaml" and
context_length=16000,
return_step_meta=False,
output_type="str", # "json", "dict", "csv" OR "string" "yaml" and
auto_generate_prompt=False, # Auto generate prompt for the agent based on name, description, and system prompt, task
artifacts_on=True,
artifacts_output_path="roth_ira_report",
artifacts_file_extension=".txt",
max_tokens=8000,
return_history=True,
max_tokens=16000, # max output tokens
interactive=True,
stopping_token="<DONE>",
execute_tool=True,
)


agent.run(
"How can I establish a ROTH IRA to buy stocks and get a tax break? What are the criteria. Create a report on this question.",
"Create a table of super high growth opportunities for AI. I have $40k to invest in ETFs, index funds, and more. Please create a table in markdown.",
all_cores=True,
)
101 changes: 75 additions & 26 deletions new_features_examples/auto_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,21 +12,31 @@ class DynamicParser:
@staticmethod
def extract_fields(model: Type[BaseModel]) -> Dict[str, Any]:
return {
field_name: (field.annotation, ... if field.is_required() else None)
field_name: (
field.annotation,
... if field.is_required() else None,
)
for field_name, field in model.model_fields.items()
}

@staticmethod
def create_partial_model(model: Type[BaseModel], data: Dict[str, Any]) -> Type[BaseModel]:
def create_partial_model(
model: Type[BaseModel], data: Dict[str, Any]
) -> Type[BaseModel]:
fields = {
field_name: (field.annotation, ... if field.is_required() else None)
field_name: (
field.annotation,
... if field.is_required() else None,
)
for field_name, field in model.model_fields.items()
if field_name in data
}
return create_model(f"Partial{model.__name__}", **fields)

@classmethod
def parse(cls, data: Union[str, Dict[str, Any]], model: Type[BaseModel]) -> Optional[BaseModel]:
def parse(
cls, data: Union[str, Dict[str, Any]], model: Type[BaseModel]
) -> Optional[BaseModel]:
if isinstance(data, str):
try:
data = json.loads(data)
Expand All @@ -47,25 +57,52 @@ def parse(cls, data: Union[str, Dict[str, Any]], model: Type[BaseModel]) -> Opti

load_dotenv()


# Define the Thoughts schema
class Thoughts(BaseModel):
text: str = Field(..., description="Current thoughts or observations regarding the task.")
reasoning: str = Field(..., description="Logical reasoning behind the thought process.")
plan: str = Field(..., description="A short bulleted list that conveys the immediate and long-term plan.")
criticism: str = Field(..., description="Constructive self-criticism to improve future responses.")
speak: str = Field(..., description="A concise summary of thoughts intended for the user.")
text: str = Field(
...,
description="Current thoughts or observations regarding the task.",
)
reasoning: str = Field(
...,
description="Logical reasoning behind the thought process.",
)
plan: str = Field(
...,
description="A short bulleted list that conveys the immediate and long-term plan.",
)
criticism: str = Field(
...,
description="Constructive self-criticism to improve future responses.",
)
speak: str = Field(
...,
description="A concise summary of thoughts intended for the user.",
)


# Define the Command schema
class Command(BaseModel):
name: str = Field(..., description="Command name to execute from the provided list of commands.")
args: Dict[str, Any] = Field(..., description="Arguments required to execute the command.")
name: str = Field(
...,
description="Command name to execute from the provided list of commands.",
)
args: Dict[str, Any] = Field(
..., description="Arguments required to execute the command."
)


# Define the AgentResponse schema
class AgentResponse(BaseModel):
thoughts: Thoughts = Field(..., description="The agent's current thoughts and reasoning.")
command: Command = Field(..., description="The command to execute along with its arguments.")


thoughts: Thoughts = Field(
..., description="The agent's current thoughts and reasoning."
)
command: Command = Field(
...,
description="The command to execute along with its arguments.",
)


# Define tool functions
def fluid_api_command(task: str):
Expand All @@ -90,17 +127,26 @@ def do_nothing_command():
def task_complete_command(reason: str):
"""Mark the task as complete and provide a reason."""
print(f"Task completed: {reason}")
return {"status": "success", "message": f"Task completed: {reason}"}
return {
"status": "success",
"message": f"Task completed: {reason}",
}


# Dynamic command execution
def execute_command(name: str, args: Dict[str, Any]):
"""Dynamically execute a command based on its name and arguments."""
command_map: Dict[str, Callable] = {
"fluid_api": lambda **kwargs: fluid_api_command(task=kwargs.get("task")),
"send_tweet": lambda **kwargs: send_tweet_command(text=kwargs.get("text")),
"fluid_api": lambda **kwargs: fluid_api_command(
task=kwargs.get("task")
),
"send_tweet": lambda **kwargs: send_tweet_command(
text=kwargs.get("text")
),
"do_nothing": lambda **kwargs: do_nothing_command(),
"task_complete": lambda **kwargs: task_complete_command(reason=kwargs.get("reason")),
"task_complete": lambda **kwargs: task_complete_command(
reason=kwargs.get("reason")
),
}

if name not in command_map:
Expand All @@ -110,23 +156,26 @@ def execute_command(name: str, args: Dict[str, Any]):
return command_map[name](**args)


def parse_and_execute_command(response: Union[str, Dict[str, Any]], base_model: Type[BaseModel] = AgentResponse) -> Any:
def parse_and_execute_command(
response: Union[str, Dict[str, Any]],
base_model: Type[BaseModel] = AgentResponse,
) -> Any:
"""Enhanced command parser with flexible input handling"""
parsed = DynamicParser.parse(response, base_model)
if not parsed:
raise ValueError("Failed to parse response")
if hasattr(parsed, 'command'):

if hasattr(parsed, "command"):
command_name = parsed.command.name
command_args = parsed.command.args
return execute_command(command_name, command_args)

return parsed


ainame = "AutoAgent"
userprovided = "assistant"

SYSTEM_PROMPT = f"""
You are {ainame}, an advanced and autonomous {userprovided}.
Your role is to make decisions and complete tasks independently without seeking user assistance. Leverage your strengths as an LLM to solve tasks efficiently, adhering strictly to the commands and resources provided.
Expand Down Expand Up @@ -174,7 +223,7 @@ def parse_and_execute_command(response: Union[str, Dict[str, Any]], base_model:
temperature=0.9,
base_model=AgentResponse, # Pass the Pydantic schema as the base model
parallel_tool_calls=False,
openai_api_key=os.getenv("OPENAI_API_KEY")
openai_api_key=os.getenv("OPENAI_API_KEY"),
)

# Example usage
Expand Down
Loading

0 comments on commit 80dcab0

Please sign in to comment.