pull/58/head
Kye 1 year ago
parent faa1ed10f1
commit 84cf977b54

@ -12,4 +12,4 @@ from swarms.agents.omni_modal_agent import OmniModalAgent
#utils #utils
from swarms.agents.message import Message from swarms.agents.message import Message
from swarms.agents.stream_response import stream from swarms.agents.stream_response import stream
from swarms.agents.base import AbstractAgent # from swarms.agents.base import AbstractAgent

@ -2,6 +2,8 @@ import logging
import os import os
import time import time
import openai
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -17,7 +19,7 @@ class OpenAI:
if api_key == "" or api_key is None: if api_key == "" or api_key is None:
api_key = os.environ.get("OPENAI_API_KEY", "") api_key = os.environ.get("OPENAI_API_KEY", "")
if api_key != "": if api_key != "":
llm.api_key = api_key openai.api_key = api_key
else: else:
raise Exception("Please provide OpenAI API key") raise Exception("Please provide OpenAI API key")
@ -25,7 +27,7 @@ class OpenAI:
api_base = os.environ.get("OPENAI_API_BASE", "") # if not set, use the default base path of "https://api.openai.com/v1" api_base = os.environ.get("OPENAI_API_BASE", "") # if not set, use the default base path of "https://api.openai.com/v1"
if api_base != "": if api_base != "":
# e.g. https://api.openai.com/v1/ or your custom url # e.g. https://api.openai.com/v1/ or your custom url
llm.api_base = api_base openai.api_base = api_base
print(f'Using custom api_base {api_base}') print(f'Using custom api_base {api_base}')
if api_model == "" or api_model is None: if api_model == "" or api_model is None:
@ -57,14 +59,14 @@ class OpenAI:
"content": prompt "content": prompt
} }
] ]
response = llm.ChatCompletion.create( response = openai.ChatCompletion.create(
model=self.api_model, model=self.api_model,
messages=messages, messages=messages,
max_tokens=max_tokens, max_tokens=max_tokens,
temperature=temperature, temperature=temperature,
) )
else: else:
response = llm.Completion.create( response = openai.Completion.create(
engine=self.api_model, engine=self.api_model,
prompt=prompt, prompt=prompt,
n=k, n=k,
@ -75,7 +77,7 @@ class OpenAI:
with open("openai.logs", 'a') as log_file: with open("openai.logs", 'a') as log_file:
log_file.write("\n" + "-----------" + '\n' +"Prompt : "+ prompt+"\n") log_file.write("\n" + "-----------" + '\n' +"Prompt : "+ prompt+"\n")
return response return response
except llm.error.RateLimitError as e: except openai.error.RateLimitError as e:
sleep_duratoin = os.environ.get("OPENAI_RATE_TIMEOUT", 30) sleep_duratoin = os.environ.get("OPENAI_RATE_TIMEOUT", 30)
print(f'{str(e)}, sleep for {sleep_duratoin}s, set it by env OPENAI_RATE_TIMEOUT') print(f'{str(e)}, sleep for {sleep_duratoin}s, set it by env OPENAI_RATE_TIMEOUT')
time.sleep(sleep_duratoin) time.sleep(sleep_duratoin)
@ -110,9 +112,9 @@ class OpenAI:
rejected_solutions=None rejected_solutions=None
): ):
if (type(state) == str): if (type(state) == str):
pass state_text = state
else: else:
'\n'.join(state) state_text = '\n'.join(state)
print("New state generating thought:", state, "\n\n") print("New state generating thought:", state, "\n\n")
prompt = f""" prompt = f"""
Accomplish the task below by decomposing it as many very explicit subtasks as possible, be very explicit and thorough denoted by Accomplish the task below by decomposing it as many very explicit subtasks as possible, be very explicit and thorough denoted by
@ -150,8 +152,7 @@ class OpenAI:
while taking rejected solutions into account and learning from them. while taking rejected solutions into account and learning from them.
Considering the reasoning provided:\n\n Considering the reasoning provided:\n\n
###'{state_text}'\n\n### ###'{state_text}'\n\n###
Devise the best possible solution for the task: {initial_prompt}, Devise the best possible solution for the task: {initial_prompt}, Here are evaluated solutions that were rejected:
Here are evaluated solutions that were rejected:
###{rejected_solutions}###, ###{rejected_solutions}###,
complete the {initial_prompt} without making the same mistakes you did with the evaluated rejected solutions. Be simple. Be direct. Provide intuitive solutions as soon as you think of them.""" complete the {initial_prompt} without making the same mistakes you did with the evaluated rejected solutions. Be simple. Be direct. Provide intuitive solutions as soon as you think of them."""
answer = self.generate_text(prompt, 1) answer = self.generate_text(prompt, 1)
@ -192,7 +193,6 @@ class OpenAI:
else: else:
raise ValueError("Invalid evaluation strategy. Choose 'value' or 'vote'.") raise ValueError("Invalid evaluation strategy. Choose 'value' or 'vote'.")
class AoTAgent: class AoTAgent:
def __init__( def __init__(
self, self,

@ -2,13 +2,13 @@ import sys
from dataclasses import dataclass from dataclasses import dataclass
from typing import Dict, List, Optional, Union from typing import Dict, List, Optional, Union
from swarms.agents.base import AbstractAgent from swarms.workers.worker import Worker
@dataclass @dataclass
class GroupChat: class GroupChat:
"""A group chat with multiple participants with a list of agents and a max number of rounds""" """A group chat with multiple participants with a list of agents and a max number of rounds"""
agents: List[AbstractAgent] agents: List[Worker]
messages: List[Dict] messages: List[Dict]
max_rounds: int = 10 max_rounds: int = 10
admin_name: str = "Admin" #admin agent admin_name: str = "Admin" #admin agent
@ -21,11 +21,11 @@ class GroupChat:
def reset(self): def reset(self):
self.messages.clear() self.messages.clear()
def agent_by_name(self, name: str) -> AbstractAgent: def agent_by_name(self, name: str) -> Worker:
"""Find the next speaker baed on the message""" """Find the next speaker baed on the message"""
return self.agents[self.agent_names.index(name)] return self.agents[self.agent_names.index(name)]
def next_agent(self, agent: AbstractAgent) -> AbstractAgent: def next_agent(self, agent: Worker) -> Worker:
"""Returns the next agent in the list""" """Returns the next agent in the list"""
return self.agents[ return self.agents[
(self.agents_names.index(agent.ai_name) + 1) % len(self.agents) (self.agents_names.index(agent.ai_name) + 1) % len(self.agents)
@ -44,8 +44,8 @@ class GroupChat:
def select_speaker( def select_speaker(
self, self,
last_speaker: AbstractAgent, last_speaker: Worker,
selector: AbstractAgent, selector: Worker,
): ):
"""Selects the next speaker""" """Selects the next speaker"""
selector.update_system_message(self.select_speaker_msg()) selector.update_system_message(self.select_speaker_msg())
@ -72,7 +72,7 @@ class GroupChat:
class GroupChatManager(AbstractAgent): class GroupChatManager(Worker):
def __init__( def __init__(
self, self,
groupchat: GroupChat, groupchat: GroupChat,
@ -91,7 +91,7 @@ class GroupChatManager(AbstractAgent):
**kwargs **kwargs
) )
self.register_reply( self.register_reply(
AbstractAgent, Worker,
GroupChatManager.run_chat, GroupChatManager.run_chat,
config=groupchat, config=groupchat,
reset_config=GroupChat.reset reset_config=GroupChat.reset
@ -100,7 +100,7 @@ class GroupChatManager(AbstractAgent):
def run( def run(
self, self,
messages: Optional[List[Dict]] = None, messages: Optional[List[Dict]] = None,
sender: Optional[AbstractAgent] = None, sender: Optional[Worker] = None,
config: Optional[GroupChat] = None, config: Optional[GroupChat] = None,
) -> Union[str, Dict, None]: ) -> Union[str, Dict, None]:
#run #run

Loading…
Cancel
Save