Compare commits

...
48 Commits
Author SHA1 Message Date
Mervin Praison 024eaed456 Merge pull request #316 from MervinPraison/develop
Develop
2025-01-21 17:51:15 +00:00
MervinPraison 4fd3a572cf Update PraisonAI to version 2.0.55 and adjust dependencies
- Bumped PraisonAI version from 2.0.54 to 2.0.55 in `Dockerfile`, `pyproject.toml`, and `uv.lock` to reflect the latest updates.
- Updated the `praisonai.rb` formula to point to the new version's tarball.
- Updated the `praisonaiagents` dependency version from `0.0.45` to `0.0.46` across relevant files for improved functionality.
- Adjusted deployment scripts and documentation to ensure compatibility with the new version.

These changes enhance the overall functionality and usability of the PraisonAI framework, particularly in dependency management and deployment processes.
2025-01-21 17:50:53 +00:00
MervinPraison baaf8b6256 Update version to 0.0.46 and enhance memory feature checks
- Bumped the version of the `praisonaiagents` package from 0.0.45 to 0.0.46 in `pyproject.toml` and `uv.lock` to reflect the latest updates.
- Added import checks for memory features in the `Agent`, `PraisonAIAgents`, and `Task` classes to ensure proper handling of memory dependencies.
- Removed the obsolete `Memory` import from the `__init__.py` file to streamline the codebase.

These changes improve the robustness of the PraisonAI framework by ensuring that memory features are only utilized when the necessary dependencies are installed.
2025-01-21 16:47:31 +00:00
Mervin Praison fe4550d2bc Merge pull request #315 from MervinPraison/develop
2.0.54
2025-01-21 15:01:57 +00:00
MervinPraison db09a94425 Update PraisonAI to version 2.0.54 and enhance agent functionality
- Bumped PraisonAI version from 2.0.53 to 2.0.54 in `Dockerfile`, `pyproject.toml`, and `uv.lock` to reflect the latest updates.
- Updated the `praisonai.rb` formula to point to the new version's tarball.
- Updated the `praisonaiagents` dependency version from `0.0.44` to `0.0.45` across relevant files for improved functionality.
- Removed the obsolete `knowledge-embedding-agents.py` file and introduced a new `vector-db-agents.py` file to enhance knowledge retrieval capabilities.
- Added new documentation for RAG (Retrieval Augmented Generation) agents, detailing their configuration and usage in `docs/features/rag.mdx`.
- Updated deployment scripts to ensure compatibility with the new version and improved agent functionalities.

These changes improve the overall functionality and usability of the PraisonAI framework, particularly in knowledge management and retrieval capabilities.
2025-01-21 15:01:12 +00:00
MervinPraison 2db36dc932 Enhance Knowledge Agent Configuration and Update Version
- Updated the Knowledge Agent configuration to include a new versioning system and improved vector store settings.
- Changed the collection name from "custom_knowledge" to "praison" for consistency across files.
- Added user_id parameter to the Knowledge Agent for better user tracking.
- Enhanced the embedding database configuration to support dynamic context management.
- Bumped the version of the `praisonaiagents` package from 0.0.44 to 0.0.45 in `pyproject.toml` to reflect these updates.

These changes improve the functionality and usability of the Knowledge Agent within the PraisonAI framework, particularly in knowledge management and retrieval capabilities.
2025-01-21 13:09:41 +00:00
Mervin Praison 8c0e4277a4 Merge pull request #313 from MervinPraison/develop
Update PraisonAI to version 2.0.53 and enhance agent functionality
2025-01-20 10:04:38 +00:00
MervinPraison 41448617d5 Update PraisonAI to version 2.0.53 and enhance agent functionality
- Bumped PraisonAI version from 2.0.52 to 2.0.53 in `Dockerfile`, `pyproject.toml`, and `uv.lock` to reflect the latest updates.
- Updated the `praisonai.rb` formula to point to the new version's tarball.
- Updated the `praisonaiagents` dependency version from `0.0.43` to `0.0.44` across relevant files for improved functionality.
- Enhanced the `PraisonAIAgents` class to include a `max_iter` parameter, allowing for more control over agent iterations.
- Added new tasks to `agents/tasks.csv` to expand the capabilities of the agents in handling various writing tasks.
- Updated documentation to reflect changes in agent functionality and new task examples.

These changes improve the overall functionality and usability of the PraisonAI framework, particularly in task execution and agent capabilities.
2025-01-20 10:04:20 +00:00
Mervin Praison 49ea23c676 Merge pull request #312 from MervinPraison/develop
Introducing Repetitive Agents
2025-01-20 07:18:19 +00:00
MervinPraison bb0dc63680 Update PraisonAI to version 2.0.52 and enhance repetitive agents functionality
- Bumped PraisonAI version from 2.0.51 to 2.0.52 in `Dockerfile`, `pyproject.toml`, and `uv.lock` to reflect the latest updates.
- Updated the `praisonai.rb` formula to point to the new version's tarball.
- Updated the `praisonaiagents` dependency version from `0.0.42` to `0.0.43` across relevant files for improved functionality.
- Introduced new files for repetitive agents in `agents/repetitive-agents.py` and `examples/concepts/repetitive-agents.py`, enabling automated task loops.
- Enhanced documentation with a new section on repetitive agents in `docs/features/repetitive.mdx` and updated `mint.json` to include the new feature.

These changes improve the overall functionality and usability of the PraisonAI framework, particularly in handling repetitive tasks and enhancing agent capabilities.
2025-01-20 07:17:43 +00:00
MervinPraison 7774f2c565 Add loop agent functionality and update task management in PraisonAI agents
- Introduced a new loop agent in `loop_agents.py` to create and manage a loop of tasks from a CSV file.
- Added a new file `repetitive-manual-agents.py` that implements task identification, status checking, and updating functionalities.
- Updated `process.py` to enhance task handling by allowing dynamic input files for loop tasks.
- Removed the obsolete `repeat_agents.py` file to streamline the codebase.
- Bumped the version of the `praisonaiagents` package from 0.0.42 to 0.0.43 in `pyproject.toml` and `uv.lock` to reflect these changes.

These updates improve the task execution capabilities of the PraisonAI framework, particularly in handling repetitive tasks and enhancing agent functionality.
2025-01-20 06:56:33 +00:00
MervinPraison 5533fd3476 Enhance logging and improve decision/loop task handling in PraisonAI agents
- Suppressed debug logs from the markdown parser to reduce noise in the logging output.
- Refactored decision-making logic to utilize Pydantic models for better type safety and clarity.
- Updated loop task handling to ensure proper context management and error handling.
- Introduced dynamic literal types for decision and loop tasks to enhance flexibility in task definitions.

These changes improve the overall robustness and usability of the PraisonAI framework, particularly in task execution and logging clarity.
2025-01-19 05:58:46 +00:00
Mervin Praison 262a90a235 Merge pull request #310 from MervinPraison/develop
2.0.51
2025-01-18 06:02:35 +00:00
MervinPraison 60928dcb90 Update PraisonAI to version 2.0.51 and enhance dependencies
- Bumped PraisonAI version from 2.0.50 to 2.0.51 in `Dockerfile`, `pyproject.toml`, and `uv.lock` to reflect the latest updates.
- Updated the `praisonai.rb` formula to point to the new version's tarball.
- Updated the `praisonaiagents` dependency version from `0.0.41` to `0.0.42` across relevant files for improved functionality.
- Enhanced documentation with updated installation instructions for various examples, ensuring users have access to the latest package versions.

These changes improve the overall functionality and usability of the PraisonAI framework, particularly in dependency management and documentation clarity.
2025-01-18 06:02:09 +00:00
MervinPraison c8552e1158 Update PraisonAI agents package version to 0.0.42 in pyproject.toml and uv.lock
- Bumped the version from 0.0.41 to 0.0.42 to reflect recent updates and ensure users have access to the latest features and improvements.
- This change maintains the integrity of the PraisonAI framework and prepares it for future enhancements.
2025-01-18 05:48:57 +00:00
Mervin Praison c57d7db9bb Merge pull request #309 from MervinPraison/develop
Enhance Streamlit UIs for Code Analysis and Hackathon Judging
2025-01-17 22:21:06 +00:00
MervinPraison 236abc2c83 Enhance Streamlit UIs for Code Analysis and Hackathon Judging
- Updated `mint.json` to group Streamlit pages under a new "Streamlit" section, improving organization.
- Renamed titles in `code-analysis.mdx` and `hackathon-judge.mdx` to include "Agent" for clarity.
- Added new Streamlit UI files: `code-analysis-streamlit.mdx` and `hackathon-judge-streamlit.mdx`, providing interactive interfaces for code analysis and hackathon project evaluation.
- Each new UI includes detailed descriptions, features, quick start guides, and visual flowcharts to enhance user experience and understanding.

These changes significantly improve the usability and accessibility of the PraisonAI framework's Streamlit applications, offering users powerful tools for code and project evaluation.
2025-01-17 22:20:51 +00:00
Mervin Praison 76c5f8fe3f Merge pull request #308 from MervinPraison/develop
Add new code analysis and hackathon judge agents with Streamlit integ…
2025-01-17 19:03:12 +00:00
MervinPraison 82750020d2 Add new code analysis and hackathon judge agents with Streamlit integration
- Introduced `code-analysis-agents.py` and `code-analysis-streamlit.py` for comprehensive code evaluation, including metrics on architecture, maintainability, performance, and security.
- Added `context-agents-code.py` and `context-agents.py` for CV analysis capabilities, providing detailed scoring and recommendations.
- Implemented `hackathon-judge-agent.py` and `hackathon-judge-streamlit.py` for evaluating hackathon projects through video demonstrations, offering scores and feedback on innovation, technical complexity, and presentation quality.
- Enhanced documentation with new examples for code analysis and hackathon judging, improving user guidance and showcasing agent capabilities.
- Updated `mint.json` to include new examples, enriching the available resources for users.

These additions significantly expand the functionality of the PraisonAI framework, providing users with powerful tools for code and project evaluation.
2025-01-17 19:02:56 +00:00
Mervin Praison f49ad9fbc2 Merge pull request #306 from MervinPraison/develop
Develop
2025-01-17 17:35:18 +00:00
MervinPraison c086c60fd6 Update PraisonAI to version 2.0.50 and enhance dependencies
- Bumped PraisonAI version from 2.0.49 to 2.0.50 in `Dockerfile`, `pyproject.toml`, and `uv.lock` to reflect the latest updates.
- Updated the `praisonai.rb` formula to point to the new version's tarball.
- Updated the `praisonaiagents` dependency version from `0.0.40` to `0.0.41` across relevant files for improved functionality.
- Added a new `context-agents.py` file to introduce a CV analysis agent with comprehensive evaluation capabilities.
- Modified deployment scripts to ensure compatibility with the updated package version.

These changes improve the overall functionality and usability of the PraisonAI framework, particularly in dependency management and the introduction of new agent capabilities.
2025-01-17 17:35:00 +00:00
MervinPraison 4f8f4f2036 Update package version to 0.0.41 in uv.lock
- Bumped the version of the PraisonAI agents package from 0.0.40 to 0.0.41 to reflect recent updates.
- This change ensures that the latest features and improvements are properly versioned and available for users.
2025-01-17 17:26:51 +00:00
MervinPraison 8e91c20967 Update package version to 0.0.41 in pyproject.toml
- Bumped the version of the PraisonAI agents package from 0.0.40 to 0.0.41 to reflect recent updates.
- This change ensures that the latest features and improvements are properly versioned and available for users.

These updates maintain the integrity of the PraisonAI framework and prepare it for future enhancements.
2025-01-17 17:26:34 +00:00
MervinPraison 6f092c1507 Refactor agent context handling and improve task prompt generation
- Updated `crewai-tools-example.py` to remove unnecessary whitespace.
- Modified `agent.py` to replace `schema_json()` with `model_json_schema()` for JSON output consistency.
- Enhanced context handling in `agents.py` to avoid duplicates and improve clarity in task prompts by using lists instead of strings.
- Added support for passing content to tasks in both `start` and `astart` methods, allowing for dynamic context management.
- Improved task prompt generation in `task.py` to handle various context types, ensuring better output formatting.

These changes enhance the functionality and usability of the PraisonAI agents, particularly in context management and task execution clarity.
2025-01-17 17:25:58 +00:00
Mervin Praison 8f553d3a54 Merge pull request #305 from MervinPraison/develop
2.0.49
2025-01-17 12:24:16 +00:00
MervinPraison 2d647e25b5 Update PraisonAI to version 2.0.49 and enhance dependencies
- Bumped PraisonAI version from 2.0.48 to 2.0.49 in `Dockerfile`, `pyproject.toml`, and `uv.lock` to reflect the latest updates.
- Updated the `praisonai.rb` formula to point to the new version's tarball.
- Updated the `praisonaiagents` dependency version from `0.0.39` to `0.0.40` across relevant files for improved functionality.
- Modified deployment scripts to ensure compatibility with the updated package version.
- Enhanced documentation by adding a new "Tools" section in `mint.json` and updating the title in `custom.mdx` for better clarity.

These changes improve the overall functionality and usability of the PraisonAI framework, particularly in dependency management and documentation clarity.
2025-01-17 12:23:44 +00:00
MervinPraison 039bb772f5 Update version to 0.0.40 and enhance agent functionality
- Bumped the package version in `pyproject.toml` and `uv.lock` from `0.0.39` to `0.0.40` to reflect recent updates.
- Improved the `Agent` class in `agent.py` to support both Langchain and CrewAI tools by adding checks for the presence of `run` and `_run` methods, allowing for more flexible function handling.

These changes enhance the functionality of the PraisonAI agents, ensuring compatibility with different toolsets and improving overall usability.
2025-01-17 12:13:08 +00:00
Mervin Praison 459c2f2b70 Merge pull request #304 from MervinPraison/develop
Add new examples and enhance documentation for AI agent use cases
2025-01-17 10:34:16 +00:00
MervinPraison ee59706357 Add new examples and enhance documentation for AI agent use cases
- Introduced multiple new example files for various AI agent applications, including Climate Impact, Crypto Validator, DeFi Market Maker, Medicine Protocol, Neural Architecture, Quantum Optimiser, Research Assistant, Space Mission, and Vulnerability Detection.
- Updated `mint.json` to include new examples, improving the breadth of use cases available for users.
- Enhanced the `examples.mdx` file to provide links and descriptions for the newly added examples, facilitating easier navigation and understanding of the capabilities of PraisonAI.

These changes significantly expand the documentation and practical examples available to users, showcasing the versatility of the PraisonAI framework in various domains.
2025-01-17 10:33:58 +00:00
Mervin Praison 2a51644773 Merge pull request #303 from MervinPraison/develop
Refactor documentation and enhance quickstart guide for PraisonAI
2025-01-16 11:45:30 +00:00
MervinPraison cce908fa22 Refactor documentation and enhance quickstart guide for PraisonAI
- Removed unnecessary note from the introduction section of `introduction.mdx` for improved clarity.
- Updated the `quickstart.mdx` to provide a more comprehensive and user-friendly guide, including detailed steps for both code and no-code approaches to creating AI agents.
- Enhanced the `knowledge.mdx` file by renaming the vector store from "Chroma" to "Vector DB" for better clarity in terminology.
- Added prerequisites and tips to the quickstart guide to assist users in setting up their environment effectively.

These changes improve the overall usability and clarity of the documentation, making it easier for users to get started with PraisonAI.
2025-01-16 11:45:01 +00:00
Mervin Praison acf476f715 Merge pull request #302 from MervinPraison/develop
Develop
2025-01-16 11:13:41 +00:00
MervinPraison e5d77de79c Update PraisonAI to version 2.0.48 and enhance dependencies
- Bumped PraisonAI version from 2.0.47 to 2.0.48 in `Dockerfile`, `pyproject.toml`, and `uv.lock` to reflect the latest updates.
- Updated the `praisonai.rb` formula to point to the new version's tarball.
- Updated the `praisonaiagents` dependency version from `0.0.38` to `0.0.39` across relevant files for improved functionality.
- Modified deployment scripts to ensure compatibility with the updated package version.
- Removed outdated references in documentation and improved clarity in agent-related concepts.

These changes enhance the overall functionality and usability of the PraisonAI framework, particularly in dependency management and deployment processes.
2025-01-16 11:13:22 +00:00
MervinPraison 9ab444b54c Update knowledge agent configuration and versioning
- Changed the knowledge source in `knowledge-agents.py` from `small.pdf` to `large.pdf` to utilize a more comprehensive dataset.
- Bumped the package version in `pyproject.toml` and `uv.lock` from `0.0.38` to `0.0.39` to reflect recent updates.
- Enhanced the `Knowledge` class in `knowledge.py` by adding a progress display for memory storage operations, improving user experience during knowledge updates.

These changes improve the functionality and usability of the knowledge management system within the PraisonAI framework.
2025-01-16 10:14:11 +00:00
Mervin Praison e13f543c6d Merge pull request #301 from MervinPraison/develop
v0.0.38
2025-01-16 08:27:58 +00:00
MervinPraison 4f235d358c Update PraisonAI to version 2.0.47 and enhance knowledge management features
- Bumped PraisonAI version from 2.0.46 to 2.0.47 in `Dockerfile`, `pyproject.toml`, and `uv.lock` to reflect the latest updates.
- Updated the `praisonai.rb` formula to point to the new version's tarball.
- Enhanced the knowledge management system by adding a new `knowledge.mdx` file and related examples for creating knowledge-based agents.
- Updated documentation to include new concepts and improve clarity on knowledge management functionalities.
- Refactored deployment scripts to ensure compatibility with the updated package version.

These changes improve the overall functionality and usability of the PraisonAI framework, particularly in knowledge management and deployment processes.
2025-01-16 08:27:33 +00:00
MervinPraison b7847feb1e Update package version and enhance logging in Knowledge class
- Bumped the package version in `pyproject.toml` and `uv.lock` from `0.0.37` to `0.0.38` to reflect recent changes.
- Modified the `Knowledge` class in `knowledge.py` to include a `verbose` parameter for improved logging control.
- Implemented an internal logging helper method to streamline log messages and manage logging levels based on the `verbose` setting.
- Updated various logging statements to utilize the new logging helper, enhancing clarity and consistency in log outputs.

These changes improve the maintainability and usability of the knowledge management system by providing better logging capabilities.
2025-01-16 08:14:21 +00:00
MervinPraison 7ac730462c Update knowledge agent configuration and enhance memory management
- Changed the knowledge source in `knowledge-agents.py` from `large.pdf` to `small.pdf` for improved testing consistency.
- Bumped the package version in `pyproject.toml` from `0.0.36` to `0.0.37` to reflect recent changes.
- Updated the `chromadb` dependency version in `pyproject.toml` to `0.5.23` for compatibility.
- Enhanced the `CustomMemory` class in `knowledge.py` to allow dynamic memory management without relying on LLM, improving performance and flexibility.
- Introduced cached properties in the `Knowledge` class for better configuration handling and memory management.

These changes improve the knowledge agent's functionality and ensure better performance in memory operations.
2025-01-16 08:07:08 +00:00
MervinPraison 9cbc8d082d Add chunking functionality and update knowledge management features
Knowledge working without lazy loading

- Introduced a new `chunking-direct-test.py` file to demonstrate the usage of the `Chunking` class for text chunking with various strategies.
- Updated `knowledge-agents.py` to change the knowledge source from `2409.13731v3.pdf` to `large.pdf` and modified the agent's query for clarity.
- Revised `knowledge-direct-test.py` to replace the reference to `sample.pdf` with `small.pdf`, ensuring consistency in test file usage.
- Added `knowledge-large-pdf-test.py` to test the handling of large PDF files, integrating logging for better traceability.
- Updated `pyproject.toml` to include the new `chonkie` dependency for chunking functionalities.
- Removed the deprecated `sample.pdf` and added `small.pdf` to the agents directory for testing purposes.
- Enhanced the `Knowledge` class in `knowledge.py` to utilize the new `Chunking` class for improved memory management and content processing.

These changes enhance the knowledge management system's capabilities by integrating chunking strategies and improving file handling processes.
2025-01-16 07:56:32 +00:00
MervinPraison 7fb0aed7ac Refactor memory handling in knowledge-direct-test.py and knowledge.py
- Updated memory retrieval, updating, and deletion methods in `knowledge-direct-test.py` to correctly access memory IDs from the new results structure.
- Enhanced logging to provide clearer information about memory operations, including warnings for unexpected memory formats.
- Modified the `Knowledge` class in `knowledge.py` to ensure all memory results are returned in a consistent format, improving the handling of stored memories.
- Improved error handling and added checks for valid memory formats when verifying stored content from text and PDF files.

These changes enhance the robustness and clarity of memory management within the knowledge management system.
2025-01-16 06:24:15 +00:00
MervinPraison 206f0d01e7 Add new knowledge management features and files
- Introduced a new `knowledge-agents-task.py` script to define and execute tasks for knowledge agents, enhancing the framework's capabilities for knowledge retrieval and management.
- Added `knowledge-agents.py` to create a knowledge agent with specific instructions and knowledge sources, allowing for more tailored interactions.
- Implemented `knowledge-direct-test.py` for testing memory storage and retrieval functionalities, showcasing the new capabilities of the knowledge management system.
- Created `md.py` for handling Markdown file conversions, integrating with the knowledge management features.
- Updated `pyproject.toml` to specify the exact version of the `chromadb` dependency, ensuring compatibility with the new features.
- Added new PDF and DOCX files to the agents directory for testing and demonstration purposes.
- Enhanced the `Knowledge` class in `knowledge.py` to support user and agent identifiers, improving memory management and retrieval processes.

This commit significantly expands the knowledge management functionalities within the PraisonAI framework, providing new tools and scripts for better handling of knowledge content.
2025-01-16 05:36:08 +00:00
MervinPraison e19a310314 Update dependencies and enhance knowledge management system
- Updated the `chainlit` dependency version from `2.0.1` to `2.0.3` across multiple configurations in `pyproject.toml` and `agents/pyproject.toml` to ensure compatibility with the latest features and fixes.
- Introduced a new optional dependency group `knowledge` in `agents/pyproject.toml` for enhanced knowledge management capabilities, including `mem0ai` and `markitdown`.
- Refactored the `Knowledge` class in `knowledge.py` to improve initialization and memory management, allowing for better handling of user and agent identifiers.
- Enhanced methods for storing, retrieving, and managing memories, including new functionalities for updating and deleting memories.
- Updated UI components in `mint.json` and `realtime.py` to reflect changes in model naming conventions, improving user experience and clarity.

This commit strengthens the overall functionality and usability of the PraisonAI framework, particularly in knowledge management and UI interactions.
2025-01-15 17:00:15 +00:00
MervinPraison 1ea572689e Refactor Knowledge Management System in knowledge.py
- Overhauled the `Knowledge` class to enhance the knowledge management system, introducing a more flexible initialization with user and agent identifiers, and improved configuration options.
- Streamlined methods for adding, searching, and deleting knowledge, integrating a new memory management system for better performance and organization.
- Updated vector store and embedding configurations to support a wider range of providers and models, including options for graph capabilities.
- Enhanced error handling and debugging features for improved troubleshooting.
- Removed deprecated methods and optimized existing functionality for clarity and efficiency.

This commit significantly improves the structure and capabilities of the knowledge management system within the PraisonAI framework, facilitating better content handling and retrieval.
2025-01-15 06:52:26 +00:00
MervinPraison 96df649b05 Add Knowledge Management System in knowledge.py
- Introduced a new `Knowledge` class for managing knowledge content, including methods for adding, updating, searching, and deleting knowledge.
- Implemented support for various vector store types (Chroma, Pinecone, PGVector, Qdrant, Milvus) for storing embeddings.
- Added functionality for chunking text, generating embeddings using different models (OpenAI, Cohere, SentenceTransformers, HuggingFace), and optional encryption of content.
- Enhanced caching mechanism for search results to improve performance.
- Included comprehensive error handling and debug mode for better troubleshooting.

This commit establishes a robust framework for knowledge management within the PraisonAI agents, enhancing the system's capabilities for handling and retrieving information efficiently.
2025-01-15 06:18:33 +00:00
Mervin Praison 5aed75837a Merge pull request #300 from MervinPraison/develop
Refactor UI documentation and update navigation structure
2025-01-15 05:18:38 +00:00
MervinPraison 9c8f68a05f Refactor UI documentation and update navigation structure
- Renamed and reorganized the UI documentation in `ui.mdx`, changing the title and sidebar title for clarity.
- Updated the installation instructions to provide a more streamlined setup process.
- Removed the previous table of available interfaces and replaced it with a concise description of features.
- Adjusted the `mint.json` file to reflect the new UI documentation structure, enhancing navigation for users.

This commit improves the clarity and accessibility of the user interface documentation, making it easier for users to understand and utilize the PraisonAI framework.
2025-01-15 05:18:07 +00:00
Mervin Praison 9778a69c4d Merge pull request #299 from MervinPraison/develop
Remove deprecated use case documentation and update navigation structure
2025-01-14 17:12:40 +00:00
MervinPraison 73c7994380 Remove deprecated use case documentation and update navigation structure
- Deleted multiple use case files including "Examples," "Adaptive Learning," "Code Review," "Customer Service," "Emergency Response," "Fraud Detection," "Healthcare Diagnosis," "Multilingual Content," "Predictive Maintenance," "Smart City," and "Supply Chain" to streamline documentation.
- Updated `mint.json` to replace "Use Cases" with "Examples" in the navigation, enhancing clarity and organization.
- Adjusted navigation groups to reflect the new structure, ensuring users can easily find relevant information.

