Skip to content

Commit

Permalink
[CLEANUP]
Browse files Browse the repository at this point in the history
  • Loading branch information
Kye committed Apr 24, 2024
1 parent 01bfc71 commit 8f91a7d
Show file tree
Hide file tree
Showing 11 changed files with 822 additions and 40 deletions.
9 changes: 8 additions & 1 deletion example.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,14 @@
verbose=True,
stopping_token="<DONE>",
interactive=True,
state_save_file_type="json",
saved_state_path="transcript_generator.json",
)

# Run the Agent on a task
agent("Generate a transcript for a youtube video on what swarms are!")
# out = agent("Generate a transcript for a youtube video on what swarms are!")
check = agent.save_state(
"transcript_generator.json",
"Generate a transcript for a youtube video on what swarms are!",
)
print(check)
134 changes: 134 additions & 0 deletions playground/agents/complete_agent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
from swarms import Agent, Anthropic, tool, ChromaDB
import subprocess
from pydantic import BaseModel


# Initilaize the chromadb client
chromadb = ChromaDB(
metric="cosine",
output="results",
docs_folder="docs",
)


# Create a schema for the code revision tool
class CodeRevisionSchema(BaseModel):
code: str = None
revision: str = None


# iNitialize the schema
tool_schema = CodeRevisionSchema(
code="print('Hello, World!')",
revision="print('What is 2+2')",
)


# Model
llm = Anthropic(
temperature=0.1,
)


# Tools
@tool
def terminal(
code: str,
):
"""
Run code in the terminal.
Args:
code (str): The code to run in the terminal.
Returns:
str: The output of the code.
"""
out = subprocess.run(
code, shell=True, capture_output=True, text=True
).stdout
return str(out)


@tool
def browser(query: str):
"""
Search the query in the browser with the `browser` tool.
Args:
query (str): The query to search in the browser.
Returns:
str: The search results.
"""
import webbrowser

url = f"https://www.google.com/search?q={query}"
webbrowser.open(url)
return f"Searching for {query} in the browser."


@tool
def create_file(file_path: str, content: str):
"""
Create a file using the file editor tool.
Args:
file_path (str): The path to the file.
content (str): The content to write to the file.
Returns:
str: The result of the file creation operation.
"""
with open(file_path, "w") as file:
file.write(content)
return f"File {file_path} created successfully."


@tool
def file_editor(file_path: str, mode: str, content: str):
"""
Edit a file using the file editor tool.
Args:
file_path (str): The path to the file.
mode (str): The mode to open the file in.
content (str): The content to write to the file.
Returns:
str: The result of the file editing operation.
"""
with open(file_path, mode) as file:
file.write(content)
return f"File {file_path} edited successfully."


# Agent
agent = Agent(
agent_name="Devin",
system_prompt=(
"Autonomous agent that can interact with humans and other"
" agents. Be Helpful and Kind. Use the tools provided to"
" assist the user. Return all code in markdown format."
),
llm=llm,
max_loops="auto",
autosave=True,
dashboard=False,
streaming_on=True,
verbose=True,
stopping_token="<DONE>",
interactive=True,
tools=[terminal, browser, file_editor, create_file],
long_term_memory=chromadb,
output_type=tool_schema, # or dict, or str
metadata_output_type="json",
# List of schemas that the agent can handle
list_tool_schemas=[tool_schema],
function_calling_format_type="OpenAI",
function_calling_type="json", # or soon yaml
)

# Run the agent
out = agent.run("Create a new file for a plan to take over the world.")
print(out)
File renamed without changes.
2 changes: 1 addition & 1 deletion swarms/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
)
from swarms.models.popular_llms import OctoAIChat
from swarms.models.qwen import QwenVLMultiModal # noqa: E402

from swarms.models.popular_llms import ReplicateChat as Replicate
from swarms.models.sampling_params import SamplingParams, SamplingType
from swarms.models.together import TogetherLLM # noqa: E402
from swarms.models.types import ( # noqa: E402
Expand Down
109 changes: 77 additions & 32 deletions swarms/structs/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@
multi_pydantic_to_functions,
)
from swarms.structs.schemas import Step, ManySteps
from swarms.telemetry.user_utils import get_user_device_data
from swarms.structs.yaml_model import YamlModel


