Compare commits

...
72 Commits
Author SHA1 Message Date
Mervin Praison c6c27e58a6 Merge pull request #432 from MervinPraison/develop
adding other changes
2025-03-29 17:59:16 +00:00
MervinPraison ae21881522 adding other changes 2025-03-29 17:58:51 +00:00
Mervin Praison 68efb982af Merge pull request #429 from MervinPraison/develop
Add MCP integration for stock price retrieval
2025-03-29 17:58:05 +00:00
MervinPraison c539306b96 Increment version number in pyproject.toml to 2.0.81 2025-03-29 17:57:31 +00:00
MervinPraison c2f2d43d0d adding mcp 2025-03-29 17:57:10 +00:00
MervinPraison 7847515b4b adding mcp npx 2025-03-29 17:55:09 +00:00
Mervin Praison 1f2c412521 Merge pull request #428 from asiffarhankhan/main
Add .py files for all existing .mdx tools, Add .mdx, .py for the new AgentQL tool
2025-03-26 06:06:06 +00:00
asiffarhankhan 355fe1e59c Add local test file 2025-03-23 12:26:56 +05:30
asiffarhankhan 2ed64adc48 Remove API key from code 2025-03-23 12:19:55 +05:30
asiffarhankhan b8bc8583b1 Add agentql tool 2025-03-23 12:13:04 +05:30
asiffarhankhan 51a3a065c4 Add Python Files for existing MDX tools 2025-03-23 04:52:18 +05:30
Mervin Praison 4ba8745544 Merge pull request #427 from bhavnicksm/update-chonkie-config
Fix: `tokenizer` is not recognized error with `chonkie.RecursiveChunker`
2025-03-20 06:03:10 +00:00
bhavnicksm efc347f507 Update chonkie dependency version to ensure compatibility 2025-03-20 05:45:05 +05:30
bhavnicksm 72a162c722 Refactor tokenizer parameter in Chunking class for consistency and clarity 2025-03-20 05:41:02 +05:30
bhavnicksm 734a632dd4 Update chonkie dependency version in requirements.txt 2025-03-20 05:35:11 +05:30
MervinPraison dfaa3ed671 Add MCP integration for stock price retrieval
- Introduced multiple new files for MCP agent functionality, including `mcp-agents-detailed.py`, `mcp-agents.py`, `mcp-basic.py`, `mcp-multiagents.py`, and `mcp-test.py`.
- Implemented a dedicated `MCP` class for managing connections and tool execution.
- Created an asynchronous function to retrieve stock prices using MCP tools.
- Added example agents for stock price checking and web searching.
- Updated `pyproject.toml` and `uv.lock` to reflect version increment to 0.0.66.
- Ensured backward compatibility and improved tool function generation for better usability.
2025-03-18 18:23:39 +00:00
Mervin Praison 175b55704d Merge pull request #425 from asiffarhankhan/main
Add Bearly, Azure and Jina Code Interpreter
2025-03-18 16:56:19 +00:00
asiffarhankhan 084d1a2820 Add Azure and Jina, Bearly Code Interpreter 2025-03-17 23:46:41 +05:30
asiffarhankhan 8518c3ae9d Add Azure and Jina Code Inerpreter 2025-03-17 23:33:33 +05:30
Mervin Praison ac95c0000b Merge pull request #419 from asiffarhankhan/main
Add SearchAPI, YouSearch, TavillySearch tools
2025-03-17 13:38:39 +00:00
asiffarhankhan 8447e02f5d Merge branch 'main' of github.com:asiffarhankhan/PraisonAI 2025-03-15 15:07:38 +05:30
asiffarhankhan 3e612f61dc Add SearchAPI, YouSearch, TavillySearch tools 2025-03-15 15:06:07 +05:30
Mervin Praison b39c04dfb5 Merge pull request #417 from asiffarhankhan/main
Add MDX for Google and Jina Search
2025-03-14 04:46:44 +00:00
asiffarhankhan 8fc367ee6d Add "YOUR_API_KEY" placeholder to empty API variable 2025-03-12 14:26:43 +05:30
asiffarhankhan f7f157d3e7 Update Jina Search to MDX format 2025-03-12 14:19:49 +05:30
asiffarhankhan 05ede2a366 Add Google, Jina Search tools 2025-03-12 14:14:06 +05:30
Mervin Praison f8a2a93400 Merge pull request #416 from MervinPraison/develop
Add playground documentation to navigation
2025-03-11 10:34:12 +00:00
MervinPraison 1a77826a21 Add playground documentation to navigation
- Updated `mint.json` to include the "playground" page in the documentation navigation
- Positioned under the "Other Features" group for easy access
2025-03-11 10:33:54 +00:00
Mervin Praison adfd982547 Merge pull request #415 from MervinPraison/develop
updates
2025-03-11 09:43:36 +00:00
MervinPraison facd52103e updates 2025-03-11 09:42:04 +00:00
Mervin Praison 06d3d3decb Merge pull request #414 from MervinPraison/develop
Add course documentation for AI Agents
2025-03-11 04:59:27 +00:00
MervinPraison 7f35ac6113 Add course documentation for AI Agents
- Created a comprehensive course on AI Agents covering 20 lessons
- Included documentation for course topics like agent architecture, tools, memory, multi-agent systems, and deployment
- Added structured MDX files for each lesson with code examples, explanations, and best practices
- Updated `mint.json` to include new course navigation and pages
- Provided a step-by-step learning path for understanding and building AI agents
2025-03-11 04:58:56 +00:00
Mervin Praison e68fbb46f6 Merge pull request #413 from MervinPraison/develop
Add documentation for additional search tools
2025-03-11 04:10:25 +00:00
MervinPraison 50a7bf6c91 Add documentation for additional search tools
- Updated `mint.json` to include new search tools
- Added documentation pages for DuckDuckGo, Exa, Google Serper, Serp, and Wikipedia search tools
- Included installation instructions, overview, and example code for each search tool
2025-03-11 04:10:02 +00:00
Mervin Praison bce6e424d8 Merge pull request #412 from asiffarhankhan/main
Add search based tools using wikipedia, serper, serp, brave, exa, duckduckgo
2025-03-11 04:01:30 +00:00
asiffarhankhan 5cad05dc0d Align .py files with existing .mdx files 2025-03-11 00:37:40 +05:30
asiffarhankhan 3ecc722866 Add search based tools using wikipedia, serper, serp, brave, exa, duckduckgo 2025-03-11 00:32:02 +05:30
Mervin Praison c881fb3280 Merge pull request #408 from MervinPraison/develop
Refactor tools documentation with comprehensive examples and improved…
2025-03-10 06:20:01 +00:00
MervinPraison 15f9cbbe47 Refactor tools documentation with comprehensive examples and improved structure
- Updated tools documentation with new tabbed interface
- Added detailed code and no-code examples for tool creation
- Simplified tool registration and agent configuration examples
- Improved readability and provided step-by-step guidance for tool implementation
2025-03-10 06:19:41 +00:00
Mervin Praison f431347793 Merge pull request #407 from MervinPraison/develop
Add Langchain external search tool examples for PraisonAI agents
2025-03-10 06:03:11 +00:00
MervinPraison e0725c1296 Add Langchain external search tool examples for PraisonAI agents
- Introduced example scripts for Brave Search, Google Trends, and SerpAPI
- Demonstrated multi-agent workflows using external search tools
- Added API key configuration instructions for each search tool
- Included examples of research and content generation agents using search capabilities
2025-03-10 06:02:45 +00:00
Mervin Praison b40295efb9 Merge pull request #406 from MervinPraison/develop
Add external search tool documentation for PraisonAI agents
2025-03-10 05:54:34 +00:00
MervinPraison 2f7769d334 Add external search tool documentation for PraisonAI agents
- Updated `mint.json` to include new external tools section
- Expanded `langchain_tools.mdx` with more comprehensive examples and explanations
- Added documentation pages for BraveSearch, Google Trends, and SerpAPI tools
- Included installation, setup, and usage examples for external search tools
- Organized new documentation under the "External Tools" group
2025-03-10 05:54:13 +00:00
Mervin Praison c326aaf015 Merge pull request #405 from MervinPraison/develop
Add TypeScript documentation and examples for AI agent tools
2025-03-04 20:52:08 +00:00
MervinPraison 03874553eb Add TypeScript documentation and examples for AI agent tools
- Expanded documentation for TypeScript AI agents with tool registration examples
- Added new documentation pages for custom tools in TypeScript
- Updated installation and quickstart guides to include TypeScript sections
- Created example scripts demonstrating single and multi-agent tool usage
- Introduced new documentation for external tools like Google Trends
2025-03-04 20:51:53 +00:00
Mervin Praison 97ae6647c9 Merge pull request #403 from MervinPraison/develop
Expand tool registration documentation and examples
2025-03-03 08:25:09 +00:00
MervinPraison 046fb7cbe7 Expand tool registration documentation and examples
- Added comprehensive TypeScript documentation for tool registration methods in `docs/js/typescript.mdx`
- Created new README example file `examples/README-tool-examples.md` with detailed tool registration approaches
- Updated example scripts to demonstrate direct function tool registration
- Refined agent tool registration logic to support multiple function registration styles
- Bumped package version to 1.0.19
2025-03-03 08:24:46 +00:00
Mervin Praison afdd6ab6f8 Merge pull request #402 from MervinPraison/develop
Enhance agent tool function registration with direct function support
2025-03-03 08:13:52 +00:00
MervinPraison 4581486a81 Enhance agent tool function registration with direct function support
- Added support for directly registering tool functions without global declaration
- Implemented auto-generation of tool definitions for registered functions
- Created new example scripts demonstrating direct function tool registration
- Updated package version to 1.0.18
- Expanded Agent configuration to support `toolFunctions` property
- Added type exports for improved type safety
2025-03-03 08:13:31 +00:00
Mervin Praison e10b991fab Merge pull request #401 from MervinPraison/develop
npm 1.0.17 praisonai
2025-03-03 07:52:40 +00:00
MervinPraison 2d790f79a9 Add tool call support for agents with multi-tool and single-tool test cases
- Enhanced OpenAI service to support tool calls in chat and text generation methods
- Updated Agent classes to register and process tool functions dynamically
- Added new test cases for single and multi-tool agent interactions
- Improved type safety and conversion for OpenAI tool and message formats
- Bumped package version to 1.0.17
2025-03-03 07:52:07 +00:00
MervinPraison ec04dd7a91 test 7 2025-02-28 17:12:25 +00:00
MervinPraison bd49416f2b test 6 2025-02-28 17:05:09 +00:00
MervinPraison da2e11921c test 5 2025-02-28 17:03:42 +00:00
MervinPraison 8287c3a3d4 test 4 2025-02-28 16:57:02 +00:00
MervinPraison 6904f86557 test 3 2025-02-28 16:54:54 +00:00
MervinPraison cbebb3a900 test 2 2025-02-28 16:53:48 +00:00
MervinPraison 413484ea9f test 2025-02-28 16:36:58 +00:00
MervinPraison 785317c4fa test 2025-02-28 11:56:13 +00:00
MervinPraison c70f9ebf1f Add package.json and update documentation requirements
- Created package.json for documentation with Mintlify dev and build scripts
- Updated requirements.in with additional documentation and tool dependencies
- Removed redundant requirements.txt file
- Added support for enhanced documentation generation and API documentation
2025-02-28 11:51:31 +00:00
Mervin Praison d278f2d2b2 Merge pull request #399 from MervinPraison/develop
Bump version to 2.0.80 and update praisonaiagents dependency
2025-02-28 10:25:47 +00:00
MervinPraison df4596a699 Bump version to 2.0.80 and update praisonaiagents dependency
- Updated version to 2.0.80 across multiple files including praisonai.rb, pyproject.toml, uv.lock, Dockerfile, and docs
- Upgraded praisonaiagents dependency from 0.0.64 to 0.0.65
- Enhanced agent start methods with optional return_dict parameter
- Improved result handling in start and astart methods to return final response by default
- Synchronized version updates across project configuration files
2025-02-28 10:25:32 +00:00
Mervin Praison dd0f47ec81 Merge pull request #398 from MervinPraison/develop
Bump version to 2.0.79 and update praisonaiagents dependency
2025-02-28 07:26:52 +00:00
MervinPraison e53017a2fe Bump version to 2.0.79 and update praisonaiagents dependency
- Updated version to 2.0.79 across multiple files including praisonai.rb, pyproject.toml, uv.lock, Dockerfile, and docs
- Upgraded praisonaiagents dependency from 0.0.63 to 0.0.64
- Updated example agent scripts for Anthropic and Gemini LLMs
- Added parameter modification support in LLM initialization
- Synchronized version updates across project configuration files
2025-02-28 07:26:22 +00:00
Mervin Praison fe034ba8f4 Merge pull request #397 from MervinPraison/develop
Enhance Agent Tool Execution Logging and Debugging
2025-02-28 07:05:13 +00:00
MervinPraison 063e5780d6 Enhance Agent Tool Execution Logging and Debugging
- Added comprehensive debug logging for tool execution in LLM and Agent components
- Improved display of tool call messages with more detailed information
- Added logging for empty content and tool execution scenarios
- Enhanced error handling and logging in display functions
- Added new Anthropic LLM example script in src/praisonai-agents
- Bumped version to 2.0.78 and updated praisonaiagents dependency to 0.0.63
2025-02-28 07:04:50 +00:00
Mervin Praison 904e21ca87 Merge pull request #396 from MervinPraison/develop
v2.0.77
2025-02-27 09:12:33 +00:00
MervinPraison 526665ea11 Bump version to 2.0.77 and update praisonaiagents dependency
- Updated version to 2.0.77 across multiple files including praisonai.rb, pyproject.toml, uv.lock, Dockerfile, and docs
- Upgraded praisonaiagents dependency from 0.0.61 to 0.0.62
- Synchronized version updates across project configuration files
2025-02-27 09:11:18 +00:00
MervinPraison c2e97d2432 adding litellm tools fix 2025-02-27 09:08:22 +00:00
MervinPraison 60be6a1f99 Add Comprehensive Debug Logging to LLM and Agent Components
- Enhanced LLM and Agent classes with detailed debug logging capabilities
- Added parameter and configuration logging for get_response and chat methods
- Implemented time tracking for method execution in debug mode
- Masked sensitive information like API keys in logs
- Created new Wikipedia agent example script demonstrating agent initialization
2025-02-27 06:54:32 +00:00
Mervin Praison 0ba7d2e834 Merge pull request #385 from MervinPraison/develop
Add Vision Model Upload Functionality and Enhance Training Workflow
2025-02-09 21:23:38 +00:00
MervinPraison 184b241395 Add Vision Model Upload Functionality and Enhance Training Workflow
- Introduced new upload_vision.py script for comprehensive model upload capabilities
- Extended train_vision.py with additional upload methods for Hugging Face and Ollama
- Added support for saving merged models, pushing GGUF models, and creating Ollama models
- Implemented flexible upload targeting with configurable options
- Enhanced model preparation and deployment workflow for vision models
2025-02-09 21:23:24 +00:00
123 changed files with 18320 additions and 207 deletions

No files matched your search

