jgravelle / AutoGroq

AutoGroq is a groundbreaking tool that revolutionizes the way users interact with Autogen™ and other AI assistants. By dynamically generating tailored teams of AI agents based on your project requirements, AutoGroq eliminates the need for manual configuration and allows you to tackle any question, problem, or project with ease and efficiency.

Home Page:https://autogroq.streamlit.app/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Error parsing JSON: Invalid \escape: line 2 column 8 (char 9)

jsarsoun opened this issue · comments

{
"expert_name": "Data Analysis Expert",
"description": "This expert should be able to analyze the results of the operation and present them in a clear and concise manner.",
"skills": ["data_analysis"],
"tools": []
}
Error parsing JSON: Invalid \escape: line 2 column 8 (char 9)
Content: {
"expert_name": "Math Expert",
"description": "The primary role of this expert is to provide a thorough understanding of basic arithmetic operations and their application in real-world scenarios.",
"skills": ["calculate_area"],
"tools": []
},

User-specific configurations

LLM_PROVIDER = "lmstudio"
GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions"
LMSTUDIO_API_URL = "http://localhost:1234/v1/chat/completions"
OLLAMA_API_URL = "http://127.0.0.1:11434/api/generate"
OPENAI_API_KEY = "your_openai_api_key"
OPENAI_API_URL = "https://api.openai.com/v1/chat/completions"

Here is the debug output as it's shown in pycharms terminal

Getting agents from text...
Response received. Status Code: 200
Request successful. Parsing response...
Response Data: {
"choices": [
{
"message": {
"content": "[\n{\n"expert\_name": "Project Manager",\n"description": "A skilled leader with experience in managing projects and ensuring that tasks are completed on time and within budget.",\n"skills": ["p
roject management", "task completion"],\n"tools": []\n},\n{\n"expert\_name": "Math Expert",\n"description": "An individual with a strong background in mathematics, particularly in basic arithmetic operations such
as addition. They should be able to provide a clear and concise answer to the question 'What is the result of adding 1 to 1?'",\n"skills": ["basic arithmetic", "math"],\n"tools": []\n},\n{\n"expert\_name": "Comm
unication Specialist",\n"description": "A person skilled in effectively conveying complex information in a simple and understandable manner. They will be responsible for ensuring that the final answer is presented in a way that is easy to understand for the intended audience.",\n"skills": ["communication", "information presentation"],\n"tools": []\n}\n]"
}
}
]
}

Here's what it looks like when you try to put it into json format

