Compare commits

...
4 Commits
Author SHA1 Message Date
Mervin Praison 94cf264b4c Merge pull request #266 from MervinPraison/develop
setting openai_model_name env variable to set
2025-01-06 09:52:09 +00:00
MervinPraison ab44fd4b27 setting openai_model_name env variable to set 2025-01-06 09:51:50 +00:00
Mervin Praison 7bad6cf7e9 Merge pull request #265 from MervinPraison/develop
adding mini agents
2025-01-06 09:31:54 +00:00
MervinPraison 4ffbe48c58 adding mini agents 2025-01-06 09:31:39 +00:00
18 changed files with 418 additions and 42 deletions

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
FROM python:3.11-slim
WORKDIR /app
COPY . .
RUN pip install flask praisonai==2.0.28 gunicorn markdown
RUN pip install flask praisonai==2.0.30 gunicorn markdown
EXPOSE 8080
CMD ["gunicorn", "-b", "0.0.0.0:8080", "api:app"]
View File
Whitespace-only changes.
+6
View File
@@ -0,0 +1,6 @@
from praisonaiagents import Agent, Agents, Tools
research_agent = Agent(instructions="You are a research agent to search internet about AI 2024", tools=[Tools.internet_search])
summarise_agent = Agent(instructions="You are a summarize agent to summarise in points")
agents = Agents(agents=[research_agent, summarise_agent])
agents.start()
+6
View File
@@ -5,6 +5,7 @@ Praison AI Agents - A package for hierarchical AI agent task execution
from .agent.agent import Agent
from .agents.agents import PraisonAIAgents
from .task.task import Task
from .tools.tools import Tools
from .main import (
TaskOutput,
ReflectionOutput,
@@ -21,9 +22,14 @@ from .main import (
async_display_callbacks,
)
# Add Agents as an alias for PraisonAIAgents
Agents = PraisonAIAgents
__all__ = [
'Agent',
'PraisonAIAgents',
'Agents',
'Tools',
'Task',
'TaskOutput',
'ReflectionOutput',
+52 -14
View File
@@ -3,7 +3,7 @@ import time
import json
import logging
import asyncio
from typing import List, Optional, Any, Dict, Union, Literal
from typing import List, Optional, Any, Dict, Union, Literal, TYPE_CHECKING
from rich.console import Console
from rich.live import Live
from openai import AsyncOpenAI
@@ -19,6 +19,9 @@ from ..main import (
error_logs
)
if TYPE_CHECKING:
from ..task.task import Task
class Agent:
def _generate_tool_definition(self, function_name):
"""
@@ -132,11 +135,12 @@ class Agent:
def __init__(
self,
name: str,
role: str,
goal: str,
backstory: str,
llm: Optional[Union[str, Any]] = "gpt-4o",
name: Optional[str] = None,
role: Optional[str] = None,
goal: Optional[str] = None,
backstory: Optional[str] = None,
instructions: Optional[str] = None,
llm: Optional[Union[str, Any]] = None,
tools: Optional[List[Any]] = None,
function_calling_llm: Optional[Any] = None,
max_iter: int = 20,
@@ -158,16 +162,35 @@ class Agent:
knowledge_sources: Optional[List[Any]] = None,
use_system_prompt: Optional[bool] = True,
markdown: bool = True,
self_reflect: bool = True,
self_reflect: Optional[bool] = None,
max_reflect: int = 3,
min_reflect: int = 1,
reflect_llm: Optional[str] = None
):
self.name = name
self.role = role
self.goal = goal
self.backstory = backstory
self.llm = llm
# Handle backward compatibility for required fields
if all(x is None for x in [name, role, goal, backstory, instructions]):
raise ValueError("At least one of name, role, goal, backstory, or instructions must be provided")
# If instructions are provided, use them to set role, goal, and backstory
if instructions:
self.name = name or "Agent"
self.role = role or "Assistant"
self.goal = goal or instructions
self.backstory = backstory or instructions
# Set self_reflect to False by default for instruction-based agents
self.self_reflect = False if self_reflect is None else self_reflect
else:
# Use provided values or defaults
self.name = name or "Agent"
self.role = role or "Assistant"
self.goal = goal or "Help the user with their tasks"
self.backstory = backstory or "I am an AI assistant"
# Default to True for traditional agents if not specified
self.self_reflect = True if self_reflect is None else self_reflect
self.instructions = instructions
# Check for model name in environment variable if not provided
self.llm = llm or os.getenv('OPENAI_MODEL_NAME', 'gpt-4o')
self.tools = tools if tools else [] # Store original tools
self.function_calling_llm = function_calling_llm
self.max_iter = max_iter
@@ -190,10 +213,10 @@ class Agent:
self.use_system_prompt = use_system_prompt
self.chat_history = []
self.markdown = markdown
self.self_reflect = self_reflect
self.max_reflect = max_reflect
self.min_reflect = min_reflect
self.reflect_llm = reflect_llm
# Use the same model selection logic for reflect_llm
self.reflect_llm = reflect_llm or os.getenv('OPENAI_MODEL_NAME', 'gpt-4o')
self.console = Console() # Create a single console instance for the agent
# Initialize system prompt
@@ -202,6 +225,21 @@ Your Role: {self.role}\n
Your Goal: {self.goal}
"""
def generate_task(self) -> 'Task':
"""Generate a Task object from the agent's instructions"""
from ..task.task import Task
description = self.instructions if self.instructions else f"Execute task as {self.role} with goal: {self.goal}"
expected_output = "Complete the assigned task successfully"
return Task(
name=self.name,
description=description,
expected_output=expected_output,
agent=self,
tools=self.tools
)
def execute_tool(self, function_name, arguments):
"""
Execute a tool dynamically based on the function name and arguments.
+43 -11
View File
@@ -41,7 +41,10 @@ def process_video(video_path: str, seconds_per_frame=2):
return base64_frames
class PraisonAIAgents:
def __init__(self, agents, tasks, verbose=0, completion_checker=None, max_retries=5, process="sequential", manager_llm=None):
def __init__(self, agents, tasks=None, verbose=0, completion_checker=None, max_retries=5, process="sequential", manager_llm=None):
if not agents:
raise ValueError("At least one agent must be provided")
self.agents = agents
self.tasks = {}
if max_retries < 3:
@@ -51,12 +54,41 @@ class PraisonAIAgents:
self.verbose = verbose
self.max_retries = max_retries
self.process = process
if not manager_llm:
logging.debug("No manager_llm provided. Using OPENAI_MODEL_NAME environment variable or defaulting to 'gpt-4o'")
self.manager_llm = manager_llm if manager_llm else os.getenv('OPENAI_MODEL_NAME', 'gpt-4o')
# Check for manager_llm in environment variable if not provided
self.manager_llm = manager_llm or os.getenv('OPENAI_MODEL_NAME', 'gpt-4o')
if self.verbose:
logging.info(f"Using model {self.manager_llm} for manager")
# If no tasks provided, generate them from agents
if tasks is None:
tasks = []
for agent in self.agents:
task = agent.generate_task()
tasks.append(task)
logging.info(f"Auto-generated {len(tasks)} tasks from agents")
else:
# Validate tasks for backward compatibility
if not tasks:
raise ValueError("If tasks are provided, at least one task must be present")
logging.info(f"Using {len(tasks)} provided tasks")
# Add tasks and set their status
for task in tasks:
self.add_task(task)
task.status = "not started"
# If tasks were auto-generated from agents or process is sequential, set up sequential flow
if len(tasks) > 1 and (process == "sequential" or all(task.next_tasks == [] for task in tasks)):
for i in range(len(tasks) - 1):
# Set up next task relationship
tasks[i].next_tasks = [tasks[i + 1].name]
# Set up context for the next task to include the current task
if tasks[i + 1].context is None:
tasks[i + 1].context = []
tasks[i + 1].context.append(tasks[i])
logging.info("Set up sequential flow with automatic context passing")
self._state = {} # Add state storage at PraisonAIAgents level
def add_task(self, task):
@@ -119,9 +151,9 @@ Expected Output: {task.expected_output}.
else:
context_results += f"Previous task {context_task.name if context_task.name else context_task.description} had no result.\n"
task_prompt += f"""
Here are the results of previous tasks that might be useful:\n
{context_results}
"""
Here are the results of previous tasks that might be useful:\n
{context_results}
"""
task_prompt += "Please provide only the final result of your work. Do not add any conversation or extra explanation."
if self.verbose >= 2:
@@ -320,7 +352,7 @@ Expected Output: {task.expected_output}.
task_prompt = f"""
You need to do the following task: {task.description}.
Expected Output: {task.expected_output}.
"""
"""
if task.context:
context_results = ""
for context_task in task.context:
@@ -329,9 +361,9 @@ Expected Output: {task.expected_output}.
else:
context_results += f"Previous task {context_task.name if context_task.name else context_task.description} had no result.\n"
task_prompt += f"""
Here are the results of previous tasks that might be useful:\n
{context_results}
"""
Here are the results of previous tasks that might be useful:\n
{context_results}
"""
task_prompt += "Please provide only the final result of your work. Do not add any conversation or extra explanation."
if self.verbose >= 2:
+4
View File
@@ -0,0 +1,4 @@
"""Tools package for PraisonAI Agents"""
from .tools import Tools
__all__ = ['Tools']
+40
View File
@@ -0,0 +1,40 @@
"""Tools module for PraisonAI Agents"""
from typing import List, Dict
import logging
import importlib
class Tools:
@staticmethod
def internet_search(query: str) -> List[Dict]:
"""
Perform a search using DuckDuckGo.
Args:
query (str): The search query.
Returns:
list: A list of search result titles, URLs, and snippets.
"""
# Check if duckduckgo_search is installed
if importlib.util.find_spec("duckduckgo_search") is None:
error_msg = "DuckDuckGo search is not available. Please install duckduckgo_search package using: pip install duckduckgo_search"
logging.error(error_msg)
return [{"error": error_msg}]
try:
# Import only when needed
from duckduckgo_search import DDGS
results = []
ddgs = DDGS()
for result in ddgs.text(keywords=query, max_results=5):
results.append({
"title": result.get("title", ""),
"url": result.get("href", ""),
"snippet": result.get("body", "")
})
return results
except Exception as e:
error_msg = f"Error during DuckDuckGo search: {e}"
logging.error(error_msg)
return [{"error": error_msg}]
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "praisonaiagents"
version = "0.0.20"
version = "0.0.22"
description = "Praison AI agents for completing complex tasks with Self Reflection Agents"
authors = [
{ name="Mervin Praison" }
+1 -1
View File
@@ -186,7 +186,7 @@ wheels = [
[[package]]
name = "praisonaiagents"
version = "0.0.20"
version = "0.0.22"
source = { editable = "." }
dependencies = [
{ name = "openai" },
+1 -1
View File
@@ -110,7 +110,7 @@ Loads environment variables from .env file or system and sets them.</p>
file.write(&#34;FROM python:3.11-slim\n&#34;)
file.write(&#34;WORKDIR /app\n&#34;)
file.write(&#34;COPY . .\n&#34;)
file.write(&#34;RUN pip install flask praisonai==2.0.28 gunicorn markdown\n&#34;)
file.write(&#34;RUN pip install flask praisonai==2.0.30 gunicorn markdown\n&#34;)
file.write(&#34;EXPOSE 8080\n&#34;)
file.write(&#39;CMD [&#34;gunicorn&#34;, &#34;-b&#34;, &#34;0.0.0.0:8080&#34;, &#34;api:app&#34;]\n&#39;)
+3 -2
View File
@@ -1,12 +1,13 @@
---
title: "Callbacks"
title: "AI Agents with Callbacks"
sidebarTitle: "Callbacks"
description: "Learn how to implement callbacks to monitor and log AI agent interactions, errors, and task completions."
icon: "bell"
---
<Note>
**Prerequisites**
- Python 3.8 or higher
- Python 3.10 or higher
- PraisonAI Agents package installed
- Basic understanding of Python functions
</Note>
+248
View File
@@ -0,0 +1,248 @@
---
title: "Mini AI Agents"
description: "Learn how to create simple yet powerful AI agents in just a few lines of code."
icon: "robot"
---
<Note>
**Prerequisites**
- Python 3.10 or higher
- PraisonAI Agents package installed
- Basic understanding of Python
</Note>
## Quick Start
Create multiple AI agents that can work together in just a few lines of code!
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Import Required Components">
Import the necessary components:
```python
from praisonaiagents import Agent, Agents
```
</Step>
<Step title="Create Your Agents">
Create specialized agents with specific roles:
```python
summarise_agent = Agent(instructions="Summarise what is Photosynthesis")
```
</Step>
<Step title="Start Your Agents">
Initialize and run your agents:
```python
agents = Agents(agents=[summarise_agent])
agents.start()
```
</Step>
</Steps>
## Understanding Mini AI Agents
<Card title="What are Mini AI Agents?" icon="question">
Mini AI Agents are simplified yet powerful AI agents that can:
- Work together to accomplish tasks
- Use tools like internet search
- Process and summarize information
- Execute tasks sequentially
</Card>
## Key Components
<CardGroup cols={2}>
<Card title="Agent" icon="user-robot">
Individual AI agents with specific roles and capabilities
```python
Agent(instructions="Your agent's role description")
```
</Card>
<Card title="Tools" icon="wrench">
Built-in tools that agents can use
```python
tools=[Tools.internet_search]
```
</Card>
<Card title="Agents Manager" icon="users">
Coordinates multiple agents
```python
Agents(agents=[agent1, agent2])
```
</Card>
<Card title="Sequential Flow" icon="arrow-right">
Agents work in sequence, passing results to each other
</Card>
</CardGroup>
## Available Tools
<CardGroup cols={2}>
<Card title="Internet Search" icon="search">
```python
Tools.internet_search
```
Search the internet using DuckDuckGo
<Note>
Requires: `pip install duckduckgo_search`
</Note>
</Card>
</CardGroup>
## Examples
### Basic Research and Summary
```terminal
pip install praisonaiagents duckduckgo_search
```
```python
from praisonaiagents import Agent, Agents, Tools
# Create a research agent
research_agent = Agent(
instructions="You are a research agent to search internet about AI 2024",
tools=[Tools.internet_search]
)
# Create a summarize agent
summarise_agent = Agent(
instructions="You are a summarize agent to summarise research agent's findings"
)
# Initialize and run agents
agents = Agents(agents=[research_agent, summarise_agent])
agents.start()
```
### Custom Instructions
<CodeGroup>
```python Basic
# Simple instructions
research_agent = Agent(
instructions="Research about climate change"
)
```
```python Advanced
# Detailed instructions
research_agent = Agent(
instructions="""
You are a research agent focused on gathering information about:
1. Latest AI developments in 2024
2. Major breakthroughs in machine learning
3. New AI applications in industry
Provide detailed and accurate information from reliable sources.
"""
)
```
</CodeGroup>
## Best Practices
<AccordionGroup>
<Accordion title="Agent Instructions">
Write clear and specific instructions:
```python
# Good
Agent(instructions="Research and analyze the latest AI developments in 2024")
# Too vague
Agent(instructions="Research AI")
```
</Accordion>
<Accordion title="Tool Usage">
Provide tools only to agents that need them:
```python
# Research agent needs search
research_agent = Agent(
instructions="Research AI",
tools=[Tools.internet_search]
)
# Summary agent doesn't need search
summary_agent = Agent(
instructions="Summarize findings"
)
```
</Accordion>
</AccordionGroup>
## Common Patterns
### Research and Analysis
```python
# Research agent
researcher = Agent(
instructions="Research latest developments in quantum computing",
tools=[Tools.internet_search]
)
# Analysis agent
analyst = Agent(
instructions="Analyze and explain the research findings in simple terms"
)
agents = Agents(agents=[researcher, analyst])
```
### Information Processing
```python
# Data collector
collector = Agent(
instructions="Collect information about renewable energy",
tools=[Tools.internet_search]
)
# Summarizer
summarizer = Agent(
instructions="Create a concise summary of the collected information"
)
# Report writer
writer = Agent(
instructions="Write a detailed report based on the summary"
)
agents = Agents(agents=[collector, summarizer, writer])
```
## Troubleshooting
<CardGroup cols={2}>
<Card title="Tool Not Available" icon="triangle-exclamation">
If using `Tools.internet_search`, install required package:
```bash
pip install duckduckgo_search
```
</Card>
<Card title="Agent Communication" icon="comments">
Ensure agent instructions are clear and complementary
</Card>
</CardGroup>
## Next Steps
<CardGroup cols={2}>
<Card title="Advanced Agents" icon="graduation-cap" href="./advanced">
Learn about advanced agent configurations
</Card>
<Card title="Custom Tools" icon="screwdriver-wrench" href="./tools">
Create your own agent tools
</Card>
</CardGroup>
<Note>
Mini AI Agents are designed to be simple yet powerful. They're perfect for quick prototypes and straightforward automation tasks.
</Note>
+1
View File
@@ -103,6 +103,7 @@
"features/reasoning",
"framework/multimodalagents",
"features/async",
"features/mini",
"features/callbacks",
"train",
"framework/praisonaiagents",
+1 -1
View File
@@ -3,7 +3,7 @@ class Praisonai < Formula
desc "AI tools for various AI applications"
homepage "https://github.com/MervinPraison/PraisonAI"
url "https://github.com/MervinPraison/PraisonAI/archive/refs/tags/2.0.28.tar.gz"
url "https://github.com/MervinPraison/PraisonAI/archive/refs/tags/2.0.30.tar.gz"
sha256 "1828fb9227d10f991522c3f24f061943a254b667196b40b1a3e4a54a8d30ce32" # Replace with actual SHA256 checksum
license "MIT"
+1 -1
View File
@@ -56,7 +56,7 @@ class CloudDeployer:
file.write("FROM python:3.11-slim\n")
file.write("WORKDIR /app\n")
file.write("COPY . .\n")
file.write("RUN pip install flask praisonai==2.0.28 gunicorn markdown\n")
file.write("RUN pip install flask praisonai==2.0.30 gunicorn markdown\n")
file.write("EXPOSE 8080\n")
file.write('CMD ["gunicorn", "-b", "0.0.0.0:8080", "api:app"]\n')
+4 -4
View File
@@ -1,6 +1,6 @@
[project]
name = "PraisonAI"
version = "2.0.28"
version = "2.0.30"
description = "PraisonAI is an AI Agents Framework with Self Reflection. PraisonAI application combines PraisonAI Agents, AutoGen, and CrewAI into a low-code solution for building and managing multi-agent LLM systems, focusing on simplicity, customisation, and efficient human–agent collaboration."
readme = "README.md"
license = ""
@@ -12,7 +12,7 @@ dependencies = [
"rich>=13.7",
"markdown>=3.5",
"pyparsing>=3.0.0",
"praisonaiagents>=0.0.20",
"praisonaiagents>=0.0.21",
"python-dotenv>=0.19.0",
"instructor>=1.3.3",
"PyYAML>=6.0",
@@ -84,7 +84,7 @@ autogen = ["pyautogen>=0.2.19", "praisonai-tools>=0.0.7", "crewai"]
[tool.poetry]
name = "PraisonAI"
version = "2.0.28"
version = "2.0.30"
description = "PraisonAI is an AI Agents Framework with Self Reflection. PraisonAI application combines PraisonAI Agents, AutoGen, and CrewAI into a low-code solution for building and managing multi-agent LLM systems, focusing on simplicity, customisation, and efficient human–agent collaboration."
authors = ["Mervin Praison"]
license = ""
@@ -102,7 +102,7 @@ python = ">=3.10,<3.13"
rich = ">=13.7"
markdown = ">=3.5"
pyparsing = ">=3.0.0"
praisonaiagents = ">=0.0.20"
praisonaiagents = ">=0.0.21"
python-dotenv = ">=0.19.0"
instructor = ">=1.3.3"
PyYAML = ">=6.0"
Generated
+5 -5
View File
@@ -3061,7 +3061,7 @@ wheels = [
[[package]]
name = "praisonai"
version = "2.0.28"
version = "2.0.30"
source = { editable = "." }
dependencies = [
{ name = "instructor" },
@@ -3198,7 +3198,7 @@ requires-dist = [
{ name = "plotly", marker = "extra == 'realtime'", specifier = ">=5.24.0" },
{ name = "praisonai-tools", marker = "extra == 'autogen'", specifier = ">=0.0.7" },
{ name = "praisonai-tools", marker = "extra == 'crewai'", specifier = ">=0.0.7" },
{ name = "praisonaiagents", specifier = ">=0.0.20" },
{ name = "praisonaiagents", specifier = ">=0.0.21" },
{ name = "pyautogen", marker = "extra == 'autogen'", specifier = ">=0.2.19" },
{ name = "pydantic", marker = "extra == 'chat'", specifier = "<=2.10.1" },
{ name = "pydantic", marker = "extra == 'code'", specifier = "<=2.10.1" },
@@ -3251,16 +3251,16 @@ wheels = [
[[package]]
name = "praisonaiagents"
version = "0.0.20"
version = "0.0.21"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "openai" },
{ name = "pydantic" },
{ name = "rich" },
]
sdist = { url = "https://files.pythonhosted.org/packages/8e/89/0e9d17b7113772ab469f3d113af51fb3ff5c2f16eb0a1b70667a12478358/praisonaiagents-0.0.20.tar.gz", hash = "sha256:15e08f2c8c06643e091870ba0f15c1614f6052dea45986c877dad52e8fe7f06e", size = 23885 }
sdist = { url = "https://files.pythonhosted.org/packages/ff/2a/9da2df9f6fc96e5c3192005f4bad3422fa7675fab1f07bfad9fcff93cd91/praisonaiagents-0.0.21.tar.gz", hash = "sha256:f6072220114ecb937b50ac675ace9f8b335667231637eed796e16ae1fc0656b1", size = 25460 }
wheels = [
{ url = "https://files.pythonhosted.org/packages/f8/94/5f62ded3aad4ee5d879e8b9712be4a3268abc2d89f71b10999109cef147c/praisonaiagents-0.0.20-py3-none-any.whl", hash = "sha256:3e9c62f3c4d8978bea8e0c95359a49e20db833511e17e122ccc06eb77996a618", size = 29883 },
{ url = "https://files.pythonhosted.org/packages/bc/61/3904cd43f66320d8b7ce407fc18c143842d3779716f51dc10b0faa9757e9/praisonaiagents-0.0.21-py3-none-any.whl", hash = "sha256:16f18d4e553471a740a03921e49d961c53ca881b287f422d65e77ae2c4c88275", size = 31742 },
]
[[package]]