mirror of
https://github.com/MervinPraison/PraisonAI.git
synced 2026-11-08 08:11:07 -10:00
Compare commits
No files matched your search
@@ -11,6 +11,7 @@ on:
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
|
||||
@@ -10,6 +10,7 @@ jobs:
|
||||
test:
|
||||
name: Run tests and collect coverage
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
|
||||
@@ -26,6 +26,7 @@ on:
|
||||
jobs:
|
||||
comprehensive-test:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
strategy:
|
||||
matrix:
|
||||
python-version: ["3.11"]
|
||||
|
||||
@@ -9,6 +9,7 @@ on:
|
||||
jobs:
|
||||
test-core:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
strategy:
|
||||
matrix:
|
||||
python-version: [3.11]
|
||||
|
||||
@@ -13,6 +13,7 @@ on:
|
||||
jobs:
|
||||
test-examples:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
@@ -43,6 +44,9 @@ jobs:
|
||||
echo "OPENAI_API_BASE=${{ secrets.OPENAI_API_BASE || 'https://api.openai.com/v1' }}" >> $GITHUB_ENV
|
||||
echo "OPENAI_MODEL_NAME=${{ secrets.OPENAI_MODEL_NAME || 'gpt-4o-mini' }}" >> $GITHUB_ENV
|
||||
echo "PYTHONPATH=${{ github.workspace }}/src/praisonai-agents:$PYTHONPATH" >> $GITHUB_ENV
|
||||
echo "PRAISONAI_TELEMETRY_DISABLED=true" >> $GITHUB_ENV
|
||||
echo "PRAISONAI_DISABLE_TELEMETRY=true" >> $GITHUB_ENV
|
||||
echo "DO_NOT_TRACK=true" >> $GITHUB_ENV
|
||||
|
||||
- name: Test Key Example Scripts
|
||||
run: |
|
||||
@@ -73,6 +77,7 @@ jobs:
|
||||
|
||||
performance-test:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
@@ -97,6 +102,12 @@ jobs:
|
||||
# Install knowledge dependencies from praisonai-agents
|
||||
uv pip install --system "praisonaiagents[knowledge]"
|
||||
|
||||
- name: Set environment variables
|
||||
run: |
|
||||
echo "PRAISONAI_TELEMETRY_DISABLED=true" >> $GITHUB_ENV
|
||||
echo "PRAISONAI_DISABLE_TELEMETRY=true" >> $GITHUB_ENV
|
||||
echo "DO_NOT_TRACK=true" >> $GITHUB_ENV
|
||||
|
||||
- name: Run Performance Benchmarks
|
||||
run: |
|
||||
echo "🏃 Running performance benchmarks..."
|
||||
@@ -161,4 +172,4 @@ jobs:
|
||||
with:
|
||||
name: performance-report
|
||||
path: performance_report.md
|
||||
retention-days: 30
|
||||
retention-days: 5
|
||||
@@ -24,6 +24,7 @@ on:
|
||||
jobs:
|
||||
framework-tests:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
strategy:
|
||||
matrix:
|
||||
python-version: [3.11]
|
||||
|
||||
@@ -26,6 +26,7 @@ jobs:
|
||||
real-tests:
|
||||
runs-on: ubuntu-latest
|
||||
if: ${{ github.event.inputs.confirm_costs == 'true' && github.event.inputs.framework != 'none' }}
|
||||
timeout-minutes: 15
|
||||
|
||||
strategy:
|
||||
matrix:
|
||||
|
||||
@@ -5,6 +5,7 @@ on: [push, pull_request]
|
||||
jobs:
|
||||
quick-test:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
|
||||
@@ -120,6 +120,10 @@ agent.start('Write a movie script about a robot in Mars');
|
||||
|
||||