This commit focuses on cleaning up outdated documentation and improving the overall user experience by refining the navigation structure.
2025-01-14 17:12:26 +00:00
129 changed files with 14331 additions and 420 deletions

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
FROM python:3.11-slim
WORKDIR /app
COPY . .
RUN pip install flask praisonai==2.0.46 gunicorn markdown
RUN pip install flask praisonai==2.0.55 gunicorn markdown
EXPOSE 8080
CMD ["gunicorn", "-b", "0.0.0.0:8080", "api:app"]
+43
View File
@@ -0,0 +1,43 @@
FROM mcr.microsoft.com/devcontainers/python:3.11
# Prevent apt from showing prompts
ENV DEBIAN_FRONTEND=noninteractive
# Install system dependencies
RUN apt-get update && apt-get install -y \
git \
curl \
build-essential \
&& rm -rf /var/lib/apt/lists/*
# Create a non-root user
ARG USERNAME=vscode
ARG USER_UID=1000
ARG USER_GID=$USER_UID
# Create the user and group only if they don't exist
RUN if ! getent group $USER_GID > /dev/null 2>&1; then \
groupadd --gid $USER_GID $USERNAME; \
fi && \
if ! getent passwd $USER_UID > /dev/null 2>&1; then \
useradd --uid $USER_UID --gid $USER_GID -m $USERNAME; \
fi && \
apt-get update && \
apt-get install -y sudo && \
echo $USERNAME ALL=\(root\) NOPASSWD:ALL > /etc/sudoers.d/$USERNAME && \
chmod 0440 /etc/sudoers.d/$USERNAME
# Set Python environment variables
ENV PYTHONUNBUFFERED=1 \
PYTHONDONTWRITEBYTECODE=1
# Install Python dependencies
COPY requirements.txt /tmp/pip-tmp/
RUN pip3 --disable-pip-version-check --no-cache-dir install -r /tmp/pip-tmp/requirements.txt \
&& rm -rf /tmp/pip-tmp
# Switch to non-root user
USER $USERNAME
# Set the default shell to bash
ENV SHELL=/bin/bash
+36
View File
@@ -0,0 +1,36 @@
{
"name": "PraisonAI Development",
"dockerFile": "Dockerfile",
"context": "..",
"runArgs": [
"--env-file",
".env",
"--network=host"
],
"customizations": {
"vscode": {
"extensions": [
"ms-python.python",
"ms-python.vscode-pylance",
"ms-python.black-formatter",
"ms-toolsai.jupyter",
"yzhang.markdown-all-in-one",
"streetsidesoftware.code-spell-checker"
],
"settings": {
"python.defaultInterpreterPath": "/usr/local/bin/python",
"python.linting.enabled": true,
"python.formatting.provider": "black",
"editor.formatOnSave": true,
"editor.rulers": [88],
"files.trimTrailingWhitespace": true
}
}
},
"remoteUser": "vscode",
"updateRemoteUserUID": false,
"forwardPorts": [],
"appPort": ["56040:56040"],
"overrideCommand": false,
"init": true
}
+14
View File
@@ -0,0 +1,14 @@
from praisonaiagents.knowledge import Chunking
# No heavy imports or initialization happens here
chunking = Chunking(chunker_type='token')
# Chunker is only initialized when first used
chunks = chunking.chunk("Your text here")
# Embedding model is only loaded if using semantic chunking
semantic_chunking = Chunking(chunker_type='recursive')
# Embedding model and chunker are loaded here on first use
semantic_chunks = semantic_chunking.chunk("Your text here")
print(semantic_chunks)
+97
View File
@@ -0,0 +1,97 @@
from praisonaiagents import Agent, Task, PraisonAIAgents
from pydantic import BaseModel
from typing import List, Dict
from gitingest import ingest
class CodeMetrics(BaseModel):
category: str
score: int
findings: List[str]
class CodeAnalysisReport(BaseModel):
overall_quality: int
code_metrics: List[CodeMetrics]
architecture_score: int
maintainability_score: int
performance_score: int
security_score: int
test_coverage: int
key_strengths: List[str]
improvement_areas: List[str]
tech_stack: List[str]
recommendations: List[str]
complexity_metrics: Dict[str, int]
best_practices: List[Dict[str, str]]
potential_risks: List[str]
documentation_quality: int
code_analyzer = Agent(
role="Code Analysis Expert",
goal="Provide comprehensive code evaluation and recommendations",
backstory="""Expert code analyst specializing in architecture review,
best practices, and technical debt assessment.""",
verbose=True
)
code_analysis_task = Task(
description="""Analyze code repository and provide structured evaluation:
1. Overall Quality (0-100)
2. Core Metrics Analysis:
- Architecture and Design
- Code Maintainability
- Performance Optimization
- Security Practices
- Test Coverage
3. Technical Assessment:
- Technology Stack Review
- Code Complexity Analysis
- Best Practices Adherence
- Risk Assessment
4. Recommendations:
- Key Improvements
- Architecture Suggestions
- Security Enhancements""",
expected_output="Detailed code analysis report with metrics and recommendations",
agent=code_analyzer,
output_pydantic=CodeAnalysisReport
)
def analyze_code(code_source: str) -> CodeAnalysisReport:
"""
Analyze code from directory path or GitHub URL
"""
# Ingest code content
summary, tree, content = ingest(code_source)
# Concatenate context into structured format
context_text = f"""
CODE REPOSITORY ANALYSIS
=======================
SUMMARY
-------
{summary}
REPOSITORY STRUCTURE
-------------------
{tree}
SOURCE CODE
-----------
{content}
"""
# Initialize and run analysis
agents = PraisonAIAgents(
agents=[code_analyzer],
tasks=[code_analysis_task]
)
return agents.start(context_text)
if __name__ == "__main__":
# Example usage
code_source = "https://github.com/openai/openai-python/tree/main/src/openai/cli/_api/chat" # GitHub URL or local directory
result = analyze_code(code_source)
print(result)
+217
View File
@@ -0,0 +1,217 @@
import streamlit as st
from praisonaiagents import Agent, Task, PraisonAIAgents
from pydantic import BaseModel
from typing import List, Dict, Any
from gitingest import ingest
# Import the same classes and code from code-analysis-agents.py
class CodeMetrics(BaseModel):
category: str
score: int
findings: List[str]
class CodeAnalysisReport(BaseModel):
overall_quality: int
code_metrics: List[CodeMetrics]
architecture_score: int
maintainability_score: int
performance_score: int
security_score: int
test_coverage: int
key_strengths: List[str]
improvement_areas: List[str]
tech_stack: List[str]
recommendations: List[str]
complexity_metrics: Dict[str, int]
best_practices: List[Dict[str, str]]
potential_risks: List[str]
documentation_quality: int
def analyze_code(code_source: str) -> CodeAnalysisReport:
"""
Analyze code from directory path or GitHub URL
"""
# Create code analyzer agent
code_analyzer = Agent(
role="Code Analysis Expert",
goal="Provide comprehensive code evaluation and recommendations",
backstory="""Expert code analyst specializing in architecture review,
best practices, and technical debt assessment.""",
verbose=True
)
# Create analysis task
code_analysis_task = Task(
description="""Analyze code repository and provide structured evaluation:
1. Overall Quality (0-100)
2. Core Metrics Analysis:
- Architecture and Design
- Code Maintainability
- Performance Optimization
- Security Practices
- Test Coverage
3. Technical Assessment:
- Technology Stack Review
- Code Complexity Analysis
- Best Practices Adherence
- Risk Assessment
4. Recommendations:
- Key Improvements
- Architecture Suggestions
- Security Enhancements""",
expected_output="Detailed code analysis report with metrics and recommendations",
agent=code_analyzer,
output_pydantic=CodeAnalysisReport
)
# Ingest code content
summary, tree, content = ingest(code_source)
# Concatenate context into structured format
context_text = f"""
CODE REPOSITORY ANALYSIS
=======================
SUMMARY
-------
{summary}
REPOSITORY STRUCTURE
-------------------
{tree}
SOURCE CODE
-----------
{content}
"""
# Initialize and run analysis
agents = PraisonAIAgents(
agents=[code_analyzer],
tasks=[code_analysis_task]
)
result = agents.start(context_text)
# Extract the Pydantic model from the result
if isinstance(result, dict) and 'task_results' in result:
# Get the first task result's pydantic output
analysis_result = result['task_results'][0].pydantic
if isinstance(analysis_result, CodeAnalysisReport):
return analysis_result
# If we can't get the Pydantic model, create one from the raw data
return CodeAnalysisReport(**result)
def display_code_metrics(metrics, cols):
"""Display code metrics in columns with color-coded scores"""
for i, metric in enumerate(metrics):
score = metric.score
color = "red" if score < 60 else "orange" if score < 75 else "green"
# Use modulo to alternate between columns
with cols[i % len(cols)]:
st.markdown(f"### {metric.category}")
st.markdown(f"**Score:** :{color}[{score}%]")
for finding in metric.findings:
st.markdown(f"• {finding}")
def display_section(title: str, items: list, icon: str = "•"):
"""Display a section with items in a consistent format"""
st.markdown(f"### {title}")
for item in items:
if isinstance(item, dict):
for key, value in item.items():
st.markdown(f"{icon} **{key}**: {value}")
else:
st.markdown(f"{icon} {item}")
def main():
st.set_page_config(
page_title="Code Analysis Agent",
layout="wide",
initial_sidebar_state="expanded"
)
st.title("Code Analysis Agent")
with st.sidebar:
st.header("Input")
code_source = st.text_input(
"GitHub URL or Local Path",
placeholder="https://github.com/username/repo or /path/to/directory"
)
analyze_button = st.button("Analyze Code", type="primary")
if analyze_button and code_source:
try:
with st.spinner("Analyzing code..."):
result = analyze_code(code_source)
# Overall Metrics
st.header("Overall Metrics")
cols = st.columns(6)
metrics = {
"Overall Quality": result.overall_quality,
"Architecture": result.architecture_score,
"Maintainability": result.maintainability_score,
"Performance": result.performance_score,
"Security": result.security_score,
"Test Coverage": result.test_coverage
}
for (metric, value), col in zip(metrics.items(), cols):
color = "red" if value < 60 else "orange" if value < 75 else "green"
col.metric(metric, f"{value}%")
col.markdown(f":{color}[{'●' * (value // 20)}]")
# Detailed Analysis
st.header("Detailed Analysis")
metric_cols = st.columns(2)
display_code_metrics(result.code_metrics, metric_cols)
# Technology Stack
col1, col2 = st.columns(2)
with col1:
st.header("Technology Stack")
for tech in result.tech_stack:
st.markdown(f"🔧 {tech}")
with col2:
st.header("Complexity Metrics")
for metric, value in result.complexity_metrics.items():
st.metric(metric.replace('_', ' ').title(), value)
# Key Findings
st.header("Key Findings")
cols = st.columns(2)
with cols[0]:
display_section("✅ Strengths", result.key_strengths)
display_section("🔄 Best Practices", result.best_practices)
with cols[1]:
display_section("⚠️ Areas for Improvement", result.improvement_areas)
display_section("❗ Potential Risks", result.potential_risks)
# Recommendations
st.header("Recommendations")
for i, rec in enumerate(result.recommendations, 1):
st.markdown(f"**{i}.** {rec}")
# Documentation Quality
st.header("Documentation")
doc_score = result.documentation_quality
color = "red" if doc_score < 60 else "orange" if doc_score < 75 else "green"
st.markdown(f"Documentation Quality: :{color}[{doc_score}%]")
except Exception as e:
st.error(f"Error analyzing code: {str(e)}")
st.exception(e)
elif analyze_button:
st.warning("Please enter a GitHub URL or local path")
if __name__ == "__main__":
main()
+98
View File
@@ -0,0 +1,98 @@
from praisonaiagents import Agent, Task, PraisonAIAgents
from pydantic import BaseModel
from typing import List, Dict
class SkillMetrics(BaseModel):
name: str
score: int
comments: str
class CVAnalysisReport(BaseModel):
overall_score: int
skill_metrics: List[SkillMetrics]
experience_score: int
education_score: int
presentation_score: int
achievement_impact_score: int
market_readiness: int
key_strengths: List[str]
areas_for_improvement: List[str]
market_fit: str
recommendations: List[str]
technical_skills: List[Dict[str, int]]
soft_skills: List[Dict[str, int]]
skill_gaps: List[str]
key_achievements: List[str]
impact_metrics: List[Dict[str, str]]
areas_of_expertise: List[str]
# Create single CV analysis agent
cv_analyzer = Agent(
role="CV Analysis Expert",
goal="Provide comprehensive CV evaluation and recommendations",
backstory="""You are an expert CV analyst with deep knowledge of industry requirements,
market trends, and talent assessment. You excel at evaluating skills, experience,
and providing actionable recommendations.""",
verbose=True
)
# Single comprehensive analysis task
cv_analysis_task = Task(
description="""Perform a detailed CV analysis with scoring metrics and provide output in the following format:
1. Overall Score (0-100):
- Calculate based on weighted average of all metrics
2. Individual Skill Metrics:
- For each major skill found in CV:
* Name of skill
* Score (0-100)
* Specific feedback/comments
3. Core Metrics (0-100 each):
- Experience Score: Based on relevance and years
- Education Score: Based on relevance and level
- Presentation Score: CV format, clarity, structure
- Achievement Impact Score: Measurable results
- Market Readiness: Current market fit
4. Technical Skills:
- List each skill with proficiency score (0-100)
- Example: {"Python": 85, "AWS": 70}
5. Soft Skills:
- List each skill with proficiency score (0-100)
- Example: {"Communication": 90, "Leadership": 75}
6. Detailed Analysis:
- Key Strengths: Top 3-5 standout points
- Areas for Improvement: 3-5 specific points
- Market Fit: Current industry alignment
- Skill Gaps: Missing critical skills for target role
- Key Achievements: Quantifiable accomplishments
- Impact Metrics: {"metric": "value"}
- Areas of Expertise: Primary domains of expertise
7. Recommendations:
- 3-5 actionable steps for improvement
Provide clear justification for all scores and ensure feedback is specific and actionable.""",
expected_output="Structured CV analysis report with detailed metrics and scoring justification",
agent=cv_analyzer,
output_pydantic=CVAnalysisReport
)
# Create and run the agent
agents = PraisonAIAgents(
agents=[cv_analyzer],
tasks=[cv_analysis_task]
)
# Read and pass CV content through start()
with open('cv.txt', 'r') as file:
cv_content = file.read()
# Start the analysis by passing CV content
result = agents.start(cv_content)
print(result)
+202
View File
@@ -0,0 +1,202 @@
import streamlit as st
from praisonaiagents import Agent, Task, PraisonAIAgents
from pydantic import BaseModel
from typing import List, Dict
import json
import asyncio
import nest_asyncio
from functools import partial
# Enable nested event loops
nest_asyncio.apply()
class SkillMetrics(BaseModel):
name: str
score: int
comments: str
class CVAnalysisReport(BaseModel):
overall_score: int
skill_metrics: List[SkillMetrics]
experience_score: int
education_score: int
presentation_score: int
achievement_impact_score: int
market_readiness: int
key_strengths: List[str]
areas_for_improvement: List[str]
market_fit: str
recommendations: List[str]
technical_skills: List[Dict[str, int]]
soft_skills: List[Dict[str, int]]
skill_gaps: List[str]
key_achievements: List[str]
impact_metrics: List[Dict[str, str]]
areas_of_expertise: List[str]
async def analyze_cv_async(cv_content):
cv_analyzer = Agent(
role="CV Analysis Expert",
goal="Provide comprehensive CV evaluation and recommendations",
backstory="""You are an expert CV analyst with deep knowledge of industry requirements,
market trends, and talent assessment. You excel at evaluating skills, experience,
and providing actionable recommendations.""",
verbose=True
)
cv_analysis_task = Task(
description="""Perform a detailed CV analysis with scoring metrics and provide output in the following format:
1. Overall Score (0-100):
- Calculate based on weighted average of all metrics
2. Individual Skill Metrics:
- For each major skill found in CV:
* Name of skill
* Score (0-100)
* Specific feedback/comments
3. Core Metrics (0-100 each):
- Experience Score: Based on relevance and years
- Education Score: Based on relevance and level
- Presentation Score: CV format, clarity, structure
- Achievement Impact Score: Measurable results
- Market Readiness: Current market fit
4. Technical Skills:
- List each skill with proficiency score (0-100)
5. Soft Skills:
- List each skill with proficiency score (0-100)
6. Detailed Analysis sections
7. Recommendations:
- 3-5 actionable steps for improvement""",
expected_output="Structured CV analysis report with detailed metrics and scoring justification",
agent=cv_analyzer,
output_pydantic=CVAnalysisReport
)
agents = PraisonAIAgents(
agents=[cv_analyzer],
tasks=[cv_analysis_task]
)
try:
result = await agents.astart(cv_content)
return result['task_results'][0].pydantic
except Exception as e:
print(f"Error during analysis: {str(e)}")
raise e
def analyze_cv(cv_content):
async def run_analysis():
return await analyze_cv_async(cv_content)
try:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
result = loop.run_until_complete(run_analysis())
return result
except Exception as e:
raise e
finally:
loop.close()
def main():
st.set_page_config(page_title="CV Analyzer", layout="wide")
st.title("Professional CV Analyzer")
# File upload
cv_file = st.file_uploader("Upload your CV (TXT format)", type=['txt'])
if cv_file:
cv_content = cv_file.read().decode()
with st.spinner('Analyzing your CV...'):
try:
analysis = analyze_cv(cv_content)
# Display Overall Score
col1, col2, col3 = st.columns(3)
with col1:
st.metric("Overall Score", f"{analysis.overall_score}/100")
with col2:
st.metric("Market Readiness", f"{analysis.market_readiness}/100")
with col3:
st.metric("Experience Score", f"{analysis.experience_score}/100")
# Core Metrics
st.subheader("Core Metrics")
metrics_cols = st.columns(4)
with metrics_cols[0]:
st.metric("Education", f"{analysis.education_score}/100")
with metrics_cols[1]:
st.metric("Presentation", f"{analysis.presentation_score}/100")
with metrics_cols[2]:
st.metric("Achievement Impact", f"{analysis.achievement_impact_score}/100")
with metrics_cols[3]:
st.metric("Market Readiness", f"{analysis.market_readiness}/100")
# Skill Metrics
st.subheader("Detailed Skill Analysis")
for skill in analysis.skill_metrics:
with st.expander(f"{skill.name} - Score: {skill.score}/100"):
st.write(skill.comments)
# Technical and Soft Skills
col1, col2 = st.columns(2)
with col1:
st.subheader("Technical Skills")
for skill in analysis.technical_skills:
for skill_name, score in skill.items():
st.progress(score/100)
st.caption(f"{skill_name}: {score}/100")
with col2:
st.subheader("Soft Skills")
for skill in analysis.soft_skills:
for skill_name, score in skill.items():
st.progress(score/100)
st.caption(f"{skill_name}: {score}/100")
# Key Information
st.subheader("Key Analysis")
col1, col2 = st.columns(2)
with col1:
st.write("🎯 Key Strengths")
for strength in analysis.key_strengths:
st.write(f"• {strength}")
st.write("🎮 Areas of Expertise")
for expertise in analysis.areas_of_expertise:
st.write(f"• {expertise}")
with col2:
st.write("🔄 Areas for Improvement")
for area in analysis.areas_for_improvement:
st.write(f"• {area}")
st.write("⚠️ Skill Gaps")
for gap in analysis.skill_gaps:
st.write(f"• {gap}")
# Impact Metrics
st.subheader("Impact Metrics")
for metric in analysis.impact_metrics:
for key, value in metric.items():
st.metric(key, value)
# Recommendations
st.subheader("📋 Recommendations")
for rec in analysis.recommendations:
st.write(f"• {rec}")
except Exception as e:
st.error(f"An error occurred during analysis: {str(e)}")
else:
st.info("Please upload your CV in TXT format to begin the analysis")
if __name__ == "__main__":
main()
+61
View File
@@ -0,0 +1,61 @@
from praisonaiagents import Agent, Task, PraisonAIAgents
from pydantic import BaseModel
from typing import List, Dict
class CVAnalysisReport(BaseModel):
overall_score: int
key_strengths: List[str]
areas_for_improvement: List[str]
market_fit: str
recommendations: List[str]
technical_skills: List[str]
soft_skills: List[str]
skill_gaps: List[str]
key_achievements: List[str]
impact_metrics: List[Dict[str, str]]
areas_of_expertise: List[str]
# Create single CV analysis agent
cv_analyzer = Agent(
role="CV Analysis Expert",
goal="Provide comprehensive CV evaluation and recommendations",
backstory="""You are an expert CV analyst with deep knowledge of industry requirements,
market trends, and talent assessment. You excel at evaluating skills, experience,
and providing actionable recommendations.""",
verbose=True
)
# Read CV content first
with open('cv.txt', 'r') as file:
cv_content = file.read()
cv_key_strengths = Task(
description="List the key strengths to look",
expected_output="List of key strengths",
agent=cv_analyzer,
)
# Single comprehensive analysis task with CV content in context
cv_analysis_task = Task(
description="""Analyze the CV comprehensively including:
1. Technical and soft skills assessment
2. Experience and achievements evaluation
3. Overall CV evaluation with recommendations
Provide detailed insights and actionable recommendations.""",
expected_output="Complete CV analysis report",
agent=cv_analyzer,
output_pydantic=CVAnalysisReport,
context=[cv_content, cv_key_strengths] # Pass CV content directly in task context
)
# Create and run the agent
agents = PraisonAIAgents(
agents=[cv_analyzer],
tasks=[cv_key_strengths,cv_analysis_task],
process="sequential"
)
# Start the analysis - no need to pass content again since it's in task context
result = agents.start()
print(result)
+27
View File
@@ -0,0 +1,27 @@
# example tools.py
from duckduckgo_search import DDGS
from praisonai_tools import BaseTool
class InternetSearchTool(BaseTool):
name: str = "InternetSearchTool"
description: str = "Search Internet for relevant information based on a query or latest news"
def _run(self, query: str):
ddgs = DDGS()
results = ddgs.text(keywords=query, region='wt-wt', safesearch='moderate', max_results=5)
return results
# Example agent
from praisonaiagents import Agent
from praisonaiagents import PraisonAIAgents
agent = Agent(
name="Internet Search Agent",
tools=[InternetSearchTool],
instructions="""
You are an agent that can search the internet for relevant information based on a query or latest news.
"""
)
# Run the agent
result = PraisonAIAgents(agents=[agent], verbose=10).start()
print(result)
+57
View File
@@ -0,0 +1,57 @@
Name: Alex Johnson
Location: London, UK
Professional Summary
Dynamic and results-oriented leader with a proven track record of driving innovation, scaling operations, and achieving transformational growth. Over 15 years of experience in engineering, strategic management, and executive leadership in the automotive and renewable energy sectors. Passionate about sustainable technologies and visionary leadership.
Professional Experience
Chief Operating Officer (COO)
NextGen Mobility Ltd. | Palo Alto, CA | 2020 – Present
Spearheaded global operations for an electric vehicle company, scaling production by 200% in three years.
Introduced automation-driven supply chain strategies, reducing costs by 15%.
Collaborated with R&D to launch three new EV models, driving 25% revenue growth annually.
Vice President of Engineering
ElectroDrive Systems | San Francisco, CA | 2015 – 2020
Led a team of 500+ engineers in developing next-generation EV batteries, achieving a 30% increase in energy efficiency.
Secured $50M in government funding for sustainable energy innovation.
Drove cross-functional collaboration, aligning product development with market needs.
Director of Renewable Energy Initiatives
GreenTech Innovations | London, UK | 2011 – 2015
Oversaw £100M projects in solar and wind energy deployment across Europe.
Established partnerships with policymakers to influence renewable energy legislation.
Pioneered a smart energy grid system, enhancing energy distribution efficiency by 40%.
Senior Project Manager
Innovate Auto Ltd. | Munich, Germany | 2008 – 2011
Managed R&D projects for autonomous driving technologies.
Delivered projects 20% under budget through strategic resource allocation.
Filed 10+ patents in automotive AI and renewable integration.
Mechanical Engineer
AutoFusion Technologies | Berlin, Germany | 2005 – 2008
Designed core systems for EV powertrains, optimising energy consumption by 15%.
Collaborated with suppliers to improve material efficiency, cutting costs by £5M annually.
Education
MBA in Strategic Management
Harvard Business School | Cambridge, MA | 2015
MSc in Renewable Energy Engineering
Imperial College London | London, UK | 2007
BSc in Mechanical Engineering
Technical University of Munich | Munich, Germany | 2005
Skills
Strategic Leadership & Visionary Thinking
Electric Vehicle Engineering
Renewable Energy Systems
Global Operations Management
Policy Advocacy & Government Relations
Supply Chain Optimisation
Achievements
Featured in Forbes 30 Under 40 for innovations in EV technology.
Author of The Future of Sustainable Mobility.
Keynote speaker at World Energy Summit, 2023.
+39
View File
@@ -0,0 +1,39 @@
from praisonaiagents import Agent, Task, PraisonAIAgents
# Define the configuration for the Knowledge instance
config = {
"vector_store": {
"provider": "chroma",
"config": {
"collection_name": "praison",
"path": ".praison"
}
}
}
# Create an agent
rag_agent = Agent(
name="RAG Agent",
role="Information Specialist",
goal="Retrieve knowledge efficiently",
llm="deepseek-r1"
)
# Define a task for the agent
rag_task = Task(
name="RAG Task",
description="What is KAG?",
expected_output="Answer to the question",
agent=rag_agent,
context=[config] # Vector Database provided as context
)
# Build Agents
agents = PraisonAIAgents(
agents=[rag_agent],
tasks=[rag_task],
user_id="user1"
)
# Start Agents
agents.start()
+3
View File
@@ -0,0 +1,3 @@
I am Mervin Praison, a software engineer and entrepreneur.
I am the founder of Praison AI, a company that is building AI agents to help people with their daily tasks.
+34
View File
@@ -0,0 +1,34 @@
import gradio as gr
from praisonaiagents import Agent, Tools
from praisonaiagents.tools import duckduckgo
def research(query):
agent = Agent(instructions="You are a Research Agent", tools=[duckduckgo])
result = agent.start(query)
# Format the result with enhanced markdown
formatted_result = f"""
{result}
----
*Generated by PraisonAI Research Assistant*
"""
return formatted_result
# Create a simple Gradio interface
demo = gr.Interface(
fn=research,
inputs=gr.Textbox(
label="Research Query",
placeholder="Enter your research topic...",
lines=2
),
outputs=gr.Markdown(
show_copy_button=True,
height=500,
container=True
),
title="AI Research Assistant",
description="Enter your research query below to get started!",
)
if __name__ == "__main__":
demo.launch()
View File
Whitespace-only changes.
+159
View File
@@ -0,0 +1,159 @@
from praisonaiagents import Agent, Task, PraisonAIAgents
from pydantic import BaseModel
from typing import List, Dict
import os
import json
class ProjectEvaluation(BaseModel):
innovation_score: int # 0-100
technical_complexity: int # 0-100
presentation_quality: int # 0-100
user_experience: int # 0-100
completeness: int # 0-100
overall_score: int # 0-100
key_strengths: List[str]
areas_for_improvement: List[str]
notable_features: List[str]
technical_highlights: List[str]
recommendations: List[str]
market_potential: str
scalability_assessment: str
# Create Vision Analysis Agent
hackathon_judge = Agent(
name="HackathonJudge",
role="Technical Project Evaluator",
goal="Evaluate hackathon projects through video demonstrations",
backstory="""You are an experienced hackathon judge and technical expert.
You excel at evaluating innovation, technical implementation, and presentation quality.
You provide constructive feedback and identify both strengths and areas for improvement.""",
llm="gpt-4o-mini", # Using vision-capable model
self_reflect=False,
knowledge=""
)
def evaluate_project(video_path: str) -> ProjectEvaluation:
"""
Evaluate a hackathon project based on its video demonstration
"""
evaluation_task = Task(
name="project_evaluation",
description="""Analyze this hackathon project video demonstration and provide a comprehensive evaluation:
1. Score the following aspects (0-100):
- Innovation and Creativity
- Technical Complexity
- Presentation Quality
- User Experience
- Project Completeness
2. Identify:
- Key strengths and standout features
- Areas that could be improved
- Notable technical implementations
- Market potential and scalability
3. Provide:
- Specific recommendations for improvement
- Technical suggestions
- Potential future enhancements""",
expected_output="Detailed project evaluation with scores and feedback",
agent=hackathon_judge,
output_pydantic=ProjectEvaluation,
images=[video_path] # Video input for multimodal analysis
)
# Initialize and run evaluation
agents = PraisonAIAgents(
agents=[hackathon_judge],
tasks=[evaluation_task],
process="sequential",
verbose=True
)
response = agents.start()
try:
# If response contains task_results, extract the Pydantic model directly
if isinstance(response, dict) and 'task_results' in response:
task_output = response['task_results'][0]
if hasattr(task_output, 'pydantic'):
return task_output.pydantic
elif hasattr(task_output, 'raw'):
# Extract JSON from raw string if it's wrapped in ```json
raw_text = task_output.raw
if raw_text.startswith('```json'):
raw_text = raw_text.split('\n', 1)[1].rsplit('\n', 1)[0]
evaluation_data = json.loads(raw_text)
else:
evaluation_data = json.loads(task_output) if isinstance(task_output, str) else task_output
# If response is a string, try to parse it as JSON
elif isinstance(response, str):
evaluation_data = json.loads(response)
# If response is a dict with task_status
elif isinstance(response, dict) and 'task_status' in response:
content = response['task_status']
if isinstance(content, dict):
evaluation_data = content
else:
evaluation_data = json.loads(content) if isinstance(content, str) else content
else:
evaluation_data = response
print(f"Debug - Parsed evaluation_data: {evaluation_data}")
# Create and return ProjectEvaluation instance
return ProjectEvaluation(
innovation_score=int(evaluation_data.get('innovation_score', 0)),
technical_complexity=int(evaluation_data.get('technical_complexity', 0)),
presentation_quality=int(evaluation_data.get('presentation_quality', 0)),
user_experience=int(evaluation_data.get('user_experience', 0)),
completeness=int(evaluation_data.get('completeness', 0)),
overall_score=int(evaluation_data.get('overall_score', 0)),
key_strengths=evaluation_data.get('key_strengths', []),
areas_for_improvement=evaluation_data.get('areas_for_improvement', []),
notable_features=evaluation_data.get('notable_features', []),
technical_highlights=evaluation_data.get('technical_highlights', []),
recommendations=evaluation_data.get('recommendations', []),
market_potential=str(evaluation_data.get('market_potential', '')),
scalability_assessment=str(evaluation_data.get('scalability_assessment', ''))
)
except Exception as e:
print(f"Debug - Raw response: {response}")
print(f"Error processing response: {e}")
raise
if __name__ == "__main__":
# Example usage
current_dir = os.path.dirname(os.path.abspath(__file__))
video_path = os.path.join(current_dir, "presentation.mp4")
result = evaluate_project(video_path) # Now returns ProjectEvaluation directly
print("\nHackathon Project Evaluation")
print("===========================")
print(f"\nOverall Score: {result.overall_score}/100")
print("\nDetailed Scores:")
print(f"Innovation: {result.innovation_score}/100")
print(f"Technical Complexity: {result.technical_complexity}/100")
print(f"Presentation: {result.presentation_quality}/100")
print(f"User Experience: {result.user_experience}/100")
print(f"Completeness: {result.completeness}/100")
print("\nKey Strengths:")
for strength in result.key_strengths:
print(f"- {strength}")
print("\nAreas for Improvement:")
for area in result.areas_for_improvement:
print(f"- {area}")
print("\nTechnical Highlights:")
for highlight in result.technical_highlights:
print(f"- {highlight}")
print("\nRecommendations:")
for rec in result.recommendations:
print(f"- {rec}")
print(f"\nMarket Potential: {result.market_potential}")
print(f"\nScalability Assessment: {result.scalability_assessment}")
+159
View File
@@ -0,0 +1,159 @@
from praisonaiagents import Agent, Task, PraisonAIAgents
from pydantic import BaseModel
from typing import List, Dict
import os
import json
class ProjectEvaluation(BaseModel):
innovation_score: int # 0-100
technical_complexity: int # 0-100
presentation_quality: int # 0-100
user_experience: int # 0-100
completeness: int # 0-100
overall_score: int # 0-100
key_strengths: List[str]
areas_for_improvement: List[str]
notable_features: List[str]
technical_highlights: List[str]
recommendations: List[str]
market_potential: str
scalability_assessment: str
# Create Vision Analysis Agent
hackathon_judge = Agent(
name="HackathonJudge",
role="Technical Project Evaluator",
goal="Evaluate hackathon projects through video demonstrations",
backstory="""You are an experienced hackathon judge and technical expert.
You excel at evaluating innovation, technical implementation, and presentation quality.
You provide constructive feedback and identify both strengths and areas for improvement.""",
llm="gpt-4o-mini", # Using vision-capable model
self_reflect=False,
knowledge=""
)
def evaluate_project(video_path: str) -> ProjectEvaluation:
"""
Evaluate a hackathon project based on its video demonstration
"""
evaluation_task = Task(
name="project_evaluation",
description="""Analyze this hackathon project video demonstration and provide a comprehensive evaluation:
1. Score the following aspects (0-100):
- Innovation and Creativity
- Technical Complexity
- Presentation Quality
- User Experience
- Project Completeness
2. Identify:
- Key strengths and standout features
- Areas that could be improved
- Notable technical implementations
- Market potential and scalability
3. Provide:
- Specific recommendations for improvement
- Technical suggestions
- Potential future enhancements""",
expected_output="Detailed project evaluation with scores and feedback",
agent=hackathon_judge,
output_pydantic=ProjectEvaluation,
images=[video_path] # Video input for multimodal analysis
)
# Initialize and run evaluation
agents = PraisonAIAgents(
agents=[hackathon_judge],
tasks=[evaluation_task],
process="sequential",
verbose=True
)
response = agents.start()
try:
# If response contains task_results, extract the Pydantic model directly
if isinstance(response, dict) and 'task_results' in response:
task_output = response['task_results'][0]
if hasattr(task_output, 'pydantic'):
return task_output.pydantic
elif hasattr(task_output, 'raw'):
# Extract JSON from raw string if it's wrapped in ```json
raw_text = task_output.raw
if raw_text.startswith('```json'):
raw_text = raw_text.split('\n', 1)[1].rsplit('\n', 1)[0]
evaluation_data = json.loads(raw_text)
else:
evaluation_data = json.loads(task_output) if isinstance(task_output, str) else task_output
# If response is a string, try to parse it as JSON
elif isinstance(response, str):
evaluation_data = json.loads(response)
# If response is a dict with task_status
elif isinstance(response, dict) and 'task_status' in response:
content = response['task_status']
if isinstance(content, dict):
evaluation_data = content
else:
evaluation_data = json.loads(content) if isinstance(content, str) else content
else:
evaluation_data = response
print(f"Debug - Parsed evaluation_data: {evaluation_data}")
# Create and return ProjectEvaluation instance
return ProjectEvaluation(
innovation_score=int(evaluation_data.get('innovation_score', 0)),
technical_complexity=int(evaluation_data.get('technical_complexity', 0)),
presentation_quality=int(evaluation_data.get('presentation_quality', 0)),
user_experience=int(evaluation_data.get('user_experience', 0)),
completeness=int(evaluation_data.get('completeness', 0)),
overall_score=int(evaluation_data.get('overall_score', 0)),
key_strengths=evaluation_data.get('key_strengths', []),
areas_for_improvement=evaluation_data.get('areas_for_improvement', []),
notable_features=evaluation_data.get('notable_features', []),
technical_highlights=evaluation_data.get('technical_highlights', []),
recommendations=evaluation_data.get('recommendations', []),
market_potential=str(evaluation_data.get('market_potential', '')),
scalability_assessment=str(evaluation_data.get('scalability_assessment', ''))
)
except Exception as e:
print(f"Debug - Raw response: {response}")
print(f"Error processing response: {e}")
raise
if __name__ == "__main__":
# Example usage
current_dir = os.path.dirname(os.path.abspath(__file__))
video_path = os.path.join(current_dir, "presentation.mp4")
result = evaluate_project(video_path) # Now returns ProjectEvaluation directly
print("\nHackathon Project Evaluation")
print("===========================")
print(f"\nOverall Score: {result.overall_score}/100")
print("\nDetailed Scores:")
print(f"Innovation: {result.innovation_score}/100")
print(f"Technical Complexity: {result.technical_complexity}/100")
print(f"Presentation: {result.presentation_quality}/100")
print(f"User Experience: {result.user_experience}/100")
print(f"Completeness: {result.completeness}/100")
print("\nKey Strengths:")
for strength in result.key_strengths:
print(f"- {strength}")
print("\nAreas for Improvement:")
for area in result.areas_for_improvement:
print(f"- {area}")
print("\nTechnical Highlights:")
for highlight in result.technical_highlights:
print(f"- {highlight}")
print("\nRecommendations:")
for rec in result.recommendations:
print(f"- {rec}")
print(f"\nMarket Potential: {result.market_potential}")
print(f"\nScalability Assessment: {result.scalability_assessment}")
+210
View File
@@ -0,0 +1,210 @@
import streamlit as st
import os
from praisonaiagents import Agent, Task, PraisonAIAgents
from pydantic import BaseModel
from typing import List, Dict
import tempfile
import json
class ProjectEvaluation(BaseModel):
innovation_score: int # 0-100
technical_complexity: int # 0-100
presentation_quality: int # 0-100
user_experience: int # 0-100
completeness: int # 0-100
overall_score: int # 0-100
key_strengths: List[str]
areas_for_improvement: List[str]
notable_features: List[str]
technical_highlights: List[str]
recommendations: List[str]
market_potential: str
scalability_assessment: str
# Set page config
st.set_page_config(
page_title="Hackathon Project Evaluator",
page_icon="🏆",
layout="wide"
)
# Create Vision Analysis Agent
@st.cache_resource
def get_hackathon_judge():
return Agent(
name="HackathonJudge",
role="Technical Project Evaluator",
goal="Evaluate hackathon projects through video demonstrations",
backstory="""You are an experienced hackathon judge and technical expert.
You excel at evaluating innovation, technical implementation, and presentation quality.
You provide constructive feedback and identify both strengths and areas for improvement.""",
llm="gpt-4o-mini", # Using vision-capable model
self_reflect=False,
knowledge=""
)
def evaluate_project(video_path: str) -> ProjectEvaluation:
"""
Evaluate a hackathon project based on its video demonstration
"""
hackathon_judge = get_hackathon_judge()
evaluation_task = Task(
name="project_evaluation",
description="""Analyze this hackathon project video demonstration and provide a comprehensive evaluation:
1. Score the following aspects (0-100):
- Innovation and Creativity
- Technical Complexity
- Presentation Quality
- User Experience
- Project Completeness
2. Identify:
- Key strengths and standout features
- Areas that could be improved
- Notable technical implementations
- Market potential and scalability
3. Provide:
- Specific recommendations for improvement
- Technical suggestions
- Potential future enhancements""",
expected_output="Detailed project evaluation with scores and feedback",
agent=hackathon_judge,
output_pydantic=ProjectEvaluation,
images=[video_path] # Video input for multimodal analysis
)
# Initialize and run evaluation
agents = PraisonAIAgents(
agents=[hackathon_judge],
tasks=[evaluation_task],
process="sequential",
verbose=True
)
response = agents.start()
try:
# If response contains task_results, extract the Pydantic model directly
if isinstance(response, dict) and 'task_results' in response:
task_output = response['task_results'][0]
if hasattr(task_output, 'pydantic'):
return task_output.pydantic
elif hasattr(task_output, 'raw'):
# Extract JSON from raw string if it's wrapped in ```json
raw_text = task_output.raw
if raw_text.startswith('```json'):
raw_text = raw_text.split('\n', 1)[1].rsplit('\n', 1)[0]
evaluation_data = json.loads(raw_text)
else:
evaluation_data = json.loads(task_output) if isinstance(task_output, str) else task_output
elif isinstance(response, str):
evaluation_data = json.loads(response)
elif isinstance(response, dict) and 'task_status' in response:
content = response['task_status']
if isinstance(content, dict):
evaluation_data = content
else:
evaluation_data = json.loads(content) if isinstance(content, str) else content
else:
evaluation_data = response
# Create and return ProjectEvaluation instance
return ProjectEvaluation(
innovation_score=int(evaluation_data.get('innovation_score', 0)),
technical_complexity=int(evaluation_data.get('technical_complexity', 0)),
presentation_quality=int(evaluation_data.get('presentation_quality', 0)),
user_experience=int(evaluation_data.get('user_experience', 0)),
completeness=int(evaluation_data.get('completeness', 0)),
overall_score=int(evaluation_data.get('overall_score', 0)),
key_strengths=evaluation_data.get('key_strengths', []),
areas_for_improvement=evaluation_data.get('areas_for_improvement', []),
notable_features=evaluation_data.get('notable_features', []),
technical_highlights=evaluation_data.get('technical_highlights', []),
recommendations=evaluation_data.get('recommendations', []),
market_potential=str(evaluation_data.get('market_potential', '')),
scalability_assessment=str(evaluation_data.get('scalability_assessment', ''))
)
except Exception as e:
print(f"Debug - Raw response: {response}")
print(f"Error processing response: {e}")
raise
# Title and description
st.title("🏆 Hackathon Judge Agent")
st.markdown("""
Upload your hackathon project demonstration video for an AI-powered evaluation.
Get comprehensive feedback on various aspects of your project.
""")
# File uploader
uploaded_file = st.file_uploader("Choose a video file", type=['mp4', 'avi', 'mov', 'mkv'])
if uploaded_file:
# Create a temporary file to store the video
with tempfile.NamedTemporaryFile(delete=False, suffix='.'+uploaded_file.name.split('.')[-1]) as tmp_file:
tmp_file.write(uploaded_file.getvalue())
video_path = tmp_file.name
with st.spinner("🤖 AI is evaluating your project..."):
try:
# Evaluate the project
result = evaluate_project(video_path)
# Display results
st.header("Overall Score")
st.metric("Overall Score", f"{result.overall_score}/100")
# Display detailed scores
st.header("Detailed Scores")
col1, col2, col3 = st.columns(3)
with col1:
st.metric("Innovation", f"{result.innovation_score}/100")
st.metric("Technical Complexity", f"{result.technical_complexity}/100")
with col2:
st.metric("Presentation", f"{result.presentation_quality}/100")
st.metric("User Experience", f"{result.user_experience}/100")
with col3:
st.metric("Completeness", f"{result.completeness}/100")
# Display qualitative feedback
st.header("Key Strengths")
for strength in result.key_strengths:
st.write(f"• {strength}")
st.header("Areas for Improvement")
for area in result.areas_for_improvement:
st.write(f"• {area}")
st.header("Technical Highlights")
for highlight in result.technical_highlights:
st.write(f"• {highlight}")
st.header("Notable Features")
for feature in result.notable_features:
st.write(f"• {feature}")
st.header("Recommendations")
for rec in result.recommendations:
st.write(f"• {rec}")
# Market Analysis
st.header("Market Analysis")
col1, col2 = st.columns(2)
with col1:
st.subheader("Market Potential")
st.write(result.market_potential)
with col2:
st.subheader("Scalability Assessment")
st.write(result.scalability_assessment)
except Exception as e:
st.error(f"Error evaluating the project: {str(e)}")
finally:
# Clean up the temporary file
os.unlink(video_path)
else:
# Display placeholder content
st.info("👆 Upload a video file to get started!")
+70
View File
@@ -0,0 +1,70 @@
from praisonaiagents import Agent, Task, PraisonAIAgents
import logging
import os
import json
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
# Define the configuration for the Knowledge instance
config = {
"version": "v1.1",
"vector_store": {
"provider": "chroma",
"config": {
"collection_name": "praison",
"path": os.path.abspath("./.praison"),
"host": None,
"port": None
}
},
"embedder": {
"provider": "openai",
"config": {
"model": "text-embedding-3-small",
"embedding_dims": 1536
}
},
"llm": {
"provider": "openai",
"config": {
"model": "gpt-4o-mini",
"temperature": 0,
"max_tokens": 1000
}
}
}
# Create an agent with knowledge capabilities
knowledge_agent = Agent(
name="KnowledgeAgent",
role="Information Specialist",
goal="Store and retrieve knowledge efficiently",
backstory="Expert in managing and utilizing stored knowledge",
verbose=True
)
# Define a task for the agent
knowledge_task = Task(
name="knowledge_task",
description="KAG",
expected_output="Answer to the question",
agent=knowledge_agent,
context=[
{
"embedding_db_config": json.dumps(config["vector_store"])
}
]
)
# Create and start the agents
agents = PraisonAIAgents(
agents=[knowledge_agent],
tasks=[knowledge_task],
process="sequential",
user_id="user1"
)
# Start execution
result = agents.start()
+21
View File
@@ -0,0 +1,21 @@
from praisonaiagents import Agent
config = {
"vector_store": {
"provider": "chroma",
"config": {
"collection_name": "praison",
"path": ".praison",
}
}
}
agent = Agent(
name="Knowledge Agent",
instructions="You answer questions based on the provided knowledge.",
knowledge=["large.pdf"],
knowledge_config=config,
user_id="user1"
)
agent.start("What is KAG in one line?")
+44
View File
@@ -0,0 +1,44 @@
import logging
from praisonaiagents.knowledge import Knowledge
import os
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
config = {
"version": "v1.1",
"vector_store": {
"provider": "chroma",
"config": {
"collection_name": "praison",
"path": os.path.abspath("./.praison"),
"host": None,
"port": None
}
},
"embedder": {
"provider": "openai",
"config": {
"model": "text-embedding-3-small",
"embedding_dims": 1536
}
},
"llm": {
"provider": "openai",
"config": {
"model": "gpt-4o-mini",
"temperature": 0,
"max_tokens": 1000
}
}
}
knowledge = Knowledge(config)
# Search for memories based on a query
query = "KAG"
logger.info(f"Searching for memories with query: {query}")
search_results = knowledge.search(query, user_id="user1")
logger.info(f"Search results: {search_results}")
print(f"\nSearch results for '{query}':")
print(search_results)
+171
View File
@@ -0,0 +1,171 @@
import logging
from praisonaiagents.knowledge import Knowledge
import os
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
config = {
"vector_store": {
"provider": "chroma",
"config": {
"collection_name": "test",
"path": ".praison",
}
}
}
knowledge = Knowledge(config)
# Store memories
logger.info("Storing memories...")
cricket_memory = knowledge.store("Likes to play cricket on weekends", user_id="alice", metadata={"category": "hobbies"})
logger.info(f"Stored cricket memory: {cricket_memory}")
tennis_memory = knowledge.store("Enjoys playing tennis with friends", user_id="alice", metadata={"category": "hobbies"})
logger.info(f"Stored tennis memory: {tennis_memory}")
work_memory = knowledge.store("Works as a software engineer", user_id="alice", metadata={"category": "work"})
logger.info(f"Stored work memory: {work_memory}")
print("Stored memories:")
print(cricket_memory)
print(tennis_memory)
print(work_memory)
# Retrieve all memories for a user
logger.info("Retrieving all memories for Alice...")
alice_memories = knowledge.get_all(user_id="alice")
logger.info(f"Retrieved memories for Alice: {alice_memories}")
print("\nAll memories for Alice:")
for memory in alice_memories:
print(memory)
# Retrieve a specific memory by ID
logger.info(f"Retrieving memory with ID: {cricket_memory['results'][0]['id']}")
retrieved_memory = knowledge.get(cricket_memory['results'][0]["id"])
logger.info(f"Retrieved memory: {retrieved_memory}")
print("\nRetrieved memory:")
print(retrieved_memory)
# Search for memories based on a query
query = "What are Alice's hobbies?"
logger.info(f"Searching for memories with query: {query}")
search_results = knowledge.search(query, user_id="alice")
logger.info(f"Search results: {search_results}")
print(f"\nSearch results for '{query}':")
for memory in search_results:
print(memory)
# Update a memory
logger.info(f"Updating memory with ID: {tennis_memory['results'][0]['id']}")
updated_memory = knowledge.update(memory_id=tennis_memory['results'][0]["id"], data="Loves playing tennis on weekends")
logger.info(f"Updated memory: {updated_memory}")
print("\nUpdated memory:")
print(updated_memory)
# Get memory history
logger.info(f"Retrieving memory history for ID: {tennis_memory['results'][0]['id']}")
memory_history = knowledge.history(memory_id=tennis_memory['results'][0]["id"])
logger.info(f"Memory history: {memory_history}")
print("\nMemory history:")
for entry in memory_history:
print(entry)
# Delete a memory
logger.info(f"Deleting memory with ID: {work_memory['results'][0]['id']}")
knowledge.delete(memory_id=work_memory['results'][0]["id"])
logger.info("Memory deleted")
print("\nDeleted memory")
# Retrieve memories after deletion
logger.info("Retrieving memories after deletion...")
alice_memories = knowledge.get_all(user_id="alice")
logger.info(f"Retrieved memories after deletion: {alice_memories}")
print("\nMemories after deletion:")
for memory in alice_memories:
print(memory)
# Delete all memories for a user
logger.info("Deleting all memories for Alice...")
knowledge.delete_all(user_id="alice")
logger.info("All memories for Alice deleted")
print("\nAll memories for Alice deleted")
# Retrieve memories after deleting all
logger.info("Retrieving memories after deleting all...")
alice_memories = knowledge.get_all(user_id="alice")
logger.info(f"Retrieved memories after deleting all: {alice_memories}")
print("\nMemories after deleting all:")
print(alice_memories)
# Reset all memories
logger.info("Resetting all memories...")
knowledge.reset()
logger.info("All memories reset")
print("\nAll memories reset")
# Test file handling
logger.info("Testing file handling...")
try:
# Get absolute path to test files
current_dir = os.path.dirname(os.path.abspath(__file__))
pdf_file = os.path.join(current_dir, "small.pdf")
txt_file = os.path.join(current_dir, "sample.txt")
# Test text file
logger.info(f"Testing text file: {txt_file}")
# Read and display content
with open(txt_file, 'r') as file:
txt_content = file.read()
print("\nText file content:")
print(txt_content)
# Store the text file using add
txt_memory = knowledge.add(txt_file, user_id="bob", metadata={"type": "text"})
logger.info(f"Stored text file: {txt_memory}")
print("\nStored text content:")
if txt_memory and 'results' in txt_memory and txt_memory['results']:
for mem in txt_memory['results']:
print(mem)
else:
print("No valid memories were stored from the text file")
# Verify text memories are stored
if txt_memory and 'results' in txt_memory and txt_memory['results']:
logger.info("Verifying text memories...")
for mem in txt_memory['results']:
if isinstance(mem, dict) and 'id' in mem:
stored = knowledge.get(mem['id'])
logger.info(f"Verified text memory: {stored}")
else:
logger.warning(f"Unexpected memory format: {mem}")
else:
logger.warning("No valid memories were stored from the text file")
# Test pdf file
logger.info(f"Testing pdf file: {pdf_file}")
pdf_memory = knowledge.add(pdf_file, user_id="bob", metadata={"type": "pdf"})
logger.info(f"Stored pdf file: {pdf_memory}")
print("\nStored pdf content:")
if pdf_memory and 'results' in pdf_memory and pdf_memory['results']:
for mem in pdf_memory['results']:
print(mem)
else:
print("No valid memories were stored from the PDF file")
# Verify stored content
if pdf_memory and 'results' in pdf_memory and pdf_memory['results']:
for memory in pdf_memory['results']:
if isinstance(memory, dict) and 'id' in memory:
stored_memory = knowledge.get(memory['id'])
logger.info(f"Verified stored memory: {stored_memory}")
print("\nVerified content:")
print(stored_memory)
else:
logger.warning(f"Unexpected memory format: {memory}")
else:
logger.warning("No valid memories were stored from the PDF file")
except Exception as e:
logger.error(f"Error during file handling test: {str(e)}")
raise
+40
View File
@@ -0,0 +1,40 @@
import logging
from praisonaiagents.knowledge import Knowledge
import os
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
knowledge = Knowledge()
try:
# Get absolute path to test files
current_dir = os.path.dirname(os.path.abspath(__file__))
pdf_file = os.path.join(current_dir, "large.pdf")
# Test pdf file
logger.info(f"Testing pdf file: {pdf_file}")
pdf_memory = knowledge.add(pdf_file, user_id="bob", metadata={"type": "pdf"})
logger.info(f"Stored pdf file: {pdf_memory}")
print("\nStored pdf content:")
if pdf_memory and 'results' in pdf_memory and pdf_memory['results']:
for mem in pdf_memory['results']:
print(mem)
else:
print("No valid memories were stored from the PDF file")
# Verify stored content
if pdf_memory and 'results' in pdf_memory and pdf_memory['results']:
for memory in pdf_memory['results']:
if isinstance(memory, dict) and 'id' in memory:
stored_memory = knowledge.get(memory['id'])
logger.info(f"Verified stored memory: {stored_memory}")
print("\nVerified content:")
print(stored_memory)
else:
logger.warning(f"Unexpected memory format: {memory}")
else:
logger.warning("No valid memories were stored from the PDF file")
except Exception as e:
logger.error(f"Error during file handling test: {str(e)}")
raise
BIN
View File
Binary file not shown.
+5
View File
@@ -0,0 +1,5 @@
from markitdown import MarkItDown
md = MarkItDown()
result = md.convert("sample.txt")
print(result.text_content)
+220
View File
@@ -0,0 +1,220 @@
from mem0 import Memory
import logging
import json
import os
import time
from datetime import datetime
from typing import Dict, Any, Optional
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
class MemoryManager:
def __init__(self):
"""Initialize Mem0 Memory manager with configuration"""
# Define the complete configuration with only supported fields
config = {
"version": "v1.1",
"custom_prompt": None,
"vector_store": {
"provider": "chroma",
"config": {
"collection_name": "praison",
"path": os.path.abspath("./.praison/storage"),
"host": None,
"port": None
}
},
"embedder": {
"provider": "openai",
"config": {
"model": "text-embedding-3-small",
"embedding_dims": 1536
}
},
"llm": {
"provider": "openai",
"config": {
"model": "gpt-4o-mini",
"temperature": 0,
"max_tokens": 1000
}
}
}
# Ensure storage directory exists
storage_path = os.path.abspath("./.praison/storage")
if os.path.exists(storage_path):
logger.info(f"Clearing existing storage at {storage_path}")
import shutil
shutil.rmtree(storage_path)
os.makedirs(storage_path, exist_ok=True)
logger.info(f"Created storage path: {storage_path}")
# Initialize memory
self.memory = Memory.from_config(config)
logger.info("Memory manager initialized")
def pretty_print(self, data: Any) -> None:
"""Helper function to print memory data in a readable format"""
if isinstance(data, (dict, list)):
print(json.dumps(data, indent=2))
else:
print(data)
def extract_memory_id(self, result: Any) -> Optional[str]:
"""Extract memory ID from the result, handling different formats"""
try:
if isinstance(result, dict):
# v1.1 format
memories = result.get('results', [])
return memories[0]['id'] if memories else None
elif isinstance(result, list):
# v1.0 format
return result[0]['id'] if result else None
return None
except (KeyError, IndexError) as e:
logger.warning(f"Could not extract memory ID from result: {e}")
return None
def prepare_metadata(self, metadata: Optional[Dict]) -> Dict:
"""Prepare metadata by converting values to acceptable types"""
if not metadata:
return {}
clean_metadata = {}
for key, value in metadata.items():
if isinstance(value, (str, int, float, bool)):
clean_metadata[key] = value
elif isinstance(value, list):
clean_metadata[key] = ','.join(map(str, value))
elif isinstance(value, dict):
clean_metadata[key] = json.dumps(value)
else:
clean_metadata[key] = str(value)
return clean_metadata
def verify_memory_addition(self, user_id: str, max_retries: int = 3) -> bool:
"""Verify that memory was added successfully"""
for attempt in range(max_retries):
try:
time.sleep(0.5) # Brief pause to allow indexing
memories = self.memory.get_all(user_id=user_id)
if len(memories.get('results', [])) > 0:
return True
logger.warning(f"Memory not found on attempt {attempt + 1}")
except Exception as e:
logger.warning(f"Verification attempt {attempt + 1} failed: {e}")
if attempt < max_retries - 1:
time.sleep(1)
return False
def add_memory(self, text: str, user_id: Optional[str] = None, metadata: Optional[Dict] = None) -> Dict:
"""Add a new memory with error handling and verification"""
try:
logger.info(f"Adding memory for user {user_id}")
clean_metadata = self.prepare_metadata(metadata)
logger.debug(f"Prepared metadata: {clean_metadata}")
messages = [{"role": "user", "content": text}]
result = self.memory.add(
messages=messages,
user_id=user_id,
metadata=clean_metadata
)
if self.verify_memory_addition(user_id):
logger.info("Memory added and verified successfully")
else:
logger.warning("Memory addition could not be verified")
return result
except Exception as e:
logger.error(f"Failed to add memory: {str(e)}")
raise
def get_all_memories(self, user_id: Optional[str] = None) -> Dict:
"""Retrieve all memories for a user"""
try:
logger.info(f"Retrieving all memories for user {user_id}")
memories = self.memory.get_all(user_id=user_id)
count = len(memories.get('results', []))
logger.info(f"Retrieved {count} memories")
return memories
except Exception as e:
logger.error(f"Failed to retrieve memories: {str(e)}")
raise
def search_memories(self, query: str, user_id: Optional[str] = None, limit: int = 5) -> Dict:
"""Search memories with a query"""
try:
logger.info(f"Searching memories with query: {query}")
results = self.memory.search(
query=query,
user_id=user_id,
limit=limit
)
count = len(results.get('results', []))
logger.info(f"Found {count} matching memories")
return results
except Exception as e:
logger.error(f"Search failed: {str(e)}")
raise
def main():
try:
# Initialize memory manager
manager = MemoryManager()
# Add a test memory
print("\n1. Adding a new memory:")
metadata = {
"category": "hobbies",
"timestamp": datetime.now().isoformat(),
"tags": "tennis,learning",
"priority": 1,
"source": "user_input"
}
result = manager.add_memory(
text="I am working on improving my tennis skills. Suggest some online courses.",
user_id="alice",
metadata=metadata
)
manager.pretty_print(result)
# Wait briefly for indexing
time.sleep(1)
print("\n2. Retrieving all memories:")
all_memories = manager.get_all_memories(user_id="alice")
manager.pretty_print(all_memories)
print("\n3. Searching memories:")
search_results = manager.search_memories(
query="What are Alice's hobbies?",
user_id="alice",
limit=5
)
manager.pretty_print(search_results)
# Print summary
print("\nMemory Store Summary:")
total_memories = len(all_memories.get('results', []))
print(f"Total memories stored: {total_memories}")
if total_memories > 0:
print("Available memories:")
for mem in all_memories['results']:
print(f"- {mem.get('memory', 'No content')}")
except Exception as e:
logger.error(f"Main process failed: {str(e)}", exc_info=True)
raise
if __name__ == "__main__":
main()
+143
View File
@@ -0,0 +1,143 @@
from mem0 import Memory
import logging
import json
import os
from typing import Dict, Any, Optional
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
class MemorySearcher:
def __init__(self):
"""Initialize Mem0 Memory searcher with configuration"""
# Define the configuration
config = {
"version": "v1.1",
"vector_store": {
"provider": "chroma",
"config": {
"collection_name": "praison",
"path": os.path.abspath("./.praison/storage"),
"host": None,
"port": None
}
},
"embedder": {
"provider": "openai",
"config": {
"model": "text-embedding-3-small",
"embedding_dims": 1536
}
},
"llm": {
"provider": "openai",
"config": {
"model": "gpt-4o-mini",
"temperature": 0,
"max_tokens": 1000
}
}
}
# Initialize memory
self.memory = Memory.from_config(config)
logger.info("Memory searcher initialized")
def pretty_print(self, data: Any) -> None:
"""Helper function to print data in a readable format"""
if isinstance(data, (dict, list)):
print(json.dumps(data, indent=2))
else:
print(data)
def get_all_memories(self, user_id: Optional[str] = None) -> Dict:
"""Retrieve all memories for a user"""
try:
logger.info(f"Retrieving all memories for user {user_id}")
memories = self.memory.get_all(user_id=user_id)
count = len(memories.get('results', []))
logger.info(f"Retrieved {count} memories")
return memories
except Exception as e:
logger.error(f"Failed to retrieve memories: {str(e)}")
raise
def search_memories(self, query: str, user_id: Optional[str] = None, limit: int = 5) -> Dict:
"""Search memories with a query"""
try:
logger.info(f"Searching memories with query: {query}")
results = self.memory.search(
query=query,
user_id=user_id,
limit=limit
)
count = len(results.get('results', []))
logger.info(f"Found {count} matching memories")
return results
except Exception as e:
logger.error(f"Search failed: {str(e)}")
raise
def list_unique_users(self) -> list:
"""List all unique users in the memory store"""
try:
all_memories = self.memory.get_all()
users = set()
for memory in all_memories.get('results', []):
if 'user_id' in memory:
users.add(memory['user_id'])
return sorted(list(users))
except Exception as e:
logger.error(f"Failed to list users: {str(e)}")
raise
def main():
try:
# Initialize memory searcher
searcher = MemorySearcher()
# Get list of users
print("\n1. Available users in the memory store:")
users = searcher.list_unique_users()
searcher.pretty_print(users)
if not users:
print("No users found in the memory store. Please add some memories first.")
return
# Example user (using first user found)
example_user = users[0]
print(f"\n2. All memories for user '{example_user}':")
all_memories = searcher.get_all_memories(user_id=example_user)
searcher.pretty_print(all_memories)
print(f"\n3. Searching memories for user '{example_user}':")
search_results = searcher.search_memories(
query="What are their hobbies?",
user_id=example_user,
limit=5
)
searcher.pretty_print(search_results)
# Print summary
print("\nMemory Store Summary:")
total_memories = len(all_memories.get('results', []))
print(f"Total memories for {example_user}: {total_memories}")
if total_memories > 0:
print("Available memories:")
for mem in all_memories['results']:
print(f"- {mem.get('memory', 'No content')}")
if 'metadata' in mem:
print(f" Metadata: {mem['metadata']}")
except Exception as e:
logger.error(f"Main process failed: {str(e)}", exc_info=True)
raise
if __name__ == "__main__":
main()
+26
View File
@@ -0,0 +1,26 @@
from mem0 import Memory
import os
import json
# Basic configuration
config = {
"vector_store": {
"provider": "chroma",
"config": {
"collection_name": "praison",
"path": ".praison",
}
}
}
# Initialize memory
memory = Memory.from_config(config)
# Search Alice's hobbies
search_results = memory.search(
query="KAG",
user_id="user1",
limit=5
)
print(search_results)
+46
View File
@@ -0,0 +1,46 @@
from mem0 import Memory
import os
import json
# Basic configuration
config = {
"version": "v1.1",
"vector_store": {
"provider": "chroma",
"config": {
"collection_name": "praison",
"path": os.path.abspath("./.praison/storage")
}
},
"embedder": {
"provider": "openai",
"config": {
"model": "text-embedding-3-small"
}
},
"llm": {
"provider": "openai",
"config": {
"model": "gpt-4o-mini"
}
}
}
# Initialize memory
memory = Memory.from_config(config)
# Search Alice's hobbies
search_results = memory.search(
query="What are Alice's hobbies?",
user_id="alice",
limit=5
)
# Print results in a readable format
print("\nAlice's Memories:")
for memory in search_results['results']:
print(f"\nMemory: {memory['memory']}")
print(f"Score: {memory['score']}")
if 'metadata' in memory:
print("Metadata:")
print(json.dumps(memory['metadata'], indent=2))
+4 -2
View File
@@ -7,7 +7,8 @@ from .agents.agents import PraisonAIAgents
from .task.task import Task
from .tools.tools import Tools
from .agents.autoagents import AutoAgents
from .memory.memory import Memory
from .knowledge.knowledge import Knowledge
from .knowledge.chunking import Chunking
from .main import (
TaskOutput,
ReflectionOutput,
@@ -36,7 +37,6 @@ __all__ = [
'TaskOutput',
'ReflectionOutput',
'AutoAgents',
'Memory',
'display_interaction',
'display_self_reflection',
'display_instruction',
@@ -48,4 +48,6 @@ __all__ = [
'register_display_callback',
'sync_display_callbacks',
'async_display_callbacks',
'Knowledge',
'Chunking'
]
+89 -13
View File
@@ -20,6 +20,7 @@ from ..main import (
adisplay_instruction
)
import inspect
import uuid
if TYPE_CHECKING:
from ..task.task import Task
@@ -70,10 +71,15 @@ class Agent:
import inspect
# Langchain tools
if inspect.isclass(func) and hasattr(func, 'run'):
if inspect.isclass(func) and hasattr(func, 'run') and not hasattr(func, '_run'):
original_func = func
func = func.run
function_name = original_func.__name__
# CrewAI tools
elif inspect.isclass(func) and hasattr(func, '_run'):
original_func = func
func = func._run
function_name = original_func.__name__
sig = inspect.signature(func)
logging.debug(f"Function signature: {sig}")
@@ -176,14 +182,27 @@ class Agent:
respect_context_window: bool = True,
code_execution_mode: Literal["safe", "unsafe"] = "safe",
embedder_config: Optional[Dict[str, Any]] = None,
knowledge_sources: Optional[List[Any]] = None,
knowledge: Optional[List[str]] = None,
knowledge_config: Optional[Dict[str, Any]] = None,
use_system_prompt: Optional[bool] = True,
markdown: bool = True,
self_reflect: bool = False,
max_reflect: int = 3,
min_reflect: int = 1,
reflect_llm: Optional[str] = None
reflect_llm: Optional[str] = None,
user_id: Optional[str] = None
):
# Add check at start if memory is requested
if memory is not None:
try:
from ..memory.memory import Memory
MEMORY_AVAILABLE = True
except ImportError:
raise ImportError(
"Memory features requested in Agent but memory dependencies not installed. "
"Please install with: pip install \"praisonaiagents[memory]\""
)
# Handle backward compatibility for required fields
if all(x is None for x in [name, role, goal, backstory, instructions]):
raise ValueError("At least one of name, role, goal, backstory, or instructions must be provided")
@@ -226,7 +245,7 @@ class Agent:
self.respect_context_window = respect_context_window
self.code_execution_mode = code_execution_mode
self.embedder_config = embedder_config
self.knowledge_sources = knowledge_sources
self.knowledge = knowledge
self.use_system_prompt = use_system_prompt
self.chat_history = []
self.markdown = markdown
@@ -242,6 +261,40 @@ Your Role: {self.role}\n
Your Goal: {self.goal}
"""
# Generate unique IDs
self.agent_id = str(uuid.uuid4())
# Store user_id
self.user_id = user_id
# Check if knowledge parameter has any values
if not knowledge:
self.knowledge = None
else:
# Initialize Knowledge with provided or default config
from praisonaiagents.knowledge import Knowledge
self.knowledge = Knowledge(knowledge_config or None)
# Handle knowledge
if knowledge:
for source in knowledge:
self._process_knowledge(source)
def _process_knowledge(self, knowledge_item):
"""Process and store knowledge from a file path, URL, or string."""
try:
if os.path.exists(knowledge_item):
# It's a file path
self.knowledge.add(knowledge_item, user_id=self.user_id, agent_id=self.agent_id)
elif knowledge_item.startswith("http://") or knowledge_item.startswith("https://"):
# It's a URL
pass
else:
# It's a string content
self.knowledge.store(knowledge_item, user_id=self.user_id, agent_id=self.agent_id)
except Exception as e:
logging.error(f"Error processing knowledge item: {knowledge_item}, error: {e}")
def generate_task(self) -> 'Task':
"""Generate a Task object from the agent's instructions"""
from ..task.task import Task
@@ -280,14 +333,22 @@ Your Goal: {self.goal}
if func:
try:
# If it's a class with run method, instantiate and call run
if inspect.isclass(func) and hasattr(func, 'run'):
# Langchain: If it's a class with run but not _run, instantiate and call run
if inspect.isclass(func) and hasattr(func, 'run') and not hasattr(func, '_run'):
instance = func()
# Extract only the parameters that run() expects
run_params = {k: v for k, v in arguments.items()
if k in inspect.signature(instance.run).parameters
and k != 'self'}
if k in inspect.signature(instance.run).parameters
and k != 'self'}
return instance.run(**run_params)
# CrewAI: If it's a class with an _run method, instantiate and call _run
elif inspect.isclass(func) and hasattr(func, '_run'):
instance = func()
run_params = {k: v for k, v in arguments.items()
if k in inspect.signature(instance._run).parameters
and k != 'self'}
return instance._run(**run_params)
# Otherwise treat as regular function
elif callable(func):
return func(**arguments)
@@ -418,15 +479,30 @@ Your Goal: {self.goal}
return None
def chat(self, prompt, temperature=0.2, tools=None, output_json=None, output_pydantic=None):
# Search for existing knowledge if any knowledge is provided
if self.knowledge:
search_results = self.knowledge.search(prompt, agent_id=self.agent_id)
if search_results:
# Check if search_results is a list of dictionaries or strings
if isinstance(search_results, dict) and 'results' in search_results:
# Extract memory content from the results
knowledge_content = "\n".join([result['memory'] for result in search_results['results']])
else:
# If search_results is a list of strings, join them directly
knowledge_content = "\n".join(search_results)
# Append found knowledge to the prompt
prompt = f"{prompt}\n\nKnowledge: {knowledge_content}"
if self.use_system_prompt:
system_prompt = f"""{self.backstory}\n
Your Role: {self.role}\n
Your Goal: {self.goal}
"""
if output_json:
system_prompt += f"\nReturn ONLY a JSON object that matches this Pydantic model: {output_json.schema_json()}"
system_prompt += f"\nReturn ONLY a JSON object that matches this Pydantic model: {json.dumps(output_json.model_json_schema())}"
elif output_pydantic:
system_prompt += f"\nReturn ONLY a JSON object that matches this Pydantic model: {output_pydantic.schema_json()}"
system_prompt += f"\nReturn ONLY a JSON object that matches this Pydantic model: {json.dumps(output_pydantic.model_json_schema())}"
else:
system_prompt = None
@@ -616,9 +692,9 @@ Output MUST be JSON with 'reflection' and 'satisfactory'.
# Build system prompt
system_prompt = self.system_prompt
if output_json:
system_prompt += f"\nReturn ONLY a JSON object that matches this Pydantic model: {output_json.schema_json()}"
system_prompt += f"\nReturn ONLY a JSON object that matches this Pydantic model: {json.dumps(output_json.model_json_schema())}"
elif output_pydantic:
system_prompt += f"\nReturn ONLY a JSON object that matches this Pydantic model: {output_pydantic.schema_json()}"
system_prompt += f"\nReturn ONLY a JSON object that matches this Pydantic model: {json.dumps(output_pydantic.model_json_schema())}"
# Build messages
if isinstance(prompt, str):
+128 -23
View File
@@ -12,6 +12,7 @@ from ..agent.agent import Agent
from ..task.task import Task
from ..process.process import Process, LoopItems
import asyncio
import uuid
# Set up logger
logger = logging.getLogger(__name__)
@@ -44,10 +45,29 @@ def process_video(video_path: str, seconds_per_frame=2):
return base64_frames
class PraisonAIAgents:
def __init__(self, agents, tasks=None, verbose=0, completion_checker=None, max_retries=5, process="sequential", manager_llm=None, memory=False, memory_config=None, embedder=None):
def __init__(self, agents, tasks=None, verbose=0, completion_checker=None, max_retries=5, process="sequential", manager_llm=None, memory=False, memory_config=None, embedder=None, user_id=None, max_iter=10):
# Add check at the start if memory is requested
if memory:
try:
from ..memory.memory import Memory
MEMORY_AVAILABLE = True
except ImportError:
raise ImportError(
"Memory features requested but memory dependencies not installed. "
"Please install with: pip install \"praisonaiagents[memory]\""
)
if not agents:
raise ValueError("At least one agent must be provided")
self.run_id = str(uuid.uuid4()) # Auto-generate run_id
self.user_id = user_id or "praison" # Optional user_id
self.max_iter = max_iter # Add max_iter parameter
# Pass user_id to each agent
for agent in agents:
agent.user_id = self.user_id
self.agents = agents
self.tasks = {}
if max_retries < 3:
@@ -221,15 +241,46 @@ You need to do the following task: {task.description}.
Expected Output: {task.expected_output}.
"""
if task.context:
context_results = ""
for context_task in task.context:
if context_task.result:
context_results += f"Result of previous task {context_task.name if context_task.name else context_task.description}: {context_task.result.raw}\n"
else:
context_results += f"Previous task {context_task.name if context_task.name else context_task.description} had no result.\n"
context_results = [] # Use list to avoid duplicates
for context_item in task.context:
if isinstance(context_item, str):
context_results.append(f"Input Content:\n{context_item}")
elif isinstance(context_item, list):
context_results.append(f"Input Content: {' '.join(str(x) for x in context_item)}")
elif hasattr(context_item, 'result'): # Task object
if context_item.result:
context_results.append(
f"Result of previous task {context_item.name if context_item.name else context_item.description}:\n{context_item.result.raw}"
)
else:
context_results.append(
f"Previous task {context_item.name if context_item.name else context_item.description} has no result yet."
)
elif isinstance(context_item, dict) and "vector_store" in context_item:
from ..knowledge.knowledge import Knowledge
try:
# Handle both string and dict configs
cfg = context_item["vector_store"]
if isinstance(cfg, str):
cfg = json.loads(cfg)
knowledge = Knowledge(config={"vector_store": cfg}, verbose=self.verbose)
# Only use user_id as filter
db_results = knowledge.search(
task.description,
user_id=self.user_id if self.user_id else None
)
context_results.append(f"[DB Context]: {str(db_results)}")
except Exception as e:
context_results.append(f"[Vector DB Error]: {e}")
# Join unique context results
unique_contexts = list(dict.fromkeys(context_results)) # Remove duplicates
task_prompt += f"""
Here are the results of previous tasks that might be useful:\n
{context_results}
Context:
{' '.join(unique_contexts)}
"""
task_prompt += "Please provide only the final result of your work. Do not add any conversation or extra explanation."
@@ -381,7 +432,8 @@ Here are the results of previous tasks that might be useful:\n
tasks=self.tasks,
agents=self.agents,
manager_llm=self.manager_llm,
verbose=self.verbose
verbose=self.verbose,
max_iter=self.max_iter
)
if self.process == "workflow":
@@ -419,8 +471,16 @@ Here are the results of previous tasks that might be useful:\n
else:
self.run_task(task_id)
async def astart(self):
async def astart(self, content=None, **kwargs):
"""Async version of start method"""
if content:
# Add content to context of all tasks
for task in self.tasks.values():
if isinstance(content, (str, list)):
if not task.context:
task.context = []
task.context.append(content)
await self.arun_all_tasks()
return {
"task_status": self.get_all_tasks_status(),
@@ -477,16 +537,48 @@ You need to do the following task: {task.description}.
Expected Output: {task.expected_output}.
"""
if task.context:
context_results = ""
for context_task in task.context:
if context_task.result:
context_results += f"Result of previous task {context_task.name if context_task.name else context_task.description}: {context_task.result.raw}\n"
else:
context_results += f"Previous task {context_task.name if context_task.name else context_task.description} had no result.\n"
context_results = [] # Use list to avoid duplicates
for context_item in task.context:
if isinstance(context_item, str):
context_results.append(f"Input Content:\n{context_item}")
elif isinstance(context_item, list):
context_results.append(f"Input Content: {' '.join(str(x) for x in context_item)}")
elif hasattr(context_item, 'result'): # Task object
if context_item.result:
context_results.append(
f"Result of previous task {context_item.name if context_item.name else context_item.description}:\n{context_item.result.raw}"
)
else:
context_results.append(
f"Previous task {context_item.name if context_item.name else context_item.description} has no result yet."
)
elif isinstance(context_item, dict) and "vector_store" in context_item:
from ..knowledge.knowledge import Knowledge
try:
# Handle both string and dict configs
cfg = context_item["vector_store"]
if isinstance(cfg, str):
cfg = json.loads(cfg)
knowledge = Knowledge(config={"vector_store": cfg}, verbose=self.verbose)
# Only use user_id as filter
db_results = knowledge.search(
task.description,
user_id=self.user_id if self.user_id else None
)
context_results.append(f"[DB Context]: {str(db_results)}")
except Exception as e:
context_results.append(f"[Vector DB Error]: {e}")
# Join unique context results
unique_contexts = list(dict.fromkeys(context_results)) # Remove duplicates
task_prompt += f"""
Here are the results of previous tasks that might be useful:\n
{context_results}
Context:
{' '.join(unique_contexts)}
"""
# Add memory context if available
if task.memory:
try:
@@ -667,7 +759,8 @@ Here are the results of previous tasks that might be useful:\n
tasks=self.tasks,
agents=self.agents,
manager_llm=self.manager_llm,
verbose=self.verbose
verbose=self.verbose,
max_iter=self.max_iter
)
if self.process == "workflow":
@@ -706,12 +799,24 @@ Here are the results of previous tasks that might be useful:\n
return str(agent[0])
return None
def start(self):
def start(self, content=None, **kwargs):
"""Start agent execution with optional content and config"""
if content:
# Add content to context of all tasks
for task in self.tasks.values():
if isinstance(content, (str, list)):
# If context is empty, initialize it
if not task.context:
task.context = []
# Add content to context
task.context.append(content)
# Run tasks as before
self.run_all_tasks()
return {
"task_status": self.get_all_tasks_status(),
"task_results": {task_id: self.get_task_result(task_id) for task_id in self.tasks}
}
}
def set_state(self, key: str, value: Any) -> None:
"""Set a state value"""
@@ -0,0 +1,8 @@
"""
PraisonAI Knowledge - Advanced knowledge management system with configurable features
"""
from praisonaiagents.knowledge.knowledge import Knowledge
from praisonaiagents.knowledge.chunking import Chunking
__all__ = ["Knowledge", "Chunking"]
@@ -0,0 +1,182 @@
from typing import List, Union, Optional, Dict, Any
from functools import cached_property
import importlib
class Chunking:
"""A unified class for text chunking with various chunking strategies."""
CHUNKER_PARAMS = {
'token': ['chunk_size', 'chunk_overlap', 'tokenizer'],
'word': ['chunk_size', 'chunk_overlap', 'tokenizer'],
'sentence': ['chunk_size', 'chunk_overlap', 'tokenizer'],
'semantic': ['chunk_size', 'embedding_model', 'tokenizer'],
'sdpm': ['chunk_size', 'embedding_model', 'tokenizer'],
'late': ['chunk_size', 'embedding_model', 'tokenizer'],
'recursive': ['chunk_size', 'tokenizer']
}
@cached_property
def SUPPORTED_CHUNKERS(self) -> Dict[str, Any]:
"""Lazy load chunker classes."""
try:
from chonkie.chunker import (
TokenChunker,
WordChunker,
SentenceChunker,
SemanticChunker,
SDPMChunker,
LateChunker,
RecursiveChunker
)
except ImportError:
raise ImportError(
"chonkie package not found. Please install it using: pip install 'praisonaiagents[knowledge]'"
)
return {
'token': TokenChunker,
'word': WordChunker,
'sentence': SentenceChunker,
'semantic': SemanticChunker,
'sdpm': SDPMChunker,
'late': LateChunker,
'recursive': RecursiveChunker
}
def __init__(
self,
chunker_type: str = 'token',
chunk_size: int = 512,
chunk_overlap: int = 128,
tokenizer: str = "gpt2",
embedding_model: Optional[Union[str, Any]] = None,
**kwargs
):
"""Initialize the Chunking class."""
if chunker_type not in self.CHUNKER_PARAMS:
raise ValueError(
f"Unsupported chunker type: {chunker_type}. "
f"Must be one of: {list(self.CHUNKER_PARAMS.keys())}"
)
self.chunker_type = chunker_type
self.chunk_size = chunk_size
self.chunk_overlap = chunk_overlap
self.tokenizer = tokenizer
self._embedding_model = embedding_model
self.kwargs = kwargs
# Initialize these as None for lazy loading
self._chunker = None
self._embeddings = None
@cached_property
def embedding_model(self):
"""Lazy load the embedding model."""
if self._embedding_model is None and self.chunker_type in ['semantic', 'sdpm', 'late']:
from chonkie.embeddings import AutoEmbeddings
return AutoEmbeddings.get_embeddings("all-MiniLM-L6-v2")
elif isinstance(self._embedding_model, str):
from chonkie.embeddings import AutoEmbeddings
return AutoEmbeddings.get_embeddings(self._embedding_model)
return self._embedding_model
def _get_chunker_params(self) -> Dict[str, Any]:
"""Get the appropriate parameters for the current chunker type."""
allowed_params = self.CHUNKER_PARAMS[self.chunker_type]
params = {'chunk_size': self.chunk_size}
if 'chunk_overlap' in allowed_params:
params['chunk_overlap'] = self.chunk_overlap
if 'tokenizer' in allowed_params:
if self.chunker_type in ['semantic', 'sdpm', 'late']:
params['tokenizer'] = self.embedding_model.get_tokenizer_or_token_counter()
else:
params['tokenizer'] = self.tokenizer
if 'embedding_model' in allowed_params:
params['embedding_model'] = self.embedding_model
# Add any additional kwargs that are in allowed_params
for key, value in self.kwargs.items():
if key in allowed_params:
params[key] = value
return params
@cached_property
def chunker(self):
"""Lazy load the chunker instance."""
if self._chunker is None:
chunker_cls = self.SUPPORTED_CHUNKERS[self.chunker_type]
common_params = self._get_chunker_params()
self._chunker = chunker_cls(**common_params)
return self._chunker
def _get_overlap_refinery(self, context_size: Optional[int] = None, **kwargs):
"""Lazy load the overlap refinery."""
try:
from chonkie.refinery import OverlapRefinery
except ImportError:
raise ImportError("Failed to import OverlapRefinery from chonkie.refinery")
if context_size is None:
context_size = self.chunk_overlap
return OverlapRefinery(
context_size=context_size,
tokenizer=self.chunker.tokenizer,
**kwargs
)
def add_overlap_context(
self,
chunks: List[Any],
context_size: int = None,
mode: str = "suffix",
merge_context: bool = True
) -> List[Any]:
"""Add overlap context to chunks using OverlapRefinery."""
refinery = self._get_overlap_refinery(
context_size=context_size,
mode=mode,
merge_context=merge_context
)
return refinery.refine(chunks)
def chunk(
self,
text: Union[str, List[str]],
add_context: bool = False,
context_params: Optional[Dict[str, Any]] = None
) -> Union[List[Any], List[List[Any]]]:
"""Chunk text using the configured chunking strategy."""
chunks = self.chunker(text)
if add_context:
context_params = context_params or {}
if isinstance(text, str):
chunks = self.add_overlap_context(chunks, **context_params)
else:
chunks = [self.add_overlap_context(c, **context_params) for c in chunks]
return chunks
def __call__(
self,
text: Union[str, List[str]],
add_context: bool = False,
context_params: Optional[Dict[str, Any]] = None
) -> Union[List[Any], List[List[Any]]]:
"""Make the Chunking instance callable."""
return self.chunk(text, add_context, context_params)
def __repr__(self) -> str:
"""String representation of the Chunking instance."""
return (
f"Chunking(chunker_type='{self.chunker_type}', "
f"chunk_size={self.chunk_size}, "
f"chunk_overlap={self.chunk_overlap})"
)
@@ -0,0 +1,321 @@
import os
import logging
import uuid
import time
from .chunking import Chunking
from functools import cached_property
from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn, TaskProgressColumn
logger = logging.getLogger(__name__)
class CustomMemory:
@classmethod
def from_config(cls, config):
from mem0 import Memory
return type('CustomMemory', (Memory,), {
'_add_to_vector_store': cls._add_to_vector_store
}).from_config(config)
@staticmethod
def _add_to_vector_store(self, messages, metadata, filters):
# Custom implementation that doesn't use LLM
parsed_messages = "\n".join([msg["content"] for msg in messages])
# Create a simple fact without using LLM
new_retrieved_facts = [parsed_messages]
# Process embeddings and continue with vector store operations
new_message_embeddings = {}
for new_mem in new_retrieved_facts:
messages_embeddings = self.embedding_model.embed(new_mem)
new_message_embeddings[new_mem] = messages_embeddings
# Create the memory
memory_id = self._create_memory(
data=parsed_messages,
existing_embeddings=new_message_embeddings,
metadata=metadata
)
return [{
"id": memory_id,
"memory": parsed_messages,
"event": "ADD"
}]
class Knowledge:
def __init__(self, config=None, verbose=None):
self._config = config
self._verbose = verbose or 0
os.environ['ANONYMIZED_TELEMETRY'] = 'False' # Chromadb
# Configure logging levels based on verbose setting
if not self._verbose:
# Suppress logs from all relevant dependencies
for logger_name in [
'mem0',
'chromadb',
'local_persistent_hnsw',
'_client',
'main'
]:
logging.getLogger(logger_name).setLevel(logging.WARNING)
# Disable OpenAI API request logging
logging.getLogger('openai').setLevel(logging.WARNING)
# Set root logger to warning to catch any uncategorized logs
logging.getLogger().setLevel(logging.WARNING)
@cached_property
def _deps(self):
try:
from markitdown import MarkItDown
import chromadb
return {
'chromadb': chromadb,
'markdown': MarkItDown()
}
except ImportError:
raise ImportError(
"Required packages not installed. Please install using: "
'pip install "praisonaiagents[knowledge]"'
)
@cached_property
def config(self):
# Generate unique collection name for each instance (only if not provided in config)
default_collection = f"test_{int(time.time())}_{str(uuid.uuid4())[:8]}"
persist_dir = ".praison"
# Create persistent client config
base_config = {
"vector_store": {
"provider": "chroma",
"config": {
"collection_name": default_collection,
"path": persist_dir,
"client": self._deps['chromadb'].PersistentClient(path=persist_dir),
"host": None,
"port": None
}
},
"version": "v1.1",
"custom_prompt": "Return {{\"facts\": [text]}} where text is the exact input provided and json response"
}
# If config is provided, merge it with base config
if self._config:
# Merge version if provided
if "version" in self._config:
base_config["version"] = self._config["version"]
# Merge vector_store config
if "vector_store" in self._config:
if "provider" in self._config["vector_store"]:
base_config["vector_store"]["provider"] = self._config["vector_store"]["provider"]
if "config" in self._config["vector_store"]:
config_copy = self._config["vector_store"]["config"].copy()
# Only exclude client as it's managed internally
if "client" in config_copy:
del config_copy["client"]
base_config["vector_store"]["config"].update(config_copy)
# Merge embedder config if provided
if "embedder" in self._config:
base_config["embedder"] = self._config["embedder"]
# Merge llm config if provided
if "llm" in self._config:
base_config["llm"] = self._config["llm"]
return base_config
@cached_property
def memory(self):
try:
return CustomMemory.from_config(self.config)
except (NotImplementedError, ValueError) as e:
if "list_collections" in str(e) or "Extra fields not allowed" in str(e):
# Keep only allowed fields
vector_store_config = {
"collection_name": self.config["vector_store"]["config"]["collection_name"],
"path": self.config["vector_store"]["config"]["path"]
}
self.config["vector_store"]["config"] = vector_store_config
from mem0 import Memory
return Memory.from_config(self.config)
raise
@cached_property
def markdown(self):
return self._deps['markdown']
@cached_property
def chunker(self):
return Chunking(
chunker_type='recursive',
chunk_size=512,
chunk_overlap=50
)
def _log(self, message, level=2):
"""Internal logging helper"""
if self._verbose and self._verbose >= level:
logger.info(message)
def store(self, content, user_id=None, agent_id=None, run_id=None, metadata=None):
"""Store a memory."""
try:
if isinstance(content, str):
if any(content.lower().endswith(ext) for ext in ['.pdf', '.doc', '.docx', '.txt']):
self._log(f"Content appears to be a file path, processing file: {content}")
return self.add(content, user_id=user_id, agent_id=agent_id, run_id=run_id, metadata=metadata)
content = content.strip()
if not content:
return []
result = self.memory.add(content, user_id=user_id, agent_id=agent_id, run_id=run_id, metadata=metadata)
self._log(f"Store operation result: {result}")
return result
except Exception as e:
logger.error(f"Error storing content: {str(e)}")
return []
def get_all(self, user_id=None, agent_id=None, run_id=None):
"""Retrieve all memories."""
return self.memory.get_all(user_id=user_id, agent_id=agent_id, run_id=run_id)
def get(self, memory_id):
"""Retrieve a specific memory by ID."""
return self.memory.get(memory_id)
def search(self, query, user_id=None, agent_id=None, run_id=None):
"""Search for memories related to a query."""
return self.memory.search(query, user_id=user_id, agent_id=agent_id, run_id=run_id)
def update(self, memory_id, data):
"""Update a memory."""
return self.memory.update(memory_id, data)
def history(self, memory_id):
"""Get the history of changes for a memory."""
return self.memory.history(memory_id)
def delete(self, memory_id):
"""Delete a memory."""
self.memory.delete(memory_id)
def delete_all(self, user_id=None, agent_id=None, run_id=None):
"""Delete all memories."""
self.memory.delete_all(user_id=user_id, agent_id=agent_id, run_id=run_id)
def reset(self):
"""Reset all memories."""
self.memory.reset()
def normalize_content(self, content):
"""Normalize content for consistent storage."""
# Example normalization: strip whitespace, convert to lowercase
return content.strip().lower()
def add(self, file_path, user_id=None, agent_id=None, run_id=None, metadata=None):
"""Read file content and store it in memory.
Args:
file_path: Can be:
- A string path to local file
- A URL string
- A list containing file paths and/or URLs
"""
if isinstance(file_path, (list, tuple)):
results = []
for path in file_path:
result = self._process_single_input(path, user_id, agent_id, run_id, metadata)
results.extend(result.get('results', []))
return {'results': results, 'relations': []}
return self._process_single_input(file_path, user_id, agent_id, run_id, metadata)
def _process_single_input(self, input_path, user_id=None, agent_id=None, run_id=None, metadata=None):
"""Process a single input which can be a file path or URL."""
try:
# Define supported file extensions
DOCUMENT_EXTENSIONS = {
'document': ('.pdf', '.ppt', '.pptx', '.doc', '.docx', '.xls', '.xlsx'),
'media': ('.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.mp3', '.wav', '.ogg', '.m4a'),
'text': ('.txt', '.csv', '.json', '.xml', '.md', '.html', '.htm'),
'archive': '.zip'
}
# Check if input is URL
if isinstance(input_path, str) and (input_path.startswith('http://') or input_path.startswith('https://')):
self._log(f"Processing URL: {input_path}")
raise NotImplementedError("URL processing not yet implemented")
# Check if input ends with any supported extension
is_supported_file = any(input_path.lower().endswith(ext)
for exts in DOCUMENT_EXTENSIONS.values()
for ext in (exts if isinstance(exts, tuple) else (exts,)))
if is_supported_file:
self._log(f"Processing as file path: {input_path}")
if not os.path.exists(input_path):
logger.error(f"File not found: {input_path}")
raise FileNotFoundError(f"File not found: {input_path}")
file_ext = '.' + input_path.lower().split('.')[-1] # Get extension reliably
# Process file based on type
if file_ext in DOCUMENT_EXTENSIONS['text']:
with open(input_path, 'r', encoding='utf-8') as file:
content = file.read().strip()
if not content:
raise ValueError("Empty text file")
memories = [self.normalize_content(content)]
else:
# Use MarkItDown for documents and media
result = self.markdown.convert(input_path)
content = result.text_content
if not content:
raise ValueError("No content could be extracted from file")
chunks = self.chunker.chunk(content)
memories = [chunk.text.strip() if hasattr(chunk, 'text') else str(chunk).strip()
for chunk in chunks if chunk]
# Set metadata for file
if not metadata:
metadata = {}
metadata['file_type'] = file_ext.lstrip('.')
metadata['filename'] = os.path.basename(input_path)
else:
# Treat as raw text content only if no file extension
memories = [self.normalize_content(input_path)]
# Create progress display
progress = Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
BarColumn(),
TaskProgressColumn(),
transient=True
)
# Store memories with progress bar
all_results = []
with progress:
store_task = progress.add_task(f"Adding to Knowledge from {os.path.basename(input_path)}", total=len(memories))
for memory in memories:
if memory:
memory_result = self.store(memory, user_id=user_id, agent_id=agent_id,
run_id=run_id, metadata=metadata)
if memory_result:
all_results.extend(memory_result.get('results', []))
progress.advance(store_task)
return {'results': all_results, 'relations': []}
except Exception as e:
logger.error(f"Error processing input {input_path}: {str(e)}", exc_info=True)
raise
+4
View File
@@ -23,6 +23,10 @@ logging.basicConfig(
handlers=[RichHandler(rich_tracebacks=True)]
)
# Add these lines to suppress markdown parser debug logs
logging.getLogger('markdown_it').setLevel(logging.WARNING)
logging.getLogger('rich.markdown').setLevel(logging.WARNING)
# Global list to store error logs
error_logs = []
+1 -1
View File
@@ -15,7 +15,7 @@ try:
CHROMADB_AVAILABLE = True
except ImportError:
CHROMADB_AVAILABLE = False
logger.warning("To use memory features, please run: pip install \"praisonaiagents[memory]\"")
pass
try:
import mem0
+157 -76
View File
@@ -5,6 +5,8 @@ from pydantic import BaseModel
from ..agent.agent import Agent
from ..task.task import Task
from ..main import display_error, client
import csv
import os
class LoopItems(BaseModel):
items: List[Any]
@@ -62,46 +64,47 @@ class Process:
if prev_task and prev_task.result:
# Handle loop data
if current_task.task_type == "loop":
# create a loop manager Agent
loop_manager = Agent(
name="Loop Manager",
role="Loop data processor",
goal="Process loop data and convert it to list format",
backstory="Expert at handling loop data and converting it to proper format",
llm=self.manager_llm,
verbose=self.verbose,
markdown=True
)
# # create a loop manager Agent
# loop_manager = Agent(
# name="Loop Manager",
# role="Loop data processor",
# goal="Process loop data and convert it to list format",
# backstory="Expert at handling loop data and converting it to proper format",
# llm=self.manager_llm,
# verbose=self.verbose,
# markdown=True
# )
# get the loop data convert it to list using calling Agent class chat
loop_prompt = f"""
Process this data into a list format:
{prev_task.result.raw}
# # get the loop data convert it to list using calling Agent class chat
# loop_prompt = f"""
# Process this data into a list format:
# {prev_task.result.raw}
Return a JSON object with an 'items' array containing the items to process.
"""
if current_task.async_execution:
loop_data_str = await loop_manager.achat(
prompt=loop_prompt,
output_json=LoopItems
)
else:
loop_data_str = loop_manager.chat(
prompt=loop_prompt,
output_json=LoopItems
)
# Return a JSON object with an 'items' array containing the items to process.
# """
# if current_task.async_execution:
# loop_data_str = await loop_manager.achat(
# prompt=loop_prompt,
# output_json=LoopItems
# )
# else:
# loop_data_str = loop_manager.chat(
# prompt=loop_prompt,
# output_json=LoopItems
# )
try:
# The response will already be parsed into LoopItems model
loop_data[f"loop_{current_task.name}"] = {
"items": loop_data_str.items,
"index": 0,
"remaining": len(loop_data_str.items)
}
context += f"\nCurrent loop item: {loop_data_str.items[0]}"
except Exception as e:
display_error(f"Failed to process loop data: {e}")
context += f"\n{prev_name}: {prev_task.result.raw}"
# try:
# # The response will already be parsed into LoopItems model
# loop_data[f"loop_{current_task.name}"] = {
# "items": loop_data_str.items,
# "index": 0,
# "remaining": len(loop_data_str.items)
# }
# context += f"\nCurrent loop item: {loop_data_str.items[0]}"
# except Exception as e:
# display_error(f"Failed to process loop data: {e}")
# context += f"\n{prev_name}: {prev_task.result.raw}"
context += f"\n{prev_name}: {prev_task.result.raw}"
else:
context += f"\n{prev_name}: {prev_task.result.raw}"
@@ -144,13 +147,17 @@ Return a JSON object with an 'items' array containing the items to process.
next_task = None
if current_task and current_task.result:
if current_task.task_type in ["decision", "loop"]:
result = current_task.result.raw.lower()
# MINIMAL CHANGE: use pydantic decision if present
decision_str = current_task.result.raw.lower()
if current_task.result.pydantic and hasattr(current_task.result.pydantic, "decision"):
decision_str = current_task.result.pydantic.decision.lower()
# Check conditions
for condition, tasks in current_task.condition.items():
if condition.lower() in result:
if condition.lower() == decision_str:
# Handle both list and direct string values
task_value = tasks[0] if isinstance(tasks, list) else tasks
if not task_value or task_value == "exit": # If empty or explicit exit
if not task_value or task_value == "exit":
logging.info("Workflow exit condition met, ending workflow")
current_task = None
break
@@ -322,7 +329,76 @@ Provide a JSON with the structure:
if not start_task:
start_task = list(self.tasks.values())[0]
logging.info("No start task marked, using first task")
# If loop type and no input_file, default to tasks.csv
if start_task and start_task.task_type == "loop" and not start_task.input_file:
start_task.input_file = "tasks.csv"
# --- If loop + input_file, read file & create tasks
if start_task and start_task.task_type == "loop" and getattr(start_task, "input_file", None):
try:
file_ext = os.path.splitext(start_task.input_file)[1].lower()
new_tasks = []
if file_ext == ".csv":
# existing CSV reading logic
with open(start_task.input_file, "r", encoding="utf-8") as f:
# Try as simple CSV first
reader = csv.reader(f)
previous_task = None
for i, row in enumerate(reader):
if row: # Skip empty rows
task_desc = row[0] # Take first column
row_task = Task(
description=task_desc, # Keep full row as description
agent=start_task.agent,
name=task_desc, # Use first column as name
is_start=(i == 0),
task_type="task",
condition={
"complete": ["next"],
"retry": ["current"]
}
)
self.tasks[row_task.id] = row_task
new_tasks.append(row_task)
if previous_task:
previous_task.next_tasks = [row_task.name]
previous_task.condition["complete"] = [row_task.name]
previous_task = row_task
else:
# If not CSV, read lines
with open(start_task.input_file, "r", encoding="utf-8") as f:
lines = f.read().splitlines()
previous_task = None
for i, line in enumerate(lines):
row_task = Task(
description=line.strip(),
agent=start_task.agent,
name=line.strip(),
is_start=(i == 0),
task_type="task",
condition={
"complete": ["next"],
"retry": ["current"]
}
)
self.tasks[row_task.id] = row_task
new_tasks.append(row_task)
if previous_task:
previous_task.next_tasks = [row_task.name]
previous_task.condition["complete"] = [row_task.name]
previous_task = row_task
if new_tasks:
start_task = new_tasks[0]
logging.info(f"Created {len(new_tasks)} tasks from: {start_task.input_file}")
except Exception as e:
logging.error(f"Failed to read file tasks: {e}")
# end of the new block
current_task = start_task
visited_tasks = set()
loop_data = {} # Store loop-specific data
@@ -346,40 +422,41 @@ Provide a JSON with the structure:
if prev_task and prev_task.result:
# Handle loop data
if current_task.task_type == "loop":
# create a loop manager Agent
loop_manager = Agent(
name="Loop Manager",
role="Loop data processor",
goal="Process loop data and convert it to list format",
backstory="Expert at handling loop data and converting it to proper format",
llm=self.manager_llm,
verbose=self.verbose,
markdown=True
)
# # create a loop manager Agent
# loop_manager = Agent(
# name="Loop Manager",
# role="Loop data processor",
# goal="Process loop data and convert it to list format",
# backstory="Expert at handling loop data and converting it to proper format",
# llm=self.manager_llm,
# verbose=self.verbose,
# markdown=True
# )
# get the loop data convert it to list using calling Agent class chat
loop_prompt = f"""
Process this data into a list format:
{prev_task.result.raw}
# # get the loop data convert it to list using calling Agent class chat
# loop_prompt = f"""
# Process this data into a list format:
# {prev_task.result.raw}
Return a JSON object with an 'items' array containing the items to process.
"""
loop_data_str = loop_manager.chat(
prompt=loop_prompt,
output_json=LoopItems
)
# Return a JSON object with an 'items' array containing the items to process.
# """
# loop_data_str = loop_manager.chat(
# prompt=loop_prompt,
# output_json=LoopItems
# )
try:
# The response will already be parsed into LoopItems model
loop_data[f"loop_{current_task.name}"] = {
"items": loop_data_str.items,
"index": 0,
"remaining": len(loop_data_str.items)
}
context += f"\nCurrent loop item: {loop_data_str.items[0]}"
except Exception as e:
display_error(f"Failed to process loop data: {e}")
context += f"\n{prev_name}: {prev_task.result.raw}"
# try:
# # The response will already be parsed into LoopItems model
# loop_data[f"loop_{current_task.name}"] = {
# "items": loop_data_str.items,
# "index": 0,
# "remaining": len(loop_data_str.items)
# }
# context += f"\nCurrent loop item: {loop_data_str.items[0]}"
# except Exception as e:
# display_error(f"Failed to process loop data: {e}")
# context += f"\n{prev_name}: {prev_task.result.raw}"
context += f"\n{prev_name}: {prev_task.result.raw}"
else:
context += f"\n{prev_name}: {prev_task.result.raw}"
@@ -396,7 +473,7 @@ Return a JSON object with an 'items' array containing the items to process.
yield task_id
visited_tasks.add(task_id)
# Reset completed task to "not started" so it can run again
# Reset completed task to "not started" so it can run again: Only for workflow because some tasks may be revisited
if self.tasks[task_id].status == "completed":
logging.debug(f"Task {task_id} was completed, resetting to 'not started' for next iteration.")
self.tasks[task_id].status = "not started"
@@ -422,13 +499,17 @@ Return a JSON object with an 'items' array containing the items to process.
next_task = None
if current_task and current_task.result:
if current_task.task_type in ["decision", "loop"]:
result = current_task.result.raw.lower()
# MINIMAL CHANGE: use pydantic decision if present
decision_str = current_task.result.raw.lower()
if current_task.result.pydantic and hasattr(current_task.result.pydantic, "decision"):
decision_str = current_task.result.pydantic.decision.lower()
# Check conditions
for condition, tasks in current_task.condition.items():
if condition.lower() in result:
if condition.lower() == decision_str:
# Handle both list and direct string values
task_value = tasks[0] if isinstance(tasks, list) else tasks
if not task_value or task_value == "exit": # If empty or explicit exit
if not task_value or task_value == "exit":
logging.info("Workflow exit condition met, ending workflow")
current_task = None
break
+87 -4
View File
@@ -1,6 +1,6 @@
import logging
import asyncio
from typing import List, Optional, Dict, Any, Type, Callable, Union, Coroutine
from typing import List, Optional, Dict, Any, Type, Callable, Union, Coroutine, Literal
from pydantic import BaseModel
from ..main import TaskOutput
from ..agent.agent import Agent
@@ -19,7 +19,7 @@ class Task:
agent: Optional[Agent] = None,
name: Optional[str] = None,
tools: Optional[List[Any]] = None,
context: Optional[List["Task"]] = None,
context: Optional[List[Union[str, List, 'Task']]] = None,
async_execution: Optional[bool] = False,
config: Optional[Dict[str, Any]] = None,
output_file: Optional[str] = None,
@@ -37,8 +37,21 @@ class Task:
is_start: bool = False,
loop_state: Optional[Dict[str, Union[str, int]]] = None,
memory=None,
quality_check=True
quality_check=True,
input_file: Optional[str] = None
):
# Add check if memory config is provided
if memory is not None or (config and config.get('memory_config')):
try:
from ..memory.memory import Memory
MEMORY_AVAILABLE = True
except ImportError:
raise ImportError(
"Memory features requested in Task but memory dependencies not installed. "
"Please install with: pip install \"praisonaiagents[memory]\""
)
self.input_file = input_file
self.id = str(uuid.uuid4()) if id is None else str(id)
self.name = name
self.description = description
@@ -83,6 +96,47 @@ class Task:
# Track previous tasks based on next_tasks relationships
self.previous_tasks = []
# If task_type="decision" and output_pydantic is not set
if self.task_type == "decision" and not self.output_pydantic:
from pydantic import BaseModel
from typing import Literal
# Gather condition keys for the "decision" field
condition_keys = list(self.condition.keys())
if not condition_keys:
# Fall back to placeholders if nothing is specified
condition_keys = ["next_task", "exit"]
# Create a dynamic literal type from condition keys
DecisionLiteral = Literal.__getitem__(tuple(condition_keys))
class DecisionModel(BaseModel):
response: str
decision: DecisionLiteral
self.output_pydantic = DecisionModel
# If task_type="loop" and output_pydantic is not set
if self.task_type == "loop" and not self.output_pydantic:
from pydantic import BaseModel
from typing import Literal
# Gather condition keys for the "decision" field
condition_keys = list(self.condition.keys())
if not condition_keys:
# Fall back to placeholders if nothing is specified
condition_keys = ["next_item", "exit"]
# Create a dynamic literal type
LoopLiteral = Literal.__getitem__(tuple(condition_keys))
class LoopModel(BaseModel):
response: str
decision: LoopLiteral
loop_id: str # Additional field for loop
self.output_pydantic = LoopModel
def __str__(self):
return f"Task(name='{self.name if self.name else 'None'}', description='{self.description}', agent='{self.agent.name if self.agent else 'None'}', status='{self.status}')"
@@ -219,4 +273,33 @@ class Task:
self.callback(task_output)
except Exception as e:
logger.error(f"Task {self.id}: Failed to execute callback: {e}")
logger.exception(e)
logger.exception(e)
task_prompt = f"""
You need to do the following task: {self.description}.
Expected Output: {self.expected_output}.
"""
if self.context:
context_results = [] # Use list to avoid duplicates
for context_item in self.context:
if isinstance(context_item, str):
context_results.append(f"Input Content:\n{context_item}")
elif isinstance(context_item, list):
context_results.append(f"Input Content: {' '.join(str(x) for x in context_item)}")
elif hasattr(context_item, 'result'): # Task object
if context_item.result:
context_results.append(
f"Result of previous task {context_item.name if context_item.name else context_item.description}:\n{context_item.result.raw}"
)
else:
context_results.append(
f"Previous task {context_item.name if context_item.name else context_item.description} has no result yet."
)
# Join unique context results
unique_contexts = list(dict.fromkeys(context_results)) # Remove duplicates
task_prompt += f"""
Context:
{' '.join(unique_contexts)}
"""
+16 -3
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "praisonaiagents"
version = "0.0.36"
version = "0.0.46"
description = "Praison AI agents for completing complex tasks with Self Reflection Agents"
authors = [
{ name="Mervin Praison" }
@@ -17,5 +17,18 @@ dependencies = [
[project.optional-dependencies]
memory = [
"chromadb>=0.6.0"
]
"chromadb>=0.5.23"
]
knowledge = [
"mem0ai>=0.1.0",
"chromadb==0.5.23",
"markitdown",
"chonkie"
]
# Combined features
all = [
"praisonaiagents[memory]",
"praisonaiagents[knowledge]"
]
+22
View File
@@ -0,0 +1,22 @@
from praisonaiagents import Agent, Task, PraisonAIAgents
agent = Agent(
instructions="You are a loop agent that creating a loop of tasks.",
llm="gpt-4o-mini"
)
task = Task(
description="Create the list of tasks to be looped through.",
agent=agent,
task_type="loop",
input_file="tasks.csv"
)
agents = PraisonAIAgents(
agents=[agent],
tasks=[task],
process="workflow",
max_iter=30
)
agents.start()
+139
View File
@@ -0,0 +1,139 @@
from praisonaiagents import Agent, Task, PraisonAIAgents
from praisonaiagents.tools import read_csv, write_csv
import pandas as pd
def read_csv_smart(csv_path: str) -> pd.DataFrame:
"""Read CSV and use first column as task, handling both header/no-header cases"""
# Try reading with headers first
df = pd.read_csv(csv_path)
# Check if first row looks like data
if not any(col.lower() in ['task', 'description', 'status', 'state'] for col in df.columns):
# If no header-like names found, read without headers
df = pd.read_csv(csv_path, header=None)
# Rename columns consistently
df.columns = [*['task'], *[f'col_{i}' for i in range(1, len(df.columns))]]
if 'status' not in df.columns:
df['status'] = 'pending'
if 'loop_id' not in df.columns:
# Start loop_id from 1 instead of 0
df['loop_id'] = (df.index + 1).astype(str)
return df[['task', 'status', 'loop_id']]
def has_pending_tasks(df: pd.DataFrame) -> bool:
"""Check if there are any pending tasks in the DataFrame"""
return not df[df['status'] == 'pending'].empty
def check_task_status(csv_path: str) -> dict:
"""Read task status from CSV file"""
try:
# Always read directly from CSV file
df = pd.read_csv(csv_path, keep_default_na=False)
# Get only pending tasks from original status
pending_tasks = df[df['status'].str.lower() == 'pending']
if not pending_tasks.empty:
task_data = pending_tasks.iloc[0].to_dict()
return {
'has_pending': True,
'next_task': task_data
}
return {'has_pending': False, 'next_task': None}
except Exception as e:
print(f"Error reading CSV: {e}")
return {'has_pending': False, 'next_task': None, 'error': str(e)}
def get_next_task() -> dict:
"""Get the next pending task from CSV"""
status = check_task_status("tasks.csv")
if status['has_pending'] and status['next_task']:
task = status['next_task']
if task['status'].lower() == 'pending':
return {
'loop_data': {
'task': task['task'],
'loop_id': task['loop_id'],
'status': task['status']
}
}
return None
def update_task_status(loop_id: str, new_status: str) -> bool:
"""Update task status in CSV file using loop_id as identifier"""
try:
# Read directly from CSV file
df = pd.read_csv("tasks.csv", keep_default_na=False)
df['loop_id'] = df['loop_id'].astype(str)
mask = df['loop_id'] == str(loop_id)
if mask.any():
df.loc[mask, 'status'] = new_status
df.to_csv("tasks.csv", index=False)
return True
print(f"No task found with loop_id: {loop_id}")
return False
except Exception as e:
print(f"Error updating status: {e}")
return False
identify_agent = Agent(
name="Identify Agent",
role="Pending Task Identifier",
goal="Identify the next pending task",
tools=[get_next_task],
llm="gpt-4o-mini"
)
# Create the repetitive agent
repetitive_agent = Agent(
name="TaskProcessor",
role="Task Processing Specialist",
goal="Complete the task response",
llm="gpt-4o-mini"
)
update_status_agent = Agent(
name="UpdateStatusAgent",
role="Status Updater",
goal="Update the status of the task in CSV",
tools=[update_task_status],
llm="gpt-4o-mini"
)
# Define the repetitive task
identify_task = Task(
name="identify_task",
description="Identify the next pending task. If there are no pending tasks decision is completed.",
agent=identify_agent,
task_type="loop",
condition={
"pending": ["process_task"],
"completed": "exit"
}
)
process_task = Task(
name="process_task",
description="Complete the task mentioned in the response",
agent=repetitive_agent,
context=[identify_task],
task_type="loop",
next_tasks=["update_task"]
)
update_task = Task(
name="update_task",
description="Update the task status",
agent=update_status_agent,
next_tasks= ["identify_task"]
)
# Create and run agents manager
agents = PraisonAIAgents(
agents=[identify_agent, repetitive_agent],
tasks=[identify_task, process_task, update_task],
process="workflow"
)
agents.start()
+15
View File
@@ -0,0 +1,15 @@
# Core dependencies
pydantic
rich
openai>=1.30.0
# Memory dependencies
chromadb>=0.5.23
# Knowledge dependencies
mem0ai>=0.1.0
markitdown
chonkie
# Development dependencies
python-dotenv>=0.19.0
Binary file not shown.
+5
View File
@@ -0,0 +1,5 @@
# Sample Markdown
## Section 1
This is a test markdown file.
## Section 2
It contains some formatted text and sections.
+3
View File
@@ -0,0 +1,3 @@
This is a sample text file.
It contains multiple lines.
This is for testing purposes.
BIN
View File
Binary file not shown.
+21
View File
@@ -0,0 +1,21 @@
import streamlit as st
from praisonaiagents import Agent, Tools
from praisonaiagents.tools import duckduckgo
st.title("AI Research Assistant")
st.write("Enter your research query below to get started!")
# Initialize the research agent
agent = Agent(instructions="You are a Research Agent", tools=[duckduckgo])
# Create the input field
query = st.text_input("Research Query", placeholder="Enter your research topic...")
# Add a search button
if st.button("Search"):
if query:
with st.spinner("Researching..."):
result = agent.start(query)
st.write(result)
else:
st.warning("Please enter a research query")
View File
Whitespace-only changes.
+100
View File
@@ -0,0 +1,100 @@
Write a product description for a smartwatch in 2 lines.
Create a user manual for a blender in 2 lines.
Draft an apology email for delayed delivery in 2 lines.
Write a blog post on "Benefits of Meditation" in 2 lines.
Create a privacy policy for a website in 2 lines.
Write instructions for setting up a Wi-Fi router in 2 lines.
Draft an email to follow up after a job interview in 2 lines.
Create a FAQ page for an e-commerce store in 2 lines.
Write an invitation email for a webinar in 2 lines.
Create a terms and conditions page for an app in 2 lines.
Write a press release for a product launch in 2 lines.
Create a checklist for house cleaning tasks in 2 lines.
Draft a resignation letter template in 2 lines.
Write a cover letter for a software developer role in 2 lines.
Create onboarding instructions for new employees in 2 lines.
Write a memo announcing a new policy in a company in 2 lines.
Create a safety guidelines document for a workplace in 2 lines.
Write a pitch email to potential investors in 2 lines.
Draft a thank-you email for attending a conference in 2 lines.
Create a refund policy template for an online store in 2 lines.
Write a blog on "How to Improve Time Management" in 2 lines.
Create step-by-step instructions for changing a car tyre in 2 lines.
Write a welcome email for new subscribers in 2 lines.
Draft an event agenda template in 2 lines.
Create a code of conduct for an online forum in 2 lines.
Write a guide for beginners to start a blog in 2 lines.
Create a checklist for organising a party in 2 lines.
Draft an email to request a product review in 2 lines.
Write a policy for remote work in a company in 2 lines.
Create a simple tutorial for using Excel formulas in 2 lines.
Write a thank-you letter for a donation in 2 lines.
Draft a meeting minutes template in 2 lines.
Create an FAQ for a gym membership in 2 lines.
Write a blog post about "Healthy Snacks for Kids" in 2 lines.
Create a guide for securing your social media accounts in 2 lines.
Draft an email to request a testimonial from a client in 2 lines.
Write a safety checklist for camping trips in 2 lines.
Create a script for a customer service call in 2 lines.
Write a tutorial for creating a simple PowerPoint presentation in 2 lines.
Create a packing list for a beach vacation in 2 lines.
Draft an email to cancel a service subscription in 2 lines.
Write a personal statement for university admission in 2 lines.
Create a template for tracking monthly expenses in 2 lines.
Write a guide for planting and caring for succulents in 2 lines.
Create a simple user guide for a mobile app in 2 lines.
Draft an email to announce a team-building activity in 2 lines.
Write a step-by-step guide for baking a cake in 2 lines.
Create a list of house maintenance tasks in 2 lines.
Draft a partnership proposal email in 2 lines.
Write a guide for basic photography tips in 2 lines.
Create a feedback form template for an online course in 2 lines.
Write a blog on "Top 5 Budget Travel Destinations" in 2 lines.
Draft a letter of recommendation for a colleague in 2 lines.
Create a workout plan for beginners in 2 lines.
Write a guide for troubleshooting common tech issues in 2 lines.
Draft a reminder email for an upcoming appointment in 2 lines.
Create a guide for setting personal goals in 2 lines.
Write a blog post about "How to Start Freelancing" in 2 lines.
Create a template for event planning in 2 lines.
Draft an email to notify users about system maintenance in 2 lines.
Write a guide for choosing the right laptop in 2 lines.
Create a checklist for moving to a new house in 2 lines.
Draft an email to update a client on project status in 2 lines.
Write a guide for reducing screen time in 2 lines.
Create a shopping list template for weekly groceries in 2 lines.
Draft a thank-you email for completing a survey in 2 lines.
Write a blog on "Simple DIY Crafts for Beginners" in 2 lines.
Create a checklist for starting a small business in 2 lines.
Draft an email to apologise for a customer complaint in 2 lines.
Write a guide for setting up a personal budget in 2 lines.
Create a policy for using company-provided equipment in 2 lines.
Draft an email to notify about a price increase in 2 lines.
Write a tutorial for creating a resume using Word in 2 lines.
Create a simple guide for organising a charity event in 2 lines.
Draft a formal invitation letter for a conference in 2 lines.
Write a blog post about "Top Productivity Apps" in 2 lines.
Create a checklist for first-time pet owners in 2 lines.
Draft an email to confirm a service appointment in 2 lines.
Write a beginner’s guide for learning to code in 2 lines.
Create a guide for assembling a basic toolkit in 2 lines.
Draft a welcome email for a new team member in 2 lines.
Write a guide for preparing a home for winter in 2 lines.
Create a schedule template for meal planning in 2 lines.
Draft an email to request feedback from a customer in 2 lines.
Write a guide on "How to Build a Morning Routine" in 2 lines.
Create a checklist for hosting a virtual meeting in 2 lines.
Draft a newsletter for a non-profit organisation in 2 lines.
Write a guide for beginners to use Canva in 2 lines.
Create a guide for organising your workspace in 2 lines.
Draft an email to invite users to a beta program in 2 lines.
Write a step-by-step guide for creating a podcast in 2 lines.
Create a simple guide for buying your first car in 2 lines.
Draft an email to announce a new team member in 2 lines.
Write a tutorial on creating basic charts in Excel in 2 lines.
Create a guide for teaching basic first aid in 2 lines.
Draft an email to follow up after a sales call in 2 lines.
Write a blog post on "How to Save Money on Utilities" in 2 lines.
Create a guide for designing a basic website in 2 lines.
Draft a thank-you email for a business referral in 2 lines.
Write a guide for setting up a new smartphone in 2 lines.
Can't render this file because it contains an unexpected character in line 4 and column 22.
+919 -21
View File
File diff suppressed because it is too large. Load diff
+39
View File
@@ -0,0 +1,39 @@
from praisonaiagents import Agent, Task, PraisonAIAgents
# Define the configuration for the Knowledge instance
config = {
"vector_store": {
"provider": "chroma",
"config": {
"collection_name": "praison",
"path": ".praison"
}
}
}
# Create an agent
rag_agent = Agent(
name="RAG Agent",
role="Information Specialist",
goal="Retrieve knowledge efficiently",
llm="gpt-4o-mini"
)
# Define a task for the agent
rag_task = Task(
name="RAG Task",
description="What is KAG?",
expected_output="Answer to the question",
agent=rag_agent,
context=[config] # Vector Database provided as context
)
# Build Agents
agents = PraisonAIAgents(
agents=[rag_agent],
tasks=[rag_task],
user_id="user1"
)
# Start Agents
agents.start()
+124
View File
@@ -0,0 +1,124 @@
---
title: "AI Agents"
description: "Overview of all available PraisonAI agents and their capabilities"
icon: "robot"
---
PraisonAI provides a diverse set of specialized agents for various tasks. Each agent is designed with specific capabilities and tools to handle different types of tasks effectively.
```mermaid
graph LR
%% Define the main flow
Start([▶ Start]) --> Agent1
Agent1 --> Process[⚙ Process]
Process --> Agent2
Agent2 --> Output([✓ Output])
Process -.-> Agent1
%% Define subgraphs for agents and their tasks
subgraph Agent1[ ]
Task1[📋 Task]
AgentIcon1[🤖 AI Agent]
Tools1[🔧 Tools]
Task1 --- AgentIcon1
AgentIcon1 --- Tools1
end
subgraph Agent2[ ]
Task2[📋 Task]
AgentIcon2[🤖 AI Agent]
Tools2[🔧 Tools]
Task2 --- AgentIcon2
AgentIcon2 --- Tools2
end
classDef input fill:#8B0000,stroke:#7C90A0,color:#fff
classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
classDef tools fill:#2E8B57,stroke:#7C90A0,color:#fff
classDef transparent fill:none,stroke:none
class Start,Output,Task1,Task2 input
class Process,AgentIcon1,AgentIcon2 process
class Tools1,Tools2 tools
class Agent1,Agent2 transparent
```
## Data & Analysis
<CardGroup cols={2}>
<Card title="Data Analyst" icon="chart-line" href="/agents/data-analyst">
Analyze data from various sources, create visualizations, and generate insights.
</Card>
<Card title="Finance" icon="money-bill-trend-up" href="/agents/finance">
Track stocks, analyze financial data, and provide investment recommendations.
</Card>
<Card title="Research" icon="magnifying-glass-chart" href="/agents/research">
Conduct comprehensive research and analysis across various topics.
</Card>
<Card title="Wikipedia" icon="book" href="/agents/wikipedia">
Search and extract information from Wikipedia articles.
</Card>
</CardGroup>
## Media & Content
<CardGroup cols={2}>
<Card title="Image Analysis" icon="image" href="/agents/image">
Analyze and understand visual content from images.
</Card>
<Card title="Image to Text" icon="text" href="/agents/image-to-text">
Convert images to textual descriptions and extract text content.
</Card>
<Card title="Video" icon="video" href="/agents/video">
Analyze video content and extract meaningful information.
</Card>
<Card title="Markdown" icon="markdown" href="/agents/markdown">
Generate and format content in Markdown syntax.
</Card>
</CardGroup>
## Search & Recommendations
<CardGroup cols={2}>
<Card title="Web Search" icon="globe" href="/agents/websearch">
Perform intelligent web searches and gather information.
</Card>
<Card title="Recommendation" icon="thumbs-up" href="/agents/recommendation">
Generate personalized recommendations based on preferences.
</Card>
<Card title="Shopping" icon="shop" href="/agents/shopping">
Compare prices and find the best deals across stores.
</Card>
<Card title="Planning" icon="calendar" href="/agents/planning">
Create travel plans and detailed itineraries.
</Card>
</CardGroup>
## Development
<CardGroup cols={2}>
<Card title="Programming" icon="code" href="/agents/programming">
Write, analyze, and debug code across multiple languages.
</Card>
<Card title="Single Agent" icon="circle-1" href="/agents/single">
Simple, focused agent for basic tasks without external tools.
</Card>
</CardGroup>
## Getting Started
Each agent can be easily initialized and customized for your specific needs. Here's a basic example:
```python
from praisonaiagents import Agent
# Create an agent with specific instructions
agent = Agent(instructions="Your task-specific instructions")
# Start the agent with a task
response = agent.start("Your task description")
```
For more detailed information about each agent, click on the respective cards above.
+1 -1
View File
@@ -2,7 +2,7 @@
title: "Image to Text Agent"
sidebarTitle: "Image to Text"
description: "Learn how to create AI agents for converting images to textual descriptions and extracting text from images."
icon: "image-to-text"
icon: "text"
---
```mermaid
+1 -1
View File
@@ -2,7 +2,7 @@
title: "Shopping Agent"
sidebarTitle: "Shopping"
description: "Learn how to create AI agents for price comparison and shopping assistance."
icon: "shopping-cart"
icon: "shop"
---
```mermaid
+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.46 gunicorn markdown\n&#34;)
file.write(&#34;RUN pip install flask praisonai==2.0.55 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;)
+13 -27
View File
@@ -4,11 +4,8 @@ description: "Understanding Agents in PraisonAI"
icon: "user"
---
<Note>
Agents are the core building blocks of PraisonAI. Each agent is an autonomous AI entity with specific roles, goals, and capabilities.
</Note>
# Understanding Agents
Agents are the core building blocks of PraisonAI. Each agent is an autonomous AI entity with specific roles, goals, and capabilities.
```mermaid
graph LR
@@ -19,45 +16,34 @@ graph LR
Agent2 --> Output([✓ Output])
Process -.-> Agent1
%% Styling for main elements
style Start fill:#2D3047,stroke:#7C90A0,color:#fff
style Output fill:#2D3047,stroke:#7C90A0,color:#fff
style Process fill:#5C80BC,stroke:#7C90A0,color:#fff
%% Define subgraphs for agents and their tasks
subgraph Agent1[" "]
subgraph Agent1[ ]
Task1[📋 Task]
AgentIcon1[🤖 AI Agent]
Tools1[🔧 Tools]
Task1 --- AgentIcon1
AgentIcon1 --- Tools1
style Task1 fill:#2D3047,stroke:#7C90A0,color:#fff
style AgentIcon1 fill:#5C80BC,stroke:#7C90A0,color:#fff
style Tools1 fill:#2D3047,stroke:#7C90A0,color:#fff
end
subgraph Agent2[" "]
subgraph Agent2[ ]
Task2[📋 Task]
AgentIcon2[🤖 AI Agent]
Tools2[🔧 Tools]
Task2 --- AgentIcon2
AgentIcon2 --- Tools2
style Task2 fill:#2D3047,stroke:#7C90A0,color:#fff
style AgentIcon2 fill:#5C80BC,stroke:#7C90A0,color:#fff
style Tools2 fill:#2D3047,stroke:#7C90A0,color:#fff
end
%% Style for agent containers
style Agent1 fill:#1B1F3B,stroke:#7C90A0,color:#fff
style Agent2 fill:#1B1F3B,stroke:#7C90A0,color:#fff
%% Global styles
classDef default fill:#2D3047,stroke:#7C90A0,color:#fff
linkStyle default stroke:#7C90A0,stroke-width:2px
classDef input fill:#8B0000,stroke:#7C90A0,color:#fff
classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
classDef tools fill:#2E8B57,stroke:#7C90A0,color:#fff
classDef transparent fill:none,stroke:none
class Start,Output,Task1,Task2 input
class Process,AgentIcon1,AgentIcon2 process
class Tools1,Tools2 tools
class Agent1,Agent2 transparent
```
## Key Components
+241
View File
@@ -0,0 +1,241 @@
---
title: "AI Agents with Knowledge"
sidebarTitle: "Knowledge"
description: "Learn how to create AI agents with custom knowledge bases"
icon: "book"
---
```mermaid
flowchart LR
subgraph In[Input]
PDF[PDF]
TXT[TXT]
MD[MD]
end
subgraph Router[Vector Store]
DB[(Vector DB)]
end
subgraph Out[Agents]
A1[Agent 1]
A2[Agent 2]
A3[Agent 3]
end
In --> Router
Router --> A1
Router --> A2
Router --> A3
style In fill:#8B0000,color:#fff
style Router fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
| Feature | [Knowledge](/concepts/knowledge) | [Memory](/concepts/memory) |
|---------|--------------------------------|---------------------------|
| When Used | Pre-loaded before agent execution | Created and updated during runtime |
| Purpose | Provide static reference information | Store dynamic context and interactions |
| Storage | Read-only knowledge base | Read-write memory store |
| Persistence | Permanent until explicitly changed | Can be temporary (STM) or persistent (LTM) |
| Updates | Manual updates through knowledge files | Automatic updates during agent execution |
## Quick Start
<Steps>
<Step title="Install Package">
Install PraisonAI Agents with knowledge support:
```bash
pip install "praisonaiagents[knowledge]"
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key:
```bash
export OPENAI_API_KEY=xxxxx
```
</Step>
<Step title="Create Script">
Create a new file `app.py`:
```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?")
```
</Step>
</Steps>
## Basic Usage
The simplest way to create a knowledge-based agent is without any configuration:
```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?")
```
## Multi-Agent Knowledge System
For more complex scenarios, you can create a knowledge-based system with multiple agents:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
import logging
import os
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
# Define the configuration for the Knowledge instance
config = {
"vector_store": {
"provider": "chroma",
"config": {
"collection_name": "knowledge_test",
"path": ".praison",
}
}
}
# Create an agent with knowledge capabilities
knowledge_agent = Agent(
name="KnowledgeAgent",
role="Information Specialist",
goal="Store and retrieve knowledge efficiently",
backstory="Expert in managing and utilizing stored knowledge",
knowledge=["sample.pdf"],
knowledge_config=config,
verbose=True
)
# Define a task for the agent
knowledge_task = Task(
name="knowledge_task",
description="Who is Mervin Praison?",
expected_output="Answer to the question",
agent=knowledge_agent
)
# Create and start the agents
agents = PraisonAIAgents(
agents=[knowledge_agent],
tasks=[knowledge_task],
process="sequential",
user_id="user1"
)
# Start execution
result = agents.start()
```
## Understanding Knowledge Configuration
<AccordionGroup>
<Accordion title="Vector Store Options">
- **Provider**: Choose between different vector store backends (e.g., "chroma")
- **Collection Name**: Name for your knowledge collection
- **Path**: Location to store the vector database
</Accordion>
<Accordion title="Supported File Types">
- PDF documents (*.pdf)
- Text files (*.txt)
- Markdown files (*.md, *.mdx)
- And more...
</Accordion>
<Accordion title="Multi-Agent Setup">
- **Role**: Define specialized roles for knowledge agents
- **Goal**: Set specific knowledge management objectives
- **Process**: Choose between sequential or parallel execution
</Accordion>
</AccordionGroup>
## Features
<CardGroup cols={2}>
<Card title="Custom Knowledge" icon="book">
Import your own documents and data as knowledge sources
</Card>
<Card title="Vector Storage" icon="database">
Efficient storage and retrieval of knowledge embeddings
</Card>
<Card title="Multiple Sources" icon="layer-group">
Combine multiple documents and file types
</Card>
<Card title="Persistent Storage" icon="hard-drive">
Save and reuse knowledge bases across sessions
</Card>
</CardGroup>
## Best Practices
1. **Document Preparation**
- Clean and well-formatted documents work best
- Break large documents into smaller chunks
- Use consistent formatting
2. **Knowledge Organization**
- Group related documents together
- Use meaningful file names
- Keep knowledge bases focused and relevant
3. **Performance Optimization**
- Monitor vector store size
- Clean up unused collections
- Use appropriate chunk sizes
4. **Multi-Agent Coordination**
- Define clear roles and responsibilities
- Set appropriate logging levels for debugging
- Use unique collection names for different agent groups
## Next Steps
- Learn about [Memory Management](/concepts/memory) for long-term recall
- Explore [Tool Integration](/concepts/tools) for enhanced capabilities
- Check out [Examples](/examples) for implementation ideas
+43 -12
View File
@@ -5,6 +5,48 @@ description: "Learn how to create AI agents with memory capabilities for maintai
icon: "brain"
---
```mermaid
flowchart TB
subgraph Memory
direction TB
STM[Short Term]
LTM[Long Term]
end
subgraph Store
direction TB
DB[(Vector DB)]
end
Input[Input] ---> Agents
subgraph Agents
direction LR
A1[Agent 1]
A2[Agent 2]
A3[Agent 3]
end
Agents ---> Output[Output]
Memory <--> Store
Store <--> A1
Store <--> A2
Store <--> A3
style Memory fill:#189AB4,color:#fff
style Store fill:#2E8B57,color:#fff
style Agents fill:#8B0000,color:#fff
style Input fill:#8B0000,color:#fff
style Output fill:#8B0000,color:#fff
```
| Feature | [Knowledge](/concepts/knowledge) | [Memory](/concepts/memory) |
|---------|--------------------------------|---------------------------|
| When Used | Pre-loaded before agent execution | Created and updated during runtime |
| Purpose | Provide static reference information | Store dynamic context and interactions |
| Storage | Read-only knowledge base | Read-write memory store |
| Persistence | Permanent until explicitly changed | Can be temporary (STM) or persistent (LTM) |
| Updates | Manual updates through knowledge files | Automatic updates during agent execution |
## Quick Start
<Tabs>
@@ -396,16 +438,6 @@ PraisonAI's memory system includes several types of memory:
- Semantic search capabilities with RAG
- Quality-based storage decisions
</Card>
<Card title="Entity Memory" icon="diagram-project">
- Store information about specific entities
- Track relationships and attributes
- Specialized search for entity information
</Card>
<Card title="User Memory" icon="user">
- Store user-specific information
- Personalized context for each user
- Persistent across sessions
</Card>
</CardGroup>
### Memory Quality Control
@@ -437,5 +469,4 @@ results = agents.memory.search_long_term(
query="search query",
min_quality=0.8, # Only return high-quality matches
limit=5 # Maximum number of results
)
```
)
+78
View File
@@ -36,6 +36,24 @@ Process types in PraisonAI define how tasks are executed and how agents collabor
## Sequential Process
```mermaid
graph LR
Input[Input] --> A1
subgraph Agents
direction LR
A1[Agent 1] --> A2[Agent 2] --> A3[Agent 3]
end
A3 --> Output[Output]
classDef input fill:#8B0000,stroke:#7C90A0,color:#fff
classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
classDef transparent fill:none,stroke:none
class Input,Output input
class A1,A2,A3 process
class Agents transparent
```
The simplest form of task execution where tasks are performed one after another.
<Card>
@@ -57,6 +75,39 @@ The simplest form of task execution where tasks are performed one after another.
## Hierarchical Process
```mermaid
graph TB
Input[Input] --> Manager
subgraph Agents
Manager[Manager Agent]
subgraph Workers
direction LR
W1[Worker 1]
W2[Worker 2]
W3[Worker 3]
end
Manager --> W1
Manager --> W2
Manager --> W3
end
W1 --> Manager
W2 --> Manager
W3 --> Manager
Manager --> Output[Output]
classDef input fill:#8B0000,stroke:#7C90A0,color:#fff
classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
classDef transparent fill:none,stroke:none
class Input,Output input
class Manager,W1,W2,W3 process
class Agents,Workers transparent
```
Uses a manager agent to coordinate task execution and agent assignments.
<Card>
@@ -79,6 +130,33 @@ Uses a manager agent to coordinate task execution and agent assignments.
## Workflow Process
```mermaid
graph LR
Input[Input] --> Start
subgraph Workflow
direction LR
Start[Start] --> C1{Condition}
C1 --> |Yes| A1[Agent 1]
C1 --> |No| A2[Agent 2]
A1 --> Join
A2 --> Join
Join --> A3[Agent 3]
end
A3 --> Output[Output]
classDef input fill:#8B0000,stroke:#7C90A0,color:#fff
classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
classDef decision fill:#2E8B57,stroke:#7C90A0,color:#fff
classDef transparent fill:none,stroke:none
class Input,Output input
class Start,A1,A2,A3,Join process
class C1 decision
class Workflow transparent
```
Advanced process type supporting complex task relationships and conditional execution.
<Card>
+30 -3
View File
@@ -4,9 +4,36 @@ description: "Understanding Tasks in PraisonAI"
icon: "list-check"
---
<Note>
Tasks are the fundamental units of work in PraisonAI, defining what needs to be done, how it should be done, and who should do it.
</Note>
# Understanding Tasks
Tasks are units of work that agents execute. Each task has a clear goal, input requirements, and expected outputs.
```mermaid
graph LR
Input[Input] ---> Task
subgraph Task
direction LR
Role[Role]
Goal[Goal]
Story[Backstory]
Expected[Expected Output]
Role --> Goal
Goal --> Story
Story --> Expected
end
Task ---> Output[Output]
classDef input fill:#8B0000,stroke:#7C90A0,color:#fff
classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
classDef tools fill:#2E8B57,stroke:#7C90A0,color:#fff
classDef transparent fill:none,stroke:none
class Input,Output input
class Role,Goal,Story,Expected process
class Task transparent
```
## Core Components
+41 -4
View File
@@ -1,12 +1,49 @@
---
title: "Tools"
description: "Understanding Tools in PraisonAI"
title: "AI Agents with Tools"
sidebarTitle: "Tools"
description: "Learn how to create AI agents that can use tools to interact with external systems and perform actions."
icon: "screwdriver-wrench"
---
# Understanding Tools
```mermaid
flowchart TB
subgraph Tools
direction TB
T3[Internet Search]
T1[Code Execution]
T2[Formatting]
end
Tools in PraisonAI are functions that agents can use to interact with external systems, perform computations, or access data. They extend the capabilities of agents beyond just language processing.
Input[Input] ---> Agents
subgraph Agents
direction LR
A1[Agent 1]
A2[Agent 2]
A3[Agent 3]
end
Agents ---> Output[Output]
T3 --> A1
T1 --> A2
T2 --> A3
style Tools fill:#189AB4,color:#fff
style Agents fill:#8B0000,color:#fff
style Input fill:#8B0000,color:#fff
style Output fill:#8B0000,color:#fff
```
| Feature | [Knowledge](/concepts/knowledge) | [Tools](/concepts/tools) |
|---------|--------------------------------|---------------------------|
| Purpose | Static reference information | Dynamic interaction capabilities |
| Access | Read-only reference | Execute actions and commands |
| Updates | Manual through files | Real-time through tool calls |
| Storage | Knowledge base | Assigned to specific agents |
| Persistence | Permanent until changed | Available during agent execution |
## Quick Start
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.
## Creating Custom Tool
<Steps>
-109
View File
@@ -1,109 +0,0 @@
---
title: "Examples"
sidebarTitle: "Examples"
description: "Explore real-world examples and use cases built with PraisonAI Agents."
icon: "code"
---
## Use Cases
<CardGroup cols={2}>
<Card
title="Predictive Maintenance"
icon="wrench"
href="/usecases/predictive-maintenance"
>
Learn how to create AI agents for predictive maintenance and equipment monitoring.
</Card>
<Card
title="Emergency Response"
icon="truck-medical"
href="/usecases/emergency-response"
>
Learn how to create AI agents for coordinated emergency response and resource management.
</Card>
<Card
title="Code Review"
icon="code"
href="/usecases/code-review"
>
Learn how to create AI agents for automated code review and issue resolution.
</Card>
<Card
title="Adaptive Learning"
icon="graduation-cap"
href="/usecases/adaptive-learning"
>
Learn how to create AI agents for personalized adaptive learning experiences.
</Card>
<Card
title="Supply Chain"
icon="truck"
href="/usecases/supply-chain"
>
Learn how to create AI agents for supply chain risk management and mitigation.
</Card>
<Card
title="Customer Service"
icon="headset"
href="/usecases/customer-service"
>
Learn how to create AI agents for automated customer service and support.
</Card>
<Card
title="Fraud Detection"
icon="shield-check"
href="/usecases/fraud-detection"
>
Learn how to create AI agents for real-time fraud detection and alert management.
</Card>
<Card
title="Healthcare Diagnosis"
icon="stethoscope"
href="/usecases/healthcare-diagnosis"
>
Learn how to create AI agents for medical diagnosis and treatment recommendations.
</Card>
<Card
title="Smart City"
icon="city"
href="/usecases/smart-city"
>
Learn how to create AI agents for smart city resource optimization and management.
</Card>
<Card
title="Multilingual Content"
icon="language"
href="/usecases/multilingual-content"
>
Learn how to create AI agents for multilingual content generation and cultural adaptation.
</Card>
</CardGroup>
## What's Next?
<CardGroup cols={2}>
<Card
title="Features"
icon="stars"
href="/features/promptchaining"
>
Explore advanced features like prompt chaining and parallel execution
</Card>
<Card
title="API Reference"
icon="code"
href="/api-reference"
>
View the complete API reference documentation
</Card>
</CardGroup>
File renamed without changes.
+297
View File
@@ -0,0 +1,297 @@
---
title: "Climate Impact"
description: "Learn how to create AI agents for climate impact analysis and adaptation strategies."
icon: "cloud-sun"
---
```mermaid
flowchart LR
In[In] --> Monitor[Environmental Monitor]
Monitor --> Urban[Urban Analyzer]
Urban --> Climate[Climate Modeler]
Climate --> Impact[Impact Predictor]
Impact --> Strategy[Strategy Generator]
Strategy --> Out[Out]
style In fill:#8B0000,color:#fff
style Monitor fill:#2E8B57,color:#fff
style Urban fill:#2E8B57,color:#fff
style Climate fill:#2E8B57,color:#fff
style Impact fill:#2E8B57,color:#fff
style Strategy fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
## What is Climate Impact Analysis?
Climate Impact Analysis is a systematic process of collecting environmental data, analyzing urban factors, modeling microclimates, predicting impacts, and generating adaptation strategies. This helps cities and communities understand and prepare for climate change effects, ensuring sustainable urban development and public health.
## Features
<CardGroup cols={2}>
<Card title="Environmental Monitoring" icon="temperature-high">
Collection of temperature, humidity, and air quality data with trend analysis.
</Card>
<Card title="Urban Analysis" icon="city">
Assessment of building density, green spaces, traffic flow, and heat islands.
</Card>
<Card title="Climate Modeling" icon="chart-line">
Microclimate modeling for different urban locations with temperature and air quality impacts.
</Card>
<Card title="Impact Prediction" icon="chart-mixed">
Prediction of health impacts, energy consumption, and livability scores.
</Card>
<Card title="Adaptation Strategies" icon="leaf">
Generation of location-specific strategies for climate adaptation.
</Card>
</CardGroup>
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</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:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
import time
from typing import Dict, List
import asyncio
def collect_environmental_data():
"""Simulates environmental data collection"""
data = {
"temperature": {
"current": 25 + (time.time() % 10),
"historical": [24, 25, 26, 24, 23],
"trend": "increasing"
},
"humidity": {
"current": 60 + (time.time() % 20),
"historical": [65, 62, 58, 63, 61],
"trend": "stable"
},
"air_quality": {
"pm25": 35 + (time.time() % 15),
"co2": 415 + (time.time() % 30),
"trend": "deteriorating"
}
}
return data
def analyze_urban_factors():
"""Simulates urban environment analysis"""
factors = {
"building_density": 75 + (time.time() % 20),
"green_spaces": 25 + (time.time() % 10),
"traffic_flow": {
"peak_hours": [8, 17],
"congestion_level": "high"
},
"heat_islands": [
{"location": "downtown", "intensity": "high"},
{"location": "industrial", "intensity": "medium"}
]
}
return factors
def model_microclimate(env_data: Dict, urban_factors: Dict):
"""Models microclimate conditions"""
models = []
locations = ["downtown", "residential", "industrial", "parks"]
for location in locations:
models.append({
"location": location,
"temperature_delta": 2 + (time.time() % 3),
"air_quality_impact": "moderate" if "park" in location else "significant",
"humidity_variation": 5 + (time.time() % 5)
})
return models
def predict_impacts(models: List[Dict]):
"""Predicts climate impacts"""
predictions = []
for model in models:
predictions.append({
"location": model["location"],
"health_impact": "high" if model["air_quality_impact"] == "significant" else "medium",
"energy_consumption": {
"cooling_need": model["temperature_delta"] * 10,
"trend": "increasing" if model["temperature_delta"] > 2.5 else "stable"
},
"livability_score": 70 - (model["temperature_delta"] * 5)
})
return predictions
def generate_adaptation_strategies(predictions: List[Dict]):
"""Generates adaptation strategies"""
strategies = []
for pred in predictions:
if pred["health_impact"] == "high":
strategies.append({
"location": pred["location"],
"actions": [
"increase_green_spaces",
"traffic_reduction",
"building_retrofitting"
],
"priority": "immediate",
"cost_estimate": "high"
})
else:
strategies.append({
"location": pred["location"],
"actions": [
"tree_planting",
"cool_roofs"
],
"priority": "medium",
"cost_estimate": "moderate"
})
return strategies
# Create specialized agents
environmental_monitor = Agent(
name="Environmental Monitor",
role="Data Collection",
goal="Collect environmental data",
instructions="Monitor and collect climate data",
tools=[collect_environmental_data]
)
urban_analyzer = Agent(
name="Urban Analyzer",
role="Urban Analysis",
goal="Analyze urban environment",
instructions="Assess urban factors affecting climate",
tools=[analyze_urban_factors]
)
climate_modeler = Agent(
name="Climate Modeler",
role="Climate Modeling",
goal="Model microclimate conditions",
instructions="Create detailed climate models",
tools=[model_microclimate]
)
impact_predictor = Agent(
name="Impact Predictor",
role="Impact Analysis",
goal="Predict climate impacts",
instructions="Assess potential climate impacts",
tools=[predict_impacts]
)
strategy_generator = Agent(
name="Strategy Generator",
role="Strategy Development",
goal="Generate adaptation strategies",
instructions="Develop climate adaptation strategies",
tools=[generate_adaptation_strategies]
)
# Create workflow tasks
monitoring_task = Task(
name="collect_data",
description="Collect environmental data",
expected_output="Environmental measurements",
agent=environmental_monitor,
is_start=True,
next_tasks=["analyze_urban"]
)
urban_task = Task(
name="analyze_urban",
description="Analyze urban factors",
expected_output="Urban analysis",
agent=urban_analyzer,
next_tasks=["model_climate"]
)
modeling_task = Task(
name="model_climate",
description="Model microclimate",
expected_output="Climate models",
agent=climate_modeler,
context=[monitoring_task, urban_task],
next_tasks=["predict_impacts"]
)
prediction_task = Task(
name="predict_impacts",
description="Predict climate impacts",
expected_output="Impact predictions",
agent=impact_predictor,
next_tasks=["generate_strategies"]
)
strategy_task = Task(
name="generate_strategies",
description="Generate adaptation strategies",
expected_output="Adaptation strategies",
agent=strategy_generator,
task_type="decision",
condition={
"immediate": ["collect_data"], # Continuous monitoring for high priority
"medium": "", # End workflow for medium priority
"low": "" # End workflow for low priority
}
)
# Create workflow
workflow = PraisonAIAgents(
agents=[environmental_monitor, urban_analyzer, climate_modeler,
impact_predictor, strategy_generator],
tasks=[monitoring_task, urban_task, modeling_task,
prediction_task, strategy_task],
process="workflow",
verbose=True
)
async def main():
print("\nStarting Climate Impact Prediction Workflow...")
print("=" * 50)
# Run workflow
results = await workflow.astart()
# Print results
print("\nClimate Impact Analysis Results:")
print("=" * 50)
for task_id, result in results["task_results"].items():
if result:
print(f"\nTask: {task_id}")
print(f"Result: {result.raw}")
print("-" * 50)
if __name__ == "__main__":
asyncio.run(main())
```
</Step>
</Steps>
## Next Steps
<CardGroup>
<Card title="Introduction" icon="book" href="/introduction">
Learn more about PraisonAI and its core concepts
</Card>
<Card title="Quick Start" icon="bolt" href="/quickstart">
Get started with the basics of PraisonAI
</Card>
</CardGroup>
+203
View File
@@ -0,0 +1,203 @@
---
title: "Code Analysis Agent"
description: "Learn how to create AI agents for comprehensive code analysis and quality assessment."
icon: "code-merge"
---
```mermaid
flowchart LR
In[In] --> Analyzer[Code Analyzer]
Analyzer --> Quality[Quality Assessment]
Quality --> Metrics[Core Metrics]
Metrics --> Technical[Technical Review]
Technical --> Recommendations[Recommendations]
Recommendations --> Out[Out]
style In fill:#8B0000,color:#fff
style Analyzer fill:#2E8B57,color:#fff
style Quality fill:#2E8B57,color:#fff
style Metrics fill:#2E8B57,color:#fff
style Technical fill:#2E8B57,color:#fff
style Recommendations fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
## What is Code Analysis?
Code Analysis is a systematic process of evaluating source code to assess its quality, maintainability, performance, and security. This helps developers and organizations maintain high code standards and identify areas for improvement.
## Features
<CardGroup cols={2}>
<Card title="Quality Assessment" icon="chart-simple">
Comprehensive evaluation of code quality with numerical scoring.
</Card>
<Card title="Core Metrics Analysis" icon="gauge">
Analysis of architecture, maintainability, performance, and security.
</Card>
<Card title="Technical Assessment" icon="code">
Review of tech stack, complexity, and best practices adherence.
</Card>
<Card title="Risk Assessment" icon="shield">
Identification of potential risks and security vulnerabilities.
</Card>
<Card title="Recommendations" icon="lightbulb">
Actionable suggestions for improvements and enhancements.
</Card>
</CardGroup>
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents gitingest
```
</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 `code_analysis.py` with the following code:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
from pydantic import BaseModel
from typing import List, Dict
from gitingest import ingest
class CodeMetrics(BaseModel):
category: str
score: int
findings: List[str]
class CodeAnalysisReport(BaseModel):
overall_quality: int
code_metrics: List[CodeMetrics]
architecture_score: int
maintainability_score: int
performance_score: int
security_score: int
test_coverage: int
key_strengths: List[str]
improvement_areas: List[str]
tech_stack: List[str]
recommendations: List[str]
complexity_metrics: Dict[str, int]
best_practices: List[Dict[str, str]]
potential_risks: List[str]
documentation_quality: int
code_analyzer = Agent(
role="Code Analysis Expert",
goal="Provide comprehensive code evaluation and recommendations",
backstory="""Expert code analyst specializing in architecture review,
best practices, and technical debt assessment.""",
verbose=True
)
code_analysis_task = Task(
description="""Analyze code repository and provide structured evaluation:
1. Overall Quality (0-100)
2. Core Metrics Analysis:
- Architecture and Design
- Code Maintainability
- Performance Optimization
- Security Practices
- Test Coverage
3. Technical Assessment:
- Technology Stack Review
- Code Complexity Analysis
- Best Practices Adherence
- Risk Assessment
4. Recommendations:
- Key Improvements
- Architecture Suggestions
- Security Enhancements""",
expected_output="Detailed code analysis report with metrics and recommendations",
agent=code_analyzer,
output_pydantic=CodeAnalysisReport
)
def analyze_code(code_source: str) -> CodeAnalysisReport:
"""
Analyze code from directory path or GitHub URL
"""
# Ingest code content
summary, tree, content = ingest(code_source)
# Concatenate context into structured format
context_text = f"""
CODE REPOSITORY ANALYSIS
=======================
SUMMARY
-------
{summary}
REPOSITORY STRUCTURE
-------------------
{tree}
SOURCE CODE
-----------
{content}
"""
# Initialize and run analysis
agents = PraisonAIAgents(
agents=[code_analyzer],
tasks=[code_analysis_task]
)
return agents.start(context_text)
if __name__ == "__main__":
# Example usage
code_source = "https://github.com/openai/openai-python/tree/main/src/openai/cli/_api/chat" # GitHub URL or local directory
result = analyze_code(code_source)
print(result)
```
</Step>
</Steps>
## Understanding the Output
The code analysis generates a comprehensive report with the following components:
- Overall Quality Score (0-100)
- Core Metrics Analysis
- Architecture and Design Score
- Code Maintainability Score
- Performance Score
- Security Score
- Test Coverage Percentage
- Technical Assessment
- Technology Stack
- Complexity Metrics
- Best Practices Review
- Risk Assessment
- Recommendations
- Key Improvements
- Architecture Suggestions
- Security Enhancements
## Next Steps
<CardGroup>
<Card title="Introduction" icon="book" href="/introduction">
Learn more about PraisonAI and its core concepts
</Card>
<Card title="Quick Start" icon="bolt" href="/quickstart">
Get started with the basics of PraisonAI
</Card>
<Card title="API Reference" icon="code" href="/api-reference">
Explore the complete API documentation
</Card>
</CardGroup>
File renamed without changes.
+316
View File
@@ -0,0 +1,316 @@
---
title: "Crypto Validator"
description: "Learn how to create AI agents for post-quantum cryptographic scheme validation and security analysis."
icon: "key"
---
```mermaid
flowchart LR
In[In] --> Analyzer[Crypto Analyzer]
Analyzer --> Quantum[Attack Simulator]
Analyzer --> Perf[Performance Benchmarker]
Quantum --> Security[Implementation Assessor]
Perf --> Security
Security --> Compliance[Compliance Validator]
Compliance --> Out[Out]
style In fill:#8B0000,color:#fff
style Analyzer fill:#2E8B57,color:#fff
style Quantum fill:#2E8B57,color:#fff
style Perf fill:#2E8B57,color:#fff
style Security fill:#2E8B57,color:#fff
style Compliance fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
## What is Post-Quantum Cryptography?
Post-quantum cryptography focuses on developing cryptographic systems that are secure against both quantum and classical computers. This involves analyzing cryptographic schemes, simulating quantum attacks, and ensuring compliance with security standards.
## Features
<CardGroup cols={2}>
<Card title="Cryptographic Analysis" icon="shield-check">
Analyze quantum-resistant cryptographic schemes including lattice-based encryption and multivariate signatures.
</Card>
<Card title="Attack Simulation" icon="bug">
Test resistance against quantum attacks including Grover's algorithm and Shor's algorithm.
</Card>
<Card title="Performance Testing" icon="gauge-high">
Benchmark key generation, encryption/decryption speeds, and throughput metrics.
</Card>
<Card title="Security Assessment" icon="lock">
Evaluate implementation security including side-channel resistance and hardening measures.
</Card>
<Card title="Compliance Validation" icon="certificate">
Verify compliance with NIST PQC, Common Criteria, and FIPS standards.
</Card>
</CardGroup>
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</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:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
import time
from typing import Dict, List
import asyncio
def analyze_cryptographic_scheme():
"""Simulates cryptographic scheme analysis"""
schemes = [
{
"name": "lattice_based",
"type": "encryption",
"key_size": 2048,
"security_level": "AES-256 equivalent",
"parameters": {
"lattice_dimension": 1024,
"modulus": "q = 2^32 - 1",
"error_distribution": "discrete_gaussian"
}
},
{
"name": "multivariate",
"type": "signature",
"key_size": 4096,
"security_level": "SHA-384 equivalent",
"parameters": {
"variables": 128,
"equations": 128,
"field_size": "2^8"
}
}
]
return schemes[int(time.time()) % 2]
def simulate_quantum_attacks(scheme: Dict):
"""Simulates quantum attack scenarios"""
attacks = {
"grover_search": {
"effectiveness": "reduced",
"quantum_speedup": "quadratic",
"estimated_qubits": 2048,
"time_complexity": "O(2^n/2)"
},
"shor_algorithm": {
"effectiveness": "ineffective",
"quantum_speedup": "none",
"vulnerability": "resistant",
"classical_hardness": "maintained"
},
"quantum_hidden_subgroup": {
"effectiveness": "partial",
"applicability": "limited",
"mitigation": "parameter_adjustment"
}
}
return attacks
def benchmark_performance(scheme: Dict):
"""Benchmarks cryptographic performance"""
benchmarks = {
"key_generation": {
"time": 0.5 + (time.time() % 1) / 10, # seconds
"memory": 128 + (int(time.time()) % 64) # MB
},
"encryption_speed": {
"small_message": 0.001 + (time.time() % 1) / 1000, # seconds
"large_message": 0.1 + (time.time() % 1) / 10 # seconds
},
"decryption_speed": {
"small_message": 0.002 + (time.time() % 1) / 1000,
"large_message": 0.15 + (time.time() % 1) / 10
},
"throughput": {
"encryption": 100 + (int(time.time()) % 50), # MB/s
"decryption": 80 + (int(time.time()) % 40) # MB/s
}
}
return benchmarks
def assess_implementation(scheme: Dict, benchmarks: Dict):
"""Assesses implementation security"""
assessment = {
"side_channel_resistance": {
"timing_attacks": "protected",
"power_analysis": "partial_vulnerability",
"cache_attacks": "mitigated"
},
"implementation_hardening": {
"constant_time": True,
"memory_protection": True,
"error_handling": "secure"
},
"compiler_optimizations": {
"safety": "verified",
"performance_impact": -0.05 + (time.time() % 1) / 10
}
}
return assessment
def validate_compliance(scheme: Dict, assessment: Dict):
"""Validates compliance and standards"""
compliance = {
"nist_pqc": {
"status": "submitted",
"round": 3,
"requirements_met": True
},
"common_criteria": {
"evaluation_level": "EAL4+",
"protection_profile": "compliant"
},
"fips_140_3": {
"security_level": 3,
"validation_status": "in_process"
}
}
return compliance
# Create specialized agents
crypto_analyzer = Agent(
name="Crypto Analyzer",
role="Cryptographic Analysis",
goal="Analyze cryptographic schemes",
instructions="Evaluate quantum-resistant cryptographic schemes",
tools=[analyze_cryptographic_scheme]
)
attack_simulator = Agent(
name="Attack Simulator",
role="Attack Simulation",
goal="Simulate quantum attacks",
instructions="Test resistance against quantum attacks",
tools=[simulate_quantum_attacks]
)
performance_benchmarker = Agent(
name="Performance Benchmarker",
role="Performance Testing",
goal="Benchmark cryptographic performance",
instructions="Measure performance metrics",
tools=[benchmark_performance]
)
implementation_assessor = Agent(
name="Implementation Assessor",
role="Implementation Assessment",
goal="Assess implementation security",
instructions="Evaluate implementation security",
tools=[assess_implementation]
)
compliance_validator = Agent(
name="Compliance Validator",
role="Compliance Validation",
goal="Validate standards compliance",
instructions="Verify compliance with standards",
tools=[validate_compliance]
)
# Create workflow tasks
analysis_task = Task(
name="analyze_crypto",
description="Analyze cryptographic scheme",
expected_output="Cryptographic analysis",
agent=crypto_analyzer,
is_start=True,
next_tasks=["simulate_attacks", "benchmark_performance"]
)
attack_task = Task(
name="simulate_attacks",
description="Simulate quantum attacks",
expected_output="Attack simulation results",
agent=attack_simulator,
next_tasks=["assess_implementation"]
)
benchmark_task = Task(
name="benchmark_performance",
description="Benchmark performance",
expected_output="Performance benchmarks",
agent=performance_benchmarker,
next_tasks=["assess_implementation"]
)
assessment_task = Task(
name="assess_implementation",
description="Assess implementation",
expected_output="Implementation assessment",
agent=implementation_assessor,
context=[attack_task, benchmark_task],
next_tasks=["validate_compliance"]
)
compliance_task = Task(
name="validate_compliance",
description="Validate compliance",
expected_output="Compliance validation",
agent=compliance_validator,
task_type="decision",
condition={
"compliant": "", # End workflow if compliant
"non_compliant": ["assess_implementation"] # Reassess if non-compliant
}
)
# Create workflow
workflow = PraisonAIAgents(
agents=[crypto_analyzer, attack_simulator, performance_benchmarker,
implementation_assessor, compliance_validator],
tasks=[analysis_task, attack_task, benchmark_task,
assessment_task, compliance_task],
process="workflow",
verbose=True
)
async def main():
print("\nStarting Quantum-Resistant Cryptography Validation Workflow...")
print("=" * 50)
# Run workflow
results = await workflow.astart()
# Print results
print("\nCryptography Validation Results:")
print("=" * 50)
for task_id, result in results["task_results"].items():
if result:
print(f"\nTask: {task_id}")
print(f"Result: {result.raw}")
print("-" * 50)
if __name__ == "__main__":
asyncio.run(main())
```
</Step>
</Steps>
## Next Steps
<CardGroup>
<Card title="Introduction" icon="book" href="/introduction">
Learn more about PraisonAI and its core concepts
</Card>
<Card title="Quick Start" icon="bolt" href="/quickstart">
Get started with the basics of PraisonAI
</Card>
</CardGroup>
File renamed without changes.
+302
View File
@@ -0,0 +1,302 @@
---
title: "DeFi Market Maker"
description: "Learn how to create AI agents for decentralized finance market making and arbitrage."
icon: "chart-line"
---
```mermaid
flowchart LR
In[In] --> Market[Market Analyzer]
Market --> Arbitrage[Arbitrage Detector]
Market --> Liquidity[Liquidity Optimizer]
Arbitrage --> Risk[Risk Assessor]
Liquidity --> Risk
Risk --> Executor[Trade Executor]
Executor --> Out[Out]
style In fill:#8B0000,color:#fff
style Market fill:#2E8B57,color:#fff
style Arbitrage fill:#2E8B57,color:#fff
style Liquidity fill:#2E8B57,color:#fff
style Risk fill:#2E8B57,color:#fff
style Executor fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
## What is DeFi Market Making?
Decentralized Finance (DeFi) market making involves providing liquidity to decentralized exchanges and automatically executing trades to capture arbitrage opportunities. This requires real-time analysis of market conditions, optimization of liquidity positions, and risk management.
## Features
<CardGroup cols={2}>
<Card title="Market Analysis" icon="chart-candlestick">
Real-time analysis of liquidity pools, market volatility, trading volumes, and gas prices.
</Card>
<Card title="Arbitrage Detection" icon="magnifying-glass-dollar">
Identification of profitable trading opportunities across different liquidity pools.
</Card>
<Card title="Liquidity Optimization" icon="water">
Optimization of liquidity distribution and pool ratios for maximum efficiency.
</Card>
<Card title="Risk Assessment" icon="shield-halved">
Comprehensive risk analysis including impermanent loss and smart contract risks.
</Card>
<Card title="Trade Execution" icon="money-bill-transfer">
Automated execution of optimized trades with performance monitoring.
</Card>
</CardGroup>
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</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:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
import time
from typing import Dict, List
import asyncio
def analyze_market_conditions():
"""Simulates market analysis"""
conditions = {
"liquidity_pools": {
"pool_A": {
"token_0": {"balance": 1000000, "price": 1.0},
"token_1": {"balance": 500000, "price": 2.0},
"total_value_locked": 2000000
},
"pool_B": {
"token_0": {"balance": 800000, "price": 1.0},
"token_1": {"balance": 400000, "price": 2.0},
"total_value_locked": 1600000
}
},
"market_volatility": 0.15 + (time.time() % 10) / 100,
"trading_volume_24h": 5000000 + (time.time() % 1000000),
"gas_prices": 50 + (time.time() % 30)
}
return conditions
def detect_arbitrage():
"""Simulates arbitrage opportunity detection"""
opportunities = [
{
"path": ["pool_A", "pool_B"],
"profit_potential": 0.02 + (time.time() % 5) / 100,
"required_capital": 10000,
"execution_cost": 50,
"risk_level": "low"
},
{
"path": ["pool_B", "pool_C"],
"profit_potential": 0.03 + (time.time() % 5) / 100,
"required_capital": 20000,
"execution_cost": 75,
"risk_level": "medium"
}
]
return opportunities[int(time.time()) % 2]
def optimize_liquidity(market_conditions: Dict):
"""Optimizes liquidity distribution"""
optimizations = {
"pool_A": {
"target_ratio": 2.0,
"suggested_actions": [
{
"action": "rebalance",
"token": "token_1",
"amount": 10000,
"direction": "add"
}
],
"expected_improvement": 0.05
},
"pool_B": {
"target_ratio": 1.8,
"suggested_actions": [
{
"action": "rebalance",
"token": "token_0",
"amount": 5000,
"direction": "remove"
}
],
"expected_improvement": 0.03
}
}
return optimizations
def assess_risks(arbitrage: Dict, optimizations: Dict):
"""Assesses potential risks"""
risk_assessment = {
"impermanent_loss_risk": 0.1 + (time.time() % 5) / 100,
"smart_contract_risk": "low",
"market_manipulation_risk": "medium" if arbitrage["profit_potential"] > 0.025 else "low",
"gas_price_risk": "high" if arbitrage["execution_cost"] > 60 else "medium",
"mitigation_strategies": [
"implement_slippage_protection",
"set_maximum_gas_price",
"use_multiple_liquidity_sources"
]
}
return risk_assessment
def execute_trades(arbitrage: Dict, risks: Dict):
"""Simulates trade execution"""
execution_results = {
"status": "success" if time.time() % 2 == 0 else "failed",
"executed_volume": arbitrage["required_capital"] * 0.95,
"actual_profit": arbitrage["profit_potential"] * 0.9,
"gas_used": arbitrage["execution_cost"] * 1.1,
"timestamp": time.time()
}
return execution_results
# Create specialized agents
market_analyzer = Agent(
name="Market Analyzer",
role="Market Analysis",
goal="Analyze market conditions",
instructions="Monitor and analyze DeFi market conditions",
tools=[analyze_market_conditions]
)
arbitrage_detector = Agent(
name="Arbitrage Detector",
role="Arbitrage Detection",
goal="Detect arbitrage opportunities",
instructions="Identify profitable trading opportunities",
tools=[detect_arbitrage]
)
liquidity_optimizer = Agent(
name="Liquidity Optimizer",
role="Liquidity Optimization",
goal="Optimize liquidity distribution",
instructions="Optimize pool liquidity ratios",
tools=[optimize_liquidity]
)
risk_assessor = Agent(
name="Risk Assessor",
role="Risk Assessment",
goal="Assess trading risks",
instructions="Evaluate potential risks and mitigation strategies",
tools=[assess_risks]
)
trade_executor = Agent(
name="Trade Executor",
role="Trade Execution",
goal="Execute optimized trades",
instructions="Execute trades based on analysis",
tools=[execute_trades]
)
# Create workflow tasks
market_task = Task(
name="analyze_market",
description="Analyze market conditions",
expected_output="Market analysis",
agent=market_analyzer,
is_start=True,
next_tasks=["detect_arbitrage", "optimize_liquidity"]
)
arbitrage_task = Task(
name="detect_arbitrage",
description="Detect arbitrage opportunities",
expected_output="Arbitrage opportunities",
agent=arbitrage_detector,
next_tasks=["assess_risks"]
)
liquidity_task = Task(
name="optimize_liquidity",
description="Optimize liquidity",
expected_output="Liquidity optimization",
agent=liquidity_optimizer,
context=[market_task],
next_tasks=["assess_risks"]
)
risk_task = Task(
name="assess_risks",
description="Assess trading risks",
expected_output="Risk assessment",
agent=risk_assessor,
context=[arbitrage_task, liquidity_task],
next_tasks=["execute_trades"]
)
execution_task = Task(
name="execute_trades",
description="Execute trades",
expected_output="Trade execution results",
agent=trade_executor,
task_type="decision",
condition={
"success": ["analyze_market"], # Continue monitoring if successful
"failed": ["optimize_liquidity"] # Reoptimize if failed
}
)
# Create workflow
workflow = PraisonAIAgents(
agents=[market_analyzer, arbitrage_detector, liquidity_optimizer,
risk_assessor, trade_executor],
tasks=[market_task, arbitrage_task, liquidity_task,
risk_task, execution_task],
process="workflow",
verbose=True
)
async def main():
print("\nStarting DeFi Market Making Workflow...")
print("=" * 50)
# Run workflow
results = await workflow.astart()
# Print results
print("\nMarket Making Results:")
print("=" * 50)
for task_id, result in results["task_results"].items():
if result:
print(f"\nTask: {task_id}")
print(f"Result: {result.raw}")
print("-" * 50)
if __name__ == "__main__":
asyncio.run(main())
```
</Step>
</Steps>
## Next Steps
<CardGroup>
<Card title="Introduction" icon="book" href="/introduction">
Learn more about PraisonAI and its core concepts
</Card>
<Card title="Quick Start" icon="bolt" href="/quickstart">
Get started with the basics of PraisonAI
</Card>
</CardGroup>
File renamed without changes.
+189
View File
@@ -0,0 +1,189 @@
---
title: "Examples"
sidebarTitle: "Examples"
description: "Explore real-world examples and use cases built with PraisonAI Agents."
icon: "code"
---
## Use Cases
<CardGroup cols={2}>
<Card
title="Predictive Maintenance"
icon="wrench"
href="/examples/predictive-maintenance"
>
Learn how to create AI agents for predictive maintenance and equipment monitoring.
</Card>
<Card
title="Emergency Response"
icon="truck-medical"
href="/examples/emergency-response"
>
Learn how to create AI agents for coordinated emergency response and resource management.
</Card>
<Card
title="Code Review"
icon="code"
href="/examples/code-review"
>
Learn how to create AI agents for automated code review and issue resolution.
</Card>
<Card
title="Adaptive Learning"
icon="graduation-cap"
href="/examples/adaptive-learning"
>
Learn how to create AI agents for personalized adaptive learning experiences.
</Card>
<Card
title="Supply Chain"
icon="truck"
href="/examples/supply-chain"
>
Learn how to create AI agents for supply chain risk management and mitigation.
</Card>
<Card
title="Customer Service"
icon="headset"
href="/examples/customer-service"
>
Learn how to create AI agents for automated customer service and support.
</Card>
<Card
title="Fraud Detection"
icon="shield-check"
href="/examples/fraud-detection"
>
Learn how to create AI agents for real-time fraud detection and alert management.
</Card>
<Card
title="Healthcare Diagnosis"
icon="stethoscope"
href="/examples/healthcare-diagnosis"
>
Learn how to create AI agents for medical diagnosis and treatment recommendations.
</Card>
<Card
title="Smart City"
icon="city"
href="/examples/smart-city"
>
Learn how to create AI agents for smart city resource optimization and management.
</Card>
<Card
title="Multilingual Content"
icon="language"
href="/examples/multilingual-content"
>
Learn how to create AI agents for multilingual content generation and cultural adaptation.
</Card>
<Card
title="Climate Impact"
icon="cloud-sun"
href="/examples/climate-impact"
>
Learn how to create AI agents for climate impact analysis and adaptation strategies.
</Card>
<Card
title="Space Mission"
icon="rocket"
href="/examples/space-mission"
>
Learn how to create AI agents for space mission planning and resource optimization.
</Card>
<Card
title="Neural Architecture"
icon="network-wired"
href="/examples/neural-architecture"
>
Learn how to create AI agents for neural architecture search and optimization.
</Card>
<Card
title="DeFi Market Maker"
icon="money-bill-trend-up"
href="/examples/defi-market-maker"
>
Learn how to create AI agents for decentralized finance market making and liquidity provision.
</Card>
<Card
title="Quantum Optimiser"
icon="atom"
href="/examples/quantum-optimiser"
>
Learn how to create AI agents for quantum computing optimization and algorithm design.
</Card>
<Card
title="Medicine Protocol"
icon="prescription-bottle-medical"
href="/examples/medicine-protocol"
>
Learn how to create AI agents for medical protocol optimization and drug discovery.
</Card>
<Card
title="Crypto Validator"
icon="key"
href="/examples/crypto-validator"
>
Learn how to create AI agents for cryptocurrency validation and blockchain security.
</Card>
<Card
title="Research Assistant"
icon="microscope"
href="/examples/research-assistant"
>
Learn how to create AI agents for research analysis and experiment design.
</Card>
<Card
title="Vulnerability Detection"
icon="shield-check"
href="/examples/vulnerability-detection"
>
Learn how to create AI agents for vulnerability detection and analysis.
</Card>
<Card
title="Healthcare Diagnosis"
icon="stethoscope"
href="/examples/healthcare-diagnosis"
>
Learn how to create AI agents for medical diagnosis and treatment recommendations.
</Card>
</CardGroup>
## What's Next?
<CardGroup cols={2}>
<Card
title="Features"
icon="stars"
href="/features/promptchaining"
>
Explore advanced features like prompt chaining and parallel execution
</Card>
<Card
title="API Reference"
icon="code"
href="/api-reference"
>
View the complete API reference documentation
</Card>
</CardGroup>
File renamed without changes.
+265
View File
@@ -0,0 +1,265 @@
---
title: "Hackathon Judge Agent"
description: "Learn how to create AI agents for evaluating hackathon projects through video demonstrations."
icon: "trophy"
---
```mermaid
flowchart LR
In[In] --> Judge[Hackathon Judge]
Judge --> Scores[Project Scores]
Scores --> Analysis[Detailed Analysis]
Analysis --> Feedback[Feedback]
Feedback --> Recommendations[Recommendations]
Recommendations --> Out[Out]
style In fill:#8B0000,color:#fff
style Judge fill:#2E8B57,color:#fff
style Scores fill:#2E8B57,color:#fff
style Analysis fill:#2E8B57,color:#fff
style Feedback fill:#2E8B57,color:#fff
style Recommendations fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
## What is Hackathon Project Evaluation?
Hackathon Project Evaluation is an automated process for assessing hackathon projects through video demonstrations. It provides comprehensive scoring across multiple dimensions including innovation, technical complexity, and presentation quality, helping organizers make informed decisions and providing valuable feedback to participants.
## Features
<CardGroup cols={2}>
<Card title="Project Scoring" icon="star">
Comprehensive scoring system across multiple dimensions (0-100).
</Card>
<Card title="Technical Analysis" icon="microchip">
Evaluation of technical complexity and implementation quality.
</Card>
<Card title="Innovation Assessment" icon="lightbulb">
Analysis of creativity and unique project features.
</Card>
<Card title="Market Analysis" icon="chart-line">
Assessment of market potential and scalability.
</Card>
<Card title="Detailed Feedback" icon="comments">
Constructive feedback and specific recommendations for improvement.
</Card>
</CardGroup>
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents opencv-python moviepy
```
</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 `hackathon_judge.py` with the following code:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
from pydantic import BaseModel
from typing import List, Dict
import os
import json
class ProjectEvaluation(BaseModel):
innovation_score: int # 0-100
technical_complexity: int # 0-100
presentation_quality: int # 0-100
user_experience: int # 0-100
completeness: int # 0-100
overall_score: int # 0-100
key_strengths: List[str]
areas_for_improvement: List[str]
notable_features: List[str]
technical_highlights: List[str]
recommendations: List[str]
market_potential: str
scalability_assessment: str
# Create Vision Analysis Agent
hackathon_judge = Agent(
name="HackathonJudge",
role="Technical Project Evaluator",
goal="Evaluate hackathon projects through video demonstrations",
backstory="""You are an experienced hackathon judge and technical expert.
You excel at evaluating innovation, technical implementation, and presentation quality.
You provide constructive feedback and identify both strengths and areas for improvement.""",
llm="gpt-4o-mini", # Using vision-capable model
self_reflect=False,
knowledge=""
)
def evaluate_project(video_path: str) -> ProjectEvaluation:
"""
Evaluate a hackathon project based on its video demonstration
"""
evaluation_task = Task(
name="project_evaluation",
description="""Analyze this hackathon project video demonstration and provide a comprehensive evaluation:
1. Score the following aspects (0-100):
- Innovation and Creativity
- Technical Complexity
- Presentation Quality
- User Experience
- Project Completeness
2. Identify:
- Key strengths and standout features
- Areas that could be improved
- Notable technical implementations
- Market potential and scalability
3. Provide:
- Specific recommendations for improvement
- Technical suggestions
- Potential future enhancements""",
expected_output="Detailed project evaluation with scores and feedback",
agent=hackathon_judge,
output_pydantic=ProjectEvaluation,
images=[video_path] # Video input for multimodal analysis
)
# Initialize and run evaluation
agents = PraisonAIAgents(
agents=[hackathon_judge],
tasks=[evaluation_task],
process="sequential",
verbose=True
)
response = agents.start()
try:
# If response contains task_results, extract the Pydantic model directly
if isinstance(response, dict) and 'task_results' in response:
task_output = response['task_results'][0]
if hasattr(task_output, 'pydantic'):
return task_output.pydantic
elif hasattr(task_output, 'raw'):
# Extract JSON from raw string if it's wrapped in ```json
raw_text = task_output.raw
if raw_text.startswith('```json'):
raw_text = raw_text.split('\n', 1)[1].rsplit('\n', 1)[0]
evaluation_data = json.loads(raw_text)
else:
evaluation_data = json.loads(task_output) if isinstance(task_output, str) else task_output
# If response is a string, try to parse it as JSON
elif isinstance(response, str):
evaluation_data = json.loads(response)
# If response is a dict with task_status
elif isinstance(response, dict) and 'task_status' in response:
content = response['task_status']
if isinstance(content, dict):
evaluation_data = content
else:
evaluation_data = json.loads(content) if isinstance(content, str) else content
else:
evaluation_data = response
print(f"Debug - Parsed evaluation_data: {evaluation_data}")
# Create and return ProjectEvaluation instance
return ProjectEvaluation(
innovation_score=int(evaluation_data.get('innovation_score', 0)),
technical_complexity=int(evaluation_data.get('technical_complexity', 0)),
presentation_quality=int(evaluation_data.get('presentation_quality', 0)),
user_experience=int(evaluation_data.get('user_experience', 0)),
completeness=int(evaluation_data.get('completeness', 0)),
overall_score=int(evaluation_data.get('overall_score', 0)),
key_strengths=evaluation_data.get('key_strengths', []),
areas_for_improvement=evaluation_data.get('areas_for_improvement', []),
notable_features=evaluation_data.get('notable_features', []),
technical_highlights=evaluation_data.get('technical_highlights', []),
recommendations=evaluation_data.get('recommendations', []),
market_potential=str(evaluation_data.get('market_potential', '')),
scalability_assessment=str(evaluation_data.get('scalability_assessment', ''))
)
except Exception as e:
print(f"Debug - Raw response: {response}")
print(f"Error processing response: {e}")
raise
if __name__ == "__main__":
# Example usage
current_dir = os.path.dirname(os.path.abspath(__file__))
video_path = os.path.join(current_dir, "presentation.mp4")
result = evaluate_project(video_path) # Now returns ProjectEvaluation directly
print("\nHackathon Project Evaluation")
print("===========================")
print(f"\nOverall Score: {result.overall_score}/100")
print("\nDetailed Scores:")
print(f"Innovation: {result.innovation_score}/100")
print(f"Technical Complexity: {result.technical_complexity}/100")
print(f"Presentation: {result.presentation_quality}/100")
print(f"User Experience: {result.user_experience}/100")
print(f"Completeness: {result.completeness}/100")
print("\nKey Strengths:")
for strength in result.key_strengths:
print(f"- {strength}")
print("\nAreas for Improvement:")
for area in result.areas_for_improvement:
print(f"- {area}")
print("\nTechnical Highlights:")
for highlight in result.technical_highlights:
print(f"- {highlight}")
print("\nRecommendations:")
for rec in result.recommendations:
print(f"- {rec}")
print(f"\nMarket Potential: {result.market_potential}")
print(f"\nScalability Assessment: {result.scalability_assessment}")
```
</Step>
</Steps>
## Understanding the Output
The hackathon project evaluation generates a comprehensive report with the following components:
- Scoring Metrics (0-100)
- Innovation Score
- Technical Complexity
- Presentation Quality
- User Experience
- Project Completeness
- Overall Score
- Qualitative Analysis
- Key Strengths
- Areas for Improvement
- Notable Features
- Technical Highlights
- Strategic Assessment
- Recommendations
- Market Potential
- Scalability Assessment
## Next Steps
<CardGroup>
<Card title="Introduction" icon="book" href="/introduction">
Learn more about PraisonAI and its core concepts
</Card>
<Card title="Quick Start" icon="bolt" href="/quickstart">
Get started with the basics of PraisonAI
</Card>
<Card title="API Reference" icon="code" href="/api-reference">
Explore the complete API documentation
</Card>
</CardGroup>
+300
View File
@@ -0,0 +1,300 @@
---
title: "Medicine Protocol"
description: "Learn how to create AI agents for personalized medicine protocol generation and analysis."
icon: "stethoscope"
---
```mermaid
flowchart LR
In[In] --> Genetic[Genetic Analyzer]
In --> History[Patient History]
Genetic --> Interaction[Drug Interaction]
History --> Interaction
Interaction --> Protocol[Protocol Generator]
Protocol --> Simulation[Effectiveness Simulator]
Simulation --> Out[Out]
style In fill:#8B0000,color:#fff
style Genetic fill:#2E8B57,color:#fff
style History fill:#2E8B57,color:#fff
style Interaction fill:#2E8B57,color:#fff
style Protocol fill:#2E8B57,color:#fff
style Simulation fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
## What is Personalized Medicine?
Personalized medicine is an approach that tailors medical treatment to individual characteristics of each patient. It involves analyzing genetic markers, patient history, and drug interactions to create optimized treatment protocols.
## Features
<CardGroup cols={2}>
<Card title="Genetic Analysis" icon="dna">
Deep analysis of genetic markers including metabolism genes, risk factors, and drug response markers.
</Card>
<Card title="Patient History" icon="notes-medical">
Comprehensive evaluation of medical conditions, medications, allergies, and family history.
</Card>
<Card title="Drug Interaction" icon="pills">
Analysis of potential drug interactions based on genetic data and patient history.
</Card>
<Card title="Protocol Generation" icon="file-medical">
Creation of personalized treatment protocols with dosage adjustments and monitoring plans.
</Card>
<Card title="Treatment Simulation" icon="chart-line">
Prediction of treatment effectiveness, side effects, and adherence probability.
</Card>
</CardGroup>
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</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:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
import time
from typing import Dict, List
import asyncio
def analyze_genetic_markers():
"""Simulates genetic marker analysis"""
markers = {
"metabolism_genes": {
"CYP2D6": "rapid_metabolizer",
"CYP2C19": "normal_metabolizer",
"DPYD": "poor_metabolizer"
},
"risk_factors": {
"cardiovascular": "elevated",
"diabetes": "low",
"autoimmune": "moderate"
},
"drug_response_markers": {
"TPMT": "high_sensitivity",
"HLA-B*5701": "negative",
"UGT1A1": "normal"
}
}
return markers
def evaluate_patient_history():
"""Simulates patient history evaluation"""
history = {
"conditions": [
{"name": "hypertension", "duration": "5_years", "severity": "moderate"},
{"name": "arthritis", "duration": "2_years", "severity": "mild"}
],
"medications": [
{"name": "lisinopril", "response": "good", "side_effects": "minimal"},
{"name": "methotrexate", "response": "moderate", "side_effects": "mild"}
],
"allergies": ["penicillin", "sulfa"],
"family_history": ["diabetes", "heart_disease"]
}
return history
def analyze_drug_interactions(genetic_data: Dict, patient_history: Dict):
"""Analyzes potential drug interactions"""
interactions = []
medications = [med["name"] for med in patient_history["medications"]]
for med in medications:
interactions.append({
"medication": med,
"genetic_impact": "significant" if genetic_data["metabolism_genes"]["CYP2D6"] == "rapid_metabolizer" else "normal",
"risk_level": "high" if med in patient_history["allergies"] else "low",
"monitoring_needed": True if genetic_data["metabolism_genes"]["DPYD"] == "poor_metabolizer" else False
})
return interactions
def generate_protocol(genetic_data: Dict, interactions: List[Dict]):
"""Generates treatment protocol"""
protocol = {
"primary_treatment": {
"medication": "custom_formulation_A",
"dosage": "adjusted_based_on_metabolism",
"frequency": "twice_daily",
"monitoring": {
"type": "blood_levels",
"frequency": "weekly"
}
},
"alternatives": [
{
"medication": "custom_formulation_B",
"conditions": ["genetic_compatibility", "no_interactions"]
}
],
"precautions": []
}
if genetic_data["metabolism_genes"]["CYP2D6"] == "rapid_metabolizer":
protocol["precautions"].append("increase_monitoring_frequency")
if any(i["risk_level"] == "high" for i in interactions):
protocol["precautions"].append("alternative_medication_needed")
return protocol
def simulate_effectiveness(protocol: Dict):
"""Simulates treatment effectiveness"""
simulation = {
"efficacy_prediction": 0.85 + (time.time() % 2) / 10,
"side_effect_risk": 0.15 + (time.time() % 1) / 10,
"adherence_probability": 0.9 + (time.time() % 1) / 10,
"expected_outcomes": [
"symptom_reduction_80_percent",
"minimal_side_effects",
"good_tolerance"
]
}
return simulation
# Create specialized agents
genetic_analyzer = Agent(
name="Genetic Analyzer",
role="Genetic Analysis",
goal="Analyze genetic markers",
instructions="Evaluate genetic markers and variants",
tools=[analyze_genetic_markers]
)
history_analyzer = Agent(
name="History Analyzer",
role="History Analysis",
goal="Analyze patient history",
instructions="Evaluate medical history and conditions",
tools=[evaluate_patient_history]
)
interaction_analyzer = Agent(
name="Interaction Analyzer",
role="Drug Interaction",
goal="Analyze drug interactions",
instructions="Evaluate potential drug interactions",
tools=[analyze_drug_interactions]
)
protocol_generator = Agent(
name="Protocol Generator",
role="Protocol Generation",
goal="Generate treatment protocol",
instructions="Create personalized treatment protocol",
tools=[generate_protocol]
)
effectiveness_simulator = Agent(
name="Effectiveness Simulator",
role="Treatment Simulation",
goal="Simulate treatment effectiveness",
instructions="Predict treatment outcomes",
tools=[simulate_effectiveness]
)
# Create workflow tasks
genetic_task = Task(
name="analyze_genetics",
description="Analyze genetic markers",
expected_output="Genetic analysis",
agent=genetic_analyzer,
is_start=True,
next_tasks=["analyze_history"]
)
history_task = Task(
name="analyze_history",
description="Analyze patient history",
expected_output="History analysis",
agent=history_analyzer,
next_tasks=["analyze_interactions"]
)
interaction_task = Task(
name="analyze_interactions",
description="Analyze drug interactions",
expected_output="Interaction analysis",
agent=interaction_analyzer,
context=[genetic_task, history_task],
next_tasks=["generate_protocol"]
)
protocol_task = Task(
name="generate_protocol",
description="Generate treatment protocol",
expected_output="Treatment protocol",
agent=protocol_generator,
context=[genetic_task, interaction_task],
next_tasks=["simulate_effectiveness"]
)
simulation_task = Task(
name="simulate_effectiveness",
description="Simulate treatment effectiveness",
expected_output="Effectiveness simulation",
agent=effectiveness_simulator,
task_type="decision",
condition={
"high": "", # End workflow if high effectiveness
"medium": ["generate_protocol"], # Adjust protocol if medium
"low": ["analyze_interactions"] # Reanalyze if low
}
)
# Create workflow
workflow = PraisonAIAgents(
agents=[genetic_analyzer, history_analyzer, interaction_analyzer,
protocol_generator, effectiveness_simulator],
tasks=[genetic_task, history_task, interaction_task,
protocol_task, simulation_task],
process="workflow",
verbose=True
)
async def main():
print("\nStarting Personalized Medicine Protocol Generation...")
print("=" * 50)
# Run workflow
results = await workflow.astart()
# Print results
print("\nProtocol Generation Results:")
print("=" * 50)
for task_id, result in results["task_results"].items():
if result:
print(f"\nTask: {task_id}")
print(f"Result: {result.raw}")
print("-" * 50)
if __name__ == "__main__":
asyncio.run(main())
```
</Step>
</Steps>
## Next Steps
<CardGroup>
<Card title="Introduction" icon="book" href="/introduction">
Learn more about PraisonAI and its core concepts
</Card>
<Card title="Quick Start" icon="bolt" href="/quickstart">
Get started with the basics of PraisonAI
</Card>
</CardGroup>
+284
View File
@@ -0,0 +1,284 @@
---
title: "Neural Architecture"
description: "Learn how to create AI agents for neural architecture search and optimization."
icon: "brain"
---
```mermaid
flowchart LR
In[In] --> Hardware[Hardware Analyzer]
Hardware --> Generator[Architecture Generator]
Generator --> Hyperparams[Hyperparameter Optimizer]
Hyperparams --> Performance[Performance Estimator]
Performance --> Deployment[Deployment Optimizer]
Deployment --> Out[Out]
style In fill:#8B0000,color:#fff
style Hardware fill:#2E8B57,color:#fff
style Generator fill:#2E8B57,color:#fff
style Hyperparams fill:#2E8B57,color:#fff
style Performance fill:#2E8B57,color:#fff
style Deployment fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
## What is Neural Architecture Search?
Neural Architecture Search (NAS) is an automated process for designing optimal neural network architectures. It involves analyzing hardware constraints, generating candidate architectures, optimizing hyperparameters, and configuring deployment settings to create efficient and performant models.
## Features
<CardGroup cols={2}>
<Card title="Hardware Analysis" icon="microchip">
Analysis of GPU memory, compute capability, bandwidth, and thermal constraints.
</Card>
<Card title="Architecture Generation" icon="diagram-project">
Creation of candidate architectures including transformers and CNNs with optimized structures.
</Card>
<Card title="Hyperparameter Tuning" icon="sliders">
Optimization of learning rates, batch sizes, optimizers, and regularization parameters.
</Card>
<Card title="Performance Estimation" icon="gauge-high">
Prediction of model accuracy, training time, memory requirements, and FLOPS.
</Card>
<Card title="Deployment Optimization" icon="rocket">
Configuration of quantization, pruning, and batching for efficient deployment.
</Card>
</CardGroup>
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</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:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
import time
from typing import Dict, List
import asyncio
def analyze_hardware_constraints():
"""Simulates hardware analysis"""
constraints = {
"gpu_memory": 16 * 1024, # MB
"compute_capability": "7.5",
"memory_bandwidth": 900, # GB/s
"tensor_cores": True,
"max_power_consumption": 300, # Watts
"thermal_limits": 85 # Celsius
}
return constraints
def generate_architecture_candidates():
"""Generates candidate architectures"""
candidates = [
{
"type": "transformer",
"layers": 12 + (int(time.time()) % 6),
"attention_heads": 8,
"embedding_dim": 512,
"estimated_params": 125_000_000
},
{
"type": "cnn",
"layers": 50 + (int(time.time()) % 50),
"filters": [64, 128, 256, 512],
"estimated_params": 25_000_000
}
]
return candidates[int(time.time()) % 2]
def optimize_hyperparameters(architecture: Dict):
"""Optimizes hyperparameters"""
optimization = {
"learning_rate": 0.001 + (time.time() % 9) / 10000,
"batch_size": 32 * (1 + int(time.time()) % 4),
"optimizer": "adam",
"weight_decay": 0.0001,
"dropout_rate": 0.1 + (time.time() % 3) / 10,
"activation": "gelu" if architecture["type"] == "transformer" else "relu"
}
return optimization
def estimate_performance(architecture: Dict, hyperparams: Dict):
"""Estimates model performance"""
performance = {
"estimated_accuracy": 0.85 + (time.time() % 10) / 100,
"estimated_training_time": {
"hours": 24 + (int(time.time()) % 24),
"gpu_hours": 96
},
"memory_requirements": {
"training": architecture["estimated_params"] * 4 / (1024 * 1024), # GB
"inference": architecture["estimated_params"] * 2 / (1024 * 1024) # GB
},
"flops_count": architecture["estimated_params"] * 2
}
return performance
def optimize_deployment(architecture: Dict, performance: Dict):
"""Optimizes deployment configuration"""
deployment = {
"quantization": {
"method": "dynamic",
"precision": "int8",
"estimated_speedup": 2.5
},
"pruning": {
"method": "magnitude",
"target_sparsity": 0.3,
"estimated_size_reduction": 0.6
},
"batching": {
"max_batch_size": 32,
"dynamic_batching": True
}
}
return deployment
# Create specialized agents
hardware_analyzer = Agent(
name="Hardware Analyzer",
role="Hardware Analysis",
goal="Analyze hardware constraints",
instructions="Evaluate available hardware resources",
tools=[analyze_hardware_constraints]
)
architecture_generator = Agent(
name="Architecture Generator",
role="Architecture Generation",
goal="Generate neural architectures",
instructions="Create candidate neural architectures",
tools=[generate_architecture_candidates]
)
hyperparameter_optimizer = Agent(
name="Hyperparameter Optimizer",
role="Hyperparameter Optimization",
goal="Optimize hyperparameters",
instructions="Find optimal hyperparameter settings",
tools=[optimize_hyperparameters]
)
performance_estimator = Agent(
name="Performance Estimator",
role="Performance Estimation",
goal="Estimate model performance",
instructions="Predict model performance metrics",
tools=[estimate_performance]
)
deployment_optimizer = Agent(
name="Deployment Optimizer",
role="Deployment Optimization",
goal="Optimize deployment settings",
instructions="Configure optimal deployment",
tools=[optimize_deployment]
)
# Create workflow tasks
hardware_task = Task(
name="analyze_hardware",
description="Analyze hardware constraints",
expected_output="Hardware analysis",
agent=hardware_analyzer,
is_start=True,
next_tasks=["generate_architecture"]
)
architecture_task = Task(
name="generate_architecture",
description="Generate architecture candidates",
expected_output="Architecture candidates",
agent=architecture_generator,
next_tasks=["optimize_hyperparameters"]
)
hyperparameter_task = Task(
name="optimize_hyperparameters",
description="Optimize hyperparameters",
expected_output="Hyperparameter settings",
agent=hyperparameter_optimizer,
context=[architecture_task],
next_tasks=["estimate_performance"]
)
performance_task = Task(
name="estimate_performance",
description="Estimate performance",
expected_output="Performance estimates",
agent=performance_estimator,
context=[architecture_task, hyperparameter_task],
next_tasks=["optimize_deployment"]
)
deployment_task = Task(
name="optimize_deployment",
description="Optimize deployment",
expected_output="Deployment configuration",
agent=deployment_optimizer,
context=[architecture_task, performance_task],
task_type="decision",
condition={
"success": ["generate_architecture"], # Try new architecture
"failure": ["optimize_hyperparameters"] # Reoptimize hyperparameters
}
)
# Create workflow
workflow = PraisonAIAgents(
agents=[hardware_analyzer, architecture_generator, hyperparameter_optimizer,
performance_estimator, deployment_optimizer],
tasks=[hardware_task, architecture_task, hyperparameter_task,
performance_task, deployment_task],
process="workflow",
verbose=True
)
async def main():
print("\nStarting Neural Architecture Search Workflow...")
print("=" * 50)
# Run workflow
results = await workflow.astart()
# Print results
print("\nArchitecture Search Results:")
print("=" * 50)
for task_id, result in results["task_results"].items():
if result:
print(f"\nTask: {task_id}")
print(f"Result: {result.raw}")
print("-" * 50)
if __name__ == "__main__":
asyncio.run(main())
```
</Step>
</Steps>
## Next Steps
<CardGroup>
<Card title="Introduction" icon="book" href="/introduction">
Learn more about PraisonAI and its core concepts
</Card>
<Card title="Quick Start" icon="bolt" href="/quickstart">
Get started with the basics of PraisonAI
</Card>
</CardGroup>
+279
View File
@@ -0,0 +1,279 @@
---
title: "Quantum Optimiser"
description: "Learn how to create AI agents for quantum circuit optimization and performance analysis."
icon: "atom"
---
```mermaid
flowchart LR
In[In] --> Analyzer[Circuit Analyzer]
Analyzer --> Finder[Optimization Finder]
Finder --> Optimizer[Circuit Optimizer]
Optimizer --> Benchmarker[Performance Benchmarker]
Benchmarker --> Validator[Results Validator]
Validator --> Out[Out]
style In fill:#8B0000,color:#fff
style Analyzer fill:#2E8B57,color:#fff
style Finder fill:#2E8B57,color:#fff
style Optimizer fill:#2E8B57,color:#fff
style Benchmarker fill:#2E8B57,color:#fff
style Validator fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
## What is Quantum Circuit Optimization?
Quantum circuit optimization is the process of improving quantum algorithms by reducing circuit depth, minimizing gate count, and enhancing execution efficiency while maintaining computational fidelity. This is crucial for making quantum algorithms practical on real quantum hardware.
## Features
<CardGroup cols={2}>
<Card title="Circuit Analysis" icon="microchip">
Deep analysis of quantum circuit metrics including depth, gate counts, and qubit usage.
</Card>
<Card title="Optimization Detection" icon="magnifying-glass">
Identification of optimization opportunities through gate reduction and parallel execution.
</Card>
<Card title="Performance Simulation" icon="gauge-high">
Simulation of optimization results with improvement metrics and success probabilities.
</Card>
<Card title="Benchmark Testing" icon="chart-line">
Comprehensive benchmarking of execution time, fidelity, and resource usage.
</Card>
<Card title="Result Validation" icon="check-double">
Validation of optimization results ensuring performance gains and fidelity maintenance.
</Card>
</CardGroup>
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</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:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
import time
from typing import Dict, List
import asyncio
def analyze_quantum_circuit():
"""Simulates quantum circuit analysis"""
circuit_metrics = {
"depth": 15 + (int(time.time()) % 10),
"gates": {
"single_qubit": 25 + (int(time.time()) % 15),
"two_qubit": 10 + (int(time.time()) % 8),
"measurement": 5 + (int(time.time()) % 3)
},
"qubits": 8 + (int(time.time()) % 4)
}
return circuit_metrics
def identify_optimization_opportunities(metrics: Dict):
"""Identifies potential optimization areas"""
opportunities = []
if metrics["depth"] > 20:
opportunities.append({
"type": "depth_reduction",
"potential": "high",
"technique": "parallel_gates"
})
if metrics["gates"]["two_qubit"] > 15:
opportunities.append({
"type": "gate_reduction",
"potential": "medium",
"technique": "gate_decomposition"
})
return opportunities
def simulate_optimization(opportunities: List[Dict]):
"""Simulates optimization results"""
results = []
for opt in opportunities:
improvement = {
"high": 0.3 + (time.time() % 2) / 10,
"medium": 0.2 + (time.time() % 2) / 10,
"low": 0.1 + (time.time() % 2) / 10
}
results.append({
"type": opt["type"],
"improvement": improvement[opt["potential"]],
"success_probability": 0.8 + (time.time() % 2) / 10
})
return results
def benchmark_performance(original: Dict, optimized: List[Dict]):
"""Benchmarks optimization performance"""
benchmarks = {
"execution_time": {
"original": 100 + (int(time.time()) % 50),
"optimized": 70 + (int(time.time()) % 30)
},
"fidelity": {
"original": 0.9 + (time.time() % 1) / 10,
"optimized": 0.85 + (time.time() % 1) / 10
},
"resource_usage": {
"original": original["qubits"],
"optimized": original["qubits"] - len(optimized)
}
}
return benchmarks
def validate_results(benchmarks: Dict):
"""Validates optimization results"""
validations = {
"performance_gain": (benchmarks["execution_time"]["original"] -
benchmarks["execution_time"]["optimized"]) /
benchmarks["execution_time"]["original"],
"fidelity_maintained": benchmarks["fidelity"]["optimized"] > 0.8,
"resource_efficient": benchmarks["resource_usage"]["optimized"] <
benchmarks["resource_usage"]["original"]
}
return validations
# Create specialized agents
circuit_analyzer = Agent(
name="Circuit Analyzer",
role="Circuit Analysis",
goal="Analyze quantum circuit structure",
instructions="Evaluate quantum circuit metrics",
tools=[analyze_quantum_circuit]
)
optimization_finder = Agent(
name="Optimization Finder",
role="Optimization Discovery",
goal="Identify optimization opportunities",
instructions="Find potential optimization techniques",
tools=[identify_optimization_opportunities]
)
optimizer = Agent(
name="Circuit Optimizer",
role="Circuit Optimization",
goal="Optimize quantum circuit",
instructions="Apply optimization techniques",
tools=[simulate_optimization]
)
benchmarker = Agent(
name="Performance Benchmarker",
role="Performance Analysis",
goal="Benchmark optimization results",
instructions="Measure performance improvements",
tools=[benchmark_performance]
)
validator = Agent(
name="Results Validator",
role="Validation",
goal="Validate optimization results",
instructions="Ensure optimization quality",
tools=[validate_results]
)
# Create workflow tasks
analysis_task = Task(
name="analyze_circuit",
description="Analyze quantum circuit",
expected_output="Circuit metrics",
agent=circuit_analyzer,
is_start=True,
next_tasks=["find_optimizations"]
)
optimization_task = Task(
name="find_optimizations",
description="Find optimization opportunities",
expected_output="Optimization opportunities",
agent=optimization_finder,
next_tasks=["optimize_circuit"]
)
optimization_execution_task = Task(
name="optimize_circuit",
description="Execute circuit optimization",
expected_output="Optimization results",
agent=optimizer,
next_tasks=["benchmark_performance"]
)
benchmark_task = Task(
name="benchmark_performance",
description="Benchmark optimization",
expected_output="Performance metrics",
agent=benchmarker,
next_tasks=["validate_results"],
context=[analysis_task, optimization_execution_task]
)
validation_task = Task(
name="validate_results",
description="Validate optimization results",
expected_output="Validation results",
agent=validator,
task_type="decision",
condition={
"True": "", # End workflow if validation passes
"False": ["find_optimizations"] # Retry optimization if validation fails
}
)
# Create workflow
workflow = PraisonAIAgents(
agents=[circuit_analyzer, optimization_finder, optimizer,
benchmarker, validator],
tasks=[analysis_task, optimization_task, optimization_execution_task,
benchmark_task, validation_task],
process="workflow",
verbose=True
)
async def main():
print("\nStarting Quantum Algorithm Optimization Workflow...")
print("=" * 50)
# Run workflow
results = await workflow.astart()
# Print results
print("\nOptimization Results:")
print("=" * 50)
for task_id, result in results["task_results"].items():
if result:
print(f"\nTask: {task_id}")
print(f"Result: {result.raw}")
print("-" * 50)
if __name__ == "__main__":
asyncio.run(main())
```
</Step>
</Steps>
## Next Steps
<CardGroup>
<Card title="Introduction" icon="book" href="/introduction">
Learn more about PraisonAI and its core concepts
</Card>
<Card title="Quick Start" icon="bolt" href="/quickstart">
Get started with the basics of PraisonAI
</Card>
</CardGroup>
+274
View File
@@ -0,0 +1,274 @@
---
title: "Research Assistant"
description: "Learn how to create AI agents for research analysis and experiment design."
icon: "microscope"
---
```mermaid
flowchart LR
In[In] --> Analyzer[Paper Analyzer]
Analyzer --> Gap[Gap Identifier]
Gap --> Designer[Experiment Designer]
Designer --> Validator[Methodology Validator]
Validator --> Impact[Impact Predictor]
Impact --> Out[Out]
style In fill:#8B0000,color:#fff
style Analyzer fill:#2E8B57,color:#fff
style Gap fill:#2E8B57,color:#fff
style Designer fill:#2E8B57,color:#fff
style Validator fill:#2E8B57,color:#fff
style Impact fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
## What is Research Analysis?
Research Analysis is a systematic process of analyzing scientific papers, identifying knowledge gaps, designing experiments, validating methodologies, and predicting research impact. This helps researchers make informed decisions about their research direction and experimental design.
## Features
<CardGroup cols={2}>
<Card title="Paper Analysis" icon="book">
Analysis of research papers with topic identification and impact assessment.
</Card>
<Card title="Gap Identification" icon="magnifying-glass">
Discovery of research gaps with significance and potential evaluation.
</Card>
<Card title="Experiment Design" icon="flask">
Creation of experimental methodologies with resource planning.
</Card>
<Card title="Methodology Validation" icon="check-double">
Validation of experimental design with statistical power and feasibility checks.
</Card>
<Card title="Impact Prediction" icon="chart-line">
Prediction of research impact with novelty and breakthrough probability.
</Card>
</CardGroup>
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</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:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
import time
from typing import Dict, List
import asyncio
def analyze_research_papers():
"""Simulates research paper analysis"""
papers = [
{
"topic": "quantum_computing",
"gaps": ["error_correction", "scalability"],
"methodology": "experimental",
"impact_factor": 8.5
},
{
"topic": "machine_learning",
"gaps": ["interpretability", "robustness"],
"methodology": "theoretical",
"impact_factor": 7.8
}
]
return papers[int(time.time()) % 2]
def identify_knowledge_gaps(papers: Dict):
"""Identifies research gaps"""
gaps = []
for gap in papers["gaps"]:
gaps.append({
"area": gap,
"significance": "high" if papers["impact_factor"] > 8 else "medium",
"research_potential": 0.8 + (time.time() % 2) / 10
})
return gaps
def design_experiment(gaps: List[Dict]):
"""Designs experimental methodology"""
experiments = []
for gap in gaps:
experiments.append({
"area": gap["area"],
"methodology": {
"type": "quantitative",
"duration": "3_months",
"resources_needed": ["equipment_A", "dataset_B"],
"expected_outcome": "validation_metrics"
},
"priority": gap["significance"]
})
return experiments
def validate_methodology(experiments: List[Dict]):
"""Validates experimental design"""
validations = []
for exp in experiments:
validations.append({
"area": exp["area"],
"statistical_power": 0.9 + (time.time() % 1) / 10,
"resource_feasibility": 0.8 + (time.time() % 1) / 10,
"ethical_compliance": True,
"recommendations": []
})
return validations
def predict_impact(experiments: List[Dict], validations: List[Dict]):
"""Predicts research impact"""
predictions = []
for exp, val in zip(experiments, validations):
predictions.append({
"area": exp["area"],
"potential_impact": val["statistical_power"] * 10,
"novelty_score": 0.7 + (time.time() % 3) / 10,
"breakthrough_probability": 0.5 + (time.time() % 4) / 10
})
return predictions
# Create specialized agents
paper_analyzer = Agent(
name="Paper Analyzer",
role="Research Analysis",
goal="Analyze research papers",
instructions="Review and analyze scientific papers",
tools=[analyze_research_papers]
)
gap_identifier = Agent(
name="Gap Identifier",
role="Gap Analysis",
goal="Identify knowledge gaps",
instructions="Identify research opportunities",
tools=[identify_knowledge_gaps]
)
experiment_designer = Agent(
name="Experiment Designer",
role="Experimental Design",
goal="Design research experiments",
instructions="Create experimental methodologies",
tools=[design_experiment]
)
methodology_validator = Agent(
name="Methodology Validator",
role="Validation",
goal="Validate experimental design",
instructions="Ensure methodology validity",
tools=[validate_methodology]
)
impact_predictor = Agent(
name="Impact Predictor",
role="Impact Analysis",
goal="Predict research impact",
instructions="Assess potential impact",
tools=[predict_impact]
)
# Create workflow tasks
analysis_task = Task(
name="analyze_papers",
description="Analyze research papers",
expected_output="Paper analysis results",
agent=paper_analyzer,
is_start=True,
next_tasks=["identify_gaps"]
)
gap_task = Task(
name="identify_gaps",
description="Identify knowledge gaps",
expected_output="Research gaps",
agent=gap_identifier,
next_tasks=["design_experiments"]
)
design_task = Task(
name="design_experiments",
description="Design experiments",
expected_output="Experimental designs",
agent=experiment_designer,
next_tasks=["validate_methodology"]
)
validation_task = Task(
name="validate_methodology",
description="Validate methodology",
expected_output="Validation results",
agent=methodology_validator,
next_tasks=["predict_impact"]
)
prediction_task = Task(
name="predict_impact",
description="Predict research impact",
expected_output="Impact predictions",
agent=impact_predictor,
task_type="decision",
condition={
"high": "", # End workflow if high impact
"medium": ["design_experiments"], # Refine if medium impact
"low": ["identify_gaps"] # Restart if low impact
},
context=[design_task, validation_task]
)
# Create workflow
workflow = PraisonAIAgents(
agents=[paper_analyzer, gap_identifier, experiment_designer,
methodology_validator, impact_predictor],
tasks=[analysis_task, gap_task, design_task,
validation_task, prediction_task],
process="workflow",
verbose=True
)
async def main():
print("\nStarting Research Assistant Workflow...")
print("=" * 50)
# Run workflow
results = await workflow.astart()
# Print results
print("\nResearch Analysis Results:")
print("=" * 50)
for task_id, result in results["task_results"].items():
if result:
print(f"\nTask: {task_id}")
print(f"Result: {result.raw}")
print("-" * 50)
if __name__ == "__main__":
asyncio.run(main())
```
</Step>
</Steps>
## Next Steps
<CardGroup>
<Card title="Introduction" icon="book" href="/introduction">
Learn more about PraisonAI and its core concepts
</Card>
<Card title="Quick Start" icon="bolt" href="/quickstart">
Get started with the basics of PraisonAI
</Card>
</CardGroup>
File renamed without changes.
+313
View File
@@ -0,0 +1,313 @@
---
title: "Space Mission"
description: "Learn how to create AI agents for space mission planning and resource optimization."
icon: "rocket"
---
```mermaid
flowchart LR
In[In] --> Mission[Mission Analyzer]
Mission --> Resources[Resource Calculator]
Resources --> Contingency[Contingency Planner]
Contingency --> Optimizer[Resource Optimizer]
Optimizer --> Simulator[Scenario Simulator]
Simulator --> Out[Out]
style In fill:#8B0000,color:#fff
style Mission fill:#2E8B57,color:#fff
style Resources fill:#2E8B57,color:#fff
style Contingency fill:#2E8B57,color:#fff
style Optimizer fill:#2E8B57,color:#fff
style Simulator fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
## What is Space Mission Planning?
Space Mission Planning is a complex process that involves analyzing mission parameters, calculating resource requirements, planning contingencies, optimizing resource allocation, and simulating various scenarios. This ensures the safety and success of space missions by carefully managing resources and preparing for potential emergencies.
## Features
<CardGroup cols={2}>
<Card title="Mission Analysis" icon="satellite">
Analysis of mission duration, crew size, orbital parameters, and objectives.
</Card>
<Card title="Resource Calculation" icon="calculator">
Computation of life support, power, and propellant requirements.
</Card>
<Card title="Contingency Planning" icon="shield">
Planning for power failures, life support malfunctions, and other emergencies.
</Card>
<Card title="Resource Optimization" icon="chart-line">
Optimization of resource allocation with buffers for contingencies.
</Card>
<Card title="Scenario Simulation" icon="vr-cardboard">
Simulation of nominal operations and emergency scenarios.
</Card>
</CardGroup>
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</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:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
import time
from typing import Dict, List
import asyncio
def analyze_mission_parameters():
"""Simulates mission parameter analysis"""
parameters = {
"duration": 180, # days
"crew_size": 4,
"orbital_parameters": {
"altitude": 400, # km
"inclination": 51.6, # degrees
"period": 92.68 # minutes
},
"mission_objectives": [
"scientific_research",
"satellite_deployment",
"space_station_maintenance"
]
}
return parameters
def calculate_resource_requirements(params: Dict):
"""Calculates required resources"""
requirements = {
"life_support": {
"oxygen": params["duration"] * params["crew_size"] * 0.84, # kg
"water": params["duration"] * params["crew_size"] * 2.5, # liters
"food": params["duration"] * params["crew_size"] * 1.8 # kg
},
"power": {
"daily_consumption": 30 + (params["crew_size"] * 5), # kWh
"peak_demand": 45 + (params["crew_size"] * 8), # kW
"backup_capacity": 72 # hours
},
"propellant": {
"main_engine": 2000, # kg
"attitude_control": 500, # kg
"reserve": 300 # kg
}
}
return requirements
def plan_contingencies(requirements: Dict):
"""Plans contingency scenarios"""
contingencies = [
{
"scenario": "power_failure",
"probability": 0.05,
"impact": "critical",
"resources_needed": {
"backup_power": requirements["power"]["daily_consumption"] * 3,
"repair_equipment": ["solar_panel_kit", "power_distribution_unit"]
}
},
{
"scenario": "life_support_malfunction",
"probability": 0.03,
"impact": "severe",
"resources_needed": {
"oxygen_reserve": requirements["life_support"]["oxygen"] * 0.2,
"repair_parts": ["filter_system", "pressure_regulators"]
}
}
]
return contingencies[int(time.time()) % 2]
def optimize_allocation(requirements: Dict, contingencies: Dict):
"""Optimizes resource allocation"""
allocation = {
"primary_resources": {
"life_support": {
"nominal": requirements["life_support"],
"buffer": 0.15 # 15% buffer
},
"power": {
"nominal": requirements["power"],
"buffer": 0.2 # 20% buffer
}
},
"contingency_resources": {
"type": contingencies["scenario"],
"allocation": contingencies["resources_needed"],
"priority": "high" if contingencies["impact"] == "critical" else "medium"
}
}
return allocation
def simulate_mission_scenarios(allocation: Dict):
"""Simulates various mission scenarios"""
scenarios = {
"nominal_operations": {
"success_rate": 0.95,
"resource_utilization": 0.85,
"efficiency_rating": 0.9
},
"emergency_scenarios": [
{
"type": "power_reduction",
"duration": 48, # hours
"impact": "moderate",
"resolution_success": 0.88
},
{
"type": "life_support_adjustment",
"duration": 24, # hours
"impact": "minor",
"resolution_success": 0.92
}
]
}
return scenarios
# Create specialized agents
mission_analyzer = Agent(
name="Mission Analyzer",
role="Mission Analysis",
goal="Analyze mission parameters",
instructions="Evaluate mission requirements and constraints",
tools=[analyze_mission_parameters]
)
resource_calculator = Agent(
name="Resource Calculator",
role="Resource Calculation",
goal="Calculate resource requirements",
instructions="Determine required resources for mission",
tools=[calculate_resource_requirements]
)
contingency_planner = Agent(
name="Contingency Planner",
role="Contingency Planning",
goal="Plan for contingencies",
instructions="Develop contingency scenarios and plans",
tools=[plan_contingencies]
)
resource_optimizer = Agent(
name="Resource Optimizer",
role="Resource Optimization",
goal="Optimize resource allocation",
instructions="Optimize resource distribution",
tools=[optimize_allocation]
)
scenario_simulator = Agent(
name="Scenario Simulator",
role="Scenario Simulation",
goal="Simulate mission scenarios",
instructions="Simulate various mission scenarios",
tools=[simulate_mission_scenarios]
)
# Create workflow tasks
mission_task = Task(
name="analyze_mission",
description="Analyze mission parameters",
expected_output="Mission parameters",
agent=mission_analyzer,
is_start=True,
next_tasks=["calculate_resources"]
)
resource_task = Task(
name="calculate_resources",
description="Calculate resource requirements",
expected_output="Resource requirements",
agent=resource_calculator,
next_tasks=["plan_contingencies"]
)
contingency_task = Task(
name="plan_contingencies",
description="Plan contingencies",
expected_output="Contingency plans",
agent=contingency_planner,
context=[resource_task],
next_tasks=["optimize_resources"]
)
optimization_task = Task(
name="optimize_resources",
description="Optimize resource allocation",
expected_output="Resource allocation",
agent=resource_optimizer,
context=[resource_task, contingency_task],
next_tasks=["simulate_scenarios"]
)
simulation_task = Task(
name="simulate_scenarios",
description="Simulate scenarios",
expected_output="Simulation results",
agent=scenario_simulator,
task_type="decision",
condition={
"nominal_operations": "", # End workflow if nominal
"emergency_scenarios": ["optimize_resources"] # Reoptimize if emergency
}
)
# Create workflow
workflow = PraisonAIAgents(
agents=[mission_analyzer, resource_calculator, contingency_planner,
resource_optimizer, scenario_simulator],
tasks=[mission_task, resource_task, contingency_task,
optimization_task, simulation_task],
process="workflow",
verbose=True
)
async def main():
print("\nStarting Space Mission Resource Optimization Workflow...")
print("=" * 50)
# Run workflow
results = await workflow.astart()
# Print results
print("\nResource Optimization Results:")
print("=" * 50)
for task_id, result in results["task_results"].items():
if result:
print(f"\nTask: {task_id}")
print(f"Result: {result.raw}")
print("-" * 50)
if __name__ == "__main__":
asyncio.run(main())
```
</Step>
</Steps>
## Next Steps
<CardGroup>
<Card title="Introduction" icon="book" href="/introduction">
Learn more about PraisonAI and its core concepts
</Card>
<Card title="Quick Start" icon="bolt" href="/quickstart">
Get started with the basics of PraisonAI
</Card>
</CardGroup>
File renamed without changes.
+277
View File
@@ -0,0 +1,277 @@
---
title: "Vulnerability Detection"
description: "Learn how to create AI agents for vulnerability detection and analysis."
icon: "shield-check"
---
```mermaid
flowchart LR
In[In] --> Scanner[Pattern Scanner]
Scanner --> Vector[Vector Analyzer]
Vector --> Simulator[Exploit Simulator]
Simulator --> Generator[Signature Generator]
Generator --> Validator[Finding Validator]
Validator --> Out[Out]
style In fill:#8B0000,color:#fff
style Scanner fill:#2E8B57,color:#fff
style Vector fill:#2E8B57,color:#fff
style Simulator fill:#2E8B57,color:#fff
style Generator fill:#2E8B57,color:#fff
style Validator fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
## What is Vulnerability Detection?
Vulnerability Detection is a systematic process of identifying, analyzing, and validating security vulnerabilities in code. It involves pattern scanning, attack vector analysis, exploitation simulation, signature generation, and finding validation to ensure robust security measures are in place.
## Features
<CardGroup cols={2}>
<Card title="Pattern Scanning" icon="magnifying-glass">
Detection of buffer overflows, SQL injections, and race conditions.
</Card>
<Card title="Attack Vector Analysis" icon="route">
Analysis of attack paths, complexity, and CVSS scores.
</Card>
<Card title="Exploit Simulation" icon="bug">
Simulation of exploitation attempts with success rate and detection time.
</Card>
<Card title="Signature Generation" icon="fingerprint">
Creation of vulnerability signatures with reliability metrics.
</Card>
<Card title="Finding Validation" icon="check-double">
Validation of findings with confidence and reproducibility scores.
</Card>
</CardGroup>
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</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:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
import time
from typing import Dict, List
import asyncio
def scan_code_patterns():
"""Simulates code pattern scanning"""
patterns = [
{
"type": "buffer_overflow",
"severity": "critical",
"location": "memory_management",
"frequency": 3
},
{
"type": "sql_injection",
"severity": "high",
"location": "database_interface",
"frequency": 2
},
{
"type": "race_condition",
"severity": "medium",
"location": "thread_handling",
"frequency": 1
}
]
return patterns[int(time.time()) % 3]
def analyze_attack_vectors(pattern: Dict):
"""Analyzes potential attack vectors"""
vectors = []
severity_scores = {"critical": 9.5, "high": 8.0, "medium": 6.5}
base_score = severity_scores[pattern["type"]]
vectors.append({
"type": pattern["type"],
"attack_path": f"exploit_{pattern['location']}",
"complexity": "high" if pattern["frequency"] < 2 else "medium",
"cvss_score": base_score + (time.time() % 1)
})
return vectors
def simulate_exploitation(vectors: List[Dict]):
"""Simulates exploitation attempts"""
results = []
for vector in vectors:
results.append({
"vector": vector["type"],
"success_rate": 0.7 + (time.time() % 3) / 10,
"detection_time": 100 + (int(time.time()) % 50),
"mitigation_possible": vector["complexity"] != "high"
})
return results
def generate_signatures(results: List[Dict]):
"""Generates vulnerability signatures"""
signatures = []
for result in results:
signatures.append({
"pattern": f"signature_{result['vector']}",
"reliability": result['success_rate'],
"false_positive_rate": 0.1 + (time.time() % 2) / 10,
"detection_speed": result['detection_time']
})
return signatures
def validate_findings(signatures: List[Dict]):
"""Validates vulnerability findings"""
validations = []
for sig in signatures:
validations.append({
"signature": sig["pattern"],
"confidence": sig["reliability"] * (1 - sig["false_positive_rate"]),
"reproducibility": 0.8 + (time.time() % 2) / 10,
"severity": "critical" if sig["reliability"] > 0.8 else "high"
})
return validations
# Create specialized agents
pattern_scanner = Agent(
name="Pattern Scanner",
role="Code Analysis",
goal="Scan for suspicious patterns",
instructions="Analyze code for potential vulnerabilities",
tools=[scan_code_patterns]
)
vector_analyzer = Agent(
name="Vector Analyzer",
role="Attack Vector Analysis",
goal="Analyze attack vectors",
instructions="Identify potential attack paths",
tools=[analyze_attack_vectors]
)
exploit_simulator = Agent(
name="Exploit Simulator",
role="Exploitation Testing",
goal="Simulate exploitation attempts",
instructions="Test potential vulnerabilities",
tools=[simulate_exploitation]
)
signature_generator = Agent(
name="Signature Generator",
role="Signature Creation",
goal="Generate vulnerability signatures",
instructions="Create detection signatures",
tools=[generate_signatures]
)
finding_validator = Agent(
name="Finding Validator",
role="Validation",
goal="Validate findings",
instructions="Verify vulnerability findings",
tools=[validate_findings]
)
# Create workflow tasks
scanning_task = Task(
name="scan_patterns",
description="Scan code patterns",
expected_output="Suspicious patterns",
agent=pattern_scanner,
is_start=True,
next_tasks=["analyze_vectors"]
)
vector_task = Task(
name="analyze_vectors",
description="Analyze attack vectors",
expected_output="Attack vectors",
agent=vector_analyzer,
next_tasks=["simulate_exploits"]
)
simulation_task = Task(
name="simulate_exploits",
description="Simulate exploits",
expected_output="Exploitation results",
agent=exploit_simulator,
next_tasks=["generate_signatures"]
)
signature_task = Task(
name="generate_signatures",
description="Generate signatures",
expected_output="Vulnerability signatures",
agent=signature_generator,
next_tasks=["validate_findings"]
)
validation_task = Task(
name="validate_findings",
description="Validate findings",
expected_output="Validation results",
agent=finding_validator,
task_type="decision",
condition={
"critical": ["scan_patterns"], # Continue scanning if critical
"high": ["analyze_vectors"], # Reanalyze if high
"medium": "" # End workflow if medium
}
)
# Create workflow
workflow = PraisonAIAgents(
agents=[pattern_scanner, vector_analyzer, exploit_simulator,
signature_generator, finding_validator],
tasks=[scanning_task, vector_task, simulation_task,
signature_task, validation_task],
process="workflow",
verbose=True
)
async def main():
print("\nStarting Vulnerability Detection Workflow...")
print("=" * 50)
# Run workflow
results = await workflow.astart()
# Print results
print("\nVulnerability Detection Results:")
print("=" * 50)
for task_id, result in results["task_results"].items():
if result:
print(f"\nTask: {task_id}")
print(f"Result: {result.raw}")
print("-" * 50)
if __name__ == "__main__":
asyncio.run(main())
```
</Step>
</Steps>
## Next Steps
<CardGroup>
<Card title="Introduction" icon="book" href="/introduction">
Learn more about PraisonAI and its core concepts
</Card>
<Card title="Quick Start" icon="bolt" href="/quickstart">
Get started with the basics of PraisonAI
</Card>
</CardGroup>
+2 -2
View File
@@ -12,7 +12,7 @@ icon: "images"
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
pip install praisonaiagents opencv-python moviepy
```
</Step>
<Step title="Set API Key">
@@ -71,7 +71,7 @@ icon: "images"
<Step title="Install Package">
Install the PraisonAI package:
```bash
pip install praisonai
pip install praisonai opencv-python moviepy
```
</Step>
<Step title="Set API Key">
+352
View File
@@ -0,0 +1,352 @@
---
title: "RAG Agents"
description: "Learn how to create AI agents that can efficiently interact with vector databases for knowledge retrieval and storage."
icon: "database"
---
```mermaid
flowchart LR
In[Input] --> RAGAgent[("RAG Agent")]
VDB[(Vector DB)] --> RAGAgent
RAGAgent --> Task[Knowledge Task]
Task --> |Query| VDB
Task --> Out[Output]
style In fill:#8B0000,color:#fff
style RAGAgent fill:#2E8B57,color:#fff,shape:circle
style VDB fill:#4169E1,color:#fff,shape:cylinder
style Task fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
A knowledge-centric workflow where RAG (Retrieval Augmented Generation) agents interact with vector databases to store and retrieve information efficiently, enabling sophisticated question-answering and information retrieval capabilities.
## Quick Start
<Steps>
<Step title="Install Package">
Install PraisonAI Agents with knowledge support:
```bash
pip install "praisonaiagents[knowledge]"
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key:
```bash
export OPENAI_API_KEY=xxxxx
```
</Step>
<Step title="Create Script">
Create a new file `app.py`:
```python
from praisonaiagents import Agent
agent = Agent(
name="Knowledge Agent",
instructions="You answer questions based on the provided knowledge.",
knowledge=["small.pdf"], # Indexing
)
agent.start("What is KAG in one line?") # Retrieval
```
</Step>
</Steps>
## Data Indexing and Retrieval Agents
<Note>
Indexing and Ingestion are relatively the same.
</Note>
```mermaid
flowchart LR
subgraph In[Input]
PDF[PDF]
TXT[TXT]
MD[MD]
end
subgraph Router[Vector Store]
DB[(Vector DB)]
end
subgraph Out[Agents]
A1[Agent 1]
A2[Agent 2]
A3[Agent 3]
end
In --> Router
Router --> A1
Router --> A2
Router --> A3
style In fill:#8B0000,color:#fff
style Router fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
The simplest way to create a knowledge-based agent is without any configuration:
```python
from praisonaiagents import Agent
agent = Agent(
name="Knowledge Agent",
instructions="You answer questions based on the provided knowledge.",
knowledge=["small.pdf"] # Indexing
)
agent.start("What is KAG in one line?") # Retrieval
```
### 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": "praison",
"path": ".praison",
}
}
}
agent = Agent(
name="Knowledge Agent",
instructions="You answer questions based on the provided knowledge.",
knowledge=["small.pdf"], # Indexing
knowledge_config=config # Configuration
)
agent.start("What is KAG in one line?") # Retrieval
```
### Multi-Agent Knowledge System
For more complex scenarios, you can create a knowledge-based system with multiple agents:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
import logging
import os
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
# Define the configuration for the Knowledge instance
config = {
"vector_store": {
"provider": "chroma",
"config": {
"collection_name": "praison",
"path": ".praison",
}
}
}
# Create an agent with knowledge capabilities
knowledge_agent = Agent(
name="KnowledgeAgent",
role="Information Specialist",
goal="Store and retrieve knowledge efficiently",
backstory="Expert in managing and utilizing stored knowledge",
knowledge=["sample.pdf"], # Indexing
knowledge_config=config, # Configuration
verbose=True
)
# Define a task for the agent
knowledge_task = Task(
name="knowledge_task",
description="Who is Mervin Praison?",
expected_output="Answer to the question",
agent=knowledge_agent # Agent
)
# Create and start the agents
agents = PraisonAIAgents(
agents=[knowledge_agent],
tasks=[knowledge_task],
process="sequential",
user_id="user1" # User ID
)
# Start execution
result = agents.start() # Retrieval
```
## Retrieval Agents
<Note>
Retrieval is the process of querying the vector database for information.
Considering there is data already in the Vector Database.
</Note>
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</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 `rag_agent.py` with the basic setup:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
# Define the configuration for the Knowledge instance
config = {
"vector_store": {
"provider": "chroma",
"config": {
"collection_name": "praison",
"path": ".praison"
}
}
}
# Create an agent
rag_agent = Agent(
name="RAG Agent",
role="Information Specialist",
goal="Retrieve knowledge efficiently",
llm="gpt-4o-mini"
)
# Define a task for the agent
rag_task = Task(
name="RAG Task",
description="What is KAG?",
expected_output="Answer to the question",
agent=rag_agent,
context=[config] # Retrieval : Vector Database provided as context
)
# Build Agents
agents = PraisonAIAgents(
agents=[rag_agent],
tasks=[rag_task],
user_id="user1"
)
# Start Agents
agents.start()
```
</Step>
<Step title="Start Agents">
Type this in your terminal to run your agents:
```bash
python rag_agent.py
```
</Step>
</Steps>
<Note>
**Requirements**
- Python 3.10 or higher
- OpenAI API key. Generate OpenAI API key [here](https://platform.openai.com/api-keys). Use Other models using [this guide](/models).
- ChromaDB or other supported vector database
</Note>
### Adding Knowledge to RAG Agents
```python
from praisonaiagents import Agent
config = {
"vector_store": {
"provider": "chroma",
"config": {
"collection_name": "praison",
"path": ".praison",
}
}
}
agent = Agent(
name="Knowledge Agent",
instructions="You answer questions based on the provided knowledge.",
knowledge=["small.pdf"], # Indexing
knowledge_config=config # Configuration
)
agent.start("What is KAG in one line?") # Retrieval
```
## Understanding RAG Agents
<Card title="What are RAG Agents?" icon="question">
RAG (Retrieval Augmented Generation) agents enable:
- Efficient knowledge retrieval
- Semantic search capabilities
- Persistent knowledge storage
- Context-aware responses
</Card>
## Features
<CardGroup cols={2}>
<Card title="RAG Architecture" icon="database">
Store and manage vector embeddings efficiently.
</Card>
<Card title="Semantic Search" icon="magnifying-glass">
Find relevant information using semantic similarity.
</Card>
<Card title="Knowledge Integration" icon="brain">
Seamlessly integrate with existing knowledge bases.
</Card>
<Card title="Context Management" icon="layer-group">
Handle complex contextual queries and responses.
</Card>
</CardGroup>
## Troubleshooting
<CardGroup cols={2}>
<Card title="RAG Issues" icon="triangle-exclamation">
If RAG system isn't working:
- Check database configuration
- Verify connection settings
- Enable verbose mode for debugging
</Card>
<Card title="Query Issues" icon="gauge-high">
If queries aren't returning expected results:
- Check embedding quality
- Verify search parameters
- Monitor similarity thresholds
</Card>
</CardGroup>
## Next Steps
<CardGroup cols={2}>
<Card title="AutoAgents" icon="robot" href="./autoagents">
Learn about automatically created and managed AI agents
</Card>
<Card title="Mini Agents" icon="microchip" href="./mini">
Explore lightweight, focused AI agents
</Card>
</CardGroup>
<Note>
For optimal results, ensure your vector database is properly configured and indexed for your specific use case.
</Note>
+138
View File
@@ -0,0 +1,138 @@
---
title: "Repetitive Agents"
description: "Learn how to create AI agents that can efficiently handle repetitive tasks through automated loops."
icon: "repeat"
---
```mermaid
flowchart LR
In[Input] --> LoopAgent[("Looping Agent")]
LoopAgent --> Task[Task]
Task --> |Next iteration| LoopAgent
Task --> |Done| Out[Output]
style In fill:#8B0000,color:#fff
style LoopAgent fill:#2E8B57,color:#fff,shape:circle
style Task fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
A workflow optimization pattern where agents handle repetitive tasks through automated loops, processing multiple instances efficiently while maintaining consistency.
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</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 `repetitive_agent.py` with the basic setup:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
agent = Agent(
instructions="You are a loop agent that creating a loop of tasks."
)
task = Task(
description="Create the list of tasks to be looped through.",
agent=agent,
task_type="loop",
input_file="tasks.csv"
)
agents = PraisonAIAgents(
agents=[agent],
tasks=[task],
process="workflow",
max_iter=30
)
agents.start()
```
</Step>
<Step title="Start Agents">
Type this in your terminal to run your agents:
```bash
python repetitive_agent.py
```
</Step>
</Steps>
<Note>
**Requirements**
- Python 3.10 or higher
- OpenAI API key. Generate OpenAI API key [here](https://platform.openai.com/api-keys). Use Other models using [this guide](/models).
</Note>
## Understanding Repetitive Agents
<Card title="What are Repetitive Agents?" icon="question">
Repetitive agents enable:
- Automated task loops
- Batch processing
- Consistent task execution
- Efficient handling of multiple similar tasks
</Card>
## Features
<CardGroup cols={2}>
<Card title="Task Looping" icon="repeat">
Process multiple tasks through automated loops.
</Card>
<Card title="Batch Processing" icon="layer-group">
Handle multiple similar tasks efficiently.
</Card>
<Card title="Input Management" icon="file-csv">
Process tasks from structured input files.
</Card>
<Card title="Progress Tracking" icon="chart-line">
Monitor task completion and progress.
</Card>
</CardGroup>
## Troubleshooting
<CardGroup cols={2}>
<Card title="Loop Issues" icon="triangle-exclamation">
If loops aren't working as expected:
- Verify input file format
- Check task configurations
- Enable verbose mode for debugging
</Card>
<Card title="Performance Issues" icon="gauge-high">
If processing is slow:
- Check batch sizes
- Verify resource allocation
- Monitor memory usage
</Card>
</CardGroup>
## Next Steps
<CardGroup cols={2}>
<Card title="AutoAgents" icon="robot" href="./autoagents">
Learn about automatically created and managed AI agents
</Card>
<Card title="Mini Agents" icon="microchip" href="./mini">
Explore lightweight, focused AI agents
</Card>
</CardGroup>
<Note>
For optimal results, ensure your input files are properly formatted and your task configurations are appropriate for your use case.
</Note>
+13 -26
View File
@@ -6,9 +6,7 @@ icon: "book-open"
## What is PraisonAI?
<Note>
PraisonAI is a powerful Multi-Agent Framework for building and deploying AI agents that can understand, reason, and execute complex tasks autonomously.
</Note>
PraisonAI is a powerful Multi-Agent Framework for building and deploying AI agents that can understand, reason, and execute complex tasks autonomously.
<CardGroup cols={1}>
<Card title="Welcome to PraisonAI" icon="wand-magic-sparkles">
Build powerful autonomous agents that understand, decide, and execute with unprecedented capability.
@@ -26,45 +24,34 @@ graph LR
Agent2 --> Output([✓ Output])
Process -.-> Agent1
%% Styling for main elements
style Start fill:#2D3047,stroke:#7C90A0,color:#fff
style Output fill:#2D3047,stroke:#7C90A0,color:#fff
style Process fill:#5C80BC,stroke:#7C90A0,color:#fff
%% Define subgraphs for agents and their tasks
subgraph Agent1[" "]
subgraph Agent1[ ]
Task1[📋 Task]
AgentIcon1[🤖 AI Agent]
Tools1[🔧 Tools]
Task1 --- AgentIcon1
AgentIcon1 --- Tools1
style Task1 fill:#2D3047,stroke:#7C90A0,color:#fff
style AgentIcon1 fill:#5C80BC,stroke:#7C90A0,color:#fff
style Tools1 fill:#2D3047,stroke:#7C90A0,color:#fff
end
subgraph Agent2[" "]
subgraph Agent2[ ]
Task2[📋 Task]
AgentIcon2[🤖 AI Agent]
Tools2[🔧 Tools]
Task2 --- AgentIcon2
AgentIcon2 --- Tools2
style Task2 fill:#2D3047,stroke:#7C90A0,color:#fff
style AgentIcon2 fill:#5C80BC,stroke:#7C90A0,color:#fff
style Tools2 fill:#2D3047,stroke:#7C90A0,color:#fff
end
%% Style for agent containers
style Agent1 fill:#1B1F3B,stroke:#7C90A0,color:#fff
style Agent2 fill:#1B1F3B,stroke:#7C90A0,color:#fff
%% Global styles
classDef default fill:#2D3047,stroke:#7C90A0,color:#fff
linkStyle default stroke:#7C90A0,stroke-width:2px
classDef input fill:#8B0000,stroke:#7C90A0,color:#fff
classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
classDef tools fill:#2E8B57,stroke:#7C90A0,color:#fff
classDef transparent fill:none,stroke:none
class Start,Output,Task1,Task2 input
class Process,AgentIcon1,AgentIcon2 process
class Tools1,Tools2 tools
class Agent1,Agent2 transparent
```
<br />
<CardGroup cols={2}>
+53 -19
View File
@@ -60,12 +60,20 @@
"url": "/index"
},
{
"name": "Use Cases",
"url": "/usecases"
"name": "Examples",
"url": "/examples"
},
{
"name": "Agents",
"url": "/agents"
},
{
"name": "UI",
"url": "/ui"
},
{
"name": "Tools",
"url": "/tools"
}
],
"navigation": [
@@ -88,7 +96,8 @@
"concepts/tasks",
"concepts/process",
"concepts/tools",
"concepts/memory"
"concepts/memory",
"concepts/knowledge"
]
},
{
@@ -99,7 +108,8 @@
"features/autonomous-workflow",
"features/parallelisation",
"features/promptchaining",
"features/evaluator-optimiser"
"features/evaluator-optimiser",
"features/repetitive"
]
},
{
@@ -107,6 +117,7 @@
"pages": [
"features/autoagents",
"features/selfreflection",
"features/rag",
"features/reasoning",
"features/multimodal",
"features/langchain",
@@ -134,23 +145,36 @@
]
},
{
"group": "Usecases",
"group": "Examples",
"pages": [
"usecases/predictive-maintenance",
"usecases/emergency-response",
"usecases/code-review",
"usecases/fraud-detection",
"usecases/supply-chain",
"usecases/healthcare-diagnosis",
"usecases/customer-service",
"usecases/smart-city",
"usecases/multilingual-content",
"usecases/adaptive-learning"
"examples/examples",
"examples/code-analysis",
"examples/hackathon-judge",
"examples/predictive-maintenance",
"examples/emergency-response",
"examples/code-review",
"examples/fraud-detection",
"examples/supply-chain",
"examples/healthcare-diagnosis",
"examples/customer-service",
"examples/smart-city",
"examples/multilingual-content",
"examples/adaptive-learning",
"examples/crypto-validator",
"examples/space-mission",
"examples/neural-architecture",
"examples/defi-market-maker",
"examples/medicine-protocol",
"examples/climate-impact",
"examples/vulnerability-detection",
"examples/research-assistant",
"examples/quantum-optimiser"
]
},
{
"group": "Agents",
"pages": [
"agents/agents",
"agents/data-analyst",
"agents/finance",
"agents/image",
@@ -170,6 +194,8 @@
{
"group": "Tools",
"pages": [
"tools/tools",
"tools/langchain_tools",
"tools/duckduckgo_tools",
"tools/arxiv_tools",
"tools/calculator_tools",
@@ -187,7 +213,6 @@
"tools/xml_tools",
"tools/yaml_tools",
"tools/yfinance_tools",
"tools",
"tools/custom",
"tools/tools_class",
"tools/gpt",
@@ -217,10 +242,20 @@
{
"group": "User Interface",
"pages": [
"ui/overview",
"ui/gradio",
{
"group": "Streamlit",
"icon": "pen-paintbrush",
"pages": [
"ui/streamlit",
"ui/streamlit/code-analysis-streamlit",
"ui/streamlit/hackathon-judge-streamlit"
]
},
"ui/ui",
"ui/chat",
"ui/code",
"ui/realtime"
"ui/code"
]
},
{
@@ -230,7 +265,6 @@
{
"group": "Developers",
"pages": [
"examples",
"developers/test",
"developers/agents-playbook",
"developers/wrapper",
+138 -4
View File
@@ -1,9 +1,143 @@
---
title: Quick Start
description: Build your first AI agent with PraisonAI
icon: bolt
title: "Quick Start"
description: "Create AI Agents and make them work for you in just a few lines of code."
icon: "bolt"
---
# Basic
<Tabs>
<Tab title="Code">
<Steps>
<Step title="Install Package">
Install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
```bash
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 Agents">
Create `app.py`:
<CodeGroup>
```python Single Agent
from praisonaiagents import Agent, PraisonAIAgents
# Create a simple agent
summarise_agent = Agent(instructions="Summarise Photosynthesis")
# Run the agent
agents = PraisonAIAgents(agents=[summarise_agent])
agents.start()
```
```python Multiple Agents
from praisonaiagents import Agent, PraisonAIAgents
# Create agents with specific roles
diet_agent = Agent(
instructions="Give me 5 healthy food recipes",
)
blog_agent = Agent(
instructions="Write a blog post about the food recipes",
)
# Run multiple agents
agents = PraisonAIAgents(agents=[diet_agent, blog_agent])
agents.start()
```
</CodeGroup>
</Step>
<Step title="Run Agents">
Execute your script:
```bash
python app.py
```
You'll see:
- Agent initialization
- Task execution progress
- Final results
<Tip>
You have successfully CreatedAI Agents and made them work for you!
</Tip>
</Step>
</Steps>
</Tab>
<Tab title="No Code">
<Steps>
<Step title="Install Package">
Install the No Code PraisonAI Package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
```bash
export OPENAI_API_KEY=your_openai_key
```
</Step>
<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 agents.yaml
```
</Step>
</Steps>
</Tab>
</Tabs>
<Note>
**Prerequisites**
- Python 3.10 or higher
- OpenAI API key (get it [here](https://platform.openai.com/api-keys))
- For other LLM providers, see [Models](/models)
</Note>
# Advanced
## Providing Detailed Tasks to Agents (Optional)
<Tabs>
<Tab title="Code">
<Steps>
@@ -180,7 +314,7 @@ praisonai --init create movie script about cat in mars
</Tabs>
## Creating Custom Tool for Agents
## Creating Custom Tool for Agents (Optional)
<Info>
Tools makes the Agent powerful.
+2 -1
View File
@@ -1,5 +1,6 @@
---
title: "Create Custom Tools"
title: "Low Code Custom Tools"
sidebarTitle: "Low Code Custom Tools"
description: "Step-by-step guide for creating and implementing custom tools in PraisonAI, including examples and configuration instructions"
icon: "wrench"
---
+219
View File
@@ -0,0 +1,219 @@
---
title: "LangChain Agent"
sidebarTitle: "LangChain Agent"
description: "Learn how to use LangChain tools and utilities with PraisonAI agents."
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
```
</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, Task, PraisonAIAgents
from langchain_community.utilities import WikipediaAPIWrapper
# Create an agent with Wikipedia tool
agent = Agent(
name="WikiAgent",
role="Research Assistant",
goal="Search Wikipedia for accurate information",
backstory="I am an AI assistant specialized in Wikipedia research",
tools=[WikipediaAPIWrapper],
self_reflect=False
)
# Create a research task
task = Task(
name="wiki_search",
description="Research 'Artificial Intelligence' on Wikipedia",
expected_output="Comprehensive information from Wikipedia articles",
agent=agent
)
# Create and start the workflow
agents = PraisonAIAgents(
agents=[agent],
tasks=[task],
verbose=True
)
agents.start()
```
```python Multiple Tools
from praisonaiagents import Agent, Task, PraisonAIAgents
from langchain_community.tools import YouTubeSearchTool
from langchain_community.utilities import WikipediaAPIWrapper
# Create YouTube search agent
agent = Agent(
name="SearchAgent",
role="Research Assistant",
goal="Search for information from YouTube",
backstory="I am an AI assistant that can search YouTube for relevant videos.",
tools=[YouTubeSearchTool],
self_reflect=False
)
# Create Wikipedia research agent
agent2 = Agent(
name="WikiAgent",
role="Research Assistant",
goal="Search for information from Wikipedia",
backstory="I am an AI assistant that can search Wikipedia for accurate information.",
tools=[WikipediaAPIWrapper],
self_reflect=False
)
# Create YouTube search task
task = Task(
name="search_task",
description="Search for information about 'AI advancements' on YouTube",
expected_output="Relevant information from YouTube videos",
agent=agent
)
# Create Wikipedia research task
task2 = Task(
name="wiki_task",
description="Search for information about 'AI advancements' on Wikipedia",
expected_output="Comprehensive information from Wikipedia articles",
agent=agent2
)
# Create and start the workflow
agents = PraisonAIAgents(
agents=[agent, agent2],
tasks=[task, task2],
verbose=True
)
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>
## 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>
+40
View File
@@ -12,6 +12,46 @@ export REDDIT_CLIENT_SECRET=xxxxxx
export REDDIT_CLIENT_ID=xxxxxx
```
[USER] in this format script:APP:v1.0(by/u/USERNAME)
```bash
pip install praisonai langchain_community praw
```
```bash
export OPENAI_API_KEY="Enter your API key"
```
## Code
### Single Agent
```python
from praisonaiagents import Agent
from langchain_community.tools.reddit_search.tool import RedditSearchRun
agent = Agent(name="RedditSearchAgent",instructions="Search Reddit for information", tools=[RedditSearchRun],)
agent.start("Search Reddit for information about the latest AI advancements in subreddit all")
```
### Multi Agents
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
from langchain_community.tools.reddit_search.tool import RedditSearchRun
agent = Agent(name="RedditSearchAgent",instructions="Search Reddit for information", tools=[RedditSearchRun],)
task = Task(description="Search Reddit for information about the latest AI news in subreddit all", agent=agent)
agents = PraisonAIAgents(agents=[agent],tasks=[task])
agents.start()
```
## No Code
tools.py
```python
+647
View File
@@ -0,0 +1,647 @@
---
title: "AI Agents with Tools"
sidebarTitle: "Tools"
description: "Learn how to create AI agents that can use tools to interact with external systems and perform actions."
icon: "screwdriver-wrench"
---
```mermaid
flowchart TB
subgraph Tools
direction TB
T3[Internet Search]
T1[Code Execution]
T2[Formatting]
end
Input[Input] ---> Agents
subgraph Agents
direction LR
A1[Agent 1]
A2[Agent 2]
A3[Agent 3]
end
Agents ---> Output[Output]
T3 --> A1
T1 --> A2
T2 --> A3
style Tools fill:#189AB4,color:#fff
style Agents fill:#8B0000,color:#fff
style Input fill:#8B0000,color:#fff
style Output fill:#8B0000,color:#fff
```
| Feature | [Knowledge](/concepts/knowledge) | [Tools](/concepts/tools) |
|---------|--------------------------------|---------------------------|
| Purpose | Static reference information | Dynamic interaction capabilities |
| Access | Read-only reference | Execute actions and commands |
| Updates | Manual through files | Real-time through tool calls |
| Storage | Knowledge base | Assigned to specific agents |
| Persistence | Permanent until changed | Available during agent execution |
## Quick Start
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.
## 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
"""
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(
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
)
```
</Step>
</Steps>
<Card title="That's it!">
<Check>You have created a custom tool and assigned it to an agent.</Check>
</Card>
## Implementing Tools Full Code Example
<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`
```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
"""
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
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],
self_reflect=False
)
# 3. Task Definition
collect_task = Task(
description="Perform an internet search using the query: 'AI job trends in 2024'. Return results as a list of title, URL, and snippet.",
expected_output="List of search results with titles, URLs, and snippets.",
agent=data_agent,
name="collect_data",
)
# 4. Start Agents
agents = PraisonAIAgents(
agents=[data_agent],
tasks=[collect_task],
process="sequential"
)
agents.start()
```
</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>
## In-build Tools in PraisonAI
<CardGroup cols={2}>
<Card title="Search Tools" icon="magnifying-glass" href="/tools/search">
Tools for searching and retrieving information from various sources
</Card>
<Card title="Python Tools" icon="python" href="/tools/python_tools">
Essential Python utilities for data manipulation and scripting
</Card>
<Card title="Spider Tools" icon="spider" href="/tools/spider_tools">
Web crawling and scraping capabilities for data extraction
</Card>
<Card title="Arxiv Tools" icon="book" href="/tools/arxiv_tools">
Access and search academic papers from arXiv repository
</Card>
<Card title="Newspaper Tools" icon="newspaper" href="/tools/newspaper_tools">
Extract and parse content from news articles and websites
</Card>
<Card title="DuckDB Tools" icon="database" href="/tools/duckdb_tools">
Fast analytical SQL database operations and queries
</Card>
<Card title="DuckDuckGo Tools" icon="duck" href="/tools/duckduckgo_tools">
Web search functionality using DuckDuckGo's API
</Card>
<Card title="Calculator Tools" icon="calculator" href="/tools/calculator_tools">
Perform mathematical calculations and conversions
</Card>
<Card title="YAML Tools" icon="file-code" href="/tools/yaml_tools">
Parse and manipulate YAML format data
</Card>
<Card title="JSON Tools" icon="brackets-curly" href="/tools/json_tools">
Handle JSON data structures and operations
</Card>
<Card title="Pandas Tools" icon="table" href="/tools/pandas_tools">
Data analysis and manipulation using Pandas
</Card>
<Card title="YFinance Tools" icon="chart-line" href="/tools/yfinance_tools">
Fetch financial market data from Yahoo Finance
</Card>
<Card title="Shell Tools" icon="terminal" href="/tools/shell_tools">
Execute shell commands and system operations
</Card>
<Card title="Wikipedia Tools" icon="book-open" href="/tools/wikipedia_tools">
Access and search Wikipedia articles and data
</Card>
<Card title="XML Tools" icon="code" href="/tools/xml_tools">
Process and manipulate XML format data
</Card>
<Card title="File Tools" icon="file" href="/tools/file_tools">
File system operations and management utilities
</Card>
<Card title="Excel Tools" icon="file-excel" href="/tools/excel_tools">
Work with Excel spreadsheets and workbooks
</Card>
<Card title="CSV Tools" icon="file-csv" href="/tools/csv_tools">
Handle CSV file operations and transformations
</Card>
</CardGroup>
## Tools Overview
<CardGroup cols={3}>
<Card
title="Search Tools"
icon="magnifying-glass"
iconType="solid"
>
Tools for searching and retrieving information from various sources
</Card>
<Card
title="File Tools"
icon="file"
iconType="solid"
>
Tools for reading, writing, and manipulating files
</Card>
<Card
title="API Tools"
icon="code"
iconType="solid"
>
Tools for interacting with external APIs and services
</Card>
</CardGroup>
## Advanced Tool Features
### Tool Configuration
<Frame>
```python
def configured_tool(
query: str,
max_results: int = 5,
timeout: int = 10
) -> List[Dict]:
"""
Example of a configurable tool
Args:
query (str): Search query
max_results (int): Maximum number of results
timeout (int): Request timeout in seconds
Returns:
List[Dict]: Search results
"""
# Tool implementation
pass
```
</Frame>
### Tool Chaining
<Frame>
```python
def chain_tools(input_data: str) -> Dict:
"""
Example of chaining multiple tools
Args:
input_data (str): Input data
Returns:
Dict: Processed results
"""
# 1. Search for data
search_results = internet_search_tool(input_data)
# 2. Process results
processed_data = process_tool(search_results)
# 3. Format output
return format_tool(processed_data)
```
</Frame>
### Tool Categories
<CardGroup cols={3}>
<Card title="Data Collection Tools">
- Web scraping
- API integration
- Database queries
</Card>
<Card title="Processing Tools">
- Data transformation
- Text analysis
- Image processing
</Card>
<Card title="Output Tools">
- File generation
- Report creation
- Data visualization
</Card>
</CardGroup>
## Tool Integration
### Adding Tools to Agents
<Frame>
```python
# Multiple tools
agent = Agent(
name="MultiTool Agent",
tools=[
internet_search_tool,
file_processing_tool,
api_integration_tool
]
)
```
</Frame>
### Tool Dependencies
<Frame>
```python
# Tool with dependencies
def advanced_tool(data: Dict) -> Dict:
"""
Tool that depends on external libraries
Args:
data (Dict): Input data
Returns:
Dict: Processed data
"""
try:
import required_library
# Tool implementation
return processed_result
except ImportError:
raise Exception("Required library not installed")
```
</Frame>
## Tool Guidelines
<CardGroup cols={2}>
<Card title="Best Practices">
1. **Type Hints**
- Use Python type hints
- Define clear input/output types
- Document complex types
2. **Documentation**
- Write clear docstrings
- Explain parameters
- Provide usage examples
3. **Error Handling**
- Handle exceptions gracefully
- Return meaningful errors
- Validate inputs
</Card>
<Card title="Tool Types">
1. **Search Tools**
- Web search
- Database queries
- Document search
2. **File Tools**
- Read/write operations
- File conversion
- Data extraction
3. **API Tools**
- REST API calls
- GraphQL queries
- Service integration
</Card>
</CardGroup>
## Best Practices Summary
<Note>
Following these best practices will help you create robust, efficient, and secure tools in PraisonAI.
</Note>
<CardGroup cols={1}>
<Card title="Design Principles" icon="compass-drafting" iconType="solid">
<AccordionGroup>
<Accordion title="Single Responsibility">
Each tool should have one clear purpose and do it well. Avoid creating tools that try to do too many things.
```python
# Good Example
def process_image(image: np.array) -> np.array:
return processed_image
# Avoid
def process_and_save_and_upload(image):
# Too many responsibilities
pass
```
</Accordion>
<Accordion title="Clear Interfaces">
Define explicit input/output types and maintain consistent parameter naming.
```python
def search_tool(
query: str,
max_results: int = 10
) -> List[Dict[str, Any]]:
"""
Search for information with clear parameters
"""
pass
```
</Accordion>
<Accordion title="Documentation">
Always include detailed docstrings and type hints.
```python
def analyze_text(
text: str,
language: str = "en"
) -> Dict[str, float]:
"""
Analyze text sentiment and emotions.
Args:
text: Input text to analyze
language: ISO language code
Returns:
Dict with sentiment scores
"""
pass
```
</Accordion>
</AccordionGroup>
</Card>
</CardGroup>
<br />
<CardGroup cols={1}>
<Card title="Performance Optimization" icon="bolt" iconType="solid">
<AccordionGroup>
<Accordion title="Efficient Processing">
Optimize resource usage and processing time.
```python
# Use generators for large datasets
def process_large_data():
for chunk in data_generator():
yield process_chunk(chunk)
```
</Accordion>
<Accordion title="Resource Management">
Properly handle resource allocation and cleanup.
```python
async with aiohttp.ClientSession() as session:
# Resource automatically managed
await process_data(session)
```
</Accordion>
<Accordion title="Caching">
Implement caching for frequently accessed data.
```python
@cache.memoize(timeout=300)
def expensive_operation(data: str) -> Dict:
return process_expensive(data)
```
</Accordion>
<Accordion title="Async Operations">
Use async/await for I/O-bound operations.
```python
async def fetch_data(urls: List[str]):
async with aiohttp.ClientSession() as session:
tasks = [fetch_url(session, url) for url in urls]
return await asyncio.gather(*tasks)
```
</Accordion>
</AccordionGroup>
</Card>
</CardGroup>
<br />
<CardGroup cols={1}>
<Card title="Security Best Practices" icon="shield-check" iconType="solid">
<AccordionGroup>
<Accordion title="Input Validation">
Always validate and sanitize inputs to prevent security vulnerabilities.
```python
def process_user_input(data: str) -> str:
if not isinstance(data, str):
raise ValueError("Input must be string")
return sanitize_input(data.strip())
```
</Accordion>
<Accordion title="Rate Limiting">
Implement rate limiting for API calls to prevent abuse.
```python
@rate_limit(calls=100, period=60)
async def api_call():
return await make_request()
```
</Accordion>
<Accordion title="API Key Management">
Securely handle API keys and credentials using environment variables.
```python
# Use environment variables
api_key = os.getenv('API_KEY')
if not api_key:
raise ConfigError("API key not found")
```
</Accordion>
<Accordion title="Error Masking">
Hide sensitive information in error messages to prevent information leakage.
```python
try:
result = process_sensitive_data()
except Exception as e:
# Log detailed error internally
logger.error(f"Detailed error: {str(e)}")
# Return sanitized error to user
raise PublicError("Processing failed")
```
</Accordion>
</AccordionGroup>
</Card>
</CardGroup>
<br />
<Tip>
**Pro Tip**: Start with these practices from the beginning of your project. It's easier to maintain good practices than to retrofit them later.
</Tip>
+147
View File
@@ -0,0 +1,147 @@
---
title: "Gradio Agent"
sidebarTitle: "Gradio"
description: "Learn how to create web interfaces for your AI agents using Gradio"
icon: "browser"
---
```mermaid
flowchart LR
In[User Input] --> UI[Gradio UI]
UI --> Agent[AI Agent]
Agent --> Out[Results Display]
style In fill:#8B0000,color:#fff
style UI fill:#2E8B57,color:#fff
style Agent fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
## Quick Start
<Steps>
<Step title="Install Dependencies">
First, install the required packages:
```bash
pip install praisonaiagents gradio
```
</Step>
<Step title="Create Script">
Create a new file `app.py`:
```python
import gradio as gr
from praisonaiagents import Agent, Tools
from praisonaiagents.tools import duckduckgo
def research(query):
agent = Agent(instructions="You are a Research Agent", tools=[duckduckgo])
result = agent.start(query)
# Format the result with enhanced markdown
formatted_result = f"""
{result}
----
*Generated by PraisonAI Research Assistant*
"""
return formatted_result
# Create a simple Gradio interface
demo = gr.Interface(
fn=research,
inputs=gr.Textbox(
label="Research Query",
placeholder="Enter your research topic...",
lines=2
),
outputs=gr.Markdown(
show_copy_button=True,
height=500,
container=True
),
title="AI Research Assistant",
description="Enter your research query below to get started!",
)
if __name__ == "__main__":
demo.launch()
```
</Step>
<Step title="Run Application">
Run your Gradio app:
```bash
python app.py
```
</Step>
</Steps>
## Features
<CardGroup cols={2}>
<Card title="Simple Interface" icon="wand-magic-sparkles">
Create beautiful UIs with minimal code.
</Card>
<Card title="Markdown Support" icon="markdown">
Rich text output with built-in markdown rendering.
</Card>
<Card title="Copy Button" icon="copy">
One-click copying of results.
</Card>
<Card title="Responsive Design" icon="mobile">
Mobile-friendly interface out of the box.
</Card>
</CardGroup>
## Understanding the Code
The example demonstrates a simple research assistant with these key components:
1. **Function Definition**:
- `research()` function that processes user input
- Agent initialization and execution
- Result formatting with markdown
2. **Interface Setup**:
- Input textbox configuration
- Markdown output with copy button
- Title and description settings
3. **Launch Configuration**:
- Main entry point check
- Server launch with default settings
## Customization
You can enhance the UI with additional Gradio components:
```python
# Add multiple input types
demo = gr.Interface(
fn=process_inputs,
inputs=[
gr.Textbox(label="Query"),
gr.File(label="Upload Document"),
gr.Dropdown(choices=["Option 1", "Option 2"])
],
outputs=[
gr.Markdown(label="Results"),
gr.Plot(label="Visualization")
]
)
# Add themes and styling
demo = gr.Interface(
...
theme="default",
css=".gradio-container {background-color: #f0f0f0}"
)
# Add authentication
demo.launch(auth=("username", "password"))
```
## Next Steps
- Learn about [Prompt Chaining](/features/promptchaining) for complex UI workflows
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving responses
- Check out [Streamlit Integration](/ui/streamlit) for an alternative UI framework
+63
View File
@@ -0,0 +1,63 @@
---
title: "User Interfaces"
sidebarTitle: "Overview"
description: "Overview of available user interfaces for PraisonAI agents"
icon: "browser"
---
## Available Interfaces
| Interface | Description | URL |
|---|---|---|
| **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) |
| **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) |
## Interface Types
<CardGroup cols={2}>
<Card title="Web Applications" icon="browser">
Create full-featured web interfaces with Streamlit and Gradio.
</Card>
<Card title="Chat Interfaces" icon="messages">
Build conversational experiences with Chat and Chainlit.
</Card>
<Card title="Code Interaction" icon="code">
Interact with codebases using the Code interface.
</Card>
<Card title="Multi-Agent Systems" icon="users">
Orchestrate multiple agents with UI framework.
</Card>
</CardGroup>
## Features by Interface
### Web Frameworks
- **Streamlit**: Interactive components, real-time updates, data visualization
- **Gradio**: Rapid prototyping, markdown support, file handling
### Chat Systems
- **Chat**: Multiple LLM support, conversation history, context management
### Specialized Interfaces
- **UI**: Agent orchestration, workflow management, inter-agent communication
- **Code**: Codebase navigation, syntax highlighting, version control integration
## Getting Started
<Steps>
<Step title="Choose Interface">
Select the interface that best matches your use case from the table above.
</Step>
<Step title="Install Dependencies">
Each interface has its own installation requirements. Follow the specific guide.
</Step>
<Step title="Create Application">
Use the provided examples and templates to build your application.
</Step>
<Step title="Customize">
Add features and styling to match your needs using the interface's components.
</Step>
</Steps>
+124
View File
@@ -0,0 +1,124 @@
---
title: "Streamlit Agent"
sidebarTitle: "Streamlit"
description: "Learn how to create web interfaces for your AI agents using Streamlit"
icon: "browser"
---
```mermaid
flowchart LR
In[User Input] --> UI[Streamlit UI]
UI --> Agent[AI Agent]
Agent --> Out[Results Display]
style In fill:#8B0000,color:#fff
style UI fill:#2E8B57,color:#fff
style Agent fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
## Quick Start
<Steps>
<Step title="Install Dependencies">
First, install the required packages:
```bash
pip install praisonaiagents streamlit
```
</Step>
<Step title="Create Script">
Create a new file `app.py`:
```python
import streamlit as st
from praisonaiagents import Agent, Tools
from praisonaiagents.tools import duckduckgo
st.title("AI Research Assistant")
st.write("Enter your research query below to get started!")
# Initialize the research agent
agent = Agent(instructions="You are a Research Agent", tools=[duckduckgo])
# Create the input field
query = st.text_input("Research Query", placeholder="Enter your research topic...")
# Add a search button
if st.button("Search"):
if query:
with st.spinner("Researching..."):
result = agent.start(query)
st.write(result)
else:
st.warning("Please enter a research query")
```
</Step>
<Step title="Run Application">
Run your Streamlit app:
```bash
streamlit run app.py
```
</Step>
</Steps>
## Features
<CardGroup cols={2}>
<Card title="Easy Integration" icon="puzzle-piece">
Seamlessly integrate AI agents with Streamlit's UI components.
</Card>
<Card title="Interactive UI" icon="hand-pointer">
Create responsive interfaces with real-time updates.
</Card>
<Card title="Progress Indicators" icon="spinner">
Built-in loading states and progress indicators.
</Card>
<Card title="Rich Output" icon="text-size">
Display formatted text, markdown, and other rich content.
</Card>
</CardGroup>
## Understanding the Code
The example demonstrates a simple research assistant with these key components:
1. **UI Setup**:
- Title and description using `st.title()` and `st.write()`
- Input field with `st.text_input()`
- Search button with `st.button()`
2. **Agent Integration**:
- Initialize the AI agent with specific instructions
- Connect the agent to the UI components
- Handle user input and display results
3. **User Experience**:
- Loading spinner during processing
- Input validation and error messages
- Clean result display
## Customization
You can enhance the UI with additional Streamlit components:
```python
# Add sidebar options
st.sidebar.title("Settings")
model = st.sidebar.selectbox("Select Model", ["GPT-3", "GPT-4"])
# Add multiple input types
text_input = st.text_area("Long Query", height=100)
file_input = st.file_uploader("Upload File")
# Display results with formatting
st.markdown("### Results")
st.json(structured_data)
st.dataframe(tabular_data)
```
## Next Steps
- Learn about [Prompt Chaining](/features/promptchaining) for complex UI workflows
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving responses
- Check out [Gradio Integration](/ui/gradio) for an alternative UI framework
@@ -0,0 +1,333 @@
---
title: "Code Analysis Agent UI"
sidebarTitle: "Code Analysis"
description: "Build an interactive web interface for analyzing code quality and providing detailed recommendations using Streamlit and AI agents."
icon: "laptop-code"
---
```mermaid
flowchart LR
Input[Input URL] --> Process[Process Code]
Process --> Analyze[AI Analysis]
Analyze --> Display[Display Results]
Display --> Metrics[Show Metrics]
Display --> Details[Show Details]
style Input fill:#8B0000,color:#fff
style Process fill:#2E8B57,color:#fff
style Analyze fill:#2E8B57,color:#fff
style Display fill:#2E8B57,color:#fff
style Metrics fill:#2E8B57,color:#fff
style Details fill:#2E8B57,color:#fff
```
## What is the Code Analysis Streamlit App?
The Code Analysis Streamlit App provides a user-friendly web interface for analyzing code repositories and generating comprehensive quality assessments. It combines AI-powered code analysis with an interactive dashboard to display detailed metrics, recommendations, and insights.
## Features
<CardGroup cols={2}>
<Card title="Repository Analysis" icon="code-branch">
Support for GitHub URLs and local code repositories.
</Card>
<Card title="Real-time Processing" icon="spinner">
Live analysis and evaluation of code.
</Card>
<Card title="Interactive Metrics" icon="chart-column">
Visual presentation of code quality metrics.
</Card>
<Card title="Detailed Reports" icon="file-lines">
Comprehensive analysis of code structure and patterns.
</Card>
<Card title="Best Practices" icon="check-double">
Evaluation against industry best practices.
</Card>
</CardGroup>
## Quick Start
<Steps>
<Step title="Install Dependencies">
Install the required packages:
```bash
pip install streamlit praisonaiagents gitingest
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create the App">
Create a new file `code_analysis_app.py` with the following code:
```python
import streamlit as st
from praisonaiagents import Agent, Task, PraisonAIAgents
from pydantic import BaseModel
from typing import List, Dict, Any
from gitingest import ingest
# Import the same classes and code from code-analysis-agents.py
class CodeMetrics(BaseModel):
category: str
score: int
findings: List[str]
class CodeAnalysisReport(BaseModel):
overall_quality: int
code_metrics: List[CodeMetrics]
architecture_score: int
maintainability_score: int
performance_score: int
security_score: int
test_coverage: int
key_strengths: List[str]
improvement_areas: List[str]
tech_stack: List[str]
recommendations: List[str]
complexity_metrics: Dict[str, int]
best_practices: List[Dict[str, str]]
potential_risks: List[str]
documentation_quality: int
def analyze_code(code_source: str) -> CodeAnalysisReport:
"""
Analyze code from directory path or GitHub URL
"""
# Create code analyzer agent
code_analyzer = Agent(
role="Code Analysis Expert",
goal="Provide comprehensive code evaluation and recommendations",
backstory="""Expert code analyst specializing in architecture review,
best practices, and technical debt assessment.""",
verbose=True
)
# Create analysis task
code_analysis_task = Task(
description="""Analyze code repository and provide structured evaluation:
1. Overall Quality (0-100)
2. Core Metrics Analysis:
- Architecture and Design
- Code Maintainability
- Performance Optimization
- Security Practices
- Test Coverage
3. Technical Assessment:
- Technology Stack Review
- Code Complexity Analysis
- Best Practices Adherence
- Risk Assessment
4. Recommendations:
- Key Improvements
- Architecture Suggestions
- Security Enhancements""",
expected_output="Detailed code analysis report with metrics and recommendations",
agent=code_analyzer,
output_pydantic=CodeAnalysisReport
)
# Ingest code content
summary, tree, content = ingest(code_source)
# Concatenate context into structured format
context_text = f"""
CODE REPOSITORY ANALYSIS
=======================
SUMMARY
-------
{summary}
REPOSITORY STRUCTURE
-------------------
{tree}
SOURCE CODE
-----------
{content}
"""
# Initialize and run analysis
agents = PraisonAIAgents(
agents=[code_analyzer],
tasks=[code_analysis_task]
)
result = agents.start(context_text)
# Extract the Pydantic model from the result
if isinstance(result, dict) and 'task_results' in result:
# Get the first task result's pydantic output
analysis_result = result['task_results'][0].pydantic
if isinstance(analysis_result, CodeAnalysisReport):
return analysis_result
# If we can't get the Pydantic model, create one from the raw data
return CodeAnalysisReport(**result)
def display_code_metrics(metrics, cols):
"""Display code metrics in columns with color-coded scores"""
for i, metric in enumerate(metrics):
score = metric.score
color = "red" if score < 60 else "orange" if score < 75 else "green"
# Use modulo to alternate between columns
with cols[i % len(cols)]:
st.markdown(f"### {metric.category}")
st.markdown(f"**Score:** :{color}[{score}%]")
for finding in metric.findings:
st.markdown(f"• {finding}")
def display_section(title: str, items: list, icon: str = "•"):
"""Display a section with items in a consistent format"""
st.markdown(f"### {title}")
for item in items:
if isinstance(item, dict):
for key, value in item.items():
st.markdown(f"{icon} **{key}**: {value}")
else:
st.markdown(f"{icon} {item}")
def main():
st.set_page_config(
page_title="Code Analysis Agent",
layout="wide",
initial_sidebar_state="expanded"
)
st.title("Code Analysis Agent")
with st.sidebar:
st.header("Input")
code_source = st.text_input(
"GitHub URL or Local Path",
placeholder="https://github.com/username/repo or /path/to/directory"
)
analyze_button = st.button("Analyze Code", type="primary")
if analyze_button and code_source:
try:
with st.spinner("Analyzing code..."):
result = analyze_code(code_source)
# Overall Metrics
st.header("Overall Metrics")
cols = st.columns(6)
metrics = {
"Overall Quality": result.overall_quality,
"Architecture": result.architecture_score,
"Maintainability": result.maintainability_score,
"Performance": result.performance_score,
"Security": result.security_score,
"Test Coverage": result.test_coverage
}
for (metric, value), col in zip(metrics.items(), cols):
color = "red" if value < 60 else "orange" if value < 75 else "green"
col.metric(metric, f"{value}%")
col.markdown(f":{color}[{'●' * (value // 20)}]")
# Detailed Analysis
st.header("Detailed Analysis")
metric_cols = st.columns(2)
display_code_metrics(result.code_metrics, metric_cols)
# Technology Stack
col1, col2 = st.columns(2)
with col1:
st.header("Technology Stack")
for tech in result.tech_stack:
st.markdown(f"🔧 {tech}")
with col2:
st.header("Complexity Metrics")
for metric, value in result.complexity_metrics.items():
st.metric(metric.replace('_', ' ').title(), value)
# Key Findings
st.header("Key Findings")
cols = st.columns(2)
with cols[0]:
display_section("✅ Strengths", result.key_strengths)
display_section("🔄 Best Practices", result.best_practices)
with cols[1]:
display_section("⚠️ Areas for Improvement", result.improvement_areas)
display_section("❗ Potential Risks", result.potential_risks)
# Recommendations
st.header("Recommendations")
for i, rec in enumerate(result.recommendations, 1):
st.markdown(f"**{i}.** {rec}")
# Documentation Quality
st.header("Documentation")
doc_score = result.documentation_quality
color = "red" if doc_score < 60 else "orange" if doc_score < 75 else "green"
st.markdown(f"Documentation Quality: :{color}[{doc_score}%]")
except Exception as e:
st.error(f"Error analyzing code: {str(e)}")
st.exception(e)
elif analyze_button:
st.warning("Please enter a GitHub URL or local path")
if __name__ == "__main__":
main()
```
</Step>
<Step title="Run the App">
Start the Streamlit app:
```bash
streamlit run code_analysis_app.py
```
</Step>
</Steps>
## Understanding the Interface
The Streamlit app provides an intuitive interface with the following sections:
- **Input**: GitHub URL or local path input in the sidebar
- **Overall Metrics**: Visual display of key quality scores
- Overall Quality
- Architecture Score
- Maintainability Score
- Performance Score
- Security Score
- Test Coverage
- **Detailed Analysis**:
- Code Metrics with Findings
- Technology Stack Overview
- Complexity Metrics
- **Key Findings**:
- Strengths
- Best Practices
- Areas for Improvement
- Potential Risks
- **Additional Information**:
- Recommendations
- Documentation Quality Assessment
## Next Steps
<CardGroup>
<Card title="Streamlit Docs" icon="book" href="https://docs.streamlit.io">
Learn more about Streamlit features
</Card>
<Card title="PraisonAI Docs" icon="bolt" href="/introduction">
Explore PraisonAI capabilities
</Card>
<Card title="Examples" icon="code" href="/examples">
View more example applications
</Card>
</CardGroup>
@@ -0,0 +1,323 @@
---
title: "Hackathon Judge Agent UI"
sidebarTitle: "Hackathon Judge"
description: "Build an interactive web interface for evaluating hackathon projects using Streamlit and AI agents."
icon: "desktop"
---
```mermaid
flowchart LR
Upload[Upload Video] --> Process[Process Video]
Process --> Evaluate[AI Evaluation]
Evaluate --> Display[Display Results]
Display --> Scores[Show Scores]
Display --> Feedback[Show Feedback]
style Upload fill:#8B0000,color:#fff
style Process fill:#2E8B57,color:#fff
style Evaluate fill:#2E8B57,color:#fff
style Display fill:#2E8B57,color:#fff
style Scores fill:#2E8B57,color:#fff
style Feedback fill:#2E8B57,color:#fff
```
## What is the Hackathon Judge Streamlit App?
The Hackathon Judge Streamlit App provides a user-friendly web interface for evaluating hackathon projects through video demonstrations. It combines the power of AI evaluation with an interactive dashboard to display comprehensive project assessments, scores, and feedback.
## Features
<CardGroup cols={2}>
<Card title="Video Upload" icon="upload">
Easy-to-use interface for uploading project demonstration videos.
</Card>
<Card title="Real-time Processing" icon="spinner">
Live processing and evaluation of uploaded videos.
</Card>
<Card title="Interactive Dashboard" icon="chart-simple">
Visual presentation of scores and metrics.
</Card>
<Card title="Detailed Feedback" icon="comments">
Comprehensive display of evaluation results and recommendations.
</Card>
<Card title="Market Analysis" icon="briefcase">
Visual presentation of market potential and scalability.
</Card>
</CardGroup>
## Quick Start
<Steps>
<Step title="Install Dependencies">
Install the required packages:
```bash
pip install streamlit praisonaiagents opencv-python moviepy
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create the App">
Create a new file `hackathon_judge_app.py` with the following code:
```python
import streamlit as st
import os
from praisonaiagents import Agent, Task, PraisonAIAgents
from pydantic import BaseModel
from typing import List, Dict
import tempfile
import json
class ProjectEvaluation(BaseModel):
innovation_score: int # 0-100
technical_complexity: int # 0-100
presentation_quality: int # 0-100
user_experience: int # 0-100
completeness: int # 0-100
overall_score: int # 0-100
key_strengths: List[str]
areas_for_improvement: List[str]
notable_features: List[str]
technical_highlights: List[str]
recommendations: List[str]
market_potential: str
scalability_assessment: str
# Set page config
st.set_page_config(
page_title="Hackathon Project Evaluator",
page_icon="🏆",
layout="wide"
)
# Create Vision Analysis Agent
@st.cache_resource
def get_hackathon_judge():
return Agent(
name="HackathonJudge",
role="Technical Project Evaluator",
goal="Evaluate hackathon projects through video demonstrations",
backstory="""You are an experienced hackathon judge and technical expert.
You excel at evaluating innovation, technical implementation, and presentation quality.
You provide constructive feedback and identify both strengths and areas for improvement.""",
llm="gpt-4o-mini", # Using vision-capable model
self_reflect=False,
knowledge=""
)
def evaluate_project(video_path: str) -> ProjectEvaluation:
"""
Evaluate a hackathon project based on its video demonstration
"""
hackathon_judge = get_hackathon_judge()
evaluation_task = Task(
name="project_evaluation",
description="""Analyze this hackathon project video demonstration and provide a comprehensive evaluation:
1. Score the following aspects (0-100):
- Innovation and Creativity
- Technical Complexity
- Presentation Quality
- User Experience
- Project Completeness
2. Identify:
- Key strengths and standout features
- Areas that could be improved
- Notable technical implementations
- Market potential and scalability
3. Provide:
- Specific recommendations for improvement
- Technical suggestions
- Potential future enhancements""",
expected_output="Detailed project evaluation with scores and feedback",
agent=hackathon_judge,
output_pydantic=ProjectEvaluation,
images=[video_path] # Video input for multimodal analysis
)
# Initialize and run evaluation
agents = PraisonAIAgents(
agents=[hackathon_judge],
tasks=[evaluation_task],
process="sequential",
verbose=True
)
response = agents.start()
try:
# If response contains task_results, extract the Pydantic model directly
if isinstance(response, dict) and 'task_results' in response:
task_output = response['task_results'][0]
if hasattr(task_output, 'pydantic'):
return task_output.pydantic
elif hasattr(task_output, 'raw'):
# Extract JSON from raw string if it's wrapped in ```json
raw_text = task_output.raw
if raw_text.startswith('```json'):
raw_text = raw_text.split('\n', 1)[1].rsplit('\n', 1)[0]
evaluation_data = json.loads(raw_text)
else:
evaluation_data = json.loads(task_output) if isinstance(task_output, str) else task_output
elif isinstance(response, str):
evaluation_data = json.loads(response)
elif isinstance(response, dict) and 'task_status' in response:
content = response['task_status']
if isinstance(content, dict):
evaluation_data = content
else:
evaluation_data = json.loads(content) if isinstance(content, str) else content
else:
evaluation_data = response
# Create and return ProjectEvaluation instance
return ProjectEvaluation(
innovation_score=int(evaluation_data.get('innovation_score', 0)),
technical_complexity=int(evaluation_data.get('technical_complexity', 0)),
presentation_quality=int(evaluation_data.get('presentation_quality', 0)),
user_experience=int(evaluation_data.get('user_experience', 0)),
completeness=int(evaluation_data.get('completeness', 0)),
overall_score=int(evaluation_data.get('overall_score', 0)),
key_strengths=evaluation_data.get('key_strengths', []),
areas_for_improvement=evaluation_data.get('areas_for_improvement', []),
notable_features=evaluation_data.get('notable_features', []),
technical_highlights=evaluation_data.get('technical_highlights', []),
recommendations=evaluation_data.get('recommendations', []),
market_potential=str(evaluation_data.get('market_potential', '')),
scalability_assessment=str(evaluation_data.get('scalability_assessment', ''))
)
except Exception as e:
print(f"Debug - Raw response: {response}")
print(f"Error processing response: {e}")
raise
# Title and description
st.title("🏆 Hackathon Judge Agent")
st.markdown("""
Upload your hackathon project demonstration video for an AI-powered evaluation.
Get comprehensive feedback on various aspects of your project.
""")
# File uploader
uploaded_file = st.file_uploader("Choose a video file", type=['mp4', 'avi', 'mov', 'mkv'])
if uploaded_file:
# Create a temporary file to store the video
with tempfile.NamedTemporaryFile(delete=False, suffix='.'+uploaded_file.name.split('.')[-1]) as tmp_file:
tmp_file.write(uploaded_file.getvalue())
video_path = tmp_file.name
with st.spinner("🤖 AI is evaluating your project..."):
try:
# Evaluate the project
result = evaluate_project(video_path)
# Display results
st.header("Overall Score")
st.metric("Overall Score", f"{result.overall_score}/100")
# Display detailed scores
st.header("Detailed Scores")
col1, col2, col3 = st.columns(3)
with col1:
st.metric("Innovation", f"{result.innovation_score}/100")
st.metric("Technical Complexity", f"{result.technical_complexity}/100")
with col2:
st.metric("Presentation", f"{result.presentation_quality}/100")
st.metric("User Experience", f"{result.user_experience}/100")
with col3:
st.metric("Completeness", f"{result.completeness}/100")
# Display qualitative feedback
st.header("Key Strengths")
for strength in result.key_strengths:
st.write(f"• {strength}")
st.header("Areas for Improvement")
for area in result.areas_for_improvement:
st.write(f"• {area}")
st.header("Technical Highlights")
for highlight in result.technical_highlights:
st.write(f"• {highlight}")
st.header("Notable Features")
for feature in result.notable_features:
st.write(f"• {feature}")
st.header("Recommendations")
for rec in result.recommendations:
st.write(f"• {rec}")
# Market Analysis
st.header("Market Analysis")
col1, col2 = st.columns(2)
with col1:
st.subheader("Market Potential")
st.write(result.market_potential)
with col2:
st.subheader("Scalability Assessment")
st.write(result.scalability_assessment)
except Exception as e:
st.error(f"Error evaluating the project: {str(e)}")
finally:
# Clean up the temporary file
os.unlink(video_path)
else:
# Display placeholder content
st.info("👆 Upload a video file to get started!")
```
</Step>
<Step title="Run the App">
Start the Streamlit app:
```bash
streamlit run hackathon_judge_app.py
```
</Step>
</Steps>
## Understanding the Interface
The Streamlit app provides an intuitive interface with the following sections:
- **Video Upload**: Drag and drop or browse to upload your project demo video
- **Overall Score**: A prominent display of the project's overall rating
- **Detailed Scores**:
- Innovation Score
- Technical Complexity
- Presentation Quality
- User Experience
- Project Completeness
- **Qualitative Feedback**:
- Key Strengths
- Areas for Improvement
- Technical Highlights
- Notable Features
- Recommendations
- **Market Analysis**:
- Market Potential
- Scalability Assessment
## Next Steps
<CardGroup>
<Card title="Streamlit Docs" icon="book" href="https://docs.streamlit.io">
Learn more about Streamlit features
</Card>
<Card title="PraisonAI Docs" icon="bolt" href="/introduction">
Explore PraisonAI capabilities
</Card>
<Card title="Examples" icon="code" href="/examples">
View more example applications
</Card>
</CardGroup>
Loaded 100 of 129 files, more files were not shown because too many files have changed in this diff. Show more