+4 -1
View File
@@ -1,3 +1,4 @@
workspace.code-workspace
.vscode
crewai
.cache
@@ -66,4 +67,6 @@ agents/praisonaiagents/build
agents/praisonaiagents/dist
agents/praisonaiagents/praisonaiagents.egg-info
.codegpt
.praison
.praison
# Local Netlify folder
.netlify
+1 -1
View File
@@ -1,6 +1,6 @@
FROM python:3.11-slim
WORKDIR /app
COPY . .
RUN pip install flask praisonai==2.0.76 gunicorn markdown
RUN pip install flask praisonai==2.0.81 gunicorn markdown
EXPOSE 8080
CMD ["gunicorn", "-b", "0.0.0.0:8080", "api:app"]
+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.76 gunicorn markdown\n&#34;)
file.write(&#34;RUN pip install flask praisonai==2.0.81 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;)
+71
View File
@@ -0,0 +1,71 @@
---
title: "Introduction to AI Agents"
description: "Welcome to the beginner's course on AI Agents"
icon: "book-open"
---
# Introduction to AI Agents
Welcome to the beginners' course on AI Agents! This course is designed to help you understand and build your own AI agents, even if you have little to no programming experience.
## What Are AI Agents?
An AI agent is a software program that can:
- Understand information from its environment
- Make decisions based on that information
- Take actions to achieve specific goals
Think of an AI agent like a helpful assistant that can perform tasks for you automatically.
```mermaid
graph TD
A[Perceive Information] --> B[Make Decisions]
B --> C[Take Actions]
C --> A
```
## Examples in Daily Life
You might already be using AI agents without realizing it:
- **Virtual Assistants**: Siri, Alexa, and Google Assistant are AI agents that respond to your voice commands
- **Recommendation Systems**: Netflix, YouTube, and Amazon use AI agents to suggest content you might like
- **Smart Home Devices**: Devices that adjust temperature or lighting based on your preferences
## What You'll Learn in This Course
Throughout this course, you will:
1. Understand the basic concepts of AI agents
2. Learn about different types of AI agents
3. Explore how AI agents make decisions
4. Discover how to build simple AI agents without complex programming
5. Create your own functional AI agents
## Who This Course Is For
This course is perfect for:
- Complete beginners with no prior knowledge of AI
- Non-technical professionals interested in how AI can solve problems
- Students curious about artificial intelligence
- Anyone who wants to understand and use AI agents in practical ways
Let's begin our journey into the fascinating world of AI agents!
<iframe
id="codeExecutionFrame"
src="https://code-execution-server-praisonai.replit.app/?code=import%20openai%0A%0Aclient%20%3D%20openai.OpenAI()%0Aresult%20%3D%20client.chat.completions.create(%0A%20%20%20%20model%3D%22gpt-3.5-turbo%22%2C%0A%20%20%20%20messages%3D%5B%0A%20%20%20%20%20%20%20%20%7B%22role%22%3A%20%22user%22%2C%20%22content%22%3A%20%22Hello%20World%22%7D%0A%20%20%20%20%5D%0A)%0A%0Aprint(result.choices%5B0%5D.message.content)"
width="100%"
height="600px"
frameborder="0"
allow="clipboard-read; clipboard-write"
scrolling="yes"
onload="resizeIframe(this)"
></iframe>
<IframeWithAutoHeight />
<CardGroup cols={1}>
<Card title="Ready to Start?" icon="rocket">
Continue to the next lesson to learn about the different types of AI agents.
</Card>
</CardGroup>
+113
View File
@@ -0,0 +1,113 @@
---
title: "Types of AI Agents"
description: "Understanding the different categories of AI agents"
icon: "sitemap"
---
# Types of AI Agents
AI agents come in different forms, each designed for specific purposes and with varying levels of complexity. Understanding these types will help you choose the right approach for your needs.
## Simple Reflex Agents
These are the most basic type of AI agents that operate using simple if-then rules.
<CardGroup cols={1}>
<Card title="Key Characteristics" icon="lightbulb">
- React directly to current input only
- No memory of past events
- No prediction of future states
- Use predefined rules to determine actions
</Card>
</CardGroup>
**Real-world example**: A basic thermostat that turns heating on when temperature drops below a set point.
```mermaid
graph LR
A[Sensor Input] --> B{If-Then Rules}
B --> C[Action]
```
## Model-Based Agents
These agents maintain an internal model of their environment to make better decisions.
<CardGroup cols={1}>
<Card title="Key Characteristics" icon="brain">
- Build and maintain an internal representation of the world
- Can work with partial information
- Can consider "what if" scenarios
- Make decisions based on their understanding of how the world works
</Card>
</CardGroup>
**Real-world example**: A GPS navigation system that models roads and traffic conditions.
## Goal-Based Agents
These agents make decisions based on how their actions will help achieve specific goals.
<CardGroup cols={1}>
<Card title="Key Characteristics" icon="bullseye">
- Consider future consequences of actions
- Evaluate which actions will lead toward goals
- Can plan sequences of actions
- Choose actions that maximize goal attainment
</Card>
</CardGroup>
**Real-world example**: A chess-playing AI that plans moves to achieve checkmate.
## Utility-Based Agents
These agents choose actions that maximize a specific utility (or happiness) function.
<CardGroup cols={1}>
<Card title="Key Characteristics" icon="chart-line">
- Assign a utility value to different possible outcomes
- Consider probability and risk
- Choose actions that maximize expected utility
- Can balance competing objectives
</Card>
</CardGroup>
**Real-world example**: An investment robo-advisor that balances risk and return.
## Learning Agents
These agents improve their performance over time through experience.
<CardGroup cols={1}>
<Card title="Key Characteristics" icon="graduation-cap">
- Learn from past experiences
- Adapt to changing environments
- Improve decision-making over time
- Can discover new strategies
</Card>
</CardGroup>
**Real-world example**: Recommendation systems that learn your preferences over time.
## Understanding Agent Complexity
<Tip>
As you move from Simple Reflex Agents toward Learning Agents, both capability and complexity increase. For beginners, starting with simpler agent types is often best.
</Tip>
## Which Agent Type Should You Build?
The best type of agent for your project depends on:
1. **The problem complexity**: Simple problems may only need reflex agents
2. **Available data**: Learning agents need training data
3. **Required adaptability**: Will your agent need to adapt to new situations?
4. **Available resources**: More complex agents require more computational power
In this course, we'll focus primarily on goal-based and simple learning agents as they provide a good balance of capability and complexity for beginners.
<CardGroup cols={1}>
<Card title="Next Steps" icon="arrow-right">
In the next lesson, we'll explore how agents process information and make decisions.
</Card>
</CardGroup>
@@ -0,0 +1,157 @@
---
title: "Agent Architecture"
description: "Understanding how AI agents are structured"
icon: "layer-group"
---
# Agent Architecture
Understanding how AI agents are structured will help you build more effective agents. This lesson covers the fundamental components of an agent's architecture.
## Basic Components of an AI Agent
Every AI agent, regardless of complexity, has these basic components:
```mermaid
graph TD
A[Sensors/Input] --> B[Processing Unit]
B --> C[Decision-Making]
C --> D[Actions/Output]
```
### 1. Input (Sensors)
This is how agents receive information from their environment.
<CardGroup cols={1}>
<Card title="Examples of Input" icon="eye">
- Text input from users
- Data from databases
- Image or audio input
- API responses
- Sensor readings (in physical agents)
</Card>
</CardGroup>
### 2. Processing Unit
This component processes information and converts it into a format the agent can understand.
<CardGroup cols={1}>
<Card title="Processing Functions" icon="gears">
- Data cleaning and transformation
- Feature extraction
- Context building
- Information retrieval
- Pattern recognition
</Card>
</CardGroup>
### 3. Decision-Making Core
The "brain" of the agent that determines what actions to take.
<CardGroup cols={1}>
<Card title="Decision Components" icon="brain">
- Language models (like GPT-4)
- Rule systems
- Planning algorithms
- Knowledge base
- Memory systems
</Card>
</CardGroup>
### 4. Output (Actions)
The actions the agent can perform to achieve its goals.
<CardGroup cols={1}>
<Card title="Action Examples" icon="hand">
- Generating text responses
- Creating visual content
- Making API calls
- Controlling other systems
- Updating databases
</Card>
</CardGroup>
## The Agent Loop
Agents operate in a continuous loop:
```mermaid
graph LR
A[Perceive] --> B[Process]
B --> C[Decide]
C --> D[Act]
D --> A
```
This cycle allows agents to continuously:
1. Gather information
2. Update their understanding
3. Make new decisions
4. Take appropriate actions
## PraisonAI Agent Architecture
In the PraisonAI framework, agents follow a specific architecture:
<CardGroup cols={1}>
<Card title="PraisonAI Agent Components" icon="puzzle-piece">
- **Instructions**: Defines the agent's purpose and behavior
- **Language Model**: Powers the agent's intelligence (e.g., GPT-4)
- **Memory**: Stores context and previous interactions
- **Tools**: Specialized capabilities an agent can use
</Card>
</CardGroup>
### Simple Agent Structure
```python
from praisonaiagents import Agent
# Create a simple agent
research_agent = Agent(
instructions="Research the latest developments in renewable energy",
name="ResearchAgent"
)
# Start the agent
research_agent.start()
```
## Understanding Agent Communication
Multi-agent systems allow agents to communicate with each other:
```mermaid
graph LR
A[Agent 1] --> B[Agent 2]
B --> C[Agent 3]
C --> A
```
Each agent can:
- Pass information to other agents
- Request assistance from specialized agents
- Collaborate on complex tasks
## Key Takeaways
<CardGroup cols={2}>
<Card title="Component Importance" icon="check">
Each component plays a vital role in the agent's functionality
</Card>
<Card title="Agent Customization" icon="gear">
You can customize each component based on your specific needs
</Card>
<Card title="Component Balance" icon="scale-balanced">
A well-designed agent balances all components effectively
</Card>
<Card title="Continuous Improvement" icon="arrow-trend-up">
Agents can be improved by enhancing individual components
</Card>
</CardGroup>
In the next lesson, we'll explore how to define effective instructions for your AI agents.
@@ -0,0 +1,187 @@
---
title: "Creating Effective Agent Instructions"
description: "How to write clear instructions for your AI agents"
icon: "file-lines"
---
# Creating Effective Agent Instructions
The instructions you give to your AI agent are crucial to its performance. Well-crafted instructions lead to agents that understand their purpose and execute tasks effectively.
## Why Instructions Matter
Instructions serve as the agent's "job description" and guide its behavior:
<CardGroup cols={2}>
<Card title="Clarity" icon="glasses">
Clear instructions reduce confusion and misinterpretation
</Card>
<Card title="Focus" icon="bullseye">
Specific instructions keep the agent on task
</Card>
<Card title="Boundaries" icon="border-all">
Good instructions define what an agent should and shouldn't do
</Card>
<Card title="Personality" icon="face-smile">
Instructions can shape how an agent communicates
</Card>
</CardGroup>
## Elements of Effective Instructions
### 1. Role Definition
Tell the agent who it is and what its expertise should be.
<CodeGroup>
```text Good Example
You are a financial analyst with expertise in market trends and investment strategies.
```
```text Weak Example
You are a helper.
```
</CodeGroup>
### 2. Purpose and Goals
Clearly state what the agent should accomplish.
<CodeGroup>
```text Good Example
Your goal is to analyze company quarterly reports and provide actionable investment insights.
```
```text Weak Example
Help with finance stuff.
```
</CodeGroup>
### 3. Process Guidelines
Explain how the agent should approach tasks.
<CodeGroup>
```text Good Example
First analyze the data trends, then identify key risk factors, and finally make recommendations based on the client's risk tolerance.
```
```text Weak Example
Just do a good analysis.
```
</CodeGroup>
### 4. Response Format
Specify how you want information presented.
<CodeGroup>
```text Good Example
Present your analysis in a structured format with: Summary, Key Findings, Risk Assessment, and Recommendations.
```
```text Weak Example
Tell me what you find.
```
</CodeGroup>
## Instructions Template
Here's a template you can use to create effective agent instructions:
```
You are a [ROLE] specializing in [EXPERTISE AREAS].
Your goal is to [MAIN OBJECTIVE].
When approaching tasks:
1. [FIRST STEP/APPROACH]
2. [SECOND STEP/APPROACH]
3. [THIRD STEP/APPROACH]
Present your results in [FORMAT PREFERENCES].
Additional guidelines:
- [SPECIFIC BEHAVIOR 1]
- [SPECIFIC BEHAVIOR 2]
- [SPECIFIC BEHAVIOR 3]
```
## Examples in PraisonAI
Let's look at how instructions are implemented in PraisonAI:
<CodeGroup>
```python Simple Example
from praisonaiagents import Agent
research_agent = Agent(
instructions="You are a research assistant specializing in climate science. Your goal is to find the latest research on rising sea levels and summarize key findings in bullet points."
)
research_agent.start()
```
```python Detailed Example
from praisonaiagents import Agent
content_agent = Agent(
name="ContentCreator",
instructions="""
You are a content creation specialist with expertise in digital marketing.
Your goal is to create engaging blog content that drives traffic and conversions.
When creating content:
1. Research the target keyword thoroughly
2. Create an attention-grabbing headline
3. Develop well-structured content with clear sections
4. Include actionable takeaways for readers
Present content in markdown format with proper headings, bullet points, and emphasis where appropriate.
Additional guidelines:
- Maintain a conversational but professional tone
- Include 2-3 relevant statistics to support key points
- Add a call-to-action at the end of each piece
"""
)
content_agent.start("Create a blog post about sustainable living tips")
```
</CodeGroup>
## Common Instruction Mistakes
<CardGroup cols={2}>
<Card title="Being Too Vague" icon="cloud">
Vague instructions lead to unpredictable outputs
</Card>
<Card title="Information Overload" icon="bomb">
Too many details can confuse the agent's priorities
</Card>
<Card title="Contradictory Guidelines" icon="arrows-split-up-and-left">
Conflicting instructions create confusion
</Card>
<Card title="Missing Context" icon="puzzle-piece-missing">
Insufficient background information leads to generic outputs
</Card>
</CardGroup>
## Refining Your Instructions
<Tip>
Good instructions often require iteration. Start with basic instructions, review the agent's performance, and refine as needed.
</Tip>
Effective instruction improvement follows this cycle:
```mermaid
graph TD
A[Write Initial Instructions] --> B[Test Agent Performance]
B --> C[Identify Issues/Gaps]
C --> D[Refine Instructions]
D --> B
```
In the next lesson, we'll explore how agents use tools to extend their capabilities.
+183
View File
@@ -0,0 +1,183 @@
---
title: "Agent Tools"
description: "Understanding how tools extend agent capabilities"
icon: "screwdriver-wrench"
---
# Agent Tools
Tools allow AI agents to interact with the world and perform specific actions. Think of tools as the "hands" of your agent that let it accomplish tasks beyond just generating text.
## What Are Agent Tools?
<CardGroup cols={1}>
<Card title="Definition" icon="toolbox">
Tools are functions or capabilities that agents can access to perform specific actions, retrieve information, or interact with external systems.
</Card>
</CardGroup>
Just as humans use tools to extend their physical abilities, AI agents use digital tools to extend their capabilities.
## Why Tools Matter
Tools transform agents from simple chat interfaces into powerful assistants that can:
<CardGroup cols={2}>
<Card title="Access Information" icon="database">
Retrieve data from various sources
</Card>
<Card title="Perform Calculations" icon="calculator">
Analyze numbers and data accurately
</Card>
<Card title="Create Content" icon="pen-to-square">
Generate images, code, or other media
</Card>
<Card title="Control Systems" icon="gears">
Interact with other software or hardware
</Card>
</CardGroup>
## Common Types of Tools
### 1. Information Retrieval Tools
These tools help agents access information beyond their training data.
**Examples:**
- Web search tools
- Database query tools
- Document retrieval tools
```python
# Example of a simple web search tool
from praisonaiagents import Agent
def web_search(query):
# Simplified example
return f"Results for: {query}"
agent = Agent(
instructions="Research assistant",
tools=[web_search]
)
```
### 2. Computation Tools
These tools perform calculations or data processing.
**Examples:**
- Calculator tools
- Data analysis tools
- Conversion tools
### 3. Content Creation Tools
These tools help generate or modify various types of content.
**Examples:**
- Image generation tools
- Code writing tools
- Document formatting tools
### 4. External API Tools
These tools connect to third-party services.
**Examples:**
- Weather API tools
- Translation API tools
- E-commerce API tools
## How Tools Work in PraisonAI
In the PraisonAI framework, tools follow a simple pattern:
1. Tools are defined as functions
2. Tools are registered with an agent
3. The agent decides when to use appropriate tools
4. Tool results are incorporated into the agent's reasoning
```mermaid
graph TD
A[Agent Receives Task] --> B{Needs a Tool?}
B -->|Yes| C[Select Appropriate Tool]
C --> D[Execute Tool]
D --> E[Process Tool Results]
E --> F[Continue Task]
B -->|No| F
```
## Creating Basic Tools
Here's a simple example of creating and using tools in PraisonAI:
```python
from praisonaiagents import Agent
# Define a simple calculator tool
def calculator(expression):
try:
return str(eval(expression))
except:
return "Error: Could not calculate"
# Create an agent with the tool
math_agent = Agent(
instructions="You are a math tutor helping students solve problems",
tools=[calculator]
)
# Use the agent
math_agent.start("Calculate 24 * 17 and explain the steps")
```
## Tool Best Practices
<CardGroup cols={2}>
<Card title="Clear Descriptions" icon="comment">
Provide detailed descriptions so the agent knows when to use each tool
</Card>
<Card title="Error Handling" icon="shield">
Make tools robust with proper error handling
</Card>
<Card title="Focused Purpose" icon="bullseye">
Each tool should do one thing well
</Card>
<Card title="Input Validation" icon="check-double">
Validate inputs to prevent misuse
</Card>
</CardGroup>
## Building a Toolbox
As you advance, you'll want to create a collection of tools your agent can use:
```python
from praisonaiagents import Agent, Tool
# Define multiple tools
def weather(location):
return f"Weather in {location}: Sunny, 75°F"
def translator(text, target_language):
return f"Translated to {target_language}: {text} (placeholder)"
def reminder(message, time):
return f"Reminder set for {time}: {message}"
# Create tool collection
tools = [
Tool(name="weather", function=weather, description="Get weather for a location"),
Tool(name="translator", function=translator, description="Translate text"),
Tool(name="reminder", function=reminder, description="Set a reminder")
]
# Create agent with multiple tools
assistant = Agent(
instructions="You are a helpful personal assistant",
tools=tools
)
```
In the next lesson, we'll explore how agents use memory to maintain context across interactions.
+167
View File
@@ -0,0 +1,167 @@
---
title: "Agent Memory"
description: "Understanding how agents maintain context and learn"
icon: "brain"
---
# Agent Memory
Memory enables AI agents to remember past interactions, maintain context, and provide more coherent responses over time. Without memory, agents would treat each interaction as if it was their first.
## Why Memory Matters
<CardGroup cols={2}>
<Card title="Context Awareness" icon="comments">
Remembers previous parts of a conversation
</Card>
<Card title="Personalization" icon="user-gear">
Recalls user preferences and history
</Card>
<Card title="Continuous Learning" icon="graduation-cap">
Builds on past experiences
</Card>
<Card title="Task Persistence" icon="list-check">
Maintains progress on long-running tasks
</Card>
</CardGroup>
## Types of Agent Memory
### 1. Short-Term Memory (Conversation Memory)
This type of memory stores recent interactions within a session.
```mermaid
graph LR
A[User Input 1] --> B[Agent Response 1]
B --> C[User Input 2]
C --> D[Agent Response 2]
D --> E[User Input 3]
```
The agent can refer back to earlier messages in the same conversation.
### 2. Long-Term Memory
This allows agents to remember information across different sessions.
<CardGroup cols={1}>
<Card title="Use Cases" icon="clock">
- Remembering user preferences
- Recalling previous tasks completed
- Storing learned information
- Maintaining relationship history
</Card>
</CardGroup>
### 3. Working Memory
This is where agents process current information and combine it with retrieved memories.
```mermaid
graph TD
A[Current Input] --> D[Working Memory]
B[Short-Term Memory] --> D
C[Long-Term Memory] --> D
D --> E[Agent Response]
```
## How Memory Works in PraisonAI
In the PraisonAI framework, memory is handled automatically for basic cases and can be customized for more advanced needs:
```python
from praisonaiagents import Agent
# Basic agent with default memory handling
agent = Agent(
instructions="You are a helpful assistant that remembers our conversations"
)
# The conversation history is maintained automatically
agent.start("My name is Alex")
agent.continue("What's my name?")# Note: TODO: This Feature yet to be developed # Agent will remember "Alex"
```
## Memory Limitations
<Tip>
All AI memories have limitations. They aren't perfect and may occasionally forget or misremember information.
</Tip>
Common limitations include:
<CardGroup cols={2}>
<Card title="Memory Capacity" icon="database">
Limit to how much information can be stored
</Card>
<Card title="Context Window" icon="window">
Only a portion of memory fits in the active context
</Card>
<Card title="Memory Decay" icon="hourglass-half">
Older memories may become less accessible
</Card>
<Card title="Memory Retrieval" icon="magnifying-glass">
Finding the right memory at the right time
</Card>
</CardGroup>
## Implementing Persistent Memory
For more advanced applications, you can implement custom memory systems:
```python
# Note: TODO: This Feature yet to be tested
from praisonaiagents import Agent, Memory
# Create a simple memory store
memory = Memory()
# Add information to memory
memory.add("user_name", "Alex")
memory.add("favorite_color", "blue")
# Create agent with this memory
agent = Agent(
instructions="You are a personal assistant",
memory=memory
)
# The agent can now access these memories
agent.start("What's my favorite color?") # Agent should respond "blue"
```
## Memory Best Practices
<CardGroup cols={2}>
<Card title="Prioritize Important Info" icon="star">
Not everything needs to be remembered
</Card>
<Card title="Verify When Uncertain" icon="question">
Have agents confirm uncertain memories
</Card>
<Card title="Structured Storage" icon="folder-tree">
Organize memories by categories
</Card>
<Card title="Regular Updates" icon="arrows-rotate">
Update memories when information changes
</Card>
</CardGroup>
## Memory in Multi-Agent Systems
In systems with multiple agents, memory can be:
1. **Private**: Each agent has its own memories
2. **Shared**: Agents have access to a common memory store
3. **Hybrid**: Some memories are private, others are shared
```mermaid
graph TD
A[Agent 1] --> B[Private Memory 1]
C[Agent 2] --> D[Private Memory 2]
A -.-> E[Shared Memory]
C -.-> E
```
In the next lesson, we'll learn about how to set up multiple agents to work together effectively.
@@ -0,0 +1,171 @@
---
title: "Multi-Agent Systems"
description: "How multiple agents can work together"
icon: "users"
---
# Multi-Agent Systems
Multi-agent systems allow multiple AI agents to work together, each handling different parts of a complex task. This approach mirrors how human teams collaborate, with each member contributing their specialized skills.
## Why Use Multiple Agents?
<CardGroup cols={2}>
<Card title="Specialization" icon="star">
Each agent can focus on its area of expertise
</Card>
<Card title="Complex Tasks" icon="puzzle-piece">
Break down difficult problems into manageable pieces
</Card>
<Card title="Scalability" icon="arrows-up-down">
Add more agents as tasks become more complex
</Card>
<Card title="Diverse Perspectives" icon="lightbulb">
Different agents can approach problems differently
</Card>
</CardGroup>
## Basic Multi-Agent Architecture
```mermaid
graph LR
A[Research Agent] --> B[Analysis Agent]
B --> C[Writing Agent]
C --> D[Final Output]
```
In this example:
1. The Research Agent gathers information
2. The Analysis Agent processes and interprets the data
3. The Writing Agent creates the final content
## Multi-Agent Patterns
### 1. Pipeline Pattern
Agents work in sequence, with each agent handling a specific stage of the process.
```mermaid
graph LR
A[Agent 1] --> B[Agent 2]
B --> C[Agent 3]
```
**Example Use Case**: Content creation where one agent researches, another drafts, and a third edits.
### 2. Expert Panel Pattern
Multiple specialist agents work in parallel on the same problem, then their outputs are combined.
```mermaid
graph TD
Task --> A[Expert Agent 1]
Task --> B[Expert Agent 2]
Task --> C[Expert Agent 3]
A --> D[Coordination Agent]
B --> D
C --> D
D --> Result
```
**Example Use Case**: Financial analysis where different experts analyze market trends, economic indicators, and company performance.
### 3. Hierarchical Pattern
A manager agent delegates tasks to worker agents and coordinates their efforts.
```mermaid
graph TD
A[Manager Agent] --> B[Worker Agent 1]
A --> C[Worker Agent 2]
A --> D[Worker Agent 3]
B --> A
C --> A
D --> A
```
**Example Use Case**: Project management where a coordinator assigns tasks and integrates results.
## Implementing Multi-Agent Systems in PraisonAI
Here's a simple example of creating a multi-agent system:
```python
from praisonaiagents import Agent, PraisonAIAgents
# Create individual agents
research_agent = Agent(
name="Researcher",
instructions="Research the latest trends in renewable energy"
)
analysis_agent = Agent(
name="Analyst",
instructions="Analyze the research findings and identify key insights"
)
writing_agent = Agent(
name="Writer",
instructions="Create a clear, engaging report based on the analysis"
)
# Create a multi-agent system
agents = PraisonAIAgents(
agents=[research_agent, analysis_agent, writing_agent]
)
# Start the agents
agents.start()
```
## Agent Communication
For agents to work together effectively, they need to communicate. This happens through:
<CardGroup cols={2}>
<Card title="Output Passing" icon="arrow-right">
One agent's output becomes another's input
</Card>
<Card title="Shared Memory" icon="database">
Agents can access common information
</Card>
<Card title="Message Exchange" icon="comments">
Agents can send specific messages to each other
</Card>
<Card title="Coordination Protocols" icon="traffic-light">
Rules that determine how agents interact
</Card>
</CardGroup>
## Challenges in Multi-Agent Systems
<CardGroup cols={2}>
<Card title="Coordination" icon="shuffle">
Ensuring agents work together smoothly
</Card>
<Card title="Conflicting Goals" icon="arrows-split-up-and-left">
Managing agents with different objectives
</Card>
<Card title="Information Transfer" icon="exchange">
Passing information effectively between agents
</Card>
<Card title="Resource Management" icon="microchip">
Allocating computational resources efficiently
</Card>
</CardGroup>
## Designing Effective Multi-Agent Systems
<Tip>
Start simple with just 2-3 agents and a clear workflow before scaling to more complex systems.
</Tip>
Key principles for effective design:
1. **Clear Role Definition**: Each agent should have a specific and well-defined role
2. **Minimized Dependencies**: Reduce complex interdependencies between agents
3. **Standardized Communication**: Use consistent formats for information exchange
4. **Failure Handling**: Plan for cases where an agent fails to complete its task
5. **Performance Monitoring**: Track how well each agent and the overall system performs
In the next lesson, we'll explore how to create effective agent workflows using the Process component.
+152
View File
@@ -0,0 +1,152 @@
---
title: "Agent Process"
description: "Understanding agent workflows and processes"
icon: "diagram-project"
---
# Agent Process
The Process component in AI agent systems defines how agents work together and the flow of information between them. Think of it as the "playbook" that coordinates how agents complete tasks.
## What is an Agent Process?
<CardGroup cols={1}>
<Card title="Definition" icon="route">
A process is a structured workflow that defines the sequence of steps, decision points, and information flow between agents to complete a task.
</Card>
</CardGroup>
## Process Flow Basics
A simple process flow might look like this:
```mermaid
graph LR
A[Start] --> B[Gather Information]
B --> C[Process Information]
C --> D[Make Decision]
D --> E[Take Action]
E --> F[Report Results]
```
Each step could be handled by a different agent or by the same agent in different stages.
## Types of Process Flows
### 1. Sequential Process
Agents work in a straight line, one after another.
```mermaid
graph LR
A[Agent 1] --> B[Agent 2]
B --> C[Agent 3]
C --> D[Complete]
```
**Best for**: Tasks with clear, linear stages
### 2. Parallel Process
Multiple agents work simultaneously on different parts of a task.
```mermaid
graph TD
A[Start] --> B[Agent 1]
A --> C[Agent 2]
A --> D[Agent 3]
B --> E[Combine Results]
C --> E
D --> E
E --> F[Complete]
```
**Best for**: Tasks that can be broken into independent pieces
### 3. Conditional Process
The workflow changes based on decisions or conditions.
```mermaid
graph TD
A[Start] --> B{Decision Point}
B -->|Condition A| C[Agent 1]
B -->|Condition B| D[Agent 2]
C --> E[Complete]
D --> E
```
**Best for**: Tasks requiring different approaches based on circumstances
## Implementing Process in PraisonAI
Here's a simple example of creating a process in PraisonAI:
```python
from praisonaiagents import Agent, Process, PraisonAIAgents
# Create agents
research_agent = Agent(
name="Researcher",
instructions="Research the topic and gather key information about AI"
)
writing_agent = Agent(
name="Writer",
instructions="Create content based on the research"
)
editing_agent = Agent(
name="Editor",
instructions="Review and improve the content"
)
# Create the multi-agent system with the process
agents = PraisonAIAgents(
agents=[research_agent, writing_agent, editing_agent],
process="hierarchical"
)
# Start the process
agents.start()
```
## Process Best Practices
<CardGroup cols={2}>
<Card title="Clear Step Definitions" icon="list-check">
Define exactly what each step should accomplish
</Card>
<Card title="Error Handling" icon="bug">
Include steps for handling unexpected situations
</Card>
<Card title="Feedback Loops" icon="repeat">
Allow agents to request clarification when needed
</Card>
<Card title="Modular Design" icon="cubes">
Create reusable process components
</Card>
</CardGroup>
<Tip>
Start with simple processes and gradually add complexity as you become more comfortable with the system.
</Tip>
## Monitoring Process Execution
It's important to track how your processes are running:
```python
agents = PraisonAIAgents(
agents=[research_agent, writing_agent, editing_agent],
process=content_process,
verbose=True # Enables detailed logging
)
```
This will provide information about:
- Which step is currently running
- The inputs and outputs of each step
- Any errors or issues encountered
In the next lesson, we'll explore how to use knowledge bases to enhance agent capabilities.
+190
View File
@@ -0,0 +1,190 @@
---
title: "Knowledge Bases"
description: "Enhancing agents with specialized knowledge"
icon: "book"
---
# Knowledge Bases
Knowledge bases provide agents with specialized information beyond their training data. They help agents answer specific questions, follow guidelines, or work within defined domains.
## What is a Knowledge Base?
<CardGroup cols={1}>
<Card title="Definition" icon="database">
A knowledge base is a structured collection of information that an agent can access to answer questions or make decisions.
</Card>
</CardGroup>
Think of a knowledge base as a specialized reference library for your agent.
## Why Use Knowledge Bases?
<CardGroup cols={2}>
<Card title="Domain Expertise" icon="user-graduate">
Provide specialized information for specific fields
</Card>
<Card title="Current Information" icon="clock">
Include data beyond the agent's training cutoff
</Card>
<Card title="Custom Guidelines" icon="list">
Define rules and policies for the agent to follow
</Card>
<Card title="Consistent Responses" icon="equals">
Ensure agents provide standardized answers
</Card>
</CardGroup>
## Types of Knowledge Bases
### 1. Document Collections
Text documents, articles, guides, or manuals that agents can reference.
```mermaid
graph TD
A[Query] --> B[Search Documents]
B --> C[Find Relevant Content]
C --> D[Generate Response]
```
### 2. Structured Data
Databases, tables, or other structured formats that organize information systematically.
<CardGroup cols={1}>
<Card title="Examples" icon="table">
- Product catalogs with specifications
- Customer information databases
- Statistical data collections
- Reference tables for compliance information
</Card>
</CardGroup>
### 3. Vector Databases
Special databases that store information as numerical representations (vectors) for semantic search.
```mermaid
graph TD
A[User Question] --> B[Convert to Vector]
B --> C[Find Similar Vectors]
C --> D[Retrieve Related Information]
D --> E[Generate Answer]
```
## Implementing Knowledge Bases in PraisonAI
Here's an example of how to use a knowledge base with an agent:
```python
from praisonaiagents import Agent
agent = Agent(
name="Knowledge Agent",
instructions="You answer questions based on the provided knowledge.",
knowledge=["small.pdf"]
)
agent.start("What is KAG in one line?")
```
## Advanced Configuration
For more control over the knowledge base, you can specify a configuration:
```python
from praisonaiagents import Agent
config = {
"vector_store": {
"provider": "chroma",
"config": {
"collection_name": "custom_knowledge",
"path": ".praison",
}
}
}
agent = Agent(
name="Knowledge Agent",
instructions="You answer questions based on the provided knowledge.",
knowledge=["small.pdf"],
knowledge_config=config
)
agent.start("What is KAG in one line?")
```
## Knowledge Retrieval Process
When an agent uses a knowledge base, this typical process occurs:
```mermaid
graph LR
A[User Question] --> B[Query Processing]
B --> C[Search Knowledge Base]
C --> D[Rank Results]
D --> E[Synthesize Answer]
```
1. **Query Processing**: The user's question is analyzed
2. **Search**: The system searches the knowledge base for relevant information
3. **Ranking**: Results are ranked by relevance
4. **Synthesis**: The agent creates an answer using the retrieved information
## Best Practices for Knowledge Bases
<CardGroup cols={2}>
<Card title="Keep Information Current" icon="arrows-rotate">
Regularly update your knowledge base
</Card>
<Card title="Organize Logically" icon="folder-tree">
Structure information in intuitive categories
</Card>
<Card title="Prioritize Quality" icon="star">
Focus on accurate, high-quality information
</Card>
<Card title="Include Examples" icon="list">
Add examples to illustrate complex concepts
</Card>
</CardGroup>
## When to Use Knowledge Bases
Knowledge bases are particularly valuable when:
1. Your agent needs to reference specific information that may change over time
2. You need to ensure consistent answers to common questions
3. Your agent needs to follow specific guidelines or protocols
4. You want to provide expertise in specialized domains
<Tip>
Start with a small knowledge base focusing on the most important information, then expand as needed.
</Tip>
## Creating a Simple Knowledge Base
For beginners, you can start with a simple text-based knowledge base:
```
# Company FAQ Knowledge Base
## Return Policy
Our return policy allows customers to return products within 30 days of purchase for a full refund.
## Shipping Information
Standard shipping takes 3-5 business days. Express shipping takes 1-2 business days.
## Product Warranty
All products come with a 1-year limited warranty covering manufacturing defects.
```
Save this as a text file and add it to your knowledge base:
```python
kb = KnowledgeBase()
kb.add_document("company_faq.txt")
```
In the next lesson, we'll explore how agents handle tasks and the task management process.
+274
View File
@@ -0,0 +1,274 @@
---
title: "Agent Tasks"
description: "Understanding how agents handle and manage tasks"
icon: "clipboard-list"
---
# Agent Tasks
Tasks are the specific units of work that AI agents perform. Understanding how to define and manage tasks is essential for creating effective agent systems.
## What is an Agent Task?
<CardGroup cols={1}>
<Card title="Definition" icon="list-check">
A task is a specific, well-defined piece of work assigned to an agent with clear inputs, expected outputs, and success criteria.
</Card>
</CardGroup>
Just as human jobs are broken into specific responsibilities, agent systems work best when complex goals are divided into manageable tasks.
## Anatomy of a Task
A well-defined task includes:
<CardGroup cols={2}>
<Card title="Objective" icon="bullseye">
What the task should accomplish
</Card>
<Card title="Inputs" icon="arrow-right-to-bracket">
Information provided to complete the task
</Card>
<Card title="Process" icon="gears">
Steps to follow or approach to take
</Card>
<Card title="Outputs" icon="arrow-right-from-bracket">
Expected results or deliverables
</Card>
</CardGroup>
## Task Types
### 1. Information Tasks
These tasks involve finding, analyzing, or summarizing information.
**Examples:**
- Research a topic
- Summarize a document
- Extract data from text
- Answer questions
### 2. Creation Tasks
These tasks involve generating new content.
**Examples:**
- Write an article
- Create a marketing plan
- Generate images (with appropriate tools)
- Design a workflow
### 3. Analysis Tasks
These tasks involve evaluating information and drawing conclusions.
**Examples:**
- Analyze data trends
- Review content for quality
- Evaluate options
- Identify patterns
### 4. Interaction Tasks
These tasks involve communicating or working with users or other systems.
**Examples:**
- Answer customer questions
- Guide users through processes
- Collect information from users
- Notify about events
## Creating Tasks in PraisonAI
### Task Flow
The typical lifecycle of a task follows this pattern:
```mermaid
graph LR
A[Define Task] --> B[Assign to Agent]
B --> C[Execute Task]
C --> D[Return Results]
D --> E[Evaluate Success]
```
### Task Configuration
<CodeGroup>
```python Basic
task = Task(
description="Research AI trends",
expected_output="Summary report",
agent=research_agent
)
```
```python Advanced
task = Task(
description="Analyze market data",
expected_output="Detailed analysis",
agent=analyst_agent,
tools=[AnalysisTool()],
output_file="analysis.md",
async_execution=True
)
```
</CodeGroup>
# Understanding Tasks
<br />
```mermaid
graph LR
%% Task Flow Steps
Start([▶ Start]) --> TaskDef
TaskDef --> AgentAssign
AgentAssign --> Exec
Exec --> Output([✓ Output])
%% Define subgraphs for each step
subgraph TaskDef[" "]
TD_Icon[📋 Task Definition]
TD_Desc[Description & Requirements]
TD_Icon --- TD_Desc
style TD_Icon fill:#2D3047,stroke:#7C90A0,color:#fff
style TD_Desc fill:#5C80BC,stroke:#7C90A0,color:#fff
end
subgraph AgentAssign[" "]
AA_Icon[🤖 Agent Assignment]
AA_Desc[Matching & Delegation]
AA_Icon --- AA_Desc
style AA_Icon fill:#2D3047,stroke:#7C90A0,color:#fff
style AA_Desc fill:#5C80BC,stroke:#7C90A0,color:#fff
end
subgraph Exec[" "]
E_Icon[⚙️ Execution]
E_Desc[Processing & Tools]
E_Icon --- E_Desc
style E_Icon fill:#2D3047,stroke:#7C90A0,color:#fff
style E_Desc fill:#5C80BC,stroke:#7C90A0,color:#fff
end
%% Styling for main elements
style Start fill:#2D3047,stroke:#7C90A0,color:#fff
style Output fill:#2D3047,stroke:#7C90A0,color:#fff
%% Style for containers
style TaskDef fill:#1B1F3B,stroke:#7C90A0,color:#fff
style AgentAssign fill:#1B1F3B,stroke:#7C90A0,color:#fff
style Exec fill:#1B1F3B,stroke:#7C90A0,color:#fff
%% Global styles
classDef default fill:#2D3047,stroke:#7C90A0,color:#fff
linkStyle default stroke:#7C90A0,stroke-width:2px
```
<br /><br />
```mermaid
graph LR
%% Task States
Pending([📥 Pending]) --> InProgress([⚡ In Progress])
InProgress --> Completed([✅ Completed])
InProgress --> Failed([❌ Failed])
%% Styling
style Pending fill:#2D3047,stroke:#7C90A0,color:#fff
style InProgress fill:#5C80BC,stroke:#7C90A0,color:#fff
style Completed fill:#2D3047,stroke:#7C90A0,color:#fff
style Failed fill:#2D3047,stroke:#7C90A0,color:#fff
%% Global styles
classDef default fill:#2D3047,stroke:#7C90A0,color:#fff
linkStyle default stroke:#7C90A0,stroke-width:2px
```
## Task Types
<Steps>
<Step title="Basic Task">
Simple, single-operation tasks with clear inputs and outputs
</Step>
<Step title="Decision Task">
Tasks involving choices and conditional paths
```python
decision_task = Task(
type="decision",
conditions={
"success": ["next_task"],
"failure": ["error_task"]
}
)
```
</Step>
<Step title="Loop Task">
Repetitive operations over collections
```python
loop_task = Task(
type="loop",
items=data_list,
operation="process_item"
)
```
</Step>
</Steps>
## Task Relationships
<Warning>
Properly managing task dependencies is crucial for complex workflows. Always ensure proper context sharing and error handling.
</Warning>
### Context Sharing
```python
task_a = Task(name="research")
task_b = Task(
name="analyze",
context=[task_a] # Uses task_a's output
)
```
## Task Best Practices
<CardGroup cols={2}>
<Card title="Be Specific" icon="magnifying-glass">
Clearly define what the task should accomplish
</Card>
<Card title="One Goal Per Task" icon="check-double">
Each task should focus on a single objective
</Card>
<Card title="Provide Context" icon="circle-info">
Include necessary background information
</Card>
<Card title="Define Success" icon="trophy">
Specify what a successful outcome looks like
</Card>
</CardGroup>
<Tip>
Break complex goals into multiple smaller tasks rather than creating one large, complex task.
</Tip>
## Common Task Mistakes
<CardGroup cols={2}>
<Card title="Vague Instructions" icon="question">
Unclear about what the agent should do
</Card>
<Card title="Too Many Objectives" icon="list-ol">
Asking for too many things in one task
</Card>
<Card title="Missing Context" icon="puzzle-piece-missing">
Not providing necessary background information
</Card>
<Card title="Unrealistic Expectations" icon="mountain-sun">
Asking for tasks beyond agent capabilities
</Card>
</CardGroup>
In the next lesson, we'll learn about creating your first complete agent application.
@@ -0,0 +1,172 @@
---
title: "Creating Your First Agent"
description: "A step-by-step guide to building your first AI agent"
icon: "robot"
---
# Creating Your First Agent
In this lesson, we'll walk through the process of building a simple AI agent. We'll focus on practical implementation without complex programming.
## What We'll Build
We'll create a basic research assistant agent that can:
- Understand simple instructions
- Respond to questions
- Provide helpful information
## Prerequisites
Before you begin, make sure you have:
1. A basic understanding of the concepts from previous lessons
2. Python installed on your computer (if following the code examples)
3. An OpenAI API key (or access to another supported language model)
## Step 1: Installation
First, install the PraisonAI package:
```bash
pip install praisonaiagents
```
## Step 2: Setup Your Environment
Create a file called `first_agent.py` and set up your API key:
```python
import os
from praisonaiagents import Agent
# Set your API key
# Option 1: Set it in your environment (recommended)
# export OPENAI_API_KEY=your_key_here
# Option 2: Set it in your code (not recommended for production)
# os.environ["OPENAI_API_KEY"] = "your_key_here"
```
## Step 3: Define Your Agent
Now, let's create a simple agent:
```python
# Create a research assistant agent
research_assistant = Agent(
name="ResearchAssistant",
instructions="""
You are a helpful research assistant that provides clear,
accurate information on various topics. When answering:
1. Be concise and to the point
2. Explain complex concepts in simple terms
3. When appropriate, organize information with bullet points
4. If you don't know something, admit it instead of guessing
"""
)
```
## Step 4: Start Your Agent
Now let's use our agent to answer a question:
```python
# Start the agent with a specific query
response = research_assistant.start("Explain how solar panels work in simple terms")
# Print the response
print(response)
```
## Step 5: Run Your Agent
Save the file and run it from your terminal:
```bash
python first_agent.py
```
You should see the agent's response explaining how solar panels work in simple terms.
## Experimenting with Your Agent
Try changing the question to see how your agent responds to different topics:
```python
# Try different questions
response = research_assistant.start("What are the benefits of exercise?")
# or
response = research_assistant.start("How does artificial intelligence work?")
```
## Modifying Agent Behavior
You can change how your agent behaves by adjusting its instructions:
```python
# Create an agent with different instructions
creative_writer = Agent(
name="CreativeWriter",
instructions="""
You are a creative writer that specializes in short, engaging stories.
Your writing should:
1. Include vivid descriptions
2. Have interesting characters
3. Include some dialogue
4. Have a clear beginning, middle, and end
"""
)
# Ask for a story
story = creative_writer.start("Write a short story about a lost dog finding its way home")
print(story)
```
## Examining How It Works
What's happening behind the scenes:
1. The agent receives your instructions and query
2. The language model (like GPT-4) processes the information
3. The model generates a response based on the instructions and query
4. The response is returned to you
```mermaid
graph TD
A[Your Instructions] --> B[Agent]
C[Your Query] --> B
B --> D[Language Model]
D --> E[Generated Response]
E --> F[Output to You]
```
## Common Challenges
If you encounter issues, check these common problems:
<CardGroup cols={2}>
<Card title="API Key Issues" icon="key">
Make sure your API key is set correctly
</Card>
<Card title="Connection Problems" icon="wifi">
Check your internet connection
</Card>
<Card title="Unclear Instructions" icon="circle-question">
Try making your instructions more specific
</Card>
<Card title="Rate Limits" icon="hand">
You might be making too many API calls
</Card>
</CardGroup>
## Next Steps
Now that you've created your first agent, you can:
- Experiment with different instructions
- Try more complex queries
- Add specialized capabilities (we'll cover this in upcoming lessons)
- Create agents for specific use cases
Congratulations on creating your first AI agent! In the next lesson, we'll explore how to add tools to enhance your agent's capabilities.
@@ -0,0 +1,275 @@
---
title: "Adding Tools to Agents"
description: "Enhancing your agents with specialized capabilities"
icon: "screwdriver-wrench"
---
# Adding Tools to Agents
In this lesson, we'll learn how to enhance your agents by adding tools. Tools allow agents to perform specific actions beyond just generating text, making them much more useful for real-world tasks.
## What You'll Learn
By the end of this lesson, you'll understand:
- What agent tools are and why they're useful
- How to create simple tools for your agents
- How to integrate tools with your agents
- Best practices for tool design
## Understanding Agent Tools
Tools give your agents the ability to:
- Perform calculations
- Access specific information
- Interact with external systems
- Generate different types of content
<Tabs>
<Tab title="Code">
<Steps>
<Step title="Install PraisonAI">
Install the core package:
```bash Terminal
pip install praisonaiagents duckduckgo-search
```
</Step>
<Step title="Configure Environment">
```bash Terminal
export OPENAI_API_KEY=your_openai_key
```
Generate your OpenAI API key from [OpenAI](https://platform.openai.com/api-keys)
Use other LLM providers like Ollama, Anthropic, Groq, Google, etc. Please refer to the [Models](/models) for more information.
</Step>
<Step title="Create Agent with Tool">
Create `app.py`
<CodeGroup>
```python Single Agent
from praisonaiagents import Agent
from duckduckgo_search import DDGS
# 1. Define the tool
def internet_search_tool(query: str):
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
# 2. Assign the tool to an agent
search_agent = Agent(
instructions="Perform internet searches to collect relevant information.",
tools=[internet_search_tool] # <--- Tool Assignment
)
# 3. Start Agent
search_agent.start("Search about AI job trends in 2025")
```
```python Multiple Agents
from praisonaiagents import Agent, PraisonAIAgents
from duckduckgo_search import DDGS
# 1. Define the tool
def internet_search_tool(query: str):
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
# 2. Assign the tool to an agent
search_agent = Agent(
instructions="Search about AI job trends in 2025",
tools=[internet_search_tool] # <--- Tool Assignment
)
blog_agent = Agent(
instructions="Write a blog article based on the previous agent's search results."
)
# 3. Start Agents
agents = PraisonAIAgents(agents=[search_agent, blog_agent])
agents.start()
```
</CodeGroup>
</Step>
<Step title="Start Agents">
Execute your script:
```bash Terminal
python app.py
```
</Step>
</Steps>
</Tab>
<Tab title="No Code">
<Steps>
<Step title="Install PraisonAI">
Install the core package and duckduckgo_search package:
```bash Terminal
pip install praisonai duckduckgo_search
```
</Step>
<Step title="Create Custom Tool">
<Info>
To add additional tools/features you need some coding which can be generated using ChatGPT or any LLM
</Info>
Create a new file `tools.py` with the following content:
```python
from duckduckgo_search import DDGS
from typing import List, Dict
# 1. Tool
def internet_search_tool(query: str) -> List[Dict]:
"""
Perform Internet Search
"""
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
```
</Step>
<Step title="Create Agent">
Create a new file `agents.yaml` with the following content:
```yaml
framework: praisonai
topic: create movie script about cat in mars
roles:
scriptwriter:
backstory: Expert in dialogue and script structure, translating concepts into
scripts.
goal: Write a movie script about a cat in Mars
role: Scriptwriter
tools:
- internet_search_tool # <-- Tool assigned to Agent here
tasks:
scriptwriting_task:
description: Turn the story concept into a production-ready movie script,
including dialogue and scene details.
expected_output: Final movie script with dialogue and scene details.
```
</Step>
<Step title="Start Agents">
Execute your script:
```bash Terminal
praisonai agents.yaml
```
</Step>
</Steps>
</Tab>
</Tabs>
## Creating Custom Tool
<Steps>
<Step>
Create any function that you want to use as a tool, that performs a specific task.
```python
from duckduckgo_search import DDGS
def internet_search_tool(query: str):
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
```
</Step>
<Step>
Assign the tool to an agent
```python
data_agent = Agent(
instructions="Search about AI job trends in 2025",
tools=[internet_search_tool], # <-- Tool Assignment
)
```
</Step>
</Steps>
<Card title="That's it!">
<Check>You have created a custom tool and assigned it to an agent.</Check>
</Card>
## When Does the Agent Use Tools?
The agent decides when to use tools based on:
1. The nature of the user's request
2. The tools available to it
3. The instructions you've provided
If your agent isn't using tools when expected, you might need to:
- Make your instructions more explicit about when to use tools
- Provide more descriptive tool definitions
- Ensure the tools are appropriate for the task
## Tool Best Practices
<CardGroup cols={2}>
<Card title="Specific Purpose" icon="bullseye">
Each tool should have a clear, specific purpose
</Card>
<Card title="Error Handling" icon="shield-check">
Tools should handle errors gracefully
</Card>
<Card title="Descriptive Names" icon="tag">
Use clear names that indicate functionality
</Card>
<Card title="Clear Documentation" icon="file-lines">
Include detailed descriptions and examples
</Card>
</CardGroup>
## Real-World Tool Examples
In production systems, you might create tools for:
<CardGroup cols={2}>
<Card title="Database Access" icon="database">
Retrieve or store information in databases
</Card>
<Card title="API Integration" icon="link">
Connect to external services
</Card>
<Card title="File Operations" icon="folder">
Read from or write to files
</Card>
<Card title="Image Generation" icon="image">
Create images based on descriptions
</Card>
</CardGroup>
## Advanced Tool Concepts
As you become more comfortable with tools, you can explore:
- Tools that call other tools
- Tools with complex parameters
- Tools that maintain state
- Dynamically generated tools
In the next lesson, we'll explore how to create a multi-agent system for more complex tasks.
@@ -0,0 +1,218 @@
---
title: "Building a Multi-Agent System"
description: "Creating a system with multiple cooperative agents"
icon: "users"
---
# Building a Multi-Agent System
In this lesson, we'll create a simple multi-agent system where several agents work together to accomplish a task. This approach allows you to divide complex problems into smaller, more manageable pieces.
## What We'll Build
We'll create a content creation system with three specialized agents:
1. A research agent to gather information
2. A writing agent to create content
3. An editing agent to improve and refine the content
## Step 1: Setting Up
First, let's import the necessary modules and set up our environment:
```python
from praisonaiagents import Agent, PraisonAIAgents
# Make sure your API key is set in your environment:
# export OPENAI_API_KEY=your_openai_key
```
## Step 2: Creating Specialized Agents
Now, let's create our three specialized agents:
```python
# Research Agent
research_agent = Agent(
name="Researcher",
instructions="""
You are a research specialist who excels at finding relevant information.
Your job is to:
1. Thoroughly research the given topic
2. Identify key facts, statistics, and insights
3. Organize the information in a clear, structured format
4. Provide accurate information with no fabrications
5. Focus on the most relevant and current information
"""
)
# Writing Agent
writing_agent = Agent(
name="Writer",
instructions="""
You are a content writer who creates engaging, reader-friendly content.
Your job is to:
1. Use the research provided to create well-structured content
2. Write in a clear, engaging style
3. Include an attention-grabbing introduction
4. Organize the content with appropriate headings
5. Conclude with a summary and call-to-action when appropriate
"""
)
# Editing Agent
editing_agent = Agent(
name="Editor",
instructions="""
You are an editor who refines and improves content.
Your job is to:
1. Correct any grammatical or spelling errors
2. Improve clarity and flow
3. Ensure consistency in tone and style
4. Check for logical structure and organization
5. Enhance readability for the target audience
"""
)
```
## Step 3: Creating the Multi-Agent System
Now, let's combine these agents into a multi-agent system:
```python
# Create a multi-agent system
content_team = PraisonAIAgents(
agents=[research_agent, writing_agent, editing_agent]
)
```
## Step 4: Setting Up the Workflow
Next, we need to define how our agents will work together:
```python
# Define a topic
topic = "The Benefits of Regular Exercise"
# Start the multi-agent process
results = content_team.start(
f"""
Task: Create a comprehensive blog post about {topic}
Process:
1. Researcher: Research {topic} and provide key information including:
- Main benefits of exercise (physical and mental)
- Recommended exercise guidelines
- Scientific studies supporting the benefits
- Common misconceptions
2. Writer: Use the research to create a 500-word blog post about {topic} with:
- An engaging introduction
- Clear sections with headings
- Practical advice for readers
- A compelling conclusion
3. Editor: Review and improve the blog post by:
- Correcting any errors
- Enhancing clarity and flow
- Ensuring a consistent tone
- Making the content more engaging
"""
)
# Print the final result
print(results)
```
## Understanding the Workflow
Let's examine how the multi-agent system works:
```mermaid
graph TD
A[Start] --> B[Research Agent]
B --> C[Writing Agent]
C --> D[Editing Agent]
D --> E[Final Output]
```
1. The research agent gathers and organizes relevant information
2. The writing agent uses that research to create the initial content
3. The editing agent refines and improves the content
4. The final polished content is returned
## Customizing Agent Interactions
You can customize how agents interact by modifying the process instructions. For example, you could add feedback loops:
```python
process_with_feedback = """
Task: Create a comprehensive blog post about {topic}
Process:
1. Researcher: Research {topic} and provide key information
2. Writer: Use the research to create a blog post
3. Editor: Review the blog post and provide feedback
4. Writer: Revise the blog post based on the editor's feedback
5. Editor: Make final improvements to the revised blog post
"""
```
## Alternative Agent Configurations
You can organize multi-agent systems in different ways:
### Parallel Processing
```python
parallel_process = """
Task: Create a marketing campaign for a new product
Process:
1. Market Researcher: Research the target market and competitors
Content Researcher: Research the product features and benefits
[These tasks happen in parallel]
2. Strategy Agent: Use both research results to create a marketing strategy
3. Content Creator: Create the marketing materials based on the strategy
"""
```
### Expert Panel
```python
expert_panel = """
Task: Evaluate a business idea
Process:
1. Financial Expert: Analyze financial viability
Market Expert: Analyze market potential
Technical Expert: Analyze technical feasibility
[These assessments happen in parallel]
2. Coordinator: Compile all expert opinions into a final recommendation
"""
```
## Best Practices for Multi-Agent Systems
<CardGroup cols={2}>
<Card title="Clear Role Definition" icon="user-tag">
Define exactly what each agent is responsible for
</Card>
<Card title="Explicit Handoffs" icon="arrow-right-arrow-left">
Specify how information passes between agents
</Card>
<Card title="Avoid Redundancy" icon="copy">
Don't have multiple agents do the same work
</Card>
<Card title="Include Error Handling" icon="triangle-exclamation">
Plan for cases where an agent might fail
</Card>
</CardGroup>
In the next lesson, we'll learn how to create a conversational agent that can maintain context across multiple interactions.
@@ -0,0 +1,193 @@
---
title: "Building Conversational Agents"
description: "Creating agents that maintain context in conversations"
icon: "comments"
---
# Building Conversational Agents
In this lesson, we'll learn how to create conversational agents that can maintain context across multiple interactions. This is essential for creating assistants that feel natural to interact with.
## What Makes a Good Conversational Agent?
A good conversational agent should:
- Remember previous parts of the conversation
- Understand context and references
- Provide coherent, relevant responses
- Maintain a consistent personality
## Creating a Simple Conversational Agent
Let's build a basic conversational agent:
```python
# Note: TODO: This Feature yet to be developed
from praisonaiagents import Agent
# Create a conversational agent
chat_agent = Agent(
name="Conversational Assistant",
instructions="""
You are a friendly, helpful conversational assistant.
When chatting with users:
1. Maintain a warm, friendly tone
2. Remember information shared earlier in the conversation
3. Ask clarifying questions when needed
4. Keep responses concise but informative
5. Be helpful while respecting boundaries
"""
)
# Start a conversation
response = chat_agent.start("Hi there! My name is Jamie.")
print(response)
# Continue the conversation
response = chat_agent.continue("What can you help me with today?")
print(response)
# The agent should remember the user's name
response = chat_agent.continue("Can you remember my name?")
print(response)
```
## How Context Works
PraisonAI automatically manages conversation context for you:
```mermaid
graph TD
A[User Message 1] --> B[Agent]
B --> C[Response 1]
D[User Message 2] --> E[Agent + Context]
E --> F[Response 2]
G[User Message 3] --> H[Agent + More Context]
H --> I[Response 3]
```
The agent maintains a memory of the conversation, allowing it to refer back to previous messages.
## Conversation Settings
You can customize how your conversational agent behaves:
```python
# Create an agent with specific conversation settings
custom_chat_agent = Agent(
name="Custom Chat Assistant",
instructions="You are a helpful assistant",
memory_size=10, # Remember the last 10 messages
temperature=0.7 # Slightly more creative in responses
)
```
## Handling Different Types of Conversations
Different use cases require different conversation styles:
<CardGroup cols={2}>
<Card title="Customer Support" icon="headset">
- Professional and helpful tone
- Focus on problem resolution
- Remember customer details
</Card>
<Card title="Educational Tutor" icon="graduation-cap">
- Patient and explanatory
- Builds on previous lessons
- Adjusts to learning pace
</Card>
<Card title="Personal Assistant" icon="calendar">
- Remembers preferences
- Provides reminders
- Handles scheduling
</Card>
<Card title="Companion Chat" icon="user-group">
- More casual tone
- Focuses on engagement
- Shows personality
</Card>
</CardGroup>
## Example: Customer Support Agent
Let's create a specialized customer support agent:
```python
support_agent = Agent(
name="Support Agent",
instructions="""
You are a customer support specialist for a tech company.
When helping customers:
1. Greet them professionally
2. Show empathy for their issues
3. Ask for necessary information to troubleshoot
4. Provide clear step-by-step solutions
5. Confirm if the issue is resolved
6. End with an offer for additional help
Remember product details and customer information throughout the conversation.
"""
)
# Example conversation
print(support_agent.start("Hi, I'm having trouble logging into my account."))
print(support_agent.continue("My username is user123."))
print(support_agent.continue("I've tried resetting my password but I'm not receiving the email."))
```
## Building Multi-Turn Conversations
To create engaging multi-turn conversations, consider:
1. **Appropriate follow-up questions**: Keep the conversation flowing
2. **Acknowledgment**: Reference what the user has said
3. **Progressive disclosure**: Don't overwhelm with information at once
4. **Conversation repair**: Gracefully handle misunderstandings
## Example: Multi-Turn Educational Conversation
```python
tutor_agent = Agent(
name="Math Tutor",
instructions="""
You are a patient, encouraging math tutor.
When teaching:
1. Gauge the student's current understanding
2. Explain concepts using clear, simple language
3. Provide examples to illustrate points
4. Ask questions to check understanding
5. Give positive reinforcement for progress
Adapt your explanations based on the student's responses.
"""
)
# Example tutoring session
print(tutor_agent.start("Can you help me understand algebra?"))
print(tutor_agent.continue("I'm struggling with equations like 2x + 5 = 13"))
print(tutor_agent.continue("So I subtract 5 from both sides first?"))
print(tutor_agent.continue("Then I divide by 2 to get x = 4?"))
print(tutor_agent.continue("Could you give me another example to practice?"))
```
## Conversation Best Practices
<CardGroup cols={2}>
<Card title="Clear Transitions" icon="arrow-right">
Signal when changing topics
</Card>
<Card title="Manageable Chunks" icon="layer-group">
Break complex information into smaller pieces
</Card>
<Card title="Engagement Checks" icon="hand">
Periodically confirm understanding
</Card>
<Card title="Personality Consistency" icon="masks-theater">
Maintain a consistent tone and style
</Card>
</CardGroup>
In the next lesson, we'll explore how to build agents that can search and retrieve information from external sources.
+216
View File
@@ -0,0 +1,216 @@
---
title: "Building Research Agents"
description: "Creating agents that can gather and analyze information"
icon: "magnifying-glass"
---
# Building Research Agents
In this lesson, we'll build agents specialized in gathering, analyzing, and summarizing information. Research agents are valuable for quickly obtaining insights on various topics.
## What is a Research Agent?
A research agent is designed to:
- Find relevant information on specific topics
- Analyze and synthesize data
- Present findings in a clear, structured format
- Answer questions based on gathered information
## Creating a Basic Research Agent
Let's start by building a simple research agent:
```python
from praisonaiagents import Agent
# Create a basic research agent
research_agent = Agent(
name="ResearchAgent",
instructions="""
You are a research specialist who finds and summarizes information.
When researching topics:
1. Focus on finding accurate, current information
2. Organize findings in a logical structure
3. Identify key points and insights
4. Cite sources when available
5. Present information in a clear, concise format
"""
)
# Use the research agent
research_results = research_agent.start("Research the impact of renewable energy on reducing carbon emissions")
print(research_results)
```
## Adding Web Search Capability
To make our research agent more powerful, let's add web search capability:
```python
from praisonaiagents import Agent, Tool
# Define a web search function (simulated for this example)
def web_search(query):
"""
Simulated web search function.
In a real application, this would connect to a search API.
Args:
query (str): The search query
Returns:
str: Search results
"""
# This is just a simulation - in a real application, you'd call a search API
if "renewable energy" in query.lower():
return """
Search results for 'renewable energy carbon emissions':
1. According to the IEA, renewable energy prevented 2.1 billion tonnes of CO2 emissions in 2022.
2. Solar and wind power generate electricity with 95-98% lower carbon emissions than coal-based electricity.
3. The IPCC reports that renewable energy could deliver more than half of the emission reductions needed by 2030.
"""
else:
return f"Search results for '{query}' (simulated data)"
# Create the web search tool
search_tool = Tool(
name="web_search",
function=web_search,
description="Search the web for current information on a topic"
)
# Create a research agent with web search capability
enhanced_research_agent = Agent(
name="EnhancedResearchAgent",
instructions="""
You are a research specialist who finds and summarizes information.
When researching topics:
1. Use the web_search tool to find current information
2. Analyze and synthesize the search results
3. Organize findings in a logical structure
4. Identify key points and insights
5. Present information in a clear, concise format
""",
tools=[search_tool]
)
# Use the enhanced research agent
enhanced_results = enhanced_research_agent.start("What is the impact of renewable energy on carbon emissions?")
print(enhanced_results)
```
## Research Agent with Structured Output
For more organized research results, we can instruct the agent to provide structured output:
```python
structured_research_agent = Agent(
name="StructuredResearchAgent",
instructions="""
You are a research specialist who finds and organizes information.
When researching topics:
1. Use available tools to find current information
2. Analyze and synthesize the findings
Always structure your response in this format:
## Summary
[Brief 2-3 sentence overview of the topic]
## Key Facts
- [Important fact 1]
- [Important fact 2]
- [Important fact 3]
## Analysis
[Deeper analysis of the information, including implications]
## Sources
[List of sources if available]
""",
tools=[search_tool]
)
# Use the structured research agent
structured_results = structured_research_agent.start("Research the latest advancements in quantum computing")
print(structured_results)
```
## Specialized Research Agents
Different research tasks require different approaches. Here are some specialized research agents:
### Comparison Research Agent
```python
comparison_agent = Agent(
name="ComparisonAgent",
instructions="""
You are a research specialist who compares different options or topics.
When comparing items:
1. Identify the key criteria for comparison
2. Research each option thoroughly
3. Create a clear side-by-side comparison
4. Highlight advantages and disadvantages of each option
5. Provide a balanced conclusion
Present your findings in a structured table format when appropriate.
""",
tools=[search_tool]
)
# Use the comparison agent
comparison_results = comparison_agent.start("Compare solar and wind energy for residential use")
print(comparison_results)
```
### Literature Review Agent
```python
literature_agent = Agent(
name="LiteratureAgent",
instructions="""
You are a research specialist who reviews academic and professional literature.
When reviewing literature:
1. Identify key papers, articles, and studies on the topic
2. Summarize the main findings and methodologies
3. Identify trends, agreements, and contradictions
4. Evaluate the strength of evidence
5. Highlight gaps in current research
Structure your review in a clear, academic format.
""",
tools=[search_tool]
)
# Use the literature review agent
literature_results = literature_agent.start("Review recent research on artificial intelligence in healthcare")
print(literature_results)
```
## Research Process Best Practices
<CardGroup cols={2}>
<Card title="Define Scope" icon="bullseye">
Set clear boundaries for the research
</Card>
<Card title="Verify Information" icon="check-double">
Cross-check facts from multiple sources
</Card>
<Card title="Consider Bias" icon="scale-balanced">
Be aware of potential biases in sources
</Card>
<Card title="Prioritize Relevance" icon="filter">
Focus on information most relevant to the query
</Card>
</CardGroup>
In the next lesson, we'll explore how to build agents that can assist with creative tasks like content creation.
@@ -0,0 +1,252 @@
---
title: "Content Creation Agents"
description: "Building agents that generate various types of content"
icon: "pen-to-square"
---
# Content Creation Agents
Content creation agents can help generate various types of content, from blog posts to marketing materials. In this lesson, we'll learn how to build effective content creation agents.
## What is a Content Creation Agent?
A content creation agent is designed to:
- Generate written content based on specific requirements
- Structure content in appropriate formats
- Adapt tone and style to match the target audience
- Create content that achieves specific goals (inform, persuade, entertain)
## Creating a Basic Content Creation Agent
Let's start with a simple content creation agent:
```python
from praisonaiagents import Agent
# Create a basic content creation agent
content_agent = Agent(
name="ContentCreator",
instructions="""
You are a versatile content creator who specializes in writing engaging material.
When creating content:
1. Understand the purpose and target audience
2. Create a logical structure with clear sections
3. Use an engaging, appropriate writing style
4. Include a strong introduction and conclusion
5. Format content for easy readability
"""
)
# Use the content creation agent
blog_post = content_agent.start(
"""
Create a blog post about the benefits of meditation.
Target audience: Busy professionals
Length: Approximately 500 words
Tone: Informative but conversational
"""
)
print(blog_post)
```
## Specialized Content Creation Agents
Different types of content require different approaches. Let's create specialized agents for various content needs:
### Blog Post Agent
```python
blog_agent = Agent(
name="BlogWriter",
instructions="""
You are a blog post writer who creates engaging, informative articles.
When writing blog posts:
1. Create attention-grabbing headlines
2. Start with a compelling introduction
3. Use subheadings to organize content
4. Include relevant examples and evidence
5. Incorporate a clear call-to-action at the end
Format your content with proper Markdown formatting including:
- Headings (## for main sections, ### for subsections)
- Bullet points for lists
- *Italic* for emphasis
- **Bold** for important points
- > Blockquotes for notable quotes
"""
)
# Use the blog agent
blog_content = blog_agent.start(
"""
Topic: 5 Ways to Improve Your Productivity
Target audience: Remote workers
Style: Practical, actionable advice
Length: 800 words
Include: Tips, examples, and research-backed information
"""
)
print(blog_content)
```
### Social Media Content Agent
```python
social_media_agent = Agent(
name="SocialMediaCreator",
instructions="""
You are a social media content creator who crafts engaging posts.
When creating social media content:
1. Create attention-grabbing, concise content
2. Adapt to the specific platform requirements
3. Include relevant hashtags when appropriate
4. Craft content that encourages engagement
5. Consider visual elements that would pair well with the text
For each platform, follow these guidelines:
- Twitter/X: 280 characters max, punchy, relevant hashtags
- LinkedIn: Professional tone, industry insights, 1-3 paragraphs
- Instagram: Visual-focused descriptions, emoji-friendly, hashtags
- Facebook: Conversational, can be longer, question-based engagement
"""
)
# Use the social media agent
social_content = social_media_agent.start(
"""
Create posts for Twitter, LinkedIn, and Facebook announcing:
Event: Free Webinar on "Future of AI in Business"
Date: March 15, 2025
Time: 2:00 PM EST
Registration link: example.com/webinar
Key speakers: Dr. Jane Smith, AI Ethics Expert & Tom Johnson, Business AI Implementation Specialist
"""
)
print(social_content)
```
### Email Campaign Agent
```python
email_agent = Agent(
name="EmailWriter",
instructions="""
You are an email marketing specialist who creates effective email campaigns.
When writing marketing emails:
1. Create compelling subject lines that increase open rates
2. Write engaging opening lines that hook the reader
3. Keep content concise and focused on a single main message
4. Include clear calls-to-action
5. Use a tone appropriate for the brand and audience
Structure your emails with:
- Subject line
- Greeting
- Opening hook
- Main content (2-3 paragraphs maximum)
- Call-to-action
- Sign-off
"""
)
# Use the email agent
email_content = email_agent.start(
"""
Create a promotional email for:
Product: Premium Fitness Subscription
Key benefit: Personalized workout plans and nutrition advice
Special offer: 30% off first 3 months
Target audience: Health-conscious professionals aged 25-45
CTA: Sign up for the discounted offer
Tone: Motivational but not aggressive
"""
)
print(email_content)
```
## Content Creation with Templates
Templates can help create more consistent content. Let's build an agent that works with templates:
```python
template_agent = Agent(
name="TemplateWriter",
instructions="""
You are a content creator who works with templates to create consistent content.
When filling a template:
1. Maintain the overall structure of the template
2. Replace placeholder text with appropriate content
3. Ensure consistency in tone and style
4. Adapt content to the specific requirements
5. Review for coherence and flow
Always preserve formatting elements like headings, lists, and emphasis.
"""
)
# Example template
product_review_template = """
# {Product Name} Review: {Brief Opinion}
## Quick Summary
**Rating:** {Rating}/10
**Price:** {Price Range}
**Recommended For:** {Target User}
## What We Liked
- {Positive Point 1}
- {Positive Point 2}
- {Positive Point 3}
## What Could Be Better
- {Negative Point 1}
- {Negative Point 2}
## Bottom Line
{Conclusion Paragraph}
"""
# Use the template agent
filled_template = template_agent.start(
f"""
Fill the following template for a product review:
{product_review_template}
Product: Wireless Noise-Cancelling Headphones XZ200
Key features: 30-hour battery life, active noise cancellation, voice assistant integration
Price: $249.99
Target audience: Commuters and office workers
Notable pros: Sound quality, comfort, battery life
Notable cons: Price, occasional Bluetooth connectivity issues
"""
)
print(filled_template)
```
## Content Creation Best Practices
<CardGroup cols={2}>
<Card title="Know Your Audience" icon="users">
Understand who will consume the content
</Card>
<Card title="Clear Purpose" icon="bullseye">
Define what the content should achieve
</Card>
<Card title="Consistent Voice" icon="comment">
Maintain a consistent tone and style
</Card>
<Card title="Readability" icon="eye">
Make content easy to scan and understand
</Card>
</CardGroup>
In the next lesson, we'll explore how to build AI agents that can analyze and work with data.
@@ -0,0 +1,333 @@
---
title: "Data Analysis Agents"
description: "Creating agents that analyze and interpret data"
icon: "chart-line"
---
# Data Analysis Agents
Data analysis agents can help process, analyze, and extract insights from data. In this lesson, we'll learn how to build agents that can work with data effectively.
## What is a Data Analysis Agent?
A data analysis agent is designed to:
- Process and interpret data
- Identify patterns and trends
- Generate insights and recommendations
- Present findings in an understandable format
## Creating a Basic Data Analysis Agent
Let's start by building a simple data analysis agent:
```python
from praisonaiagents import Agent
# Create a basic data analysis agent
data_analysis_agent = Agent(
name="DataAnalyst",
instructions="""
You are a data analysis specialist who interprets and explains data.
When analyzing data:
1. First understand what the data represents
2. Identify key patterns, trends, or anomalies
3. Generate meaningful insights
4. Explain findings in simple, clear language
5. Provide actionable recommendations when appropriate
"""
)
# Use the data analysis agent with sample data
sample_data = """
Monthly Sales Data (2024):
January: $12,500
February: $13,200
March: $15,800
April: $14,300
May: $16,700
June: $18,900
"""
analysis = data_analysis_agent.start(
f"""
Analyze the following sales data and provide insights:
{sample_data}
Questions to answer:
1. What is the overall sales trend?
2. Which month had the highest sales?
3. What is the average monthly sales?
4. What recommendations would you make based on this data?
"""
)
print(analysis)
```
## Adding Data Processing Tools
Let's enhance our agent with basic data processing capabilities:
```python
from praisonaiagents import Agent, Tool
# Define a simple calculation tool
def calculate_statistics(data_string):
"""
Calculate basic statistics from a string of numbers.
Args:
data_string (str): A string with numbers separated by commas
Returns:
str: Statistical summary
"""
try:
# Convert string to list of numbers
data = [float(x.strip()) for x in data_string.split(',')]
# Calculate statistics
total = sum(data)
average = total / len(data)
minimum = min(data)
maximum = max(data)
return f"""
Statistical summary:
- Count: {len(data)}
- Sum: {total}
- Average: {average:.2f}
- Minimum: {minimum}
- Maximum: {maximum}
- Range: {maximum - minimum}
"""
except Exception as e:
return f"Error processing data: {str(e)}"
# Create the tool
stats_tool = Tool(
name="calculate_statistics",
function=calculate_statistics,
description="Calculate basic statistics from a list of numbers (comma-separated)"
)
# Create an agent with the statistics tool
enhanced_data_agent = Agent(
name="EnhancedDataAnalyst",
instructions="""
You are a data analysis specialist who interprets and explains data.
When analyzing data:
1. First understand what the data represents
2. Use the calculate_statistics tool for numerical data
3. Identify key patterns, trends, or anomalies
4. Generate meaningful insights
5. Explain findings in simple, clear language
6. Provide actionable recommendations when appropriate
""",
tools=[stats_tool]
)
# Use the enhanced data agent
numerical_data = "12500, 13200, 15800, 14300, 16700, 18900"
enhanced_analysis = enhanced_data_agent.start(
f"""
Analyze the following monthly sales data for the first half of 2024:
{numerical_data}
Provide a complete analysis with trends and recommendations.
"""
)
print(enhanced_analysis)
```
## Specialized Data Analysis Agents
Different analysis tasks require specialized approaches. Let's create some specialized agents:
### Market Trend Analysis Agent
```python
market_analysis_agent = Agent(
name="MarketAnalyst",
instructions="""
You are a market trend analyst who specializes in identifying patterns and making predictions.
When analyzing market data:
1. Identify long-term trends and short-term patterns
2. Compare data points to industry benchmarks
3. Identify potential causes for changes
4. Assess future implications
5. Provide strategic recommendations
Present your analysis with clear sections for:
- Overall Market Assessment
- Key Trends Identified
- Growth Opportunities
- Risk Factors
- Strategic Recommendations
""",
tools=[stats_tool]
)
# Use the market analysis agent
market_data = """
Industry Growth Rates (2021-2024):
2021: 3.2%
2022: 2.8%
2023: 4.5%
2024: 5.1%
Our Company Growth:
2021: 2.9%
2022: 3.1%
2023: 4.8%
2024: 6.3%
Competitor A Growth:
2021: 3.5%
2022: 3.7%
2023: 4.2%
2024: 4.5%
Competitor B Growth:
2021: 3.0%
2022: 2.5%
2023: 5.0%
2024: 5.8%
"""
market_analysis = market_analysis_agent.start(
f"""
Analyze the following market and company growth data:
{market_data}
Provide a comprehensive market analysis and strategic recommendations.
"""
)
print(market_analysis)
```
### Customer Data Analysis Agent
```python
customer_analysis_agent = Agent(
name="CustomerAnalyst",
instructions="""
You are a customer data analyst who specializes in understanding customer behavior.
When analyzing customer data:
1. Identify customer segments and patterns
2. Analyze purchasing behavior
3. Evaluate customer satisfaction metrics
4. Identify opportunities to improve customer experience
5. Recommend strategies for customer retention and growth
Present your analysis with sections for:
- Customer Segmentation
- Behavior Patterns
- Key Insights
- Recommended Actions
""",
tools=[stats_tool]
)
# Use the customer analysis agent
customer_data = """
Customer Segments by Age:
18-24: 15% of customers (Avg. Purchase: $45)
25-34: 32% of customers (Avg. Purchase: $78)
35-44: 28% of customers (Avg. Purchase: $92)
45-54: 18% of customers (Avg. Purchase: $85)
55+: 7% of customers (Avg. Purchase: $65)
Customer Satisfaction:
Very Satisfied: 42%
Satisfied: 35%
Neutral: 15%
Dissatisfied: 6%
Very Dissatisfied: 2%
Repeat Purchase Rate:
One-time: 40%
2-5 purchases: 35%
6-10 purchases: 15%
10+ purchases: 10%
"""
customer_analysis = customer_analysis_agent.start(
f"""
Analyze the following customer data:
{customer_data}
Provide insights on customer segments, behavior patterns, and recommendations to improve customer retention.
"""
)
print(customer_analysis)
```
## Data Visualization Recommendations
While our agents can't directly create visualizations, they can recommend appropriate visualization types:
```python
visualization_agent = Agent(
name="VisualizationAdvisor",
instructions="""
You are a data visualization specialist who helps select the best ways to visually represent data.
When recommending visualizations:
1. Understand the nature of the data (categorical, numerical, time-series, etc.)
2. Consider the key relationships or patterns to highlight
3. Recommend the most appropriate chart or graph type
4. Explain why your recommendation is effective
5. Provide suggestions for layout, color scheme, and labeling
Common visualization types to consider:
- Line charts (for trends over time)
- Bar charts (for comparing categories)
- Pie charts (for showing composition, use sparingly)
- Scatter plots (for showing relationships between variables)
- Heatmaps (for showing patterns in complex data)
- Box plots (for showing distributions)
"""
)
# Use the visualization agent
viz_recommendations = visualization_agent.start(
"""
I have the following data and need visualization recommendations:
1. Monthly sales data for the past year
2. Customer satisfaction ratings across 5 product categories
3. Market share compared to 3 competitors
4. Customer age distribution
What visualizations would you recommend for each of these datasets and why?
"""
)
print(viz_recommendations)
```
## Data Analysis Best Practices
<CardGroup cols={2}>
<Card title="Data Quality" icon="shield-check">
Ensure data is accurate and complete
</Card>
<Card title="Context Matters" icon="circle-info">
Consider external factors affecting data
</Card>
<Card title="Clear Communication" icon="comments">
Present findings in understandable terms
</Card>
<Card title="Actionable Insights" icon="bolt">
Focus on insights that lead to action
</Card>
</CardGroup>
In the next lesson, we'll explore how to build AI agents that can assist with customer support tasks.
@@ -0,0 +1,260 @@
---
title: "Customer Support Agents"
description: "Building agents that handle customer inquiries and issues"
icon: "headset"
---
# Customer Support Agents
Customer support agents can handle inquiries, resolve issues, and provide assistance to users. In this lesson, we'll learn how to build effective customer support agents.
## What is a Customer Support Agent?
A customer support agent is designed to:
- Answer frequently asked questions
- Troubleshoot common problems
- Provide information about products or services
- Collect information for support tickets
- Guide users through processes or procedures
## Creating a Basic Customer Support Agent
Let's start by building a simple customer support agent:
```python
from praisonaiagents import Agent
# Create a basic customer support agent
support_agent = Agent(
name="SupportAgent",
instructions="""
You are a helpful customer support representative for a software company.
When helping customers:
1. Greet them professionally and warmly
2. Understand their issue completely before attempting to solve it
3. Provide clear, step-by-step solutions when possible
4. Maintain a friendly, patient tone throughout
5. If you cannot solve the issue, explain how to escalate it
Our software product is a productivity app with features for:
- Task management
- Calendar scheduling
- Note-taking
- Team collaboration
"""
)
# Use the support agent
response = support_agent.start("I'm having trouble syncing my calendar with my phone. Can you help?")
print(response)
```
## Adding a Knowledge Base
Let's enhance our agent with a simple knowledge base to answer common questions:
```python
from praisonaiagents import Agent, KnowledgeBase
# Create a simple knowledge base
faq_kb = KnowledgeBase()
# Add FAQ content (in a real scenario, you would load this from files)
faq_kb.add_text("""
# Frequently Asked Questions
## Account Issues
### How do I reset my password?
To reset your password:
1. Go to the login page
2. Click on "Forgot Password"
3. Enter your email address
4. Follow the instructions sent to your email
### How do I change my email address?
To change your email address:
1. Log in to your account
2. Go to Settings > Account
3. Click on "Change Email"
4. Enter your new email and confirm with your password
## Subscription and Billing
### What subscription plans do you offer?
We offer three plans:
- Basic: $9.99/month - Includes core features for individuals
- Pro: $19.99/month - Includes advanced features and team capabilities for up to 5 users
- Enterprise: Custom pricing - Full feature set with advanced security and support
### How do I cancel my subscription?
To cancel your subscription:
1. Log in to your account
2. Go to Settings > Billing
3. Click "Cancel Subscription"
4. Follow the confirmation steps
## Technical Issues
### Why isn't my calendar syncing?
Common reasons for calendar sync issues:
1. Outdated app version - Try updating the app
2. Account permission issues - Check sync permissions in Settings > Integrations
3. Internet connectivity problems - Ensure you have a stable connection
### How do I export my data?
To export your data:
1. Go to Settings > Data
2. Click "Export Data"
3. Choose the data types you want to export
4. Select your preferred format (CSV or JSON)
5. Click "Export" and save the file
""")
# Create an agent with the knowledge base
kb_support_agent = Agent(
name="KnowledgeBaseAgent",
instructions="""
You are a helpful customer support representative with access to our FAQ knowledge base.
When helping customers:
1. Greet them professionally and warmly
2. Search the knowledge base for relevant information
3. Provide clear, accurate answers based on the knowledge base
4. If the knowledge base doesn't cover the question, provide general helpful guidance
5. Maintain a friendly, supportive tone throughout
""",
knowledge_base=faq_kb
)
# Use the knowledge base support agent
kb_response = kb_support_agent.start("How do I cancel my subscription?")
print(kb_response)
```
## Creating a Troubleshooting Agent
Let's create an agent specialized in technical troubleshooting:
```python
troubleshooting_agent = Agent(
name="TroubleshootingAgent",
instructions="""
You are a technical support specialist who helps users troubleshoot problems.
When troubleshooting:
1. Ask clarifying questions to understand the exact issue
2. Identify the most likely causes of the problem
3. Provide step-by-step solutions, starting with the simplest fixes
4. Explain what each step does and why it might help
5. Confirm if the issue is resolved or suggest next steps
Common troubleshooting areas:
- Login and account access issues
- App installation and updates
- Feature functionality problems
- Data synchronization
- Performance issues
"""
)
# Use the troubleshooting agent
troubleshooting_response = troubleshooting_agent.start("The app keeps crashing when I try to open it on my iPhone")
print(troubleshooting_response)
```
## Building a Conversational Support Agent
Let's create a support agent that can handle multi-turn conversations:
```python
conversational_support = Agent(
name="ConversationalSupport",
instructions="""
You are a customer support representative who handles support conversations.
When handling support conversations:
1. Maintain context throughout the conversation
2. Ask follow-up questions when needed
3. Verify understanding before providing solutions
4. Be patient with users who may be frustrated
5. Summarize the conversation and next steps at the end
Our product is a mobile banking app with features for:
- Account balance checking
- Money transfers
- Bill payments
- Mobile check deposits
- Budget tracking
"""
)
# Start a support conversation
initial_response = conversational_support.start("I can't find where to deposit checks in the app")
print("Initial Response:", initial_response)
# Continue the conversation
follow_up_response = conversational_support.continue("I'm using version 2.5 of the app on Android")
print("Follow-up Response:", follow_up_response)
# Further continuation
resolution_response = conversational_support.continue("I found the deposit button now, but it's giving me an error when I try to take a photo")
print("Resolution Response:", resolution_response)
```
## Support Ticket Creation Agent
Let's create an agent that can gather information for support tickets:
```python
ticket_agent = Agent(
name="TicketCreationAgent",
instructions="""
You are a support ticket creation specialist who gathers the necessary information to create support tickets.
When creating a ticket:
1. Collect the customer's name and contact information
2. Identify the category of the issue
3. Gather a detailed description of the problem
4. Determine the severity level
5. Collect relevant technical details (device, software version, etc.)
6. Organize all information in a structured ticket format
Present the final ticket in a clearly formatted structure.
"""
)
# Use the ticket creation agent
ticket = ticket_agent.start(
"""
Create a support ticket for the following issue:
Customer: Jane Smith
Email: [email protected]
Issue: Cannot access premium features after payment
Details: Completed payment yesterday, received confirmation email, but premium features are still locked in the app
Using: iPhone 13, app version 3.2.1
"""
)
print(ticket)
```
## Customer Support Best Practices
<CardGroup cols={2}>
<Card title="Empathy First" icon="heart">
Show understanding before offering solutions
</Card>
<Card title="Clear Communication" icon="comment">
Use simple language, avoid jargon
</Card>
<Card title="Consistent Responses" icon="equals">
Provide consistent answers to similar questions
</Card>
<Card title="Know Escalation Paths" icon="arrow-up-right">
Have clear processes for escalating complex issues
</Card>
</CardGroup>
In the next lesson, we'll explore how to build AI agents that can assist with personal productivity tasks.
@@ -0,0 +1,270 @@
---
title: "Personal Assistant Agents"
description: "Building agents that help with personal tasks and productivity"
icon: "calendar-check"
---
# Personal Assistant Agents
Personal assistant agents can help users manage tasks, organize information, and increase productivity. In this lesson, we'll learn how to build effective personal assistant agents.
## What is a Personal Assistant Agent?
A personal assistant agent is designed to:
- Manage tasks and reminders
- Organize information
- Answer questions
- Provide recommendations
- Help with personal productivity
## Creating a Basic Personal Assistant Agent
Let's start by building a simple personal assistant agent:
```python
from praisonaiagents import Agent
# Create a basic personal assistant agent
assistant_agent = Agent(
name="PersonalAssistant",
instructions="""
You are a helpful personal assistant who helps users manage tasks and information.
When assisting users:
1. Be concise and efficient in your responses
2. Prioritize user requests based on importance and urgency
3. Maintain a helpful, friendly tone
4. Remember important information the user shares
5. Proactively suggest relevant information when appropriate
""",
llm="gpt-4o-mini" # Using the specified model
)
# Use the personal assistant agent
response = assistant_agent.start("I need to plan a meeting with my team next Tuesday at 2 PM")
print(response)
```
## Task Management Assistant
Let's create an agent specialized in task management:
```python
task_agent = Agent(
name="TaskManager",
instructions="""
You are a task management assistant who helps users organize and prioritize tasks.
When managing tasks:
1. Help identify and clarify tasks
2. Assist with prioritization
3. Break down complex tasks into manageable steps
4. Track deadlines and progress
5. Provide reminders and follow-ups
For each task, collect:
- Task description
- Priority (High, Medium, Low)
- Deadline (if applicable)
- Dependencies (other tasks that must be completed first)
- Estimated time required
""",
llm="gpt-4o-mini" # Using the specified model
)
# Use the task management agent
task_response = task_agent.start(
"""
I need help organizing these tasks for the week:
- Prepare quarterly report (due Friday)
- Meet with client about new project (Wednesday, 2 PM)
- Review team's project proposals
- Finish budget planning for next quarter
- Send feedback on marketing materials
"""
)
print(task_response)
```
## Information Organization Assistant
Let's create an agent that helps organize information:
```python
info_agent = Agent(
name="InformationOrganizer",
instructions="""
You are an information organization assistant who helps users structure and categorize information.
When organizing information:
1. Identify the main categories and topics
2. Create logical groupings
3. Suggest clear labels and headers
4. Establish relationships between different pieces of information
5. Present information in a structured, easily navigable format
""",
llm="gpt-4o-mini" # Using the specified model
)
# Use the information organization agent
info_response = info_agent.start(
"""
Help me organize my research notes on climate change:
- Rising sea levels affecting coastal cities
- Carbon dioxide levels increasing annually
- Renewable energy adoption statistics by country
- Impact of deforestation on carbon sequestration
- Climate policy differences between EU and US
- Economic impacts of extreme weather events
- Public opinion polls on climate action
- Arctic ice sheet measurements over 50 years
- Agricultural adaptations to changing climate
"""
)
print(info_response)
```
## Daily Planning Assistant
Let's create an agent that helps with daily planning:
```python
planning_agent = Agent(
name="DailyPlanner",
instructions="""
You are a daily planning assistant who helps users organize their day efficiently.
When helping with daily planning:
1. Prioritize tasks based on importance and deadlines
2. Consider time constraints and commitments
3. Suggest efficient scheduling
4. Allow for breaks and transitions
5. Balance work tasks with personal needs
Create a structured daily plan with time blocks and priorities.
""",
llm="gpt-4o-mini" # Using the specified model
)
# Use the daily planning agent
planning_response = planning_agent.start(
"""
Help me plan my day tomorrow. I have:
- A team meeting from 9:30-10:30 AM
- A report due by end of day
- Emails to catch up on (about 1 hour's worth)
- Lunch with a colleague at 12:30 PM
- A dentist appointment at 3:00 PM (will take about 1 hour including travel)
- Need to prepare a presentation for Friday
I typically work from 8:30 AM to 5:30 PM and prefer to have short breaks between tasks.
"""
)
print(planning_response)
```
## Decision Support Assistant
Let's create an agent that helps with decision-making:
```python
decision_agent = Agent(
name="DecisionSupport",
instructions="""
You are a decision support assistant who helps users make informed choices.
When supporting decisions:
1. Help clarify the decision to be made
2. Identify relevant criteria and factors
3. Present pros and cons for each option
4. Ask questions to understand preferences and priorities
5. Provide a structured analysis without making the final decision
Present options with balanced information to help the user make their own informed choice.
""",
llm="gpt-4o-mini" # Using the specified model
)
# Use the decision support agent
decision_response = decision_agent.start(
"""
I'm trying to decide whether to buy a new laptop now or wait 3 months.
Current situation:
- My current laptop is 4 years old and running slow
- It still works but has battery issues
- I use it daily for work (programming and video calls)
- I've heard new models are coming out in 3 months
- My budget is around $1,500
What should I consider in making this decision?
"""
)
print(decision_response)
```
## Recommendation Assistant
Let's create an agent that provides personalized recommendations:
```python
recommendation_agent = Agent(
name="RecommendationAssistant",
instructions="""
You are a recommendation assistant who provides personalized suggestions.
When making recommendations:
1. Understand the user's preferences and requirements
2. Consider constraints (budget, time, location, etc.)
3. Provide diverse options that match the criteria
4. Explain why each recommendation might be suitable
5. Give enough detail for the user to evaluate options
For each recommendation, include:
- A brief description
- Key features or highlights
- Why it matches the user's needs
""",
llm="gpt-4o-mini" # Using the specified model
)
# Use the recommendation agent
recommendation_response = recommendation_agent.start(
"""
Can you recommend some books for me? I enjoy:
- Science fiction and fantasy
- Books with complex, morally gray characters
- Intricate world-building
- Books that explore philosophical themes
I've recently read and enjoyed:
- "The Fifth Season" by N.K. Jemisin
- "Dune" by Frank Herbert
- "The Lies of Locke Lamora" by Scott Lynch
"""
)
print(recommendation_response)
```
## Personal Assistant Best Practices
<CardGroup cols={2}>
<Card title="Respect Privacy" icon="lock">
Be careful with personal information
</Card>
<Card title="Customize Interactions" icon="sliders">
Adapt to the user's preferences
</Card>
<Card title="Clear Communication" icon="comment">
Keep responses direct and easy to understand
</Card>
<Card title="Contextual Awareness" icon="puzzle-piece">
Remember relevant context from previous interactions
</Card>
</CardGroup>
In the next lesson, we'll explore how to deploy and share your AI agents with others.
+342
View File
@@ -0,0 +1,342 @@
---
title: "Deploying Agents"
description: "How to deploy and share your AI agents with others"
icon: "rocket"
---
# Deploying Agents
After creating your AI agents, the next step is deploying them for use by yourself or others. In this final lesson, we'll explore different deployment options and best practices.
## Deployment Options
There are several ways to deploy your AI agents:
### 1. Local Deployment
Running your agents locally is the simplest approach:
```python
from praisonaiagents import Agent
def run_local_agent():
agent = Agent(
name="SimpleAgent",
instructions="You are a helpful assistant that answers questions concisely.",
llm="gpt-4o-mini" # Using the specified model
)
while True:
user_input = input("Ask a question (type 'exit' to quit): ")
if user_input.lower() == 'exit':
break
response = agent.start(user_input)
print("\nAgent response:")
print(response)
print("\n" + "-"*50 + "\n")
if __name__ == "__main__":
run_local_agent()
```
### 2. Web Application Deployment
You can deploy your agents as part of a web application:
```python
from flask import Flask, request, jsonify
from praisonaiagents import Agent
import os
app = Flask(__name__)
# Create agent once at startup
support_agent = Agent(
name="SupportAgent",
instructions="You are a customer support agent that helps users with product questions.",
llm="gpt-4o-mini" # Using the specified model
)
@app.route('/api/support', methods=['POST'])
def get_support():
data = request.json
user_query = data.get('query', '')
if not user_query:
return jsonify({"error": "No query provided"}), 400
try:
response = support_agent.start(user_query)
return jsonify({"response": response})
except Exception as e:
return jsonify({"error": str(e)}), 500
if __name__ == "__main__":
app.run(debug=True, port=5000)
```
### 3. Serverless Function Deployment
For scalable, event-driven deployments, serverless functions work well:
```python
# Example AWS Lambda function
import json
from praisonaiagents import Agent
# Initialize agent outside the handler for reuse across invocations
agent = Agent(
name="ServerlessAgent",
instructions="You provide concise, helpful responses to user questions.",
llm="gpt-4o-mini" # Using the specified model
)
def lambda_handler(event, context):
try:
# Get the user query from the event
body = json.loads(event.get('body', '{}'))
user_query = body.get('query', '')
if not user_query:
return {
'statusCode': 400,
'body': json.dumps({'error': 'No query provided'})
}
# Process with the agent
response = agent.start(user_query)
return {
'statusCode': 200,
'body': json.dumps({'response': response})
}
except Exception as e:
return {
'statusCode': 500,
'body': json.dumps({'error': str(e)})
}
```
## Environment Variables and Security
When deploying agents, it's crucial to handle API keys and secrets securely:
```python
import os
from dotenv import load_dotenv
from praisonaiagents import Agent
# Load environment variables from .env file
load_dotenv()
# Access API key from environment variable
api_key = os.getenv("OPENAI_API_KEY")
# Create agent with API key
agent = Agent(
name="SecureAgent",
instructions="You are a helpful assistant.",
llm="gpt-4o-mini", # Using the specified model
api_key=api_key # Pass API key securely
)
```
## Creating a Simple Chat Interface
Here's a simple command-line chat interface for your agent:
```python
import os
from praisonaiagents import Agent
def create_chat_interface():
# Initialize agent
agent = Agent(
name="ChatAgent",
instructions="""
You are a conversational assistant that maintains context throughout the conversation.
Respond in a helpful, concise manner.
""",
llm="gpt-4o-mini" # Using the specified model
)
print("Chat with AI Assistant (type 'exit' to quit)")
print("-" * 50)
# Start conversation
conversation_active = True
first_message = True
while conversation_active:
# Get user input
user_message = input("You: ")
# Check if user wants to exit
if user_message.lower() == 'exit':
print("Goodbye!")
conversation_active = False
continue
# Get agent response
try:
if first_message:
response = agent.start(user_message)
first_message = False
else:
response = agent.continue(user_message)
print("\nAssistant:", response)
print("\n" + "-" * 50)
except Exception as e:
print(f"Error: {str(e)}")
if __name__ == "__main__":
create_chat_interface()
```
## Scaling Considerations
As you deploy agents for wider use, consider these scaling factors:
<CardGroup cols={2}>
<Card title="Rate Limiting" icon="gauge-high">
Implement rate limiting to manage API usage and costs
</Card>
<Card title="Caching" icon="database">
Cache common responses to improve performance and reduce API calls
</Card>
<Card title="Error Handling" icon="triangle-exclamation">
Implement robust error handling for API failures
</Card>
<Card title="Monitoring" icon="chart-line">
Set up monitoring for usage patterns and performance issues
</Card>
</CardGroup>
## Best Practices for Deployment
### 1. Testing Before Deployment
Always test your agents thoroughly before deployment:
```python
def test_agent_functionality():
"""Test basic agent functionality with various inputs"""
agent = Agent(
name="TestAgent",
instructions="You are a helpful assistant for testing.",
llm="gpt-4o-mini" # Using the specified model
)
test_cases = [
"What is artificial intelligence?",
"How do I reset my password?",
"Tell me about machine learning"
]
for test_case in test_cases:
print(f"\nTesting: {test_case}")
response = agent.start(test_case)
print(f"Response: {response[:100]}...") # Print first 100 chars
# Add assertions or validation logic here
assert len(response) > 0, "Response should not be empty"
```
### 2. Documentation
Create clear documentation for users of your agent:
```python
"""
# Customer Support Agent API
This API provides access to an AI customer support agent
that can answer questions about our products.
## Authentication
Include your API key in the request header:
```
Authorization: Bearer YOUR_API_KEY
```
## Endpoints
POST /api/support
- Request body: {"query": "Your question here"}
- Response: {"response": "Agent's answer"}
## Example
```python
import requests
response = requests.post(
"https://api.example.com/api/support",
headers={"Authorization": "Bearer YOUR_API_KEY"},
json={"query": "How do I reset my password?"}
)
print(response.json())
```
"""
```
### 3. Version Control
Implement version control for your agents to track changes:
```python
class VersionedAgent:
def __init__(self, name, version, instructions):
self.name = name
self.version = version
self.agent = Agent(
name=f"{name}_v{version}",
instructions=instructions,
llm="gpt-4o-mini" # Using the specified model
)
def get_response(self, query):
response = self.agent.start(query)
return {
"agent_name": self.name,
"version": self.version,
"response": response,
"timestamp": datetime.now().isoformat()
}
```
## Conclusion
Congratulations on completing the AI Agents Course! You've learned how to:
1. Understand different types of AI agents and their architectures
2. Create effective agent instructions and tools
3. Implement memory and context for your agents
4. Build specialized agents for various tasks
5. Create multi-agent systems
6. Deploy your agents for real-world use
As AI agent technology continues to evolve, keep experimenting with new capabilities and use cases. Remember that the best agents are those that effectively solve real problems for users while being trustworthy, reliable, and helpful.
We hope this course has provided you with the knowledge and skills to build powerful AI agents that enhance productivity and creativity!
## Next Steps
<CardGroup cols={2}>
<Card title="Join the Community" icon="users">
Participate in discussions and share your agent projects
</Card>
<Card title="Stay Updated" icon="newspaper">
Follow updates in AI agent technology and new features
</Card>
<Card title="Share Your Feedback" icon="comment">
Let us know how you're using agents and what you'd like to learn next
</Card>
<Card title="Build Real Solutions" icon="lightbulb">
Apply your knowledge to build solutions for real-world problems
</Card>
</CardGroup>
+111 -10
View File
@@ -114,27 +114,53 @@ agents.start()
</Steps>
</Tab>
<Tab title="No Code">
<Tip>
PraisonAI combines PraisonAI Agents, AutoGen, and CrewAI into a low-code solution for building and managing multi-agent LLM systems, focusing on simplicity, customization, and efficient human-agent collaboration.
</Tip>
<Steps>
<Step title="Install Package">
Install the No Code PraisonAI Package:
```bash
pip install praisonai
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
```bash
export OPENAI_API_KEY=xxxxxxxxxxxxxxxxxxxxxx
export OPENAI_API_KEY=your_openai_key
```
</Step>
<Step title="Auto Mode">
<Step title="Create Config">
Create `agents.yaml`:
<CodeGroup>
```yaml Single Agent
roles:
summarise_agent:
instructions: Summarise Photosynthesis
```
```yaml Multiple Agents
roles:
diet_agent:
instructions: Give me 5 healthy food recipes
blog_agent:
instructions: Write a blog post about the food recipes
```
</CodeGroup>
<Note>
You can automatically create `agents.yaml` using:
```bash
praisonai --init "your task description"
```
</Note>
</Step>
<Step title="Run Agents">
Execute your config:
```bash
praisonai --auto create a movie script about Robots in Mars
praisonai agents.yaml
```
This will automatically create required agents and complete the task
</Step>
</Steps>
</Tab>
@@ -180,8 +206,83 @@ agents.start();
</Step>
</Steps>
</Tab>
<Tab title="TypeScript">
<Steps>
<Step title="Install Package">
<CodeGroup>
```bash npm
npm install praisonai
```
```bash yarn
yarn add praisonai
```
</CodeGroup>
</Step>
<Step title="Set API Key">
```bash
export OPENAI_API_KEY=xxxxxxxxxxxxxxxxxxxxxx
```
</Step>
<Step title="Create File">
Create `app.ts` file
## Code Example
<CodeGroup>
```javascript Single Agent
import { Agent } from 'praisonai';
const agent = new Agent({
instructions: `You are a creative writer who writes short stories with emojis.`,
name: "StoryWriter"
});
agent.start("Write a story about a time traveler")
```
```javascript Multi Agents
import { Agent, PraisonAIAgents } from 'praisonai';
const storyAgent = new Agent({
instructions: "Generate a very short story (2-3 sentences) about artificial intelligence with emojis.",
name: "StoryAgent"
});
const summaryAgent = new Agent({
instructions: "Summarize the provided AI story in one sentence with emojis.",
name: "SummaryAgent"
});
const agents = new PraisonAIAgents({
agents: [storyAgent, summaryAgent]
});
agents.start()
```
</CodeGroup>
</Step>
<Step title="Run Script">
```bash
npx ts-node app.ts
```
</Step>
</Steps>
</Tab>
</Tabs>
## Playground
<iframe
id="codeExecutionFrame"
src="https://code-execution-server-praisonai.replit.app/?code=import%20openai%0A%0Aclient%20%3D%20openai.OpenAI()%0Aresult%20%3D%20client.chat.completions.create(%0A%20%20%20%20model%3D%22gpt-3.5-turbo%22%2C%0A%20%20%20%20messages%3D%5B%0A%20%20%20%20%20%20%20%20%7B%22role%22%3A%20%22user%22%2C%20%22content%22%3A%20%22Hello%20World%22%7D%0A%20%20%20%20%5D%0A)%0A%0Aprint(result.choices%5B0%5D.message.content)"
width="100%"
height="600px"
frameborder="0"
allow="clipboard-read; clipboard-write"
scrolling="yes"
onload="resizeIframe(this)"
></iframe>
## AI Agents Flow
```mermaid
+19
View File
@@ -14,6 +14,9 @@ pip install praisonai
```bash JavaScript
npm install praisonai
```
```bash TypeScript
npm install praisonai
```
</RequestExample>
<Note>
@@ -109,6 +112,22 @@ Follow these steps to set up PraisonAI in your development environment.
</Step>
</Steps>
</Tab>
<Tab title="TypeScript">
<Steps>
<Step title="Install PraisonAI">
Install the PraisonAI package:
```bash
npm install praisonai
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable in your terminal:
```bash
export OPENAI_API_KEY=your_openai_key
```
</Step>
</Steps>
</Tab>
</Tabs>
Generate your OpenAI API key from [OpenAI](https://platform.openai.com/api-keys)
+75
View File
@@ -248,8 +248,83 @@ agents.start();
</Step>
</Steps>
</Tab>
<Tab title="TypeScript">
<Steps>
<Step title="Install Package">
<CodeGroup>
```bash npm
npm install praisonai
```
```bash yarn
yarn add praisonai
```
</CodeGroup>
</Step>
<Step title="Set API Key">
```bash
export OPENAI_API_KEY=xxxxxxxxxxxxxxxxxxxxxx
```
</Step>
<Step title="Create File">
Create `app.ts` file
## Code Example
<CodeGroup>
```javascript Single Agent
import { Agent } from 'praisonai';
const agent = new Agent({
instructions: `You are a creative writer who writes short stories with emojis.`,
name: "StoryWriter"
});
agent.start("Write a story about a time traveler")
```
```javascript Multi Agents
import { Agent, PraisonAIAgents } from 'praisonai';
const storyAgent = new Agent({
instructions: "Generate a very short story (2-3 sentences) about artificial intelligence with emojis.",
name: "StoryAgent"
});
const summaryAgent = new Agent({
instructions: "Summarize the provided AI story in one sentence with emojis.",
name: "SummaryAgent"
});
const agents = new PraisonAIAgents({
agents: [storyAgent, summaryAgent]
});
agents.start()
```
</CodeGroup>
</Step>
<Step title="Run Script">
```bash
npx ts-node app.ts
```
</Step>
</Steps>
</Tab>
</Tabs>
## Playground
<iframe
id="codeExecutionFrame"
src="https://code-execution-server-praisonai.replit.app/?code=import%20openai%0A%0Aclient%20%3D%20openai.OpenAI()%0Aresult%20%3D%20client.chat.completions.create(%0A%20%20%20%20model%3D%22gpt-3.5-turbo%22%2C%0A%20%20%20%20messages%3D%5B%0A%20%20%20%20%20%20%20%20%7B%22role%22%3A%20%22user%22%2C%20%22content%22%3A%20%22Hello%20World%22%7D%0A%20%20%20%20%5D%0A)%0A%0Aprint(result.choices%5B0%5D.message.content)"
width="100%"
height="600px"
frameborder="0"
allow="clipboard-read; clipboard-write"
scrolling="yes"
onload="resizeIframe(this)"
></iframe>
## Key Features
<CardGroup cols={3}>
+50
View File
@@ -0,0 +1,50 @@
---
title: "Custom Tools for TypeScript AI Agents"
sidebarTitle: "Custom Tools"
description: "Learn how to create custom tools for TypeScript AI Agents"
icon: "toolbox"
---
## Single Agent
```typescript
import { Agent } from 'praisonai';
async function getWeather(location: string) {
console.log(`Getting weather for ${location}...`);
return `${Math.floor(Math.random() * 30)}°C`;
}
const agent = new Agent({
instructions: `You provide the current weather for requested locations.`,
name: "DirectFunctionAgent",
tools: [getWeather]
});
agent.start("What's the weather in Paris, France?");
```
## Multi Agents
```typescript
import { Agent } from 'praisonai';
async function getWeather(location: string) {
console.log(`Getting weather for ${location}...`);
return `${Math.floor(Math.random() * 30)}°C`;
}
async function getTime(location: string) {
console.log(`Getting time for ${location}...`);
const now = new Date();
return `${now.getHours()}:${now.getMinutes()}`;
}
const agent = new Agent({
instructions: `You provide the current weather and time for requested locations.`,
name: "DirectFunctionAgent",
tools: [getWeather, getTime]
});
agent.start("What's the weather and time in Paris, France and Tokyo, Japan?");
```
+31
View File
@@ -264,3 +264,34 @@ agents.start()
```
</Step>
</Steps>
## Tool Calls Examples
<AccordionGroup>
<Accordion title="Direct Function Tools" icon="code" defaultOpen>
Create an agent with directly registered function tools:
```typescript
import { Agent } from 'praisonai';
async function getWeather(location: string) {
console.log(`Getting weather for ${location}...`);
return `${Math.floor(Math.random() * 30)}°C`;
}
async function getTime(location: string) {
console.log(`Getting time for ${location}...`);
const now = new Date();
return `${now.getHours()}:${now.getMinutes()}`;
}
const agent = new Agent({
instructions: `You provide the current weather and time for requested locations.`,
name: "DirectFunctionAgent",
tools: [getWeather, getTime]
});
agent.start("What's the weather and time in Paris, France and Tokyo, Japan?");
```
</Accordion>
</AccordionGroup>
+52 -1
View File
@@ -78,6 +78,10 @@
{
"name": "JS",
"url": "/js"
},
{
"name": "Course",
"url": "/course"
}
],
"navigation": [
@@ -154,6 +158,31 @@
"models/other"
]
},
{
"group": "Course",
"pages": [
"course/agents/01-introduction",
"course/agents/02-types-of-agents",
"course/agents/03-agent-architecture",
"course/agents/04-agent-instructions",
"course/agents/05-agent-tools",
"course/agents/06-agent-memory",
"course/agents/07-multi-agent-systems",
"course/agents/08-agent-process",
"course/agents/09-knowledge-bases",
"course/agents/10-agent-tasks",
"course/agents/11-creating-your-first-agent",
"course/agents/12-adding-tools-to-agents",
"course/agents/13-building-multi-agent-system",
"course/agents/14-conversational-agents",
"course/agents/15-research-agents",
"course/agents/16-content-creation-agents",
"course/agents/17-data-analysis-agents",
"course/agents/18-customer-support-agents",
"course/agents/19-personal-assistant-agents",
"course/agents/20-deploying-agents"
]
},
{
"group": "Examples",
"pages": [
@@ -206,6 +235,20 @@
"pages": [
"tools/tools",
"tools/langchain_tools",
{
"group": "External Tools",
"icon": "subscript",
"pages": [
"tools/external/serp-api",
"tools/external/brave-search",
"tools/external/google-trends",
"tools/external/exa-search",
"tools/external/wikipedia-search",
"tools/external/duckduckgo-search",
"tools/external/google-serper-search",
"tools/external/serp-search"
]
},
"tools/duckduckgo_tools",
"tools/arxiv_tools",
"tools/calculator_tools",
@@ -244,7 +287,14 @@
"group": "JavaScript",
"pages": [
"js/js",
"js/typescript",
{
"group": "TypeScript Agents",
"icon": "subscript",
"pages": [
"js/typescript",
"js/customtools"
]
},
"js/nodejs",
"js/typescript-async",
"js/development"
@@ -254,6 +304,7 @@
"group": "Other Features",
"pages": [
"train",
"playground",
"framework/crewai",
"framework/autogen",
"framework/praisonaiagents"
+4
View File
@@ -0,0 +1,4 @@
[build]
command = "npm install && npm run build"
publish = "dist"
base = "docs"
+9373
View File
File diff suppressed because it is too large. Load diff
+14
View File
@@ -0,0 +1,14 @@
{
"name": "praisonai-docs",
"version": "1.0.0",
"description": "PraisonAI Documentation",
"scripts": {
"dev": "mintlify dev",
"start": "mintlify dev",
"build": "mkdir -p dist && find . -type f -not -path \"./dist/*\" -not -path \"./node_modules/*\" -not -path \"./.git/*\" -not -path \"./.*\" -not -name \"*.json\" -not -name \"*.md\" -not -name \"*.yaml\" -not -name \"*.yml\" -not -name \"*.toml\" -not -name \"*.lock\" | while read file; do mkdir -p \"dist/$(dirname \"$file\")\" && cp \"$file\" \"dist/$file\"; done"
},
"dependencies": {
"mintlify": "^4.0.0"
}
}
+33
View File
@@ -0,0 +1,33 @@
---
title: "Praison AI Agents Playground"
sidebarTitle: "Playground"
description: "Interactive environment to test and run your AI Agents"
icon: "code"
---
<iframe
id="codeExecutionFrame"
src="https://code-execution-server-praisonai.replit.app/?code=import%20openai%0A%0Aclient%20%3D%20openai.OpenAI()%0Aresult%20%3D%20client.chat.completions.create(%0A%20%20%20%20model%3D%22gpt-3.5-turbo%22%2C%0A%20%20%20%20messages%3D%5B%0A%20%20%20%20%20%20%20%20%7B%22role%22%3A%20%22user%22%2C%20%22content%22%3A%20%22Hello%20World%22%7D%0A%20%20%20%20%5D%0A)%0A%0Aprint(result.choices%5B0%5D.message.content)"
width="100%"
height="800px"
frameborder="0"
allow="clipboard-read; clipboard-write"
scrolling="yes"
onload="resizeIframe(this)"
></iframe>
## How to Use the Playground
1. The code editor is pre-loaded with a simple example using Praison AI Agents
2. Modify the code as needed for your experiments
3. Click "Run" to execute the code and see the results
4. Use the playground to test concepts from the course or your own ideas
<CardGroup cols={2}>
<Card title="API Documentation" icon="book" href="https://docs.praison.ai">
Reference the Praison AI Agents documentation for more examples
</Card>
<Card title="Back to Course" icon="arrow-left" href="/course/agents/01-introduction">
Return to the AI Agents course
</Card>
</CardGroup>
+75
View File
@@ -167,6 +167,68 @@ agents.start();
</Step>
</Steps>
</Tab>
<Tab title="TypeScript">
<Steps>
<Step title="Install Package">
<CodeGroup>
```bash npm
npm install praisonai
```
```bash yarn
yarn add praisonai
```
</CodeGroup>
</Step>
<Step title="Set API Key">
```bash
export OPENAI_API_KEY=xxxxxxxxxxxxxxxxxxxxxx
```
</Step>
<Step title="Create File">
Create `app.ts` file
## Code Example
<CodeGroup>
```javascript Single Agent
import { Agent } from 'praisonai';
const agent = new Agent({
instructions: `You are a creative writer who writes short stories with emojis.`,
name: "StoryWriter"
});
agent.start("Write a story about a time traveler")
```
```javascript Multi Agents
import { Agent, PraisonAIAgents } from 'praisonai';
const storyAgent = new Agent({
instructions: "Generate a very short story (2-3 sentences) about artificial intelligence with emojis.",
name: "StoryAgent"
});
const summaryAgent = new Agent({
instructions: "Summarize the provided AI story in one sentence with emojis.",
name: "SummaryAgent"
});
const agents = new PraisonAIAgents({
agents: [storyAgent, summaryAgent]
});
agents.start()
```
</CodeGroup>
</Step>
<Step title="Run Script">
```bash
npx ts-node app.ts
```
</Step>
</Steps>
</Tab>
</Tabs>
<Note>
@@ -176,6 +238,19 @@ agents.start();
- For other LLM providers, see [Models](/models)
</Note>
## Playground
<iframe
id="codeExecutionFrame"
src="https://code-execution-server-praisonai.replit.app/?code=import%20openai%0A%0Aclient%20%3D%20openai.OpenAI()%0Aresult%20%3D%20client.chat.completions.create(%0A%20%20%20%20model%3D%22gpt-3.5-turbo%22%2C%0A%20%20%20%20messages%3D%5B%0A%20%20%20%20%20%20%20%20%7B%22role%22%3A%20%22user%22%2C%20%22content%22%3A%20%22Hello%20World%22%7D%0A%20%20%20%20%5D%0A)%0A%0Aprint(result.choices%5B0%5D.message.content)"
width="100%"
height="600px"
frameborder="0"
allow="clipboard-read; clipboard-write"
scrolling="yes"
onload="resizeIframe(this)"
></iframe>
# Advanced
## Providing Detailed Tasks to Agents (Optional)
+13 -1
View File
@@ -5,8 +5,20 @@ mkdocs
markdown-include
mkdocs-material
mkdocs-jupyter
mkdocs-glightbox
pymdown-extensions
Pygments
mkdocstrings
mkdocs-apidoc
mkdocstrings-python
mkdocs-jupyter
pdoc3
rich
pyautogen
crewai
gradio
duckduckgo_search
praisonai_tools
open-interpreter
xmlrunner
unittest2
unittest2
-24
View File
@@ -1,24 +0,0 @@
sphinx
sphinx_rtd_theme
sphinx-autodoc-typehints
mkdocs
markdown-include
mkdocs-material
mkdocs-jupyter
mkdocs-glightbox
pymdown-extensions
Pygments
mkdocstrings
mkdocs-apidoc
mkdocstrings-python
mkdocs-jupyter
pdoc3
rich
pyautogen
crewai
gradio
duckduckgo_search
praisonai_tools
open-interpreter
xmlrunner
unittest2
+52
View File
@@ -0,0 +1,52 @@
---
title: "AgentQL structured data extraction Tool"
description: "Guide for using the AgentQL structured data extraction with PraisonAI agents."
icon: "code"
---
## Overview
AgentQL is a tool that allows you to extract structured data from webpages using AI Agents.
```bash
pip install langchain_agentql langchain-community
```
```bash
os.environ["AGENTQL_API_KEY"] = "your_api_key_here"
```
```python
from praisonaiagents import Agent, PraisonAIAgents
from langchain_agentql.tools import ExtractWebDataTool
from dotenv import load_dotenv
import os
os.environ["AGENTQL_API_KEY"] = os.getenv('AGENTQL_API_KEY')
def extract_web_data_tool(url, query):
agentql_tool = ExtractWebDataTool().invoke(
{
"url": url,
"prompt": query,
},)
return agentql_tool
# Create agent with web extraction instructions
orchestration_agent = Agent(
instructions="""Extract All 37 products from the url https://www.colorbarcosmetics.com/bestsellers along with its name, overview, description, price and additional information by recursively clicking on each product""",
tools=[extract_web_data_tool]
)
# Initialize and run agents
agents = PraisonAIAgents(agents=[orchestration_agent])
agents.start()
```
## Getting Started
1. Get your AgentQL API key from [AgentQL Dashboard](https://agentql.com)
2. Set the API key in your environment variables
3. Install the required dependencies
4. Use the example code to start extracting structured data
+28
View File
@@ -0,0 +1,28 @@
---
title: "Azure Container Apps dynamic sessions Code runtime Tool"
description: "Guide for using the Azure Container Apps dynamic sessions based code Interpreter tool with PraisonAI agents."
icon: "code"
---
## Overview
The Azure Container Apps dynamic sessions based code Interpreter tool is a tool that allows you to execute and run development environments using the AI Agents.
```bash
pip install langchain-azure-dynamic-sessions langchain-openai langchainhub langchain langchain-community
```
```python
from praisonaiagents import Agent, PraisonAIAgents
import getpass
from langchain_azure_dynamic_sessions import SessionsPythonREPLTool
POOL_MANAGEMENT_ENDPOINT = getpass.getpass()
coder_agent = Agent(instructions="""word = "strawberry"
count = word.count("r")
print(f"There are {count}'R's in the word 'Strawberry'")""", tools=[SessionsPythonREPLTool])
agents = PraisonAIAgents(agents=[coder_agent])
agents.start()
```
+25
View File
@@ -0,0 +1,25 @@
---
title: "Bearly Code Interpreter Tool"
description: "Guide for using the Bearly Code Interpreter tool with PraisonAI agents."
icon: "code"
---
## Overview
The Bearly Code Interpreter tool is a tool that allows you to execute various programming languages using the AI Agents.
```bash
pip install langchain-community
export BEARLY_API_KEY=your_api_key_here
```
```python
from praisonaiagents import Agent, PraisonAIAgents
from langchain_community.tools import BearlyInterpreterTool
coder_agent = Agent(instructions="""for i in range(0,10):
print(f'The number is {i}')""", tools=[BearlyInterpreterTool])
agents = PraisonAIAgents(agents=[coder_agent])
agents.start()
```
+38
View File
@@ -0,0 +1,38 @@
---
title: "BraveSearch Tool"
description: "Guide for using the BraveSearch tool with PraisonAI agents."
icon: "magnifying-glass"
---
## Overview
The BraveSearch tool is a tool that allows you to search the web using the BraveSearch API.
```bash
pip install langchain-community google-search-results
```
```bash
export BRAVE_SEARCH_API=your_api_key_here
export OPENAI_API_KEY=your_api_key_here
```
```python
from praisonaiagents import Agent, PraisonAIAgents
from langchain_community.tools import BraveSearch
import os
def search_brave(query: str):
"""Searches using BraveSearch and returns results."""
api_key = os.environ['BRAVE_SEARCH_API']
tool = BraveSearch.from_api_key(api_key=api_key, search_kwargs={"count": 3})
return tool.run(query)
data_agent = Agent(instructions="Search about AI job trends in 2025", tools=[search_brave])
editor_agent = Agent(instructions="Write a blog article")
agents = PraisonAIAgents(agents=[data_agent, editor_agent])
agents.start()
```
Generate your BraveSearch API key from [BraveSearch](https://brave.com/search/api/)
+24
View File
@@ -0,0 +1,24 @@
---
title: "DuckDuckGo Search Tool"
description: "Guide for using the DuckDuckGo Search tool with PraisonAI agents."
icon: "duck"
---
## Overview
The DuckDuckGo Search tool is a tool that allows you to search the web using the DuckDuckGo search engine.
```bash
pip install praisonaiagents
export OPENAI_API_KEY=your_api_key_here
```
```python
from praisonaiagents import Agent, PraisonAIAgents
from praisonaiagents.tools import duckduckgo
data_agent = Agent(instructions="Search and Read Research Papers on DNA Mutation", tools=[duckduckgo])
editor_agent = Agent(instructions="Write a scientifically researched outcome and findings about DNA Mutation")
agents = PraisonAIAgents(agents=[data_agent, editor_agent])
agents.start()
```
+35
View File
@@ -0,0 +1,35 @@
---
title: "Exa Search Tool"
description: "Guide for using the Exa Search tool with PraisonAI agents."
icon: "magnifying-glass-chart"
---
## Overview
The Exa Search tool is a tool that allows you to search the web and retrieve content using the Exa API.
```bash
pip install praisonaiagents exa-py
export EXA_API_KEY=your_api_key_here
export OPENAI_API_KEY=your_api_key_here
```
```python
from praisonaiagents import Agent, PraisonAIAgents
from exa_py import Exa
import os
exa = Exa(api_key=os.environ["EXA_API_KEY"])
def search_and_contents(query: str):
"""Search for webpages based on the query and retrieve their contents."""
# This combines two API endpoints: search and contents retrieval
return str(exa.search_and_contents(
query, use_autoprompt=False, num_results=5, text=True, highlights=True
))
data_agent = Agent(instructions="Find the latest jobs for Video Editor in New York at startups", tools=[search_and_contents])
editor_agent = Agent(instructions="Curate the available jobs at startups and their email for the candidate to apply based on his skills on Canva, Adobe Premiere Pro, and Adobe After Effects")
agents = PraisonAIAgents(agents=[data_agent, editor_agent], process='hierarchical')
agents.start()
```
+32
View File
@@ -0,0 +1,32 @@
---
title: "GoogleSearch Tool"
description: "Guide for using the GoogleSearch tool with PraisonAI agents."
icon: "magnifying-glass"
---
## Overview
The GoogleSearch tool is a tool that allows you to search the web using the GoogleSearch API.
```bash
pip install langchain-community langchain-google-community
```
```bash
os.environ["GOOGLE_CSE_ID"] = "YOUR_API_KEY"
os.environ["GOOGLE_API_KEY"] = "YOUR_API_KEY"
```
```python
import os
from langchain_google_community import GoogleSearchAPIWrapper
from praisonaiagents import Agent, PraisonAIAgents
data_agent = Agent(instructions="Search about best places to visit in India during Summer", tools=[GoogleSearchAPIWrapper])
editor_agent = Agent(instructions="Write a blog article")
agents = PraisonAIAgents(agents=[data_agent, editor_agent], process='hierarchical')
agents.start()
```
Generate your GoogleSearch API key from Google CloudConsole by clicking on [Create Credentials](https://console.cloud.google.com/apis/credentials)
To get a CSE ID, Create a Google Programmable Search Engine [here](https://programmablesearchengine.google.com/)
From the Overview of your newly created search engine copy the "Search engine ID"
+33
View File
@@ -0,0 +1,33 @@
---
title: "Google Serper Search Tool"
description: "Guide for using the Google Serper Search tool with PraisonAI agents."
icon: "google"
---
## Overview
The Google Serper Search tool is a tool that allows you to search the web using the Google Serper API.
```bash
pip install langchain-community python-dotenv
export SERPER_API_KEY=your_api_key_here
export OPENAI_API_KEY=your_api_key_here
```
```python
from praisonaiagents import Agent, PraisonAIAgents
from langchain_community.utilities import GoogleSerperAPIWrapper
import os
from dotenv import load_dotenv
load_dotenv()
os.environ['SERPER_API_KEY'] = os.getenv('SERPER_API_KEY')
search = GoogleSerperAPIWrapper()
data_agent = Agent(instructions="Suggest me top 5 most visited websites for Dosa Recipe", tools=[search])
editor_agent = Agent(instructions="List out the websites with their url and a short description")
agents = PraisonAIAgents(agents=[data_agent, editor_agent])
agents.start()
```
+34
View File
@@ -0,0 +1,34 @@
---
title: "Google Trends Tool"
description: "Guide for using the Google Trends tool with PraisonAI agents."
icon: "arrow-trend-up"
---
## Overview
The Google Trends tool is a tool that allows you to search the web using the Google Trends API.
```bash
pip install langchain-community google-search-results
```
```bash
export SERPAPI_API_KEY=your_api_key_here
```
```python
from langchain_community.utilities.google_trends import GoogleTrendsAPIWrapper
from praisonaiagents import Agent, PraisonAIAgents
research_agent = Agent(
instructions="Research trending topics related to AI",
tools=[GoogleTrendsAPIWrapper]
)
summarise_agent = Agent(
instructions="Summarise findings from the research agent",
)
agents = PraisonAIAgents(agents=[research_agent, summarise_agent])
agents.start()
```
+26
View File
@@ -0,0 +1,26 @@
---
title: "Jina Code Interpreter Tool"
description: "Guide for using the Jina Code Interpreter tool with PraisonAI agents."
icon: "code"
---
## Overview
The Jina Code Interpreter tool is a tool that allows you to execute various programming languages using the AI Agents.
```bash
pip install langchain-community rizaio
export RIZA_API_KEY=your_api_key_here
```
```python
from praisonaiagents import Agent, PraisonAIAgents
from langchain_community.tools.riza.command import ExecPython
coder_agent = Agent(instructions="""word = "strawberry"
count = word.count("r")
print(f"There are {count}'R's in the word 'Strawberry'")""", tools=[ExecPython])
agents = PraisonAIAgents(agents=[coder_agent])
agents.start()
```
+40
View File
@@ -0,0 +1,40 @@
---
title: "JinaSearch Tool"
description: "Guide for using the JinaSearch tool with PraisonAI agents."
icon: "magnifying-glass"
---
## Overview
The JinaSearch tool is a tool that allows you to search the web using the JinaSearch API.
```bash
pip install langchain-community
```
```bash
os.environ["JINA_API_KEY"]= "YOUR_API_KEY"
```
```python
from praisonaiagents import Agent, PraisonAIAgents
from langchain_community.tools import JinaSearch
import os
def invoke_jina_search(query: str):
JinaSearchTool = JinaSearch()
model_generated_tool_call = {
"args": {"query": query},
"id": "1",
"name": JinaSearchTool.name,
"type": "tool_call",
}
tool_msg = JinaSearchTool.invoke(model_generated_tool_call)
return(tool_msg.content[:1000])
data_agent = Agent(instructions="Find 10 websites where I can learn coding for free", tools=[invoke_jina_search])
editor_agent = Agent(instructions="write a listicle blog ranking the best websites. The blog should contain a proper intro and conclusion")
agents = PraisonAIAgents(agents=[data_agent, editor_agent], process='hierarchical')
agents.start()
```
Register on Jina Generate your JinaSearch API key from [Jina Platform](https://jina.ai/api-dashboard/key-manager)
+24
View File
@@ -0,0 +1,24 @@
---
title: "SearchApi Tool"
description: "Guide for using the SearchApi tool with PraisonAI agents."
icon: "searchengine"
---
## Overview
The SearchApi tool is a tool that allows you to search the web using the SearchApi.
```bash
export SEARCHAPI_API_KEY=your_api_key_here
```
```python
from praisonaiagents import Agent, PraisonAIAgents
from langchain_community.utilities import SearchApiAPIWrapper
data_agent = Agent(instructions="I am looking for the top google searches of 2025", tools=[SearchApiAPIWrapper])
editor_agent = Agent(instructions="Analyze the data and derive insights")
agents = PraisonAIAgents(agents=[data_agent, editor_agent])
agents.start()
```
+26
View File
@@ -0,0 +1,26 @@
---
title: "SerpAPI Tool"
description: "Guide for using the SerpAPI tool with PraisonAI agents."
icon: "searchengin"
---
## Overview
The SerpAPI tool is a tool that allows you to search the web using the SerpAPI.
```bash
pip install langchain-community google-search-results
export SERPAPI_API_KEY=your_api_key_here
export OPENAI_API_KEY=your_api_key_here
```
```python
from praisonaiagents import Agent, PraisonAIAgents
from langchain_community.utilities import SerpAPIWrapper
data_agent = Agent(instructions="Search about AI job trends in 2025", tools=[SerpAPIWrapper])
editor_agent = Agent(instructions="Write a blog article")
agents = PraisonAIAgents(agents=[data_agent, editor_agent])
agents.start()
```
+25
View File
@@ -0,0 +1,25 @@
---
title: "SerpSearch Tool"
description: "Guide for using the SerpSearch tool with PraisonAI agents."
icon: "searchengin"
---
## Overview
The SerpSearch tool is a tool that allows you to search the web using the SerpAPI.
```bash
pip install langchain-community google-search-results
export SERPAPI_API_KEY=your_api_key_here
export OPENAI_API_KEY=your_api_key_here
```
```python
from praisonaiagents import Agent, PraisonAIAgents
from langchain_community.utilities import SerpAPIWrapper
data_agent = Agent(instructions="Search about decline of recruitment across various industries with the rise of AI", tools=[SerpAPIWrapper])
editor_agent = Agent(instructions="Write a blog article pointing out the jobs most at rish due to the rise of AI")
agents = PraisonAIAgents(agents=[data_agent, editor_agent])
agents.start()
```
+35
View File
@@ -0,0 +1,35 @@
---
title: "TavilySearch Tool"
description: "Guide for using the TavilySearch tool with PraisonAI agents."
icon: "searchengine"
---
## Overview
The TavilySearch tool is a tool that allows you to search the web using the TavilySearch.
```bash
pip install "langchain-community>=0.2.11" tavily-python
export TAVILY_API_KEY=your_api_key_here
```
```python
from praisonaiagents import Agent, PraisonAIAgents
from langchain_community.tools import TavilySearchResults
def search_tool(query: str):
tool = TavilySearchResults(
max_results=5,
search_depth="advanced",
include_answer=True,
include_raw_content=True,
include_images=True
)
return tool.run(query)
data_agent = Agent(instructions="I am looking for the top google searches on AI tools of 2025", tools=[search_tool])
editor_agent = Agent(instructions="Analyze the data and rank the tools based on their popularity")
agents = PraisonAIAgents(agents=[data_agent, editor_agent])
agents.start()
```
+24
View File
@@ -0,0 +1,24 @@
---
title: "Wikipedia Search Tool"
description: "Guide for using the Wikipedia Search tool with PraisonAI agents."
icon: "wikipedia-w"
---
## Overview
The Wikipedia Search tool is a tool that allows you to search and retrieve information from Wikipedia.
```bash
pip install langchain-community
export OPENAI_API_KEY=your_api_key_here
```
```python
from praisonaiagents import Agent, PraisonAIAgents
from langchain_community.utilities import WikipediaAPIWrapper
data_agent = Agent(instructions="Gather all of Messi's record in LaLiga", tools=[WikipediaAPIWrapper])
summarise_agent = Agent(instructions="Summarize the data into a well structured format")
agents = PraisonAIAgents(agents=[data_agent, summarise_agent])
agents.start()
```
+25
View File
@@ -0,0 +1,25 @@
---
title: "YouSearchAPI Tool"
description: "Guide for using the YouSearchAPI tool with PraisonAI agents."
icon: "searchengine"
---
## Overview
The YouSearchAPI tool is a tool that allows you to search the web using the YouSearchAPI.
```bash
pip install langchain-community
export YDC_API_KEY=your_api_key_here
```
```python
from praisonaiagents import Agent, PraisonAIAgents
from langchain_community.utilities.you import YouSearchAPIWrapper
data_agent = Agent(instructions="Gather the weather data for Barcelona", tools=[YouSearchAPIWrapper])
editor_agent = Agent(instructions="Breifly describe the weather in Barcelona")
agents = PraisonAIAgents(agents=[data_agent, editor_agent])
agents.start()
```
+212 -53
View File
@@ -7,6 +7,217 @@ icon: "link-simple"
## Quick Start
<Tabs>
<Tab title="Code">
<Steps>
<Step title="Install Package">
First, install the required packages:
```bash
pip install praisonaiagents langchain-community wikipedia youtube-search
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable in your terminal:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create a file">
Create a new file `app.py` with the basic setup:
<CodeGroup>
```python Single Tool
from praisonaiagents import Agent
from langchain_community.utilities import WikipediaAPIWrapper
wiki_agent = Agent(
instructions="You are a wikipedia research Agent",
tools=[WikipediaAPIWrapper]
)
wiki_agent.start("Research 'Artificial Intelligence' on Wikipedia")
```
```python Multiple Tools
from praisonaiagents import Agent, PraisonAIAgents
from langchain_community.utilities import WikipediaAPIWrapper
from langchain_community.tools import YouTubeSearchTool
youtube_agent = Agent(
instructions="Search for information about 'AI advancements' on YouTube",
tools=[YouTubeSearchTool]
)
wiki_agent = Agent(
instructions="Research 'Artificial Intelligence' on Wikipedia",
tools=[WikipediaAPIWrapper]
)
agents = PraisonAIAgents(agents=[youtube_agent, wiki_agent])
agents.start()
```
</CodeGroup>
</Step>
<Step title="Start Agents">
Type this in your terminal to run your agents:
```bash
python app.py
```
</Step>
</Steps>
</Tab>
<Tab title="No Code">
<Steps>
<Step title="Install Package">
(Upcoming Feature)
Install the PraisonAI package:
```bash
pip install "praisonai"
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable in your terminal:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create a file">
Create a new file `agents.yaml` with the basic setup:
```yaml
framework: praisonai
process: sequential
roles:
researcher:
name: SearchAgent
role: Research Assistant
goal: Search for information from multiple sources
backstory: I am an AI assistant that can search YouTube and Wikipedia.
tools:
- youtube_search
- wikipedia
tasks:
search_task:
name: search_task
description: Search for information about 'AI advancements' on both YouTube and Wikipedia
expected_output: Combined information from YouTube videos and Wikipedia articles
```
</Step>
<Step title="Start Agents">
Type this in your terminal to run your agents:
```bash
praisonai agents.yaml
```
</Step>
</Steps>
</Tab>
</Tabs>
<Note>
**Requirements**
- Python 3.10 or higher
- OpenAI API key. Generate OpenAI API key [here](https://platform.openai.com/api-keys)
- LangChain compatible tools and utilities
</Note>
## Understanding LangChain Integration
<Card title="What is LangChain Integration?" icon="question">
LangChain integration enables agents to:
- Use LangChain's extensive tool ecosystem
- Access various data sources and APIs
- Leverage pre-built utilities and wrappers
- Combine multiple tools in a single agent
- Extend agent capabilities with community tools
</Card>
## Features
<CardGroup cols={2}>
<Card title="Tool Integration" icon="plug">
Seamlessly use LangChain tools with PraisonAI agents.
</Card>
<Card title="Multiple Sources" icon="database">
Access various data sources through LangChain utilities.
</Card>
<Card title="Community Tools" icon="users">
Leverage the extensive LangChain community ecosystem.
</Card>
<Card title="Custom Tools" icon="wrench">
Create and integrate custom LangChain tools.
</Card>
</CardGroup>
## LangChain Tools with Wrappers
<Note>
- LangChain tools with wrappers can be directly used as Tools without modification.
- PraisonAI will automatically detect the tool and use it.
- Some exceptions apply where it doesn't work.
</Note>
### Example Wrapper Usage
```bash
pip install langchain-community google-search-results
export SERPAPI_API_KEY=your_api_key_here
export OPENAI_API_KEY=your_api_key_here
```
```python
from praisonaiagents import Agent, PraisonAIAgents
from langchain_community.utilities import SerpAPIWrapper
data_agent = Agent(instructions="Search about AI job trends in 2025", tools=[SerpAPIWrapper])
editor_agent = Agent(instructions="Write a blog article")
agents = PraisonAIAgents(agents=[data_agent, editor_agent])
agents.start()
```
### Example without Wrapper Usage
```bash
pip install langchain-community
export BRAVE_SEARCH_API=your_api_key_here
export OPENAI_API_KEY=your_api_key_here
```
```python
from praisonaiagents import Agent, PraisonAIAgents
from langchain_community.tools import BraveSearch
import os
def search_brave(query: str):
"""Searches using BraveSearch and returns results."""
api_key = os.environ['BRAVE_SEARCH_API']
tool = BraveSearch.from_api_key(api_key=api_key, search_kwargs={"count": 3})
return tool.run(query)
data_agent = Agent(instructions="Search about AI job trends in 2025", tools=[search_brave])
editor_agent = Agent(instructions="Write a blog article")
agents = PraisonAIAgents(agents=[data_agent, editor_agent])
agents.start()
```
## Next Steps
<CardGroup cols={2}>
<Card title="Memory Integration" icon="brain" href="../concepts/memory">
Learn how to combine LangChain tools with agent memory
</Card>
<Card title="Custom Tools" icon="wrench" href="./tools">
Create your own custom tools for agents
</Card>
</CardGroup>
<Note>
For optimal results, ensure all required dependencies are installed and API keys are properly configured for each tool.
</Note>
## With More Detailed Instructions
<Tabs>
<Tab title="Code">
<Steps>
@@ -164,56 +375,4 @@ praisonai agents.yaml
</Step>
</Steps>
</Tab>
</Tabs>
<Note>
**Requirements**
- Python 3.10 or higher
- OpenAI API key. Generate OpenAI API key [here](https://platform.openai.com/api-keys)
- LangChain compatible tools and utilities
</Note>
## Understanding LangChain Integration
<Card title="What is LangChain Integration?" icon="question">
LangChain integration enables agents to:
- Use LangChain's extensive tool ecosystem
- Access various data sources and APIs
- Leverage pre-built utilities and wrappers
- Combine multiple tools in a single agent
- Extend agent capabilities with community tools
</Card>
## Features
<CardGroup cols={2}>
<Card title="Tool Integration" icon="plug">
Seamlessly use LangChain tools with PraisonAI agents.
</Card>
<Card title="Multiple Sources" icon="database">
Access various data sources through LangChain utilities.
</Card>
<Card title="Community Tools" icon="users">
Leverage the extensive LangChain community ecosystem.
</Card>
<Card title="Custom Tools" icon="wrench">
Create and integrate custom LangChain tools.
</Card>
</CardGroup>
## Next Steps
<CardGroup cols={2}>
<Card title="Memory Integration" icon="brain" href="../concepts/memory">
Learn how to combine LangChain tools with agent memory
</Card>
<Card title="Custom Tools" icon="wrench" href="./tools">
Create your own custom tools for agents
</Card>
</CardGroup>
<Note>
For optimal results, ensure all required dependencies are installed and API keys are properly configured for each tool.
</Note>
</Tabs>
+163 -29
View File
@@ -45,25 +45,172 @@ flowchart TB
Tools are functions that agents can use to interact with external systems and perform actions. They are essential for creating agents that can do more than just process text.
<Tabs>
<Tab title="Code">
<Steps>
<Step title="Install PraisonAI">
Install the core package:
```bash Terminal
pip install praisonaiagents duckduckgo-search
```
</Step>
<Step title="Configure Environment">
```bash Terminal
export OPENAI_API_KEY=your_openai_key
```
Generate your OpenAI API key from [OpenAI](https://platform.openai.com/api-keys)
Use other LLM providers like Ollama, Anthropic, Groq, Google, etc. Please refer to the [Models](/models) for more information.
</Step>
<Step title="Create Agent with Tool">
Create `app.py`
<CodeGroup>
```python Single Agent
from praisonaiagents import Agent
from duckduckgo_search import DDGS
# 1. Define the tool
def internet_search_tool(query: str):
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
# 2. Assign the tool to an agent
search_agent = Agent(
instructions="Perform internet searches to collect relevant information.",
tools=[internet_search_tool] # <--- Tool Assignment
)
# 3. Start Agent
search_agent.start("Search about AI job trends in 2025")
```
```python Multiple Agents
from praisonaiagents import Agent, PraisonAIAgents
from duckduckgo_search import DDGS
# 1. Define the tool
def internet_search_tool(query: str):
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
# 2. Assign the tool to an agent
search_agent = Agent(
instructions="Search about AI job trends in 2025",
tools=[internet_search_tool] # <--- Tool Assignment
)
blog_agent = Agent(
instructions="Write a blog article based on the previous agent's search results."
)
# 3. Start Agents
agents = PraisonAIAgents(agents=[search_agent, blog_agent])
agents.start()
```
</CodeGroup>
</Step>
<Step title="Start Agents">
Execute your script:
```bash Terminal
python app.py
```
</Step>
</Steps>
</Tab>
<Tab title="No Code">
<Steps>
<Step title="Install PraisonAI">
Install the core package and duckduckgo_search package:
```bash Terminal
pip install praisonai duckduckgo_search
```
</Step>
<Step title="Create Custom Tool">
<Info>
To add additional tools/features you need some coding which can be generated using ChatGPT or any LLM
</Info>
Create a new file `tools.py` with the following content:
```python
from duckduckgo_search import DDGS
from typing import List, Dict
# 1. Tool
def internet_search_tool(query: str) -> List[Dict]:
"""
Perform Internet Search
"""
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
```
</Step>
<Step title="Create Agent">
Create a new file `agents.yaml` with the following content:
```yaml
framework: praisonai
topic: create movie script about cat in mars
roles:
scriptwriter:
backstory: Expert in dialogue and script structure, translating concepts into
scripts.
goal: Write a movie script about a cat in Mars
role: Scriptwriter
tools:
- internet_search_tool # <-- Tool assigned to Agent here
tasks:
scriptwriting_task:
description: Turn the story concept into a production-ready movie script,
including dialogue and scene details.
expected_output: Final movie script with dialogue and scene details.
```
</Step>
<Step title="Start Agents">
Execute your script:
```bash Terminal
praisonai agents.yaml
```
</Step>
</Steps>
</Tab>
</Tabs>
## Creating Custom Tool
<Steps>
<Step>
Create any function that you want to use as a tool, that performs a specific task.
```python
from duckduckgo_search import DDGS
from typing import List, Dict
# Tool Implementation
def internet_search_tool(query: str) -> List[Dict]:
"""
Perform Internet Search using DuckDuckGo
Args:
query (str): The search query string
Returns:
List[Dict]: List of search results containing title, URL, and snippet
"""
def internet_search_tool(query: str):
results = []
ddgs = DDGS()
for result in ddgs.text(keywords=query, max_results=5):
@@ -79,11 +226,8 @@ def internet_search_tool(query: str) -> List[Dict]:
Assign the tool to an agent
```python
data_agent = Agent(
name="DataCollector",
role="Search Specialist",
goal="Perform internet searches to collect relevant information.",
backstory="Expert in finding and organising internet data.",
tools=[internet_search_tool], ## Add the tool to the agent i.e the function name
instructions="Search about AI job trends in 2025",
tools=[internet_search_tool], # <-- Tool Assignment
)
```
</Step>
@@ -93,7 +237,7 @@ Assign the tool to an agent
<Check>You have created a custom tool and assigned it to an agent.</Check>
</Card>
## Implementing Tools Full Code Example
## Creating Custom Tool with Detailed Instructions
<Tabs>
<Tab title="Code">
@@ -119,19 +263,9 @@ pip install praisonaiagents duckduckgo-search
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
from duckduckgo_search import DDGS
from typing import List, Dict
# 1. Tool Implementation
def internet_search_tool(query: str) -> List[Dict]:
"""
Perform Internet Search using DuckDuckGo
Args:
query (str): The search query string
Returns:
List[Dict]: List of search results containing title, URL, and snippet
"""
def internet_search_tool(query: str):
results = []
ddgs = DDGS()
for result in ddgs.text(keywords=query, max_results=5):
@@ -0,0 +1,27 @@
from praisonaiagents import Agent, PraisonAIAgents
from langchain_agentql.tools import ExtractWebDataTool
from dotenv import load_dotenv
load_dotenv()
import os
os.environ["AGENTQL_API_KEY"] = os.getenv('AGENTQL_API_KEY')
def extract_web_data_tool(url, query):
agentql_tool = ExtractWebDataTool().invoke(
{
"url": url,
"prompt": query,
},)
return agentql_tool
# Create agent with web extraction instructions
orchestration_agent = Agent(
instructions="""Extract All 37 products from the url https://www.colorbarcosmetics.com/bestsellers along with its name, overview, description, price and additional information by recursively clicking on each product""",
tools=[extract_web_data_tool]
)
# Initialize and run agents
agents = PraisonAIAgents(agents=[orchestration_agent])
agents.start()
@@ -0,0 +1,12 @@
from praisonaiagents import Agent, PraisonAIAgents
import getpass
from langchain_azure_dynamic_sessions import SessionsPythonREPLTool
POOL_MANAGEMENT_ENDPOINT = getpass.getpass()
coder_agent = Agent(instructions="""word = "strawberry"
count = word.count("r")
print(f"There are {count}'R's in the word 'Strawberry'")""", tools=[SessionsPythonREPLTool])
agents = PraisonAIAgents(agents=[coder_agent])
agents.start()
@@ -0,0 +1,8 @@
from praisonaiagents import Agent, PraisonAIAgents
from langchain_community.tools import BearlyInterpreterTool
coder_agent = Agent(instructions="""for i in range(0,10):
print(f'The number is {i}')""", tools=[BearlyInterpreterTool])
agents = PraisonAIAgents(agents=[coder_agent])
agents.start()
+18
View File
@@ -0,0 +1,18 @@
# pip install langchain-community
# export BRAVE_SEARCH_API=your_api_key_here
# export OPENAI_API_KEY=your_api_key_here
from praisonaiagents import Agent, PraisonAIAgents
from langchain_community.tools import BraveSearch
import os
def search_brave(query: str):
"""Searches using BraveSearch and returns results."""
api_key = os.environ['BRAVE_SEARCH_API']
tool = BraveSearch.from_api_key(api_key=api_key, search_kwargs={"count": 3})
return tool.run(query)
data_agent = Agent(instructions="Search about AI job trends in 2025", tools=[search_brave])
editor_agent = Agent(instructions="Write a blog article")
agents = PraisonAIAgents(agents=[data_agent, editor_agent])
agents.start()
@@ -0,0 +1,7 @@
from praisonaiagents import Agent, PraisonAIAgents
from praisonaiagents.tools import duckduckgo
data_agent = Agent(instructions="Search and Read Research Papers on DNA Mutation", tools=[duckduckgo])
editor_agent = Agent(instructions="Write a scientifically researched outcome and findings about DNA Mutation")
agents = PraisonAIAgents(agents=[data_agent, editor_agent])
agents.start()
+17
View File
@@ -0,0 +1,17 @@
from praisonaiagents import Agent, PraisonAIAgents
from exa_py import Exa
import os
exa = Exa(api_key=os.environ["EXA_API_KEY"])
def search_and_contents(query: str):
"""Search for webpages based on the query and retrieve their contents."""
# This combines two API endpoints: search and contents retrieval
return str(exa.search_and_contents(
query, use_autoprompt=False, num_results=5, text=True, highlights=True
))
data_agent = Agent(instructions="Find the latest jobs for Video Editor in New York at startups", tools=[search_and_contents])
editor_agent = Agent(instructions="Curate the available jobs at startups and their email for the candidate to apply based on his skills on Canva, Adobe Premiere Pro, and Adobe After Effects")
agents = PraisonAIAgents(agents=[data_agent, editor_agent], process='hierarchical')
agents.start()
@@ -0,0 +1,8 @@
import os
from langchain_google_community import GoogleSearchAPIWrapper
from praisonaiagents import Agent, PraisonAIAgents
data_agent = Agent(instructions="Search about best places to visit in India during Summer", tools=[GoogleSearchAPIWrapper])
editor_agent = Agent(instructions="Write a blog article")
agents = PraisonAIAgents(agents=[data_agent, editor_agent], process='hierarchical')
agents.start()
@@ -0,0 +1,15 @@
from praisonaiagents import Agent, PraisonAIAgents
from langchain_community.utilities import GoogleSerperAPIWrapper
import os
from dotenv import load_dotenv
load_dotenv()
os.environ['SERPER_API_KEY'] = os.getenv('SERPER_API_KEY')
search = GoogleSerperAPIWrapper()
data_agent = Agent(instructions="Suggest me top 5 most visited websites for Dosa Recipe", tools=[search])
editor_agent = Agent(instructions="List out the websites with their url and a short description")
agents = PraisonAIAgents(agents=[data_agent, editor_agent])
agents.start()
+18
View File
@@ -0,0 +1,18 @@
# pip install langchain-community google-search-results
# export SERPAPI_API_KEY=your_api_key_here
# export OPENAI_API_KEY=your_api_key_here
from langchain_community.utilities.google_trends import GoogleTrendsAPIWrapper
from praisonaiagents import Agent, PraisonAIAgents
research_agent = Agent(
instructions="Research trending topics related to AI",
tools=[GoogleTrendsAPIWrapper]
)
summarise_agent = Agent(
instructions="Summarise findings from the research agent",
)
agents = PraisonAIAgents(agents=[research_agent, summarise_agent])
agents.start()
@@ -0,0 +1,9 @@
from praisonaiagents import Agent, PraisonAIAgents
from langchain_community.tools.riza.command import ExecPython
coder_agent = Agent(instructions="""word = "strawberry"
count = word.count("r")
print(f"There are {count}'R's in the word 'Strawberry'")""", tools=[ExecPython])
agents = PraisonAIAgents(agents=[coder_agent])
agents.start()
+19
View File
@@ -0,0 +1,19 @@
from praisonaiagents import Agent, PraisonAIAgents
from langchain_community.tools import JinaSearch
import os
def invoke_jina_search(query: str):
JinaSearchTool = JinaSearch()
model_generated_tool_call = {
"args": {"query": query},
"id": "1",
"name": JinaSearchTool.name,
"type": "tool_call",
}
tool_msg = JinaSearchTool.invoke(model_generated_tool_call)
return(tool_msg.content[:1000])
data_agent = Agent(instructions="Find 10 websites where I can learn coding for free", tools=[invoke_jina_search])
editor_agent = Agent(instructions="write a listicle blog ranking the best websites. The blog should contain a proper intro and conclusion")
agents = PraisonAIAgents(agents=[data_agent, editor_agent], process='hierarchical')
agents.start()
@@ -0,0 +1,8 @@
from praisonaiagents import Agent, PraisonAIAgents
from langchain_community.utilities import SearchApiAPIWrapper
data_agent = Agent(instructions="I am looking for the top google searches of 2025", tools=[SearchApiAPIWrapper])
editor_agent = Agent(instructions="Analyze the data and derive insights")
agents = PraisonAIAgents(agents=[data_agent, editor_agent])
agents.start()
+12
View File
@@ -0,0 +1,12 @@
# pip install langchain-community google-search-results
# export SERPAPI_API_KEY=your_api_key_here
# export OPENAI_API_KEY=your_api_key_here
from praisonaiagents import Agent, PraisonAIAgents
from langchain_community.utilities import SerpAPIWrapper
data_agent = Agent(instructions="Search about AI job trends in 2025", tools=[SerpAPIWrapper])
editor_agent = Agent(instructions="Write a blog article")
agents = PraisonAIAgents(agents=[data_agent, editor_agent])
agents.start()
+7
View File
@@ -0,0 +1,7 @@
from praisonaiagents import Agent, PraisonAIAgents
from langchain_community.utilities import SerpAPIWrapper
data_agent = Agent(instructions="Search about decline of recruitment across various industries with the rise of AI", tools=[SerpAPIWrapper])
editor_agent = Agent(instructions="Write a blog article pointing out the jobs most at rish due to the rise of AI")
agents = PraisonAIAgents(agents=[data_agent, editor_agent])
agents.start()
+18
View File
@@ -0,0 +1,18 @@
from praisonaiagents import Agent, PraisonAIAgents
from langchain_community.tools import TavilySearchResults
def search_tool(query: str):
tool = TavilySearchResults(
max_results=5,
search_depth="advanced",
include_answer=True,
include_raw_content=True,
include_images=True
)
return tool.run(query)
data_agent = Agent(instructions="I am looking for the top google searches on AI tools of 2025", tools=[search_tool])
editor_agent = Agent(instructions="Analyze the data and rank the tools based on their popularity")
agents = PraisonAIAgents(agents=[data_agent, editor_agent])
agents.start()
@@ -0,0 +1,7 @@
from praisonaiagents import Agent, PraisonAIAgents
from langchain_community.utilities import WikipediaAPIWrapper
data_agent = Agent(instructions="Gather all of Messi's record in LaLiga", tools=[WikipediaAPIWrapper])
summarise_agent = Agent(instructions="Summarize the data into a well structured format")
agents = PraisonAIAgents(agents=[data_agent, summarise_agent])
agents.start()
+8
View File
@@ -0,0 +1,8 @@
from praisonaiagents import Agent, PraisonAIAgents
from langchain_community.utilities.you import YouSearchAPIWrapper
data_agent = Agent(instructions="Gather the weather data for Barcelona", tools=[YouSearchAPIWrapper])
editor_agent = Agent(instructions="Breifly describe the weather in Barcelona")
agents = PraisonAIAgents(agents=[data_agent, editor_agent])
agents.start()
+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.76.tar.gz"
url "https://github.com/MervinPraison/PraisonAI/archive/refs/tags/2.0.81.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.76 gunicorn markdown\n")
file.write("RUN pip install flask praisonai==2.0.81 gunicorn markdown\n")
file.write("EXPOSE 8080\n")
file.write('CMD ["gunicorn", "-b", "0.0.0.0:8080", "api:app"]\n')
+32
View File
@@ -240,6 +240,32 @@ class TrainVisionModel:
quantization_method="q4_k_m"
)
def prepare_modelfile_content(self):
output_model = self.config["hf_model_name"]
template = '''{{- range $index, $_ := .Messages }}<|start_header_id|>{{ .Role }}<|end_header_id|>
{{ .Content }}
{{- if gt (len (slice $.Messages $index)) 1 }}<|eot_id|>
{{- else if ne .Role "assistant" }}<|eot_id|><|start_header_id|>assistant<|end_header_id|>
{{ end }}
{{- end }}'''
return f"""FROM {output_model}
TEMPLATE {template}
PARAMETER temperature 0.6
PARAMETER top_p 0.9
"""
def create_and_push_ollama_model(self):
modelfile_content = self.prepare_modelfile_content()
with open("Modelfile", "w") as file:
file.write(modelfile_content)
subprocess.run(["ollama", "serve"])
subprocess.run(["ollama", "create", f"{self.config['ollama_model']}:{self.config['model_parameters']}", "-f", "Modelfile"])
subprocess.run(["ollama", "push", f"{self.config['ollama_model']}:{self.config['model_parameters']}"])
def run(self):
self.print_system_info()
self.check_gpu()
@@ -247,6 +273,12 @@ class TrainVisionModel:
if self.config.get("train", "true").lower() == "true":
self.prepare_model()
self.train_model()
if self.config.get("huggingface_save", "true").lower() == "true":
self.save_model_merged()
if self.config.get("huggingface_save_gguf", "true").lower() == "true":
self.push_model_gguf()
if self.config.get("ollama_save", "true").lower() == "true":
self.create_and_push_ollama_model()
def main():
+140
View File
@@ -0,0 +1,140 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This script handles uploading trained vision models to Hugging Face and Ollama.
It reads configuration from config.yaml and provides options to upload in different formats.
"""
import os
import yaml
import torch
import shutil
import subprocess
from unsloth import FastVisionModel
class UploadVisionModel:
def __init__(self, config_path="config.yaml"):
self.load_config(config_path)
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.model = None
self.hf_tokenizer = None
def load_config(self, path):
"""Load configuration from yaml file."""
with open(path, "r") as file:
self.config = yaml.safe_load(file)
print("DEBUG: Loaded config:", self.config)
def prepare_model(self):
"""Load the trained model for uploading."""
print("DEBUG: Loading trained model and tokenizer...")
self.model, original_tokenizer = FastVisionModel.from_pretrained(
model_name=self.config.get("output_dir", "lora_model"),
load_in_4bit=self.config.get("load_in_4bit", True)
)
self.hf_tokenizer = original_tokenizer
print("DEBUG: Model and tokenizer loaded successfully.")
def save_model_merged(self):
"""Save merged model to Hugging Face Hub."""
print(f"DEBUG: Saving merged model to Hugging Face Hub: {self.config['hf_model_name']}")
if os.path.exists(self.config["hf_model_name"]):
shutil.rmtree(self.config["hf_model_name"])
self.model.push_to_hub_merged(
self.config["hf_model_name"],
self.hf_tokenizer,
save_method="merged_16bit",
token=os.getenv("HF_TOKEN")
)
print("DEBUG: Model saved to Hugging Face Hub successfully.")
def push_model_gguf(self):
"""Push model in GGUF format to Hugging Face Hub."""
print(f"DEBUG: Pushing GGUF model to Hugging Face Hub: {self.config['hf_model_name']}")
self.model.push_to_hub_gguf(
self.config["hf_model_name"],
self.hf_tokenizer,
quantization_method=self.config.get("quantization_method", "q4_k_m"),
token=os.getenv("HF_TOKEN")
)
print("DEBUG: GGUF model pushed to Hugging Face Hub successfully.")
def prepare_modelfile_content(self):
"""Prepare Ollama modelfile content using Llama 3.2 vision template."""
output_model = self.config["hf_model_name"]
# Using Llama 3.2 vision template format
template = """{{- range $index, $_ := .Messages }}<|start_header_id|>{{ .Role }}<|end_header_id|>
{{ .Content }}
{{- if gt (len (slice $.Messages $index)) 1 }}<|eot_id|>
{{- else if ne .Role "assistant" }}<|eot_id|><|start_header_id|>assistant<|end_header_id|>
{{ end }}
{{- end }}"""
# Assemble the modelfile content with Llama 3.2 vision parameters
modelfile = f"FROM {output_model}\n"
modelfile += "TEMPLATE \"""" + template + "\"""\n"
modelfile += "PARAMETER temperature 0.6\n"
modelfile += "PARAMETER top_p 0.9\n"
return modelfile
def create_and_push_ollama_model(self):
"""Create and push model to Ollama."""
print(f"DEBUG: Creating Ollama model: {self.config['ollama_model']}:{self.config['model_parameters']}")
modelfile_content = self.prepare_modelfile_content()
with open("Modelfile", "w") as file:
file.write(modelfile_content)
print("DEBUG: Starting Ollama server...")
subprocess.run(["ollama", "serve"])
print("DEBUG: Creating Ollama model...")
subprocess.run([
"ollama", "create",
f"{self.config['ollama_model']}:{self.config['model_parameters']}",
"-f", "Modelfile"
])
print("DEBUG: Pushing model to Ollama...")
subprocess.run([
"ollama", "push",
f"{self.config['ollama_model']}:{self.config['model_parameters']}"
])
print("DEBUG: Model pushed to Ollama successfully.")
def upload(self, target="all"):
"""
Upload the model to specified targets.
Args:
target (str): One of 'all', 'huggingface', 'huggingface_gguf', or 'ollama'
"""
self.prepare_model()
if target in ["all", "huggingface"]:
self.save_model_merged()
if target in ["all", "huggingface_gguf"]:
self.push_model_gguf()
if target in ["all", "ollama"]:
self.create_and_push_ollama_model()
def main():
import argparse
parser = argparse.ArgumentParser(description="Upload Vision Model to Various Platforms")
parser.add_argument("--config", default="config.yaml", help="Path to configuration file")
parser.add_argument(
"--target",
choices=["all", "huggingface", "huggingface_gguf", "ollama"],
default="all",
help="Target platform to upload to"
)
args = parser.parse_args()
uploader = UploadVisionModel(config_path=args.config)
uploader.upload(target=args.target)
if __name__ == "__main__":
main()
+4 -4
View File
@@ -1,6 +1,6 @@
[project]
name = "PraisonAI"
version = "2.0.76"
version = "2.0.81"
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.61",
"praisonaiagents>=0.0.67",
"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.76"
version = "2.0.81"
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.61"
praisonaiagents = ">=0.0.67"
python-dotenv = ">=0.19.0"
instructor = ">=1.3.3"
PyYAML = ">=6.0"
+37
View File
@@ -0,0 +1,37 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are a Wikipedia Agent",
llm="anthropic/claude-3-7-sonnet-20250219"
)
result = agent.start("Why Sky is Blue?")
print(result)
from praisonaiagents import Agent
from praisonaiagents.tools import internet_search
agent = Agent(
instructions="You are a Wikipedia Agent",
tools=[internet_search],
llm="anthropic/claude-3-7-sonnet-20250219"
)
agent.start("What is Praison AI?")
from praisonaiagents import Agent, PraisonAIAgents
from praisonaiagents.tools import internet_search
research_agent = Agent(
instructions="Search Information about Claude Sonnet 3.7",
tools=[internet_search],
llm="anthropic/claude-3-7-sonnet-20250219"
)
editor_agent = Agent(
instructions="Write a Blog Post with the provided information about Claude Sonnet 3.7",
llm="anthropic/claude-3-7-sonnet-20250219"
)
agents = PraisonAIAgents(agents=[research_agent, editor_agent])
result = agents.start()
print(result)
+4 -4
View File
@@ -1,10 +1,10 @@
from praisonaiagents import Agent
from praisonaiagents.tools import internet_search
agent = Agent(
instructions="You are a helpful assistant",
llm="gemini/gemini-1.5-flash-8b",
self_reflect=True,
verbose=True
tools=[internet_search],
llm="gemini/gemini-1.5-flash-8b"
)
agent.start("Why sky is Blue?")
agent.start("What is Praison AI?")
+18
View File
@@ -0,0 +1,18 @@
from praisonaiagents import Agent
from praisonaiagents.tools import wiki_search, wiki_summary, wiki_page, wiki_random, wiki_language
agent1 = Agent(
instructions="You are a Wikipedia Agent",
tools=[wiki_search, wiki_summary, wiki_page, wiki_random, wiki_language],
llm="openai/gpt-4o-mini",
verbose=10
)
agent1.start("history of AI in 1 line")
agent2 = Agent(
instructions="You are a Wikipedia Agent",
tools=[wiki_search, wiki_summary, wiki_page, wiki_random, wiki_language],
llm="gpt-4o-mini",
verbose=10
)
agent2.start("history of AI in 1 line")
@@ -0,0 +1,13 @@
from praisonaiagents import Agent, MCP
agent = Agent(
instructions="""You are a helpful assistant that can check stock prices and perform other tasks.
Use the available tools when relevant to answer user questions.""",
llm="gpt-4o-mini",
tools=MCP(
command="/Users/praison/miniconda3/envs/mcp/bin/python",
args=["/Users/praison/stockprice/app.py"]
)
)
agent.start("What is the stock price of Tesla?")
+10
View File
@@ -0,0 +1,10 @@
from praisonaiagents import Agent, MCP
agent = Agent(
instructions="""You are a helpful assistant that can check stock prices and perform other tasks.
Use the available tools when relevant to answer user questions.""",
llm="gpt-4o-mini",
tools = MCP("/Users/praison/miniconda3/envs/mcp/bin/python /Users/praison/stockprice/app.py")
)
agent.start("What is the stock price of Tesla?")
+61
View File
@@ -0,0 +1,61 @@
import asyncio
from praisonaiagents import Agent
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
# Define server configuration - pointing to your stock price app
server_params = StdioServerParameters(
command="/Users/praison/miniconda3/envs/mcp/bin/python",
args=[
"/Users/praison/stockprice/app.py",
],
)
# Function to get stock price using MCP
async def get_stock_price(symbol):
# Start server and connect client
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
# Initialize the connection
await session.initialize()
# Get tools
tools_result = await session.list_tools()
tools = tools_result.tools
print(f"Available tools: {[tool.name for tool in tools]}")
# Find a tool that can get stock prices
# Assuming there's a tool like "get_stock_price" or similar
stock_tool = None
for tool in tools:
if "stock" in tool.name.lower() or "price" in tool.name.lower():
stock_tool = tool
break
if stock_tool:
print(f"Using tool: {stock_tool.name}")
# Call the tool with the stock symbol
result = await session.call_tool(
stock_tool.name,
arguments={"ticker": symbol}
)
return result
else:
return "No suitable stock price tool found"
# Create a custom tool for the agent
def stock_price_tool(symbol: str) -> str:
"""Get the current stock price for a given symbol"""
# Run the async function to get the stock price
result = asyncio.run(get_stock_price(symbol))
return f"Stock price for {symbol}: {result}"
# Create agent with the stock price tool
agent = Agent(
instructions="You are a helpful assistant that can check stock prices. When asked about stock prices, use the stock_price_tool.",
llm="gpt-4o-mini",
tools=[stock_price_tool]
)
# Start the agent
agent.start("What is the stock price of Tesla?")
+23
View File
@@ -0,0 +1,23 @@
from praisonaiagents import Agent, MCP
import os
stock_agent = Agent(
instructions="""You are a helpful assistant that can check stock prices and perform other tasks.
Use the available tools when relevant to answer user questions.""",
llm="gpt-4o-mini",
tools=MCP(
command="/Users/praison/miniconda3/envs/mcp/bin/python",
args=["/Users/praison/stockprice/app.py"]
)
)
brave_api_key = os.getenv("BRAVE_API_KEY")
search_agent = Agent(
instructions="""You are a helpful assistant that can search the web for information.
Use the available tools when relevant to answer user questions.""",
llm="gpt-4o-mini",
tools=MCP(f'npx -y @smithery/cli@latest install @smithery-ai/brave-search --client claude --config "{{\\\"braveApiKey\\\":\\\"{brave_api_key}\\\"}}"')
)
stock_agent.start("What is the stock price of Tesla?")
search_agent.start("Search more information about Praison AI")
@@ -0,0 +1,18 @@
from praisonaiagents import Agent
import npx_mcp_wrapper_main
search_agent = Agent(
instructions="""You help book apartments on Airbnb.""",
llm="gpt-4o-mini",
tools=npx_mcp_wrapper_main.MCP(
command="npx",
args=[
"-y",
"@openbnb/mcp-server-airbnb",
"--ignore-robots-txt",
]
)
)
search_agent.start("I want to book an apartment in Paris for 2 nights. 03/28 - 03/30 for 2 adults")
@@ -0,0 +1,25 @@
from praisonaiagents import Agent, MCP
search_agent = Agent(
instructions="""You help book apartments on Airbnb.""",
llm="gpt-4o-mini",
tools=MCP(
command="npx",
args=[
"-y",
"@openbnb/mcp-server-airbnb",
"--ignore-robots-txt",
]
)
)
search_agent.start("I want to book an apartment in Paris for 2 nights. 03/28 - 03/30 for 2 adults")
agent = Agent(
instructions="""You are a helpful assistant that can check stock prices and perform other tasks.
Use the available tools when relevant to answer user questions.""",
llm="gpt-4o-mini",
tools = MCP("/Users/praison/miniconda3/envs/mcp/bin/python /Users/praison/stockprice/app.py")
)
agent.start("What is the stock price of Tesla?")
+16
View File
@@ -0,0 +1,16 @@
from praisonaiagents import Agent, MCP
search_agent = Agent(
instructions="""You help book apartments on Airbnb.""",
llm="gpt-4o-mini",
tools=MCP(
command="npx",
args=[
"-y",
"@openbnb/mcp-server-airbnb",
"--ignore-robots-txt",
]
)
)
search_agent.start("I want to book an apartment in Paris for 2 nights. 03/28 - 03/30 for 2 adults")
+24
View File
@@ -0,0 +1,24 @@
from praisonaiagents import Agent, MCP
search_agent = Agent(
instructions="""You are a helpful assistant that can search the web for information.
Use the available tools when relevant to answer user questions.""",
llm="gpt-4o-mini",
tools=MCP(
command="npx",
args=[
"-y",
"@smithery/cli@latest",
"install",
"@smithery-ai/brave-search",
"--client",
"claude",
"--config",
'{"braveApiKey":"BSANfDaqLKO9wq7e08mrPth9ZlJvKtc"}'
],
timeout=30, # 3 minutes for brave-search
debug=True # Enable detailed logging
)
)
search_agent.start("Search more information about Praison AI")
@@ -0,0 +1,67 @@
from google import genai
from google.genai import types
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
import os
client = genai.Client(
api_key=os.getenv("GEMINI_API_KEY")
) # Replace with your actual API key setup
# Create server parameters for stdio connection
server_params = StdioServerParameters(
command="npx", # Executable
args=[
"-y",
"@openbnb/mcp-server-airbnb",
"--ignore-robots-txt",
], # Optional command line arguments
env=None, # Optional environment variables
)
async def run():
async with stdio_client(server_params) as (read, write):
async with ClientSession(
read,
write,
) as session:
prompt = "I want to book an apartment in Paris for 2 nights. 03/28 - 03/30"
# Initialize the connection
await session.initialize()
# Get tools from MCP session and convert to Gemini Tool objects
mcp_tools = await session.list_tools()
tools = types.Tool(function_declarations=[
{
"name": tool.name,
"description": tool.description,
"parameters": tool.inputSchema,
}
for tool in mcp_tools.tools
])
# Send request with function declarations
response = client.models.generate_content(
model="gemini-2.0-flash", # Or your preferred model supporting function calling
contents=prompt,
config=types.GenerateContentConfig(
temperature=0.7,
tools=[tools],
), # Example other config
)
# Check for a function call
if response.candidates[0].content.parts[0].function_call:
function_call = response.candidates[0].content.parts[0].function_call
print(f"Function to call: {function_call.name}")
print(f"Arguments: {function_call.args}")
# In a real app, you would call your function here:
# result = await session.call_tool(function_call.args, arguments=function_call.args)
# sent new request with function call
else:
print("No function call found in the response.")
print(response.text)
if __name__ == "__main__":
import asyncio
asyncio.run(run())
@@ -0,0 +1,121 @@
from typing import List
from google import genai
from google.genai import types
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
import os
client = genai.Client(api_key=os.getenv("GEMINI_API_KEY"))
model = "gemini-2.0-flash"
# Create server parameters for stdio connection
server_params = StdioServerParameters(
command="npx", # Executable
args=[
"-y",
"@openbnb/mcp-server-airbnb",
"--ignore-robots-txt",
], # Optional command line arguments
env=None, # Optional environment variables
)
async def agent_loop(prompt: str, client: genai.Client, session: ClientSession):
contents = [types.Content(role="user", parts=[types.Part(text=prompt)])]
# Initialize the connection
await session.initialize()
# --- 1. Get Tools from Session and convert to Gemini Tool objects ---
mcp_tools = await session.list_tools()
tools = types.Tool(function_declarations=[
{
"name": tool.name,
"description": tool.description,
"parameters": tool.inputSchema,
}
for tool in mcp_tools.tools
])
# --- 2. Initial Request with user prompt and function declarations ---
response = await client.aio.models.generate_content(
model=model, # Or your preferred model supporting function calling
contents=contents,
config=types.GenerateContentConfig(
temperature=0,
tools=[tools],
), # Example other config
)
# --- 3. Append initial response to contents ---
contents.append(response.candidates[0].content)
# --- 4. Tool Calling Loop ---
turn_count = 0
max_tool_turns = 5
while response.function_calls and turn_count < max_tool_turns:
turn_count += 1
tool_response_parts: List[types.Part] = []
# --- 4.1 Process all function calls in order and return in this turn ---
for fc_part in response.function_calls:
tool_name = fc_part.name
args = fc_part.args or {} # Ensure args is a dict
print(f"Attempting to call MCP tool: '{tool_name}' with args: {args}")
tool_response: dict
try:
# Call the session's tool executor
tool_result = await session.call_tool(tool_name, args)
print(f"MCP tool '{tool_name}' executed successfully.")
if tool_result.isError:
tool_response = {"error": tool_result.content[0].text}
else:
tool_response = {"result": tool_result.content[0].text}
except Exception as e:
tool_response = {"error": f"Tool execution failed: {type(e).__name__}: {e}"}
# Prepare FunctionResponse Part
tool_response_parts.append(
types.Part.from_function_response(
name=tool_name, response=tool_response
)
)
# --- 4.2 Add the tool response(s) to history ---
contents.append(types.Content(role="user", parts=tool_response_parts))
print(f"Added {len(tool_response_parts)} tool response parts to history.")
# --- 4.3 Make the next call to the model with updated history ---
print("Making subsequent API call with tool responses...")
response = await client.aio.models.generate_content(
model=model,
contents=contents, # Send updated history
config=types.GenerateContentConfig(
temperature=1.0,
tools=[tools],
), # Keep sending same config
)
contents.append(response.candidates[0].content)
if turn_count >= max_tool_turns and response.function_calls:
print(f"Maximum tool turns ({max_tool_turns}) reached. Exiting loop.")
print("MCP tool calling loop finished. Returning final response.")
# --- 5. Return Final Response ---
return response
async def run():
async with stdio_client(server_params) as (read, write):
async with ClientSession(
read,
write,
) as session:
# Test prompt
prompt = "I want to book an apartment in Paris for 2 nights. 03/28 - 03/30"
print(f"Running agent loop with prompt: {prompt}")
# Run agent loop
res = await agent_loop(prompt, client, session)
return res
if __name__ == "__main__":
import asyncio
res = asyncio.run(run())
print(res.text)
+68
View File
@@ -0,0 +1,68 @@
"""
MCP Client using the MCPWrapper to interact with MCP servers.
This script demonstrates how to use the MCPWrapper to connect to an MCP server
and execute queries using Google's Gemini models.
"""
import os
import asyncio
import argparse
from dotenv import load_dotenv
from mcp_wrapper import MCPWrapper
# Load environment variables from .env file if it exists
load_dotenv()
async def main():
parser = argparse.ArgumentParser(description='MCP Client for Gemini')
parser.add_argument('--api-key', help='Google API key for Gemini')
parser.add_argument('--model', default='gemini-1.5-pro', help='Model to use (default: gemini-1.5-pro)')
args = parser.parse_args()
# Get API key from args or environment
api_key = args.api_key or os.getenv("GEMINI_API_KEY")
if not api_key:
print("Error: API key must be provided via --api-key or GEMINI_API_KEY environment variable")
return
# Create the MCP wrapper
wrapper = MCPWrapper(api_key=api_key, model=args.model)
try:
# Connect to the test MCP server
print("Connecting to test MCP server...")
await wrapper.connect_to_server(
command="python",
args=[
"/Users/praison/praisonai-package/src/praisonai-agents/mcp_test_server.py",
]
)
# Interactive mode
print("\nMCP Client Started!")
print("Type your queries or 'quit' to exit.")
while True:
query = input("\nQuery: ").strip()
if query.lower() == 'quit':
break
print("Processing query...")
response = await wrapper.execute_query(query)
print("\nResponse:")
print(response.text)
except Exception as e:
print(f"Error: {e}")
finally:
# Close the session
if wrapper.session:
await wrapper.close()
print("Session closed.")
if __name__ == "__main__":
asyncio.run(main())
+248
View File
@@ -0,0 +1,248 @@
"""
MCP Wrapper for Google's Gemini models.
This module provides a wrapper for the Model Context Protocol (MCP) to be used with
Google's Gemini models.
"""
import os
from typing import List, Dict, Optional
from contextlib import AsyncExitStack
from dotenv import load_dotenv
from google import genai
from google.genai import types
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
# Load environment variables from .env file if it exists
load_dotenv()
class MCPWrapper:
"""
A wrapper for the Model Context Protocol (MCP) to be used with Google's Gemini models.
This class provides methods to connect to MCP servers and execute queries using
Google's Gemini models.
"""
def __init__(self, api_key: Optional[str] = None, model: str = "gemini-1.5-pro"):
"""
Initialize the MCP wrapper.
Args:
api_key: Google API key for Gemini. If None, will try to get from environment variable.
model: The model to use for generating content. Default is "gemini-1.5-pro".
"""
self.api_key = api_key or os.getenv("GEMINI_API_KEY")
if not self.api_key:
raise ValueError("API key must be provided or set as GEMINI_API_KEY environment variable")
self.client = genai.Client(api_key=self.api_key)
self.model = model
self.session = None
self.server_params = None
self.exit_stack = AsyncExitStack()
self.stdio_transport = None
async def connect_to_server(self, command: str, args: List[str] = None, env: Dict[str, str] = None):
"""
Connect to an MCP server.
Args:
command: The command to execute (e.g., "npx").
args: List of arguments to pass to the command.
env: Environment variables to set for the command.
Returns:
The ClientSession object.
"""
self.server_params = StdioServerParameters(
command=command,
args=args or [],
env=env,
)
# Use AsyncExitStack to properly manage async context managers
self.stdio_transport = await self.exit_stack.enter_async_context(stdio_client(self.server_params))
read, write = self.stdio_transport
self.session = await self.exit_stack.enter_async_context(ClientSession(read, write))
# Initialize the connection
await self.session.initialize()
# Get available tools
tools_response = await self.session.list_tools()
print(f"Connected to MCP server with tools: {[tool.name for tool in tools_response.tools]}")
return self.session
async def execute_query(self, prompt: str, temperature: float = 0.7, max_tool_turns: int = 5, mock_response: bool = True):
"""
Execute a query using the connected MCP server and Gemini model.
Args:
prompt: The user prompt to process.
temperature: The temperature to use for generating content.
max_tool_turns: Maximum number of tool turns to execute.
mock_response: If True, use mock responses for testing when API key is invalid.
Returns:
The final response from the model.
"""
if not self.session:
raise ValueError("Not connected to an MCP server. Call connect_to_server first.")
# Create initial content
contents = [types.Content(role="user", parts=[types.Part(text=prompt)])]
# Get tools from MCP session and convert to Gemini Tool objects
mcp_tools = await self.session.list_tools()
tools = types.Tool(function_declarations=[
{
"name": tool.name,
"description": tool.description,
"parameters": tool.inputSchema,
}
for tool in mcp_tools.tools
])
# Initial request with function declarations
try:
response = await self.client.aio.models.generate_content(
model=self.model,
contents=contents,
config=types.GenerateContentConfig(
temperature=temperature,
tools=[tools],
),
)
except Exception as e:
if mock_response:
print(f"Using mock response due to API error: {e}")
# Create a mock response for testing purposes
if "time" in prompt.lower():
# Mock response for get_current_time tool
mock_text = "I'll help you get the current time."
class MockFunctionCall:
def __init__(self, name, args):
self.name = name
self.args = args
mock_function_calls = [MockFunctionCall("get_current_time", {"timezone": "UTC"})]
elif "calculate" in prompt.lower():
# Mock response for calculate tool
mock_text = "I'll help you with that calculation."
class MockFunctionCall:
def __init__(self, name, args):
self.name = name
self.args = args
mock_function_calls = [MockFunctionCall("calculate", {"expression": "5+3"})]
else:
# Generic mock response
mock_text = "I understand your request. Let me help you with that."
mock_function_calls = [] # No function calls for generic responses
# Create a mock response object with the necessary attributes
class MockCandidate:
def __init__(self, content):
self.content = content
class MockResponse:
def __init__(self, text, function_calls):
self.text = text
self.function_calls = function_calls
self.candidates = [MockCandidate(types.Content(role="model", parts=[types.Part(text=text)]))]
response = MockResponse(mock_text, mock_function_calls)
else:
# Re-raise the exception if mock_response is False
raise
# Append initial response to contents
contents.append(response.candidates[0].content)
# Tool calling loop
turn_count = 0
while response.function_calls and turn_count < max_tool_turns:
turn_count += 1
tool_response_parts: List[types.Part] = []
# Process all function calls in order
for fc_part in response.function_calls:
tool_name = fc_part.name
args = fc_part.args or {}
print(f"Attempting to call MCP tool: '{tool_name}' with args: {args}")
try:
# Call the session's tool executor
tool_result = await self.session.call_tool(tool_name, args)
print(f"MCP tool '{tool_name}' executed successfully.")
if tool_result.isError:
tool_response = {"error": tool_result.content[0].text}
else:
tool_response = {"result": tool_result.content[0].text}
except Exception as e:
tool_response = {"error": f"Tool execution failed: {type(e).__name__}: {e}"}
# Prepare FunctionResponse Part
tool_response_parts.append(
types.Part.from_function_response(
name=tool_name, response=tool_response
)
)
# Add the tool response(s) to history
contents.append(types.Content(role="user", parts=tool_response_parts))
print(f"Added {len(tool_response_parts)} tool response parts to history.")
# Make the next call to the model with updated history
print("Making subsequent API call with tool responses...")
try:
response = await self.client.aio.models.generate_content(
model=self.model,
contents=contents,
config=types.GenerateContentConfig(
temperature=temperature,
tools=[tools],
),
)
except Exception as e:
if mock_response:
print(f"Using mock response due to API error: {e}")
# Create a final mock response with no function calls
mock_text = f"Based on the information from the tools, here's my response: {tool_response}"
class MockCandidate:
def __init__(self, content):
self.content = content
class MockResponse:
def __init__(self, text):
self.text = text
self.function_calls = None
self.candidates = [MockCandidate(types.Content(role="model", parts=[types.Part(text=text)]))]
response = MockResponse(mock_text)
else:
# Re-raise the exception if mock_response is False
raise
contents.append(response.candidates[0].content)
if turn_count >= max_tool_turns and response.function_calls:
print(f"Maximum tool turns ({max_tool_turns}) reached. Exiting loop.")
print("MCP tool calling loop finished. Returning final response.")
return response
async def close(self):
"""Close the MCP session and all associated resources."""
if self.exit_stack:
await self.exit_stack.aclose()
self.session = None
self.stdio_transport = None
@@ -0,0 +1,262 @@
import subprocess
import logging
import json
from typing import List, Any, Dict, Callable
import os
import sys
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s', datefmt='[%H:%M:%S]')
logger = logging.getLogger("npx-mcp-wrapper")
class MCP:
"""
Wrapper class that integrates NPX-based MCP servers with the PraisonAI agent system.
This provides a compatible interface for the Agent class to use MCP tools.
This class handles the extraction of tool definitions from MCP servers and creates:
1. Tool definitions in the global namespace for Agent._generate_tool_definition to find
2. Callable wrappers for each tool that can be invoked by the Agent
The tool definitions include parameter information formatted to match the expectations
of the Agent class, ensuring proper argument passing when tools are invoked.
"""
def __init__(self, command: str = "npx", args: List[str] = None, timeout: int = 180, debug: bool = False):
"""
Initialize the NPX MCP wrapper.
Args:
command: The NPX command to run (default: "npx")
args: List of arguments for the NPX command
timeout: Timeout in seconds (default: 180)
debug: Enable debug logging (default: False)
"""
self.command = command
self.args = args or []
self.timeout = timeout
self.debug = debug
if debug:
logging.getLogger("npx-mcp-wrapper").setLevel(logging.DEBUG)
os.environ["DEBUG"] = "mcp:*"
self._tools = []
self._function_declarations = []
# Initialize the MCP tools
self._initialize_mcp_tools()
def _initialize_mcp_tools(self):
"""
Initialize the MCP tools by running a script that extracts the tool definitions.
This approach avoids the complexity of managing async context managers.
"""
try:
# Create a temporary script to extract MCP tool definitions
temp_script = """
import asyncio
import json
import sys
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
async def extract_tools(command, args):
# Create server parameters
server_params = StdioServerParameters(
command=command,
args=args
)
try:
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
# Initialize connection
await session.initialize()
# Get available tools
mcp_tools = await session.list_tools()
# Convert MCP tools to function declarations with detailed schema
function_declarations = []
for tool in mcp_tools.tools:
# Make sure parameters are properly formatted
parameters = tool.inputSchema
if not parameters.get("properties"):
parameters = {
"type": "object",
"properties": {},
"required": []
}
# Add the tool declaration
function_declarations.append({
"name": tool.name,
"description": tool.description,
"parameters": parameters
})
# Print the function declarations as JSON
print(json.dumps(function_declarations))
except Exception as e:
print(f"Error: {str(e)}", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
command = sys.argv[1]
args = sys.argv[2:]
asyncio.run(extract_tools(command, args))
"""
# Write the temporary script to a file
temp_script_path = os.path.join(os.path.dirname(__file__), "_temp_extract_mcp_tools.py")
with open(temp_script_path, "w") as f:
f.write(temp_script)
# Run the temporary script to extract the tool definitions
cmd = ["python", temp_script_path, self.command] + self.args
result = subprocess.run(cmd, capture_output=True, text=True, timeout=self.timeout)
# Remove the temporary script
os.remove(temp_script_path)
if result.returncode != 0:
logger.error(f"Error extracting MCP tools: {result.stderr}")
raise RuntimeError(f"Failed to extract MCP tools: {result.stderr}")
# Parse the function declarations from the script output
self._function_declarations = json.loads(result.stdout.strip())
# Create tool wrappers for each function declaration
for func_decl in self._function_declarations:
tool_name = func_decl["name"]
self._tools.append(self._create_tool_wrapper(tool_name, func_decl))
# Create a tool definition function in the global namespace
self._create_tool_definition_function(tool_name, func_decl)
logger.info(f"Initialized MCP tools: {[t.__name__ for t in self._tools]}")
except Exception as e:
logger.error(f"Failed to initialize MCP tools: {e}")
raise
def _create_tool_wrapper(self, tool_name: str, func_decl: Dict[str, Any]) -> Callable:
"""
Create a wrapper function for an MCP tool.
Args:
tool_name: The name of the tool
func_decl: The function declaration for the tool
Returns:
A callable function that wraps the MCP tool
"""
def wrapper(**kwargs) -> Any:
# Create a temporary script to call the MCP tool
temp_script = """
import asyncio
import json
import sys
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
async def call_tool(command, args, tool_name, kwargs):
# Create server parameters
server_params = StdioServerParameters(
command=command,
args=args
)
try:
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
# Initialize connection
await session.initialize()
# Call the tool
result = await session.call_tool(tool_name, kwargs)
# Extract the result content
if result.isError:
error_msg = result.content[0].text if result.content else "Unknown error"
print(json.dumps({"error": error_msg}))
else:
print(json.dumps({"result": result.content[0].text if result.content else ""}))
except Exception as e:
print(json.dumps({"error": str(e)}))
if __name__ == "__main__":
command = sys.argv[1]
args = sys.argv[2:-2]
tool_name = sys.argv[-2]
kwargs_json = sys.argv[-1]
kwargs = json.loads(kwargs_json)
asyncio.run(call_tool(command, args, tool_name, kwargs))
"""
try:
# Write the temporary script to a file
temp_script_path = os.path.join(os.path.dirname(__file__), f"_temp_call_mcp_tool_{tool_name}.py")
with open(temp_script_path, "w") as f:
f.write(temp_script)
# Run the temporary script to call the MCP tool
cmd = ["python", temp_script_path, self.command] + self.args + [tool_name, json.dumps(kwargs)]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=self.timeout)
# Remove the temporary script
os.remove(temp_script_path)
if result.returncode != 0:
logger.error(f"Error calling MCP tool {tool_name}: {result.stderr}")
return {"error": f"Failed to call MCP tool: {result.stderr}"}
# Parse the result from the script output
return json.loads(result.stdout.strip())
except Exception as e:
logger.error(f"Error calling MCP tool {tool_name}: {e}")
return {"error": str(e)}
# Set the name and docstring for the wrapper function
wrapper.__name__ = tool_name
wrapper.__doc__ = func_decl.get("description", f"Call the {tool_name} tool on the MCP server")
return wrapper
def __iter__(self):
"""Make the wrapper iterable to work with the agent system."""
return iter(self._tools)
def _create_tool_definition_function(self, tool_name, func_decl):
"""
Create a tool definition function in the global namespace.
This allows the Agent._generate_tool_definition method to find the tool definition.
Args:
tool_name: The name of the tool
func_decl: The function declaration for the tool
"""
# Create the tool definition
tool_def = {
"type": "function",
"function": func_decl
}
# Store the tool definition in the global namespace directly
# This way Agent._generate_tool_definition can find it
tool_def_name = f"{tool_name}_definition"
setattr(sys.modules["__main__"], tool_def_name, tool_def)
globals()[tool_def_name] = tool_def
logger.debug(f"Created tool definition: {tool_def_name}")
def to_openai_tool(self):
"""Return the function declarations as OpenAI tools."""
return [
{
"type": "function",
"function": func_decl
}
for func_decl in self._function_declarations
]
@@ -10,6 +10,7 @@ from .tools.tools import Tools
from .agents.autoagents import AutoAgents
from .knowledge.knowledge import Knowledge
from .knowledge.chunking import Chunking
from .mcp.mcp import MCP
from .main import (
TaskOutput,
ReflectionOutput,
@@ -51,5 +52,6 @@ __all__ = [
'sync_display_callbacks',
'async_display_callbacks',
'Knowledge',
'Chunking'
'Chunking',
'MCP'
]
@@ -714,6 +714,22 @@ Your Goal: {self.goal}
return None
def chat(self, prompt, temperature=0.2, tools=None, output_json=None, output_pydantic=None, reasoning_steps=False):
# Log all parameter values when in debug mode
if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
param_info = {
"prompt": str(prompt)[:100] + "..." if isinstance(prompt, str) and len(str(prompt)) > 100 else str(prompt),
"temperature": temperature,
"tools": [t.__name__ if hasattr(t, "__name__") else str(t) for t in tools] if tools else None,
"output_json": str(output_json.__class__.__name__) if output_json else None,
"output_pydantic": str(output_pydantic.__class__.__name__) if output_pydantic else None,
"reasoning_steps": reasoning_steps,
"agent_name": self.name,
"agent_role": self.role,
"agent_goal": self.goal
}
logging.debug(f"Agent.chat parameters: {json.dumps(param_info, indent=2, default=str)}")
start_time = time.time()
reasoning_steps = reasoning_steps or self.reasoning_steps
# Search for existing knowledge if any knowledge is provided
if self.knowledge:
@@ -738,7 +754,7 @@ Your Goal: {self.goal}
system_prompt=f"{self.backstory}\n\nYour Role: {self.role}\n\nYour Goal: {self.goal}" if self.use_system_prompt else None,
chat_history=self.chat_history,
temperature=temperature,
tools=tools,
tools=self.tools if tools is None else tools,
output_json=output_json,
output_pydantic=output_pydantic,
verbose=self.verbose,
@@ -749,7 +765,7 @@ Your Goal: {self.goal}
console=self.console,
agent_name=self.name,
agent_role=self.role,
agent_tools=[t.__name__ if hasattr(t, '__name__') else str(t) for t in self.tools],
agent_tools=[t.__name__ if hasattr(t, '__name__') else str(t) for t in (tools if tools is not None else self.tools)],
execute_tool_fn=self.execute_tool, # Pass tool execution function
reasoning_steps=reasoning_steps
)
@@ -757,6 +773,11 @@ Your Goal: {self.goal}
self.chat_history.append({"role": "user", "content": prompt})
self.chat_history.append({"role": "assistant", "content": response_text})
# Log completion time if in debug mode
if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
total_time = time.time() - start_time
logging.debug(f"Agent.chat completed in {total_time:.2f} seconds")
return response_text
except Exception as e:
display_error(f"Error in LLM chat: {e}")
@@ -944,6 +965,13 @@ Output MUST be JSON with 'reflection' and 'satisfactory'.
display_error(f"Error in chat: {e}", console=self.console)
return None
# Log completion time if in debug mode
if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
total_time = time.time() - start_time
logging.debug(f"Agent.chat completed in {total_time:.2f} seconds")
return response_text
def clean_json_output(self, output: str) -> str:
"""Clean and extract JSON from response text."""
cleaned = output.strip()
@@ -958,6 +986,22 @@ Output MUST be JSON with 'reflection' and 'satisfactory'.
async def achat(self, prompt: str, temperature=0.2, tools=None, output_json=None, output_pydantic=None, reasoning_steps=False):
"""Async version of chat method. TODO: Requires Syncing with chat method."""
# Log all parameter values when in debug mode
if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
param_info = {
"prompt": str(prompt)[:100] + "..." if isinstance(prompt, str) and len(str(prompt)) > 100 else str(prompt),
"temperature": temperature,
"tools": [t.__name__ if hasattr(t, "__name__") else str(t) for t in tools] if tools else None,
"output_json": str(output_json.__class__.__name__) if output_json else None,
"output_pydantic": str(output_pydantic.__class__.__name__) if output_pydantic else None,
"reasoning_steps": reasoning_steps,
"agent_name": self.name,
"agent_role": self.role,
"agent_goal": self.goal
}
logging.debug(f"Agent.achat parameters: {json.dumps(param_info, indent=2, default=str)}")
start_time = time.time()
reasoning_steps = reasoning_steps or self.reasoning_steps
try:
# Search for existing knowledge if any knowledge is provided
@@ -996,9 +1040,15 @@ Output MUST be JSON with 'reflection' and 'satisfactory'.
self.chat_history.append({"role": "user", "content": prompt})
self.chat_history.append({"role": "assistant", "content": response_text})
if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
total_time = time.time() - start_time
logging.debug(f"Agent.achat completed in {total_time:.2f} seconds")
return response_text
except Exception as e:
display_error(f"Error in LLM chat: {e}")
if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
total_time = time.time() - start_time
logging.debug(f"Agent.achat failed in {total_time:.2f} seconds: {str(e)}")
return None
# For OpenAI client
@@ -1081,7 +1131,11 @@ Your Goal: {self.goal}
temperature=temperature,
tools=formatted_tools
)
return await self._achat_completion(response, tools)
result = await self._achat_completion(response, tools)
if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
total_time = time.time() - start_time
logging.debug(f"Agent.achat completed in {total_time:.2f} seconds")
return result
elif output_json or output_pydantic:
response = await async_client.chat.completions.create(
model=self.llm,
@@ -1090,6 +1144,9 @@ Your Goal: {self.goal}
response_format={"type": "json_object"}
)
# Return the raw response
if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
total_time = time.time() - start_time
logging.debug(f"Agent.achat completed in {total_time:.2f} seconds")
return response.choices[0].message.content
else:
response = await async_client.chat.completions.create(
@@ -1097,12 +1154,21 @@ Your Goal: {self.goal}
messages=messages,
temperature=temperature
)
if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
total_time = time.time() - start_time
logging.debug(f"Agent.achat completed in {total_time:.2f} seconds")
return response.choices[0].message.content
except Exception as e:
display_error(f"Error in chat completion: {e}")
if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
total_time = time.time() - start_time
logging.debug(f"Agent.achat failed in {total_time:.2f} seconds: {str(e)}")
return None
except Exception as e:
display_error(f"Error in achat: {e}")
if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
total_time = time.time() - start_time
logging.debug(f"Agent.achat failed in {total_time:.2f} seconds: {str(e)}")
return None
async def _achat_completion(self, response, tools, reasoning_steps=False):
@@ -477,8 +477,14 @@ Context:
else:
self.run_task(task_id)
async def astart(self, content=None, **kwargs):
"""Async version of start method"""
async def astart(self, content=None, return_dict=False, **kwargs):
"""Async version of start method
Args:
content: Optional content to add to all tasks' context
return_dict: If True, returns the full results dictionary instead of only the final response
**kwargs: Additional arguments
"""
if content:
# Add content to context of all tasks
for task in self.tasks.values():
@@ -488,10 +494,25 @@ Context:
task.context.append(content)
await self.arun_all_tasks()
return {
# Get results
results = {
"task_status": self.get_all_tasks_status(),
"task_results": {task_id: self.get_task_result(task_id) for task_id in self.tasks}
}
# By default, return only the final agent's response
if not return_dict:
# Get the last task (assuming sequential processing)
task_ids = list(self.tasks.keys())
if task_ids:
last_task_id = task_ids[-1]
last_result = self.get_task_result(last_task_id)
if last_result:
return last_result.raw
# Return full results dict if return_dict is True or if no final result was found
return results
def save_output_to_file(self, task, task_output):
if task.output_file:
@@ -801,8 +822,14 @@ Context:
return str(agent[0])
return None
def start(self, content=None, **kwargs):
"""Start agent execution with optional content and config"""
def start(self, content=None, return_dict=False, **kwargs):
"""Start agent execution with optional content and config
Args:
content: Optional content to add to all tasks' context
return_dict: If True, returns the full results dictionary instead of only the final response
**kwargs: Additional arguments
"""
if content:
# Add content to context of all tasks
for task in self.tasks.values():
@@ -815,10 +842,25 @@ Context:
# Run tasks as before
self.run_all_tasks()
return {
# Get results
results = {
"task_status": self.get_all_tasks_status(),
"task_results": {task_id: self.get_task_result(task_id) for task_id in self.tasks}
}
# By default, return only the final agent's response
if not return_dict:
# Get the last task (assuming sequential processing)
task_ids = list(self.tasks.keys())
if task_ids:
last_task_id = task_ids[-1]
last_result = self.get_task_result(last_task_id)
if last_result:
return last_result.raw
# Return full results dict if return_dict is True or if no final result was found
return results
def set_state(self, key: str, value: Any) -> None:
"""Set a state value"""
@@ -7,12 +7,12 @@ class Chunking:
CHUNKER_PARAMS = {
'token': ['chunk_size', 'chunk_overlap', 'tokenizer'],
'word': ['chunk_size', 'chunk_overlap', 'tokenizer'],
'sentence': ['chunk_size', 'chunk_overlap', 'tokenizer'],
'semantic': ['chunk_size', 'embedding_model', 'tokenizer'],
'sdpm': ['chunk_size', 'embedding_model', 'tokenizer'],
'late': ['chunk_size', 'embedding_model', 'tokenizer'],
'recursive': ['chunk_size', 'tokenizer']
'word': ['chunk_size', 'chunk_overlap', 'tokenizer_or_token_counter'],
'sentence': ['chunk_size', 'chunk_overlap', 'tokenizer_or_token_counter'],
'recursive': ['chunk_size', 'tokenizer_or_token_counter'],
'semantic': ['chunk_size', 'embedding_model'],
'sdpm': ['chunk_size', 'embedding_model'],
'late': ['chunk_size', 'embedding_model'],
}
@cached_property
@@ -48,7 +48,7 @@ class Chunking:
chunker_type: str = 'token',
chunk_size: int = 512,
chunk_overlap: int = 128,
tokenizer: str = "gpt2",
tokenizer_or_token_counter: str = "gpt2",
embedding_model: Optional[Union[str, Any]] = None,
**kwargs
):
@@ -62,7 +62,7 @@ class Chunking:
self.chunker_type = chunker_type
self.chunk_size = chunk_size
self.chunk_overlap = chunk_overlap
self.tokenizer = tokenizer
self.tokenizer_or_token_counter = tokenizer_or_token_counter
self._embedding_model = embedding_model
self.kwargs = kwargs
@@ -89,11 +89,10 @@ class Chunking:
if 'chunk_overlap' in allowed_params:
params['chunk_overlap'] = self.chunk_overlap
if 'tokenizer' in allowed_params:
if self.chunker_type in ['semantic', 'sdpm', 'late']:
params['tokenizer'] = self.embedding_model.get_tokenizer_or_token_counter()
else:
params['tokenizer'] = self.tokenizer
if 'tokenizer_or_token_counter' in allowed_params:
params['tokenizer_or_token_counter'] = self.tokenizer_or_token_counter
elif 'tokenizer' in allowed_params:
params['tokenizer'] = self.tokenizer_or_token_counter
if 'embedding_model' in allowed_params:
params['embedding_model'] = self.embedding_model
+335 -13
View File
@@ -171,7 +171,39 @@ class LLM:
# Enable error dropping for cleaner output
litellm.drop_params = True
# Enable parameter modification for providers like Anthropic
litellm.modify_params = True
self._setup_event_tracking(events)
# Log all initialization parameters when in debug mode
if not isinstance(verbose, bool) and verbose >= 10:
debug_info = {
"model": self.model,
"timeout": self.timeout,
"temperature": self.temperature,
"top_p": self.top_p,
"n": self.n,
"max_tokens": self.max_tokens,
"presence_penalty": self.presence_penalty,
"frequency_penalty": self.frequency_penalty,
"logit_bias": self.logit_bias,
"response_format": self.response_format,
"seed": self.seed,
"logprobs": self.logprobs,
"top_logprobs": self.top_logprobs,
"api_version": self.api_version,
"stop_phrases": self.stop_phrases,
"api_key": "***" if self.api_key else None, # Mask API key for security
"base_url": self.base_url,
"verbose": self.verbose,
"markdown": self.markdown,
"self_reflect": self.self_reflect,
"max_reflect": self.max_reflect,
"min_reflect": self.min_reflect,
"reasoning_steps": self.reasoning_steps,
"extra_settings": {k: v for k, v in self.extra_settings.items() if k not in ["api_key"]}
}
logging.debug(f"LLM instance initialized with: {json.dumps(debug_info, indent=2, default=str)}")
def get_response(
self,
@@ -195,6 +227,56 @@ class LLM:
**kwargs
) -> str:
"""Enhanced get_response with all OpenAI-like features"""
logging.info(f"Getting response from {self.model}")
# Log all self values when in debug mode
if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
debug_info = {
"model": self.model,
"timeout": self.timeout,
"temperature": self.temperature,
"top_p": self.top_p,
"n": self.n,
"max_tokens": self.max_tokens,
"presence_penalty": self.presence_penalty,
"frequency_penalty": self.frequency_penalty,
"logit_bias": self.logit_bias,
"response_format": self.response_format,
"seed": self.seed,
"logprobs": self.logprobs,
"top_logprobs": self.top_logprobs,
"api_version": self.api_version,
"stop_phrases": self.stop_phrases,
"api_key": "***" if self.api_key else None, # Mask API key for security
"base_url": self.base_url,
"verbose": self.verbose,
"markdown": self.markdown,
"self_reflect": self.self_reflect,
"max_reflect": self.max_reflect,
"min_reflect": self.min_reflect,
"reasoning_steps": self.reasoning_steps
}
logging.debug(f"LLM instance configuration: {json.dumps(debug_info, indent=2, default=str)}")
# Log the parameter values passed to get_response
param_info = {
"prompt": str(prompt)[:100] + "..." if isinstance(prompt, str) and len(str(prompt)) > 100 else str(prompt),
"system_prompt": system_prompt[:100] + "..." if system_prompt and len(system_prompt) > 100 else system_prompt,
"chat_history": f"[{len(chat_history)} messages]" if chat_history else None,
"temperature": temperature,
"tools": [t.__name__ if hasattr(t, "__name__") else str(t) for t in tools] if tools else None,
"output_json": str(output_json.__class__.__name__) if output_json else None,
"output_pydantic": str(output_pydantic.__class__.__name__) if output_pydantic else None,
"verbose": verbose,
"markdown": markdown,
"self_reflect": self_reflect,
"max_reflect": max_reflect,
"min_reflect": min_reflect,
"agent_name": agent_name,
"agent_role": agent_role,
"agent_tools": agent_tools,
"kwargs": str(kwargs)
}
logging.debug(f"get_response parameters: {json.dumps(param_info, indent=2, default=str)}")
try:
import litellm
# This below **kwargs** is passed to .completion() directly. so reasoning_steps has to be popped. OR find alternate best way of handling this.
@@ -202,6 +284,23 @@ class LLM:
# Disable litellm debug messages
litellm.set_verbose = False
# Format tools if provided
formatted_tools = None
if tools:
formatted_tools = []
for tool in tools:
if callable(tool):
tool_def = self._generate_tool_definition(tool.__name__)
elif isinstance(tool, str):
tool_def = self._generate_tool_definition(tool)
else:
continue
if tool_def:
formatted_tools.append(tool_def)
if not formatted_tools:
formatted_tools = None
# Build messages list
messages = []
if system_prompt:
@@ -260,6 +359,7 @@ class LLM:
messages=messages,
temperature=temperature,
stream=False, # force non-streaming
tools=formatted_tools,
**{k:v for k,v in kwargs.items() if k != 'reasoning_steps'}
)
reasoning_content = resp["choices"][0]["message"].get("provider_specific_fields", {}).get("reasoning_content")
@@ -291,6 +391,7 @@ class LLM:
for chunk in litellm.completion(
model=self.model,
messages=messages,
tools=formatted_tools,
temperature=temperature,
stream=True,
**kwargs
@@ -305,6 +406,7 @@ class LLM:
for chunk in litellm.completion(
model=self.model,
messages=messages,
tools=formatted_tools,
temperature=temperature,
stream=True,
**kwargs
@@ -318,6 +420,7 @@ class LLM:
final_response = litellm.completion(
model=self.model,
messages=messages,
tools=formatted_tools,
temperature=temperature,
stream=False, # No streaming for tool call check
**kwargs
@@ -337,20 +440,29 @@ class LLM:
function_name = tool_call["function"]["name"]
arguments = json.loads(tool_call["function"]["arguments"])
if verbose:
display_tool_call(f"Agent {agent_name} is calling function '{function_name}' with arguments: {arguments}", console=console)
logging.debug(f"[TOOL_EXEC_DEBUG] About to execute tool {function_name} with args: {arguments}")
tool_result = execute_tool_fn(function_name, arguments)
logging.debug(f"[TOOL_EXEC_DEBUG] Tool execution result: {tool_result}")
if tool_result:
if verbose:
display_tool_call(f"Function '{function_name}' returned: {tool_result}", console=console)
if verbose:
display_message = f"Agent {agent_name} called function '{function_name}' with arguments: {arguments}\n"
if tool_result:
display_message += f"Function returned: {tool_result}"
logging.debug(f"[TOOL_EXEC_DEBUG] Display message with result: {display_message}")
else:
display_message += "Function returned no output"
logging.debug("[TOOL_EXEC_DEBUG] Tool returned no output")
logging.debug(f"[TOOL_EXEC_DEBUG] About to display tool call with message: {display_message}")
display_tool_call(display_message, console=console)
messages.append({
"role": "tool",
"tool_call_id": tool_call["id"],
"content": json.dumps(tool_result)
})
else:
logging.debug("[TOOL_EXEC_DEBUG] Verbose mode off, not displaying tool call")
messages.append({
"role": "tool",
"tool_call_id": tool_call["id"],
@@ -552,6 +664,11 @@ Output MUST be JSON with 'reflection' and 'satisfactory'.
except Exception as error:
display_error(f"Error in get_response: {str(error)}")
raise
# Log completion time if in debug mode
if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
total_time = time.time() - start_time
logging.debug(f"get_response completed in {total_time:.2f} seconds")
async def get_response_async(
self,
@@ -577,6 +694,56 @@ Output MUST be JSON with 'reflection' and 'satisfactory'.
"""Async version of get_response with identical functionality."""
try:
import litellm
logging.info(f"Getting async response from {self.model}")
# Log all self values when in debug mode
if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
debug_info = {
"model": self.model,
"timeout": self.timeout,
"temperature": self.temperature,
"top_p": self.top_p,
"n": self.n,
"max_tokens": self.max_tokens,
"presence_penalty": self.presence_penalty,
"frequency_penalty": self.frequency_penalty,
"logit_bias": self.logit_bias,
"response_format": self.response_format,
"seed": self.seed,
"logprobs": self.logprobs,
"top_logprobs": self.top_logprobs,
"api_version": self.api_version,
"stop_phrases": self.stop_phrases,
"api_key": "***" if self.api_key else None, # Mask API key for security
"base_url": self.base_url,
"verbose": self.verbose,
"markdown": self.markdown,
"self_reflect": self.self_reflect,
"max_reflect": self.max_reflect,
"min_reflect": self.min_reflect,
"reasoning_steps": self.reasoning_steps
}
logging.debug(f"LLM async instance configuration: {json.dumps(debug_info, indent=2, default=str)}")
# Log the parameter values passed to get_response_async
param_info = {
"prompt": str(prompt)[:100] + "..." if isinstance(prompt, str) and len(str(prompt)) > 100 else str(prompt),
"system_prompt": system_prompt[:100] + "..." if system_prompt and len(system_prompt) > 100 else system_prompt,
"chat_history": f"[{len(chat_history)} messages]" if chat_history else None,
"temperature": temperature,
"tools": [t.__name__ if hasattr(t, "__name__") else str(t) for t in tools] if tools else None,
"output_json": str(output_json.__class__.__name__) if output_json else None,
"output_pydantic": str(output_pydantic.__class__.__name__) if output_pydantic else None,
"verbose": verbose,
"markdown": markdown,
"self_reflect": self_reflect,
"max_reflect": max_reflect,
"min_reflect": min_reflect,
"agent_name": agent_name,
"agent_role": agent_role,
"agent_tools": agent_tools,
"kwargs": str(kwargs)
}
logging.debug(f"get_response_async parameters: {json.dumps(param_info, indent=2, default=str)}")
reasoning_steps = kwargs.pop('reasoning_steps', self.reasoning_steps)
litellm.set_verbose = False
@@ -767,14 +934,15 @@ Output MUST be JSON with 'reflection' and 'satisfactory'.
function_name = tool_call.function.name
arguments = json.loads(tool_call.function.arguments)
if verbose:
display_tool_call(f"Agent {agent_name} is calling function '{function_name}' with arguments: {arguments}", console=console)
tool_result = await execute_tool_fn(function_name, arguments)
if tool_result:
if verbose:
display_tool_call(f"Function '{function_name}' returned: {tool_result}", console=console)
if verbose:
display_message = f"Agent {agent_name} called function '{function_name}' with arguments: {arguments}\n"
if tool_result:
display_message += f"Function returned: {tool_result}"
else:
display_message += "Function returned no output"
display_tool_call(display_message, console=console)
messages.append({
"role": "tool",
"tool_call_id": tool_call.id,
@@ -983,6 +1151,11 @@ Output MUST be JSON with 'reflection' and 'satisfactory'.
raise LLMContextLengthExceededException(str(error))
display_error(f"Error in get_response_async: {str(error)}")
raise
# Log completion time if in debug mode
if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
total_time = time.time() - start_time
logging.debug(f"get_response_async completed in {total_time:.2f} seconds")
def can_use_tools(self) -> bool:
"""Check if this model can use tool functions"""
@@ -1065,6 +1238,24 @@ Output MUST be JSON with 'reflection' and 'satisfactory'.
logger.debug("Using synchronous response function")
# Log all self values when in debug mode
if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
debug_info = {
"model": self.model,
"timeout": self.timeout,
"temperature": temperature,
"top_p": self.top_p,
"n": self.n,
"max_tokens": self.max_tokens,
"presence_penalty": self.presence_penalty,
"frequency_penalty": self.frequency_penalty,
"stream": stream,
"verbose": verbose,
"markdown": markdown,
"kwargs": str(kwargs)
}
logger.debug(f"Response method configuration: {json.dumps(debug_info, indent=2, default=str)}")
# Build messages list
messages = []
if system_prompt:
@@ -1150,6 +1341,24 @@ Output MUST be JSON with 'reflection' and 'satisfactory'.
logger.debug("Using asynchronous response function")
# Log all self values when in debug mode
if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
debug_info = {
"model": self.model,
"timeout": self.timeout,
"temperature": temperature,
"top_p": self.top_p,
"n": self.n,
"max_tokens": self.max_tokens,
"presence_penalty": self.presence_penalty,
"frequency_penalty": self.frequency_penalty,
"stream": stream,
"verbose": verbose,
"markdown": markdown,
"kwargs": str(kwargs)
}
logger.debug(f"Async response method configuration: {json.dumps(debug_info, indent=2, default=str)}")
# Build messages list
messages = []
if system_prompt:
@@ -1210,4 +1419,117 @@ Output MUST be JSON with 'reflection' and 'satisfactory'.
except Exception as error:
display_error(f"Error in response_async: {str(error)}")
raise
raise
def _generate_tool_definition(self, function_name: str) -> Optional[Dict]:
"""Generate a tool definition from a function name."""
logging.debug(f"Attempting to generate tool definition for: {function_name}")
# First try to get the tool definition if it exists
tool_def_name = f"{function_name}_definition"
tool_def = globals().get(tool_def_name)
logging.debug(f"Looking for {tool_def_name} in globals: {tool_def is not None}")
if not tool_def:
import __main__
tool_def = getattr(__main__, tool_def_name, None)
logging.debug(f"Looking for {tool_def_name} in __main__: {tool_def is not None}")
if tool_def:
logging.debug(f"Found tool definition: {tool_def}")
return tool_def
# Try to find the function
func = globals().get(function_name)
logging.debug(f"Looking for {function_name} in globals: {func is not None}")
if not func:
import __main__
func = getattr(__main__, function_name, None)
logging.debug(f"Looking for {function_name} in __main__: {func is not None}")
if not func or not callable(func):
logging.debug(f"Function {function_name} not found or not callable")
return None
import inspect
# Handle Langchain and CrewAI tools
if inspect.isclass(func) and hasattr(func, 'run') and not hasattr(func, '_run'):
original_func = func
func = func.run
function_name = original_func.__name__
elif inspect.isclass(func) and hasattr(func, '_run'):
original_func = func
func = func._run
function_name = original_func.__name__
sig = inspect.signature(func)
logging.debug(f"Function signature: {sig}")
# Skip self, *args, **kwargs
parameters_list = []
for name, param in sig.parameters.items():
if name == "self":
continue
if param.kind in (inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD):
continue
parameters_list.append((name, param))
parameters = {
"type": "object",
"properties": {},
"required": []
}
# Parse docstring for parameter descriptions
docstring = inspect.getdoc(func)
logging.debug(f"Function docstring: {docstring}")
param_descriptions = {}
if docstring:
import re
param_section = re.split(r'\s*Args:\s*', docstring)
logging.debug(f"Param section split: {param_section}")
if len(param_section) > 1:
param_lines = param_section[1].split('\n')
for line in param_lines:
line = line.strip()
if line and ':' in line:
param_name, param_desc = line.split(':', 1)
param_descriptions[param_name.strip()] = param_desc.strip()
logging.debug(f"Parameter descriptions: {param_descriptions}")
for name, param in parameters_list:
param_type = "string" # Default type
if param.annotation != inspect.Parameter.empty:
if param.annotation == int:
param_type = "integer"
elif param.annotation == float:
param_type = "number"
elif param.annotation == bool:
param_type = "boolean"
elif param.annotation == list:
param_type = "array"
elif param.annotation == dict:
param_type = "object"
parameters["properties"][name] = {
"type": param_type,
"description": param_descriptions.get(name, "Parameter description not available")
}
if param.default == inspect.Parameter.empty:
parameters["required"].append(name)
logging.debug(f"Generated parameters: {parameters}")
tool_def = {
"type": "function",
"function": {
"name": function_name,
"description": docstring.split('\n\n')[0] if docstring else "No description available",
"parameters": parameters
}
}
logging.debug(f"Generated tool definition: {tool_def}")
return tool_def
+11 -2
View File
@@ -86,6 +86,7 @@ async def execute_callback(display_type: str, **kwargs):
def _clean_display_content(content: str, max_length: int = 20000) -> str:
"""Helper function to clean and truncate content for display."""
if not content or not str(content).strip():
logging.debug(f"Empty content received in _clean_display_content: {repr(content)}")
return ""
content = str(content)
@@ -174,11 +175,14 @@ def display_instruction(message: str, console=None, agent_name: str = None, agen
console.print(Panel.fit(Text(message, style="bold blue"), title="Instruction", border_style="cyan"))
def display_tool_call(message: str, console=None):
logging.debug(f"display_tool_call called with message: {repr(message)}")
if not message or not message.strip():
logging.debug("Empty message in display_tool_call, returning early")
return
if console is None:
console = Console()
message = _clean_display_content(str(message))
logging.debug(f"Cleaned message in display_tool_call: {repr(message)}")
# Execute callback if registered
if 'tool_call' in sync_display_callbacks:
@@ -202,7 +206,8 @@ def display_error(message: str, console=None):
def display_generating(content: str = "", start_time: Optional[float] = None):
if not content or not str(content).strip():
return Panel("", title="", border_style="green")
logging.debug("Empty content in display_generating, returning early")
return None
elapsed_str = ""
if start_time is not None:
@@ -293,11 +298,14 @@ async def adisplay_instruction(message: str, console=None, agent_name: str = Non
async def adisplay_tool_call(message: str, console=None):
"""Async version of display_tool_call."""
logging.debug(f"adisplay_tool_call called with message: {repr(message)}")
if not message or not message.strip():
logging.debug("Empty message in adisplay_tool_call, returning early")
return
if console is None:
console = Console()
message = _clean_display_content(str(message))
logging.debug(f"Cleaned message in adisplay_tool_call: {repr(message)}")
if 'tool_call' in async_display_callbacks:
await async_display_callbacks['tool_call'](message=message)
@@ -321,7 +329,8 @@ async def adisplay_error(message: str, console=None):
async def adisplay_generating(content: str = "", start_time: Optional[float] = None):
"""Async version of display_generating."""
if not content or not str(content).strip():
return Panel("", title="", border_style="green")
logging.debug("Empty content in adisplay_generating, returning early")
return None
elapsed_str = ""
if start_time is not None:
@@ -0,0 +1,6 @@
"""
Model Context Protocol (MCP) integration for PraisonAI Agents.
"""
from .mcp import MCP
__all__ = ["MCP"]
Loaded 100 of 123 files, more files were not shown because too many files have changed in this diff. Show more