# Utils
Expand Down Expand Up @@ -228,6 +230,7 @@ def __init__(
function_calling_format_type: Optional[str] = "OpenAI",
list_tool_schemas: Optional[List[BaseModel]] = None,
metadata_output_type: str = "json",
state_save_file_type: str = "json",
*args,
**kwargs,
):
Expand Down Expand Up @@ -295,6 +298,7 @@ def __init__(
self.function_calling_format_type = function_calling_format_type
self.list_tool_schemas = list_tool_schemas
self.metadata_output_type = metadata_output_type
self.state_save_file_type = state_save_file_type

# The max_loops will be set dynamically if the dynamic_loop
if self.dynamic_loops:
Expand Down Expand Up @@ -903,7 +907,7 @@ def run(

if self.autosave:
logger.info("Autosaving agent state.")
self.save_state(self.saved_state_path)
self.save_state(self.saved_state_path, task)

# Apply the cleaner function to the response
if self.output_cleaner is not None:
Expand Down Expand Up @@ -1131,7 +1135,7 @@ def step(self, task: str, **kwargs):
def graceful_shutdown(self):
"""Gracefully shutdown the system saving the state"""
print(colored("Shutting down the system...", "red"))
return self.save_state("flow_state.json")
return self.save_state(f"{self.agent_name}.json")

def run_with_timeout(self, task: str, timeout: int = 60) -> str:
"""Run the loop but stop if it takes longer than the timeout"""
Expand Down Expand Up @@ -1236,7 +1240,10 @@ def save_to_yaml(self, file_path: str) -> None:
except Exception as error:
print(colored(f"Error saving agent to YAML: {error}", "red"))

def save_state(self, file_path: str) -> None:
def get_llm_parameters(self):
return str(vars(self.llm))

def save_state(self, file_path: str, task: str = None) -> None:
"""
Saves the current state of the agent to a JSON file, including the llm parameters.
Expand All @@ -1247,58 +1254,96 @@ def save_state(self, file_path: str) -> None:
>>> agent.save_state('saved_flow.json')
"""
try:
logger.info(f"Saving agent state to: {file_path}")
logger.info(
f"Saving Agent {self.agent_name} state to: {file_path}"
)
state = {
"agent_id": str(self.id),
"agent_name": self.agent_name,
"agent_description": self.agent_description,
"LLM": str(self.get_llm_parameters()),
"system_prompt": self.system_prompt,
"sop": self.sop,
"short_memory": (
self.short_memory.return_history_as_string()
),
"short_memory": self.short_memory.return_history_as_string(),
"loop_interval": self.loop_interval,
"retry_attempts": self.retry_attempts,
"retry_interval": self.retry_interval,
"interactive": self.interactive,
"dashboard": self.dashboard,
"dynamic_temperature": (self.dynamic_temperature_enabled),
"dynamic_temperature": self.dynamic_temperature_enabled,
"autosave": self.autosave,
"saved_state_path": self.saved_state_path,
"max_loops": self.max_loops,
"StepCache": self.step_cache,
"Task": task,
"Stopping Token": self.stopping_token,
"Dynamic Loops": self.dynamic_loops,
"tools": self.tools,
"sop": self.sop,
"sop_list": self.sop_list,
"context_length": self.context_length,
"user_name": self.user_name,
"self_healing_enabled": self.self_healing_enabled,
"code_interpreter": self.code_interpreter,
"multi_modal": self.multi_modal,
"pdf_path": self.pdf_path,
"list_of_pdf": self.list_of_pdf,
"tokenizer": self.tokenizer,
"long_term_memory": self.long_term_memory,
"preset_stopping_token": self.preset_stopping_token,
"traceback": self.traceback,
"traceback_handlers": self.traceback_handlers,
"streaming_on": self.streaming_on,
"docs": self.docs,
"docs_folder": self.docs_folder,
"verbose": self.verbose,
"parser": self.parser,
"best_of_n": self.best_of_n,
"callback": self.callback,
"metadata": self.metadata,
"callbacks": self.callbacks,
# "logger_handler": self.logger_handler,
"search_algorithm": self.search_algorithm,
"logs_to_filename": self.logs_to_filename,
"evaluator": self.evaluator,
"output_json": self.output_json,
"stopping_func": self.stopping_func,
"custom_loop_condition": self.custom_loop_condition,
"sentiment_threshold": self.sentiment_threshold,
"custom_exit_command": self.custom_exit_command,
"sentiment_analyzer": self.sentiment_analyzer,
"limit_tokens_from_string": self.limit_tokens_from_string,
# "custom_tools_prompt": self.custom_tools_prompt,
"tool_schema": self.tool_schema,
"output_type": self.output_type,
"function_calling_type": self.function_calling_type,
"output_cleaner": self.output_cleaner,
"function_calling_format_type": self.function_calling_format_type,
"list_tool_schemas": self.list_tool_schemas,
"metadata_output_type": self.metadata_output_type,
"user_meta_data": get_user_device_data(),
}

with open(file_path, "w") as f:
json.dump(state, f, indent=4)
# Save as JSON
if self.state_save_file_type == "json":
with open(file_path, "w") as f:
json.dump(state, f, indent=4)

# Save as YAML
elif self.state_save_file_type == "yaml":
out = YamlModel(input_dict=state).to_yaml()
with open(self.saved_state_path, "w") as f:
f.write(out)

# Log the saved state
saved = colored(f"Saved agent state to: {file_path}", "green")
print(saved)
except Exception as error:
print(colored(f"Error saving agent state: {error}", "red"))

def state_to_str(self):
def state_to_str(self, task: str):
"""Transform the JSON into a string"""
try:
state = {
"agent_id": str(self.id),
"agent_name": self.agent_name,
"agent_description": self.agent_description,
"system_prompt": self.system_prompt,
"sop": self.sop,
"short_memory": (
self.short_memory.return_history_as_string()
),
"loop_interval": self.loop_interval,
"retry_attempts": self.retry_attempts,
"retry_interval": self.retry_interval,
"interactive": self.interactive,
"dashboard": self.dashboard,
"dynamic_temperature": (self.dynamic_temperature_enabled),
"autosave": self.autosave,
"saved_state_path": self.saved_state_path,
"max_loops": self.max_loops,
}
out = str(state)
out = self.save_state(self.saved_state_path, task)
return out
except Exception as error:
print(
Expand Down
10 changes: 8 additions & 2 deletions swarms/structs/yaml_model.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from pydantic import BaseModel
from pydantic import BaseModel, Field
import yaml
import json
from swarms.utils.loguru_logger import logger
Expand Down Expand Up @@ -120,11 +120,17 @@ class YamlModel(BaseModel):
>>> user.save_to_yaml('user.yaml')
"""

input_dict: Dict[str, Any] = Field(
None,
title="Data",
description="The data to be serialized to YAML.",
)

def to_yaml(self):
"""
Serialize the Pydantic model instance to a YAML string.
"""
return yaml.safe_dump(self.dict(), sort_keys=False)
return yaml.safe_dump(self.input_dict, sort_keys=False)

def from_yaml(self, cls, yaml_str: str):
"""
Expand Down
3 changes: 1 addition & 2 deletions swarms/telemetry/sys_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,11 +88,10 @@ def get_package_mismatches(file_path="pyproject.toml"):


def system_info():
swarms_verison = get_swarms_verison()
return {
"Python Version": get_python_version(),
"Pip Version": get_pip_version(),
"Swarms Version": swarms_verison,
# "Swarms Version": swarms_verison,
"OS Version and Architecture": get_os_version(),
"CPU Info": get_cpu_info(),
"RAM Info": get_ram_info(),
Expand Down
2 changes: 0 additions & 2 deletions swarms/telemetry/user_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import socket
import uuid

from swarms.telemetry.check_update import check_for_package
from swarms.telemetry.sys_info import system_info


Expand Down Expand Up @@ -83,6 +82,5 @@ def get_user_device_data():
"Machine ID": get_machine_id(),
"System Info": get_system_info(),
"UniqueID": generate_unique_identifier(),
"Swarms [Version]": check_for_package("swarms"),
}
return data
Loading

0 comments on commit 8f91a7d

Please sign in to comment.