Compare commits

...
120 Commits
Author SHA1 Message Date
Mervin Praison dc393e1211 Merge pull request #456 from MervinPraison/develop
Increment version to 0.0.77 in `pyproject.toml` and update `markitdow…
2025-05-13 14:47:44 +01:00
MervinPraison fdff17faf9 MCP SSE Docs 2025-05-13 14:46:11 +01:00
MervinPraison b3d893fae1 Implement SSEMCPClient and SSEMCPTool for MCP server interaction, enhance logging configuration, and increment version to 0.0.77 in pyproject.toml and uv.lock for improved functionality. 2025-05-13 14:29:41 +01:00
MervinPraison d92dede515 Re-add mcp-sse-direct-agent.py without API key 2025-05-13 14:01:35 +01:00
MervinPraison a1882233dc mcp sse 2025-05-13 13:55:32 +01:00
MervinPraison c540ba34fb Increment version to 0.0.76 in pyproject.toml and update markitdown dependency to include all extras in uv.lock for enhanced functionality. 2025-04-08 12:05:03 +01:00
Mervin Praison 0abb1b659a Merge pull request #455 from MervinPraison/develop
Increment version to 0.0.75 in `pyproject.toml` and update Python com…
2025-04-08 11:49:15 +01:00
MervinPraison 81adb28688 Increment version to 0.0.75 in pyproject.toml and update Python compatibility requirements in uv.lock to support Python 3.11 and above. 2025-04-08 11:48:53 +01:00
Mervin Praison 5fbe6e948c Merge pull request #450 from ihsankursadunal/add-to-vector-store-fifth-positional-argument
RAG knowledge positional argument error fix
2025-04-08 11:48:11 +01:00
Mervin Praison 6128e4c885 Merge pull request #454 from MervinPraison/develop
Add new Databutton and Research agents in `databutton-mcp.py` and `mc…
2025-04-08 11:35:34 +01:00
MervinPraison 0e563989ed Add new Databutton and Research agents in databutton-mcp.py and mcp-llama4.py, respectively. Increment version to 0.0.74 in pyproject.toml and update Python requirements in uv.lock for compatibility with Python 3.13. 2025-04-08 11:34:37 +01:00
Mervin Praison 510a853e05 Merge pull request #453 from chonknick/update-chonkie-v102
Fix: breaking change with Chonkie `v1.0.2` — `WordChunker` not found
2025-04-08 11:32:13 +01:00
Bhavnick @ chonkie.ai d6084cb7ce Update chonkie dependency version to 1.0.2 in pyproject.toml and requirements.txt for improved compatibility. 2025-04-07 23:45:26 +05:30
Bhavnick @ chonkie.ai 8d4b1c411b Enhance chunking method: Disable unsupported context parameters and add warning for future support. Track in https://github.com/chonkie-inc/chonkie/issues/21 2025-04-07 23:38:37 +05:30
bhavnicksm 3be05c855b Fix: Remove WordChunker + Disable OverlapRefinery (temporarily) 2025-04-07 23:18:43 +05:30
bhavnicksm 3e5a2f76f4 Update chonkie version to the latest v1.0.2 2025-04-07 23:18:14 +05:30
ihsankursadunal 8eee881d2e RAG knowledge positional argument error fix 2025-04-06 13:09:35 +03:00
Mervin Praison d75f4be41a Merge pull request #448 from MervinPraison/develop
Develop
2025-04-03 06:47:51 +01:00
MervinPraison 9ea89448ef Increment version number to 0.0.73 in pyproject.toml and uv.lock to reflect recent updates. 2025-04-03 06:47:35 +01:00
MervinPraison 0a5e2df278 Merge PR #409: Support chat without stream while maintaining stream=True as default 2025-04-03 06:30:23 +01:00
MervinPraison cc3b64f89b fix: keep default stream=True while supporting stream=False option 2025-04-03 06:30:04 +01:00
Mervin Praison 546dc5a441 Merge pull request #391 from yiranwu0/main
Update AG2 reference
2025-04-02 21:44:22 +01:00
Mervin Praison bd7422c7ca Merge pull request #443 from MervinPraison/develop
Add WhatsApp and Perplexity MCP Integrations
2025-04-02 09:54:17 +01:00
MervinPraison 0c2c6da8dd Add WhatsApp and Perplexity MCP Integrations
- Included new MCP tools for WhatsApp and Perplexity in `mint.json` for enhanced functionality.
- Updated installation instructions in `openrouter.mdx` and `xai.mdx` to specify the correct package format.
- Added detailed documentation for WhatsApp and Perplexity integrations, including setup steps and example scripts.
- Incremented version number to 0.0.72 in `pyproject.toml` and `uv.lock` to reflect recent changes.
2025-04-02 09:54:02 +01:00
Mervin Praison b43688086f Merge pull request #442 from MervinPraison/develop
Update to version 2.1.1
2025-04-01 22:22:06 +01:00
MervinPraison 820619e8d9 Update to version 2.1.1
- Incremented version number to 2.1.1 in `pyproject.toml`, `praisonai.rb`, and `uv.lock` to reflect recent changes.
- Updated dependency version for `praisonaiagents` to 0.0.71 in `pyproject.toml` and `uv.lock`.
- Modified Dockerfile and deployment scripts to install the updated version of `praisonai`.
- Added new documentation files for various MCP integrations, including Anthropic, Gemini, Groq, Mistral, Ollama, OpenAI, and XAI.
- Introduced example scripts for each MCP integration to facilitate user understanding and implementation.
- Enhanced the LLM class to process tool results based on the original user query for improved response accuracy.
2025-04-01 22:21:50 +01:00
Mervin Praison 94202adddd Merge pull request #441 from MervinPraison/develop
Version 2.1
2025-04-01 21:14:15 +01:00
MervinPraison c7911629b1 Version 2.1 2025-04-01 21:13:30 +01:00
Mervin Praison 5a4e3ba707 Merge pull request #440 from MervinPraison/develop
Update LLM and MCP Integration
2025-04-01 17:54:05 +01:00
MervinPraison 641057b622 Update LLM and MCP Integration
- Changed the LLM model from "groq/llama-3.3-70b-versatile" to "groq/llama-3.2-90b-vision-preview" in `groq-mcp.py` for improved performance.
- Added a new example script `ollama-python.py` for stock price retrieval using the Ollama model.
- Incremented version number to 0.0.70 in `pyproject.toml` to reflect recent changes.
- Updated Python version requirement in `uv.lock` to support Python 3.11 and above for better compatibility.
- Enhanced the LLM class to handle tool calls specifically for Ollama models, ensuring proper processing of tool results.
2025-04-01 17:53:45 +01:00
Mervin Praison db1dbf142e Merge pull request #438 from MervinPraison/develop
groq support included
2025-04-01 13:51:43 +01:00
MervinPraison d9a19ae277 groq support included 2025-04-01 13:51:24 +01:00
Mervin Praison 3c9d889b4f Merge pull request #437 from MervinPraison/develop
Add MCP Integration and Update Documentation
2025-03-31 13:24:04 +01:00
MervinPraison 2f324e74db Add MCP Integration and Update Documentation
- Added `mcp` dependency to `pyproject.toml` for enhanced functionality.
- Introduced new example scripts for various MCP tools, including `fetch-mcp.py`, `git-mcp.py`, `ollama.py`, `sentry-mcp.py`, and `time-mcp.py`, to demonstrate their usage.
- Updated `airbnb.mdx` to reflect the addition of the Airbnb tool to the AI agent.
- Enhanced the `Agent` class to support MCP tools and ensure proper integration with custom LLMs.
- Improved logging for better debugging and tool management.
- Incremented version number to 0.0.68 in `pyproject.toml` for release clarity.
2025-03-31 13:23:49 +01:00
Mervin Praison c22fef3e6d Merge pull request #436 from MervinPraison/develop
Enhance MCP Documentation and Integration
2025-03-31 09:47:52 +01:00
MervinPraison 53bee19948 Enhance MCP Documentation and Integration
- Updated `mint.json` to include additional MCP pages for improved navigation.
- Added new documentation files for various MCP integrations, including AWS KB Retrieval, Everart, Filesystem, Google Drive, GitHub, GitLab, Google Maps, Memory, PostgreSQL, Puppeteer, Redis, Sequential Thinking, Slack, and Stock Price.
- Introduced example scripts for each MCP integration to facilitate user understanding and implementation.
- Ensured consistency in documentation format and clarity in instructions for setting up and using MCP tools.
2025-03-31 09:47:38 +01:00
kevin666aa 798fe68908 update reference 2025-03-30 16:40:06 -04:00
kevin666aa 95796cd4c7 Merge remote-tracking branch 'upstream/main' 2025-03-30 16:22:40 -04:00
Mervin Praison b447b7e6eb Merge pull request #434 from MervinPraison/develop
Add Gradio UI for Airbnb Booking Assistant
2025-03-29 20:55:04 +00:00
MervinPraison 29dfe4b192 Add Gradio UI for Airbnb Booking Assistant
- Introduced a new Gradio interface in `airbnb.mdx` and `ui.py` for searching and booking apartments on Airbnb.
- Implemented the `search_airbnb` function to handle user queries and display results.
- Enhanced user experience with a clear input prompt and structured output format.
2025-03-29 20:54:38 +00:00
Mervin Praison aca95b1713 Merge pull request #433 from MervinPraison/develop
Update navigation and MCP integration
2025-03-29 19:18:34 +00:00
MervinPraison b4cc3d7a8e Update navigation and MCP integration
- Added "MCP" section to `mint.json` for improved documentation navigation.
- Integrated environment variable for `BRAVE_API_KEY` in `mcp-npx-brave.py` to enhance security and flexibility.
- Updated search agent prompt for better clarity.
2025-03-29 19:17:27 +00:00
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
Yuga Sun eaf337b301 fix: remove default stream value for agent 2025-03-11 04:07:40 +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
Yuga Sun 2f73cf1882 fix: support chat without stream 2025-03-10 08:00:05 +00:00
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
kevin666aa 680949742e Merge remote-tracking branch 'upstream/main' 2025-02-13 15:44:32 -05:00
kevin666aa 560219dcd7 update 2025-02-13 13:39:48 -05: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
Mervin Praison 4354e76fe5 Merge pull request #383 from MervinPraison/develop
Enhance Vision Model Training with Robust Dataset Conversion and Memo…
2025-02-09 02:46:01 +00:00
MervinPraison 4dd77efb75 Enhance Vision Model Training with Robust Dataset Conversion and Memory Optimization
- Significantly improved train_vision.py with more robust dataset conversion process
- Added detailed debugging and logging for dataset loading and conversion
- Implemented advanced memory management techniques for vision model training
- Enhanced tokenizer handling with fallback mechanisms
- Updated version to 2.0.76 across all relevant files
2025-02-09 02:45:47 +00:00
226 changed files with 33237 additions and 406 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
+2 -2
View File
@@ -20,7 +20,7 @@
</div>
PraisonAI is a production-ready Multi-AI Agents framework with self-reflection, designed to create AI Agents to automate and solve problems ranging from simple tasks to complex challenges. By integrating PraisonAI Agents, AutoGen, and CrewAI into a low-code solution, it streamlines the building and management of multi-agent LLM systems, emphasising simplicity, customisation, and effective human-agent collaboration.
PraisonAI is a production-ready Multi-AI Agents framework with self-reflection, designed to create AI Agents to automate and solve problems ranging from simple tasks to complex challenges. By integrating PraisonAI Agents, AG2 (Formerly AutoGen), and CrewAI into a low-code solution, it streamlines the building and management of multi-agent LLM systems, emphasising simplicity, customisation, and effective human-agent collaboration.
<div align="center">
<a href="https://docs.praison.ai">
@@ -548,7 +548,7 @@ uv pip install -r pyproject.toml --extra "crewai,autogen"
## Other Features
- 🔄 Use CrewAI or AutoGen Framework
- 🔄 Use CrewAI or AG2 (Formerly AutoGen) Framework
- 💻 Chat with ENTIRE Codebase
- 🎨 Interactive UIs
- 📄 YAML-based Configuration
+1 -1
View File
@@ -1,6 +1,6 @@
FROM python:3.11-slim
WORKDIR /app
COPY . .
RUN pip install flask praisonai==2.0.75 gunicorn markdown
RUN pip install flask praisonai==2.1.1 gunicorn markdown
EXPOSE 8080
CMD ["gunicorn", "-b", "0.0.0.0:8080", "api:app"]
+1 -1
View File
@@ -30,7 +30,7 @@ Features:
- Built-in tools
- Structured workflows
### AutoGen Integration
### AG2 (Formerly AutoGen) Integration
Requires installation with:
```bash
pip install "praisonai[autogen]"
+4 -4
View File
@@ -23,7 +23,7 @@ from praisonai.auto import AutoGenerator
### praisonai.agents_generator
Framework-specific agent generation and orchestration:
- CrewAI support (requires `praisonai[crewai]`)
- AutoGen support (requires `praisonai[autogen]`)
- AG2 (Formerly AutoGen) support (requires `praisonai[autogen]`)
```python
from praisonai.agents_generator import AgentsGenerator
@@ -51,7 +51,7 @@ pip install praisonai
# Framework-specific installations
pip install "praisonai[crewai]" # Install with CrewAI support
pip install "praisonai[autogen]" # Install with AutoGen support
pip install "praisonai[autogen]" # Install with AG2 support
pip install "praisonai[crewai,autogen]" # Install both frameworks
# Additional features
@@ -71,9 +71,9 @@ When installing with `pip install "praisonai[crewai]"`, you get:
- Task delegation capabilities
- Sequential and parallel task execution
### AutoGen
### AG2 (Formerly AutoGen)
When installing with `pip install "praisonai[autogen]"`, you get:
- AutoGen framework support
- AG2 framework support
- PraisonAI tools integration
- Multi-agent conversation capabilities
- Code execution environment
+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.75 gunicorn markdown\n&#34;)
file.write(&#34;RUN pip install flask praisonai==2.1.1 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>
+2 -2
View File
@@ -65,14 +65,14 @@ def basic(): # Basic Mode
def advanced(): # Advanced Mode with options
praisonai = PraisonAI(
agent_file="agents.yaml",
framework="autogen",
framework="autogen", # use AG2 framework (Formerly AutoGen)
)
praisonai.run()
def auto(): # Full Automatic Mode
praisonai = PraisonAI(
auto="Create a movie script about car in mars",
framework="autogen"
framework="autogen" # use AG2 framework
)
print(praisonai.framework)
praisonai.run()
+7 -6
View File
@@ -1,12 +1,13 @@
---
title: "AutoGen with PraisonAI"
description: "Guide for using AutoGen framework with PraisonAI, including installation, setup, and multi-agent conversation capabilities"
title: "AG2 with PraisonAI"
description: "Guide for using AG2 framework with PraisonAI, including installation, setup, and multi-agent conversation capabilities"
icon: "robot"
---
# AutoGen with PraisonAI
# AG2 with PraisonAI
Low-code solution to run AutoGen with integrated tools and features.
Low-code solution to run AG2 with integrated tools and features.
AutoGen is being evolved into AG2, check the new look [here](https://docs.ag2.ai/docs/Home/)
## Installation
@@ -16,7 +17,7 @@ pip install "praisonai[autogen]"
```
This installation includes:
- AutoGen framework
- AG2 framework
- PraisonAI tools integration
- Multi-agent conversation capabilities
- Code execution environment
@@ -27,7 +28,7 @@ This installation includes:
# Set your OpenAI API key
export OPENAI_API_KEY=xxxxxxxxxx
# Initialize with AutoGen
# Initialize with AG2
praisonai --framework autogen --init "Create a Movie Script About Cat in Mars"
# Run the agents
+6 -6
View File
@@ -1,7 +1,7 @@
---
title: "Praison AI"
sidebarTitle: "Home"
description: "Comprehensive guide to PraisonAI - an AI Agents Framework with Self Reflection, combining PraisonAI Agents, AutoGen, and CrewAI for building multi-agent LLM systems"
description: "Comprehensive guide to PraisonAI - an AI Agents Framework with Self Reflection, combining PraisonAI Agents, AG2 (Formerly AutoGen), and CrewAI for building multi-agent LLM systems"
icon: "house"
openGraph:
url: "/"
@@ -46,7 +46,7 @@ seo:
</div>
<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.
PraisonAI combines PraisonAI Agents, AG2 (Formerly 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>
## Key Features
@@ -56,7 +56,7 @@ seo:
Automated creation and management of AI agents with self-reflection capabilities
</Card>
<Card title="Framework Integration" icon="puzzle-piece">
Seamless integration with CrewAI and AutoGen frameworks
Seamless integration with CrewAI and AG2 frameworks
</Card>
<Card title="LLM Support" icon="brain">
Support for 100+ Language Learning Models
@@ -301,8 +301,8 @@ seo:
<Card title="CrewAI Framework" icon="users-gear" href="/framework/crewai">
Build collaborative AI teams with CrewAI integration
</Card>
<Card title="AutoGen Framework" icon="robot" href="/framework/autogen">
Create autonomous agent networks using AutoGen
<Card title="AG2 Framework" icon="robot" href="/framework/autogen">
Create autonomous agent networks using AG2 (Formerly AutoGen)
</Card>
<Card title="Multimodal Agents" icon="icons" href="/framework/multimodalagents">
Work with agents that can process text, images, and other data types
@@ -316,7 +316,7 @@ seo:
<CardGroup cols={3}>
<Card title="Multi Agents UI" icon="users" href="/ui/ui">
Work with CrewAI or AutoGen multi-agent systems
Work with CrewAI or AG2 multi-agent systems
</Card>
<Card title="Chat Interface" icon="comments" href="/ui/chat">
Chat with 100+ LLMs using a single AI Agent
+116 -15
View File
@@ -1,7 +1,7 @@
---
title: "Praison AI"
sidebarTitle: "Home"
description: "PraisonAI is a production-ready Multi-AI Agents framework with self-reflection, designed to create AI Agents to automate and solve problems ranging from simple tasks to complex challenges. By integrating PraisonAI Agents, AutoGen, and CrewAI into a low-code solution, it streamlines the building and management of multi-agent LLM systems, emphasising simplicity, customisation, and effective human-agent collaboration."
description: "PraisonAI is a production-ready Multi-AI Agents framework with self-reflection, designed to create AI Agents to automate and solve problems ranging from simple tasks to complex challenges. By integrating PraisonAI Agents, AG2 (Formerly AutoGen), and CrewAI into a low-code solution, it streamlines the building and management of multi-agent LLM systems, emphasising simplicity, customisation, and effective human-agent collaboration."
icon: "house"
openGraph:
url: "/"
@@ -45,7 +45,7 @@ seo:
Automated creation and management of AI agents with self-reflection capabilities
</Card>
<Card title="Framework Integration" icon="puzzle-piece">
Seamless integration with CrewAI and AutoGen frameworks
Seamless integration with CrewAI and AG2 frameworks
</Card>
<Card title="LLM Support" icon="brain">
Support for 100+ Language Learning Models
@@ -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
@@ -610,8 +711,8 @@ flowchart LR
<Card title="CrewAI Framework" icon="users-gear" href="/framework/crewai">
Build collaborative AI teams with CrewAI integration
</Card>
<Card title="AutoGen Framework" icon="robot" href="/framework/autogen">
Create autonomous agent networks using AutoGen
<Card title="AG2 Framework" icon="robot" href="/framework/autogen">
Create autonomous agent networks using AG2 (Formerly AutoGen)
</Card>
<Card title="Multimodal Agents" icon="icons" href="/framework/multimodalagents">
Work with agents that can process text, images, and other data types
@@ -625,7 +726,7 @@ flowchart LR
<CardGroup cols={3}>
<Card title="Multi Agents UI" icon="users" href="/ui/ui">
Work with CrewAI or AutoGen multi-agent systems
Work with CrewAI or AG2 multi-agent systems
</Card>
<Card title="Chat Interface" icon="comments" href="/ui/chat">
Chat with 100+ LLMs using a single AI Agent
+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>
+112
View File
@@ -0,0 +1,112 @@
---
title: "Airbnb MCP Integration"
sidebarTitle: "Airbnb"
description: "Guide for integrating Airbnb booking capabilities with PraisonAI agents using MCP"
icon: "airbnb"
---
## Add Airbnb Tool to AI Agent
```mermaid
flowchart LR
In[In] --> Agent[AI Agent]
Agent --> Tool[Airbnb MCP]
Tool --> Agent
Agent --> Out[Out]
style In fill:#8B0000,color:#fff
style Agent fill:#2E8B57,color:#fff
style Tool fill:#FF5A5F,color:#fff
style Out fill:#8B0000,color:#fff
```
## Quick Start
<Steps>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable in your terminal:
```bash
export OPENAI_API_KEY=your_openai_api_key_here
```
</Step>
<Step title="Create a file">
Create a new file `airbnb_search.py` with the following code:
```python
from praisonaiagents import Agent, MCP
search_agent = Agent(
instructions="""You help book apartments on Airbnb.""",
llm="gpt-4o-mini",
tools=MCP("npx -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")
```
</Step>
<Step title="Install Dependencies">
Make sure you have Node.js installed, as the MCP server requires it:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Run the Agent">
Execute your script:
```bash
python airbnb_search.py
```
</Step>
</Steps>
<Note>
**Requirements**
- Python 3.10 or higher
- Node.js installed on your system
- OpenAI API key (for the agent's LLM)
</Note>
## Gradio UI
```python
from praisonaiagents import Agent, MCP
import gradio as gr
def search_airbnb(query):
agent = Agent(
instructions="You help book apartments on Airbnb.",
llm="gpt-4o-mini",
tools=MCP("npx -y @openbnb/mcp-server-airbnb --ignore-robots-txt")
)
result = agent.start(query)
return f"## Airbnb Search Results\n\n{result}"
demo = gr.Interface(
fn=search_airbnb,
inputs=gr.Textbox(placeholder="I want to book an apartment in Paris for 2 nights..."),
outputs=gr.Markdown(),
title="Airbnb Booking Assistant",
description="Enter your booking requirements below:"
)
if __name__ == "__main__":
demo.launch()
```
## Features
<CardGroup cols={2}>
<Card title="Accommodation Search" icon="hotel">
Search for accommodations on Airbnb with natural language queries.
</Card>
<Card title="MCP Integration" icon="plug">
Seamless integration with Model Context Protocol.
</Card>
<Card title="Booking Details" icon="calendar">
Specify dates, guests, and location preferences in natural language.
</Card>
<Card title="NPM Package" icon="js">
Leverages the official Airbnb MCP server package.
</Card>
</CardGroup>
+93
View File
@@ -0,0 +1,93 @@
---
title: "Anthropic MCP Integration"
sidebarTitle: "Anthropic"
description: "Guide for integrating Anthropic's Claude models with PraisonAI agents using MCP"
icon: "a"
---
## Add Anthropic Tool to AI Agent
```mermaid
flowchart LR
In[In] --> Agent[AI Agent]
Agent --> Tool[Airbnb MCP]
Tool --> Agent
Agent --> Out[Out]
style In fill:#8B0000,color:#fff
style Agent fill:#2E8B57,color:#fff
style Tool fill:#FF5A5F,color:#fff
style Out fill:#8B0000,color:#fff
```
## Quick Start
<Steps>
<Step title="Set API Key">
Set your Anthropic API key as an environment variable in your terminal:
```zsh
export ANTHROPIC_API_KEY=your_anthropic_api_key_here
```
</Step>
<Step title="Create a file">
Create a new file `anthropic_airbnb.py` with the following code:
```python
from praisonaiagents import Agent, MCP
import os
# Get API key from environment variable
anthropic_api_key = os.environ.get("ANTHROPIC_API_KEY")
search_agent = Agent(
instructions="""You help book apartments on Airbnb.""",
llm="anthropic/claude-3-7-sonnet-20250219",
tools=MCP(
command="npx",
args=["-y", "@openbnb/mcp-server-airbnb", "--ignore-robots-txt"],
env={"ANTHROPIC_API_KEY": anthropic_api_key}
)
)
search_agent.start("MUST USE airbnb_search Tool to Search. Search for Apartments in Paris for 2 nights. 04/28 - 04/30 for 2 adults. All Your Preference")
```
</Step>
<Step title="Install Dependencies">
Make sure you have Node.js installed, as the MCP server requires it:
```bash
pip install "praisonaiagents[llm]"
```
</Step>
<Step title="Run the Agent">
Execute your script:
```bash
python anthropic_airbnb.py
```
</Step>
</Steps>
<Note>
**Requirements**
- Python 3.10 or higher
- Node.js installed on your system
- Anthropic API key
</Note>
## Features
<CardGroup cols={2}>
<Card title="Claude 3.7 Sonnet" icon="brain">
Leverage Anthropic's powerful Claude 3.7 Sonnet model.
</Card>
<Card title="MCP Integration" icon="plug">
Seamless integration with Model Context Protocol.
</Card>
<Card title="Airbnb Search" icon="hotel">
Search for accommodations on Airbnb with natural language queries.
</Card>
<Card title="Environment Variables" icon="key">
Securely pass API keys using environment variables.
</Card>
</CardGroup>
+84
View File
@@ -0,0 +1,84 @@
---
title: "AWS KB Retrieval MCP Integration"
sidebarTitle: "AWS KB Retrieval"
description: "Guide for integrating AWS Knowledge Base retrieval capabilities with PraisonAI agents using MCP"
icon: "aws"
---
## Add AWS KB Retrieval Tool to AI Agent
```mermaid
flowchart LR
In[Query] --> Agent[AI Agent]
Agent --> Tool[AWS KB Retrieval MCP]
Tool --> Agent
Agent --> Out[Answer]
style In fill:#8B0000,color:#fff
style Agent fill:#2E8B57,color:#fff
style Tool fill:#FF9900,color:#fff
style Out fill:#8B0000,color:#fff
```
## Quick Start
<Steps>
<Step title="Install Dependencies">
Make sure you have Node.js installed, as the MCP server requires it:
```bash
pip install praisonaiagents mcp
```
</Step>
<Step title="Set API Keys">
Set your AWS credentials as environment variables in your terminal:
```bash
export AWS_ACCESS_KEY_ID=your_aws_access_key_id_here
export AWS_SECRET_ACCESS_KEY=your_aws_secret_access_key_here
export AWS_REGION=your_aws_region_here
export OPENAI_API_KEY=your_openai_api_key_here
```
</Step>
<Step title="Create a file">
Create a new file `aws_kb_retrieval.py` with the following code:
```python
from praisonaiagents import Agent, MCP
import os
# Get AWS credentials from environment
aws_access_key = os.getenv("AWS_ACCESS_KEY_ID")
aws_secret_key = os.getenv("AWS_SECRET_ACCESS_KEY")
aws_region = os.getenv("AWS_REGION")
# Use a single string command with AWS KB Retrieval configuration
aws_kb_agent = Agent(
instructions="""You are a helpful assistant that can interact with AWS Knowledge Base.
Use the available tools when relevant to retrieve and process AWS information.""",
llm="gpt-4o-mini",
tools=MCP("npx -y @modelcontextprotocol/server-aws-kb-retrieval",
env={
"AWS_ACCESS_KEY_ID": aws_access_key,
"AWS_SECRET_ACCESS_KEY": aws_secret_key,
"AWS_REGION": aws_region
})
)
aws_kb_agent.start("Search AWS documentation about EC2 instances")
```
</Step>
<Step title="Run the Agent">
Execute your script:
```bash
python aws_kb_retrieval.py
```
</Step>
</Steps>
<Note>
**Requirements**
- Python 3.10 or higher
- Node.js installed on your system
- AWS credentials (Access Key ID, Secret Access Key, and Region)
- OpenAI API key (for the agent's LLM)
</Note>
+77
View File
@@ -0,0 +1,77 @@
---
title: "Brave Search MCP Integration"
sidebarTitle: "Brave Search"
description: "Guide for integrating Brave Search capabilities with PraisonAI agents using MCP"
icon: "searchengin"
---
## Add Brave Search Tool to AI Agent
```mermaid
flowchart LR
In[Query] --> Agent[AI Agent]
Agent --> Tool[Brave Search MCP]
Tool --> Agent
Agent --> Out[Answer]
style In fill:#8B0000,color:#fff
style Agent fill:#2E8B57,color:#fff
style Tool fill:#4169E1,color:#fff
style Out fill:#8B0000,color:#fff
```
## Quick Start
<Steps>
<Step title="Install Dependencies">
Make sure you have Node.js installed, as the MCP server requires it:
```bash
pip install praisonaiagents mcp
```
</Step>
<Step title="Set API Key">
Set your Brave Search API key as an environment variable in your terminal:
```bash
export BRAVE_API_KEY=your_brave_api_key_here
export OPENAI_API_KEY=your_openai_api_key_here
```
You can obtain a Brave Search API key from [Brave Search API](https://brave.com/search/api/).
</Step>
<Step title="Create a file">
Create a new file `brave_search.py` with the following code:
```python
from praisonaiagents import Agent, MCP
import os
# Use the API key from environment or set it directly
brave_api_key = os.getenv("BRAVE_API_KEY") or "your_brave_api_key_here"
# Use a single string command with environment variables
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("npx -y @modelcontextprotocol/server-brave-search", env={"BRAVE_API_KEY": brave_api_key})
)
search_agent.start("Search more information about AI News")
```
</Step>
<Step title="Run the Agent">
Execute your script:
```bash
python brave_search.py
```
</Step>
</Steps>
<Note>
**Requirements**
- Python 3.10 or higher
- Node.js installed on your system
- Brave Search API key
- OpenAI API key (for the agent's LLM)
</Note>
+103
View File
@@ -0,0 +1,103 @@
---
title: "Custom Python MCP Client"
sidebarTitle: "Custom Python Client"
description: "Guide for creating a client to interact with a custom Python MCP server"
icon: "person-digging"
---
## Custom Python MCP Client
```mermaid
flowchart LR
In[Query] --> Agent[AI Agent]
Agent --> Client[Python MCP Client]
Client --> Server[Python MCP Server]
Server --> Client
Client --> Agent
Agent --> Out[Answer]
style In fill:#8B0000,color:#fff
style Agent fill:#2E8B57,color:#fff
style Client fill:#3776AB,color:#fff
style Server fill:#3776AB,color:#fff
style Out fill:#8B0000,color:#fff
```
## Overview
The Custom Python MCP Client demonstrates how to integrate a custom Python MCP server with a PraisonAI agent. This client connects to a stock price MCP server to retrieve real-time stock information.
## Quick Start
<Steps>
<Step title="Install Dependencies">
Install the required packages:
```bash
pip install praisonaiagents mcp
```
</Step>
<Step title="Set Up the Server">
First, set up the Custom Python MCP Server.
</Step>
<Step title="Create Custom Python Client">
Save the code above to a file named `custom-python-client.py`.
```python
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/custom-python-server.py")
)
# NOTE: Python Path replace with yours: /Users/praison/miniconda3/envs/mcp/bin/python
# NOTE: custom-python-server.py file path, replace it with yours: /Users/praison/stockprice/custom-python-server.py
agent.start("What is the stock price of Tesla?")
```
</Step>
<Step title="Run the Client">
Execute the client script:
```bash
python custom-python-client.py
```
</Step>
</Steps>
<Note>
**Requirements**
- Python 3.10 or higher
- praisonaiagents and mcp packages
- A properly configured custom Python MCP server
- OpenAI API key (for the agent's LLM)
</Note>
## Environment Variables
For better security and flexibility, you can modify the client to use environment variables:
```python
import os
from praisonaiagents import Agent, MCP
# Get paths from environment variables or use defaults
python_path = os.getenv("PYTHON_PATH", "/path/to/python")
server_path = os.getenv("SERVER_PATH", "/path/to/server.py")
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(f"{python_path} {server_path}")
)
agent.start("What is the stock price of Tesla?")
```
This approach allows you to set the paths using environment variables:
```bash
export PYTHON_PATH=/Users/praison/miniconda3/envs/mcp/bin/python
export SERVER_PATH=/Users/praison/stockprice/app.py
```
+86
View File
@@ -0,0 +1,86 @@
---
title: "Custom Python MCP Server"
sidebarTitle: "Custom Python Server"
description: "Guide for creating a custom Python MCP server for stock price retrieval"
icon: "server"
---
## Custom Python MCP Server
```mermaid
flowchart LR
In[Query] --> Agent[AI Agent]
Agent --> Client[Python MCP Client]
Client --> Server[Python MCP Server]
Server --> Client
Client --> Agent
Agent --> Out[Answer]
style In fill:#8B0000,color:#fff
style Agent fill:#2E8B57,color:#fff
style Client fill:#3776AB,color:#fff
style Server fill:#3776AB,color:#fff
style Out fill:#8B0000,color:#fff
```
## Overview
The Custom Python MCP Server is a simple implementation of the Model Context Protocol (MCP) that provides stock price information using the yfinance library. This server can be used with PraisonAI agents to retrieve real-time stock prices.
## Server Implementation
Below is the complete implementation of the custom Python MCP server:
## Quick Start
<Steps>
<Step title="Install Dependencies">
Install the required packages:
```bash
pip install yfinance mcp
```
</Step>
<Step title="Save the Server Code">
Save the code above to a file named `custom-python-server.py`.
```python
import yfinance as yf
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("stock_prices")
@mcp.tool()
async def get_stock_price(ticker: str) -> str:
"""Get the current stock price for a given ticker symbol.
Args:
ticker: Stock ticker symbol (e.g., AAPL, MSFT, GOOG)
Returns:
Current stock price as a string
"""
if not ticker:
return "No ticker provided"
try:
stock = yf.Ticker(ticker)
info = stock.info
current_price = info.get('currentPrice') or info.get('regularMarketPrice')
if not current_price:
return f"Could not retrieve price for {ticker}"
return f"${current_price:.2f}"
except Exception as e:
return f"Error: {str(e)}"
if __name__ == "__main__":
mcp.run(transport='stdio')
```
</Step>
</Steps>
<Note>
**Requirements**
- Python 3.10 or higher
- yfinance package
- mcp package
</Note>
+168
View File
@@ -0,0 +1,168 @@
---
title: "Custom Python MCP Server"
sidebarTitle: "Custom Python MCP"
description: "Guide for creating and using custom Python MCP servers with PraisonAI agents"
icon: "python"
---
# Custom Python MCP Server
```mermaid
flowchart LR
In[In] --> Agent[AI Agent]
Agent --> Tool[Custom Python MCP]
Tool --> Agent
Agent --> Out[Out]
style In fill:#8B0000,color:#fff
style Agent fill:#2E8B57,color:#fff
style Tool fill:#3776AB,color:#fff
style Out fill:#8B0000,color:#fff
```
## Quick Start
<Steps>
<Step title="Create MCP Server">
Create a new file `app.py` with your custom MCP server implementation:
```python
import yfinance as yf
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("stock_prices")
@mcp.tool()
async def get_stock_price(ticker: str) -> str:
"""Get the current stock price for a given ticker symbol.
Args:
ticker: Stock ticker symbol (e.g., AAPL, MSFT, GOOG)
Returns:
Current stock price as a string
"""
if not ticker:
return "No ticker provided"
try:
stock = yf.Ticker(ticker)
info = stock.info
current_price = info.get('currentPrice') or info.get('regularMarketPrice')
if not current_price:
return f"Could not retrieve price for {ticker}"
return f"${current_price:.2f}"
except Exception as e:
return f"Error: {str(e)}"
if __name__ == "__main__":
mcp.run(transport='stdio')
```
</Step>
<Step title="Install Dependencies">
Install the required dependencies in a conda environment:
```bash
pip install yfinance mcp
```
</Step>
<Step title="Create Agent Integration">
Create a new file `stock_agent.py` with the following code:
```python
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("/path/to/python /path/to/app.py")
)
# NOTE: Replace with your actual Python path and app.py file path
agent.start("What is the stock price of Tesla?")
```
</Step>
<Step title="Run the Agent">
Execute your script:
```bash
python stock_agent.py
```
</Step>
</Steps>
<Note>
**Requirements**
- Python 3.10 or higher
- Conda for environment management
- yfinance package for stock data
- mcp-python-sdk for MCP server implementation
- OpenAI API key (for the agent's LLM)
</Note>
## Features
<CardGroup cols={2}>
<Card title="Custom Tools" icon="wrench">
Create your own custom tools with Python.
</Card>
<Card title="MCP Integration" icon="plug">
Seamless integration with Model Context Protocol.
</Card>
<Card title="Type Hints" icon="code">
Strong typing for better code reliability.
</Card>
<Card title="Async Support" icon="bolt">
Built-in support for asynchronous functions.
</Card>
</CardGroup>
## Implementation Details
### FastMCP Class
The `FastMCP` class from the `mcp-python-sdk` package provides a simple way to create MCP servers in Python:
```python
from mcp.server.fastmcp import FastMCP
# Create an MCP server with a name
mcp = FastMCP("my_tools")
# Define a tool using the @mcp.tool decorator
@mcp.tool()
async def my_tool(param1: str, param2: int) -> str:
"""Tool description with clear documentation.
Args:
param1: Description of param1
param2: Description of param2
Returns:
Description of the return value
"""
# Tool implementation
return f"Processed {param1} with {param2}"
# Run the server with stdio transport
if __name__ == "__main__":
mcp.run(transport='stdio')
```
### Agent Integration
To use your custom MCP server with PraisonAI agents, use the `MCP` class to specify the command to run your Python script:
```python
from praisonaiagents import Agent, MCP
agent = Agent(
instructions="Agent instructions",
llm="gpt-4o-mini",
tools=MCP(
command="python", # Or full path to Python
args=["path/to/your/mcp_server.py"] # Path to your MCP server script
)
)
```
+76
View File
@@ -0,0 +1,76 @@
---
title: "Everart MCP Integration"
sidebarTitle: "Everart"
description: "Guide for integrating Everart AI art generation capabilities with PraisonAI agents using MCP"
icon: "palette"
---
## Add Everart Tool to AI Agent
```mermaid
flowchart LR
In[Query] --> Agent[AI Agent]
Agent --> Tool[Everart MCP]
Tool --> Agent
Agent --> Out[Answer]
style In fill:#8B0000,color:#fff
style Agent fill:#2E8B57,color:#fff
style Tool fill:#FF6B6B,color:#fff
style Out fill:#8B0000,color:#fff
```
## Quick Start
<Steps>
<Step title="Install Dependencies">
Make sure you have Node.js installed, as the MCP server requires it:
```bash
pip install praisonaiagents mcp
```
</Step>
<Step title="Set API Key">
Set your Everart API key as an environment variable in your terminal:
```bash
export EVERART_API_KEY=your_everart_api_key_here
export OPENAI_API_KEY=your_openai_api_key_here
```
</Step>
<Step title="Create a file">
Create a new file `everart_agent.py` with the following code:
```python
from praisonaiagents import Agent, MCP
import os
# Get Everart API key from environment
everart_api_key = os.getenv("EVERART_API_KEY")
# Use a single string command with Everart configuration
everart_agent = Agent(
instructions="""You are a helpful assistant that can interact with Everart.
Use the available tools when relevant to generate and manage art.""",
llm="gpt-4o-mini",
tools=MCP("npx -y @modelcontextprotocol/server-everart",
env={"EVERART_API_KEY": everart_api_key})
)
everart_agent.start("Generate an artistic image of a sunset")
```
</Step>
<Step title="Run the Agent">
Execute your script:
```bash
python everart_agent.py
```
</Step>
</Steps>
<Note>
**Requirements**
- Python 3.10 or higher
- Node.js installed on your system
- Everart API key
- OpenAI API key (for the agent's LLM)
</Note>
+77
View File
@@ -0,0 +1,77 @@
---
title: "Filesystem MCP Integration"
sidebarTitle: "Filesystem"
description: "Guide for integrating filesystem operations with PraisonAI agents using MCP"
icon: "folder-open"
---
## Add Filesystem Tool to AI Agent
```mermaid
flowchart LR
In[Query] --> Agent[AI Agent]
Agent --> Tool[Filesystem MCP]
Tool --> Agent
Agent --> Out[Answer]
style In fill:#8B0000,color:#fff
style Agent fill:#2E8B57,color:#fff
style Tool fill:#FFA500,color:#fff
style Out fill:#8B0000,color:#fff
```
## Quick Start
<Steps>
<Step title="Install Dependencies">
Make sure you have Node.js installed, as the MCP server requires it:
```bash
pip install praisonaiagents mcp
```
</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_api_key_here
```
</Step>
<Step title="Create a file">
Create a new file `filesystem_agent.py` with the following code:
```python
from praisonaiagents import Agent, MCP
import os
# Define allowed directories for filesystem access
allowed_dirs = [
"/Users/username/Desktop",
"/path/to/other/allowed/dir"
]
# Use a single string command with allowed directories
filesystem_agent = Agent(
instructions="""You are a helpful assistant that can interact with the filesystem.
Use the available tools when relevant to manage files and directories.""",
llm="gpt-4o-mini",
tools=MCP("npx -y @modelcontextprotocol/server-filesystem", args=allowed_dirs)
)
filesystem_agent.start("List files in the allowed directories")
```
</Step>
<Step title="Run the Agent">
Execute your script:
```bash
python filesystem_agent.py
```
</Step>
</Steps>
<Note>
**Requirements**
- Python 3.10 or higher
- Node.js installed on your system
- OpenAI API key (for the agent's LLM)
- Read/write access to the specified directories
</Note>
+76
View File
@@ -0,0 +1,76 @@
---
title: "Google Drive MCP Integration"
sidebarTitle: "Google Drive"
description: "Guide for integrating Google Drive file management with PraisonAI agents using MCP"
icon: "google-drive"
---
## Add Google Drive Tool to AI Agent
```mermaid
flowchart LR
In[Query] --> Agent[AI Agent]
Agent --> Tool[Google Drive MCP]
Tool --> Agent
Agent --> Out[Answer]
style In fill:#8B0000,color:#fff
style Agent fill:#2E8B57,color:#fff
style Tool fill:#0F9D58,color:#fff
style Out fill:#8B0000,color:#fff
```
## Quick Start
<Steps>
<Step title="Install Dependencies">
Make sure you have Node.js installed, as the MCP server requires it:
```bash
pip install praisonaiagents mcp
```
</Step>
<Step title="Set up Google Drive Credentials">
Set your Google Drive credentials path as an environment variable in your terminal:
```bash
export GDRIVE_CREDENTIALS_PATH=path/to/your/gcp-oauth.keys.json
export OPENAI_API_KEY=your_openai_api_key_here
```
</Step>
<Step title="Create a file">
Create a new file `gdrive_agent.py` with the following code:
```python
from praisonaiagents import Agent, MCP
import os
# Get the credentials path from environment
gdrive_credentials = os.getenv("GDRIVE_CREDENTIALS_PATH", "servers/gcp-oauth.keys.json")
# Use a single string command with Google Drive configuration
gdrive_agent = Agent(
instructions="""You are a helpful assistant that can interact with Google Drive.
Use the available tools when relevant to manage files and folders.""",
llm="gpt-4o-mini",
tools=MCP("npx -y @modelcontextprotocol/server-gdrive",
env={"GDRIVE_CREDENTIALS_PATH": gdrive_credentials})
)
gdrive_agent.start("List files in my Google Drive")
```
</Step>
<Step title="Run the Agent">
Execute your script:
```bash
python gdrive_agent.py
```
</Step>
</Steps>
<Note>
**Requirements**
- Python 3.10 or higher
- Node.js installed on your system
- Google Drive API credentials (OAuth keys)
- OpenAI API key (for the agent's LLM)
</Note>
+93
View File
@@ -0,0 +1,93 @@
---
title: "Gemini MCP Integration"
sidebarTitle: "Gemini"
description: "Guide for integrating Google's Gemini models with PraisonAI agents using MCP"
icon: "google"
---
## Add Gemini Tool to AI Agent
```mermaid
flowchart LR
In[In] --> Agent[AI Agent]
Agent --> Tool[Airbnb MCP]
Tool --> Agent
Agent --> Out[Out]
style In fill:#8B0000,color:#fff
style Agent fill:#2E8B57,color:#fff
style Tool fill:#FF5A5F,color:#fff
style Out fill:#8B0000,color:#fff
```
## Quick Start
<Steps>
<Step title="Set API Key">
Set your Google API key as an environment variable in your terminal:
```zsh
export GOOGLE_API_KEY=your_google_api_key_here
```
</Step>
<Step title="Create a file">
Create a new file `gemini_airbnb.py` with the following code:
```python
from praisonaiagents import Agent, MCP
import os
# Get API key from environment variable
google_api_key = os.environ.get("GOOGLE_API_KEY")
search_agent = Agent(
instructions="""You help book apartments on Airbnb.""",
llm="gemini/gemini-2.5-pro-exp-03-25",
tools=MCP(
command="npx",
args=["-y", "@openbnb/mcp-server-airbnb", "--ignore-robots-txt"],
env={"GOOGLE_API_KEY": google_api_key}
)
)
search_agent.start("MUST USE airbnb_search Tool to Search. Search for Apartments in Paris for 2 nights. 04/28 - 04/30 for 2 adults. All Your Preference")
```
</Step>
<Step title="Install Dependencies">
Make sure you have Node.js installed, as the MCP server requires it:
```bash
pip install "praisonaiagents[llm]"
```
</Step>
<Step title="Run the Agent">
Execute your script:
```bash
python gemini_airbnb.py
```
</Step>
</Steps>
<Note>
**Requirements**
- Python 3.10 or higher
- Node.js installed on your system
- Google API key for Gemini models
</Note>
## Features
<CardGroup cols={2}>
<Card title="Gemini 2.5 Pro" icon="brain">
Leverage Google's advanced Gemini 2.5 Pro model.
</Card>
<Card title="MCP Integration" icon="plug">
Seamless integration with Model Context Protocol.
</Card>
<Card title="Airbnb Search" icon="hotel">
Search for accommodations on Airbnb with natural language queries.
</Card>
<Card title="Environment Variables" icon="key">
Securely pass API keys using environment variables.
</Card>
</CardGroup>
+76
View File
@@ -0,0 +1,76 @@
---
title: "GitHub MCP Integration"
sidebarTitle: "GitHub"
description: "Guide for integrating GitHub repository management with PraisonAI agents using MCP"
icon: "github"
---
## Add GitHub Tool to AI Agent
```mermaid
flowchart LR
In[Query] --> Agent[AI Agent]
Agent --> Tool[GitHub MCP]
Tool --> Agent
Agent --> Out[Answer]
style In fill:#8B0000,color:#fff
style Agent fill:#2E8B57,color:#fff
style Tool fill:#181717,color:#fff
style Out fill:#8B0000,color:#fff
```
## Quick Start
<Steps>
<Step title="Install Dependencies">
Make sure you have Node.js installed, as the MCP server requires it:
```bash
pip install praisonaiagents mcp
```
</Step>
<Step title="Set API Key">
Set your GitHub Personal Access Token as an environment variable in your terminal:
```bash
export GITHUB_PERSONAL_ACCESS_TOKEN=your_github_token_here
export OPENAI_API_KEY=your_openai_api_key_here
```
</Step>
<Step title="Create a file">
Create a new file `github_agent.py` with the following code:
```python
from praisonaiagents import Agent, MCP
import os
# Use the API key from environment or set it directly
github_token = os.getenv("GITHUB_PERSONAL_ACCESS_TOKEN")
# Use a single string command with environment variables
github_agent = Agent(
instructions="""You are a helpful assistant that can interact with GitHub.
Use the available tools when relevant to answer user questions.""",
llm="gpt-4o-mini",
tools=MCP("npx -y @modelcontextprotocol/server-github",
env={"GITHUB_PERSONAL_ACCESS_TOKEN": github_token})
)
github_agent.start("List my GitHub repositories")
```
</Step>
<Step title="Run the Agent">
Execute your script:
```bash
python github_agent.py
```
</Step>
</Steps>
<Note>
**Requirements**
- Python 3.10 or higher
- Node.js installed on your system
- GitHub Personal Access Token
- OpenAI API key (for the agent's LLM)
</Note>
+81
View File
@@ -0,0 +1,81 @@
---
title: "GitLab MCP Integration"
sidebarTitle: "GitLab"
description: "Guide for integrating GitLab repository management with PraisonAI agents using MCP"
icon: "gitlab"
---
## Add GitLab Tool to AI Agent
```mermaid
flowchart LR
In[Query] --> Agent[AI Agent]
Agent --> Tool[GitLab MCP]
Tool --> Agent
Agent --> Out[Answer]
style In fill:#8B0000,color:#fff
style Agent fill:#2E8B57,color:#fff
style Tool fill:#FC6D26,color:#fff
style Out fill:#8B0000,color:#fff
```
## Quick Start
<Steps>
<Step title="Install Dependencies">
Make sure you have Node.js installed, as the MCP server requires it:
```bash
pip install praisonaiagents mcp
```
</Step>
<Step title="Set API Keys">
Set your GitLab credentials as environment variables in your terminal:
```bash
export GITLAB_PERSONAL_ACCESS_TOKEN=your_gitlab_token_here
export GITLAB_API_URL=https://gitlab.com/api/v4
export OPENAI_API_KEY=your_openai_api_key_here
```
</Step>
<Step title="Create a file">
Create a new file `gitlab_agent.py` with the following code:
```python
from praisonaiagents import Agent, MCP
import os
# Use the API token and URL from environment or set directly
gitlab_token = os.getenv("GITLAB_PERSONAL_ACCESS_TOKEN")
gitlab_api_url = os.getenv("GITLAB_API_URL", "https://gitlab.com/api/v4")
# Use a single string command with environment variables
gitlab_agent = Agent(
instructions="""You are a helpful assistant that can interact with GitLab.
Use the available tools when relevant to answer user questions.""",
llm="gpt-4o-mini",
tools=MCP("npx -y @modelcontextprotocol/server-gitlab",
env={
"GITLAB_PERSONAL_ACCESS_TOKEN": gitlab_token,
"GITLAB_API_URL": gitlab_api_url
})
)
gitlab_agent.start("List my GitLab projects")
```
</Step>
<Step title="Run the Agent">
Execute your script:
```bash
python gitlab_agent.py
```
</Step>
</Steps>
<Note>
**Requirements**
- Python 3.10 or higher
- Node.js installed on your system
- GitLab Personal Access Token
- OpenAI API key (for the agent's LLM)
</Note>
+76
View File
@@ -0,0 +1,76 @@
---
title: "Google Maps MCP Integration"
sidebarTitle: "Google Maps"
description: "Guide for integrating Google Maps location services with PraisonAI agents using MCP"
icon: "map"
---
## Add Google Maps Tool to AI Agent
```mermaid
flowchart LR
In[Query] --> Agent[AI Agent]
Agent --> Tool[Google Maps MCP]
Tool --> Agent
Agent --> Out[Answer]
style In fill:#8B0000,color:#fff
style Agent fill:#2E8B57,color:#fff
style Tool fill:#4285F4,color:#fff
style Out fill:#8B0000,color:#fff
```
## Quick Start
<Steps>
<Step title="Install Dependencies">
Make sure you have Node.js installed, as the MCP server requires it:
```bash
pip install praisonaiagents mcp
```
</Step>
<Step title="Set API Key">
Set your Google Maps API key as an environment variable in your terminal:
```bash
export GOOGLE_MAPS_API_KEY=your_google_maps_api_key_here
export OPENAI_API_KEY=your_openai_api_key_here
```
</Step>
<Step title="Create a file">
Create a new file `google_maps_agent.py` with the following code:
```python
from praisonaiagents import Agent, MCP
import os
# Get the API key from environment
maps_api_key = os.getenv("GOOGLE_MAPS_API_KEY")
# Use a single string command with Google Maps configuration
maps_agent = Agent(
instructions="""You are a helpful assistant that can interact with Google Maps.
Use the available tools when relevant to handle location-based queries.""",
llm="gpt-4o-mini",
tools=MCP("npx -y @modelcontextprotocol/server-google-maps",
env={"GOOGLE_MAPS_API_KEY": maps_api_key})
)
maps_agent.start("Find nearby restaurants in London")
```
</Step>
<Step title="Run the Agent">
Execute your script:
```bash
python google_maps_agent.py
```
</Step>
</Steps>
<Note>
**Requirements**
- Python 3.10 or higher
- Node.js installed on your system
- Google Maps API key
- OpenAI API key (for the agent's LLM)
</Note>
+85
View File
@@ -0,0 +1,85 @@
---
title: "Groq MCP Integration"
sidebarTitle: "Groq"
description: "Guide for integrating Groq models with PraisonAI agents using MCP"
icon: "bolt"
---
## Add Groq Tool to AI Agent
```mermaid
flowchart LR
In[In] --> Agent[AI Agent]
Agent --> Tool[Airbnb MCP]
Tool --> Agent
Agent --> Out[Out]
style In fill:#8B0000,color:#fff
style Agent fill:#2E8B57,color:#fff
style Tool fill:#FF5A5F,color:#fff
style Out fill:#8B0000,color:#fff
```
## Quick Start
<Steps>
<Step title="Set API Key">
Set your Groq API key as an environment variable in your terminal:
```bash
export GROQ_API_KEY=your_groq_api_key_here
```
</Step>
<Step title="Create a file">
Create a new file `groq_airbnb.py` with the following code:
```python
from praisonaiagents import Agent, MCP
search_agent = Agent(
instructions="""You help book apartments on Airbnb.""",
llm="groq/llama-3.2-90b-vision-preview",
tools=MCP("npx -y @openbnb/mcp-server-airbnb --ignore-robots-txt")
)
search_agent.start("MUST USE airbnb_search Tool to Search. Search for Apartments in Paris for 2 nights. 04/28 - 04/30 for 2 adults. All Your Preference")
```
</Step>
<Step title="Install Dependencies">
Make sure you have Node.js installed, as the MCP server requires it:
```bash
pip install "praisonaiagents[llm]"
```
</Step>
<Step title="Run the Agent">
Execute your script:
```bash
python groq_airbnb.py
```
</Step>
</Steps>
<Note>
**Requirements**
- Python 3.10 or higher
- Node.js installed on your system
- Groq API key
</Note>
## Features
<CardGroup cols={2}>
<Card title="Ultra-Fast Inference" icon="bolt">
Utilize Groq's high-performance LPU inference for rapid responses.
</Card>
<Card title="MCP Integration" icon="plug">
Seamless integration with Model Context Protocol.
</Card>
<Card title="Airbnb Search" icon="hotel">
Search for accommodations on Airbnb with natural language queries.
</Card>
<Card title="Advanced Models" icon="brain">
Access to Llama 3.2 90B and other powerful models.
</Card>
</CardGroup>
+75
View File
@@ -0,0 +1,75 @@
---
title: "Memory MCP Integration"
sidebarTitle: "Memory"
description: "Guide for integrating memory storage capabilities with PraisonAI agents using MCP"
icon: "memory"
---
## Add Memory Tool to AI Agent
```mermaid
flowchart LR
In[Query] --> Agent[AI Agent]
Agent --> Tool[Memory MCP]
Tool --> Agent
Agent --> Out[Answer]
style In fill:#8B0000,color:#fff
style Agent fill:#2E8B57,color:#fff
style Tool fill:#4B0082,color:#fff
style Out fill:#8B0000,color:#fff
```
## Quick Start
<Steps>
<Step title="Install Dependencies">
Make sure you have Node.js installed, as the MCP server requires it:
```bash
pip install praisonaiagents mcp
```
</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_api_key_here
```
</Step>
<Step title="Create a file">
Create a new file `memory_agent.py` with the following code:
```python
from praisonaiagents import Agent, MCP
import os
# Get the memory file path from environment
memory_file_path = os.getenv("MEMORY_FILE_PATH", "/path/to/custom/memory.json")
# Use a single string command with Memory configuration
memory_agent = Agent(
instructions="""You are a helpful assistant that can store and retrieve information.
Use the available tools when relevant to manage memory operations.""",
llm="gpt-4o-mini",
tools=MCP("npx -y @modelcontextprotocol/server-memory",
env={"MEMORY_FILE_PATH": memory_file_path})
)
memory_agent.start("Store this conversation in memory")
```
</Step>
<Step title="Run the Agent">
Execute your script:
```bash
python memory_agent.py
```
</Step>
</Steps>
<Note>
**Requirements**
- Python 3.10 or higher
- Node.js installed on your system
- OpenAI API key (for the agent's LLM)
- Write access to the specified memory file path
</Note>
+93
View File
@@ -0,0 +1,93 @@
---
title: "Mistral MCP Integration"
sidebarTitle: "Mistral"
description: "Guide for integrating Mistral models with PraisonAI agents using MCP"
icon: "wind"
---
## Add Mistral Tool to AI Agent
```mermaid
flowchart LR
In[In] --> Agent[AI Agent]
Agent --> Tool[Airbnb MCP]
Tool --> Agent
Agent --> Out[Out]
style In fill:#8B0000,color:#fff
style Agent fill:#2E8B57,color:#fff
style Tool fill:#FF5A5F,color:#fff
style Out fill:#8B0000,color:#fff
```
## Quick Start
<Steps>
<Step title="Set API Key">
Set your Mistral API key as an environment variable in your terminal:
```zsh
export MISTRAL_API_KEY=your_mistral_api_key_here
```
</Step>
<Step title="Create a file">
Create a new file `mistral_airbnb.py` with the following code:
```python
from praisonaiagents import Agent, MCP
import os
# Get API key from environment variable
mistral_api_key = os.environ.get("MISTRAL_API_KEY")
search_agent = Agent(
instructions="""You help book apartments on Airbnb.""",
llm="mistral/mistral-large-latest",
tools=MCP(
command="npx",
args=["-y", "@openbnb/mcp-server-airbnb", "--ignore-robots-txt"],
env={"MISTRAL_API_KEY": mistral_api_key}
)
)
search_agent.start("MUST USE airbnb_search Tool to Search. Search for Apartments in Paris for 2 nights. 04/28 - 04/30 for 2 adults. All Your Preference")
```
</Step>
<Step title="Install Dependencies">
Make sure you have Node.js installed, as the MCP server requires it:
```bash
pip install "praisonaiagents[llm]"
```
</Step>
<Step title="Run the Agent">
Execute your script:
```bash
python mistral_airbnb.py
```
</Step>
</Steps>
<Note>
**Requirements**
- Python 3.10 or higher
- Node.js installed on your system
- Mistral API key
</Note>
## Features
<CardGroup cols={2}>
<Card title="Mistral Large" icon="brain">
Leverage Mistral's powerful large language model.
</Card>
<Card title="MCP Integration" icon="plug">
Seamless integration with Model Context Protocol.
</Card>
<Card title="Airbnb Search" icon="hotel">
Search for accommodations on Airbnb with natural language queries.
</Card>
<Card title="Environment Variables" icon="key">
Securely pass API keys using environment variables.
</Card>
</CardGroup>
+90
View File
@@ -0,0 +1,90 @@
---
title: "Ollama Python MCP Integration"
sidebarTitle: "Ollama Python"
description: "Guide for integrating Ollama models with Python MCP servers using PraisonAI agents"
icon: "python"
---
## Add Ollama Python Tool to AI Agent
```mermaid
flowchart LR
In[In] --> Agent[AI Agent]
Agent --> Tool[Stock Price MCP]
Tool --> Agent
Agent --> Out[Out]
style In fill:#8B0000,color:#fff
style Agent fill:#2E8B57,color:#fff
style Tool fill:#3776AB,color:#fff
style Out fill:#8B0000,color:#fff
```
## Quick Start
<Steps>
<Step title="Set Up Ollama">
Make sure you have Ollama installed and running locally:
```bash
# Install Ollama from https://ollama.ai/
# Pull the llama3.2 model
ollama pull llama3.2
```
</Step>
<Step title="Create a file">
Create a new file `ollama_stock.py` with the following code:
```python
from praisonaiagents import Agent, MCP
stock_agent = Agent(
instructions="""You are a Stock Price Assistant.""",
llm="ollama/llama3.2",
tools=MCP("/Users/praison/miniconda3/envs/mcp/bin/python /Users/praison/stockprice/app.py")
)
# NOTE: Python Path replace with yours: /Users/praison/miniconda3/envs/mcp/bin/python
# NOTE: app.py file path, replace it with yours: /Users/praison/stockprice/app.py
stock_agent.start("What is the Stock Price of Apple?")
```
</Step>
<Step title="Install Dependencies">
Make sure you have the required packages installed:
```bash
pip install "praisonaiagents[llm]" yfinance mcp
```
</Step>
<Step title="Run the Agent">
Execute your script:
```bash
python ollama_stock.py
```
</Step>
</Steps>
<Note>
**Requirements**
- Python 3.10 or higher
- Ollama installed and running locally
- yfinance and mcp packages installed
</Note>
## Features
<CardGroup cols={2}>
<Card title="Local LLM" icon="server">
Run models locally using Ollama without relying on external APIs.
</Card>
<Card title="Stock Data" icon="chart-line">
Retrieve real-time stock price information using the yfinance library.
</Card>
<Card title="Python MCP" icon="python">
Use Python-based MCP servers for custom tool functionality.
</Card>
<Card title="Privacy-Focused" icon="shield-alt">
Keep sensitive data local with on-device inference.
</Card>
</CardGroup>
+87
View File
@@ -0,0 +1,87 @@
---
title: "Ollama MCP Integration"
sidebarTitle: "Ollama"
description: "Guide for integrating Ollama models with PraisonAI agents using MCP"
icon: "dragon"
---
## Add Ollama Tool to AI Agent
```mermaid
flowchart LR
In[In] --> Agent[AI Agent]
Agent --> Tool[Airbnb MCP]
Tool --> Agent
Agent --> Out[Out]
style In fill:#8B0000,color:#fff
style Agent fill:#2E8B57,color:#fff
style Tool fill:#FF5A5F,color:#fff
style Out fill:#8B0000,color:#fff
```
## Quick Start
<Steps>
<Step title="Set Up Ollama">
Make sure you have Ollama installed and running locally:
```bash
# Install Ollama from https://ollama.ai/
# Pull the llama3.2 model
ollama pull llama3.2
```
</Step>
<Step title="Create a file">
Create a new file `ollama_airbnb.py` with the following code:
```python
from praisonaiagents import Agent, MCP
search_agent = Agent(
instructions="""You help book apartments on Airbnb.""",
llm="ollama/llama3.2",
tools=MCP("npx -y @openbnb/mcp-server-airbnb --ignore-robots-txt")
)
search_agent.start("MUST USE airbnb_search Tool to Search. Search for Apartments in Paris for 2 nights. 04/28 - 04/30 for 2 adults. All Your Preference")
```
</Step>
<Step title="Install Dependencies">
Make sure you have Node.js installed, as the MCP server requires it:
```bash
pip install "praisonaiagents[llm]"
```
</Step>
<Step title="Run the Agent">
Execute your script:
```bash
python ollama_airbnb.py
```
</Step>
</Steps>
<Note>
**Requirements**
- Python 3.10 or higher
- Node.js installed on your system
- Ollama installed and running locally
</Note>
## Features
<CardGroup cols={2}>
<Card title="Local LLM" icon="server">
Run models locally using Ollama without relying on external APIs.
</Card>
<Card title="MCP Integration" icon="plug">
Seamless integration with Model Context Protocol.
</Card>
<Card title="Airbnb Search" icon="hotel">
Search for accommodations on Airbnb with natural language queries.
</Card>
<Card title="Privacy-Focused" icon="shield-alt">
Keep sensitive data local with on-device inference.
</Card>
</CardGroup>
+128
View File
@@ -0,0 +1,128 @@
---
title: "OpenAI MCP Integration"
sidebarTitle: "OpenAI"
description: "Guide for integrating OpenAI models with PraisonAI agents using MCP"
icon: "folder-open"
---
## Add OpenAI Tool to AI Agent
```mermaid
flowchart LR
In[In] --> Agent[AI Agent]
Agent --> Tool[Airbnb MCP]
Tool --> Agent
Agent --> Out[Out]
style In fill:#8B0000,color:#fff
style Agent fill:#2E8B57,color:#fff
style Tool fill:#FF5A5F,color:#fff
style Out fill:#8B0000,color:#fff
```
## Quick Start
<Steps>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable in your terminal:
```zsh
export OPENAI_API_KEY=your_openai_api_key_here
```
</Step>
<Step title="Create a file">
Create a new file `openai_airbnb.py` with the following code:
```python
from praisonaiagents import Agent, MCP
import os
# Get API key from environment variable
openai_api_key = os.environ.get("OPENAI_API_KEY")
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"],
env={"OPENAI_API_KEY": openai_api_key}
)
)
search_agent.start("I want to book an apartment in Paris for 2 nights. 03/28 - 03/30 for 2 adults")
```
</Step>
<Step title="Install Dependencies">
Make sure you have Node.js installed, as the MCP server requires it:
```zsh
pip install praisonaiagents
```
</Step>
<Step title="Run the Agent">
Execute your script:
```zsh
python openai_airbnb.py
```
</Step>
</Steps>
<Note>
**Requirements**
- Python 3.10 or higher
- Node.js installed on your system
- OpenAI API key (for the agent's LLM)
</Note>
## Gradio UI
```python
from praisonaiagents import Agent, MCP
import gradio as gr
import os
# Get API key from environment variable
openai_api_key = os.environ.get("OPENAI_API_KEY")
def search_airbnb(query):
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"],
env={"OPENAI_API_KEY": openai_api_key}
)
)
result = agent.start(query)
return f"## Airbnb Search Results\n\n{result}"
demo = gr.Interface(
fn=search_airbnb,
inputs=gr.Textbox(placeholder="I want to book an apartment in Paris for 2 nights..."),
outputs=gr.Markdown(),
title="Airbnb Booking Assistant",
description="Enter your booking requirements below:"
)
if __name__ == "__main__":
demo.launch()
```
## Features
<CardGroup cols={2}>
<Card title="GPT-4o-mini" icon="brain">
Uses OpenAI's efficient GPT-4o-mini model for optimal performance.
</Card>
<Card title="MCP Integration" icon="plug">
Seamless integration with Model Context Protocol.
</Card>
<Card title="Airbnb Search" icon="hotel">
Search for accommodations on Airbnb with natural language queries.
</Card>
<Card title="Environment Variables" icon="key">
Securely pass API keys using environment variables.
</Card>
</CardGroup>
+85
View File
@@ -0,0 +1,85 @@
---
title: "OpenRouter MCP Integration"
sidebarTitle: "OpenRouter"
description: "Guide for integrating OpenRouter models with PraisonAI agents using MCP"
icon: "network-wired"
---
## Add OpenRouter Tool to AI Agent
```mermaid
flowchart LR
In[In] --> Agent[AI Agent]
Agent --> Tool[Airbnb MCP]
Tool --> Agent
Agent --> Out[Out]
style In fill:#8B0000,color:#fff
style Agent fill:#2E8B57,color:#fff
style Tool fill:#FF5A5F,color:#fff
style Out fill:#8B0000,color:#fff
```
## Quick Start
<Steps>
<Step title="Set API Key">
Set your OpenRouter API key as an environment variable in your terminal:
```bash
export OPENROUTER_API_KEY=your_openrouter_api_key_here
```
</Step>
<Step title="Create a file">
Create a new file `openrouter_airbnb.py` with the following code:
```python
from praisonaiagents import Agent, MCP
search_agent = Agent(
instructions="""You help book apartments on Airbnb.""",
llm="openrouter/google/gemini-2.0-flash-exp:free",
tools=MCP("npx -y @openbnb/mcp-server-airbnb --ignore-robots-txt")
)
search_agent.start("MUST USE airbnb_search Tool to Search. Search for Apartments in Paris for 2 nights. 04/28 - 04/30 for 2 adults. All Your Preference")
```
</Step>
<Step title="Install Dependencies">
Make sure you have Node.js installed, as the MCP server requires it:
```bash
pip install "praisonaiagents[llm]"
```
</Step>
<Step title="Run the Agent">
Execute your script:
```bash
python openrouter_airbnb.py
```
</Step>
</Steps>
<Note>
**Requirements**
- Python 3.10 or higher
- Node.js installed on your system
- OpenRouter API key
</Note>
## Features
<CardGroup cols={2}>
<Card title="Model Flexibility" icon="layer-group">
Access to various models through OpenRouter's unified API.
</Card>
<Card title="MCP Integration" icon="plug">
Seamless integration with Model Context Protocol.
</Card>
<Card title="Airbnb Search" icon="hotel">
Search for accommodations on Airbnb with natural language queries.
</Card>
<Card title="Cost Effective" icon="money-bill">
Use free tier models like Gemini Flash through OpenRouter.
</Card>
</CardGroup>
+91
View File
@@ -0,0 +1,91 @@
---
title: "Perplexity MCP Integration"
sidebarTitle: "Perplexity"
description: "Guide for integrating Perplexity search with PraisonAI agents using MCP"
icon: "magnifying-glass"
---
## Add Perplexity Search Tool to AI Agent
```mermaid
flowchart LR
In[In] --> Agent[AI Agent]
Agent --> Tool[Perplexity MCP]
Tool --> Agent
Agent --> Out[Out]
style In fill:#8B0000,color:#fff
style Agent fill:#2E8B57,color:#fff
style Tool fill:#4B0082,color:#fff
style Out fill:#8B0000,color:#fff
```
## Quick Start
<Steps>
<Step title="Set API Key">
Set your Perplexity API key as an environment variable in your terminal:
```bash
export PERPLEXITY_API_KEY=your_perplexity_api_key_here
```
</Step>
<Step title="Create a file">
Create a new file `perplexity_search.py` with the following code:
```python
from praisonaiagents import Agent, MCP
import os
# Get API key from environment variable
api_key = os.getenv("PERPLEXITY_API_KEY")
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("uvx perplexity-mcp",
env={"PERPLEXITY_API_KEY": api_key, "PERPLEXITY_MODEL": "sonar" })
)
result = agent.start("What is the latest news on AI?, Pass only the query parameter to the tool")
print(result)
```
</Step>
<Step title="Install Dependencies">
Make sure you have the required packages installed:
```bash
pip install "praisonaiagents[llm]"
```
</Step>
<Step title="Run the Agent">
Execute your script:
```bash
python perplexity_search.py
```
</Step>
</Steps>
<Note>
**Requirements**
- Python 3.10 or higher
- Perplexity API key
</Note>
## Features
<CardGroup cols={2}>
<Card title="Web Search" icon="globe">
Search the web for real-time information using Perplexity's powerful search API.
</Card>
<Card title="Sonar Model" icon="radar">
Utilize Perplexity's Sonar model for high-quality search results.
</Card>
<Card title="MCP Integration" icon="plug">
Seamless integration with Model Context Protocol.
</Card>
<Card title="Environment Variables" icon="key">
Securely pass API keys using environment variables.
</Card>
</CardGroup>
+71
View File
@@ -0,0 +1,71 @@
---
title: "PostgreSQL MCP Integration"
sidebarTitle: "PostgreSQL"
description: "Guide for integrating PostgreSQL database operations with PraisonAI agents using MCP"
icon: "database"
---
## Add PostgreSQL Tool to AI Agent
```mermaid
flowchart LR
In[Query] --> Agent[AI Agent]
Agent --> Tool[PostgreSQL MCP]
Tool --> Agent
Agent --> Out[Answer]
style In fill:#8B0000,color:#fff
style Agent fill:#2E8B57,color:#fff
style Tool fill:#336791,color:#fff
style Out fill:#8B0000,color:#fff
```
## Quick Start
<Steps>
<Step title="Install Dependencies">
Make sure you have Node.js installed, as the MCP server requires it:
```bash
pip install praisonaiagents mcp
```
</Step>
<Step title="Set up PostgreSQL">
Ensure you have PostgreSQL running locally or specify your PostgreSQL connection URL.
</Step>
<Step title="Create a file">
Create a new file `postgres_agent.py` with the following code:
```python
from praisonaiagents import Agent, MCP
import os
# PostgreSQL connection string
postgres_url = "postgresql://localhost/mydb"
# Use a single string command with PostgreSQL configuration
postgres_agent = Agent(
instructions="""You are a helpful assistant that can interact with PostgreSQL databases.
Use the available tools when relevant to manage database operations.""",
llm="gpt-4o-mini",
tools=MCP("npx -y @modelcontextprotocol/server-postgres", args=[postgres_url])
)
postgres_agent.start("List all tables in the database")
```
</Step>
<Step title="Run the Agent">
Execute your script:
```bash
python postgres_agent.py
```
</Step>
</Steps>
<Note>
**Requirements**
- Python 3.10 or higher
- Node.js installed on your system
- PostgreSQL server running locally or remotely
- OpenAI API key (for the agent's LLM)
</Note>
+71
View File
@@ -0,0 +1,71 @@
---
title: "Puppeteer MCP Integration"
sidebarTitle: "Puppeteer"
description: "Guide for integrating web automation capabilities with PraisonAI agents using Puppeteer MCP"
icon: "chrome"
---
## Add Puppeteer Tool to AI Agent
```mermaid
flowchart LR
In[Query] --> Agent[AI Agent]
Agent --> Tool[Puppeteer MCP]
Tool --> Agent
Agent --> Out[Answer]
style In fill:#8B0000,color:#fff
style Agent fill:#2E8B57,color:#fff
style Tool fill:#00B4FF,color:#fff
style Out fill:#8B0000,color:#fff
```
## Quick Start
<Steps>
<Step title="Install Dependencies">
Make sure you have Node.js installed, as the MCP server requires it:
```bash
pip install praisonaiagents mcp
```
</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_api_key_here
```
</Step>
<Step title="Create a file">
Create a new file `puppeteer_agent.py` with the following code:
```python
from praisonaiagents import Agent, MCP
import os
# Use a single string command with Puppeteer configuration
puppeteer_agent = Agent(
instructions="""You are a helpful assistant that can automate web browser interactions.
Use the available tools when relevant to perform web automation tasks.""",
llm="gpt-4o-mini",
tools=MCP("npx -y @modelcontextprotocol/server-puppeteer")
)
puppeteer_agent.start("Navigate to example.com and take a screenshot")
```
</Step>
<Step title="Run the Agent">
Execute your script:
```bash
python puppeteer_agent.py
```
</Step>
</Steps>
<Note>
**Requirements**
- Python 3.10 or higher
- Node.js installed on your system
- OpenAI API key (for the agent's LLM)
- Chrome or Chromium browser installed on your system
</Note>
+71
View File
@@ -0,0 +1,71 @@
---
title: "Redis MCP Integration"
sidebarTitle: "Redis"
description: "Guide for integrating Redis database operations with PraisonAI agents using MCP"
icon: "database"
---
## Add Redis Tool to AI Agent
```mermaid
flowchart LR
In[Query] --> Agent[AI Agent]
Agent --> Tool[Redis MCP]
Tool --> Agent
Agent --> Out[Answer]
style In fill:#8B0000,color:#fff
style Agent fill:#2E8B57,color:#fff
style Tool fill:#DC382D,color:#fff
style Out fill:#8B0000,color:#fff
```
## Quick Start
<Steps>
<Step title="Install Dependencies">
Make sure you have Node.js installed, as the MCP server requires it:
```bash
pip install praisonaiagents mcp
```
</Step>
<Step title="Set up Redis">
Ensure you have Redis running locally or specify your Redis connection URL.
</Step>
<Step title="Create a file">
Create a new file `redis_agent.py` with the following code:
```python
from praisonaiagents import Agent, MCP
import os
# Redis connection string
redis_url = "redis://localhost:6379"
# Use a single string command with Redis configuration
redis_agent = Agent(
instructions="""You are a helpful assistant that can interact with Redis.
Use the available tools when relevant to manage Redis operations.""",
llm="gpt-4o-mini",
tools=MCP("npx -y @modelcontextprotocol/server-redis", args=[redis_url])
)
redis_agent.start("Set a key-value pair in Redis")
```
</Step>
<Step title="Run the Agent">
Execute your script:
```bash
python redis_agent.py
```
</Step>
</Steps>
<Note>
**Requirements**
- Python 3.10 or higher
- Node.js installed on your system
- Redis server running locally or remotely
- OpenAI API key (for the agent's LLM)
</Note>
+70
View File
@@ -0,0 +1,70 @@
---
title: "Sequential Thinking MCP Integration"
sidebarTitle: "Sequential Thinking"
description: "Guide for integrating sequential thinking capabilities with PraisonAI agents using MCP"
icon: "brain"
---
## Add Sequential Thinking Tool to AI Agent
```mermaid
flowchart LR
In[Query] --> Agent[AI Agent]
Agent --> Tool[Sequential Thinking MCP]
Tool --> Agent
Agent --> Out[Answer]
style In fill:#8B0000,color:#fff
style Agent fill:#2E8B57,color:#fff
style Tool fill:#6A5ACD,color:#fff
style Out fill:#8B0000,color:#fff
```
## Quick Start
<Steps>
<Step title="Install Dependencies">
Make sure you have Node.js installed, as the MCP server requires it:
```bash
pip install praisonaiagents mcp
```
</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_api_key_here
```
</Step>
<Step title="Create a file">
Create a new file `sequential_thinking.py` with the following code:
```python
from praisonaiagents import Agent, MCP
import os
# Use a single string command with Sequential Thinking configuration
sequential_agent = Agent(
instructions="""You are a helpful assistant that can break down complex problems.
Use the available tools when relevant to perform step-by-step analysis.""",
llm="gpt-4o-mini",
tools=MCP("npx -y @modelcontextprotocol/server-sequential-thinking")
)
sequential_agent.start("Break down the process of making a cup of tea")
```
</Step>
<Step title="Run the Agent">
Execute your script:
```bash
python sequential_thinking.py
```
</Step>
</Steps>
<Note>
**Requirements**
- Python 3.10 or higher
- Node.js installed on your system
- OpenAI API key (for the agent's LLM)
</Note>
+81
View File
@@ -0,0 +1,81 @@
---
title: "Slack MCP Integration"
sidebarTitle: "Slack"
description: "Guide for integrating Slack messaging capabilities with PraisonAI agents using MCP"
icon: "slack"
---
## Add Slack Tool to AI Agent
```mermaid
flowchart LR
In[Query] --> Agent[AI Agent]
Agent --> Tool[Slack MCP]
Tool --> Agent
Agent --> Out[Answer]
style In fill:#8B0000,color:#fff
style Agent fill:#2E8B57,color:#fff
style Tool fill:#4A154B,color:#fff
style Out fill:#8B0000,color:#fff
```
## Quick Start
<Steps>
<Step title="Install Dependencies">
Make sure you have Node.js installed, as the MCP server requires it:
```bash
pip install praisonaiagents mcp
```
</Step>
<Step title="Set API Keys">
Set your Slack credentials as environment variables in your terminal:
```bash
export SLACK_BOT_TOKEN=your_slack_bot_token_here
export SLACK_TEAM_ID=your_slack_team_id_here
export OPENAI_API_KEY=your_openai_api_key_here
```
</Step>
<Step title="Create a file">
Create a new file `slack_agent.py` with the following code:
```python
from praisonaiagents import Agent, MCP
import os
# Get Slack credentials from environment
slack_token = os.getenv("SLACK_BOT_TOKEN")
slack_team_id = os.getenv("SLACK_TEAM_ID")
# Use a single string command with Slack configuration
slack_agent = Agent(
instructions="""You are a helpful assistant that can interact with Slack.
Use the available tools when relevant to manage Slack communications.""",
llm="gpt-4o-mini",
tools=MCP("npx -y @modelcontextprotocol/server-slack",
env={
"SLACK_BOT_TOKEN": slack_token,
"SLACK_TEAM_ID": slack_team_id
})
)
slack_agent.start("Send a message to the general channel")
```
</Step>
<Step title="Run the Agent">
Execute your script:
```bash
python slack_agent.py
```
</Step>
</Steps>
<Note>
**Requirements**
- Python 3.10 or higher
- Node.js installed on your system
- Slack Bot Token and Team ID
- OpenAI API key (for the agent's LLM)
</Note>
+248
View File
@@ -0,0 +1,248 @@
---
title: "MCP SSE Integration"
sidebarTitle: "MCP SSE"
description: "Guide for integrating Server-Sent Events (SSE) with PraisonAI agents using MCP"
icon: "server"
---
## Add SSE Tool to AI Agent
```mermaid
flowchart LR
In[In] --> Agent[AI Agent]
Agent --> Tool[SSE MCP]
Tool --> Agent
Agent --> Out[Out]
style In fill:#8B0000,color:#fff
style Agent fill:#2E8B57,color:#fff
style Tool fill:#4169E1,color:#fff
style Out fill:#8B0000,color:#fff
```
## Quick Start
<Steps>
<Step title="Create a client file">
```python
from praisonaiagents import Agent, MCP
search_agent = Agent(
instructions="""You are a weather agent that can provide weather information for a given city.""",
llm="gpt-4o-mini",
tools=MCP("http://localhost:8080/sse")
)
search_agent.start("What is the weather in London?")
```
</Step>
<Step title="Set Up SSE MCP Server">
```python
# python mcp-sse-direct-server.py --host 127.0.0.1 --port 8080
from typing import Any
import httpx
from mcp.server.fastmcp import FastMCP
from starlette.applications import Starlette
from mcp.server.sse import SseServerTransport
from starlette.requests import Request
from starlette.routing import Mount, Route
from mcp.server import Server
import uvicorn
import argparse
import logging
import os
import inspect
# Set up logging based on environment variable
log_level = os.environ.get("LOGLEVEL", "info").upper()
logging.basicConfig(level=getattr(logging, log_level))
logger = logging.getLogger("mcp-server")
# Initialize FastMCP server for simple tools (SSE)
mcp = FastMCP("simple-tools")
@mcp.tool()
async def get_greeting(name: str) -> str:
"""Get a personalized greeting.
Args:
name: Name of the person to greet
"""
logger.debug(f"get_greeting called with name: {name}")
return f"Hello, {name}! Welcome to our MCP SSE server."
@mcp.tool()
async def get_weather(city: str) -> str:
"""Get a simulated weather report for a city.
Args:
city: Name of the city
"""
logger.debug(f"get_weather called with city: {city}")
# This is a mock implementation
weather_data = {
"Paris": "Sunny with a temperature of 22°C",
"London": "Rainy with a temperature of 15°C",
"New York": "Cloudy with a temperature of 18°C",
"Tokyo": "Clear skies with a temperature of 25°C",
"Sydney": "Partly cloudy with a temperature of 20°C"
}
return weather_data.get(city, f"Weather data not available for {city}")
def create_starlette_app(mcp_server: Server, *, debug: bool = False) -> Starlette:
"""Create a Starlette application that can serve the provided mcp server with SSE."""
sse = SseServerTransport("/messages/")
async def handle_sse(request: Request) -> None:
logger.debug(f"SSE connection request received from {request.client}")
async with sse.connect_sse(
request.scope,
request.receive,
request._send, # noqa: SLF001
) as (read_stream, write_stream):
await mcp_server.run(
read_stream,
write_stream,
mcp_server.create_initialization_options(),
)
return Starlette(
debug=debug,
routes=[
Route("/sse", endpoint=handle_sse),
Mount("/messages/", app=sse.handle_post_message),
],
)
if __name__ == "__main__":
mcp_server = mcp._mcp_server # noqa: WPS437
parser = argparse.ArgumentParser(description='Run MCP SSE-based server')
parser.add_argument('--host', default='localhost', help='Host to bind to')
parser.add_argument('--port', type=int, default=8080, help='Port to listen on')
args = parser.parse_args()
print(f"Starting MCP SSE server on {args.host}:{args.port}")
# Hardcode the tool names since we know what they are
tool_names = ["get_greeting", "get_weather"]
print(f"Available tools: {', '.join(tool_names)}")
# Bind SSE request handling to MCP server
starlette_app = create_starlette_app(mcp_server, debug=True)
uvicorn.run(starlette_app, host=args.host, port=args.port)
```
</Step>
<Step title="Install Dependencies">
Make sure you have the required packages installed:
```bash
pip install "praisonaiagents[llm]" mcp starlette uvicorn httpx
```
</Step>
<Step title="Export API Key">
```bash
export OPENAI_API_KEY="your_api_key"
```
</Step>
<Step title="Run the Server and Agent">
First, start the SSE server:
```bash
python mcp-sse-direct-server.py --host 127.0.0.1 --port 8080
```
Then, in a new terminal, run the agent:
```bash
python weather_agent.py
```
</Step>
</Steps>
<Note>
**Requirements**
- Python 3.10 or higher
- MCP server dependencies
</Note>
## Alternative LLM Integrations
### Using Groq with SSE
```python
from praisonaiagents import Agent, MCP
weather_agent = Agent(
instructions="""You are a weather agent that can provide weather information for a given city.""",
llm="groq/llama-3.2-90b-vision-preview",
tools=MCP("http://localhost:8080/sse")
)
weather_agent.start("What is the weather in London?")
```
### Using Ollama with SSE
```python
from praisonaiagents import Agent, MCP
weather_agent = Agent(
instructions="""You are a weather agent that can provide weather information for a given city.""",
llm="ollama/llama3.2",
tools=MCP("http://localhost:8080/sse")
)
weather_agent.start("What is the weather in London? Use get_weather tool, city is the required parameter.")
```
## Gradio UI Integration
Create a Gradio UI for your weather service:
```python
from praisonaiagents import Agent, MCP
import gradio as gr
def get_weather_info(query):
weather_agent = Agent(
instructions="""You are a weather agent that can provide weather information for a given city.""",
llm="gpt-4o-mini",
tools=MCP("http://localhost:8080/sse")
)
result = weather_agent.start(query)
return f"## Weather Information\n\n{result}"
demo = gr.Interface(
fn=get_weather_info,
inputs=gr.Textbox(placeholder="What's the weather in London?"),
outputs=gr.Markdown(),
title="Weather MCP Agent",
description="Ask about the weather in any major city:"
)
if __name__ == "__main__":
demo.launch()
```
## Features
<CardGroup cols={2}>
<Card title="Real-time Updates" icon="bolt">
Receive server-sent events in real-time from your AI agent.
</Card>
<Card title="Multi-Agent Support" icon="users">
Combine SSE with other MCP tools for complex workflows.
</Card>
<Card title="Multiple LLM Options" icon="brain">
Use with OpenAI, Groq, Ollama, or other supported LLMs.
</Card>
<Card title="Gradio UI" icon="window">
Create user-friendly interfaces for your SSE integrations.
</Card>
</CardGroup>
+153
View File
@@ -0,0 +1,153 @@
---
title: "Stock Price MCP Integration"
sidebarTitle: "Stock Price"
description: "Guide for integrating stock price retrieval capabilities with PraisonAI agents using MCP"
icon: "chart-line"
---
## Add Stock Price Tool to AI Agent
```mermaid
flowchart LR
In[Query] --> Agent[AI Agent]
Agent --> Tool[Stock Price MCP]
Tool --> Agent
Agent --> Out[Answer]
style In fill:#8B0000,color:#fff
style Agent fill:#2E8B57,color:#fff
style Tool fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
## Quick Start
<Steps>
<Step title="Install Dependencies">
Create a conda environment and install the required packages:
```bash
zsh -c "source $(conda info --base)/etc/profile.d/conda.sh && conda create -n windsurf python=3.10 -y"
zsh -c "source $(conda info --base)/etc/profile.d/conda.sh && conda activate windsurf && pip install praisonaiagents mcp yfinance"
```
</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_api_key_here
```
</Step>
<Step title="Create the MCP Server">
Create a new file `stock_price_server.py` with the following code:
```python
import yfinance as yf
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("stock_prices")
@mcp.tool()
async def get_stock_price(ticker: str) -> str:
"""Get the current stock price for a given ticker symbol.
Args:
ticker: Stock ticker symbol (e.g., AAPL, MSFT, GOOG)
Returns:
Current stock price as a string
"""
if not ticker:
return "No ticker provided"
try:
stock = yf.Ticker(ticker)
info = stock.info
current_price = info.get('currentPrice') or info.get('regularMarketPrice')
if not current_price:
return f"Could not retrieve price for {ticker}"
return f"${current_price:.2f}"
except Exception as e:
return f"Error: {str(e)}"
if __name__ == "__main__":
mcp.run(transport='stdio')
```
</Step>
<Step title="Create the Agent">
Create a new file `stock_price_agent.py` with the following code:
```python
from praisonaiagents import Agent, MCP
import os
# Get the path to your Python interpreter and the server file
python_path = os.getenv("PYTHON_PATH", "/path/to/your/python")
server_path = os.getenv("SERVER_PATH", "/path/to/your/stock_price_server.py")
# Create the agent with the stock price MCP tool
agent = Agent(
instructions="""You are a helpful assistant that can check stock prices.
Use the available tools when relevant to answer user questions.""",
llm="gpt-4o-mini",
tools=MCP(f"{python_path} {server_path}")
)
agent.start("What is the stock price of Tesla?")
```
</Step>
<Step title="Run the Agent">
Execute your script:
```bash
zsh -c "source $(conda info --base)/etc/profile.d/conda.sh && conda activate windsurf && python stock_price_agent.py"
```
</Step>
</Steps>
<Note>
**Requirements**
- Python 3.10 or higher
- yfinance package
- mcp-python-sdk package
- praisonaiagents package
- OpenAI API key (for the agent's LLM)
</Note>
## Gradio UI Example
You can also create a simple web UI for your stock price agent using Gradio:
```python
from praisonaiagents import Agent, MCP
import gradio as gr
import os
# Get the path to your Python interpreter and the server file
python_path = os.getenv("PYTHON_PATH", "/path/to/your/python")
server_path = os.getenv("SERVER_PATH", "/path/to/your/stock_price_server.py")
# Create the agent with the stock price MCP tool
agent = Agent(
instructions="""You are a helpful assistant that can check stock prices.
Use the available tools when relevant to answer user questions.""",
llm="gpt-4o-mini",
tools=MCP(f"{python_path} {server_path}")
)
def chat(message, history):
return agent.chat(message)
demo = gr.ChatInterface(
chat,
title="Stock Price Assistant",
description="Ask about any stock price and get real-time information",
theme="soft"
)
if __name__ == "__main__":
demo.launch()
```
Install Gradio with:
```bash
zsh -c "source $(conda info --base)/etc/profile.d/conda.sh && conda activate windsurf && pip install gradio"
```
+185
View File
@@ -0,0 +1,185 @@
---
title: "WhatsApp MCP Integration"
sidebarTitle: "WhatsApp"
description: "Guide for integrating WhatsApp messaging with PraisonAI agents using MCP"
icon: "whatsapp"
---
## Add WhatsApp Tool to AI Agent
```mermaid
flowchart LR
In[In] --> Agent[AI Agent]
Agent --> Tool[WhatsApp MCP]
Tool --> Agent
Agent --> Out[Out]
style In fill:#8B0000,color:#fff
style Agent fill:#2E8B57,color:#fff
style Tool fill:#25D366,color:#fff
style Out fill:#8B0000,color:#fff
```
## Quick Start
<Steps>
<Step title="Set Up WhatsApp MCP Server">
Clone and set up the WhatsApp MCP server:
```bash
git clone https://github.com/lharries/whatsapp-mcp.git
cd whatsapp-mcp
cd whatsapp-bridge
go run main.go
```
</Step>
<Step title="Create a file">
Create a new file `whatsapp_message.py` with the following code:
```python
from praisonaiagents import Agent, MCP
whatsapp_agent = Agent(
instructions="Whatsapp Agent",
llm="gpt-4o-mini",
tools=MCP("python /path/to/whatsapp-mcp/whatsapp-mcp-server/main.py")
)
whatsapp_agent.start("Send Hello to Mervin Praison")
```
Note: Replace `/path/to/whatsapp-mcp` with the actual path to your WhatsApp MCP server.
</Step>
<Step title="Install Dependencies">
Make sure you have the required packages installed:
```bash
pip install "praisonaiagents[llm]" mcp gradio
```
</Step>
<Step title="Export API Key">
```bash
export OPENAI_API_KEY="your_api_key"
```
</Step>
<Step title="Run the Agent">
Execute your script:
```bash
python whatsapp_message.py
```
</Step>
</Steps>
<Note>
**Requirements**
- Python 3.10 or higher
- WhatsApp MCP server set up and configured
</Note>
## Multi-Agent Integration
You can also combine WhatsApp with other MCP tools, such as Airbnb search:
```python
from praisonaiagents import Agent, Agents, MCP
airbnb_agent = Agent(
instructions="""Search for Apartments in Paris for 2 nights on Airbnb. 04/28 - 04/30 for 2 adults""",
llm="gpt-4o-mini",
tools=MCP("npx -y @openbnb/mcp-server-airbnb --ignore-robots-txt")
)
whatsapp_agent = Agent(
instructions="""Send AirBnb Search Result to 'Mervin Praison'""",
llm="gpt-4o-mini",
tools=MCP("python /path/to/whatsapp-mcp/whatsapp-mcp-server/main.py")
)
agents = Agents(agents=[airbnb_agent, whatsapp_agent])
agents.start()
```
## Alternative LLM Integrations
### Using Groq with WhatsApp
```python
from praisonaiagents import Agent, MCP
whatsapp_agent = Agent(
instructions="Whatsapp Agent",
llm="groq/llama-3.2-90b-vision-preview",
tools=MCP("python /path/to/whatsapp-mcp/whatsapp-mcp-server/main.py")
)
whatsapp_agent.start("Send Hello to Mervin Praison")
```
### Using Ollama with WhatsApp
```python
from praisonaiagents import Agent, MCP
whatsapp_agent = Agent(
instructions="Whatsapp Agent",
llm="ollama/llama3.2",
tools=MCP("python /path/to/whatsapp-mcp/whatsapp-mcp-server/main.py")
)
whatsapp_agent.start("Send Hello to Mervin Praison. Use send_message tool, recipient and message are the required parameters.")
```
## Gradio UI Integration
Create a Gradio UI for your WhatsApp and Airbnb integration:
```python
from praisonaiagents import Agent, Agents, MCP
import gradio as gr
def search_airbnb(query):
airbnb_agent = Agent(
instructions=query+" on Airbnb",
llm="gpt-4o-mini",
tools=MCP("npx -y @openbnb/mcp-server-airbnb --ignore-robots-txt")
)
whatsapp_agent = Agent(
instructions="""Send AirBnb Search Result to 'Mervin Praison'. Don't include Phone Number in Response, but include the AirBnb Search Result""",
llm="gpt-4o-mini",
tools=MCP("python /path/to/whatsapp-mcp/whatsapp-mcp-server/main.py")
)
agents = Agents(agents=[airbnb_agent, whatsapp_agent])
result = agents.start()
return f"## Airbnb Search Results\n\n{result}"
demo = gr.Interface(
fn=search_airbnb,
inputs=gr.Textbox(placeholder="I want to book an apartment in Paris for 2 nights..."),
outputs=gr.Markdown(),
title="WhatsApp MCP Agent",
description="Enter your booking requirements below:"
)
if __name__ == "__main__":
demo.launch()
```
## Features
<CardGroup cols={2}>
<Card title="WhatsApp Messaging" icon="message">
Send messages to WhatsApp contacts directly from your AI agent.
</Card>
<Card title="Multi-Agent Support" icon="users">
Combine WhatsApp with other MCP tools for complex workflows.
</Card>
<Card title="Multiple LLM Options" icon="brain">
Use with OpenAI, Groq, Ollama, or other supported LLMs.
</Card>
<Card title="Gradio UI" icon="window">
Create user-friendly interfaces for your WhatsApp integrations.
</Card>
</CardGroup>
+85
View File
@@ -0,0 +1,85 @@
---
title: "xAI MCP Integration"
sidebarTitle: "xAI"
description: "Guide for integrating XAI's Grok model with PraisonAI agents using MCP"
icon: "robot"
---
## Add XAI Tool to AI Agent
```mermaid
flowchart LR
In[In] --> Agent[AI Agent]
Agent --> Tool[Airbnb MCP]
Tool --> Agent
Agent --> Out[Out]
style In fill:#8B0000,color:#fff
style Agent fill:#2E8B57,color:#fff
style Tool fill:#FF5A5F,color:#fff
style Out fill:#8B0000,color:#fff
```
## Quick Start
<Steps>
<Step title="Set API Key">
Set your XAI API key as an environment variable in your terminal:
```bash
export XAI_API_KEY=your_xai_api_key_here
```
</Step>
<Step title="Create a file">
Create a new file `xai_airbnb.py` with the following code:
```python
from praisonaiagents import Agent, MCP
search_agent = Agent(
instructions="""You help book apartments on Airbnb.""",
llm="xai/grok-2-latest",
tools=MCP("npx -y @openbnb/mcp-server-airbnb --ignore-robots-txt")
)
search_agent.start("MUST USE airbnb_search Tool to Search. Search for Apartments in Paris for 2 nights. 04/28 - 04/30 for 2 adults. All Your Preference")
```
</Step>
<Step title="Install Dependencies">
Make sure you have Node.js installed, as the MCP server requires it:
```bash
pip install "praisonaiagents[llm]"
```
</Step>
<Step title="Run the Agent">
Execute your script:
```bash
python xai_airbnb.py
```
</Step>
</Steps>
<Note>
**Requirements**
- Python 3.10 or higher
- Node.js installed on your system
- XAI API key (for the Grok model)
</Note>
## Features
<CardGroup cols={2}>
<Card title="Grok Integration" icon="robot">
Uses XAI's Grok model for advanced natural language understanding.
</Card>
<Card title="MCP Integration" icon="plug">
Seamless integration with Model Context Protocol.
</Card>
<Card title="Airbnb Search" icon="hotel">
Search for accommodations on Airbnb with natural language queries.
</Card>
<Card title="NPM Package" icon="js">
Leverages the official Airbnb MCP server package.
</Card>
</CardGroup>
+91 -1
View File
@@ -75,9 +75,17 @@
"name": "Tools",
"url": "/tools"
},
{
"name": "MCP",
"url": "/mcp"
},
{
"name": "JS",
"url": "/js"
},
{
"name": "Course",
"url": "/course"
}
],
"navigation": [
@@ -154,6 +162,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": [
@@ -201,11 +234,60 @@
"agents/recommendation"
]
},
{
"group": "MCP",
"pages": [
"mcp/airbnb",
"mcp/sse",
"mcp/ollama",
"mcp/groq",
"mcp/openrouter",
"mcp/xai",
"mcp/openai",
"mcp/anthropic",
"mcp/gemini",
"mcp/mistral",
"mcp/whatsapp",
"mcp/perplexity",
"mcp/ollama-python",
"mcp/bravesearch",
"mcp/custom",
"mcp/sequential-thinking",
"mcp/filesystem",
"mcp/github",
"mcp/gdrive",
"mcp/gitlab",
"mcp/google-maps",
"mcp/memory",
"mcp/redis",
"mcp/stockprice",
"mcp/postgres",
"mcp/puppeteer",
"mcp/everart",
"mcp/slack",
"mcp/custom-python-client",
"mcp/custom-python-server"
]
},
{
"group": "Tools",
"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 +326,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 +343,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"
+5 -5
View File
@@ -1,10 +1,10 @@
---
title: "Auto Generation Mode"
description: "Guide to PraisonAI's automatic agent generation feature, supporting both CrewAI and AutoGen frameworks for automated task execution"
description: "Guide to PraisonAI's automatic agent generation feature, supporting both CrewAI and AG2 frameworks for automated task execution"
icon: "robot"
---
PraisonAI supports automatic agent generation with PraisonAI Agents, CrewAI and AutoGen frameworks.
PraisonAI supports automatic agent generation with PraisonAI Agents, CrewAI and AG2 frameworks.
## Installation
@@ -17,7 +17,7 @@ pip install praisonai
# For CrewAI
pip install "praisonai[crewai]"
# For AutoGen
# For AG2 (Formerly AutoGen)
pip install "praisonai[autogen]"
# For both frameworks
@@ -36,7 +36,7 @@ praisonai --auto "create a movie script about Dog in Moon"
praisonai --framework crewai --auto "create a movie script about Dog in Moon"
```
### With AutoGen
### With AG2
```bash
praisonai --framework autogen --auto "create a movie script about Dog in Moon"
```
@@ -49,7 +49,7 @@ praisonai --framework autogen --auto "create a movie script about Dog in Moon"
- Built-in tools integration
- Structured agent-task relationships
### AutoGen
### AG2 (Formerly AutoGen)
- Multi-agent conversation capabilities
- Code execution environment
- Built-in tools integration
+2 -2
View File
@@ -28,13 +28,13 @@ Includes:
- Task delegation capabilities
- Sequential and parallel task execution
### AutoGen Support
### AG2 Support
```bash
pip install "praisonai[autogen]"
```
Includes:
- AutoGen framework
- AG2 framework
- PraisonAI tools integration
- Multi-agent conversation capabilities
- Code execution environment
+1 -1
View File
@@ -21,7 +21,7 @@ icon: "hand-wave"
Create and orchestrate sophisticated multi-agent systems with ease
</Card>
<Card title="Framework Integration" icon="puzzle-piece">
Seamlessly integrates AutoGen and CrewAI capabilities
Seamlessly integrates AG2 and CrewAI capabilities
</Card>
<Card title="Low-Code Design" icon="code">
Build complex AI systems with minimal coding required
+3 -3
View File
@@ -1,6 +1,6 @@
---
title: "TL;DR"
description: "Quick start guide for PraisonAI with CrewAI, AutoGen, and UI setup instructions"
description: "Quick start guide for PraisonAI with CrewAI, AG2 (Formerly AutoGen), and UI setup instructions"
icon: "bolt"
---
@@ -32,10 +32,10 @@ praisonai --framework crewai --init "create a movie script about dog in moon"
praisonai --framework crewai
```
## Quick Start with AutoGen
## Quick Start with AG2
```bash
# Install with AutoGen support
# Install with AG2 support
pip install "praisonai[autogen]"
# Set your API key
+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
+1 -1
View File
@@ -71,7 +71,7 @@ To run the PraisonAI tool, simply type the following command in your terminal:
praisonai
```
If you want to run the `autogen` framework, use:
If you want to run the AG2 framework (Formerly AutoGen), use:
```bash
praisonai --framework autogen
+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):
+1 -1
View File
@@ -18,7 +18,7 @@ icon: "comments"
| Interface | Description | URL |
|---|---|---|
| **UI** | Multi Agents such as CrewAI or AutoGen | [https://docs.praison.ai/ui/ui](https://docs.praison.ai/ui/ui) |
| **UI** | Multi Agents such as CrewAI or AG2 | [https://docs.praison.ai/ui/ui](https://docs.praison.ai/ui/ui) |
| **Chat** | Chat with 100+ LLMs, single AI Agent | [https://docs.praison.ai/ui/chat](https://docs.praison.ai/ui/chat) |
| **Code** | Chat with entire Codebase, single AI Agent | [https://docs.praison.ai/ui/code](https://docs.praison.ai/ui/code) |
+1 -1
View File
@@ -20,7 +20,7 @@ PraisonAI Code helps you to interact with your whole codebase using the power of
| Interface | Description | URL |
|---|---|---|
| **UI** | Multi Agents such as CrewAI or AutoGen | [https://docs.praison.ai/ui/ui](https://docs.praison.ai/ui/ui) |
| **UI** | Multi Agents such as CrewAI or AG2 | [https://docs.praison.ai/ui/ui](https://docs.praison.ai/ui/ui) |
| **Chat** | Chat with 100+ LLMs, single AI Agent | [https://docs.praison.ai/ui/chat](https://docs.praison.ai/ui/chat) |
| **Code** | Chat with entire Codebase, single AI Agent | [https://docs.praison.ai/ui/code](https://docs.praison.ai/ui/code) |
+1 -1
View File
@@ -11,7 +11,7 @@ icon: "browser"
|---|---|---|
| **Streamlit** | Create interactive web apps with Python | [https://docs.praison.ai/ui/streamlit](/ui/streamlit) |
| **Gradio** | Build machine learning web apps rapidly | [https://docs.praison.ai/ui/gradio](/ui/gradio) |
| **UI** | Multi Agents such as CrewAI or AutoGen | [https://docs.praison.ai/ui/ui](/ui/ui) |
| **UI** | Multi Agents such as CrewAI or AG2 | [https://docs.praison.ai/ui/ui](/ui/ui) |
| **Chat** | Chat with 100+ LLMs, single AI Agent | [https://docs.praison.ai/ui/chat](/ui/chat) |
| **Code** | Chat with entire Codebase, single AI Agent | [https://docs.praison.ai/ui/code](/ui/code) |
Loaded 100 of 226 files, more files were not shown because too many files have changed in this diff. Show more