[
{
"expert_name": "Project Manager",
"description": "A skilled leader with experience in managing projects and ensuring that tasks are completed on time and within budget.",
"skills": ["p
roject management", "task completion"],
"tools": []
},
{
"expert_name": "Math Expert",
"description": "An individual with a strong background in mathematics, particularly in basic arithmetic operations such
as addition. They should be able to provide a clear and concise answer to the question 'What is the result of adding 1 to 1?'",
"skills": ["basic arithmetic", "math"],
"tools": []
},
{
"expert_name": "Comm
unication Specialist",
"description": "A person skilled in effectively conveying complex information in a simple and understandable manner. They will be responsible for ensuring that the final answer is presented in a way that is easy to understand for the intended audience.",
"skills": ["communication", "information presentation"],
"tools": []
}
]

Swap out the code for the function below. If it works, let me know and I'll push it...

def get_agents_from_text(text, api_url, max_retries=MAX_RETRIES, retry_delay=RETRY_DELAY):
print("Getting agents from text...")
temperature_value = st.session_state.get('temperature', 0.5)
llm_request_data = {
"model": st.session_state.model,
"temperature": temperature_value,
"max_tokens": st.session_state.max_tokens,
"top_p": 1,
"stop": "TERMINATE",
"messages": [
{
"role": "system",
"content": get_agents_prompt()
},
{
"role": "user",
"content": text
}
]
}
api_key = get_api_key()
llm_provider = get_llm_provider(api_key=api_key)
retry_count = 0
while retry_count < max_retries:
try:
response = llm_provider.send_request(llm_request_data)
print(f"Response received. Status Code: {response.status_code}")
if response.status_code == 200:
print("Request successful. Parsing response...")
response_data = llm_provider.process_response(response)
print(f"Response Data: {json.dumps(response_data, indent=2)}")
if "choices" in response_data and response_data["choices"]:
content = response_data["choices"][0]["message"]["content"]
print(f"Content: {content}")

                # Preprocess the JSON string
                content = content.replace("\\n", "\n").replace('\\"', '"')

                try:
                    json_data = json.loads(content)
                    if isinstance(json_data, list):
                        autogen_agents = []
                        crewai_agents = []
                        for agent_data in json_data:
                            expert_name = agent_data.get('expert_name', '')
                            if not expert_name:
                                print("Missing agent name. Retrying...")
                                retry_count += 1
                                time.sleep(retry_delay)
                                continue
                            description = agent_data.get('description', '')
                            skills = agent_data.get('skills', [])
                            tools = agent_data.get('tools', [])
                            agent_skills = st.session_state.selected_skills
                            autogen_agent_data = {
                                "type": "assistant",
                                "config": {
                                    "name": expert_name,
                                    "llm_config": {
                                        "config_list": [
                                            {
                                                "user_id": "default",
                                                "timestamp": datetime.datetime.now().isoformat(),
                                                "model": st.session_state.model,
                                                "base_url": None,
                                                "api_type": None,
                                                "api_version": None,
                                                "description": "OpenAI model configuration"
                                            }
                                        ],
                                        "temperature": temperature_value,
                                        "cache_seed": 42,
                                        "timeout": 600,
                                        "max_tokens": MODEL_TOKEN_LIMITS.get(st.session_state.model, 4096),
                                        "extra_body": None
                                    },
                                    "human_input_mode": "NEVER",
                                    "max_consecutive_auto_reply": 8,
                                    "system_message": f"You are a helpful assistant that can act as {expert_name} who {description}."
                                },
                                "description": description,
                                "skills": agent_skills,
                                "tools": tools
                            }
                            crewai_agent_data = {
                                "name": expert_name,
                                "description": description,
                                "skills": agent_skills,
                                "tools": tools,
                                "verbose": True,
                                "allow_delegation": True
                            }
                            autogen_agents.append(autogen_agent_data)
                            crewai_agents.append(crewai_agent_data)
                        print(f"AutoGen Agents: {autogen_agents}")
                        print(f"CrewAI Agents: {crewai_agents}")
                        return autogen_agents, crewai_agents
                    else:
                        print("Invalid JSON format. Expected a list of agents.")
                        return [], []
                except json.JSONDecodeError as e:
                    print(f"Error parsing JSON: {e}")
                    print(f"Content: {content}")
                    json_data = extract_json_objects(content)
                    if json_data:
                        autogen_agents = []
                        crewai_agents = []
                        for agent_data in json_data:
                            expert_name = agent_data.get('expert_name', '')
                            if not expert_name:
                                print("Missing agent name. Retrying...")
                                retry_count += 1
                                time.sleep(retry_delay)
                                continue
                            description = agent_data.get('description', '')
                            skills = agent_data.get('skills', [])
                            tools = agent_data.get('tools', [])
                            agent_skills = st.session_state.selected_skills
                            autogen_agent_data = {
                                "type": "assistant",
                                "config": {
                                    "name": expert_name,
                                    "llm_config": {
                                        "config_list": [
                                            {
                                                "user_id": "default",
                                                "timestamp": datetime.datetime.now().isoformat(),
                                                "model": st.session_state.model,
                                                "base_url": None,
                                                "api_type": None,
                                                "api_version": None,
                                                "description": "OpenAI model configuration"
                                            }
                                        ],
                                        "temperature": temperature_value,
                                        "timeout": 600,
                                        "cache_seed": 42
                                    },
                                    "human_input_mode": "NEVER",
                                    "max_consecutive_auto_reply": 8,
                                    "system_message": f"You are a helpful assistant that can act as {expert_name} who {description}."
                                },
                                "description": description,
                                "skills": agent_skills,
                                "tools": tools
                            }
                            crewai_agent_data = {
                                "name": expert_name,
                                "description": description,
                                "skills": agent_skills,
                                "tools": tools,
                                "verbose": True,
                                "allow_delegation": True
                            }
                            autogen_agents.append(autogen_agent_data)
                            crewai_agents.append(crewai_agent_data)
                        print(f"AutoGen Agents: {autogen_agents}")
                        print(f"CrewAI Agents: {crewai_agents}")
                        return autogen_agents, crewai_agents
                    else:
                        print("Failed to extract JSON objects from content.")
                        return [], []
            else:
                print("No agents data found in response")
        else:
            print(f"API request failed with status code {response.status_code}: {response.text}")
    except Exception as e:
        print(f"Error making API request: {e}")
        retry_count += 1
        time.sleep(retry_delay)
print(f"Maximum retries ({max_retries}) exceeded. Failed to retrieve valid agent names.")
return [], []