|
||||
|
||||
## Star History
|
||||
|
||||
[](https://docs.praison.ai)
|
||||
|
||||
## AI Agents Flow
|
||||
|
||||
```mermaid
|
||||
@@ -557,10 +561,6 @@ uv pip install -r pyproject.toml --extra "crewai,autogen"
|
||||
- 🖼️ Vision Language Model (VLM) Support
|
||||
- 🎙️ Real-time Voice Interaction
|
||||
|
||||
## Star History
|
||||
|
||||
[](https://docs.praison.ai)
|
||||
|
||||
## Video Tutorials
|
||||
|
||||
| Topic | Video |
|
||||
|
||||
+1
-1
@@ -16,7 +16,7 @@ RUN mkdir -p /root/.praison
|
||||
# Install Python packages (using latest versions)
|
||||
RUN pip install --no-cache-dir \
|
||||
flask \
|
||||
"praisonai>=2.2.64" \
|
||||
"praisonai>=2.2.71" \
|
||||
"praisonai[api]" \
|
||||
gunicorn \
|
||||
markdown
|
||||
|
||||
@@ -16,7 +16,7 @@ RUN mkdir -p /root/.praison
|
||||
# Install Python packages (using latest versions)
|
||||
RUN pip install --no-cache-dir \
|
||||
praisonai_tools \
|
||||
"praisonai>=2.2.64" \
|
||||
"praisonai>=2.2.71" \
|
||||
"praisonai[chat]" \
|
||||
"embedchain[github,youtube]"
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ RUN mkdir -p /root/.praison
|
||||
# Install Python packages (using latest versions)
|
||||
RUN pip install --no-cache-dir \
|
||||
praisonai_tools \
|
||||
"praisonai>=2.2.64" \
|
||||
"praisonai>=2.2.71" \
|
||||
"praisonai[ui]" \
|
||||
"praisonai[chat]" \
|
||||
"praisonai[realtime]" \
|
||||
|
||||
@@ -16,7 +16,7 @@ RUN mkdir -p /root/.praison
|
||||
# Install Python packages (using latest versions)
|
||||
RUN pip install --no-cache-dir \
|
||||
praisonai_tools \
|
||||
"praisonai>=2.2.64" \
|
||||
"praisonai>=2.2.71" \
|
||||
"praisonai[ui]" \
|
||||
"praisonai[crewai]"
|
||||
|
||||
|
||||
+2
-2
@@ -121,7 +121,7 @@ healthcheck:
|
||||
## 📦 Package Versions
|
||||
|
||||
All Docker images use consistent, up-to-date versions:
|
||||
- PraisonAI: `>=2.2.64`
|
||||
- PraisonAI: `>=2.2.71`
|
||||
- PraisonAI Agents: `>=0.0.92`
|
||||
- Python: `3.11-slim`
|
||||
|
||||
@@ -218,7 +218,7 @@ docker-compose up -d
|
||||
### Version Pinning
|
||||
To use specific versions, update the Dockerfile:
|
||||
```dockerfile
|
||||
RUN pip install "praisonai==2.2.64" "praisonaiagents==0.0.92"
|
||||
RUN pip install "praisonai==2.2.71" "praisonaiagents==0.0.92"
|
||||
```
|
||||
|
||||
## 🌐 Production Deployment
|
||||
|
||||
+343
-343
@@ -1,355 +1,355 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "_T4g3t5sLoag"
|
||||
},
|
||||
"source": [
|
||||
"# ZeroScript: AI-Powered Browser Test Automation using PraisonAI Agent & OpenAI"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "O4PKfpalLsmn"
|
||||
},
|
||||
"source": [
|
||||
"# Description"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "CEG1pfumLysm"
|
||||
},
|
||||
"source": [
|
||||
"AI-powered browser testing using PraisonAI Agent and OpenAI. Executes YAML-defined test cases, captures screenshots, logs interactions, and generates JSON reports. Ideal for intelligent, automated UI testing.\n",
|
||||
"\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "lbgxOG4gL1Wf"
|
||||
},
|
||||
"source": [
|
||||
"[](https://colab.research.google.com/github/DhivyaBharathy-web/PraisonAI/blob/main/examples/cookbooks/ZeroScript_AI_TestExecutor.ipynb)\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "WCJqMUzXIndh"
|
||||
},
|
||||
"source": [
|
||||
"# Dependencies"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 34,
|
||||
"metadata": {
|
||||
"id": "9AQhJ59cJPmR"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"!pip install --quiet praisonaiagents browser-use python-dotenv pyyaml openai\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "QD-dF-6_It1z"
|
||||
},
|
||||
"source": [
|
||||
"# Environment Setup"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 35,
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"base_uri": "https://localhost:8080/"
|
||||
},
|
||||
"id": "QkRQDli4JhCV",
|
||||
"outputId": "4b8957ed-a37a-4b11-8585-3537a0437d40"
|
||||
},
|
||||
"outputs": [
|
||||
"cells": [
|
||||
{
|
||||
"data": {
|
||||
"text/plain": [
|
||||
"True"
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "_T4g3t5sLoag"
|
||||
},
|
||||
"source": [
|
||||
"# ZeroScript: AI-Powered Browser Test Automation using PraisonAI Agent & OpenAI"
|
||||
]
|
||||
},
|
||||
"execution_count": 35,
|
||||
"metadata": {},
|
||||
"output_type": "execute_result"
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"import os\n",
|
||||
"from dotenv import load_dotenv\n",
|
||||
"\n",
|
||||
"os.environ[\"OPENAI_API_KEY\"] = \"Enter your key\" # replace with actual key\n",
|
||||
"load_dotenv()\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "ELuogWnrIw3o"
|
||||
},
|
||||
"source": [
|
||||
"# Create my_secrets.py"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 36,
|
||||
"metadata": {
|
||||
"id": "sG6tO_v0Jm5N"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"with open(\"my_secrets.py\", \"w\") as f:\n",
|
||||
" f.write('''sensitive_data = {\n",
|
||||
" \"username\": \"standard_user\",\n",
|
||||
" \"password\": \"secret_sauce\"\n",
|
||||
"}''')\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "rDB_viedIzRR"
|
||||
},
|
||||
"source": [
|
||||
"# Create views.py"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 37,
|
||||
"metadata": {
|
||||
"id": "CtwcybdbJoV8"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"with open(\"views.py\", \"w\") as f:\n",
|
||||
" f.write('''\n",
|
||||
"from pydantic import BaseModel\n",
|
||||
"\n",
|
||||
"class TestResult(BaseModel):\n",
|
||||
" status: str\n",
|
||||
" message: str = \"\"\n",
|
||||
"''')\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "YTRmBpTiI1kd"
|
||||
},
|
||||
"source": [
|
||||
"# Create agent.py"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 38,
|
||||
"metadata": {
|
||||
"id": "zdJJGt6TJpvr"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"with open(\"agent.py\", \"w\") as f:\n",
|
||||
" f.write('''\n",
|
||||
"import os\n",
|
||||
"from praisonaiagents import Agent\n",
|
||||
"from browser_use import Browser, BrowserConfig, Controller\n",
|
||||
"from browser_use.browser.context import BrowserContext, BrowserContextConfig\n",
|
||||
"from openai import OpenAI\n",
|
||||
"from views import TestResult\n",
|
||||
"from my_secrets import sensitive_data\n",
|
||||
"\n",
|
||||
"# Browser setup\n",
|
||||
"browser = Browser(config=BrowserConfig(headless=True))\n",
|
||||
"context_cfg = BrowserContextConfig(save_recording_path=\"data/recordings\")\n",
|
||||
"controller = Controller(output_model=TestResult)\n",
|
||||
"\n",
|
||||
"async def browser_use(task: str):\n",
|
||||
" context = BrowserContext(browser=browser, config=context_cfg)\n",
|
||||
" agent = Agent(\n",
|
||||
" task=task,\n",
|
||||
" llm=OpenAI(api_key=os.getenv(\"OPENAI_API_KEY\"), model=\"gpt-4\"),\n",
|
||||
" browser_context=context,\n",
|
||||
" sensitive_data=sensitive_data,\n",
|
||||
" controller=controller,\n",
|
||||
" save_conversation_path=\"data/conversations/convo\",\n",
|
||||
" extend_system_message=(\n",
|
||||
" \"You are a professional software tester. Execute browser test steps precisely.\"\n",
|
||||
" )\n",
|
||||
" )\n",
|
||||
" response = await agent.run()\n",
|
||||
" await context.close()\n",
|
||||
" return response\n",
|
||||
"''')\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "-LZtQIE3I4-_"
|
||||
},
|
||||
"source": [
|
||||
"# Create Sample Test YAML"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 39,
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"base_uri": "https://localhost:8080/"
|
||||
},
|
||||
"id": "l1OdXYI-JreK",
|
||||
"outputId": "62323fcd-c74f-498f-defc-2c170fa8983e"
|
||||
},
|
||||
"outputs": [
|
||||
{
|
||||
"data": {
|
||||
"text/plain": [
|
||||
"350"
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "O4PKfpalLsmn"
|
||||
},
|
||||
"source": [
|
||||
"# Description"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "CEG1pfumLysm"
|
||||
},
|
||||
"source": [
|
||||
"AI-powered browser testing using PraisonAI Agent and OpenAI. Executes YAML-defined test cases, captures screenshots, logs interactions, and generates JSON reports. Ideal for intelligent, automated UI testing.\n",
|
||||
"\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "lbgxOG4gL1Wf"
|
||||
},
|
||||
"source": [
|
||||
"[](https://colab.research.google.com/github/DhivyaBharathy-web/PraisonAI/blob/main/examples/cookbooks/ZeroScript_AI_TestExecutor.ipynb)\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "WCJqMUzXIndh"
|
||||
},
|
||||
"source": [
|
||||
"# Dependencies"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 34,
|
||||
"metadata": {
|
||||
"id": "9AQhJ59cJPmR"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"!pip install --quiet praisonaiagents browser-use python-dotenv pyyaml openai\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "QD-dF-6_It1z"
|
||||
},
|
||||
"source": [
|
||||
"# Environment Setup"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 35,
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"base_uri": "https://localhost:8080/"
|
||||
},
|
||||
"id": "QkRQDli4JhCV",
|
||||
"outputId": "4b8957ed-a37a-4b11-8585-3537a0437d40"
|
||||
},
|
||||
"outputs": [
|
||||
{
|
||||
"data": {
|
||||
"text/plain": [
|
||||
"True"
|
||||
]
|
||||
},
|
||||
"execution_count": 35,
|
||||
"metadata": {},
|
||||
"output_type": "execute_result"
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"import os\n",
|
||||
"from dotenv import load_dotenv\n",
|
||||
"\n",
|
||||
"os.environ[\"OPENAI_API_KEY\"] = \"Enter your key\" # replace with actual key\n",
|
||||
"load_dotenv()\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "ELuogWnrIw3o"
|
||||
},
|
||||
"source": [
|
||||
"# Create my_secrets.py"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 36,
|
||||
"metadata": {
|
||||
"id": "sG6tO_v0Jm5N"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"with open(\"my_secrets.py\", \"w\") as f:\n",
|
||||
" f.write('''sensitive_data = {\n",
|
||||
" \"username\": \"standard_user\",\n",
|
||||
" \"password\": \"secret_sauce\"\n",
|
||||
"}''')\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "rDB_viedIzRR"
|
||||
},
|
||||
"source": [
|
||||
"# Create views.py"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 37,
|
||||
"metadata": {
|
||||
"id": "CtwcybdbJoV8"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"with open(\"views.py\", \"w\") as f:\n",
|
||||
" f.write('''\n",
|
||||
"from pydantic import BaseModel\n",
|
||||
"\n",
|
||||
"class TestResult(BaseModel):\n",
|
||||
" status: str\n",
|
||||
" message: str = \"\"\n",
|
||||
"''')\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "YTRmBpTiI1kd"
|
||||
},
|
||||
"source": [
|
||||
"# Create agent.py"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 38,
|
||||
"metadata": {
|
||||
"id": "zdJJGt6TJpvr"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"with open(\"agent.py\", \"w\") as f:\n",
|
||||
" f.write('''\n",
|
||||
"import os\n",
|
||||
"from praisonaiagents import Agent\n",
|
||||
"from browser_use import Browser, BrowserConfig, Controller\n",
|
||||
"from browser_use.browser.context import BrowserContext, BrowserContextConfig\n",
|
||||
"from openai import OpenAI\n",
|
||||
"from views import TestResult\n",
|
||||
"from my_secrets import sensitive_data\n",
|
||||
"\n",
|
||||
"# Browser setup\n",
|
||||
"browser = Browser(config=BrowserConfig(headless=True))\n",
|
||||
"context_cfg = BrowserContextConfig(save_recording_path=\"data/recordings\")\n",
|
||||
"controller = Controller(output_model=TestResult)\n",
|
||||
"\n",
|
||||
"async def browser_use(task: str):\n",
|
||||
" context = BrowserContext(browser=browser, config=context_cfg)\n",
|
||||
" agent = Agent(\n",
|
||||
" task=task,\n",
|
||||
" llm=OpenAI(api_key=os.getenv(\"OPENAI_API_KEY\"), model=\"gpt-4\"),\n",
|
||||
" browser_context=context,\n",
|
||||
" sensitive_data=sensitive_data,\n",
|
||||
" controller=controller,\n",
|
||||
" save_conversation_path=\"data/conversations/convo\",\n",
|
||||
" extend_system_message=(\n",
|
||||
" \"You are a professional software tester. Execute browser test steps precisely.\"\n",
|
||||
" )\n",
|
||||
" )\n",
|
||||
" response = await agent.run()\n",
|
||||
" await context.close()\n",
|
||||
" return response\n",
|
||||
"''')\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "-LZtQIE3I4-_"
|
||||
},
|
||||
"source": [
|
||||
"# Create Sample Test YAML"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 39,
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"base_uri": "https://localhost:8080/"
|
||||
},
|
||||
"id": "l1OdXYI-JreK",
|
||||
"outputId": "62323fcd-c74f-498f-defc-2c170fa8983e"
|
||||
},
|
||||
"outputs": [
|
||||
{
|
||||
"data": {
|
||||
"text/plain": [
|
||||
"350"
|
||||
]
|
||||
},
|
||||
"execution_count": 39,
|
||||
"metadata": {},
|
||||
"output_type": "execute_result"
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"from pathlib import Path\n",
|
||||
"tests_dir = Path(\"tests\")\n",
|
||||
"tests_dir.mkdir(exist_ok=True)\n",
|
||||
"yaml_content = \"\"\"\n",
|
||||
"hooks:\n",
|
||||
" beforeEach: |\n",
|
||||
" Navigate to https://www.saucedemo.com\n",
|
||||
" afterEach: |\n",
|
||||
" Take screenshot\n",
|
||||
"\n",
|
||||
"tests:\n",
|
||||
" - id: \"login_test_001\"\n",
|
||||
" name: \"Valid Login Test\"\n",
|
||||
" instructions: |\n",
|
||||
" 1. Enter standard_user in username field\n",
|
||||
" 2. Enter secret_sauce in password field\n",
|
||||
" 3. Click login button\n",
|
||||
" 4. Verify page contains text \"Products\"\n",
|
||||
"\"\"\"\n",
|
||||
"(Path(\"tests/login_test.yml\")).write_text(yaml_content)\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "sUjy-7OdI7p_"
|
||||
},
|
||||
"source": [
|
||||
"# Run Tests"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 40,
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"base_uri": "https://localhost:8080/"
|
||||
},
|
||||
"id": "Agkiwh7xJtY3",
|
||||
"outputId": "759aa77c-fd65-49b8-b239-550588059478"
|
||||
},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stderr",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Exception ignored in: <function BrowserSession.__del__ at 0x7e2f540fb100>\n",
|
||||
"Traceback (most recent call last):\n",
|
||||
" File \"/usr/local/lib/python3.11/dist-packages/browser_use/browser/session.py\", line 497, in __del__\n",
|
||||
" status = f'\ud83e\ude93 killing pid={self.browser_pid}...' if (self.browser_pid and owns_browser) else '\u2620\ufe0f'\n",
|
||||
" ^^^^^^^^^^^^^^^^\n",
|
||||
" File \"/usr/local/lib/python3.11/dist-packages/pydantic/main.py\", line 991, in __getattr__\n",
|
||||
" raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}')\n",
|
||||
"AttributeError: 'BrowserSession' object has no attribute 'browser_pid'\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"\u2705 Report saved to data/reports/report_20250630_092319.json\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"import asyncio, yaml, json, base64, shutil\n",
|
||||
"from agent import browser_use, browser\n",
|
||||
"from pathlib import Path\n",
|
||||
"from datetime import datetime\n",
|
||||
"\n",
|
||||
"# Clean or create data dirs\n",
|
||||
"for sub in [\"recordings\", \"conversations\", \"screenshots\", \"reports\"]:\n",
|
||||
" d = Path(\"data\") / sub\n",
|
||||
" if d.exists(): shutil.rmtree(d)\n",
|
||||
" d.mkdir(parents=True, exist_ok=True)\n",
|
||||
"\n",
|
||||
"async def execute_test_file(path):\n",
|
||||
" cfg = yaml.safe_load(Path(path).read_text())\n",
|
||||
" hooks, results = cfg.get(\"hooks\", {}), []\n",
|
||||
" for t in cfg[\"tests\"]:\n",
|
||||
" task = f\"{hooks.get('beforeEach','')}\\n{t['instructions']}\\n{hooks.get('afterEach','')}\"\n",
|
||||
" res = {\"id\": t[\"id\"], \"name\": t[\"name\"]}\n",
|
||||
" try:\n",
|
||||
" r = await browser_use(task)\n",
|
||||
" imgs = r.screenshots()\n",
|
||||
" if imgs:\n",
|
||||
" out = Path(\"data/screenshots\") / f\"{t['id']}.png\"\n",
|
||||
" out.write_bytes(base64.b64decode(imgs[-1]))\n",
|
||||
" result_obj = r.final_result() if hasattr(r, \"final_result\") else str(r)\n",
|
||||
" res[\"result\"] = result_obj.model_dump() if hasattr(result_obj, \"model_dump\") else str(result_obj)\n",
|
||||
" except Exception as e:\n",
|
||||
" res[\"error\"] = str(e)\n",
|
||||
" results.append(res)\n",
|
||||
" return results\n",
|
||||
"\n",
|
||||
"async def main():\n",
|
||||
" all_results = []\n",
|
||||
" for file in Path(\"tests\").glob(\"*.yml\"):\n",
|
||||
" all_results.extend(await execute_test_file(str(file)))\n",
|
||||
" report = Path(\"data/reports\") / f\"report_{datetime.now():%Y%m%d_%H%M%S}.json\"\n",
|
||||
" report.write_text(json.dumps(all_results, indent=2))\n",
|
||||
" await browser.close()\n",
|
||||
" print(f\"\u2705 Report saved to {report}\")\n",
|
||||
"\n",
|
||||
"await main()\n"
|
||||
]
|
||||
},
|
||||
"execution_count": 39,
|
||||
"metadata": {},
|
||||
"output_type": "execute_result"
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"from pathlib import Path\n",
|
||||
"tests_dir = Path(\"tests\")\n",
|
||||
"tests_dir.mkdir(exist_ok=True)\n",
|
||||
"yaml_content = \"\"\"\n",
|
||||
"hooks:\n",
|
||||
" beforeEach: |\n",
|
||||
" Navigate to https://www.saucedemo.com\n",
|
||||
" afterEach: |\n",
|
||||
" Take screenshot\n",
|
||||
"\n",
|
||||
"tests:\n",
|
||||
" - id: \"login_test_001\"\n",
|
||||
" name: \"Valid Login Test\"\n",
|
||||
" instructions: |\n",
|
||||
" 1. Enter standard_user in username field\n",
|
||||
" 2. Enter secret_sauce in password field\n",
|
||||
" 3. Click login button\n",
|
||||
" 4. Verify page contains text \"Products\"\n",
|
||||
"\"\"\"\n",
|
||||
"(Path(\"tests/login_test.yml\")).write_text(yaml_content)\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "sUjy-7OdI7p_"
|
||||
},
|
||||
"source": [
|
||||
"# Run Tests"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 40,
|
||||
"metadata": {
|
||||
],
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"base_uri": "https://localhost:8080/"
|
||||
"provenance": []
|
||||
},
|
||||
"id": "Agkiwh7xJtY3",
|
||||
"outputId": "759aa77c-fd65-49b8-b239-550588059478"
|
||||
},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stderr",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Exception ignored in: <function BrowserSession.__del__ at 0x7e2f540fb100>\n",
|
||||
"Traceback (most recent call last):\n",
|
||||
" File \"/usr/local/lib/python3.11/dist-packages/browser_use/browser/session.py\", line 497, in __del__\n",
|
||||
" status = f'🪓 killing pid={self.browser_pid}...' if (self.browser_pid and owns_browser) else '☠️'\n",
|
||||
" ^^^^^^^^^^^^^^^^\n",
|
||||
" File \"/usr/local/lib/python3.11/dist-packages/pydantic/main.py\", line 991, in __getattr__\n",
|
||||
" raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}')\n",
|
||||
"AttributeError: 'BrowserSession' object has no attribute 'browser_pid'\n"
|
||||
]
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3",
|
||||
"name": "python3"
|
||||
},
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"✅ Report saved to data/reports/report_20250630_092319.json\n"
|
||||
]
|
||||
"language_info": {
|
||||
"name": "python"
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"import asyncio, yaml, json, base64, shutil\n",
|
||||
"from agent import browser_use, browser\n",
|
||||
"from pathlib import Path\n",
|
||||
"from datetime import datetime\n",
|
||||
"\n",
|
||||
"# Clean or create data dirs\n",
|
||||
"for sub in [\"recordings\", \"conversations\", \"screenshots\", \"reports\"]:\n",
|
||||
" d = Path(\"data\") / sub\n",
|
||||
" if d.exists(): shutil.rmtree(d)\n",
|
||||
" d.mkdir(parents=True, exist_ok=True)\n",
|
||||
"\n",
|
||||
"async def execute_test_file(path):\n",
|
||||
" cfg = yaml.safe_load(Path(path).read_text())\n",
|
||||
" hooks, results = cfg.get(\"hooks\", {}), []\n",
|
||||
" for t in cfg[\"tests\"]:\n",
|
||||
" task = f\"{hooks.get('beforeEach','')}\\n{t['instructions']}\\n{hooks.get('afterEach','')}\"\n",
|
||||
" res = {\"id\": t[\"id\"], \"name\": t[\"name\"]}\n",
|
||||
" try:\n",
|
||||
" r = await browser_use(task)\n",
|
||||
" imgs = r.screenshots()\n",
|
||||
" if imgs:\n",
|
||||
" out = Path(\"data/screenshots\") / f\"{t['id']}.png\"\n",
|
||||
" out.write_bytes(base64.b64decode(imgs[-1]))\n",
|
||||
" result_obj = r.final_result() if hasattr(r, \"final_result\") else str(r)\n",
|
||||
" res[\"result\"] = result_obj.dict() if hasattr(result_obj, \"dict\") else str(result_obj)\n",
|
||||
" except Exception as e:\n",
|
||||
" res[\"error\"] = str(e)\n",
|
||||
" results.append(res)\n",
|
||||
" return results\n",
|
||||
"\n",
|
||||
"async def main():\n",
|
||||
" all_results = []\n",
|
||||
" for file in Path(\"tests\").glob(\"*.yml\"):\n",
|
||||
" all_results.extend(await execute_test_file(str(file)))\n",
|
||||
" report = Path(\"data/reports\") / f\"report_{datetime.now():%Y%m%d_%H%M%S}.json\"\n",
|
||||
" report.write_text(json.dumps(all_results, indent=2))\n",
|
||||
" await browser.close()\n",
|
||||
" print(f\"✅ Report saved to {report}\")\n",
|
||||
"\n",
|
||||
"await main()\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"provenance": []
|
||||
},
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"name": "python"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 0
|
||||
}
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 0
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
"""
|
||||
AutoAgents Hierarchical Generation Example
|
||||
|
||||
This example demonstrates hierarchical agent patterns using PraisonAI
|
||||
for structured task delegation and coordinated workflows.
|
||||
"""
|
||||
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.tools import internet_search
|
||||
|
||||
print("=== AutoAgents Hierarchical Generation Example ===\n")
|
||||
|
||||
# Create manager agent for hierarchical coordination
|
||||
manager_agent = Agent(
|
||||
name="Project Manager",
|
||||
role="Project Coordinator",
|
||||
goal="Coordinate hierarchical task execution and manage team workflow",
|
||||
backstory="Experienced manager who excels at breaking down complex projects and coordinating teams",
|
||||
tools=[internet_search],
|
||||
allow_delegation=True,
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Create specialist agent for execution
|
||||
research_agent = Agent(
|
||||
name="Research Specialist",
|
||||
role="Market Research Analyst",
|
||||
goal="Conduct thorough market research and analysis",
|
||||
backstory="Expert researcher skilled in market analysis and competitive intelligence",
|
||||
tools=[internet_search],
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Hierarchical task structure
|
||||
planning_task = Task(
|
||||
description="""Plan a comprehensive market research project for electric vehicles:
|
||||
1. Define research scope and objectives
|
||||
2. Identify key research areas and methodologies
|
||||
3. Create task breakdown structure
|
||||
4. Set deliverable requirements for execution team
|
||||
|
||||
Prepare clear instructions for the research specialist.""",
|
||||
expected_output="Detailed project plan with clear research instructions",
|
||||
agent=manager_agent
|
||||
)
|
||||
|
||||
execution_task = Task(
|
||||
description="""Execute the market research plan:
|
||||
1. Follow the research plan from the project manager
|
||||
2. Conduct comprehensive market analysis
|
||||
3. Gather competitive intelligence and market data
|
||||
4. Prepare detailed findings report
|
||||
|
||||
Use the planning guidance to ensure complete coverage.""",
|
||||
expected_output="Comprehensive market research report with findings",
|
||||
agent=research_agent,
|
||||
context=[planning_task]
|
||||
)
|
||||
|
||||
# Run hierarchical workflow
|
||||
agents_system = PraisonAIAgents(
|
||||
agents=[manager_agent, research_agent],
|
||||
tasks=[planning_task, execution_task],
|
||||
process="sequential",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
print("Starting hierarchical agent generation...")
|
||||
result = agents_system.start()
|
||||
|
||||
print(f"\nHierarchical Result: {result[:200]}...")
|
||||
print("\n✅ AutoAgents hierarchical generation complete!")
|
||||
print("Demonstrated coordinated hierarchical workflow between manager and specialist agents.")
|
||||
@@ -440,7 +440,7 @@ async def generate_research(
|
||||
"message": "Report generation queued",
|
||||
"created_at": datetime.now().isoformat(),
|
||||
"updated_at": datetime.now().isoformat(),
|
||||
"config": request.dict()
|
||||
"config": request.model_dump()
|
||||
}
|
||||
|
||||
# Create config object
|
||||
|
||||
@@ -31,7 +31,7 @@ def save_reasoning_chain(chain: ChainOfThought) -> str:
|
||||
"""Save a chain of thought reasoning to analyze patterns."""
|
||||
filename = f"reasoning_{chain.problem[:20].replace(' ', '_')}.json"
|
||||
with open(filename, 'w') as f:
|
||||
json.dump(chain.dict(), f, indent=2)
|
||||
json.dump(chain.model_dump(), f, indent=2)
|
||||
return f"Reasoning chain saved to {filename}"
|
||||
|
||||
# Example 1: Chain of Thought Agent
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
"""
|
||||
Self-Reflection Optimization Patterns Example
|
||||
|
||||
This example demonstrates self-reflection capabilities using PraisonAI's
|
||||
built-in reflection features for iterative improvement and quality optimization.
|
||||
"""
|
||||
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.tools import internet_search
|
||||
|
||||
print("=== Self-Reflection Optimization Patterns Example ===\n")
|
||||
|
||||
# Create self-reflecting agent with built-in reflection capabilities
|
||||
reflection_agent = Agent(
|
||||
name="Self-Reflecting Agent",
|
||||
role="Self-Improving Researcher",
|
||||
goal="Demonstrate self-reflection and iterative improvement patterns",
|
||||
backstory="Expert researcher with strong self-reflection and continuous improvement capabilities",
|
||||
tools=[internet_search],
|
||||
self_reflect=True,
|
||||
min_reflect=2,
|
||||
max_reflect=4,
|
||||
reflect_llm="gpt-4o-mini",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Create task that benefits from self-reflection
|
||||
reflection_task = Task(
|
||||
description="""Research and analyze the future of artificial intelligence:
|
||||
1. Investigate current AI trends and breakthrough technologies
|
||||
2. Analyze potential impacts on society and industry
|
||||
3. Provide well-reasoned predictions for the next 5 years
|
||||
4. Ensure analysis is comprehensive, accurate, and well-structured
|
||||
|
||||
Use self-reflection to improve the quality and completeness of your analysis.""",
|
||||
expected_output="Comprehensive AI future analysis with high quality through self-reflection",
|
||||
agent=reflection_agent
|
||||
)
|
||||
|
||||
# Run with self-reflection optimization
|
||||
print("Starting self-reflection optimization demonstration...")
|
||||
result = reflection_agent.execute_task(reflection_task)
|
||||
|
||||
print(f"\nSelf-Reflection Result: {result[:200]}...")
|
||||
print("\n✅ Self-reflection optimization complete!")
|
||||
print("Agent demonstrated iterative improvement through built-in self-reflection capabilities.")
|
||||
@@ -130,9 +130,11 @@ def example_mcp_tracking():
|
||||
)
|
||||
plan = agent.chat("Plan: Search for Python documentation")
|
||||
|
||||
# Track tool usage
|
||||
# Track tool usage (this will now have actual timing)
|
||||
with tracker.track("tool_usage", request_id):
|
||||
# Simulate tool execution
|
||||
# Simulate tool execution with realistic timing
|
||||
import time
|
||||
time.sleep(0.1) # Simulate some work
|
||||
tool_result = "Found 5 relevant documentation pages"
|
||||
|
||||
# Track LLM generation
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
"""
|
||||
Advanced Callback Systems Example
|
||||
|
||||
This example demonstrates callback systems using PraisonAI's built-in
|
||||
callback functionality for monitoring agent interactions and tool usage.
|
||||
"""
|
||||
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.display_callback import register_display_callback
|
||||
from praisonaiagents.tools import internet_search
|
||||
|
||||
print("=== Advanced Callback Systems Example ===\n")
|
||||
|
||||
# Simple callback function to monitor interactions
|
||||
def interaction_callback(data):
|
||||
"""Monitor agent interactions"""
|
||||
print(f"📋 Interaction: {data.get('agent_name', 'Unknown')} - {data.get('type', 'unknown')}")
|
||||
|
||||
# Simple callback function to monitor tool usage
|
||||
def tool_callback(data):
|
||||
"""Monitor tool usage"""
|
||||
print(f"🔧 Tool Used: {data.get('agent_name', 'Unknown')} used {data.get('tool_name', 'unknown')}")
|
||||
|
||||
# Simple callback function to monitor generation
|
||||
def generation_callback(data):
|
||||
"""Monitor content generation"""
|
||||
print(f"✍️ Generation: {data.get('agent_name', 'Unknown')} generating content")
|
||||
|
||||
# Register callbacks with PraisonAI's callback system
|
||||
print("Registering callbacks...")
|
||||
register_display_callback('interaction', interaction_callback)
|
||||
register_display_callback('tool_call', tool_callback)
|
||||
register_display_callback('generating', generation_callback)
|
||||
print("✅ Callbacks registered\n")
|
||||
|
||||
# Create a research agent with callback monitoring
|
||||
research_agent = Agent(
|
||||
name="Research Agent",
|
||||
role="Information Researcher",
|
||||
goal="Research topics and demonstrate callback monitoring",
|
||||
backstory="Expert researcher that demonstrates callback functionality",
|
||||
tools=[internet_search],
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Create a simple task
|
||||
research_task = Task(
|
||||
description="Research the latest developments in renewable energy technology",
|
||||
expected_output="Brief summary of renewable energy developments",
|
||||
agent=research_agent
|
||||
)
|
||||
|
||||
# Execute with callback monitoring
|
||||
print("Starting research with callback monitoring...")
|
||||
result = research_agent.execute_task(research_task)
|
||||
|
||||
print(f"\nResearch Result: {result[:200]}...")
|
||||
print("\n✅ Callback monitoring demonstration complete!")
|
||||
print("Callbacks successfully tracked agent interactions, tool usage, and content generation.")
|
||||
@@ -0,0 +1,65 @@
|
||||
"""
|
||||
Production Guardrails Patterns Example
|
||||
|
||||
This example demonstrates production guardrail patterns using PraisonAI's
|
||||
built-in validation and safety mechanisms for secure agent operations.
|
||||
"""
|
||||
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.tools import internet_search
|
||||
|
||||
print("=== Production Guardrails Patterns Example ===\n")
|
||||
|
||||
# Simple guardrail function for content validation
|
||||
def content_guardrail(response, context):
|
||||
"""Simple content validation guardrail"""
|
||||
if not response or len(response.strip()) < 50:
|
||||
return {
|
||||
"valid": False,
|
||||
"reason": "Response too short for production use",
|
||||
"action": "regenerate"
|
||||
}
|
||||
|
||||
# Check for sensitive patterns (simplified)
|
||||
sensitive_keywords = ["password", "secret", "private_key", "api_key"]
|
||||
if any(keyword in response.lower() for keyword in sensitive_keywords):
|
||||
return {
|
||||
"valid": False,
|
||||
"reason": "Potential sensitive information detected",
|
||||
"action": "review_and_redact"
|
||||
}
|
||||
|
||||
return {"valid": True}
|
||||
|
||||
# Create production-ready agent with guardrails
|
||||
production_agent = Agent(
|
||||
name="Production Agent",
|
||||
role="Production Content Generator",
|
||||
goal="Generate safe, compliant content for production use",
|
||||
backstory="Production-ready agent with built-in safety and compliance checks",
|
||||
tools=[internet_search],
|
||||
guardrail=content_guardrail,
|
||||
max_retries=3,
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Create secure task with validation
|
||||
secure_task = Task(
|
||||
description="""Create a professional report about renewable energy trends:
|
||||
1. Research current renewable energy market developments
|
||||
2. Include factual data and reliable sources
|
||||
3. Ensure content is production-ready and compliant
|
||||
4. Avoid any sensitive or inappropriate information
|
||||
|
||||
Focus on creating safe, accurate, professional content.""",
|
||||
expected_output="Professional renewable energy report meeting production standards",
|
||||
agent=production_agent
|
||||
)
|
||||
|
||||
# Run with guardrail validation
|
||||
print("Starting production guardrails demonstration...")
|
||||
result = production_agent.execute_task(secure_task)
|
||||
|
||||
print(f"\nProduction Result: {result[:200]}...")
|
||||
print("\n✅ Production guardrails validation complete!")
|
||||
print("Agent demonstrated safe content generation with built-in guardrail validation.")
|
||||
@@ -0,0 +1,75 @@
|
||||
"""
|
||||
Advanced Graph Memory Integration Example
|
||||
|
||||
This example demonstrates graph memory capabilities with PraisonAI agents
|
||||
for knowledge graph construction and relationship-aware memory retrieval.
|
||||
"""
|
||||
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.tools import internet_search
|
||||
|
||||
print("=== Advanced Graph Memory Integration Example ===\n")
|
||||
|
||||
# Configure simple graph memory
|
||||
memory_config = {
|
||||
"provider": "mem0",
|
||||
"config": {
|
||||
"vector_store": {
|
||||
"provider": "chroma",
|
||||
"config": {
|
||||
"path": ".praison/graph_memory"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Create knowledge builder agent with graph memory
|
||||
knowledge_agent = Agent(
|
||||
name="Knowledge Agent",
|
||||
role="Knowledge Graph Builder",
|
||||
goal="Build and retrieve from knowledge graphs",
|
||||
backstory="Expert at creating structured knowledge and finding relationships",
|
||||
tools=[internet_search],
|
||||
memory=True,
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Task to build knowledge graph about AI companies
|
||||
build_task = Task(
|
||||
description="""Research and store information about major AI companies and their relationships:
|
||||
1. OpenAI - products like GPT-4, ChatGPT, leadership, partnerships
|
||||
2. Anthropic - Claude AI, safety focus, team
|
||||
3. Relationships between these companies and their technologies
|
||||
|
||||
Focus on capturing connections and relationships between entities.""",
|
||||
expected_output="Knowledge graph with AI company ecosystem relationships",
|
||||
agent=knowledge_agent
|
||||
)
|
||||
|
||||
# Task to query the knowledge graph
|
||||
query_task = Task(
|
||||
description="""Using the stored knowledge graph, answer:
|
||||
1. What are the main products of each company?
|
||||
2. Who are the key leaders in these companies?
|
||||
3. How do these companies relate to each other?
|
||||
|
||||
Use relationship-aware memory retrieval.""",
|
||||
expected_output="Analysis using graph memory relationships",
|
||||
agent=knowledge_agent
|
||||
)
|
||||
|
||||
# Run with graph memory integration
|
||||
agents_system = PraisonAIAgents(
|
||||
agents=[knowledge_agent],
|
||||
tasks=[build_task, query_task],
|
||||
memory=True,
|
||||
memory_config=memory_config,
|
||||
verbose=True
|
||||
)
|
||||
|
||||
print("Starting graph memory demonstration...")
|
||||
result = agents_system.start()
|
||||
|
||||
print(f"\nGraph Memory Result: {result[:200]}...")
|
||||
print("\n✅ Graph memory integration complete!")
|
||||
print("Agent built knowledge graph and performed relationship-aware queries.")
|
||||
@@ -0,0 +1,76 @@
|
||||
"""
|
||||
Advanced Memory Search and Optimization Example
|
||||
|
||||
This example demonstrates memory search optimization using PraisonAI's
|
||||
built-in memory capabilities with semantic search and quality filtering.
|
||||
"""
|
||||
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.tools import internet_search
|
||||
|
||||
print("=== Advanced Memory Search and Optimization Example ===\n")
|
||||
|
||||
# Configure optimized memory settings
|
||||
memory_config = {
|
||||
"provider": "mem0",
|
||||
"config": {
|
||||
"vector_store": {
|
||||
"provider": "chroma",
|
||||
"config": {
|
||||
"path": ".praison/optimized_memory"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Create research agent with optimized memory
|
||||
research_agent = Agent(
|
||||
name="Memory Research Agent",
|
||||
role="Information Researcher with Memory Optimization",
|
||||
goal="Research and demonstrate optimized memory search patterns",
|
||||
backstory="Expert at storing and retrieving information efficiently with memory optimization",
|
||||
tools=[internet_search],
|
||||
memory=True,
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Task to build searchable memory
|
||||
build_memory_task = Task(
|
||||
description="""Research and store information about these topics for later search:
|
||||
1. Artificial intelligence market trends and growth data
|
||||
2. Machine learning technologies and applications
|
||||
3. Tech industry partnerships and investments
|
||||
4. Cloud computing adoption statistics
|
||||
|
||||
Store detailed information that can be searched later.""",
|
||||
expected_output="Comprehensive research stored in optimized memory",
|
||||
agent=research_agent
|
||||
)
|
||||
|
||||
# Task to demonstrate memory search optimization
|
||||
search_task = Task(
|
||||
description="""Using the stored memory, perform optimized searches for:
|
||||
1. "AI market growth trends" - find relevant stored information
|
||||
2. "technology partnerships" - retrieve partnership data
|
||||
3. "cloud adoption statistics" - search for cloud computing info
|
||||
|
||||
Demonstrate efficient memory retrieval and search optimization.""",
|
||||
expected_output="Results from optimized memory searches",
|
||||
agent=research_agent
|
||||
)
|
||||
|
||||
# Run with memory optimization
|
||||
agents_system = PraisonAIAgents(
|
||||
agents=[research_agent],
|
||||
tasks=[build_memory_task, search_task],
|
||||
memory=True,
|
||||
memory_config=memory_config,
|
||||
verbose=True
|
||||
)
|
||||
|
||||
print("Starting memory search optimization demonstration...")
|
||||
result = agents_system.start()
|
||||
|
||||
print(f"\nMemory Search Result: {result[:200]}...")
|
||||
print("\n✅ Memory search optimization complete!")
|
||||
print("Agent demonstrated efficient memory storage and optimized search retrieval.")
|
||||
@@ -0,0 +1,12 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a creative designer AI agent. "
|
||||
"Help users with graphic design concepts, branding strategies, "
|
||||
"visual communication, and creative problem-solving. Provide guidance "
|
||||
"on design principles, color theory, typography, and user experience.",
|
||||
llm="anthropic/claude-3-5-sonnet-20241022"
|
||||
)
|
||||
|
||||
response = agent.start("Hello! I'm your creative designer assistant. "
|
||||
"How can I help you with your design projects today?")
|
||||
@@ -0,0 +1,12 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are an educational tutor AI agent. "
|
||||
"Help students learn various subjects, explain complex concepts, "
|
||||
"provide step-by-step solutions, and create personalized learning "
|
||||
"materials for different educational levels.",
|
||||
llm="anthropic/claude-3-5-sonnet-20241022"
|
||||
)
|
||||
|
||||
response = agent.start("Hello! I'm your educational tutor assistant. "
|
||||
"How can I help you learn today?")
|
||||
@@ -0,0 +1,12 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a financial advisor AI agent. "
|
||||
"Help users understand financial concepts, analyze investment opportunities, "
|
||||
"and provide guidance on personal finance, budgeting, and financial planning. "
|
||||
"Note: This is for educational purposes only, not financial advice.",
|
||||
llm="anthropic/claude-3-5-sonnet-20241022"
|
||||
)
|
||||
|
||||
response = agent.start("Hello! I'm your financial advisor assistant. "
|
||||
"How can I help you understand financial concepts today?")
|
||||
@@ -0,0 +1,12 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a legal advisor AI agent. "
|
||||
"Help users understand legal concepts, review contracts, "
|
||||
"analyze legal documents, and provide guidance on compliance "
|
||||
"and regulatory requirements. Note: This is for educational purposes only.",
|
||||
llm="anthropic/claude-3-5-sonnet-20241022"
|
||||
)
|
||||
|
||||
response = agent.start("Hello! I'm your legal advisor assistant. "
|
||||
"How can I help you understand legal concepts today?")
|
||||
@@ -0,0 +1,12 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a medical research AI agent. "
|
||||
"Help users understand medical concepts, analyze research papers, "
|
||||
"and provide insights on healthcare trends and developments. "
|
||||
"Note: This is for educational purposes only, not medical advice.",
|
||||
llm="anthropic/claude-3-5-sonnet-20241022"
|
||||
)
|
||||
|
||||
response = agent.start("Hello! I'm your medical research assistant. "
|
||||
"How can I help you understand medical concepts today?")
|
||||
@@ -1,18 +1,12 @@
|
||||
import asyncio
|
||||
from praisonaiagents import Agent
|
||||
|
||||
async def main():
|
||||
agent = Agent(
|
||||
instructions="You are a helpful assistant",
|
||||
llm="gemini/gemini-1.5-flash-8b",
|
||||
self_reflect=True,
|
||||
verbose=True
|
||||
)
|
||||
agent = Agent(
|
||||
instructions="You are a helpful assistant",
|
||||
llm="gemini/gemini-1.5-flash-8b",
|
||||
self_reflect=True,
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Use achat instead of start/chat for async operation
|
||||
response = await agent.achat("Why sky is Blue in 1000 words?")
|
||||
print(response)
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Run the async main function
|
||||
asyncio.run(main())
|
||||
# Use achat instead of start/chat for async operation
|
||||
response = asyncio.run(agent.achat("Why sky is Blue in 1000 words?"))
|
||||
@@ -0,0 +1,12 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a cybersecurity AI agent. "
|
||||
"Help users understand security concepts, analyze security threats, "
|
||||
"and provide guidance on security best practices, risk assessment, "
|
||||
"and security architecture design.",
|
||||
llm="openai/gpt-4o"
|
||||
)
|
||||
|
||||
response = agent.start("Hello! I'm your cybersecurity assistant. "
|
||||
"How can I help you with security concepts today?")
|
||||
@@ -0,0 +1,12 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a data engineer AI agent. "
|
||||
"Help users design data pipelines, optimize database performance, "
|
||||
"create ETL processes, and provide guidance on data architecture, "
|
||||
"data modeling, and big data technologies.",
|
||||
llm="openai/gpt-4o"
|
||||
)
|
||||
|
||||
response = agent.start("Hello! I'm your data engineer assistant. "
|
||||
"How can I help you with your data engineering projects today?")
|
||||
@@ -0,0 +1,12 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a marketing strategist AI agent. "
|
||||
"Help users develop marketing strategies, analyze market trends, "
|
||||
"create campaign plans, and provide guidance on digital marketing, "
|
||||
"brand positioning, and customer acquisition strategies.",
|
||||
llm="openai/gpt-4o"
|
||||
)
|
||||
|
||||
response = agent.start("Hello! I'm your marketing strategist assistant. "
|
||||
"How can I help you with your marketing strategy today?")
|
||||
@@ -0,0 +1,12 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a product manager AI agent. "
|
||||
"Help users with product strategy, feature prioritization, "
|
||||
"user research analysis, and product roadmap planning. Provide "
|
||||
"guidance on market analysis, competitive positioning, and user experience.",
|
||||
llm="openai/gpt-4o"
|
||||
)
|
||||
|
||||
response = agent.start("Hello! I'm your product manager assistant. "
|
||||
"How can I help you with your product strategy today?")
|
||||
@@ -0,0 +1,12 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a software architect AI agent. "
|
||||
"Help users design software systems, create architecture diagrams, "
|
||||
"plan system integrations, and provide guidance on scalability, "
|
||||
"security, and best practices for software development.",
|
||||
llm="openai/gpt-4o"
|
||||
)
|
||||
|
||||
response = agent.start("Hello! I'm your software architect assistant. "
|
||||
"How can I help you design your software system today?")
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,30 @@
|
||||
"""
|
||||
Basic example of using Grok model in PraisonAI
|
||||
"""
|
||||
|
||||
from praisonaiagents import Agent
|
||||
|
||||
# Initialize Agent with Grok model
|
||||
agent = Agent(
|
||||
instructions="You are a helpful assistant",
|
||||
llm="xai/grok-beta",
|
||||
)
|
||||
|
||||
# Example conversation
|
||||
response = agent.start("Hello! Can you explain quantum computing in simple terms?")
|
||||
|
||||
# Example with mathematical reasoning
|
||||
math_task = """
|
||||
Solve this problem step by step:
|
||||
If a train travels at 60 mph for 2.5 hours, how far does it travel?
|
||||
"""
|
||||
|
||||
response = agent.start(math_task)
|
||||
|
||||
# Example with creative writing
|
||||
creative_task = """
|
||||
Write a short story about a robot learning to paint.
|
||||
Make it engaging and about 100 words.
|
||||
"""
|
||||
|
||||
response = agent.start(creative_task)
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,14 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a crisis management and communication AI agent. "
|
||||
"Help users develop crisis communication strategies, "
|
||||
"manage reputation during difficult situations, and create effective messaging. "
|
||||
"Provide guidance on crisis response planning, stakeholder communication, "
|
||||
"media relations during crises, and reputation recovery strategies.",
|
||||
llm="groq/llama3.1-8b-instant"
|
||||
)
|
||||
|
||||
response = agent.start("Hello! I'm your crisis management and communication assistant. "
|
||||
"How can I help you develop effective crisis communication "
|
||||
"strategies and manage difficult situations today?")
|
||||
@@ -0,0 +1,14 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a digital marketing and SEO optimization AI agent. "
|
||||
"Help users develop digital marketing strategies, optimize for search engines, "
|
||||
"and improve online visibility. Provide guidance on SEO best practices, "
|
||||
"content marketing, social media strategies, PPC campaigns, "
|
||||
"and analytics interpretation for better ROI.",
|
||||
llm="groq/llama3.1-8b-instant"
|
||||
)
|
||||
|
||||
response = agent.start("Hello! I'm your digital marketing and SEO optimization assistant. "
|
||||
"How can I help you improve your online presence, "
|
||||
"optimize for search engines, or develop marketing strategies today?")
|
||||
@@ -0,0 +1,14 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are an environmental impact assessment AI agent. "
|
||||
"Help users evaluate environmental impacts of projects, "
|
||||
"develop sustainability strategies, and ensure compliance with environmental regulations. "
|
||||
"Provide guidance on environmental risk assessment, sustainability reporting, "
|
||||
"carbon footprint analysis, and green technology implementation.",
|
||||
llm="groq/llama3.1-8b-instant"
|
||||
)
|
||||
|
||||
response = agent.start("Hello! I'm your environmental impact assessment assistant. "
|
||||
"How can I help you evaluate environmental impacts, "
|
||||
"develop sustainability strategies, or ensure compliance today?")
|
||||
@@ -0,0 +1,14 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are an event planning and management AI agent. "
|
||||
"Help users plan, organize, and manage successful events of all types. "
|
||||
"Provide guidance on venue selection, budgeting, vendor coordination, "
|
||||
"timeline management, marketing strategies, and post-event analysis. "
|
||||
"Assist with both virtual and in-person event planning.",
|
||||
llm="groq/llama3.1-8b-instant"
|
||||
)
|
||||
|
||||
response = agent.start("Hello! I'm your event planning and management assistant. "
|
||||
"How can I help you plan and organize your next successful "
|
||||
"event today?")
|
||||
@@ -0,0 +1,14 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a healthcare and medical research AI agent. "
|
||||
"Help users with medical research, healthcare insights, "
|
||||
"and understanding complex medical information. Provide guidance on medical literature review, "
|
||||
"healthcare trends analysis, patient care strategies, "
|
||||
"and medical technology advancements for better healthcare outcomes.",
|
||||
llm="groq/llama3.1-8b-instant"
|
||||
)
|
||||
|
||||
response = agent.start("Hello! I'm your healthcare and medical research assistant. "
|
||||
"How can I help you with medical research, healthcare insights, "
|
||||
"or understanding complex medical information today?")
|
||||
@@ -0,0 +1,14 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a language learning and translation AI agent. "
|
||||
"Help users learn new languages, translate content accurately, "
|
||||
"and understand cultural nuances. Provide guidance on language learning strategies, "
|
||||
"grammar explanations, vocabulary building, pronunciation, "
|
||||
"and cultural context for effective communication.",
|
||||
llm="groq/llama3.1-8b-instant"
|
||||
)
|
||||
|
||||
response = agent.start("Hello! I'm your language learning and translation assistant. "
|
||||
"How can I help you learn new languages, translate content, "
|
||||
"or understand cultural nuances today?")
|
||||
@@ -0,0 +1,14 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a patent research and innovation AI agent. "
|
||||
"Help users conduct patent research, analyze intellectual property, "
|
||||
"identify innovation opportunities, and navigate patent filing processes. "
|
||||
"Provide guidance on patent searches, prior art analysis, "
|
||||
"innovation strategy, IP protection, and technology landscape assessment.",
|
||||
llm="groq/llama3.1-8b-instant"
|
||||
)
|
||||
|
||||
response = agent.start("Hello! I'm your patent research and innovation assistant. "
|
||||
"How can I help you with patent research, innovation strategy, "
|
||||
"and intellectual property protection today?")
|
||||
@@ -0,0 +1,19 @@
|
||||
"""
|
||||
Personal Branding & PR Agent using Groq
|
||||
Specialized agent for managing personal brand and public relations
|
||||
"""
|
||||
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a personal branding and PR AI agent. "
|
||||
"Help users build their personal brand, manage public relations, "
|
||||
"create compelling content strategies, and enhance their online presence. "
|
||||
"Provide guidance on social media management, content creation, "
|
||||
"media relations, reputation management, and brand positioning.",
|
||||
llm="groq/llama3.1-8b-instant"
|
||||
)
|
||||
|
||||
response = agent.start("Hello! I'm your personal branding and PR assistant. "
|
||||
"How can I help you build your personal brand and "
|
||||
"manage your public relations today?")
|
||||
@@ -0,0 +1,14 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a product development and innovation AI agent. "
|
||||
"Help users develop new products, improve existing ones, "
|
||||
"and drive innovation in their business. Provide guidance on product strategy, "
|
||||
"market research, user experience design, prototyping, "
|
||||
"and innovation management for successful product launches.",
|
||||
llm="groq/llama3.1-8b-instant"
|
||||
)
|
||||
|
||||
response = agent.start("Hello! I'm your product development and innovation assistant. "
|
||||
"How can I help you develop new products, improve existing ones, "
|
||||
"or drive innovation in your business today?")
|
||||
@@ -0,0 +1,14 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a supply chain optimization AI agent. "
|
||||
"Help users optimize their supply chain operations, "
|
||||
"improve logistics efficiency, reduce costs, and enhance inventory management. "
|
||||
"Provide guidance on demand forecasting, supplier management, "
|
||||
"warehouse optimization, transportation planning, and risk mitigation.",
|
||||
llm="groq/llama3.1-8b-instant"
|
||||
)
|
||||
|
||||
response = agent.start("Hello! I'm your supply chain optimization assistant. "
|
||||
"How can I help you optimize your supply chain operations "
|
||||
"and improve your logistics efficiency today?")
|
||||
@@ -0,0 +1,14 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are an aerospace engineering AI agent. "
|
||||
"Help users understand aerospace engineering concepts, "
|
||||
"aircraft design, and space technology. Provide guidance on "
|
||||
"aerodynamics, propulsion systems, materials science, "
|
||||
"and satellite technology.",
|
||||
llm="openrouter/moonshotai/kimi-k2"
|
||||
)
|
||||
|
||||
response = agent.start("Hello! I'm your aerospace engineering assistant. "
|
||||
"How can I help you with aerospace engineering "
|
||||
"and space technology today?")
|
||||
File renamed without changes.
@@ -0,0 +1,14 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a bioinformatics and genomics AI agent. "
|
||||
"Help users understand bioinformatics, genomics, "
|
||||
"and computational biology. Provide guidance on "
|
||||
"DNA sequence analysis, protein structure prediction, "
|
||||
"genetic algorithms, and biological data mining.",
|
||||
llm="openrouter/moonshotai/kimi-k2"
|
||||
)
|
||||
|
||||
response = agent.start("Hello! I'm your bioinformatics and genomics assistant. "
|
||||
"How can I help you with bioinformatics "
|
||||
"and genomics research today?")
|
||||
@@ -0,0 +1,14 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a blockchain and DeFi AI agent. "
|
||||
"Help users understand blockchain technology, "
|
||||
"decentralized finance, and cryptocurrency. Provide guidance on "
|
||||
"smart contract development, DeFi protocols, "
|
||||
"tokenomics, and blockchain security.",
|
||||
llm="openrouter/moonshotai/kimi-k2"
|
||||
)
|
||||
|
||||
response = agent.start("Hello! I'm your blockchain and DeFi assistant. "
|
||||
"How can I help you explore blockchain technology "
|
||||
"and decentralized finance today?")
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,14 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are an energy and renewables AI agent. "
|
||||
"Help users understand renewable energy technologies, "
|
||||
"energy systems, and sustainability. Provide guidance on "
|
||||
"solar power, wind energy, energy storage, "
|
||||
"and green technology solutions.",
|
||||
llm="openrouter/moonshotai/kimi-k2"
|
||||
)
|
||||
|
||||
response = agent.start("Hello! I'm your energy and renewables assistant. "
|
||||
"How can I help you with renewable energy "
|
||||
"and sustainability today?")
|
||||
File renamed without changes.
@@ -0,0 +1,14 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are an IoT and smart cities AI agent. "
|
||||
"Help users understand Internet of Things, smart city "
|
||||
"technologies, and connected systems. Provide guidance on "
|
||||
"IoT device integration, smart infrastructure, "
|
||||
"sensor networks, and urban technology solutions.",
|
||||
llm="openrouter/moonshotai/kimi-k2"
|
||||
)
|
||||
|
||||
response = agent.start("Hello! I'm your IoT and smart cities assistant. "
|
||||
"How can I help you with IoT and smart city "
|
||||
"technologies today?")
|
||||
@@ -0,0 +1,14 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a metaverse and virtual reality AI agent. "
|
||||
"Help users understand metaverse concepts, VR development, "
|
||||
"and immersive technologies. Provide guidance on "
|
||||
"3D modeling, VR programming, digital twins, "
|
||||
"and virtual world design.",
|
||||
llm="openrouter/moonshotai/kimi-k2"
|
||||
)
|
||||
|
||||
response = agent.start("Hello! I'm your metaverse and VR assistant. "
|
||||
"How can I help you explore the metaverse "
|
||||
"and virtual reality today?")
|
||||
@@ -0,0 +1,14 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a nanotechnology and materials AI agent. "
|
||||
"Help users understand nanotechnology, advanced materials, "
|
||||
"and material science. Provide guidance on "
|
||||
"nanomaterials, material properties, fabrication techniques, "
|
||||
"and applications in various industries.",
|
||||
llm="openrouter/moonshotai/kimi-k2"
|
||||
)
|
||||
|
||||
response = agent.start("Hello! I'm your nanotechnology and materials assistant. "
|
||||
"How can I help you with nanotechnology "
|
||||
"and materials science today?")
|
||||
@@ -0,0 +1,14 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a quantum AI agent. "
|
||||
"Help users understand quantum artificial intelligence, "
|
||||
"quantum machine learning, and quantum neural networks. "
|
||||
"Provide guidance on quantum algorithms for AI, "
|
||||
"quantum optimization, and hybrid quantum-classical systems.",
|
||||
llm="openrouter/moonshotai/kimi-k2"
|
||||
)
|
||||
|
||||
response = agent.start("Hello! I'm your quantum AI assistant. "
|
||||
"How can I help you explore quantum artificial "
|
||||
"intelligence today?")
|
||||
@@ -0,0 +1,14 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a quantum computing AI agent. "
|
||||
"Help users understand quantum computing concepts, "
|
||||
"quantum algorithms, and quantum programming. Provide guidance on "
|
||||
"quantum circuit design, quantum error correction, "
|
||||
"quantum machine learning, and quantum cryptography.",
|
||||
llm="openrouter/moonshotai/kimi-k2"
|
||||
)
|
||||
|
||||
response = agent.start("Hello! I'm your quantum computing assistant. "
|
||||
"How can I help you explore quantum computing "
|
||||
"and quantum programming today?")
|
||||
@@ -0,0 +1,14 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a robotics and automation AI agent. "
|
||||
"Help users understand robotics, automation systems, "
|
||||
"and industrial applications. Provide guidance on "
|
||||
"robot programming, automation workflows, "
|
||||
"sensor integration, and robotic process automation.",
|
||||
llm="openrouter/moonshotai/kimi-k2"
|
||||
)
|
||||
|
||||
response = agent.start("Hello! I'm your robotics and automation assistant. "
|
||||
"How can I help you with robotics and "
|
||||
"automation systems today?")
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,12 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a business analyst AI agent. "
|
||||
"Help users analyze business performance, market trends, "
|
||||
"competitive landscape, and strategic opportunities. Provide insights "
|
||||
"on business metrics, financial analysis, and growth strategies.",
|
||||
llm="meta-llama/Llama-3.1-8B-Instruct"
|
||||
)
|
||||
|
||||
response = agent.start("Hello! I'm your business analyst assistant. "
|
||||
"How can I help you analyze your business data and strategies today?")
|
||||
@@ -0,0 +1,12 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a code review AI agent. "
|
||||
"Help developers review code for best practices, security vulnerabilities, "
|
||||
"performance issues, and maintainability. Provide constructive feedback "
|
||||
"and suggest improvements for code quality and efficiency.",
|
||||
llm="meta-llama/Llama-3.1-8B-Instruct"
|
||||
)
|
||||
|
||||
response = agent.start("Hello! I'm your code review assistant. "
|
||||
"How can I help you improve your code quality today?")
|
||||
@@ -0,0 +1,12 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a content writing AI agent. "
|
||||
"Help users create engaging blog posts, articles, marketing copy, "
|
||||
"and social media content. Provide guidance on SEO optimization, "
|
||||
"content structure, tone adjustment, and audience targeting.",
|
||||
llm="meta-llama/Llama-3.1-8B-Instruct"
|
||||
)
|
||||
|
||||
response = agent.start("Hello! I'm your content writing assistant. "
|
||||
"How can I help you create compelling content today?")
|
||||
@@ -0,0 +1,12 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a data science AI agent. "
|
||||
"Help users with data analysis, machine learning model development, "
|
||||
"statistical analysis, and data visualization. Provide guidance on "
|
||||
"data preprocessing, feature engineering, model selection, and evaluation.",
|
||||
llm="meta-llama/Llama-3.1-8B-Instruct"
|
||||
)
|
||||
|
||||
response = agent.start("Hello! I'm your data science assistant. "
|
||||
"How can I help you with your data analysis and machine learning projects today?")
|
||||
@@ -0,0 +1,12 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a research assistant AI agent. "
|
||||
"Help users conduct comprehensive research on various topics, "
|
||||
"analyze academic papers, synthesize information, and provide "
|
||||
"evidence-based insights and recommendations.",
|
||||
llm="meta-llama/Llama-3.1-8B-Instruct"
|
||||
)
|
||||
|
||||
response = agent.start("Hello! I'm your research assistant. "
|
||||
"How can I help you with your research project today?")
|
||||
@@ -0,0 +1,315 @@
|
||||
# MongoDB Integration Examples for PraisonAI Agents
|
||||
|
||||
This directory contains comprehensive examples demonstrating how to integrate MongoDB with PraisonAI agents for memory, knowledge, and data operations.
|
||||
|
||||
## Features
|
||||
|
||||
MongoDB integration with PraisonAI provides:
|
||||
|
||||
- **Memory Provider**: Use MongoDB as a persistent memory store for agents
|
||||
- **Knowledge Store**: Store and retrieve documents with vector search capabilities
|
||||
- **Tools Integration**: Perform MongoDB operations directly from agents
|
||||
- **Vector Search**: Leverage MongoDB Atlas Vector Search for semantic similarity
|
||||
- **Scalability**: Handle large datasets with MongoDB's scalable architecture
|
||||
- **Flexibility**: Use MongoDB as both key-value store and vector database
|
||||
|
||||
## Prerequisites
|
||||
|
||||
### Installation
|
||||
|
||||
```bash
|
||||
# Install PraisonAI with MongoDB support
|
||||
pip install 'praisonaiagents[mongodb]'
|
||||
```
|
||||
|
||||
### Dependencies
|
||||
|
||||
- **MongoDB**: Local MongoDB instance or MongoDB Atlas
|
||||
- **OpenAI API Key**: For embeddings and LLM operations
|
||||
- **Python 3.10+**: Required for PraisonAI
|
||||
|
||||
### Environment Setup
|
||||
|
||||
```bash
|
||||
# Set your OpenAI API key
|
||||
export OPENAI_API_KEY="your-openai-api-key"
|
||||
|
||||
# Optional: Set MongoDB connection string
|
||||
export MONGODB_CONNECTION_STRING="mongodb://localhost:27017/"
|
||||
```
|
||||
|
||||
## Examples Overview
|
||||
|
||||
### 1. [mongodb_memory_example.py](mongodb_memory_example.py)
|
||||
|
||||
Demonstrates using MongoDB as a memory provider for PraisonAI agents.
|
||||
|
||||
**Features:**
|
||||
- MongoDB as persistent memory storage
|
||||
- Quality scoring and filtering
|
||||
- Vector search for memory retrieval
|
||||
- Multi-session memory persistence
|
||||
- Memory search and context building
|
||||
|
||||
**Usage:**
|
||||
```bash
|
||||
python mongodb_memory_example.py
|
||||
```
|
||||
|
||||
### 2. [mongodb_knowledge_example.py](mongodb_knowledge_example.py)
|
||||
|
||||
Shows how to use MongoDB as a knowledge store with vector search capabilities.
|
||||
|
||||
**Features:**
|
||||
- MongoDB as knowledge vector store
|
||||
- Document processing and storage
|
||||
- Vector search for knowledge retrieval
|
||||
- Knowledge-based agent interactions
|
||||
- File processing with MongoDB storage
|
||||
|
||||
**Usage:**
|
||||
```bash
|
||||
python mongodb_knowledge_example.py
|
||||
```
|
||||
|
||||
### 3. [mongodb_tools_example.py](mongodb_tools_example.py)
|
||||
|
||||
Demonstrates MongoDB tools integration for database operations.
|
||||
|
||||
**Features:**
|
||||
- MongoDB CRUD operations
|
||||
- Vector search with embeddings
|
||||
- Data analysis and aggregation
|
||||
- Collection management
|
||||
- Index creation and optimization
|
||||
|
||||
**Usage:**
|
||||
```bash
|
||||
python mongodb_tools_example.py
|
||||
```
|
||||
|
||||
### 4. [mongodb_comprehensive_example.py](mongodb_comprehensive_example.py)
|
||||
|
||||
Complete business scenario simulation using all MongoDB features.
|
||||
|
||||
**Features:**
|
||||
- Full MongoDB integration (memory + knowledge + tools)
|
||||
- Multi-agent business workflow
|
||||
- Real-world e-commerce simulation
|
||||
- Business intelligence analytics
|
||||
- Customer service automation
|
||||
|
||||
**Usage:**
|
||||
```bash
|
||||
python mongodb_comprehensive_example.py
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
### MongoDB Memory Configuration
|
||||
|
||||
```python
|
||||
mongodb_memory_config = {
|
||||
"provider": "mongodb",
|
||||
"config": {
|
||||
"connection_string": "mongodb://localhost:27017/",
|
||||
"database": "praisonai_memory",
|
||||
"use_vector_search": True, # Enable Atlas Vector Search
|
||||
"max_pool_size": 50,
|
||||
"min_pool_size": 10,
|
||||
"server_selection_timeout": 5000
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### MongoDB Knowledge Configuration
|
||||
|
||||
```python
|
||||
mongodb_knowledge_config = {
|
||||
"vector_store": {
|
||||
"provider": "mongodb",
|
||||
"config": {
|
||||
"connection_string": "mongodb://localhost:27017/",
|
||||
"database": "praisonai_knowledge",
|
||||
"collection": "knowledge_base",
|
||||
"use_vector_search": True
|
||||
}
|
||||
},
|
||||
"embedder": {
|
||||
"provider": "openai",
|
||||
"config": {
|
||||
"model": "text-embedding-3-small"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## MongoDB Atlas Vector Search
|
||||
|
||||
For production use with advanced vector search capabilities:
|
||||
|
||||
### Setup
|
||||
|
||||
1. **Create MongoDB Atlas Cluster**
|
||||
- Sign up for MongoDB Atlas
|
||||
- Create a new cluster
|
||||
- Get your connection string
|
||||
|
||||
2. **Enable Vector Search**
|
||||
- Create vector search indexes
|
||||
- Configure embedding dimensions (1536 for OpenAI)
|
||||
- Set similarity metric (cosine, euclidean, dotProduct)
|
||||
|
||||
3. **Update Connection String**
|
||||
```python
|
||||
"connection_string": "mongodb+srv://username:[email protected]/"
|
||||
```
|
||||
|
||||
### Vector Search Index Creation
|
||||
|
||||
```python
|
||||
# Vector search index definition
|
||||
{
|
||||
"mappings": {
|
||||
"dynamic": True,
|
||||
"fields": {
|
||||
"embedding": {
|
||||
"type": "knnVector",
|
||||
"dimensions": 1536,
|
||||
"similarity": "cosine"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
### 1. Connection Management
|
||||
|
||||
```python
|
||||
# Use connection pooling
|
||||
mongodb_config = {
|
||||
"connection_string": "mongodb://localhost:27017/",
|
||||
"max_pool_size": 50,
|
||||
"min_pool_size": 10,
|
||||
"maxIdleTimeMS": 30000,
|
||||
"serverSelectionTimeoutMS": 5000
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Indexing Strategy
|
||||
|
||||
```python
|
||||
# Create appropriate indexes
|
||||
collection.create_index([("content", "text")]) # Text search
|
||||
collection.create_index([("created_at", -1)]) # Time-based queries
|
||||
collection.create_index([("metadata.category", 1)]) # Category filtering
|
||||
```
|
||||
|
||||
### 3. Error Handling
|
||||
|
||||
```python
|
||||
try:
|
||||
# MongoDB operations
|
||||
result = collection.insert_one(document)
|
||||
except PyMongoError as e:
|
||||
logger.error(f"MongoDB error: {e}")
|
||||
# Implement fallback strategy
|
||||
```
|
||||
|
||||
### 4. Data Validation
|
||||
|
||||
```python
|
||||
# Validate data before storage
|
||||
def validate_document(doc):
|
||||
required_fields = ["content", "metadata", "created_at"]
|
||||
return all(field in doc for field in required_fields)
|
||||
```
|
||||
|
||||
## Performance Considerations
|
||||
|
||||
### 1. Indexing
|
||||
|
||||
- Create indexes on frequently queried fields
|
||||
- Use compound indexes for complex queries
|
||||
- Monitor index usage with MongoDB profiler
|
||||
|
||||
### 2. Vector Search Optimization
|
||||
|
||||
- Use appropriate vector dimensions
|
||||
- Optimize numCandidates parameter
|
||||
- Consider filtering to reduce search space
|
||||
|
||||
### 3. Connection Pooling
|
||||
|
||||
- Configure appropriate pool sizes
|
||||
- Use connection pooling for high-concurrency scenarios
|
||||
- Monitor connection metrics
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
1. **Connection Errors**
|
||||
- Check MongoDB server is running
|
||||
- Verify connection string format
|
||||
- Ensure network connectivity
|
||||
|
||||
2. **Vector Search Issues**
|
||||
- Verify Atlas Vector Search indexes exist
|
||||
- Check embedding dimensions match
|
||||
- Ensure proper index configuration
|
||||
|
||||
3. **Memory Issues**
|
||||
- Monitor memory usage with large datasets
|
||||
- Use appropriate batch sizes
|
||||
- Consider data pagination
|
||||
|
||||
### Debugging
|
||||
|
||||
```python
|
||||
# Enable detailed logging
|
||||
import logging
|
||||
logging.basicConfig(level=logging.DEBUG)
|
||||
|
||||
# Monitor MongoDB operations
|
||||
from pymongo import monitoring
|
||||
monitoring.register(CommandLogger())
|
||||
```
|
||||
|
||||
## Production Deployment
|
||||
|
||||
### 1. Security
|
||||
|
||||
```python
|
||||
# Use authentication
|
||||
connection_string = "mongodb://username:password@host:port/database"
|
||||
|
||||
# Enable SSL/TLS
|
||||
client = MongoClient(connection_string, tls=True)
|
||||
```
|
||||
|
||||
### 2. Monitoring
|
||||
|
||||
- Use MongoDB Atlas monitoring
|
||||
- Implement application-level metrics
|
||||
- Set up alerting for critical issues
|
||||
|
||||
### 3. Backup and Recovery
|
||||
|
||||
- Configure automated backups
|
||||
- Test restore procedures
|
||||
- Implement disaster recovery plans
|
||||
|
||||
## Support
|
||||
|
||||
For additional support:
|
||||
|
||||
- [PraisonAI Documentation](https://docs.praisonai.com)
|
||||
- [MongoDB Documentation](https://docs.mongodb.com)
|
||||
- [MongoDB Atlas Vector Search](https://docs.atlas.mongodb.com/atlas-vector-search/)
|
||||
|
||||
## License
|
||||
|
||||
These examples are provided under the same license as PraisonAI.
|
||||
@@ -0,0 +1,285 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Comprehensive MongoDB Integration Example for PraisonAI Agents
|
||||
|
||||
This example demonstrates a complete MongoDB integration with PraisonAI agents,
|
||||
combining memory, knowledge, and tools for a comprehensive data management system.
|
||||
|
||||
Prerequisites:
|
||||
- Install MongoDB dependencies: pip install 'praisonaiagents[mongodb]'
|
||||
- MongoDB server running (local or Atlas)
|
||||
- OpenAI API key for embeddings
|
||||
|
||||
Features demonstrated:
|
||||
- MongoDB as memory provider
|
||||
- MongoDB as knowledge store
|
||||
- MongoDB tools for data operations
|
||||
- Vector search capabilities
|
||||
- Multi-agent coordination with MongoDB
|
||||
- Real-world business scenario simulation
|
||||
"""
|
||||
|
||||
import os
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.tools import mongodb_tools
|
||||
|
||||
# Ensure OpenAI API key is set
|
||||
if not os.environ.get("OPENAI_API_KEY"):
|
||||
raise ValueError("Please set the OPENAI_API_KEY environment variable")
|
||||
|
||||
def main():
|
||||
# MongoDB configuration for different components
|
||||
mongodb_memory_config = {
|
||||
"provider": "mongodb",
|
||||
"config": {
|
||||
"connection_string": "mongodb://localhost:27017/", # Replace with your connection string
|
||||
"database": "praisonai_comprehensive",
|
||||
"use_vector_search": True,
|
||||
"max_pool_size": 50
|
||||
}
|
||||
}
|
||||
|
||||
mongodb_knowledge_config = {
|
||||
"vector_store": {
|
||||
"provider": "mongodb",
|
||||
"config": {
|
||||
"connection_string": "mongodb://localhost:27017/",
|
||||
"database": "praisonai_comprehensive",
|
||||
"collection": "knowledge_base",
|
||||
"use_vector_search": True
|
||||
}
|
||||
},
|
||||
"embedder": {
|
||||
"provider": "openai",
|
||||
"config": {
|
||||
"model": "text-embedding-3-small",
|
||||
"api_key": os.getenv("OPENAI_API_KEY")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Create specialized agents for different business functions
|
||||
|
||||
# 1. Data Manager Agent - handles data operations
|
||||
data_manager = Agent(
|
||||
name="Data Manager",
|
||||
role="Senior Data Operations Manager",
|
||||
goal="Manage and organize all data operations using MongoDB",
|
||||
backstory="""You are an expert data operations manager who specializes in
|
||||
MongoDB database management. You handle data ingestion, organization,
|
||||
indexing, and ensure data quality and accessibility across the organization.""",
|
||||
tools=[mongodb_tools],
|
||||
memory=True,
|
||||
verbose=True,
|
||||
llm="gpt-4o-mini"
|
||||
)
|
||||
|
||||
# 2. Knowledge Curator Agent - manages knowledge base
|
||||
knowledge_curator = Agent(
|
||||
name="Knowledge Curator",
|
||||
role="Knowledge Management Specialist",
|
||||
goal="Curate and maintain organizational knowledge using MongoDB",
|
||||
backstory="""You are a knowledge management specialist who excels at
|
||||
organizing, categorizing, and retrieving information from the knowledge base.
|
||||
You ensure that knowledge is properly stored, indexed, and accessible.""",
|
||||
knowledge=True,
|
||||
knowledge_config=mongodb_knowledge_config,
|
||||
memory=True,
|
||||
verbose=True,
|
||||
llm="gpt-4o-mini"
|
||||
)
|
||||
|
||||
# 3. Business Analyst Agent - analyzes data and provides insights
|
||||
business_analyst = Agent(
|
||||
name="Business Analyst",
|
||||
role="Senior Business Intelligence Analyst",
|
||||
goal="Analyze business data and provide actionable insights",
|
||||
backstory="""You are a senior business analyst who specializes in extracting
|
||||
insights from data stored in MongoDB. You create reports, identify trends,
|
||||
and provide strategic recommendations based on data analysis.""",
|
||||
tools=[mongodb_tools],
|
||||
memory=True,
|
||||
verbose=True,
|
||||
llm="gpt-4o-mini"
|
||||
)
|
||||
|
||||
# 4. Customer Service Agent - handles customer interactions
|
||||
customer_service = Agent(
|
||||
name="Customer Service Agent",
|
||||
role="Customer Service Representative",
|
||||
goal="Provide excellent customer service using stored knowledge and data",
|
||||
backstory="""You are a customer service representative who uses the
|
||||
knowledge base and customer data to provide excellent support. You can
|
||||
access customer history, product information, and troubleshooting guides.""",
|
||||
knowledge=True,
|
||||
knowledge_config=mongodb_knowledge_config,
|
||||
tools=[mongodb_tools],
|
||||
memory=True,
|
||||
verbose=True,
|
||||
llm="gpt-4o-mini"
|
||||
)
|
||||
|
||||
# Create comprehensive business tasks
|
||||
business_tasks = [
|
||||
Task(
|
||||
description="""Set up comprehensive business data infrastructure:
|
||||
1. Create collections for customers, products, orders, and support tickets
|
||||
2. Insert sample business data for an e-commerce platform
|
||||
3. Set up appropriate indexes for performance optimization
|
||||
4. Create vector indexes for product descriptions and customer support
|
||||
5. Implement data validation and business rules
|
||||
|
||||
Focus on creating a realistic business data structure.
|
||||
""",
|
||||
expected_output="Complete business data infrastructure with sample data",
|
||||
agent=data_manager
|
||||
),
|
||||
Task(
|
||||
description="""Build organizational knowledge base:
|
||||
1. Store product documentation and specifications
|
||||
2. Create customer service guidelines and FAQs
|
||||
3. Add troubleshooting guides and best practices
|
||||
4. Include company policies and procedures
|
||||
5. Organize knowledge by categories and tags
|
||||
|
||||
Ensure knowledge is searchable and well-organized.
|
||||
""",
|
||||
expected_output="Comprehensive knowledge base with categorized information",
|
||||
agent=knowledge_curator
|
||||
),
|
||||
Task(
|
||||
description="""Perform business intelligence analysis:
|
||||
1. Analyze customer purchase patterns and behavior
|
||||
2. Calculate key business metrics (revenue, conversion rates, etc.)
|
||||
3. Identify top-selling products and categories
|
||||
4. Analyze customer support ticket trends
|
||||
5. Generate insights for business optimization
|
||||
|
||||
Use MongoDB aggregation and analytics capabilities.
|
||||
""",
|
||||
expected_output="Business intelligence report with actionable insights",
|
||||
agent=business_analyst
|
||||
),
|
||||
Task(
|
||||
description="""Handle customer service scenarios:
|
||||
1. Process customer inquiries using knowledge base
|
||||
2. Look up customer order history and preferences
|
||||
3. Provide product recommendations based on customer data
|
||||
4. Access troubleshooting guides for technical issues
|
||||
5. Update customer records and interaction history
|
||||
|
||||
Demonstrate excellent customer service with data-driven support.
|
||||
""",
|
||||
expected_output="Customer service interactions with knowledge-based responses",
|
||||
agent=customer_service
|
||||
),
|
||||
Task(
|
||||
description="""Generate comprehensive business report:
|
||||
1. Combine insights from all data sources
|
||||
2. Create executive summary with key findings
|
||||
3. Provide recommendations for business improvement
|
||||
4. Include data visualizations and metrics
|
||||
5. Store report in knowledge base for future reference
|
||||
|
||||
Create a comprehensive business intelligence report.
|
||||
""",
|
||||
expected_output="Executive business report with comprehensive insights",
|
||||
agent=business_analyst
|
||||
)
|
||||
]
|
||||
|
||||
# Initialize the comprehensive business system
|
||||
print("🚀 Starting Comprehensive MongoDB Business System...")
|
||||
print("=" * 60)
|
||||
|
||||
business_system = PraisonAIAgents(
|
||||
agents=[data_manager, knowledge_curator, business_analyst, customer_service],
|
||||
tasks=business_tasks,
|
||||
memory=True,
|
||||
memory_config=mongodb_memory_config,
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Execute the comprehensive business pipeline
|
||||
try:
|
||||
results = business_system.start()
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("📊 Comprehensive Business System Results:")
|
||||
print("=" * 60)
|
||||
|
||||
for i, result in enumerate(results, 1):
|
||||
print(f"\n{i}. Task Result:")
|
||||
print(f" Output: {result.raw[:200]}...")
|
||||
print(f" Agent: {result.agent}")
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("💾 Comprehensive MongoDB Integration Complete!")
|
||||
print("=" * 60)
|
||||
|
||||
# Demonstrate system integration
|
||||
print("\n🔍 Demonstrating System Integration:")
|
||||
print("-" * 40)
|
||||
|
||||
# Access different components
|
||||
memory_system = business_system.memory
|
||||
|
||||
# Search business memories
|
||||
print("📋 Searching business memories...")
|
||||
business_memories = memory_system.search_long_term("business analysis", limit=3)
|
||||
print(f"Found {len(business_memories)} business-related memories")
|
||||
|
||||
# Access knowledge system
|
||||
from praisonaiagents.knowledge import Knowledge
|
||||
knowledge_system = Knowledge(config=mongodb_knowledge_config)
|
||||
|
||||
# Search knowledge base
|
||||
print("\n📚 Searching knowledge base...")
|
||||
knowledge_results = knowledge_system.search("customer service", limit=3)
|
||||
print(f"Found {len(knowledge_results)} knowledge entries")
|
||||
|
||||
# Direct MongoDB operations
|
||||
print("\n🔧 Direct MongoDB operations...")
|
||||
mongo_client = mongodb_tools.connect_mongodb(
|
||||
"mongodb://localhost:27017/",
|
||||
"praisonai_comprehensive"
|
||||
)
|
||||
|
||||
# Get database statistics
|
||||
stats = mongo_client.get_stats("customers")
|
||||
print(f"Customer collection stats: {stats}")
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("🎉 Comprehensive MongoDB Example Completed Successfully!")
|
||||
print("=" * 60)
|
||||
|
||||
print("\n📈 System Overview:")
|
||||
print("- Memory System: MongoDB-based persistent memory")
|
||||
print("- Knowledge Base: MongoDB vector search enabled")
|
||||
print("- Tools Integration: Full MongoDB CRUD operations")
|
||||
print("- Multi-Agent Coordination: Business workflow simulation")
|
||||
print("- Vector Search: Semantic search capabilities")
|
||||
print("- Data Analytics: Business intelligence insights")
|
||||
|
||||
except Exception as e:
|
||||
print(f"\n❌ Error during execution: {e}")
|
||||
print("Please check your MongoDB connection and API keys.")
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("Comprehensive MongoDB Integration Example")
|
||||
print("=" * 50)
|
||||
print("This example demonstrates complete MongoDB integration with PraisonAI")
|
||||
print("Features:")
|
||||
print("- MongoDB Memory Provider")
|
||||
print("- MongoDB Knowledge Store")
|
||||
print("- MongoDB Tools Integration")
|
||||
print("- Vector Search Capabilities")
|
||||
print("- Multi-Agent Business Simulation")
|
||||
print("=" * 50)
|
||||
print("Make sure you have:")
|
||||
print("1. MongoDB server running (local or Atlas)")
|
||||
print("2. OpenAI API key set in environment variables")
|
||||
print("3. MongoDB dependencies installed: pip install 'praisonaiagents[mongodb]'")
|
||||
print("=" * 50)
|
||||
|
||||
main()
|
||||
@@ -0,0 +1,195 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
MongoDB Knowledge Example for PraisonAI Agents
|
||||
|
||||
This example demonstrates how to use MongoDB as a knowledge store for PraisonAI agents.
|
||||
MongoDB can store and retrieve knowledge documents with vector search capabilities.
|
||||
|
||||
Prerequisites:
|
||||
- Install MongoDB dependencies: pip install 'praisonaiagents[mongodb]'
|
||||
- MongoDB server running (local or Atlas)
|
||||
- OpenAI API key for embeddings
|
||||
|
||||
Features demonstrated:
|
||||
- MongoDB as knowledge vector store
|
||||
- Document processing and storage
|
||||
- Vector search for knowledge retrieval
|
||||
- Knowledge-based agent interactions
|
||||
- File processing with MongoDB storage
|
||||
"""
|
||||
|
||||
import os
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
|
||||
# Ensure OpenAI API key is set
|
||||
if not os.environ.get("OPENAI_API_KEY"):
|
||||
raise ValueError("Please set the OPENAI_API_KEY environment variable")
|
||||
|
||||
def main():
|
||||
# MongoDB knowledge configuration
|
||||
mongodb_knowledge_config = {
|
||||
"vector_store": {
|
||||
"provider": "mongodb",
|
||||
"config": {
|
||||
"connection_string": "mongodb://localhost:27017/", # Replace with your MongoDB connection string
|
||||
"database": "praisonai_knowledge",
|
||||
"collection": "knowledge_base",
|
||||
"use_vector_search": True # Enable Atlas Vector Search
|
||||
}
|
||||
},
|
||||
"embedder": {
|
||||
"provider": "openai",
|
||||
"config": {
|
||||
"model": "text-embedding-3-small",
|
||||
"api_key": os.getenv("OPENAI_API_KEY")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Create a knowledge agent with MongoDB knowledge store
|
||||
knowledge_agent = Agent(
|
||||
name="MongoDB Knowledge Agent",
|
||||
role="Knowledge Specialist",
|
||||
goal="Provide accurate information from MongoDB knowledge base",
|
||||
backstory="""You are an expert knowledge specialist who can access and
|
||||
retrieve information from a comprehensive MongoDB knowledge base. You excel
|
||||
at finding relevant information, synthesizing knowledge from multiple sources,
|
||||
and providing accurate, context-aware responses.""",
|
||||
knowledge=True,
|
||||
knowledge_config=mongodb_knowledge_config,
|
||||
memory=True,
|
||||
verbose=True,
|
||||
llm="gpt-4o-mini"
|
||||
)
|
||||
|
||||
# Create a research assistant agent
|
||||
research_agent = Agent(
|
||||
name="Research Assistant",
|
||||
role="Research Assistant",
|
||||
goal="Gather information and store it in the knowledge base",
|
||||
backstory="""You are a research assistant who specializes in gathering
|
||||
information from various sources and organizing it for storage in the
|
||||
knowledge base. You ensure information is accurate, well-structured,
|
||||
and properly categorized.""",
|
||||
memory=True,
|
||||
verbose=True,
|
||||
llm="gpt-4o-mini"
|
||||
)
|
||||
|
||||
# Create tasks for knowledge management
|
||||
knowledge_tasks = [
|
||||
Task(
|
||||
description="""Research and store information about MongoDB Atlas Vector Search:
|
||||
1. Gather comprehensive information about MongoDB Atlas Vector Search
|
||||
2. Include technical specifications, use cases, and best practices
|
||||
3. Store the information in the MongoDB knowledge base
|
||||
4. Organize information by categories (features, performance, integration)
|
||||
""",
|
||||
expected_output="MongoDB Atlas Vector Search information stored in knowledge base",
|
||||
agent=research_agent
|
||||
),
|
||||
Task(
|
||||
description="""Research and store information about AI agent frameworks:
|
||||
1. Research popular AI agent frameworks (LangChain, AutoGen, etc.)
|
||||
2. Compare their features, capabilities, and use cases
|
||||
3. Store comparative analysis in the knowledge base
|
||||
4. Include code examples and best practices
|
||||
""",
|
||||
expected_output="AI agent framework comparison stored in knowledge base",
|
||||
agent=research_agent
|
||||
),
|
||||
Task(
|
||||
description="""Query the knowledge base for MongoDB information:
|
||||
1. Search for information about MongoDB Atlas Vector Search
|
||||
2. Extract key features and capabilities
|
||||
3. Provide a comprehensive summary
|
||||
4. Include technical recommendations
|
||||
""",
|
||||
expected_output="Comprehensive MongoDB Atlas Vector Search summary from knowledge base",
|
||||
agent=knowledge_agent
|
||||
),
|
||||
Task(
|
||||
description="""Query the knowledge base for AI agent framework information:
|
||||
1. Search for information about AI agent frameworks
|
||||
2. Compare different frameworks based on stored knowledge
|
||||
3. Provide recommendations for different use cases
|
||||
4. Include best practices and examples
|
||||
""",
|
||||
expected_output="AI agent framework comparison and recommendations from knowledge base",
|
||||
agent=knowledge_agent
|
||||
)
|
||||
]
|
||||
|
||||
# Initialize the multi-agent system with MongoDB knowledge
|
||||
print("🚀 Starting MongoDB Knowledge Management System...")
|
||||
print("=" * 60)
|
||||
|
||||
knowledge_system = PraisonAIAgents(
|
||||
agents=[research_agent, knowledge_agent],
|
||||
tasks=knowledge_tasks,
|
||||
memory=True,
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Execute the knowledge management pipeline
|
||||
try:
|
||||
results = knowledge_system.start()
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("📊 Knowledge Management System Results:")
|
||||
print("=" * 60)
|
||||
|
||||
for i, result in enumerate(results, 1):
|
||||
print(f"\n{i}. Task Result:")
|
||||
print(f" Output: {result.raw[:200]}...")
|
||||
print(f" Agent: {result.agent}")
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("💾 MongoDB Knowledge Integration Complete!")
|
||||
print("=" * 60)
|
||||
|
||||
# Demonstrate direct knowledge access
|
||||
print("\n🔍 Demonstrating Direct Knowledge Access:")
|
||||
print("-" * 40)
|
||||
|
||||
# Access knowledge system directly
|
||||
from praisonaiagents.knowledge import Knowledge
|
||||
|
||||
knowledge_system = Knowledge(config=mongodb_knowledge_config)
|
||||
|
||||
# Store a sample document
|
||||
sample_doc = """
|
||||
MongoDB is a document-oriented database that provides high performance,
|
||||
high availability, and easy scalability. It works on the concept of
|
||||
collections and documents, using a flexible, JSON-like document model.
|
||||
"""
|
||||
|
||||
print("📄 Storing sample document...")
|
||||
knowledge_system.store(sample_doc, metadata={"category": "database", "type": "overview"})
|
||||
|
||||
# Search for stored knowledge
|
||||
print("\n🔍 Searching knowledge base...")
|
||||
results = knowledge_system.search("MongoDB document database", limit=3)
|
||||
|
||||
print(f"Found {len(results)} knowledge entries:")
|
||||
for result in results:
|
||||
print(f" - {result.get('memory', '')[:100]}...")
|
||||
print(f" Score: {result.get('score', 'N/A')}")
|
||||
|
||||
print("\n✅ MongoDB Knowledge Example Completed Successfully!")
|
||||
|
||||
except Exception as e:
|
||||
print(f"\n❌ Error during execution: {e}")
|
||||
print("Please check your MongoDB connection and API keys.")
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("MongoDB Knowledge Example for PraisonAI Agents")
|
||||
print("=" * 50)
|
||||
print("This example demonstrates MongoDB integration for knowledge management")
|
||||
print("Make sure you have:")
|
||||
print("1. MongoDB server running (local or Atlas)")
|
||||
print("2. OpenAI API key set in environment variables")
|
||||
print("3. MongoDB dependencies installed: pip install 'praisonaiagents[mongodb]'")
|
||||
print("=" * 50)
|
||||
|
||||
main()
|
||||
@@ -0,0 +1,154 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
MongoDB Memory Example for PraisonAI Agents
|
||||
|
||||
This example demonstrates how to use MongoDB as a memory provider for PraisonAI agents.
|
||||
MongoDB can be used as both a key-value store and a vector database for memory operations.
|
||||
|
||||
Prerequisites:
|
||||
- Install MongoDB dependencies: pip install 'praisonaiagents[mongodb]'
|
||||
- MongoDB server running (local or Atlas)
|
||||
- OpenAI API key for embeddings
|
||||
|
||||
Features demonstrated:
|
||||
- MongoDB as memory provider
|
||||
- Vector search with Atlas Vector Search
|
||||
- Quality scoring and filtering
|
||||
- User-specific memory storage
|
||||
- Persistent memory across sessions
|
||||
"""
|
||||
|
||||
import os
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
|
||||
# Ensure OpenAI API key is set
|
||||
if not os.environ.get("OPENAI_API_KEY"):
|
||||
raise ValueError("Please set the OPENAI_API_KEY environment variable")
|
||||
|
||||
def main():
|
||||
# MongoDB memory configuration
|
||||
mongodb_memory_config = {
|
||||
"provider": "mongodb",
|
||||
"config": {
|
||||
"connection_string": "mongodb://localhost:27017/", # Replace with your MongoDB connection string
|
||||
"database": "praisonai_memory",
|
||||
"use_vector_search": True, # Enable Atlas Vector Search (requires MongoDB Atlas)
|
||||
"max_pool_size": 50,
|
||||
"min_pool_size": 10,
|
||||
"server_selection_timeout": 5000
|
||||
}
|
||||
}
|
||||
|
||||
# Create a research agent with MongoDB memory
|
||||
research_agent = Agent(
|
||||
name="MongoDB Research Agent",
|
||||
role="Senior Research Specialist",
|
||||
goal="Research topics and maintain persistent memory using MongoDB",
|
||||
backstory="""You are an expert researcher who specializes in collecting,
|
||||
analyzing, and storing information using advanced MongoDB-based memory systems.
|
||||
You excel at maintaining context across multiple research sessions and can
|
||||
retrieve relevant information from your persistent memory store.""",
|
||||
memory=True,
|
||||
verbose=True,
|
||||
llm="gpt-4o-mini"
|
||||
)
|
||||
|
||||
# Create research tasks
|
||||
research_tasks = [
|
||||
Task(
|
||||
description="""Research the latest developments in AI/ML for 2024:
|
||||
1. Identify major AI breakthroughs and trends
|
||||
2. Analyze the impact on various industries
|
||||
3. Store key findings in MongoDB memory with quality scores
|
||||
4. Identify emerging technologies and their potential applications
|
||||
""",
|
||||
expected_output="Comprehensive AI/ML research report with key findings stored in MongoDB",
|
||||
agent=research_agent
|
||||
),
|
||||
Task(
|
||||
description="""Research MongoDB Atlas Vector Search capabilities:
|
||||
1. Explore vector search features and use cases
|
||||
2. Compare with other vector databases
|
||||
3. Analyze performance and scalability
|
||||
4. Store technical insights in MongoDB memory
|
||||
""",
|
||||
expected_output="Technical analysis of MongoDB Atlas Vector Search with stored insights",
|
||||
agent=research_agent
|
||||
),
|
||||
Task(
|
||||
description="""Research AI agent frameworks and tools:
|
||||
1. Compare popular AI agent frameworks
|
||||
2. Analyze their strengths and weaknesses
|
||||
3. Identify best practices for agent development
|
||||
4. Store comparative analysis in MongoDB memory
|
||||
""",
|
||||
expected_output="Comparative analysis of AI agent frameworks with stored insights",
|
||||
agent=research_agent
|
||||
)
|
||||
]
|
||||
|
||||
# Initialize the multi-agent system with MongoDB memory
|
||||
print("🚀 Starting MongoDB Memory Research System...")
|
||||
print("=" * 60)
|
||||
|
||||
research_system = PraisonAIAgents(
|
||||
agents=[research_agent],
|
||||
tasks=research_tasks,
|
||||
memory=True,
|
||||
memory_config=mongodb_memory_config,
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Execute the research pipeline
|
||||
try:
|
||||
results = research_system.start()
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("📊 Research System Results:")
|
||||
print("=" * 60)
|
||||
|
||||
for i, result in enumerate(results, 1):
|
||||
print(f"\n{i}. Task Result:")
|
||||
print(f" Output: {result.raw[:200]}...")
|
||||
print(f" Agent: {result.agent}")
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("💾 MongoDB Memory Integration Complete!")
|
||||
print("=" * 60)
|
||||
|
||||
# Demonstrate memory retrieval
|
||||
print("\n🔍 Demonstrating Memory Retrieval:")
|
||||
print("-" * 40)
|
||||
|
||||
# Access the memory system directly
|
||||
memory_system = research_system.memory
|
||||
|
||||
# Search for AI-related memories
|
||||
ai_memories = memory_system.search_long_term("AI machine learning", limit=3)
|
||||
print(f"Found {len(ai_memories)} AI-related memories:")
|
||||
for memory in ai_memories:
|
||||
print(f" - {memory.get('text', '')[:100]}...")
|
||||
|
||||
# Search for MongoDB-related memories
|
||||
mongo_memories = memory_system.search_long_term("MongoDB vector search", limit=3)
|
||||
print(f"\nFound {len(mongo_memories)} MongoDB-related memories:")
|
||||
for memory in mongo_memories:
|
||||
print(f" - {memory.get('text', '')[:100]}...")
|
||||
|
||||
print("\n✅ MongoDB Memory Example Completed Successfully!")
|
||||
|
||||
except Exception as e:
|
||||
print(f"\n❌ Error during execution: {e}")
|
||||
print("Please check your MongoDB connection and API keys.")
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("MongoDB Memory Example for PraisonAI Agents")
|
||||
print("=" * 50)
|
||||
print("This example demonstrates MongoDB integration for persistent memory")
|
||||
print("Make sure you have:")
|
||||
print("1. MongoDB server running (local or Atlas)")
|
||||
print("2. OpenAI API key set in environment variables")
|
||||
print("3. MongoDB dependencies installed: pip install 'praisonaiagents[mongodb]'")
|
||||
print("=" * 50)
|
||||
|
||||
main()
|
||||
Loaded 100 of 186 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user