Compare commits

..
75 changed files with 20435 additions and 8590 deletions

No files matched your search

-3
View File
@@ -1,3 +0,0 @@
OPENAI_MODEL_NAME="gpt-4-turbo-preview"
OPENAI_API_KEY="Enter your API key"
OPENAI_API_BASE="https://api.openai.com/v1"
-40
View File
@@ -1,40 +0,0 @@
# This workflow will install Python dependencies, run tests and lint with a variety of Python versions
# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python
name: Python package
on:
push:
branches: [ "develop" ]
pull_request:
branches: [ "develop" ]
jobs:
build:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
python-version: ["3.10", "3.11"]
steps:
- uses: actions/checkout@v3
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v3
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
python -m pip install --upgrade pip
python -m pip install flake8 pytest
if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
- name: Lint with flake8
run: |
# stop the build if there are Python syntax errors or undefined names
flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
# exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide
flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
# - name: Test with pytest
# run: |
# pytest
-39
View File
@@ -1,39 +0,0 @@
# This workflow will upload a Python Package using Twine when a release is created
# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python#publishing-to-package-registries
# This workflow uses actions that are not certified by GitHub.
# They are provided by a third-party and are governed by
# separate terms of service, privacy policy, and support
# documentation.
name: Upload Python Package
on:
release:
types: [published]
permissions:
contents: read
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v3
with:
python-version: '3.x'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install build
- name: Build package
run: python -m build
- name: Publish package
uses: pypa/gh-action-pypi-publish@27b31702a0e7fc50959f5ad993c78deac1bdfc29
with:
user: __token__
password: ${{ secrets.PYPI_API_TOKEN }}
+21 -31
View File
@@ -1,33 +1,23 @@
.vscode
crewai
.cache
__pycache__
chroma.sqlite3
test/
dist/
.env
assets/*
.idea
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.pytest_cache
praisonAI.egg-info
flagged
test.yaml
db
praisonai_prompt.txt
watch.sh
docs.sh
# Ignore Sphinx build directory
docs/_build/
docs/source/
docs/build/
.env.local
.env.development.local
.env.test.local
.env.production.local
# Ignore Sphinx cache
docs/_build/doctrees/
docs/_build/doctrees/*
docs/_build/doctrees/.doctrees
# Ignore Sphinx logs and local build files
docs/_build/.buildinfo
docs/_build/.buildinfo/*
docs/_build/.buildinfo/.buildinfo
npm-debug.log*
yarn-debug.log*
yarn-error.log*
-35
View File
@@ -1,35 +0,0 @@
# Read the Docs configuration file for Sphinx projects
# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details
# Required
version: 2
# Set the OS, Python version and other tools you might need
build:
os: ubuntu-22.04
tools:
python: "3.12"
# You can also specify other tool versions:
# nodejs: "20"
# rust: "1.70"
# golang: "1.20"
# Build documentation in the "docs/" directory with Sphinx
sphinx:
configuration: docs/conf.py
# You can configure Sphinx to use a different builder, for instance use the dirhtml builder for simpler URLs
# builder: "dirhtml"
# Fail on all warnings to avoid broken references
# fail_on_warning: true
# Optionally build your docs in additional formats such as PDF and ePub
# formats:
# - pdf
# - epub
# Optional but recommended, declare the Python requirements required
# to build your documentation
# See https://docs.readthedocs.io/en/stable/guides/reproducible-builds.html
# python:
# install:
# - requirements: docs/requirements.txt
-6
View File
@@ -1,6 +0,0 @@
FROM python:3.11-slim
WORKDIR /app
COPY . .
RUN pip install flask praisonai==0.0.21 gunicorn markdown
EXPOSE 8080
CMD ["gunicorn", "-b", "0.0.0.0:8080", "api:app"]
-20
View File
@@ -1,20 +0,0 @@
MIT License
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+38 -252
View File
@@ -1,284 +1,70 @@
# Praison AI
# Getting Started with Create React App
Praison AI, leveraging both AutoGen and CrewAI or any other agent framework, represents a low-code, centralised framework designed to simplify the creation and orchestration of multi-agent systems for various LLM applications, emphasizing ease of use, customization, and human-agent interaction.
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## TL;DR
```bash
pip install praisonai
export OPENAI_API_KEY="Enter your API key"
praisonai --init create a movie script about dog in moon
praisonai
```
## Available Scripts
## Installation
In the project directory, you can run:
```bash
pip install praisonai
```
### `npm start`
## Initialise
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in your browser.
```bash
export OPENAI_API_KEY="Enter your API key"
```
The page will reload when you make changes.\
You may also see any lint errors in the console.
Generate your OPENAI API KEY from here: https://platform.openai.com/api-keys
### `npm test`
Note: You can use other providers such as Ollama, Mistral ... etc. Details are provided at the bottom.
```bash
praisonai --init create a movie script about dog in moon
```
This will automatically create agents.yaml file in the current directory.
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### To initialse with a specific agent framework (Optional):
### `npm run build`
```bash
praisonai --framework autogen --init create movie script about cat in mars
```
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
## Run
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
```bash
praisonai
```
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
or
```bash
python -m praisonai
```
### `npm run eject`
### Specify the agent framework (Optional):
**Note: this is a one-way operation. Once you `eject`, you can't go back!**
```bash
praisonai --framework autogen
```
If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
### Full Automatic Mode
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own.
```bash
praisonai --auto create a movie script about Dog in Moon
```
You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it.
## Create Custom Tools
## Learn More
### TL;DR to Create a Custom Tool
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
```bash
pip install praisonai duckduckgo-search
export OPENAI_API_KEY="Enter your API key"
praisonai --init research about the latest AI News and prepare a detailed report
```
To learn React, check out the [React documentation](https://reactjs.org/).
- Add `- InternetSearchTool` in the agents.yaml file in the tools section.
- Create a file called tools.py and add this code [tools.py](./tools.py)
### Code Splitting
```bash
praisonai
```
This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)
### Pre-requisite to Create a Custom Tool
`agents.yaml` file should be present in the current directory.
### Analyzing the Bundle Size
If it doesn't exist, create it by running the command `praisonai --init research about the latest AI News and prepare a detailed report`.
This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)
### Step 1 to Create a Custom Tool
### Making a Progressive Web App
Create a file called tools.py in the same directory as the agents.yaml file.
This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)
```python
# example tools.py
from duckduckgo_search import DDGS
from praisonai_tools import BaseTool
### Advanced Configuration
class InternetSearchTool(BaseTool):
name: str = "InternetSearchTool"
description: str = "Search Internet for relevant information based on a query or latest news"
This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)
def _run(self, query: str):
ddgs = DDGS()
results = ddgs.text(keywords=query, region='wt-wt', safesearch='moderate', max_results=5)
return results
```
### Deployment
### Step 2 to Create a Custom Tool
This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)
Add the tool to the agents.yaml file as show below under the tools section `- InternetSearchTool`.
### `npm run build` fails to minify
```yaml
framework: crewai
topic: research about the latest AI News and prepare a detailed report
roles:
research_analyst:
backstory: Experienced in gathering and analyzing data related to AI news trends.
goal: Analyze AI News trends
role: Research Analyst
tasks:
gather_data:
description: Conduct in-depth research on the latest AI News trends from reputable
sources.
expected_output: Comprehensive report on current AI News trends.
tools:
- InternetSearchTool
```
## Test
```bash
python -m unittest tests.test
```
## Agents Playbook
### Simple Playbook Example
```yaml
framework: crewai
topic: Artificial Intelligence
roles:
screenwriter:
backstory: 'Skilled in crafting scripts with engaging dialogue about {topic}.'
goal: Create scripts from concepts.
role: Screenwriter
tasks:
scriptwriting_task:
description: 'Develop scripts with compelling characters and dialogue about {topic}.'
expected_output: 'Complete script ready for production.'
```
### Detailed Playbook Example
```yaml
framework: crewai
topic: Artificial Intelligence
roles:
movie_concept_creator:
backstory: 'Creative thinker with a deep understanding of cinematic storytelling,
capable of using AI-generated storylines to create unique and compelling movie
ideas.'
goal: Generate engaging movie concepts using AI storylines
role: Movie Concept Creator
tasks:
movie_concept_development:
description: 'Develop movie concepts from AI-generated storylines, ensuring
they are engaging and have strong narrative arcs.'
expected_output: 'Well-structured movie concept document with character
bios, settings, and plot outlines.'
screenwriter:
backstory: 'Expert in writing engaging dialogue and script structure, able to
turn movie concepts into production-ready scripts.'
goal: Write compelling scripts based on movie concepts
role: Screenwriter
tasks:
scriptwriting_task:
description: 'Turn movie concepts into polished scripts with well-developed
characters, strong dialogue, and effective scene transitions.'
expected_output: 'Production-ready script with a beginning, middle, and
end, along with character development and engaging dialogues.'
editor:
backstory: 'Adept at identifying inconsistencies, improving language usage,
and maintaining the overall flow of the script.'
goal: Refine the scripts and ensure continuity of the movie storyline
role: Editor
tasks:
editing_task:
description: 'Review, edit, and refine the scripts to ensure they are cohesive
and follow a well-structured narrative.'
expected_output: 'A polished final draft of the script with no inconsistencies,
strong character development, and effective dialogue.'
dependencies: []
```
## Include praisonai package in your project
```python
from praisonai import PraisonAI
def basic(): # Basic Mode
praison_ai = PraisonAI(agent_file="agents.yaml")
praison_ai.main()
def advanced(): # Advanced Mode with options
praison_ai = PraisonAI(
agent_file="agents.yaml",
framework="autogen",
)
praison_ai.main()
def auto(): # Full Automatic Mode
praison_ai = PraisonAI(
auto="Create a movie script about car in mars",
framework="autogen"
)
print(praison_ai.framework)
praison_ai.main()
if __name__ == "__main__":
basic()
advanced()
auto()
```
## Deploy
```bash
gcloud init
gcloud services enable run.googleapis.com
gcloud services enable containerregistry.googleapis.com
gcloud services enable cloudbuild.googleapis.com
export OPENAI_MODEL_NAME="gpt-4-turbo-preview"
export OPENAI_API_KEY="Enter your API key"
export OPENAI_API_BASE="https://api.openai.com/v1"
yes | gcloud auth configure-docker us-central1-docker.pkg.dev
gcloud artifacts repositories create praisonai-repository --repository-format=docker --location=us-central1
PROJECT_ID=$(gcloud config get-value project)
TAG="latest"
docker build --platform linux/amd64 -t gcr.io/${PROJECT_ID}/praisonai-app:${TAG} .
docker tag gcr.io/${PROJECT_ID}/praisonai-app:${TAG} us-central1-docker.pkg.dev/${PROJECT_ID}/praisonai-repository/praisonai-app:${TAG}
docker push us-central1-docker.pkg.dev/${PROJECT_ID}/praisonai-repository/praisonai-app:${TAG}
gcloud run deploy praisonai-service \
--image us-central1-docker.pkg.dev/${PROJECT_ID}/praisonai-repository/praisonai-app:${TAG} \
--platform managed \
--region us-central1 \
--allow-unauthenticated \
--set-env-vars OPENAI_MODEL_NAME=${OPENAI_MODEL_NAME},OPENAI_API_KEY=${OPENAI_API_KEY},OPENAI_API_BASE=${OPENAI_API_BASE}
```
## Other Models
```bash
Ollama
OPENAI_API_BASE='http://localhost:11434/v1'
OPENAI_MODEL_NAME='mistral'
OPENAI_API_KEY='NA'
FastChat¶
OPENAI_API_BASE="http://localhost:8001/v1"
OPENAI_MODEL_NAME='oh-2.5m7b-q51'
OPENAI_API_KEY=NA
LM Studio¶
OPENAI_API_BASE="http://localhost:8000/v1"
OPENAI_MODEL_NAME=NA
OPENAI_API_KEY=NA
Mistral API¶
OPENAI_API_BASE=https://api.mistral.ai/v1
OPENAI_MODEL_NAME="mistral-small"
OPENAI_API_KEY=your-mistral-api-key
```
## Contributing
- Fork on GitHub: Use the "Fork" button on the repository page.
- Clone your fork: `git clone https://github.com/yourusername/praisonAI.git`
- Create a branch: `git checkout -b new-feature`
- Make changes and commit: `git commit -am "Add some feature"`
- Push to your fork: `git push origin new-feature`
- Submit a pull request via GitHub's web interface.
- Await feedback from project maintainers.
This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)
-42
View File
@@ -1,42 +0,0 @@
framework: crewai
topic: create a movie about cat in mars based on https://blog.celtx.com/how-to-write-a-good-story/
roles:
story_developer:
backstory: Experienced in crafting compelling narratives for a diverse audience.
goal: Develop an engaging storyline for a movie about cats in Mars
role: Story Developer
tasks:
storyline_creation:
description: Create a captivating storyline for a movie about cats in Mars
inspired by the blog post at https://blog.celtx.com/how-to-write-a-good-story/
expected_output: Detailed storyline with key plot points, character motivations,
and setting descriptions.
tools:
- 'ScrapeWebsiteTool'
screenwriter:
backstory: Proficient in translating complex narratives into engaging screenplay
format.
goal: Transform the storyline into a script
role: Screenwriter
tasks:
script_creation:
description: Transform the developed storyline into a script for the movie
about cats in Mars.
expected_output: Complete script with dialogues, scenes, and stage directions
ready for production.
tools:
- ''
director:
backstory: Experienced in visual storytelling and bringing scripts to life on
screen.
goal: Oversee the production of the movie
role: Director
tasks:
movie_production:
description: Take the script and lead the team to produce the movie 'Cats
in Mars' based on the provided content and script.
expected_output: Completed movie ready for distribution with compelling visuals
and engaging storytelling.
tools:
- ''
dependencies: []
-39
View File
@@ -1,39 +0,0 @@
framework: crewai
topic: research about the causes of lung disease
roles:
research_analyst:
backstory: Experienced in analyzing scientific data related to respiratory health.
goal: Analyze data on lung diseases
role: Research Analyst
tasks:
data_analysis:
description: Gather and analyze data on the causes and risk factors of lung
diseases.
expected_output: Report detailing key findings on lung disease causes.
tools:
- 'PubmedQueryRun'
medical_writer:
backstory: Skilled in translating complex medical information into accessible
content.
goal: Compile comprehensive content on lung disease causes
role: Medical Writer
tasks:
content_creation:
description: Create detailed content summarizing the research findings on
lung disease causes.
expected_output: Document outlining various causes and risk factors of lung
diseases.
tools:
- ''
editor:
backstory: Proficient in editing medical content for accuracy and clarity.
goal: Review and refine content on lung disease causes
role: Editor
tasks:
content_review:
description: Edit and refine the compiled content on lung disease causes for
accuracy and coherence.
expected_output: Finalized document on lung disease causes ready for dissemination.
tools:
- ''
dependencies: []
-42
View File
@@ -1,42 +0,0 @@
framework: crewai
topic: create a movie about cat in mars based on https://www.grammarly.com/blog/how-to-write-a-story/
roles:
story_developer:
backstory: Experienced in crafting compelling narratives for a diverse audience.
goal: Develop an engaging storyline for a movie about cats in Mars
role: Story Developer
tasks:
storyline_creation:
description: Create a captivating storyline for a movie about cats in Mars
inspired by the blog post at https://www.grammarly.com/blog/how-to-write-a-story/
expected_output: Detailed storyline with key plot points, character motivations,
and setting descriptions.
tools:
- 'ScrapeWebsiteTool'
screenwriter:
backstory: Proficient in translating complex narratives into engaging screenplay
format.
goal: Transform the storyline into a script
role: Screenwriter
tasks:
script_creation:
description: Transform the developed storyline into a script for the movie
about cats in Mars.
expected_output: Complete script with dialogues, scenes, and stage directions
ready for production.
tools:
- ''
director:
backstory: Experienced in visual storytelling and bringing scripts to life on
screen.
goal: Oversee the production of the movie
role: Director
tasks:
movie_production:
description: Take the script and lead the team to produce the movie 'Cats
in Mars' based on the provided content and script.
expected_output: Completed movie ready for distribution with compelling visuals
and engaging storytelling.
tools:
- ''
dependencies: []
-43
View File
@@ -1,43 +0,0 @@
framework: crewai
topic: research about nvidia growth
roles:
data_collector:
backstory: An experienced researcher with the ability to efficiently collect and
organize vast amounts of data.
goal: Gather information on Nvidia's growth
role: Data Collector
tasks:
data_collection_task:
description: Collect data on Nvidia's growth from various sources such as
financial reports, news articles, and company announcements.
expected_output: A comprehensive document detailing data points on Nvidia's
growth over the years.
tools:
- 'YouSearchTool'
data_analyst:
backstory: Specializes in extracting insights from large datasets, proficient
in quantitative and qualitative analysis.
goal: Analyze the collected data to identify trends and patterns
role: Data Analyst
tasks:
data_analysis_task:
description: Analyze the collected data to identify key trends and patterns
in Nvidia's growth.
expected_output: An analytical report summarizing trends, patterns, and key
growth metrics of Nvidia.
tools:
- ''
report_preparer:
backstory: Experienced in creating detailed reports and presentations, turning
analytical data into actionable insights.
goal: Generate a final report on Nvidia's growth
role: Report Preparer
tasks:
report_preparation_task:
description: Create a detailed report based on the analysis, highlighting
Nvidia's growth trajectory.
expected_output: A polished, comprehensive report summarizing Nvidia's growth
with visual aids and key insights.
tools:
- ''
dependencies: []
@@ -1,26 +0,0 @@
framework: crewai
topic: research about the latest AI News and prepare a detailed report
roles:
research_analyst:
backstory: Experienced in gathering and analyzing data related to AI news trends.
goal: Analyze AI News trends
role: Research Analyst
tasks:
gather_data:
description: Conduct in-depth research on the latest AI News trends from reputable
sources.
expected_output: Comprehensive report on current AI News trends.
tools:
- 'InternetSearchTool'
content_creator:
backstory: Skilled in writing informative and engaging content about AI News.
goal: Create detailed reports on AI News
role: Content Creator
tasks:
compile_report:
description: Compile all gathered data into a detailed report with analysis
and insights.
expected_output: Well-structured report on the latest AI News with key insights.
tools:
- ''
dependencies: []
@@ -1,39 +0,0 @@
framework: crewai
topic: research about the causes of lung disease
roles:
research_analyst:
backstory: Experienced in analyzing scientific data related to respiratory health.
goal: Analyze data on lung diseases
role: Research Analyst
tasks:
data_analysis:
description: Gather and analyze data on the causes and risk factors of lung
diseases.
expected_output: Report detailing key findings on lung disease causes.
tools:
- 'PubmedQueryRun'
medical_writer:
backstory: Skilled in translating complex medical information into accessible
content.
goal: Compile comprehensive content on lung disease causes
role: Medical Writer
tasks:
content_creation:
description: Create detailed content summarizing the research findings on
lung disease causes.
expected_output: Document outlining various causes and risk factors of lung
diseases.
tools:
- ''
editor:
backstory: Proficient in editing medical content for accuracy and clarity.
goal: Review and refine content on lung disease causes
role: Editor
tasks:
content_review:
description: Edit and refine the compiled content on lung disease causes for
accuracy and coherence.
expected_output: Finalized document on lung disease causes ready for dissemination.
tools:
- ''
dependencies: []
-18
View File
@@ -1,18 +0,0 @@
from flask import Flask
from praisonai import PraisonAI
import markdown
app = Flask(__name__)
def basic():
praison_ai = PraisonAI(agent_file="agents.yaml")
return praison_ai.main()
@app.route('/')
def home():
output = basic()
html_output = markdown.markdown(output)
return f'<html><body>{html_output}</body></html>'
if __name__ == "__main__":
app.run(debug=True)
-20
View File
@@ -1,20 +0,0 @@
# Minimal makefile for Sphinx documentation
#
# You can set these variables from the command line, and also
# from the environment for the first two.
SPHINXOPTS ?=
SPHINXBUILD ?= sphinx-build
SOURCEDIR = .
BUILDDIR = _build
# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
.PHONY: help Makefile
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
-28
View File
@@ -1,28 +0,0 @@
# Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Project information -----------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information
project = 'PraisonAI'
copyright = '2024, Mervin Praison'
author = 'Mervin Praison'
release = '0.0.21'
# -- General configuration ---------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon', 'sphinx_rtd_theme']
templates_path = ['_templates']
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# -- Options for HTML output -------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output
html_theme = 'alabaster'
html_static_path = ['_static']
-20
View File
@@ -1,20 +0,0 @@
.. PraisonAI documentation master file, created by
sphinx-quickstart on Mon Jun 10 12:11:57 2024.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Welcome to PraisonAI's documentation!
=====================================
.. toctree::
:maxdepth: 2
:caption: Contents:
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
-35
View File
@@ -1,35 +0,0 @@
@ECHO OFF
pushd %~dp0
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set SOURCEDIR=.
set BUILDDIR=_build
%SPHINXBUILD% >NUL 2>NUL
if errorlevel 9009 (
echo.
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
echo.installed, then set the SPHINXBUILD environment variable to point
echo.to the full path of the 'sphinx-build' executable. Alternatively you
echo.may add the Sphinx directory to PATH.
echo.
echo.If you don't have Sphinx installed, grab it from
echo.https://www.sphinx-doc.org/
exit /b 1
)
if "%1" == "" goto help
%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
goto end
:help
%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
:end
popd
-25
View File
@@ -1,25 +0,0 @@
from praisonai import PraisonAI
def basic():
praison_ai = PraisonAI(agent_file="agents.yaml")
praison_ai.main()
def advanced():
praison_ai = PraisonAI(
agent_file="agents.yaml",
framework="autogen",
)
praison_ai.main()
def auto():
praison_ai = PraisonAI(
auto="Create a movie script about car in mars",
framework="autogen"
)
print(praison_ai.framework)
praison_ai.main()
if __name__ == "__main__":
basic()
advanced()
auto()
-41
View File
@@ -1,41 +0,0 @@
framework: "crewai"
topic: "Artificial Intelligence"
roles:
researcher:
role: "Senior Data Researcher"
goal: "Uncover cutting-edge developments in {topic}"
backstory: >
You're a seasoned researcher with a knack for uncovering the latest
developments in {topic}. Known for your ability to find the most relevant
information and present it in a clear and concise manner.
tools:
- search_tool:
engine: google
tasks:
research_task:
description: >
Conduct thorough research about {topic}, focusing on the latest
trends and technologies.
expected_output: >
A list of 10 bullet points summarizing key findings with links to
relevant sources.
reporting_analyst:
role: "Reporting Analyst"
goal: "Create detailed reports based on {topic} data analysis and research findings."
backstory: >
You're a meticulous analyst with a keen eye for detail. You're known for
your ability to turn complex data into clear and concise reports, making
it easy for others to understand and act on the information you provide.
tasks:
reporting_task:
description: >
Review the research findings and create a comprehensive report on
{topic}. Include insights, potential opportunities, and recommendations.
expected_output: >
A well-structured report in Markdown format, ready for distribution.
dependencies:
- task: reporting_task
depends_on: research_task
-41
View File
@@ -1,41 +0,0 @@
framework: "autogen"
topic: "Artificial Intelligence"
roles:
narrative_designer:
role: "Narrative Designer"
goal: "Craft engaging storylines and narratives for {topic}"
backstory: >
You're a creative visionary skilled in weaving complex narratives and
developing engaging story worlds within {topic}. Your expertise lies in
conceptualizing the overarching story and ensuring it resonates with the audience.
tasks:
story_concept_development:
description: >
Develop a compelling story concept for {topic}, focusing on originality,
thematic depth, and audience engagement. Outline the main narrative arcs,
characters, and settings.
expected_output: >
A comprehensive document outlining the story concept, including key narrative
arcs, character bios, and settings descriptions.
scriptwriter:
role: "Scriptwriter"
goal: "Transform story concepts into detailed scripts for {topic}"
backstory: >
With a flair for dialogue and a deep understanding of pacing and structure,
you excel at bringing narratives to life through scriptwriting. Your work
turns story concepts into blueprints for compelling {topic} experiences.
tasks:
scriptwriting_task:
description: >
Based on the narrative concept, write a detailed script for {topic}.
Include dialogue, stage directions, and scene descriptions that bring
the story to life.
expected_output: >
A detailed script ready for production, including dialogue, stage
directions, and scene descriptions.
dependencies:
- task: scriptwriting_task
depends_on: story_concept_development
-49
View File
@@ -1,49 +0,0 @@
# 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
from langchain_community.tools.pubmed.tool import PubmedQueryRun
from langchain_community.tools.reddit_search.tool import RedditSearchRun
# pip install tavily-python
from langchain_community.utilities.tavily_search import TavilySearchAPIWrapper
from langchain_community.utilities.you import YouSearchAPIWrapper
# pip install youtube_search
from langchain_community.tools import YouTubeSearchTool
# pip install wikipedia
from langchain_community.utilities import WikipediaAPIWrapper
class TavilyTool(BaseTool):
name: str = "TavilyTool"
description: str = "Search Tavily for relevant information based on a query."
def _run(self, query: str):
api_wrapper = TavilySearchAPIWrapper()
results = api_wrapper.results(query=query, max_results=5)
return results
class YouSearchTool(BaseTool):
name: str = "You Search Tool"
description: str = "Search You.com for relevant information based on a query."
def _run(self, query: str):
api_wrapper = YouSearchAPIWrapper()
results = api_wrapper.results(query=query, max_results=5)
return results
class WikipediaSearchTool(BaseTool):
name: str = "WikipediaSearchTool"
description: str = "Search Wikipedia for relevant information based on a query."
def _run(self, query: str):
api_wrapper = WikipediaAPIWrapper(top_k_results=4, doc_content_chars_max=100)
results = api_wrapper.load(query=query)
return results
+20043
View File
File diff suppressed because it is too large. Load diff
+42
View File
@@ -0,0 +1,42 @@
{
"name": "admin-ui",
"version": "0.1.0",
"private": true,
"dependencies": {
"@chakra-ui/react": "^2.8.2",
"@emotion/react": "^11.11.4",
"@emotion/styled": "^11.11.5",
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"framer-motion": "^11.2.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
Generated
-6171
View File
File diff suppressed because it is too large. Load diff
-2
View File
@@ -1,2 +0,0 @@
from .cli import PraisonAI
from .version import __version__
-10
View File
@@ -1,10 +0,0 @@
# __main__.py
from .cli import PraisonAI
def main():
praison_ai = PraisonAI()
praison_ai.main()
if __name__ == "__main__":
main()
-182
View File
@@ -1,182 +0,0 @@
# praisonai/agents_generator.py
import sys
from .version import __version__
import yaml, os
from rich import print
from dotenv import load_dotenv
from crewai import Agent, Task, Crew
load_dotenv()
import autogen
import gradio as gr
import argparse
from .auto import AutoGenerator
from crewai_tools import (
CodeDocsSearchTool, CSVSearchTool, DirectorySearchTool, DOCXSearchTool, DirectoryReadTool,
FileReadTool, TXTSearchTool, JSONSearchTool, MDXSearchTool, PDFSearchTool, RagTool,
ScrapeElementFromWebsiteTool, ScrapeWebsiteTool, WebsiteSearchTool, XMLSearchTool, YoutubeChannelSearchTool,
YoutubeVideoSearchTool
)
from .inbuilt_tools import *
import inspect
from pathlib import Path
import importlib
import importlib.util
from praisonai_tools import BaseTool
class AgentsGenerator:
def __init__(self, agent_file, framework, config_list):
self.agent_file = agent_file
self.framework = framework
self.config_list = config_list
def is_function_or_decorated(self, obj):
return inspect.isfunction(obj) or hasattr(obj, '__call__')
def load_tools_from_module(self, module_path):
spec = importlib.util.spec_from_file_location("tools_module", module_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return {name: obj for name, obj in inspect.getmembers(module, self.is_function_or_decorated)}
def load_tools_from_module_class(self, module_path):
spec = importlib.util.spec_from_file_location("tools_module", module_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return {name: obj() for name, obj in inspect.getmembers(module, lambda x: inspect.isclass(x) and (x.__module__.startswith('langchain_community.tools') or issubclass(x, BaseTool)) and x is not BaseTool)}
def load_tools_from_package(self, package_path):
tools_dict = {}
for module_file in os.listdir(package_path):
if module_file.endswith('.py') and not module_file.startswith('__'):
module_name = f"{package_path.name}.{module_file[:-3]}" # Remove .py for import
module = importlib.import_module(module_name)
for name, obj in inspect.getmembers(module, self.is_function_or_decorated):
tools_dict[name] = obj
return tools_dict
def generate_crew_and_kickoff(self):
if self.agent_file == '/app/api:app' or self.agent_file == 'api:app':
self.agent_file = 'agents.yaml'
try:
with open(self.agent_file, 'r') as f:
config = yaml.safe_load(f)
except FileNotFoundError:
print(f"File not found: {self.agent_file}")
return
topic = config['topic']
tools_dict = {
'CodeDocsSearchTool': CodeDocsSearchTool(),
'CSVSearchTool': CSVSearchTool(),
'DirectorySearchTool': DirectorySearchTool(),
'DOCXSearchTool': DOCXSearchTool(),
'DirectoryReadTool': DirectoryReadTool(),
'FileReadTool': FileReadTool(),
# 'GithubSearchTool': GithubSearchTool(),
# 'SeperDevTool': SeperDevTool(),
'TXTSearchTool': TXTSearchTool(),
'JSONSearchTool': JSONSearchTool(),
'MDXSearchTool': MDXSearchTool(),
'PDFSearchTool': PDFSearchTool(),
# 'PGSearchTool': PGSearchTool(),
'RagTool': RagTool(),
'ScrapeElementFromWebsiteTool': ScrapeElementFromWebsiteTool(),
'ScrapeWebsiteTool': ScrapeWebsiteTool(),
'WebsiteSearchTool': WebsiteSearchTool(),
'XMLSearchTool': XMLSearchTool(),
'YoutubeChannelSearchTool': YoutubeChannelSearchTool(),
'YoutubeVideoSearchTool': YoutubeVideoSearchTool(),
}
root_directory = os.getcwd()
tools_py_path = os.path.join(root_directory, 'tools.py')
tools_dir_path = Path(root_directory) / 'tools'
if os.path.isfile(tools_py_path):
tools_dict.update(self.load_tools_from_module_class(tools_py_path))
# print("tools.py exists in the root directory. Loading tools.py and skipping tools folder.")
elif tools_dir_path.is_dir():
tools_dict.update(self.load_tools_from_module_class(tools_dir_path))
# print("tools folder exists in the root directory")
framework = self.framework or config.get('framework')
agents = {}
tasks = []
if framework == "autogen":
# Load the LLM configuration dynamically
# print(self.config_list)
llm_config = {"config_list": self.config_list}
# Assuming the user proxy agent is set up as per your requirements
user_proxy = autogen.UserProxyAgent(
name="User",
human_input_mode="NEVER",
is_termination_msg=lambda x: (x.get("content") or "").rstrip().rstrip(".").lower().endswith("terminate") or "TERMINATE" in (x.get("content") or ""),
code_execution_config={
"work_dir": "coding",
"use_docker": False,
},
# additional setup for the user proxy agent
)
for role, details in config['roles'].items():
agent_name = details['role'].format(topic=topic).replace("{topic}", topic)
agent_goal = details['goal'].format(topic=topic)
# Creating an AssistantAgent for each role dynamically
agents[role] = autogen.AssistantAgent(
name=agent_name,
llm_config=llm_config,
system_message=details['backstory'].format(topic=topic)+". Must Reply \"TERMINATE\" in the end when everything is done.",
)
for tool in details.get('tools', []):
if tool in tools_dict:
try:
tool_class = globals()[f'autogen_{type(tools_dict[tool]).__name__}']
print(f"Found {tool_class.__name__} for {tool}")
except KeyError:
print(f"Warning: autogen_{type(tools_dict[tool]).__name__} function not found. Skipping this tool.")
continue
tool_class(agents[role], user_proxy)
# Preparing tasks for initiate_chats
for task_name, task_details in details.get('tasks', {}).items():
description_filled = task_details['description'].format(topic=topic)
expected_output_filled = task_details['expected_output'].format(topic=topic)
chat_task = {
"recipient": agents[role],
"message": description_filled,
"summary_method": "last_msg",
# Additional fields like carryover can be added based on dependencies
}
tasks.append(chat_task)
response = user_proxy.initiate_chats(tasks)
result = "### Output ###\n"+response[-1].summary if hasattr(response[-1], 'summary') else ""
else:
for role, details in config['roles'].items():
role_filled = details['role'].format(topic=topic)
goal_filled = details['goal'].format(topic=topic)
backstory_filled = details['backstory'].format(topic=topic)
# Adding tools to the agent if exists
agent_tools = [tools_dict[tool] for tool in details.get('tools', []) if tool in tools_dict]
agent = Agent(role=role_filled, goal=goal_filled, backstory=backstory_filled, tools=agent_tools, allow_delegation=False)
agents[role] = agent
for task_name, task_details in details.get('tasks', {}).items():
description_filled = task_details['description'].format(topic=topic)
expected_output_filled = task_details['expected_output'].format(topic=topic)
task = Task(description=description_filled, expected_output=expected_output_filled, agent=agent)
tasks.append(task)
crew = Crew(
agents=list(agents.values()),
tasks=tasks,
verbose=2
)
response = crew.kickoff()
result = f"### Task Output ###\n{response}"
return result
-139
View File
@@ -1,139 +0,0 @@
from openai import OpenAI
from pydantic import BaseModel
from typing import Dict, List
import instructor
import os
import json
import yaml
from rich import print
# Define Pydantic models outside of the generate method
class TaskDetails(BaseModel):
description: str
expected_output: str
class RoleDetails(BaseModel):
role: str
goal: str
backstory: str
tasks: Dict[str, TaskDetails]
tools: List[str]
class TeamStructure(BaseModel):
roles: Dict[str, RoleDetails]
class AutoGenerator:
def __init__(self, topic="Movie Story writing about AI", agent_file="test.yaml", framework="crewai"):
self.config_list = [
{
'model': os.environ.get("OPENAI_MODEL_NAME", "gpt-4-turbo-preview"),
'base_url': os.environ.get("OPENAI_API_BASE", "https://api.openai.com/v1"),
}
]
self.topic = topic
self.agent_file = agent_file
self.framework = framework
self.client = instructor.patch(
OpenAI(
base_url=self.config_list[0]['base_url'],
api_key=os.getenv("OPENAI_API_KEY"),
),
mode=instructor.Mode.JSON,
)
def generate(self):
response = self.client.chat.completions.create(
model=self.config_list[0]['model'],
response_model=TeamStructure,
max_retries=10,
messages=[
{"role": "system", "content": "You are a helpful assistant designed to output complex team structures."},
{"role": "user", "content": self.get_user_content()}
]
)
json_data = json.loads(response.model_dump_json())
self.convert_and_save(json_data)
full_path = os.path.abspath(self.agent_file)
return full_path
def convert_and_save(self, json_data):
"""Converts the provided JSON data into the desired YAML format and saves it to a file.
Args:
json_data (dict): The JSON data representing the team structure.
topic (str, optional): The topic to be inserted into the YAML. Defaults to "Artificial Intelligence".
agent_file (str, optional): The name of the YAML file to save. Defaults to "test.yaml".
"""
yaml_data = {
"framework": self.framework,
"topic": self.topic,
"roles": {},
"dependencies": []
}
for role_id, role_details in json_data['roles'].items():
yaml_data['roles'][role_id] = {
"backstory": "" + role_details['backstory'],
"goal": role_details['goal'],
"role": role_details['role'],
"tasks": {},
# "tools": role_details.get('tools', []),
"tools": ['']
}
for task_id, task_details in role_details['tasks'].items():
yaml_data['roles'][role_id]['tasks'][task_id] = {
"description": "" + task_details['description'],
"expected_output": "" + task_details['expected_output']
}
# Save to YAML file, maintaining the order
with open(self.agent_file, 'w') as f:
yaml.dump(yaml_data, f, allow_unicode=True, sort_keys=False)
def get_user_content(self):
user_content = """Generate a team structure for \"""" + self.topic + """\" task.
No Input data will be provided to the team.
The team will work in sequence. First role will pass the output to the next role, and so on.
The last role will generate the final output.
Think step by step.
With maximum 3 roles, each with 1 task. Include role goals, backstories, task descriptions, and expected outputs.
List of Available Tools: CodeDocsSearchTool, CSVSearchTool, DirectorySearchTool, DOCXSearchTool, DirectoryReadTool, FileReadTool, TXTSearchTool, JSONSearchTool, MDXSearchTool, PDFSearchTool, RagTool, ScrapeElementFromWebsiteTool, ScrapeWebsiteTool, WebsiteSearchTool, XMLSearchTool, YoutubeChannelSearchTool, YoutubeVideoSearchTool.
Only use Available Tools. Do Not use any other tools.
Example Below:
Use below example to understand the structure of the output.
The final role you create should satisfy the provided task: """ + self.topic + """.
{
"roles": {
"narrative_designer": {
"role": "Narrative Designer",
"goal": "Create AI storylines",
"backstory": "Skilled in narrative development for AI, with a focus on story resonance.",
"tools": ["ScrapeWebsiteTool"],
"tasks": {
"story_concept_development": {
"description": "Craft a unique AI story concept with depth and engagement using concept from this page the content https://www.asthebirdfliesblog.com/posts/how-to-write-book-story-development .",
"expected_output": "Document with narrative arcs, character bios, and settings."
}
}
},
"scriptwriter": {
"role": "Scriptwriter",
"goal": "Write scripts from AI concepts",
"backstory": "Expert in dialogue and script structure, translating concepts into scripts.",
"tasks": {
"scriptwriting_task": {
"description": "Turn narrative concepts into scripts, including dialogue and scenes.",
"expected_output": "Production-ready script with dialogue and scene details."
}
}
}
}
}
"""
return user_content
# generator = AutoGenerator(framework="crewai", topic="Create a snake game in python")
# print(generator.generate())
-119
View File
@@ -1,119 +0,0 @@
# praisonai/cli.py
import sys
from .version import __version__
import yaml, os
from rich import print
from dotenv import load_dotenv
from crewai import Agent, Task, Crew
load_dotenv()
import autogen
import gradio as gr
import argparse
from .auto import AutoGenerator
from .agents_generator import AgentsGenerator
from .inbuilt_tools import *
class PraisonAI:
def __init__(self, agent_file="agents.yaml", framework="crewai", auto=False, init=False):
self.config_list = [
{
'model': os.environ.get("OPENAI_MODEL_NAME", "gpt-4-turbo-preview"),
'base_url': os.environ.get("OPENAI_API_BASE", "https://api.openai.com/v1"),
}
]
self.agent_file = agent_file
self.framework = framework
self.auto = auto
self.init = init
def main(self):
args = self.parse_args()
if args is None:
agents_generator = AgentsGenerator(self.agent_file, self.framework, self.config_list)
result = agents_generator.generate_crew_and_kickoff()
return result
if args.deploy:
from .deploy import CloudDeployer
deployer = CloudDeployer()
deployer.run_commands()
return
invocation_cmd = "praisonai"
version_string = f"PraisonAI version {__version__}"
if args.framework:
self.framework = args.framework
ui = args.ui
if args.agent_file:
if args.agent_file.startswith("tests.test"): # Argument used for testing purposes
print("test")
else:
self.agent_file = args.agent_file
if args.auto or args.init:
temp_topic = ' '.join(args.auto) if args.auto else ' '.join(args.init)
self.topic = temp_topic
elif self.auto or self.init: # Use the auto attribute if args.auto is not provided
self.topic = self.auto
if args.auto or self.auto:
self.agent_file = "test.yaml"
generator = AutoGenerator(topic=self.topic , framework=self.framework, agent_file=self.agent_file)
self.agent_file = generator.generate()
agents_generator = AgentsGenerator(self.agent_file, self.framework, self.config_list)
result = agents_generator.generate_crew_and_kickoff()
return result
elif args.init or self.init:
self.agent_file = "agents.yaml"
generator = AutoGenerator(topic=self.topic , framework=self.framework, agent_file=self.agent_file)
self.agent_file = generator.generate()
print("File {} created successfully".format(self.agent_file))
return "File {} created successfully".format(self.agent_file)
if ui:
self.create_gradio_interface()
else:
agents_generator = AgentsGenerator(self.agent_file, self.framework, self.config_list)
result = agents_generator.generate_crew_and_kickoff()
return result
def parse_args(self):
parser = argparse.ArgumentParser(prog="praisonai", description="praisonAI command-line interface")
parser.add_argument("--framework", choices=["crewai", "autogen"], help="Specify the framework")
parser.add_argument("--ui", action="store_true", help="Enable UI mode")
parser.add_argument("--auto", nargs=argparse.REMAINDER, help="Enable auto mode and pass arguments for it")
parser.add_argument("--init", nargs=argparse.REMAINDER, help="Enable auto mode and pass arguments for it")
parser.add_argument("agent_file", nargs="?", help="Specify the agent file")
parser.add_argument("--deploy", action="store_true", help="Deploy the application") # New argument
args, unknown_args = parser.parse_known_args()
if unknown_args and unknown_args[0] == '-b' and unknown_args[1] == 'api:app':
args.agent_file = 'agents.yaml'
if args.agent_file == 'api:app' or args.agent_file == '/app/api:app':
args.agent_file = 'agents.yaml'
return args
def create_gradio_interface(self):
def generate_crew_and_kickoff_interface(auto_args, framework):
self.framework = framework
self.agent_file = "test.yaml"
generator = AutoGenerator(topic=auto_args , framework=self.framework)
self.agent_file = generator.generate()
agents_generator = AgentsGenerator(self.agent_file, self.framework, self.config_list)
result = agents_generator.generate_crew_and_kickoff()
return result
gr.Interface(
fn=generate_crew_and_kickoff_interface,
inputs=[gr.Textbox(lines=2, label="Auto Args"), gr.Dropdown(choices=["crewai", "autogen"], label="Framework")],
outputs="textbox",
title="Praison AI Studio",
description="Create Agents and perform tasks",
theme="default"
).launch()
if __name__ == "__main__":
praison_ai = PraisonAI()
praison_ai.main()
-66
View File
@@ -1,66 +0,0 @@
import subprocess
import os
from dotenv import load_dotenv
class CloudDeployer:
def __init__(self):
# Load environment variables from .env file or system
load_dotenv()
self.set_environment_variables()
def create_dockerfile(self):
with open("Dockerfile", "w") as file:
file.write("FROM python:3.11-slim\n")
file.write("WORKDIR /app\n")
file.write("COPY . .\n")
file.write("RUN pip install flask praisonai==0.0.21 gunicorn markdown\n")
file.write("EXPOSE 8080\n")
file.write('CMD ["gunicorn", "-b", "0.0.0.0:8080", "api:app"]\n')
def create_api_file(self):
with open("api.py", "w") as file:
file.write("from flask import Flask\n")
file.write("from praisonai import PraisonAI\n")
file.write("import markdown\n\n")
file.write("app = Flask(__name__)\n\n")
file.write("def basic():\n")
file.write(" praison_ai = PraisonAI(agent_file=\"agents.yaml\")\n")
file.write(" return praison_ai.main()\n\n")
file.write("@app.route('/')\n")
file.write("def home():\n")
file.write(" output = basic()\n")
file.write(" html_output = markdown.markdown(output)\n")
file.write(" return f'<html><body>{html_output}</body></html>'\n\n")
file.write("if __name__ == \"__main__\":\n")
file.write(" app.run(debug=True)\n")
def set_environment_variables(self):
"""Sets environment variables with fallback to .env values or defaults."""
os.environ["OPENAI_MODEL_NAME"] = os.getenv("OPENAI_MODEL_NAME", "gpt-4-turbo-preview")
os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY", "Enter your API key")
os.environ["OPENAI_API_BASE"] = os.getenv("OPENAI_API_BASE", "https://api.openai.com/v1")
def run_commands(self):
self.create_api_file()
self.create_dockerfile()
"""Runs a sequence of shell commands for deployment, continues on error."""
commands = [
"yes | gcloud auth configure-docker us-central1-docker.pkg.dev",
"gcloud artifacts repositories create praisonai-repository --repository-format=docker --location=us-central1",
"docker build --platform linux/amd64 -t gcr.io/$(gcloud config get-value project)/praisonai-app:latest .",
"docker tag gcr.io/$(gcloud config get-value project)/praisonai-app:latest us-central1-docker.pkg.dev/$(gcloud config get-value project)/praisonai-repository/praisonai-app:latest",
"docker push us-central1-docker.pkg.dev/$(gcloud config get-value project)/praisonai-repository/praisonai-app:latest",
"gcloud run deploy praisonai-service --image us-central1-docker.pkg.dev/$(gcloud config get-value project)/praisonai-repository/praisonai-app:latest --platform managed --region us-central1 --allow-unauthenticated --set-env-vars OPENAI_MODEL_NAME=${OPENAI_MODEL_NAME},OPENAI_API_KEY=${OPENAI_API_KEY},OPENAI_API_BASE=${OPENAI_API_BASE}"
]
for cmd in commands:
try:
subprocess.run(cmd, shell=True, check=True)
except subprocess.CalledProcessError as e:
print(f"ERROR: Command '{e.cmd}' failed with exit status {e.returncode}")
print(f"Continuing with the next command...")
# Usage
if __name__ == "__main__":
deployer = CloudDeployer()
deployer.run_commands()
-2
View File
@@ -1,2 +0,0 @@
# from .base_tool import BaseTool, Tool, tool
from .autogen_tools import *
-203
View File
@@ -1,203 +0,0 @@
# praisonai/inbuilt_tools/autogen_tools.py
from crewai_tools import (
CodeDocsSearchTool, CSVSearchTool, DirectorySearchTool, DOCXSearchTool, DirectoryReadTool,
FileReadTool, TXTSearchTool, JSONSearchTool, MDXSearchTool, PDFSearchTool, RagTool,
ScrapeElementFromWebsiteTool, ScrapeWebsiteTool, WebsiteSearchTool, XMLSearchTool, YoutubeChannelSearchTool,
YoutubeVideoSearchTool
)
from typing import Any
from autogen import register_function
import os
import importlib
from pathlib import Path
import os
import inspect
import sys
def create_autogen_tool_function(tool_name):
def autogen_tool(assistant, user_proxy):
def register_tool(tool_class, tool_name, tool_description, assistant, user_proxy):
def tool_func(query: str) -> Any:
tool_instance = tool_class()
return tool_instance.run(query=query)
register_function(tool_func, caller=assistant, executor=user_proxy, name=tool_name, description=tool_description)
root_directory = os.getcwd()
tools_py_path = os.path.join(root_directory, 'tools.py')
tools_dir_path = Path(root_directory) / 'tools'
if os.path.isfile(tools_py_path):
print(f"{tools_py_path} exists in the root directory. Loading {tools_py_path} and skipping tools folder.")
tool_module = importlib.import_module("tools")
elif tools_dir_path.is_dir():
print(f"tools folder exists in the root directory. Loading {tool_name} from tools/{tool_name}.py.")
tool_module = importlib.import_module(f"tools.{tool_name}")
else:
raise ImportError("Neither tools.py nor tools directory found in the root directory.")
Tool = getattr(tool_module, tool_name)
register_tool(Tool, tool_name, f"Description for {tool_name}", assistant, user_proxy)
return autogen_tool
# Load tools.py
sys.path.insert(0, os.getcwd())
root_directory = os.getcwd()
tools_py_path = os.path.join(root_directory, 'tools.py')
tools_dir_path = Path(root_directory) / 'tools'
tools_module = None
if os.path.isfile(tools_py_path):
print(f"{tools_py_path} exists in the root directory. Loading {tools_py_path} and skipping tools folder.")
tools_module = importlib.import_module("tools")
elif tools_dir_path.is_dir():
print(f"tools folder exists in the root directory. Loading {tool_name} from tools/{tool_name}.py.")
tools_module = importlib.import_module(f"tools.{tool_name}")
# Create autogen_TOOL_NAME_HERE function for each tool
if tools_module is not None:
for name, obj in inspect.getmembers(tools_module):
if inspect.isclass(obj):
globals()[f"autogen_{name}"] = create_autogen_tool_function(name)
def autogen_CodeDocsSearchTool(assistant, user_proxy):
def register_code_docs_search_tool(tool_class, tool_name, tool_description, assistant, user_proxy):
def tool_func(docs_url: str, search_query: str) -> Any:
tool_instance = tool_class(docs_url=docs_url, search_query=search_query)
return tool_instance.run()
register_function(tool_func, caller=assistant, executor=user_proxy, name=tool_name, description=tool_description)
register_code_docs_search_tool(CodeDocsSearchTool, "code_docs_search_tool", "Search a Code Docs content(search_query: 'string', docs_url: 'string') - A tool that can be used to semantic search a query from a Code Docs content.", assistant, user_proxy)
def autogen_CSVSearchTool(assistant, user_proxy):
def register_csv_search_tool(tool_class, tool_name, tool_description, assistant, user_proxy):
def tool_func(csv: str, search_query: str) -> Any:
tool_instance = tool_class(csv=csv, search_query=search_query)
return tool_instance.run()
register_function(tool_func, caller=assistant, executor=user_proxy, name=tool_name, description=tool_description)
register_csv_search_tool(CSVSearchTool, "csv_search_tool", "Search a CSV's content(search_query: 'string', csv: 'string') - A tool that can be used to semantic search a query from a CSV's content.", assistant, user_proxy)
def autogen_DirectorySearchTool(assistant, user_proxy):
def register_directory_search_tool(tool_class, tool_name, tool_description, assistant, user_proxy):
def tool_func(directory: str, search_query: str) -> Any:
tool_instance = tool_class(directory=directory, search_query=search_query)
return tool_instance.run()
register_function(tool_func, caller=assistant, executor=user_proxy, name=tool_name, description=tool_description)
register_directory_search_tool(DirectorySearchTool, "directory_search_tool", "Search a directory's content(search_query: 'string', directory: 'string') - A tool that can be used to semantic search a query from a directory's content.", assistant, user_proxy)
def autogen_DOCXSearchTool(assistant, user_proxy):
def register_docx_search_tool(tool_class, tool_name, tool_description, assistant, user_proxy):
def tool_func(docx: str, search_query: str) -> Any:
tool_instance = tool_class(docx=docx, search_query=search_query)
return tool_instance.run()
register_function(tool_func, caller=assistant, executor=user_proxy, name=tool_name, description=tool_description)
register_docx_search_tool(DOCXSearchTool, "docx_search_tool", "Search a DOCX's content(search_query: 'string', docx: 'string') - A tool that can be used to semantic search a query from a DOCX's content.", assistant, user_proxy)
# DirectoryReadTool
def autogen_DirectoryReadTool(assistant, user_proxy):
def register_directory_read_tool(tool_class, tool_name, tool_description, assistant, user_proxy):
def tool_func(directory: str) -> Any:
tool_instance = tool_class(directory=directory)
return tool_instance.run()
register_function(tool_func, caller=assistant, executor=user_proxy, name=tool_name, description=tool_description)
register_directory_read_tool(DirectoryReadTool, "directory_read_tool", "List files in directory(directory: 'string') - A tool that can be used to recursively list a directory's content.", assistant, user_proxy)
# FileReadTool
def autogen_FileReadTool(assistant, user_proxy):
def register_file_read_tool(tool_class, tool_name, tool_description, assistant, user_proxy):
def tool_func(file_path: str) -> Any:
tool_instance = tool_class(file_path=file_path)
return tool_instance.run()
register_function(tool_func, caller=assistant, executor=user_proxy, name=tool_name, description=tool_description)
register_file_read_tool(FileReadTool, "file_read_tool", "Read a file's content(file_path: 'string') - A tool that can be used to read a file's content.", assistant, user_proxy)
# TXTSearchTool
def autogen_TXTSearchTool(assistant, user_proxy):
def register_txt_search_tool(tool_class, tool_name, tool_description, assistant, user_proxy):
def tool_func(txt: str, search_query: str) -> Any:
tool_instance = tool_class(txt=txt, search_query=search_query)
return tool_instance.run()
register_function(tool_func, caller=assistant, executor=user_proxy, name=tool_name, description=tool_description)
register_txt_search_tool(TXTSearchTool, "txt_search_tool", "Search a txt's content(search_query: 'string', txt: 'string') - A tool that can be used to semantic search a query from a txt's content.", assistant, user_proxy)
def autogen_JSONSearchTool(assistant, user_proxy):
def register_json_search_tool(tool_class, tool_name, tool_description, assistant, user_proxy):
def tool_func(json_path: str, search_query: str) -> Any:
tool_instance = tool_class(json_path=json_path, search_query=search_query)
return tool_instance.run()
register_function(tool_func, caller=assistant, executor=user_proxy, name=tool_name, description=tool_description)
register_json_search_tool(JSONSearchTool, "json_search_tool", "Search a JSON's content(search_query: 'string', json_path: 'string') - A tool that can be used to semantic search a query from a JSON's content.", assistant, user_proxy)
def autogen_MDXSearchTool(assistant, user_proxy):
def register_mdx_search_tool(tool_class, tool_name, tool_description, assistant, user_proxy):
def tool_func(mdx: str, search_query: str) -> Any:
tool_instance = tool_class(mdx=mdx, search_query=search_query)
return tool_instance.run()
register_function(tool_func, caller=assistant, executor=user_proxy, name=tool_name, description=tool_description)
register_mdx_search_tool(MDXSearchTool, "mdx_search_tool", "Search a MDX's content(search_query: 'string', mdx: 'string') - A tool that can be used to semantic search a query from a MDX's content.", assistant, user_proxy)
def autogen_PDFSearchTool(assistant, user_proxy):
def register_pdf_search_tool(tool_class, tool_name, tool_description, assistant, user_proxy):
def tool_func(pdf: str, search_query: str) -> Any:
tool_instance = tool_class(pdf=pdf, search_query=search_query)
return tool_instance.run()
register_function(tool_func, caller=assistant, executor=user_proxy, name=tool_name, description=tool_description)
register_pdf_search_tool(PDFSearchTool, "pdf_search_tool", "Search a PDF's content(search_query: 'string', pdf: 'string') - A tool that can be used to semantic search a query from a PDF's content.", assistant, user_proxy)
def autogen_RagTool(assistant, user_proxy):
def register_rag_tool(tool_class, tool_name, tool_description, assistant, user_proxy):
def tool_func(query: str, data: Any) -> Any:
tool_instance = tool_class(query=query, data=data)
return tool_instance.run()
register_function(tool_func, caller=assistant, executor=user_proxy, name=tool_name, description=tool_description)
register_rag_tool(RagTool, "rag_tool", "Knowledge base(query: 'string', data: Any) - A knowledge base that can be used to answer questions.", assistant, user_proxy)
def autogen_ScrapeElementFromWebsiteTool(assistant, user_proxy):
def register_scrape_element_from_website_tool(tool_class, tool_name, tool_description, assistant, user_proxy):
def tool_func(website_url: str, element_query: str) -> Any:
tool_instance = tool_class(website_url=website_url, element_query=element_query)
return tool_instance.run()
register_function(tool_func, caller=assistant, executor=user_proxy, name=tool_name, description=tool_description)
register_scrape_element_from_website_tool(ScrapeElementFromWebsiteTool, "scrape_element_from_website_tool", "Scrape an element from a website(element_query: 'string', website_url: 'string') - A tool that can be used to scrape an element from a website.", assistant, user_proxy)
def autogen_ScrapeWebsiteTool(assistant, user_proxy):
def register_scrape_website_tool(tool_class, tool_name, tool_description, assistant, user_proxy):
def tool_func(website_url: str) -> Any:
tool_instance = tool_class(website_url=website_url)
return tool_instance.run()
register_function(tool_func, caller=assistant, executor=user_proxy, name=tool_name, description=tool_description)
register_scrape_website_tool(ScrapeWebsiteTool, "scrape_website_tool", "Read website content(website_url: 'string') - A tool that can be used to read content from a specified website.", assistant, user_proxy)
def autogen_WebsiteSearchTool(assistant, user_proxy):
def register_website_search_tool(tool_class, tool_name, tool_description, assistant, user_proxy):
def tool_func(website: str, search_query: str) -> Any:
tool_instance = tool_class(website=website, search_query=search_query)
return tool_instance.run()
register_function(tool_func, caller=assistant, executor=user_proxy, name=tool_name, description=tool_description)
register_website_search_tool(WebsiteSearchTool, "website_search_tool", "Search in a specific website(search_query: 'string', website: 'string') - A tool that can be used to semantic search a query from a specific URL content.", assistant, user_proxy)
def autogen_XMLSearchTool(assistant, user_proxy):
def register_xml_search_tool(tool_class, tool_name, tool_description, assistant, user_proxy):
def tool_func(xml: str, search_query: str) -> Any:
tool_instance = tool_class(xml=xml, search_query=search_query)
return tool_instance.run()
register_function(tool_func, caller=assistant, executor=user_proxy, name=tool_name, description=tool_description)
register_xml_search_tool(XMLSearchTool, "xml_search_tool", "Search a XML's content(search_query: 'string', xml: 'string') - A tool that can be used to semantic search a query from a XML's content.", assistant, user_proxy)
def autogen_YoutubeChannelSearchTool(assistant, user_proxy):
def register_youtube_channel_search_tool(tool_class, tool_name, tool_description, assistant, user_proxy):
def tool_func(youtube_channel_handle: str, search_query: str) -> Any:
tool_instance = tool_class(youtube_channel_handle=youtube_channel_handle, search_query=search_query)
return tool_instance.run()
register_function(tool_func, caller=assistant, executor=user_proxy, name=tool_name, description=tool_description)
register_youtube_channel_search_tool(YoutubeChannelSearchTool, "youtube_channel_search_tool", "Search a Youtube Channels content(search_query: 'string', youtube_channel_handle: 'string') - A tool that can be used to semantic search a query from a Youtube Channels content.", assistant, user_proxy)
def autogen_YoutubeVideoSearchTool(assistant, user_proxy):
def register_youtube_video_search_tool(tool_class, tool_name, tool_description, assistant, user_proxy):
def tool_func(youtube_video_url: str, search_query: str) -> Any:
tool_instance = tool_class(youtube_video_url=youtube_video_url, search_query=search_query)
return tool_instance.run()
register_function(tool_func, caller=assistant, executor=user_proxy, name=tool_name, description=tool_description)
register_youtube_video_search_tool(YoutubeVideoSearchTool, "youtube_video_search_tool", "Search a Youtube Video content(search_query: 'string', youtube_video_url: 'string') - A tool that can be used to semantic search a query from a Youtube Video content.", assistant, user_proxy)
-93
View File
@@ -1,93 +0,0 @@
import yaml, os
from rich import print
from dotenv import load_dotenv
from crewai import Agent, Task, Crew
load_dotenv()
import autogen
config_list = [
{
'model': os.environ.get("OPENAI_MODEL_NAME", "gpt-3.5-turbo"),
'base_url': os.environ.get("OPENAI_API_BASE", "https://api.openai.com/v1"),
}
]
def generate_crew_and_kickoff(agent_file):
with open(agent_file, 'r') as f:
config = yaml.safe_load(f)
topic = config['topic']
framework = config['framework']
agents = {}
tasks = []
if framework == "autogen":
# Load the LLM configuration dynamically
print(config_list)
llm_config = {"config_list": config_list}
for role, details in config['roles'].items():
agent_name = details['role'].format(topic=topic).replace("{topic}", topic)
agent_goal = details['goal'].format(topic=topic)
# Creating an AssistantAgent for each role dynamically
agents[role] = autogen.AssistantAgent(
name=agent_name,
llm_config=llm_config,
system_message=details['backstory'].format(topic=topic)+". Reply \"TERMINATE\" in the end when everything is done.",
)
# Preparing tasks for initiate_chats
for task_name, task_details in details.get('tasks', {}).items():
description_filled = task_details['description'].format(topic=topic)
expected_output_filled = task_details['expected_output'].format(topic=topic)
chat_task = {
"recipient": agents[role],
"message": description_filled,
"summary_method": "last_msg", # Customize as needed
# Additional fields like carryover can be added based on dependencies
}
tasks.append(chat_task)
# Assuming the user proxy agent is set up as per your requirements
user = autogen.UserProxyAgent(
name="User",
human_input_mode="NEVER",
is_termination_msg=lambda x: (x.get("content") or "").rstrip().endswith("TERMINATE"),
code_execution_config={
"work_dir": "coding",
"use_docker": False,
},
# additional setup for the user proxy agent
)
response = user.initiate_chats(tasks)
result = "### Output ###\n"+response[-1].summary if hasattr(response[-1], 'summary') else ""
else:
for role, details in config['roles'].items():
role_filled = details['role'].format(topic=topic)
goal_filled = details['goal'].format(topic=topic)
backstory_filled = details['backstory'].format(topic=topic)
# Assume tools are loaded and handled here as per your requirements
agent = Agent(role=role_filled, goal=goal_filled, backstory=backstory_filled)
agents[role] = agent
for task_name, task_details in details.get('tasks', {}).items():
description_filled = task_details['description'].format(topic=topic)
expected_output_filled = task_details['expected_output'].format(topic=topic)
task = Task(description=description_filled, expected_output=expected_output_filled, agent=agent)
tasks.append(task)
crew = Crew(
agents=list(agents.values()),
tasks=tasks,
verbose=2
)
result = crew.kickoff()
return result
if __name__ == "__main__":
agent_file = "agents.yaml"
result = generate_crew_and_kickoff(agent_file)
print(result)
-1
View File
@@ -1 +0,0 @@
__version__ = "0.0.1"
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

+43
View File
@@ -0,0 +1,43 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

+25
View File
@@ -0,0 +1,25 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
+3
View File
@@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:
-36
View File
@@ -1,36 +0,0 @@
[tool.poetry]
name = "praisonAI"
version = "0.0.21"
description = "praisonAI application combines AutoGen and CrewAI or similar frameworks into a low-code solution for building and managing multi-agent LLM systems, focusing on simplicity, customization, and efficient human-agent collaboration."
authors = ["Mervin Praison"]
license = ""
readme = "README.md"
[tool.poetry.urls]
Homepage = "https://github.com/mervinpraison/praisonAI"
Repository = "https://github.com/mervinpraison/praisonAI"
[tool.setuptools]
packages = ["praisonAI"]
[tool.poetry.dependencies]
python = ">=3.10,<3.13"
rich = ">=13.7"
pyautogen = ">=0.2.19"
crewai = ">=0.22.5"
gradio = ">=4.20.0"
Flask = ">=3.0.0"
markdown = ">=3.5"
crewai-tools = "^0.1.1"
praisonai-tools = ">=0.0.4"
[tool.poetry.dev-dependencies]
pytest = "^8.0.0"
pre-commit = "^3.7"
[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"
[tool.poetry.scripts]
praisonai = "praisonai.__main__:main"
-7
View File
@@ -1,7 +0,0 @@
rich>=13.7
pyautogen>=0.2.19
crewai>=0.22.5
gradio>=4.20.0
crewai_tools
duckduckgo_search
praisonai_tools
+38
View File
@@ -0,0 +1,38 @@
.App {
text-align: center;
}
.App-logo {
height: 40vmin;
pointer-events: none;
}
@media (prefers-reduced-motion: no-preference) {
.App-logo {
animation: App-logo-spin infinite 20s linear;
}
}
.App-header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}
.App-link {
color: #61dafb;
}
@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
+13
View File
@@ -0,0 +1,13 @@
import React from 'react';
import './App.css';
import SettingsForm from './SettingsForm'; // Import the SettingsForm component
function App() {
return (
<div className="App">
<SettingsForm /> {/* Render the SettingsForm component */}
</div>
);
}
export default App;
+8
View File
@@ -0,0 +1,8 @@
import { render, screen } from '@testing-library/react';
import App from './App';
test('renders learn react link', () => {
render(<App />);
const linkElement = screen.getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();
});
+112
View File
@@ -0,0 +1,112 @@
import React, { useState } from 'react';
import {
Container,
FormControl,
FormLabel,
Input,
Button,
VStack,
} from '@chakra-ui/react';
// Mocking wpApiSettings for development purposes. This should be replaced with the actual object provided by WordPress in production.
const wpApiSettings = { nonce: 'dev-nonce' }; // This line is added to mock the wpApiSettings object
const SettingsForm = () => {
const [patreonClientId, setPatreonClientId] = useState('');
const [patreonClientSecret, setPatreonClientSecret] = useState('');
const [youtubeApiKey, setYoutubeApiKey] = useState('');
const [file, setFile] = useState(null);
const handleSubmit = (event) => {
event.preventDefault();
// Handle the submission logic here
// This will involve saving the API credentials to the WordPress database
// For now, we'll log the credentials to the console
console.log({
patreonClientId,
patreonClientSecret,
youtubeApiKey,
});
// TODO: Implement API call to save these settings in WordPress
};
const handleFileChange = (event) => {
setFile(event.target.files[0]);
};
const handleFileUpload = async (event) => {
event.preventDefault();
if (file) {
const formData = new FormData();
formData.append('file', file);
try {
const response = await fetch('/wp-json/patreon-youtube/v1/upload_media', {
method: 'POST',
headers: {
'X-WP-Nonce': wpApiSettings.nonce,
},
body: formData,
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const result = await response.json();
console.log('File uploaded successfully:', result);
// TODO: Handle the successful upload (e.g., display a success message, clear the form, etc.)
} catch (error) {
console.error('File upload error:', error);
// TODO: Handle the upload error (e.g., display an error message to the user)
}
} else {
console.error('No file selected');
// TODO: Inform the user that no file was selected
}
};
return (
<Container>
<form onSubmit={handleSubmit}>
<VStack spacing={4}>
<FormControl id="patreon-client-id">
<FormLabel>Patreon Client ID</FormLabel>
<Input
type="text"
value={patreonClientId}
onChange={(e) => setPatreonClientId(e.target.value)}
/>
</FormControl>
<FormControl id="patreon-client-secret">
<FormLabel>Patreon Client Secret</FormLabel>
<Input
type="text"
value={patreonClientSecret}
onChange={(e) => setPatreonClientSecret(e.target.value)}
/>
</FormControl>
<FormControl id="youtube-api-key">
<FormLabel>YouTube API Key</FormLabel>
<Input
type="text"
value={youtubeApiKey}
onChange={(e) => setYoutubeApiKey(e.target.value)}
/>
</FormControl>
<FormControl id="file-upload">
<FormLabel>Upload Media</FormLabel>
<Input
type="file"
onChange={handleFileChange}
/>
<Button onClick={handleFileUpload} colorScheme="blue">Upload</Button>
</FormControl>
<Button type="submit" colorScheme="blue">Save Settings</Button>
</VStack>
</form>
</Container>
);
};
export default SettingsForm;
+13
View File
@@ -0,0 +1,13 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}
+17
View File
@@ -0,0 +1,17 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 841.9 595.3"><g fill="#61DAFB"><path d="M666.3 296.5c0-32.5-40.7-63.3-103.1-82.4 14.4-63.6 8-114.2-20.2-130.4-6.5-3.8-14.1-5.6-22.4-5.6v22.3c4.6 0 8.3.9 11.4 2.6 13.6 7.8 19.5 37.5 14.9 75.7-1.1 9.4-2.9 19.3-5.1 29.4-19.6-4.8-41-8.5-63.5-10.9-13.5-18.5-27.5-35.3-41.6-50 32.6-30.3 63.2-46.9 84-46.9V78c-27.5 0-63.5 19.6-99.9 53.6-36.4-33.8-72.4-53.2-99.9-53.2v22.3c20.7 0 51.4 16.5 84 46.6-14 14.7-28 31.4-41.3 49.9-22.6 2.4-44 6.1-63.6 11-2.3-10-4-19.7-5.2-29-4.7-38.2 1.1-67.9 14.6-75.8 3-1.8 6.9-2.6 11.5-2.6V78.5c-8.4 0-16 1.8-22.6 5.6-28.1 16.2-34.4 66.7-19.9 130.1-62.2 19.2-102.7 49.9-102.7 82.3 0 32.5 40.7 63.3 103.1 82.4-14.4 63.6-8 114.2 20.2 130.4 6.5 3.8 14.1 5.6 22.5 5.6 27.5 0 63.5-19.6 99.9-53.6 36.4 33.8 72.4 53.2 99.9 53.2 8.4 0 16-1.8 22.6-5.6 28.1-16.2 34.4-66.7 19.9-130.1 62-19.1 102.5-49.9 102.5-82.3zm-130.2-66.7c-3.7 12.9-8.3 26.2-13.5 39.5-4.1-8-8.4-16-13.1-24-4.6-8-9.5-15.8-14.4-23.4 14.2 2.1 27.9 4.7 41 7.9zm-45.8 106.5c-7.8 13.5-15.8 26.3-24.1 38.2-14.9 1.3-30 2-45.2 2-15.1 0-30.2-.7-45-1.9-8.3-11.9-16.4-24.6-24.2-38-7.6-13.1-14.5-26.4-20.8-39.8 6.2-13.4 13.2-26.8 20.7-39.9 7.8-13.5 15.8-26.3 24.1-38.2 14.9-1.3 30-2 45.2-2 15.1 0 30.2.7 45 1.9 8.3 11.9 16.4 24.6 24.2 38 7.6 13.1 14.5 26.4 20.8 39.8-6.3 13.4-13.2 26.8-20.7 39.9zm32.3-13c5.4 13.4 10 26.8 13.8 39.8-13.1 3.2-26.9 5.9-41.2 8 4.9-7.7 9.8-15.6 14.4-23.7 4.6-8 8.9-16.1 13-24.1zM421.2 430c-9.3-9.6-18.6-20.3-27.8-32 9 .4 18.2.7 27.5.7 9.4 0 18.7-.2 27.8-.7-9 11.7-18.3 22.4-27.5 32zm-74.4-58.9c-14.2-2.1-27.9-4.7-41-7.9 3.7-12.9 8.3-26.2 13.5-39.5 4.1 8 8.4 16 13.1 24 4.7 8 9.5 15.8 14.4 23.4zM420.7 163c9.3 9.6 18.6 20.3 27.8 32-9-.4-18.2-.7-27.5-.7-9.4 0-18.7.2-27.8.7 9-11.7 18.3-22.4 27.5-32zm-74 58.9c-4.9 7.7-9.8 15.6-14.4 23.7-4.6 8-8.9 16-13 24-5.4-13.4-10-26.8-13.8-39.8 13.1-3.1 26.9-5.8 41.2-7.9zm-90.5 125.2c-35.4-15.1-58.3-34.9-58.3-50.6 0-15.7 22.9-35.6 58.3-50.6 8.6-3.7 18-7 27.7-10.1 5.7 19.6 13.2 40 22.5 60.9-9.2 20.8-16.6 41.1-22.2 60.6-9.9-3.1-19.3-6.5-28-10.2zM310 490c-13.6-7.8-19.5-37.5-14.9-75.7 1.1-9.4 2.9-19.3 5.1-29.4 19.6 4.8 41 8.5 63.5 10.9 13.5 18.5 27.5 35.3 41.6 50-32.6 30.3-63.2 46.9-84 46.9-4.5-.1-8.3-1-11.3-2.7zm237.2-76.2c4.7 38.2-1.1 67.9-14.6 75.8-3 1.8-6.9 2.6-11.5 2.6-20.7 0-51.4-16.5-84-46.6 14-14.7 28-31.4 41.3-49.9 22.6-2.4 44-6.1 63.6-11 2.3 10.1 4.1 19.8 5.2 29.1zm38.5-66.7c-8.6 3.7-18 7-27.7 10.1-5.7-19.6-13.2-40-22.5-60.9 9.2-20.8 16.6-41.1 22.2-60.6 9.9 3.1 19.3 6.5 28.1 10.2 35.4 15.1 58.3 34.9 58.3 50.6-.1 15.7-23 35.6-58.4 50.6zM320.8 78.4z"/><circle cx="420.9" cy="296.5" r="45.7"/><path d="M520.5 78.1z"/></g></svg>

After

Width:  |  Height:  |  Size: 2.6 KiB

+13
View File
@@ -0,0 +1,13 @@
const reportWebVitals = onPerfEntry => {
if (onPerfEntry && onPerfEntry instanceof Function) {
import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
getCLS(onPerfEntry);
getFID(onPerfEntry);
getFCP(onPerfEntry);
getLCP(onPerfEntry);
getTTFB(onPerfEntry);
});
}
};
export default reportWebVitals;
+5
View File
@@ -0,0 +1,5 @@
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';
-30
View File
@@ -1,30 +0,0 @@
#!/bin/bash
# Check the first argument provided to the script for platform selection
if [ "$1" = "groq" ]; then
# Check for a second argument for the model name, default to mixtral-8x7b-32768 if not provided
MODEL_NAME=${2:-mixtral-8x7b-32768}
# Set environment variables for Groq configuration with dynamic model name
export OPENAI_MODEL_NAME=$MODEL_NAME
export OPENAI_API_BASE=https://api.groq.com/openai/v1
export OPENAI_API_KEY=$(echo $GROQ_API_KEY)
echo "Groq configuration initiated with model $MODEL_NAME."
elif [ "$1" = "openai" ] || [ -z "$1" ]; then
# Check for a second argument for the model name, default to gpt-3.5-turbo if not provided
MODEL_NAME=${2:-gpt-3.5-turbo}
# Set environment variables for OpenAI configuration with dynamic model name
export OPENAI_MODEL_NAME=$MODEL_NAME
export OPENAI_API_BASE=https://api.openai.com/v1
export OPENAI_API_KEY=$(echo $OAI_API_KEY)
echo "OpenAI configuration initiated with model $MODEL_NAME."
elif [ "$1" = "ollama" ]; then
# Check for a second argument for the model name, default to a custom model if not provided
MODEL_NAME=${2:-default-ollama-model}
# Set environment variables for Ollama local configuration with dynamic model name
export OPENAI_MODEL_NAME=$MODEL_NAME
export OPENAI_API_BASE=http://127.0.0.1:11434
export OPENAI_API_KEY=$(echo $OLLAMA_API_KEY)
# Set up SSH public key
export SSH_PUBLIC_KEY="ssh-ed25519 AAAA..."
echo "Ollama local model configuration initiated with model $MODEL_NAME.
fi
View File
Whitespace-only changes.
-12
View File
@@ -1,12 +0,0 @@
from praisonai import PraisonAI
def advanced():
praison_ai = PraisonAI(
agent_file="agents.yaml",
framework="autogen",
)
print(praison_ai)
return praison_ai.main()
if __name__ == "__main__":
print(advanced())
-41
View File
@@ -1,41 +0,0 @@
framework: "crewai"
topic: "Artificial Intelligence"
roles:
narrative_designer:
role: "Narrative Designer"
goal: "Craft engaging storylines and narratives for {topic}"
backstory: >
You're a creative visionary skilled in weaving complex narratives and
developing engaging story worlds within {topic}. Your expertise lies in
conceptualizing the overarching story and ensuring it resonates with the audience.
tasks:
story_concept_development:
description: >
Develop a compelling story concept for {topic}, focusing on originality,
thematic depth, and audience engagement. Outline the main narrative arcs,
characters, and settings.
expected_output: >
A comprehensive document outlining the story concept, including key narrative
arcs, character bios, and settings descriptions.
scriptwriter:
role: "Scriptwriter"
goal: "Transform story concepts into detailed scripts for {topic}"
backstory: >
With a flair for dialogue and a deep understanding of pacing and structure,
you excel at bringing narratives to life through scriptwriting. Your work
turns story concepts into blueprints for compelling {topic} experiences.
tasks:
scriptwriting_task:
description: >
Based on the narrative concept, write a detailed script for {topic}.
Include dialogue, stage directions, and scene descriptions that bring
the story to life.
expected_output: >
A detailed script ready for production, including dialogue, stage
directions, and scene descriptions.
dependencies:
- task: scriptwriting_task
depends_on: story_concept_development
-12
View File
@@ -1,12 +0,0 @@
from praisonai import PraisonAI
def auto():
praison_ai = PraisonAI(
auto="Create a movie script about car in mars",
framework="autogen"
)
print(praison_ai.framework)
return praison_ai.main()
if __name__ == "__main__":
print(auto())
-41
View File
@@ -1,41 +0,0 @@
framework: "autogen"
topic: "Artificial Intelligence"
roles:
narrative_designer:
role: "Narrative Designer"
goal: "Craft engaging storylines and narratives for {topic}"
backstory: >
You're a creative visionary skilled in weaving complex narratives and
developing engaging story worlds within {topic}. Your expertise lies in
conceptualizing the overarching story and ensuring it resonates with the audience.
tasks:
story_concept_development:
description: >
Develop a compelling story concept for {topic}, focusing on originality,
thematic depth, and audience engagement. Outline the main narrative arcs,
characters, and settings.
expected_output: >
A comprehensive document outlining the story concept, including key narrative
arcs, character bios, and settings descriptions.
scriptwriter:
role: "Scriptwriter"
goal: "Transform story concepts into detailed scripts for {topic}"
backstory: >
With a flair for dialogue and a deep understanding of pacing and structure,
you excel at bringing narratives to life through scriptwriting. Your work
turns story concepts into blueprints for compelling {topic} experiences.
tasks:
scriptwriting_task:
description: >
Based on the narrative concept, write a detailed script for {topic}.
Include dialogue, stage directions, and scene descriptions that bring
the story to life.
expected_output: >
A detailed script ready for production, including dialogue, stage
directions, and scene descriptions.
dependencies:
- task: scriptwriting_task
depends_on: story_concept_development
-8
View File
@@ -1,8 +0,0 @@
from praisonai import PraisonAI
def main():
praison_ai = PraisonAI(agent_file="agents.yaml")
return praison_ai.main()
if __name__ == "__main__":
print(main())
-41
View File
@@ -1,41 +0,0 @@
framework: "crewai"
topic: "Artificial Intelligence"
roles:
narrative_designer:
role: "Narrative Designer"
goal: "Craft engaging storylines and narratives for {topic}"
backstory: >
You're a creative visionary skilled in weaving complex narratives and
developing engaging story worlds within {topic}. Your expertise lies in
conceptualizing the overarching story and ensuring it resonates with the audience.
tasks:
story_concept_development:
description: >
Develop a compelling story concept for {topic}, focusing on originality,
thematic depth, and audience engagement. Outline the main narrative arcs,
characters, and settings.
expected_output: >
A comprehensive document outlining the story concept, including key narrative
arcs, character bios, and settings descriptions.
scriptwriter:
role: "Scriptwriter"
goal: "Transform story concepts into detailed scripts for {topic}"
backstory: >
With a flair for dialogue and a deep understanding of pacing and structure,
you excel at bringing narratives to life through scriptwriting. Your work
turns story concepts into blueprints for compelling {topic} experiences.
tasks:
scriptwriting_task:
description: >
Based on the narrative concept, write a detailed script for {topic}.
Include dialogue, stage directions, and scene descriptions that bring
the story to life.
expected_output: >
A detailed script ready for production, including dialogue, stage
directions, and scene descriptions.
dependencies:
- task: scriptwriting_task
depends_on: story_concept_development
-21
View File
@@ -1,21 +0,0 @@
# tests/debug.py
import tracemalloc
import logging
import warnings
import sys
import traceback
# Enable Tracemalloc
tracemalloc.start()
# Configure Logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)d - %(message)s')
# Function to Log Warnings with Traceback
def warn_with_traceback(message, category, filename, lineno, file=None, line=None):
log = file if hasattr(file, 'write') else sys.stderr
traceback.print_stack(file=log)
log.write(warnings.formatwarning(message, category, filename, lineno, line))
# Override showwarning
warnings.showwarning = warn_with_traceback
-42
View File
@@ -1,42 +0,0 @@
framework: crewai
topic: create a movie about cat in mars based on https://blog.celtx.com/how-to-write-a-good-story/
roles:
story_developer:
backstory: Experienced in crafting compelling narratives for a diverse audience.
goal: Develop an engaging storyline for a movie about cats in Mars
role: Story Developer
tasks:
storyline_creation:
description: Create a captivating storyline for a movie about cats in Mars
inspired by the blog post at https://blog.celtx.com/how-to-write-a-good-story/
expected_output: Detailed storyline with key plot points, character motivations,
and setting descriptions.
tools:
- ScrapeWebsiteTool
screenwriter:
backstory: Proficient in translating complex narratives into engaging screenplay
format.
goal: Transform the storyline into a script
role: Screenwriter
tasks:
script_creation:
description: Transform the developed storyline into a script for the movie
about cats in Mars.
expected_output: Complete script with dialogues, scenes, and stage directions
ready for production.
tools:
- ''
director:
backstory: Experienced in visual storytelling and bringing scripts to life on
screen.
goal: Oversee the production of the movie
role: Director
tasks:
movie_production:
description: Take the script and lead the team to produce the movie 'Cats
in Mars' based on the provided content and script.
expected_output: Completed movie ready for distribution with compelling visuals
and engaging storytelling.
tools:
- ''
dependencies: []
-42
View File
@@ -1,42 +0,0 @@
framework: crewai
topic: create a movie about cat in mars
roles:
story_developer:
backstory: Experienced in crafting compelling narratives for a diverse audience.
goal: Develop an engaging storyline for a movie about cats in Mars
role: Story Developer
tasks:
storyline_creation:
description: Create a captivating storyline for a movie about cats in Mars.
Use Internet Search Tool to understand the latest story writing ideas.
expected_output: Detailed storyline with key plot points, character motivations,
and setting descriptions.
tools:
- internet_search_tool
screenwriter:
backstory: Proficient in translating complex narratives into engaging screenplay
format.
goal: Transform the storyline into a script
role: Screenwriter
tasks:
script_creation:
description: Transform the developed storyline into a script for the movie
about cats in Mars.
expected_output: Complete script with dialogues, scenes, and stage directions
ready for production.
tools:
- ''
director:
backstory: Experienced in visual storytelling and bringing scripts to life on
screen.
goal: Oversee the production of the movie
role: Director
tasks:
movie_production:
description: Take the script and lead the team to produce the movie 'Cats
in Mars' based on the provided content and script.
expected_output: Completed movie ready for distribution with compelling visuals
and engaging storytelling.
tools:
- ''
dependencies: []
-44
View File
@@ -1,44 +0,0 @@
from typing import Annotated, Literal
import os
from autogen import ConversableAgent
Operator = Literal["+", "-", "*", "/"]
def calculator(a: int, b: int, operator: Annotated[Operator, "operator"]) -> int:
if operator == "+":
return a + b
elif operator == "-":
return a - b
elif operator == "*":
return a * b
elif operator == "/":
return int(a / b)
else:
raise ValueError("Invalid operator")
assistant = ConversableAgent(
name="Assistant",
system_message="You are a helpful AI assistant. "
"You can help with simple calculations. "
"Return 'TERMINATE' when the task is done.",
llm_config={"config_list": [{"model": "gpt-3.5-turbo", "api_key": os.environ["OPENAI_API_KEY"]}]},
)
user_proxy = ConversableAgent(
name="User",
llm_config=False,
is_termination_msg=lambda msg: msg.get("content") is not None and "TERMINATE" in msg["content"],
human_input_mode="NEVER",
)
from autogen import register_function
# Register the calculator function to the agent and user proxy to add a calculator tool.
register_function(
calculator,
caller=assistant, # The assistant agent can suggest calls to the calculator.
executor=user_proxy, # The user proxy agent can execute the calculator calls.
name="calculator", # By default, the function name is used as the tool name.
description="A simple calculator", # A description of the tool.
)
chat_result = user_proxy.initiate_chat(assistant, message="What is (44232 + 13312 / (232 - 32)) * 5?")
-99
View File
@@ -1,99 +0,0 @@
import math
import os
from typing import Optional, Type
# Starndard Langchain example
from langchain.agents import create_spark_sql_agent
from langchain.agents.agent_toolkits import SparkSQLToolkit
from langchain.chat_models import ChatOpenAI
# Import things that are needed generically
from langchain.pydantic_v1 import BaseModel, Field
from langchain.tools import BaseTool
from langchain.tools.file_management.read import ReadFileTool
from langchain.utilities.spark_sql import SparkSQL
import autogen
class CircumferenceToolInput(BaseModel):
radius: float = Field()
class CircumferenceTool(BaseTool):
name = "circumference_calculator"
description = "Use this tool when you need to calculate a circumference using the radius of a circle"
args_schema: Type[BaseModel] = CircumferenceToolInput
def _run(self, radius: float):
return float(radius) * 2.0 * math.pi
def get_file_path_of_example():
current_dir = os.path.dirname(__file__)
file_path = os.path.join(current_dir, "radius.txt")
return file_path
# Define a function to generate llm_config from a LangChain tool
def generate_llm_config(tool):
# Define the function schema based on the tool's args_schema
function_schema = {
"name": tool.name.lower().replace(" ", "_"),
"description": tool.description,
"parameters": {
"type": "object",
"properties": {},
"required": [],
},
}
if tool.args is not None:
function_schema["parameters"]["properties"] = tool.args
return function_schema
# Instantiate the ReadFileTool
read_file_tool = ReadFileTool()
custom_tool = CircumferenceTool()
# Construct the llm_config
llm_config = {
# Generate functions config for the Tool
"functions": [
generate_llm_config(custom_tool),
generate_llm_config(read_file_tool),
],
"config_list": [{"model": "gpt-3.5-turbo", "api_key": os.environ["OPENAI_API_KEY"]}],
"timeout": 120,
}
user_proxy = autogen.UserProxyAgent(
name="user_proxy",
is_termination_msg=lambda x: x.get("content", "") and x.get("content", "").rstrip().endswith("TERMINATE"),
human_input_mode="NEVER",
max_consecutive_auto_reply=10,
code_execution_config={
"work_dir": "coding",
"use_docker": False,
}, # Please set use_docker=True if docker is available to run the generated code. Using docker is safer than running the generated code directly.
)
# Register the tool and start the conversation
user_proxy.register_function(
function_map={
custom_tool.name: custom_tool._run,
read_file_tool.name: read_file_tool._run,
}
)
chatbot = autogen.AssistantAgent(
name="chatbot",
system_message="For coding tasks, only use the functions you have been provided with. Reply TERMINATE when the task is done.",
llm_config=llm_config,
)
user_proxy.initiate_chat(
chatbot,
message=f"Read the file with the path {get_file_path_of_example()}, then calculate the circumference of a circle that has a radius of that files contents.", # 7.81mm in the file
llm_config=llm_config,
)
-71
View File
@@ -1,71 +0,0 @@
import os
from crewai import Agent, Task, Crew
from duckduckgo_search import DDGS
from langchain.tools import tool
@tool("Internet Search Tool")
def internet_search_tool(query: str) -> list:
"""Search Internet for relevant information based on a query."""
ddgs = DDGS()
results = ddgs.text(keywords=query, region='wt-wt', safesearch='moderate', max_results=5)
return results
# Define agents
researcher = Agent(
role='Researcher',
goal='Gather and analyze information on specific topics',
verbose=True,
backstory=(
"As a seasoned researcher, you have a keen eye for detail and a "
"deep understanding of your field. You're adept at sifting through "
"information to find the most relevant and accurate data."
),
tools=[internet_search_tool],
allow_delegation=True
)
writer = Agent(
role='Writer',
goal='Compose informative and engaging articles based on research findings',
verbose=True,
backstory=(
"With a talent for storytelling, you translate complex ideas into "
"clear, compelling narratives. Your articles are well-researched, "
"thought-provoking, and accessible to a broad audience."
),
tools=[internet_search_tool],
allow_delegation=False
)
# Define tasks
research_task = Task(
description=(
"Investigate the latest trends in renewable energy technologies. "
"Identify key advancements, challenges, and potential impacts on "
"global energy policies."
),
expected_output='A detailed report summarizing the findings.',
tools=[internet_search_tool],
agent=researcher,
)
writing_task = Task(
description=(
"Based on the research findings, write an article that highlights "
"the importance of renewable energy innovations. The article should "
"educate the public on how these technologies can contribute to "
"sustainable development."
),
expected_output='An engaging and informative article suitable for publication.',
tools=[internet_search_tool],
agent=writer,
)
# Create and kick off the crew
crew = Crew(
agents=[researcher, writer],
tasks=[research_task, writing_task]
)
result = crew.kickoff(inputs={'topic': 'renewable energy'})
print(result)
-1
View File
@@ -1 +0,0 @@
7.81mm
-63
View File
@@ -1,63 +0,0 @@
# tests/test.py
# from .debug import * # Uncomment this line to import the debug.py file for debugging
import unittest
import subprocess
from praisonai.cli import PraisonAI
from .advanced_example import advanced
from .basic_example import main
from .auto_example import auto
class TestPraisonAIFramework(unittest.TestCase):
def test_main_with_autogen_framework(self):
praison_ai = PraisonAI(agent_file='tests/autogen-agents.yaml')
result = praison_ai.main()
self.assertIn('### Task Output ###', result)
def test_main_with_custom_framework(self):
praison_ai = PraisonAI(agent_file='tests/crewai-agents.yaml')
result = praison_ai.main()
self.assertIn('### Task Output ###', result)
def test_main_with_internet_search_tool(self):
praison_ai = PraisonAI(agent_file='tests/search-tool-agents.yaml')
result = praison_ai.main()
self.assertIn('### Task Output ###', result)
def test_main_with_built_in_tool(self):
praison_ai = PraisonAI(agent_file='tests/inbuilt-tool-agents.yaml')
result = praison_ai.main()
self.assertIn('### Task Output ###', result)
class TestPraisonAICommandLine(unittest.TestCase):
def run_command(self, command):
result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, text=True)
return result.stdout
def test_praisonai_command(self):
command = "praisonai --framework autogen --auto create movie script about cat in mars"
result = self.run_command(command)
self.assertIn('TERMINATE', result)
def test_praisonai_init_command(self):
command = "praisonai --framework autogen --init create movie script about cat in mars"
result = self.run_command(command)
self.assertIn('created successfully', result)
class TestExamples(unittest.TestCase):
def test_basic_example(self):
# Assuming main() has been adjusted to return a value for assertion
result = main()
self.assertIsNotNone(result) # Adjust this assertion based on the expected outcome of main()
def test_advanced_example(self):
# Assuming advanced() returns a value suitable for assertion
result = advanced()
self.assertIsNotNone(result) # Adjust this assertion as needed
def test_auto_example(self):
# Assuming auto() returns a value that can be asserted
result = auto()
self.assertIsNotNone(result) # Adjust this assertion according to what auto() is expected to do
if __name__ == '__main__':
unittest.main()
-25
View File
@@ -1,25 +0,0 @@
# tests/test_agents_playbook.py
import unittest
import subprocess
from praisonai import PraisonAI
class TestPraisonAIFramework(unittest.TestCase):
def test_main_with_autogen_framework(self):
praison_ai = PraisonAI(agent_file='tests/autogen-agents.yaml')
result = praison_ai.main()
self.assertIn('### Task Output ###', result)
def test_main_with_custom_framework(self):
praison_ai = PraisonAI(agent_file='tests/crewai-agents.yaml')
result = praison_ai.main()
self.assertIn('### Task Output ###', result)
def test_main_with_internet_search_tool(self):
praison_ai = PraisonAI(agent_file='tests/search-tool-agents.yaml')
result = praison_ai.main()
self.assertIn('### Task Output ###', result)
def test_main_with_built_in_tool(self):
praison_ai = PraisonAI(agent_file='tests/inbuilt-tool-agents.yaml')
result = praison_ai.main()
self.assertIn('### Task Output ###', result)
View File
Whitespace-only changes.
-9
View File
@@ -1,9 +0,0 @@
from duckduckgo_search import DDGS
from langchain.tools import tool
@tool("Internet Search Tool")
def internet_search_tool(query: str) -> list:
"""Search Internet for relevant information based on a query."""
ddgs = DDGS()
results = ddgs.text(keywords=query, region='wt-wt', safesearch='moderate', max_results=5)
return results
-12
View File
@@ -1,12 +0,0 @@
# 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
View File
Whitespace-only changes.
-11
View File
@@ -1,11 +0,0 @@
from duckduckgo_search import DDGS
from praisonai_tools import BaseTool
class InternetSearchTool(BaseTool):
name: str = "Internet Search Tool"
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