mirror of
https://github.com/MervinPraison/PraisonAI.git
synced 2026-11-07 17:33:33 -10:00
Compare commits
No files matched your search
@@ -1,4 +1,4 @@
|
||||
name: Auto Issue Comment
|
||||
name: Auto Issue Comment with PR Creation
|
||||
|
||||
on:
|
||||
issues:
|
||||
@@ -9,6 +9,9 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
issues: write
|
||||
contents: write
|
||||
pull-requests: write
|
||||
actions: read
|
||||
steps:
|
||||
- name: Add automated comment
|
||||
uses: actions/github-script@v7
|
||||
@@ -19,5 +22,5 @@ jobs:
|
||||
issue_number: context.issue.number,
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
body: '@claude review this issue and do a detailed analysis and fix this if the existing code doesn\'t have the solution implemented. Making sure it has backward compatibility, no existing features removed. After making those changes, again review the applied changes. Use @web to search if you dont know any information or to find the latest documentation or to find the latest version. Run the code if you think you need to run it to test it. Minimal code change to start with if required any changes.'
|
||||
})
|
||||
body: '@claude review this issue and do a detailed analysis and fix this if the existing code doesn\'t have the solution implemented. Making sure it has backward compatibility, no existing features removed. After making those changes, again review the applied changes. Use @web to search if you dont know any information or to find the latest documentation or to find the latest version. Run the code if you think you need to run it to test it. Minimal code change to start with if required any changes. **Please create a PR using gh tool with your changes**.'
|
||||
})
|
||||
@@ -11,6 +11,7 @@ on:
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
name: Claude Code
|
||||
name: Claude Assistant
|
||||
|
||||
on:
|
||||
issue_comment:
|
||||
@@ -6,41 +6,60 @@ on:
|
||||
pull_request_review_comment:
|
||||
types: [created]
|
||||
issues:
|
||||
types: [opened, assigned]
|
||||
types: [opened, assigned, labeled]
|
||||
pull_request_review:
|
||||
types: [submitted]
|
||||
|
||||
jobs:
|
||||
claude:
|
||||
claude-response:
|
||||
# Prevent bots from triggering this action
|
||||
if: |
|
||||
(github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) ||
|
||||
(github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) ||
|
||||
(github.event_name == 'pull_request_review' && contains(github.event.review.body, '@claude')) ||
|
||||
(github.event_name == 'issues' && (contains(github.event.issue.body, '@claude') || contains(github.event.issue.title, '@claude')))
|
||||
github.actor != 'dependabot[bot]' &&
|
||||
github.actor != 'github-actions[bot]' &&
|
||||
github.actor != 'cursor[bot]' &&
|
||||
!contains(github.actor, '[bot]') &&
|
||||
github.actor != 'renovate[bot]'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: read
|
||||
issues: read
|
||||
id-token: write
|
||||
contents: write
|
||||
pull-requests: write
|
||||
issues: write
|
||||
actions: read
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 1
|
||||
|
||||
- name: Run Claude Code (OAuth)
|
||||
id: claude
|
||||
uses: grll/claude-code-action@beta
|
||||
fetch-depth: 0
|
||||
|
||||
- uses: anthropics/claude-code-action@beta
|
||||
with:
|
||||
use_oauth: true
|
||||
claude_access_token: ${{ secrets.CLAUDE_ACCESS_TOKEN }}
|
||||
claude_refresh_token: ${{ secrets.CLAUDE_REFRESH_TOKEN }}
|
||||
claude_expires_at: ${{ secrets.CLAUDE_EXPIRES_AT }}
|
||||
claude_code_oauth_token: ${{ secrets.CLAUDE_ACCESS_TOKEN }}
|
||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
trigger_phrase: "@claude"
|
||||
allowed_tools: |
|
||||
Bash(git:*)
|
||||
Bash(python:*)
|
||||
Bash(pip:*)
|
||||
Bash(conda:*)
|
||||
Bash(pytest:*)
|
||||
Bash(gh:*)
|
||||
Bash(python -m pytest:*)
|
||||
Bash(python -m pip:*)
|
||||
Bash(poetry:*)
|
||||
View
|
||||
GlobTool
|
||||
GrepTool
|
||||
BatchTool
|
||||
Edit
|
||||
Replace
|
||||
mcp__github__get_issue
|
||||
mcp__github__get_issue_comments
|
||||
mcp__github__update_issue
|
||||
timeout_minutes: 30
|
||||
|
||||
post-review-comment:
|
||||
needs: claude
|
||||
if: success() && needs.claude.result == 'success'
|
||||
needs: claude-response
|
||||
if: success() && needs.claude-response.result == 'success'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -53,7 +72,7 @@ jobs:
|
||||
with:
|
||||
github-token: ${{ secrets.GH_TOKEN }}
|
||||
script: |
|
||||
const reviewText = '@claude review if the changes made are as per the requirements';
|
||||
const reviewText = '@claude review if the changes made in the above branch are as per the requirements and make changes to the above branch if issues still exist.';
|
||||
let comments = [];
|
||||
let issueNumber;
|
||||
|
||||
@@ -75,22 +94,34 @@ jobs:
|
||||
issue_number: issueNumber
|
||||
});
|
||||
|
||||
const existingComment = comments.data.find(comment =>
|
||||
// Look for Claude's completed review comments
|
||||
const claudeReviewComments = comments.data.filter(comment =>
|
||||
(comment.user.login === 'claude[bot]' || comment.body.includes('✅') || comment.body.includes('## Summary')) &&
|
||||
!comment.body.includes('⏳') &&
|
||||
!comment.body.includes('🔄') &&
|
||||
!comment.body.includes('Loading...')
|
||||
);
|
||||
|
||||
// Check if our review request comment already exists
|
||||
const existingReviewRequest = comments.data.find(comment =>
|
||||
comment.body.includes(reviewText)
|
||||
);
|
||||
|
||||
const shouldPost = !existingComment;
|
||||
// Post if Claude has completed a review AND we haven't posted the review request yet
|
||||
const shouldPost = claudeReviewComments.length > 0 && !existingReviewRequest;
|
||||
core.setOutput('should-post', shouldPost);
|
||||
console.log(`Claude review completed: ${claudeReviewComments.length > 0}`);
|
||||
console.log(`Review request exists: ${!!existingReviewRequest}`);
|
||||
console.log(`Should post comment: ${shouldPost}`);
|
||||
|
||||
} catch (error) {
|
||||
console.log('Error checking comments:', error);
|
||||
core.setOutput('should-post', true); // If we can't check, proceed with posting
|
||||
core.setOutput('should-post', false); // If we can't check, don't post
|
||||
}
|
||||
|
||||
- name: Wait 20 seconds before posting comment
|
||||
- name: Wait 30 seconds before posting comment
|
||||
if: steps.check-comment.outputs.should-post == 'true'
|
||||
run: sleep 20
|
||||
run: sleep 30
|
||||
|
||||
- name: Post review comment
|
||||
if: steps.check-comment.outputs.should-post == 'true'
|
||||
@@ -99,23 +130,32 @@ jobs:
|
||||
github-token: ${{ secrets.GH_TOKEN }}
|
||||
script: |
|
||||
let issueNumber;
|
||||
let isPR = false;
|
||||
|
||||
// Determine issue/PR number based on event type
|
||||
// Determine issue/PR number and type based on event type
|
||||
if (context.eventName === 'pull_request_review_comment' || context.eventName === 'pull_request_review') {
|
||||
issueNumber = context.payload.pull_request?.number || context.issue.number;
|
||||
isPR = true;
|
||||
} else if (context.eventName === 'issue_comment' && context.payload.issue.pull_request) {
|
||||
// This is a comment on a PR (not an issue)
|
||||
issueNumber = context.payload.issue.number;
|
||||
isPR = true;
|
||||
} else {
|
||||
// This is a regular issue
|
||||
// This is a regular issue - don't post review comment
|
||||
issueNumber = context.issue.number;
|
||||
isPR = false;
|
||||
}
|
||||
|
||||
console.log(`Posting review comment on issue/PR #${issueNumber}`);
|
||||
|
||||
await github.rest.issues.createComment({
|
||||
issue_number: issueNumber,
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
body: '@claude review if the changes made are as per the requirements'
|
||||
});
|
||||
// Only post review comment on PRs, not regular issues
|
||||
if (isPR) {
|
||||
console.log(`Posting review comment on PR #${issueNumber}`);
|
||||
|
||||
await github.rest.issues.createComment({
|
||||
issue_number: issueNumber,
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
body: '@claude review if the changes made in the above branch are as per the requirements and make changes to the above branch if issues still exist.'
|
||||
});
|
||||
} else {
|
||||
console.log(`Skipping review comment for regular issue #${issueNumber}`);
|
||||
}
|
||||
@@ -10,6 +10,7 @@ jobs:
|
||||
test:
|
||||
name: Run tests and collect coverage
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
|
||||
@@ -40,5 +40,6 @@ jobs:
|
||||
uses: docker/build-push-action@v2
|
||||
with:
|
||||
context: .
|
||||
file: ./docker/Dockerfile
|
||||
push: true
|
||||
tags: ghcr.io/mervinpraison/praisonai:latest
|
||||
@@ -1,11 +1,18 @@
|
||||
name: Gemini Automated Issue Triage
|
||||
|
||||
on:
|
||||
issues:
|
||||
types: [opened, reopened]
|
||||
issue_comment:
|
||||
types: [created]
|
||||
|
||||
jobs:
|
||||
triage-issue:
|
||||
if: >
|
||||
github.event_name == 'issue_comment' &&
|
||||
!github.event.issue.pull_request &&
|
||||
contains(github.event.comment.body, '@gemini triage') &&
|
||||
(github.event.comment.author_association == 'OWNER' ||
|
||||
github.event.comment.author_association == 'MEMBER' ||
|
||||
github.event.comment.author_association == 'COLLABORATOR')
|
||||
timeout-minutes: 5
|
||||
permissions:
|
||||
issues: write
|
||||
|
||||
@@ -2,8 +2,6 @@ name: Gemini Issue Review
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
issues:
|
||||
types: [opened, edited]
|
||||
issue_comment:
|
||||
types: [created]
|
||||
|
||||
@@ -16,10 +14,10 @@ jobs:
|
||||
review-issue:
|
||||
if: >
|
||||
github.event_name == 'workflow_dispatch' ||
|
||||
github.event_name == 'issues' ||
|
||||
(github.event_name == 'issue_comment' &&
|
||||
!github.event.issue.pull_request &&
|
||||
contains(github.event.comment.body, '@gemini') &&
|
||||
!contains(github.event.comment.body, '@gemini triage') &&
|
||||
(github.event.comment.author_association == 'OWNER' ||
|
||||
github.event.comment.author_association == 'MEMBER' ||
|
||||
github.event.comment.author_association == 'COLLABORATOR'))
|
||||
|
||||
@@ -35,11 +35,20 @@ jobs:
|
||||
app-id: ${{ secrets.APP_ID }}
|
||||
private-key: ${{ secrets.PRIVATE_KEY }}
|
||||
|
||||
- name: Determine checkout ref
|
||||
id: checkout_ref
|
||||
run: |
|
||||
if [ "${{ github.event_name }}" = "issue_comment" ]; then
|
||||
echo "ref=refs/pull/${{ github.event.issue.number }}/head" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "ref=${{ github.event.pull_request.head.sha }}" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Checkout PR code
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
token: ${{ steps.generate_token.outputs.token }}
|
||||
ref: ${{ github.event.pull_request.head.sha }}
|
||||
ref: ${{ steps.checkout_ref.outputs.ref }}
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Get PR details
|
||||
@@ -96,12 +105,19 @@ jobs:
|
||||
"run_shell_command(gh pr view)",
|
||||
"run_shell_command(gh pr diff)",
|
||||
"run_shell_command(gh pr comment)",
|
||||
"run_shell_command(gh pr list)",
|
||||
"run_shell_command(cat)",
|
||||
"run_shell_command(head)",
|
||||
"run_shell_command(tail)",
|
||||
"run_shell_command(grep)",
|
||||
"run_shell_command(find)",
|
||||
"run_shell_command(git)",
|
||||
"run_shell_command(git checkout)",
|
||||
"run_shell_command(git add)",
|
||||
"run_shell_command(git commit)",
|
||||
"run_shell_command(git push)",
|
||||
"run_shell_command(git status)",
|
||||
"run_shell_command(git branch)",
|
||||
"run_shell_command(git fetch)",
|
||||
"list_directory",
|
||||
"read_file",
|
||||
"read_many_files",
|
||||
@@ -120,25 +136,47 @@ jobs:
|
||||
"sandbox": false
|
||||
}
|
||||
prompt: |
|
||||
You are an expert code reviewer. You have access to shell commands to gather PR information and perform the review.
|
||||
You are an expert code reviewer and AI assistant for Pull Requests. You can review code AND make modifications to improve the PR.
|
||||
|
||||
IMPORTANT: Use the available shell commands to gather information. Do not ask for information to be provided.
|
||||
**PR Details:**
|
||||
- PR Number: #$PR_NUMBER
|
||||
- Repository: $REPOSITORY
|
||||
- Additional Instructions: $ADDITIONAL_INSTRUCTIONS
|
||||
|
||||
Start by running these commands to gather the required data:
|
||||
1. Run: echo "$PR_DATA" to get PR details (JSON format)
|
||||
2. Run: echo "$CHANGED_FILES" to get the list of changed files
|
||||
3. Run: echo "$PR_NUMBER" to get the PR number
|
||||
4. Run: echo "$ADDITIONAL_INSTRUCTIONS" to see any specific review instructions from the user
|
||||
5. Run: gh pr diff $PR_NUMBER to see the full diff
|
||||
6. For any specific files, use: cat filename, head -50 filename, or tail -50 filename
|
||||
|
||||
Additional Review Instructions:
|
||||
If ADDITIONAL_INSTRUCTIONS contains text, prioritize those specific areas or focus points in your review.
|
||||
Common instruction examples: "focus on security", "check performance", "review error handling", "check for breaking changes"
|
||||
|
||||
Once you have the information, provide a comprehensive code review by:
|
||||
1. Writing your review to a file: write_file("review.md", "<your detailed review feedback here>")
|
||||
2. Posting the review: gh pr comment $PR_NUMBER --body-file review.md --repo $REPOSITORY
|
||||
**CRITICAL: When making code modifications, follow this EXACT workflow:**
|
||||
|
||||
**STEP 1: Analyze the PR**
|
||||
- Use: `echo "$PR_DATA"` to get PR details (JSON format)
|
||||
- Use: `echo "$CHANGED_FILES"` to get changed files list
|
||||
- Use: `gh pr diff ${PR_NUMBER}` to see the full diff
|
||||
- Use: `gh pr view ${PR_NUMBER} --json title,body,headRefName` to get PR info
|
||||
- Analyze the code changes thoroughly
|
||||
|
||||
**STEP 2: If Code Improvements Are Needed**
|
||||
**IMPORTANT:** DO NOT create a new branch! Work on the EXISTING PR branch.
|
||||
- Use: `git fetch origin` to get latest changes
|
||||
- Get PR branch name: `gh pr view ${PR_NUMBER} --json headRefName`
|
||||
- Switch to PR branch: `git checkout BRANCH_NAME` (use actual branch name from PR)
|
||||
- Use: `git pull origin BRANCH_NAME` to get latest PR changes
|
||||
|
||||
**STEP 3: Make Code Modifications**
|
||||
- Use `read_file` to examine existing code
|
||||
- Use `write_file` or `replace` to make improvements
|
||||
- Use `search_file_content` to find related code
|
||||
- Make focused, targeted improvements to the PR
|
||||
|
||||
**STEP 4: Test Changes (if applicable)**
|
||||
- Run relevant tests if test files exist
|
||||
- Use `run_shell_command` to execute test commands
|
||||
|
||||
**STEP 5: Commit and Push Changes to EXISTING PR Branch**
|
||||
- Use: `git add .` (or specific files)
|
||||
- Use: `git commit -m "Gemini: [PR #${PR_NUMBER}] Brief description of improvements"`
|
||||
- Use: `git push origin BRANCH_NAME` (push to EXISTING PR branch)
|
||||
|
||||
**STEP 6: Review and Comment on PR**
|
||||
Write comprehensive review and post comment with your analysis and any improvements made.
|
||||
Use: `gh pr comment ${PR_NUMBER} -b "MESSAGE"`
|
||||
|
||||
Review Guidelines:
|
||||
- Focus on code quality, security, performance, and maintainability
|
||||
|
||||
@@ -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
|
||||
|
||||
+3
-1
@@ -75,4 +75,6 @@ agents/praisonaiagents/praisonaiagents.egg-info
|
||||
# Local Netlify folder
|
||||
.netlify
|
||||
.qodo
|
||||
CopilotKit*
|
||||
CopilotKit*
|
||||
.gemini
|
||||
issue_details.json
|
||||
@@ -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.53" \
|
||||
"praisonai>=2.2.72" \
|
||||
"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.53" \
|
||||
"praisonai>=2.2.72" \
|
||||
"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.53" \
|
||||
"praisonai>=2.2.72" \
|
||||
"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.53" \
|
||||
"praisonai>=2.2.72" \
|
||||
"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.53`
|
||||
- PraisonAI: `>=2.2.72`
|
||||
- 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.53" "praisonaiagents==0.0.92"
|
||||
RUN pip install "praisonai==2.2.72" "praisonaiagents==0.0.92"
|
||||
```
|
||||
|
||||
## 🌐 Production Deployment
|
||||
|
||||
@@ -1,70 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Example demonstrating validation feedback in workflow retry logic"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src/praisonai-agents'))
|
||||
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
|
||||
# This example shows how validation feedback is now passed to retry tasks
|
||||
|
||||
print("""
|
||||
==========================================
|
||||
Validation Feedback Feature Demonstration
|
||||
==========================================
|
||||
|
||||
This example shows how the workflow retry logic now includes validation feedback.
|
||||
|
||||
Before: When validation failed, the retry task would start fresh without knowing why it failed.
|
||||
After: The retry task receives detailed feedback about what went wrong.
|
||||
|
||||
Example Scenario:
|
||||
1. A data collection task produces output
|
||||
2. A validation task checks if the output meets criteria
|
||||
3. If validation fails, the data collection task is retried WITH feedback about why it failed
|
||||
|
||||
The retry task will see:
|
||||
- Previous attempt failed validation with reason: invalid
|
||||
- Validation feedback: [specific reason for failure]
|
||||
- Rejected output: [the output that failed validation]
|
||||
- Please try again with a different approach based on this feedback.
|
||||
|
||||
This enables context-dependent tasks to improve on retry instead of repeating the same mistakes.
|
||||
==========================================
|
||||
|
||||
Implementation Details:
|
||||
1. Added 'validation_feedback' field to Task class
|
||||
2. When routing from decision task to retry task, capture validation details
|
||||
3. Include feedback in task context when building retry task description
|
||||
4. Clear feedback after use to prevent persistence
|
||||
|
||||
The solution is minimal and backward compatible - existing workflows continue to work unchanged.
|
||||
""")
|
||||
|
||||
# Example workflow structure (without actual execution)
|
||||
print("\nExample Workflow Structure:")
|
||||
print("""
|
||||
collect_task = Task(
|
||||
name="collect_data",
|
||||
description="Collect data from source",
|
||||
is_start=True,
|
||||
next_tasks=["validate_data"]
|
||||
)
|
||||
|
||||
validate_task = Task(
|
||||
name="validate_data",
|
||||
task_type="decision",
|
||||
description="Validate if data meets criteria",
|
||||
condition={
|
||||
"valid": [], # End workflow
|
||||
"invalid": ["collect_data"] # Retry with feedback
|
||||
}
|
||||
)
|
||||
|
||||
# When validation returns "invalid":
|
||||
# 1. The workflow captures the validation output
|
||||
# 2. Stores it in collect_task.validation_feedback
|
||||
# 3. On retry, collect_data task sees the feedback in its context
|
||||
# 4. Agent can adjust approach based on specific failure reason
|
||||
""")
|
||||
@@ -0,0 +1,293 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "ZOWgx2fYqW8T"
|
||||
},
|
||||
"source": [
|
||||
"# GitHub Repository Insights with PraisonAIAgents"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "XgJdLRiIqZ2L"
|
||||
},
|
||||
"source": [
|
||||
"This notebook demonstrates how to explore and analyze GitHub repositories using PraisonAIAgents in Google Colab. You can query repository issues, pull requests, and activity patterns with natural language, leveraging the power of agentic tools—all without leaving your notebook."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "Y_koMT6qzxne"
|
||||
},
|
||||
"source": [
|
||||
"[](https://colab.research.google.com/github/Dhivya-Bharathy/PraisonAI/blob/main/examples/cookbooks/Programming_Code_Analysis_Agents/GitHub_Repository_Insights.ipynb)\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "2ey7zWAJrIPx"
|
||||
},
|
||||
"source": [
|
||||
"# Dependencies"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 24,
|
||||
"metadata": {
|
||||
"id": "_xFH-iLTxzd8"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"!pip install praisonaiagents openai requests --quiet"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "Kzty0zxzsbZ_"
|
||||
},
|
||||
"source": [
|
||||
"# Set Up Key"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 25,
|
||||
"metadata": {
|
||||
"id": "HCVP5fmvx2hH"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import os\n",
|
||||
"\n",
|
||||
"# Set your GitHub token here\n",
|
||||
"GITHUB_TOKEN = \"your-github-token\" # <-- Replace with your actual token\n",
|
||||
"\n",
|
||||
"# Set your OpenAI API key here (required by PraisonAIAgents, even if not used for LLM)\n",
|
||||
"OPENAI_API_KEY = \"your-openai-api-key\" # <-- Replace with your actual OpenAI API key\n",
|
||||
"\n",
|
||||
"# Set environment variable for OpenAI\n",
|
||||
"os.environ[\"OPENAI_API_KEY\"] = OPENAI_API_KEY"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "10BTLbF4s_f-"
|
||||
},
|
||||
"source": [
|
||||
"# Import Libraries"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 26,
|
||||
"metadata": {
|
||||
"id": "_sLahvfXyEb0"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from praisonaiagents import Agent\n",
|
||||
"import requests\n",
|
||||
"from IPython.display import display, Markdown"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "GRftdghxtUDs"
|
||||
},
|
||||
"source": [
|
||||
"# Custom Tool"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 27,
|
||||
"metadata": {
|
||||
"id": "nT11EFNNyIHl"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def github_query_tool(query: str, repo: str, github_token: str) -> str:\n",
|
||||
" \"\"\"\n",
|
||||
" Custom tool to query GitHub repository data using the GitHub API.\n",
|
||||
" Supports basic queries for issues, pull requests, and repository info.\n",
|
||||
" \"\"\"\n",
|
||||
" headers = {\n",
|
||||
" \"Authorization\": f\"token {github_token}\",\n",
|
||||
" \"Accept\": \"application/vnd.github.v3+json\"\n",
|
||||
" }\n",
|
||||
" base_url = f\"https://api.github.com/repos/{repo}\"\n",
|
||||
" result = \"\"\n",
|
||||
"\n",
|
||||
" if \"issue\" in query.lower():\n",
|
||||
" url = f\"{base_url}/issues\"\n",
|
||||
" response = requests.get(url, headers=headers)\n",
|
||||
" if response.ok:\n",
|
||||
" issues = response.json()\n",
|
||||
" result = f\"Found {len(issues)} issues in {repo}.\\n\"\n",
|
||||
" for issue in issues[:5]:\n",
|
||||
" result += f\"- #{issue['number']}: {issue['title']} (State: {issue['state']})\\n\"\n",
|
||||
" else:\n",
|
||||
" result = f\"Failed to fetch issues: {response.text}\"\n",
|
||||
"\n",
|
||||
" elif \"pull request\" in query.lower() or \"pr\" in query.lower():\n",
|
||||
" url = f\"{base_url}/pulls\"\n",
|
||||
" response = requests.get(url, headers=headers)\n",
|
||||
" if response.ok:\n",
|
||||
" pulls = response.json()\n",
|
||||
" result = f\"Found {len(pulls)} pull requests in {repo}.\\n\"\n",
|
||||
" for pr in pulls[:5]:\n",
|
||||
" result += f\"- #{pr['number']}: {pr['title']} (State: {pr['state']})\\n\"\n",
|
||||
" else:\n",
|
||||
" result = f\"Failed to fetch pull requests: {response.text}\"\n",
|
||||
"\n",
|
||||
" elif \"activity\" in query.lower() or \"stats\" in query.lower():\n",
|
||||
" url = f\"{base_url}/stats/contributors\"\n",
|
||||
" response = requests.get(url, headers=headers)\n",
|
||||
" if response.ok:\n",
|
||||
" stats = response.json()\n",
|
||||
" result = f\"Repository activity for {repo}:\\n\"\n",
|
||||
" for contributor in stats[:5]:\n",
|
||||
" result += f\"- {contributor['author']['login']}: {contributor['total']} commits\\n\"\n",
|
||||
" else:\n",
|
||||
" result = f\"Failed to fetch activity stats: {response.text}\"\n",
|
||||
"\n",
|
||||
" else:\n",
|
||||
" # Default: basic repo info\n",
|
||||
" response = requests.get(base_url, headers=headers)\n",
|
||||
" if response.ok:\n",
|
||||
" info = response.json()\n",
|
||||
" result = (\n",
|
||||
" f\"Repository: {info['full_name']}\\n\"\n",
|
||||
" f\"Description: {info.get('description', 'No description')}\\n\"\n",
|
||||
" f\"Stars: {info['stargazers_count']}\\n\"\n",
|
||||
" f\"Forks: {info['forks_count']}\\n\"\n",
|
||||
" f\"Open Issues: {info['open_issues_count']}\\n\"\n",
|
||||
" )\n",
|
||||
" else:\n",
|
||||
" result = f\"Failed to fetch repository info: {response.text}\"\n",
|
||||
"\n",
|
||||
" return result"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "mAFg5SW-tacD"
|
||||
},
|
||||
"source": [
|
||||
"# Register Tool and Create Agent"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 28,
|
||||
"metadata": {
|
||||
"id": "x_MmUc_AyMaB"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def github_tool_wrapper(inputs):\n",
|
||||
" query = inputs.get(\"query\", \"\")\n",
|
||||
" repo = inputs.get(\"repo\", \"\")\n",
|
||||
" github_token = inputs.get(\"github_token\", \"\")\n",
|
||||
" return github_query_tool(query, repo, github_token)\n",
|
||||
"\n",
|
||||
"agent = Agent(\n",
|
||||
" instructions=\"\"\"\n",
|
||||
" You are a GitHub assistant. Help users explore repositories and their activity.\n",
|
||||
" - Provide organized, concise insights about the repository.\n",
|
||||
" - Focus on facts and data from the GitHub API.\n",
|
||||
" - Use markdown formatting for better readability.\n",
|
||||
" - Present numerical data in tables when appropriate.\n",
|
||||
" - Include links to relevant GitHub pages when helpful.\n",
|
||||
" \"\"\",\n",
|
||||
" tools={\n",
|
||||
" \"github_query_tool\": github_tool_wrapper\n",
|
||||
" }\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "lPstz7bbtr0k"
|
||||
},
|
||||
"source": [
|
||||
"# User Input and Run Agent"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 30,
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"base_uri": "https://localhost:8080/",
|
||||
"height": 118
|
||||
},
|
||||
"id": "MymtRmlnyQqd",
|
||||
"outputId": "33a23810-4a67-4615-f9e9-146b3030fcbf"
|
||||
},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Enter the GitHub repository (owner/repo): Dhivya-Bharathy/PraisonAI\n",
|
||||
"Enter your question (e.g., Show me open issues): Show me open issues\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"data": {
|
||||
"text/markdown": [
|
||||
"### Results\n",
|
||||
"Found 0 issues in Dhivya-Bharathy/PraisonAI.\n"
|
||||
],
|
||||
"text/plain": [
|
||||
"<IPython.core.display.Markdown object>"
|
||||
]
|
||||
},
|
||||
"metadata": {},
|
||||
"output_type": "display_data"
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"# User input\n",
|
||||
"repo = input(\"Enter the GitHub repository (owner/repo): \")\n",
|
||||
"query = input(\"Enter your question (e.g., Show me open issues): \")\n",
|
||||
"\n",
|
||||
"# Call the tool directly (since agent.chat expects an LLM, but we want tool output)\n",
|
||||
"response = agent.execute_tool(\"github_query_tool\", {\n",
|
||||
" \"query\": query,\n",
|
||||
" \"repo\": repo,\n",
|
||||
" \"github_token\": GITHUB_TOKEN\n",
|
||||
"})\n",
|
||||
"\n",
|
||||
"# Display the result\n",
|
||||
"display(Markdown(f\"### Results\\n{response}\"))"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"provenance": []
|
||||
},
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"name": "python"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 0
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "vmQmHoy-5cAh"
|
||||
},
|
||||
"source": [
|
||||
"# Notion Workspace Assistant with PraisonAIAgents"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "WOow52NM5dmh"
|
||||
},
|
||||
"source": [
|
||||
"This notebook demonstrates how to interact with your Notion workspace using PraisonAIAgents in Google Colab. You can read, search, and update Notion pages with natural language queries, leveraging agentic tools for seamless document management—all within a notebook environment."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "TlnFAv9P_lGL"
|
||||
},
|
||||
"source": [
|
||||
"[](https://colab.research.google.com/github/Dhivya-Bharathy/PraisonAI/blob/main/examples/cookbooks/Programming_Code_Analysis_Agents/Notion_Workspace_Assistant.ipynb)\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "zMn7hUGZ5hn5"
|
||||
},
|
||||
"source": [
|
||||
"# Dependencies"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "U6X3lKAu6iU3"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"!pip install praisonaiagents openai requests --quiet"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "4_96-D7z6lrC"
|
||||
},
|
||||
"source": [
|
||||
"# Set Up Key"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 2,
|
||||
"metadata": {
|
||||
"id": "kltUFVIW6rEO"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import os\n",
|
||||
"\n",
|
||||
"# Set your Notion and OpenAI API keys here\n",
|
||||
"NOTION_API_KEY = \"ntn_..\" # <-- Replace with your actual Notion integration token\n",
|
||||
"OPENAI_API_KEY = \"sk-proj-_..\" # <-- Replace with your actual OpenAI API key\n",
|
||||
"\n",
|
||||
"# Set environment variables for downstream libraries\n",
|
||||
"os.environ[\"NOTION_API_KEY\"] = NOTION_API_KEY\n",
|
||||
"os.environ[\"OPENAI_API_KEY\"] = OPENAI_API_KEY"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "FOLTBEXu635I"
|
||||
},
|
||||
"source": [
|
||||
"# Tools"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 3,
|
||||
"metadata": {
|
||||
"id": "fLWxSASM5jlU"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from praisonaiagents import Agent\n",
|
||||
"import requests\n",
|
||||
"from IPython.display import display, Markdown"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "KN_Sxha37EQ0"
|
||||
},
|
||||
"source": [
|
||||
"# Custom Tool"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 4,
|
||||
"metadata": {
|
||||
"id": "WWxcfO9L7Fsu"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def notion_read_page_tool(page_id: str, notion_token: str) -> str:\n",
|
||||
" \"\"\"\n",
|
||||
" Custom tool to read the content of a Notion page using the Notion API.\n",
|
||||
" \"\"\"\n",
|
||||
" url = f\"https://api.notion.com/v1/blocks/{page_id}/children\"\n",
|
||||
" headers = {\n",
|
||||
" \"Authorization\": f\"Bearer {notion_token}\",\n",
|
||||
" \"Notion-Version\": \"2022-06-28\"\n",
|
||||
" }\n",
|
||||
" response = requests.get(url, headers=headers)\n",
|
||||
" if response.ok:\n",
|
||||
" data = response.json()\n",
|
||||
" blocks = data.get(\"results\", [])\n",
|
||||
" content = []\n",
|
||||
" for block in blocks:\n",
|
||||
" block_type = block.get(\"type\", \"\")\n",
|
||||
" text = \"\"\n",
|
||||
" if block_type == \"paragraph\":\n",
|
||||
" text = block.get(\"paragraph\", {}).get(\"text\", [])\n",
|
||||
" if text:\n",
|
||||
" text = text[0].get(\"plain_text\", \"\")\n",
|
||||
" elif block_type == \"heading_1\":\n",
|
||||
" text = block.get(\"heading_1\", {}).get(\"text\", [])\n",
|
||||
" if text:\n",
|
||||
" text = \"# \" + text[0].get(\"plain_text\", \"\")\n",
|
||||
" elif block_type == \"heading_2\":\n",
|
||||
" text = block.get(\"heading_2\", {}).get(\"text\", [])\n",
|
||||
" if text:\n",
|
||||
" text = \"## \" + text[0].get(\"plain_text\", \"\")\n",
|
||||
" elif block_type == \"heading_3\":\n",
|
||||
" text = block.get(\"heading_3\", {}).get(\"text\", [])\n",
|
||||
" if text:\n",
|
||||
" text = \"### \" + text[0].get(\"plain_text\", \"\")\n",
|
||||
" if text:\n",
|
||||
" content.append(text)\n",
|
||||
" return \"\\n\".join(content) if content else \"No readable content found on this page.\"\n",
|
||||
" else:\n",
|
||||
" return f\"Failed to fetch page content: {response.text}\""
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "ebuhw9z27Nae"
|
||||
},
|
||||
"source": [
|
||||
"# YAML Prompt"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 5,
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"base_uri": "https://localhost:8080/"
|
||||
},
|
||||
"id": "eMjDDjzO7Pf3",
|
||||
"outputId": "b935f96d-f147-44de-80ea-7f75d23f9e7b"
|
||||
},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"\n",
|
||||
"agent_instructions: |\n",
|
||||
" You are a Notion workspace assistant. Help users read and manage their Notion pages.\n",
|
||||
" - Provide clear, organized summaries of page content.\n",
|
||||
" - Use the Notion API to fetch and display information.\n",
|
||||
" - If a page cannot be read, explain the issue clearly.\n",
|
||||
"\n",
|
||||
"tools:\n",
|
||||
" - name: notion_read_page_tool\n",
|
||||
" description: >\n",
|
||||
" Reads the content of a Notion page using its page ID and the user's Notion integration token.\n",
|
||||
" parameters:\n",
|
||||
" - name: page_id\n",
|
||||
" type: string\n",
|
||||
" description: The Notion page ID to read.\n",
|
||||
" - name: notion_token\n",
|
||||
" type: string\n",
|
||||
" description: The user's Notion integration token.\n",
|
||||
"\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"yaml_prompt = \"\"\"\n",
|
||||
"agent_instructions: |\n",
|
||||
" You are a Notion workspace assistant. Help users read and manage their Notion pages.\n",
|
||||
" - Provide clear, organized summaries of page content.\n",
|
||||
" - Use the Notion API to fetch and display information.\n",
|
||||
" - If a page cannot be read, explain the issue clearly.\n",
|
||||
"\n",
|
||||
"tools:\n",
|
||||
" - name: notion_read_page_tool\n",
|
||||
" description: >\n",
|
||||
" Reads the content of a Notion page using its page ID and the user's Notion integration token.\n",
|
||||
" parameters:\n",
|
||||
" - name: page_id\n",
|
||||
" type: string\n",
|
||||
" description: The Notion page ID to read.\n",
|
||||
" - name: notion_token\n",
|
||||
" type: string\n",
|
||||
" description: The user's Notion integration token.\n",
|
||||
"\"\"\"\n",
|
||||
"print(yaml_prompt)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "1ozm6Z467WQK"
|
||||
},
|
||||
"source": [
|
||||
"# Main"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 15,
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"base_uri": "https://localhost:8080/",
|
||||
"height": 83
|
||||
},
|
||||
"id": "eNg-jwpx7X5s",
|
||||
"outputId": "4440b52a-46b3-4683-9183-13cd21596e25"
|
||||
},
|
||||
"outputs": [
|
||||
{
|
||||
"data": {
|
||||
"text/markdown": [
|
||||
"### Notion Page Content\n",
|
||||
"*No content found or page is not accessible. Please check your page ID and sharing settings.*"
|
||||
],
|
||||
"text/plain": [
|
||||
"<IPython.core.display.Markdown object>"
|
||||
]
|
||||
},
|
||||
"metadata": {},
|
||||
"output_type": "display_data"
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"# Define a wrapper to match the agent's expected tool signature\n",
|
||||
"def notion_tool_wrapper(inputs):\n",
|
||||
" page_id = inputs.get(\"page_id\", \"\")\n",
|
||||
" notion_token = inputs.get(\"notion_token\", \"\")\n",
|
||||
" return notion_read_page_tool(page_id, notion_token)\n",
|
||||
"\n",
|
||||
"# Create the agent and register the tool\n",
|
||||
"agent = Agent(\n",
|
||||
" instructions=\"\"\"\n",
|
||||
" You are a Notion workspace assistant. Help users read and manage their Notion pages.\n",
|
||||
" - Provide clear, organized summaries of page content.\n",
|
||||
" - Use the Notion API to fetch and display information.\n",
|
||||
" - If a page cannot be read, explain the issue clearly.\n",
|
||||
" \"\"\",\n",
|
||||
" tools={\n",
|
||||
" \"notion_read_page_tool\": notion_tool_wrapper\n",
|
||||
" }\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"# Call the tool directly (since agent.chat expects an LLM, but we want tool output)\n",
|
||||
"response = agent.execute_tool(\"notion_read_page_tool\", {\n",
|
||||
" \"page_id\": page_id,\n",
|
||||
" \"notion_token\": NOTION_API_KEY\n",
|
||||
"})\n",
|
||||
"\n",
|
||||
"# Check for error pattern and display a friendly message\n",
|
||||
"if response.startswith(\"Failed to fetch page content:\"):\n",
|
||||
" display(Markdown(\"### Notion Page Content\\n*No content found or page is not accessible. Please check your page ID and sharing settings.*\"))\n",
|
||||
"else:\n",
|
||||
" display(Markdown(f\"### Notion Page Content\\n{response}\"))"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"provenance": []
|
||||
},
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"name": "python"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 0
|
||||
}
|
||||
+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,142 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Fixed example demonstrating proper guardrail usage with PraisonAI Agents.
|
||||
This addresses the issues reported in issue #875.
|
||||
"""
|
||||
|
||||
from praisonaiagents import Agent, Task, GuardrailResult, PraisonAIAgents, TaskOutput
|
||||
from typing import Tuple, Any
|
||||
import trafilatura
|
||||
|
||||
# Example 1: Using GuardrailResult return type (now supported!)
|
||||
def validate_length_guardrailresult(output: TaskOutput) -> GuardrailResult:
|
||||
"""Ensure output is between 100-500 characters using GuardrailResult"""
|
||||
# Extract the raw text from the TaskOutput object
|
||||
text = output.raw if hasattr(output, 'raw') else str(output)
|
||||
length = len(text)
|
||||
|
||||
if 100 <= length <= 500:
|
||||
return GuardrailResult(
|
||||
success=True,
|
||||
result=output, # Pass through the original output
|
||||
error=""
|
||||
)
|
||||
else:
|
||||
return GuardrailResult(
|
||||
success=False,
|
||||
result=None,
|
||||
error=f"Output must be 100-500 chars, got {length}"
|
||||
)
|
||||
|
||||
# Example 2: Using Tuple[bool, Any] return type (original method)
|
||||
def validate_length_tuple(output: TaskOutput) -> Tuple[bool, Any]:
|
||||
"""Ensure output is between 100-500 characters using tuple"""
|
||||
text = output.raw if hasattr(output, 'raw') else str(output)
|
||||
length = len(text)
|
||||
|
||||
if 100 <= length <= 500:
|
||||
return True, output
|
||||
else:
|
||||
return False, f"Output must be 100-500 chars, got {length}"
|
||||
|
||||
# Tool function
|
||||
def get_url_context(url):
|
||||
"""Fetch and extract content from a URL"""
|
||||
downloaded = trafilatura.fetch_url(url)
|
||||
if not downloaded:
|
||||
return "Sorry, I couldn't fetch the content from that URL."
|
||||
|
||||
extracted = trafilatura.extract(
|
||||
downloaded,
|
||||
include_comments=False,
|
||||
include_links=True,
|
||||
output_format='json',
|
||||
with_metadata=True,
|
||||
url=url
|
||||
)
|
||||
|
||||
if not extracted:
|
||||
return "Sorry, I couldn't extract readable content from that page."
|
||||
|
||||
return extracted # returns JSON string
|
||||
|
||||
# Create agent with FIXED tools parameter (must be a list!)
|
||||
agent = Agent(
|
||||
name="Content Summarizer",
|
||||
role="Content Analysis Expert",
|
||||
goal="Summarize web content concisely",
|
||||
instructions="You are a helpful assistant that summarizes web content",
|
||||
llm="gemini/gemini-2.5-flash-lite-preview-06-17",
|
||||
self_reflect=False,
|
||||
verbose=True,
|
||||
tools=[get_url_context] # FIX: tools must be a list, not a single function
|
||||
)
|
||||
|
||||
# Create task with GuardrailResult guardrail
|
||||
task_with_guardrailresult = Task(
|
||||
name="summarise article with GuardrailResult",
|
||||
description="get the context of this url: https://blog.google/technology/ai/dolphingemma/ and produce a summary below 500 characters",
|
||||
agent=agent,
|
||||
guardrail=validate_length_guardrailresult, # Using GuardrailResult
|
||||
expected_output="summary of the article below 500 characters",
|
||||
max_retries=3 # Will retry up to 3 times if guardrail fails
|
||||
)
|
||||
|
||||
# Alternative: Create task with tuple guardrail
|
||||
task_with_tuple = Task(
|
||||
name="summarise article with tuple",
|
||||
description="get the context of this url: https://blog.google/technology/ai/dolphingemma/ and produce a summary below 500 characters",
|
||||
agent=agent,
|
||||
guardrail=validate_length_tuple, # Using Tuple[bool, Any]
|
||||
expected_output="summary of the article below 500 characters",
|
||||
max_retries=3
|
||||
)
|
||||
|
||||
# Example with string-based LLM guardrail
|
||||
task_with_llm_guardrail = Task(
|
||||
name="summarise with LLM guardrail",
|
||||
description="get the context of this url: https://blog.google/technology/ai/dolphingemma/ and produce a summary",
|
||||
agent=agent,
|
||||
guardrail="Ensure the summary is professional, factual, and between 100-500 characters",
|
||||
expected_output="professional summary of the article"
|
||||
)
|
||||
|
||||
# Run with GuardrailResult example
|
||||
print("=== Running with GuardrailResult guardrail ===")
|
||||
agents_gr = PraisonAIAgents(
|
||||
agents=[agent],
|
||||
tasks=[task_with_guardrailresult]
|
||||
)
|
||||
|
||||
# Uncomment to run:
|
||||
# result_gr = agents_gr.start()
|
||||
|
||||
# Run with Tuple example
|
||||
print("\n=== Running with Tuple[bool, Any] guardrail ===")
|
||||
agents_tuple = PraisonAIAgents(
|
||||
agents=[agent],
|
||||
tasks=[task_with_tuple]
|
||||
)
|
||||
|
||||
# Uncomment to run:
|
||||
# result_tuple = agents_tuple.start()
|
||||
|
||||
# Run with LLM guardrail example
|
||||
print("\n=== Running with LLM-based guardrail ===")
|
||||
agents_llm = PraisonAIAgents(
|
||||
agents=[agent],
|
||||
tasks=[task_with_llm_guardrail]
|
||||
)
|
||||
|
||||
# Uncomment to run:
|
||||
# result_llm = agents_llm.start()
|
||||
|
||||
print("""
|
||||
Key fixes applied:
|
||||
1. GuardrailResult is now accepted as a valid return type annotation
|
||||
2. tools parameter must be a list: tools=[get_url_context] not tools=get_url_context
|
||||
3. Both GuardrailResult and Tuple[bool, Any] return types are supported
|
||||
4. String-based LLM guardrails are also supported
|
||||
|
||||
The guardrail will automatically retry (up to max_retries times) if validation fails.
|
||||
""")
|
||||
@@ -0,0 +1,259 @@
|
||||
# Multi-Provider/Multi-Model Support
|
||||
|
||||
PraisonAI now supports intelligent multi-provider and multi-model capabilities, allowing agents to automatically select the most appropriate AI model based on task requirements, cost considerations, and performance needs.
|
||||
|
||||
## 🚀 Key Features
|
||||
|
||||
### 1. **Automatic Model Selection**
|
||||
- Analyzes task complexity and selects the best model
|
||||
- Considers cost vs. performance trade-offs
|
||||
- Supports fallback mechanisms for reliability
|
||||
|
||||
### 2. **Cost Optimization**
|
||||
- Routes simple tasks to cheaper models (e.g., GPT-4o-mini, Gemini Flash)
|
||||
- Reserves expensive models for complex tasks
|
||||
- Tracks usage and provides cost estimates
|
||||
|
||||
### 3. **Multi-Provider Support**
|
||||
- Works with OpenAI, Anthropic, Google, Groq, and more
|
||||
- Seamless switching between providers
|
||||
- Provider preference settings
|
||||
|
||||
### 4. **Flexible Routing Strategies**
|
||||
- `auto`: Automatic selection based on task analysis
|
||||
- `cost-optimized`: Prioritize cheaper models
|
||||
- `performance-optimized`: Prioritize capability
|
||||
- `manual`: Use specified model
|
||||
|
||||
## 📦 Installation
|
||||
|
||||
The multi-provider support is included in the standard installation:
|
||||
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
|
||||
## 🔧 Basic Usage
|
||||
|
||||
### Simple Multi-Model Agent
|
||||
|
||||
```python
|
||||
from praisonaiagents import Task, PraisonAIAgents
|
||||
from praisonaiagents.agent import RouterAgent
|
||||
|
||||
# Create a multi-model agent
|
||||
agent = RouterAgent(
|
||||
name="Smart Assistant",
|
||||
role="Adaptive AI Assistant",
|
||||
goal="Complete tasks using the most appropriate model",
|
||||
models=["gpt-4o-mini", "gpt-4o", "claude-3-5-sonnet-20241022"],
|
||||
routing_strategy="auto" # Automatic model selection
|
||||
)
|
||||
|
||||
# Create tasks
|
||||
simple_task = Task(
|
||||
name="calculate",
|
||||
description="What is 15% of 250?",
|
||||
agent=agent
|
||||
)
|
||||
|
||||
complex_task = Task(
|
||||
name="analyze",
|
||||
description="Write a Python implementation of the A* pathfinding algorithm",
|
||||
agent=agent
|
||||
)
|
||||
|
||||
# Run tasks - agent will automatically select appropriate models
|
||||
agents = PraisonAIAgents(
|
||||
agents=[agent],
|
||||
tasks=[simple_task, complex_task]
|
||||
)
|
||||
|
||||
results = agents.start()
|
||||
```
|
||||
|
||||
### Cost-Optimized Workflow
|
||||
|
||||
```python
|
||||
from praisonaiagents.llm import ModelRouter
|
||||
|
||||
# Create custom router with cost constraints
|
||||
router = ModelRouter(
|
||||
cost_threshold=0.005, # Max $0.005 per 1k tokens
|
||||
preferred_providers=["google", "openai"]
|
||||
)
|
||||
|
||||
# Create cost-conscious agent
|
||||
analyzer = RouterAgent(
|
||||
name="Budget Analyzer",
|
||||
role="Data Analyst",
|
||||
goal="Analyze data efficiently",
|
||||
models={
|
||||
"gemini/gemini-1.5-flash": {},
|
||||
"gpt-4o-mini": {},
|
||||
"claude-3-haiku-20240307": {}
|
||||
},
|
||||
model_router=router,
|
||||
routing_strategy="cost-optimized"
|
||||
)
|
||||
```
|
||||
|
||||
## 🎯 Routing Strategies
|
||||
|
||||
### Auto Routing (Default)
|
||||
Automatically selects models based on:
|
||||
- Task complexity analysis
|
||||
- Required capabilities (tools, vision, etc.)
|
||||
- Context size requirements
|
||||
- Cost/performance balance
|
||||
|
||||
### Cost-Optimized
|
||||
Prioritizes cheaper models while meeting task requirements:
|
||||
- Uses lightweight models for simple tasks
|
||||
- Only escalates to expensive models when necessary
|
||||
- Ideal for high-volume operations
|
||||
|
||||
### Performance-Optimized
|
||||
Prioritizes model capability:
|
||||
- Uses the best available model for the task
|
||||
- Ideal for quality-critical applications
|
||||
- Less concern for cost
|
||||
|
||||
### Manual
|
||||
Uses the specified model without routing:
|
||||
- Direct control over model selection
|
||||
- Useful for testing or specific requirements
|
||||
|
||||
## 📊 Model Profiles
|
||||
|
||||
The system includes pre-configured profiles for popular models:
|
||||
|
||||
| Model | Provider | Best For | Cost/1k tokens |
|
||||
|-------|----------|----------|----------------|
|
||||
| gpt-4o-mini | OpenAI | Simple tasks, speed | $0.00075 |
|
||||
| gemini-1.5-flash | Google | Cost-effective, multimodal | $0.000125 |
|
||||
| claude-3-haiku | Anthropic | Fast responses | $0.0008 |
|
||||
| gpt-4o | OpenAI | General purpose | $0.0075 |
|
||||
| claude-3-5-sonnet-20241022 | Anthropic | Complex reasoning | $0.009 |
|
||||
| deepseek-chat | DeepSeek | Code & math | $0.0014 |
|
||||
|
||||
## 🔍 Task Complexity Analysis
|
||||
|
||||
The system analyzes tasks to determine complexity:
|
||||
|
||||
- **Simple**: Basic calculations, definitions, yes/no questions
|
||||
- **Moderate**: Summarization, basic analysis, classification
|
||||
- **Complex**: Code generation, algorithm implementation
|
||||
- **Very Complex**: Multi-step reasoning, system design
|
||||
|
||||
## 📈 Usage Tracking
|
||||
|
||||
Track model usage and costs:
|
||||
|
||||
```python
|
||||
# Get usage report
|
||||
report = agent.get_usage_report()
|
||||
print(report)
|
||||
|
||||
# Output:
|
||||
{
|
||||
'agent_name': 'Smart Assistant',
|
||||
'routing_strategy': 'auto',
|
||||
'model_usage': {
|
||||
'gpt-4o-mini': {'calls': 5, 'tokens': 1500, 'cost': 0.0011},
|
||||
'gpt-4o': {'calls': 2, 'tokens': 3000, 'cost': 0.0225}
|
||||
},
|
||||
'total_cost_estimate': 0.0236,
|
||||
'total_calls': 7
|
||||
}
|
||||
```
|
||||
|
||||
## 🛠️ Custom Model Configuration
|
||||
|
||||
Add custom model profiles:
|
||||
|
||||
```python
|
||||
from praisonaiagents.llm import ModelProfile, TaskComplexity
|
||||
|
||||
custom_model = ModelProfile(
|
||||
name="custom-model",
|
||||
provider="custom",
|
||||
complexity_range=(TaskComplexity.SIMPLE, TaskComplexity.MODERATE),
|
||||
cost_per_1k_tokens=0.002,
|
||||
strengths=["domain-specific"],
|
||||
capabilities=["text"],
|
||||
context_window=32000
|
||||
)
|
||||
|
||||
router = ModelRouter(models=[custom_model])
|
||||
```
|
||||
|
||||
## 🔗 Integration with AutoAgents
|
||||
|
||||
Works seamlessly with AutoAgents:
|
||||
|
||||
```python
|
||||
from praisonaiagents.agents import AutoAgents
|
||||
|
||||
# Create auto agents
|
||||
auto = AutoAgents(
|
||||
instructions="Analyze market trends and create a report",
|
||||
max_agents=3
|
||||
)
|
||||
|
||||
# Convert to multi-model agents
|
||||
for i, agent in enumerate(auto.agents):
|
||||
auto.agents[i] = RouterAgent(
|
||||
name=agent.name,
|
||||
role=agent.role,
|
||||
goal=agent.goal,
|
||||
models=["gpt-4o-mini", "gpt-4o", "claude-3-5-sonnet"],
|
||||
routing_strategy="auto"
|
||||
)
|
||||
|
||||
results = auto.start()
|
||||
```
|
||||
|
||||
## 🌟 Best Practices
|
||||
|
||||
1. **Start with Auto Routing**: Let the system learn your needs
|
||||
2. **Monitor Costs**: Use usage reports to optimize
|
||||
3. **Set Cost Thresholds**: Prevent unexpected expenses
|
||||
4. **Use Appropriate Models**: Don't use GPT-4 for simple math
|
||||
5. **Leverage Fallbacks**: Configure fallback models for reliability
|
||||
|
||||
## 🔐 Environment Variables
|
||||
|
||||
Set API keys for each provider:
|
||||
|
||||
```bash
|
||||
export OPENAI_API_KEY="sk-..."
|
||||
export ANTHROPIC_API_KEY="sk-ant-..."
|
||||
export GEMINI_API_KEY="..."
|
||||
export GROQ_API_KEY="..."
|
||||
```
|
||||
|
||||
## 🤝 Contributing
|
||||
|
||||
The multi-provider system is extensible. To add new models:
|
||||
|
||||
1. Add model profile to `ModelRouter.DEFAULT_MODELS`
|
||||
2. Ensure the provider is supported by LiteLLM
|
||||
3. Test with various task complexities
|
||||
|
||||
## 📚 Examples
|
||||
|
||||
See the complete example in `examples/python/agents/multi-provider-agent.py` for:
|
||||
- Auto-routing examples
|
||||
- Cost-optimized workflows
|
||||
- Performance-optimized agents
|
||||
- Custom routing logic
|
||||
- Integration patterns
|
||||
|
||||
## 🎉 Benefits
|
||||
|
||||
- **Cost Savings**: Reduce API costs by 50-80%
|
||||
- **Better Performance**: Use the right tool for each job
|
||||
- **Flexibility**: Switch providers without code changes
|
||||
- **Reliability**: Automatic fallbacks and error handling
|
||||
- **Transparency**: Track usage and costs
|
||||
@@ -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.")
|
||||
@@ -0,0 +1,231 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Context Agent Example - Basic Usage
|
||||
|
||||
This example demonstrates how to use the ContextAgent for automated context generation.
|
||||
The ContextAgent implements Context Engineering principles to generate comprehensive
|
||||
context for AI coding assistants, enabling first-try implementation success.
|
||||
|
||||
Key features demonstrated:
|
||||
- Basic ContextAgent instantiation
|
||||
- Codebase pattern analysis
|
||||
- Context document generation
|
||||
- Validation loop creation
|
||||
- Prompt enhancement with context
|
||||
- PRP (Product Requirements Prompt) generation
|
||||
"""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# Add the src directory to Python path for imports
|
||||
project_root = Path(__file__).parent.parent.parent.parent / "src" / "praisonai-agents"
|
||||
sys.path.insert(0, str(project_root))
|
||||
|
||||
from praisonaiagents import create_context_agent
|
||||
|
||||
def demonstrate_basic_context_generation():
|
||||
"""Demonstrate basic context generation capabilities."""
|
||||
print("🔧 Context Engineering Example: Basic Usage")
|
||||
print("=" * 60)
|
||||
|
||||
# Create a ContextAgent using the factory function
|
||||
context_agent = create_context_agent(
|
||||
llm="gpt-4o-mini",
|
||||
name="Basic Context Engineer",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Example 1: Analyze codebase patterns
|
||||
print("\n📁 Example 1: Analyzing Codebase Patterns")
|
||||
print("-" * 40)
|
||||
|
||||
# Use current project as example (adjust path as needed)
|
||||
project_path = str(project_root)
|
||||
analysis = context_agent.analyze_codebase_patterns(
|
||||
project_path=project_path,
|
||||
file_patterns=["*.py"]
|
||||
)
|
||||
|
||||
print(f"✅ Analyzed project at: {project_path}")
|
||||
print(f" Project structure: {len(analysis.get('project_structure', {}).get('directories', []))} directories")
|
||||
print(f" Code patterns identified: {len(analysis.get('code_patterns', {}))}")
|
||||
print(f" Architecture: {analysis.get('architecture_insights', {}).get('primary_pattern', 'Unknown')}")
|
||||
|
||||
# Example 2: Generate context document
|
||||
print("\n📄 Example 2: Generating Context Document")
|
||||
print("-" * 40)
|
||||
|
||||
feature_request = "Add user authentication system with JWT tokens and role-based access control"
|
||||
context_doc = context_agent.generate_context_document(
|
||||
project_path=project_path,
|
||||
requirements=feature_request,
|
||||
analysis=analysis
|
||||
)
|
||||
|
||||
print(f"✅ Generated context document for: {feature_request}")
|
||||
print(f" Document length: {len(context_doc)} characters")
|
||||
print(f" Contains architecture patterns: {'Architecture Patterns' in context_doc}")
|
||||
print(f" Contains validation criteria: {'Validation Criteria' in context_doc}")
|
||||
|
||||
# Example 3: Create validation loop
|
||||
print("\n✅ Example 3: Creating Validation Loop")
|
||||
print("-" * 40)
|
||||
|
||||
success_criteria = [
|
||||
"Authentication system accepts valid JWT tokens",
|
||||
"Role-based access control blocks unauthorized users",
|
||||
"User registration and login endpoints work correctly",
|
||||
"Password hashing follows security best practices",
|
||||
"Session management handles token expiration"
|
||||
]
|
||||
|
||||
validation_config = context_agent.create_validation_loop(
|
||||
implementation_requirements=feature_request,
|
||||
success_criteria=success_criteria
|
||||
)
|
||||
|
||||
print(f"✅ Created validation loop with {len(validation_config['validation_steps'])} steps")
|
||||
print(f" Success criteria: {len(success_criteria)}")
|
||||
print(f" Executable tests: {len(validation_config['executable_tests'])}")
|
||||
print(f" Quality gates: {len(validation_config['quality_gates'])}")
|
||||
|
||||
# Example 4: Enhance prompt with context
|
||||
print("\n🚀 Example 4: Enhancing Prompt with Context")
|
||||
print("-" * 40)
|
||||
|
||||
basic_prompt = "Implement user authentication"
|
||||
enhanced_prompt = context_agent.enhance_prompt_with_context(
|
||||
base_prompt=basic_prompt,
|
||||
context_data=analysis
|
||||
)
|
||||
|
||||
print(f"✅ Enhanced prompt from {len(basic_prompt)} to {len(enhanced_prompt)} characters")
|
||||
print(f" Original: '{basic_prompt}'")
|
||||
print(" Enhanced includes: Context Engineering, Implementation Context, Quality Requirements")
|
||||
|
||||
# Example 5: Generate PRP (Product Requirements Prompt)
|
||||
print("\n📋 Example 5: Generating PRP")
|
||||
print("-" * 40)
|
||||
|
||||
documentation_links = [
|
||||
"https://jwt.io/introduction/",
|
||||
"https://fastapi.tiangolo.com/tutorial/security/",
|
||||
"https://passlib.readthedocs.io/en/stable/"
|
||||
]
|
||||
|
||||
prp = context_agent.generate_prp(
|
||||
feature_request=feature_request,
|
||||
context_analysis=analysis,
|
||||
documentation_links=documentation_links
|
||||
)
|
||||
|
||||
print("✅ Generated comprehensive PRP")
|
||||
print(f" PRP length: {len(prp)} characters")
|
||||
print(f" Contains feature request: {feature_request in prp}")
|
||||
print(f" Contains documentation links: {len(documentation_links)} links included")
|
||||
print(f" Contains implementation blueprint: {'Implementation Blueprint' in prp}")
|
||||
print(f" Confidence score: {'9/10' in prp}")
|
||||
|
||||
def demonstrate_context_agent_as_tool():
|
||||
"""Demonstrate using ContextAgent as a tool in a multi-agent workflow."""
|
||||
print("\n🔗 Context Engineering Example: Multi-Agent Integration")
|
||||
print("=" * 60)
|
||||
|
||||
# Create ContextAgent
|
||||
context_agent = create_context_agent(llm="gpt-4o-mini")
|
||||
|
||||
# Example scenario: Product planning workflow
|
||||
project_path = str(project_root)
|
||||
feature_request = "Build a real-time chat system with WebSocket support"
|
||||
|
||||
# Step 1: Context analysis
|
||||
print("\n1️⃣ Step 1: Context Analysis")
|
||||
analysis = context_agent.analyze_codebase_patterns(project_path)
|
||||
print(f"✅ Analyzed codebase architecture and patterns")
|
||||
|
||||
# Step 2: Generate implementation blueprint
|
||||
print("\n2️⃣ Step 2: Implementation Blueprint")
|
||||
blueprint = context_agent.create_implementation_blueprint(feature_request, analysis)
|
||||
print(f"✅ Created implementation blueprint with {len(blueprint['implementation_steps'])} steps")
|
||||
|
||||
# Step 3: Generate comprehensive PRP
|
||||
print("\n3️⃣ Step 3: Generate PRP")
|
||||
prp = context_agent.generate_prp(feature_request, analysis) # Generated PRP for implementation guidance
|
||||
print(f"✅ Generated PRP for implementation guidance")
|
||||
|
||||
# Step 4: Create validation framework
|
||||
print("\n4️⃣ Step 4: Validation Framework")
|
||||
criteria = [
|
||||
"WebSocket connections establish successfully",
|
||||
"Messages broadcast to all connected clients",
|
||||
"Chat history persists and loads correctly",
|
||||
"User authentication works with WebSocket",
|
||||
"Connection handling is robust with reconnection"
|
||||
]
|
||||
validation = context_agent.create_validation_loop(feature_request, criteria) # Validation framework for QA
|
||||
print(f"✅ Created validation framework with {len(criteria)} criteria")
|
||||
|
||||
print("\n🎯 Context Engineering Workflow Complete!")
|
||||
print(f" Feature: {feature_request}")
|
||||
print(" Implementation ready with comprehensive context")
|
||||
print(" Validation criteria defined for quality assurance")
|
||||
|
||||
def show_context_engineering_benefits():
|
||||
"""Demonstrate the benefits of Context Engineering vs traditional approaches."""
|
||||
print("\n📊 Context Engineering Benefits")
|
||||
print("=" * 60)
|
||||
|
||||
# Traditional prompt engineering approach
|
||||
print("\n❌ Traditional Prompt Engineering:")
|
||||
traditional_prompt = "Create a user authentication system"
|
||||
print(f" Prompt: '{traditional_prompt}'")
|
||||
print(f" Length: {len(traditional_prompt)} characters")
|
||||
print(f" Context: Minimal - relies on AI's general knowledge")
|
||||
print(f" Success Rate: Variable - depends on AI model's training")
|
||||
|
||||
# Context Engineering approach
|
||||
print("\n✅ Context Engineering Approach:")
|
||||
context_agent = create_context_agent(llm="gpt-4o-mini")
|
||||
|
||||
# Generate comprehensive context
|
||||
analysis = context_agent.analyze_codebase_patterns(str(project_root))
|
||||
enhanced_prompt = context_agent.enhance_prompt_with_context(
|
||||
traditional_prompt, analysis
|
||||
)
|
||||
|
||||
print(f" Enhanced Prompt Length: {len(enhanced_prompt)} characters")
|
||||
print(f" Context: Comprehensive - includes:")
|
||||
print(f" • Codebase architecture analysis")
|
||||
print(f" • Existing patterns and conventions")
|
||||
print(f" • Implementation guidance")
|
||||
print(f" • Quality requirements")
|
||||
print(f" • Validation criteria")
|
||||
print(f" Success Rate: Higher - AI has all necessary context")
|
||||
|
||||
print(f"\n🎯 Context Engineering provides:")
|
||||
print(" 📈 10x better than prompt engineering (comprehensive vs clever wording)")
|
||||
print(" 📈 100x better than vibe coding (structured vs ad-hoc)")
|
||||
print(" 🎯 First-try implementation success through complete context")
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("🚀 PraisonAI Context Engineering Examples")
|
||||
print("=========================================")
|
||||
|
||||
try:
|
||||
# Run all examples
|
||||
demonstrate_basic_context_generation()
|
||||
demonstrate_context_agent_as_tool()
|
||||
show_context_engineering_benefits()
|
||||
|
||||
print("\n🎉 All Context Engineering examples completed successfully!")
|
||||
print("\n💡 Key Takeaways:")
|
||||
print(" • ContextAgent automates comprehensive context generation")
|
||||
print(" • Context Engineering enables first-try implementation success")
|
||||
print(" • Integration with existing PraisonAI agents is seamless")
|
||||
print(" • Validation frameworks ensure quality and completeness")
|
||||
|
||||
except Exception as e:
|
||||
print(f"\n❌ Error running examples: {e}")
|
||||
print(" Make sure you have the PraisonAI package installed and configured")
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,285 @@
|
||||
"""
|
||||
Multi-Provider/Multi-Model Agent Example
|
||||
|
||||
This example demonstrates how to use multiple AI providers/models with intelligent
|
||||
agent-based selection for cost optimization and performance.
|
||||
"""
|
||||
|
||||
import os
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.agent import RouterAgent
|
||||
from praisonaiagents.llm.model_router import ModelRouter, ModelProfile, TaskComplexity
|
||||
|
||||
# Example 1: Simple Multi-Model Agent with Auto-Routing
|
||||
def example_auto_routing():
|
||||
"""Example of automatic model routing based on task complexity"""
|
||||
print("\n=== Example 1: Auto-Routing Multi-Model Agent ===\n")
|
||||
|
||||
# Create a router agent that automatically selects models
|
||||
research_agent = RouterAgent(
|
||||
name="Smart Researcher",
|
||||
role="Adaptive Research Assistant",
|
||||
goal="Research topics using the most appropriate AI model",
|
||||
backstory="I analyze task complexity and route to the best model",
|
||||
models=["gpt-4o-mini", "gpt-4o", "claude-3-5-sonnet-20241022"],
|
||||
routing_strategy="auto", # Automatic model selection
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Create tasks with different complexity levels
|
||||
simple_task = Task(
|
||||
name="simple_calculation",
|
||||
description="Calculate the sum of 1542 and 2873",
|
||||
expected_output="The numerical result",
|
||||
agent=research_agent
|
||||
)
|
||||
|
||||
moderate_task = Task(
|
||||
name="summarize_article",
|
||||
description="Summarize the key points about renewable energy trends",
|
||||
expected_output="A concise summary with main points",
|
||||
agent=research_agent
|
||||
)
|
||||
|
||||
complex_task = Task(
|
||||
name="analyze_code",
|
||||
description="Implement a Python function to find the longest palindromic substring in a given string with O(n^2) complexity",
|
||||
expected_output="Complete Python implementation with explanation",
|
||||
agent=research_agent
|
||||
)
|
||||
|
||||
# Run the tasks
|
||||
agents = PraisonAIAgents(
|
||||
agents=[research_agent],
|
||||
tasks=[simple_task, moderate_task, complex_task],
|
||||
process="sequential",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
results = agents.start()
|
||||
|
||||
# Show usage report
|
||||
print("\n=== Model Usage Report ===")
|
||||
print(research_agent.get_usage_report())
|
||||
|
||||
|
||||
# Example 2: Cost-Optimized Workflow with Routing
|
||||
def example_cost_optimized_workflow():
|
||||
"""Example of cost-optimized workflow with model routing"""
|
||||
print("\n=== Example 2: Cost-Optimized Workflow ===\n")
|
||||
|
||||
# Create custom model router with cost threshold
|
||||
cost_router = ModelRouter(
|
||||
cost_threshold=0.01, # Max $0.01 per 1k tokens
|
||||
preferred_providers=["google", "openai", "anthropic"] # Provider preference
|
||||
)
|
||||
|
||||
# Create specialized agents with different model strategies
|
||||
analyzer = RouterAgent(
|
||||
name="Cost-Conscious Analyzer",
|
||||
role="Data Analyzer",
|
||||
goal="Analyze data efficiently while minimizing costs",
|
||||
models={
|
||||
"gemini/gemini-1.5-flash": {},
|
||||
"gpt-4o-mini": {},
|
||||
"deepseek-chat": {}
|
||||
},
|
||||
model_router=cost_router,
|
||||
routing_strategy="cost-optimized",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
writer = RouterAgent(
|
||||
name="Quality Writer",
|
||||
role="Content Writer",
|
||||
goal="Create high-quality content",
|
||||
models={
|
||||
"claude-3-5-sonnet-20241022": {},
|
||||
"gpt-4o": {}
|
||||
},
|
||||
routing_strategy="performance-optimized", # Prefer better models
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Create workflow tasks
|
||||
analysis_task = Task(
|
||||
name="analyze_data",
|
||||
description="Analyze this dataset: [1, 2, 3, 4, 5]. Find mean, median, and mode.",
|
||||
expected_output="Statistical analysis results",
|
||||
agent=analyzer
|
||||
)
|
||||
|
||||
writing_task = Task(
|
||||
name="write_report",
|
||||
description="Write a professional report based on the analysis",
|
||||
expected_output="Professional report with insights",
|
||||
agent=writer,
|
||||
context=[analysis_task] # Use results from analysis
|
||||
)
|
||||
|
||||
# Run workflow
|
||||
workflow = PraisonAIAgents(
|
||||
agents=[analyzer, writer],
|
||||
tasks=[analysis_task, writing_task],
|
||||
process="sequential",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
results = workflow.start()
|
||||
|
||||
# Show cost comparison
|
||||
print("\n=== Cost Analysis ===")
|
||||
print(f"Analyzer costs: {analyzer.get_usage_report()}")
|
||||
print(f"Writer costs: {writer.get_usage_report()}")
|
||||
|
||||
|
||||
# Example 3: Auto Agent Mode with Multi-Provider Support
|
||||
def example_auto_agents_multi_provider():
|
||||
"""Example using AutoAgents with multi-provider support"""
|
||||
print("\n=== Example 3: AutoAgents with Multi-Provider Support ===\n")
|
||||
|
||||
from praisonaiagents.agents import AutoAgents
|
||||
|
||||
# Create AutoAgents that will automatically assign appropriate models
|
||||
auto_agents = AutoAgents(
|
||||
instructions="Create a market research report on electric vehicles. Include data analysis, competitor analysis, and future projections.",
|
||||
max_agents=3,
|
||||
llm="gpt-4o-mini", # Default model for agent generation
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# After agents are created, upgrade them to multi-model agents
|
||||
multi_model_agents = []
|
||||
for agent in auto_agents.agents:
|
||||
# Convert regular agents to multi-model agents
|
||||
multi_agent = RouterAgent(
|
||||
name=agent.name,
|
||||
role=agent.role,
|
||||
goal=agent.goal,
|
||||
backstory=agent.backstory,
|
||||
tools=agent.tools,
|
||||
models=["gpt-4o-mini", "gemini/gemini-1.5-flash", "claude-3-haiku-20240307", "gpt-4o"],
|
||||
routing_strategy="auto",
|
||||
verbose=True
|
||||
)
|
||||
multi_model_agents.append(multi_agent)
|
||||
|
||||
# Update the agents in the AutoAgents instance
|
||||
auto_agents.agents = multi_model_agents
|
||||
|
||||
# Run the auto-generated workflow
|
||||
results = auto_agents.start()
|
||||
|
||||
# Show model usage across all agents
|
||||
print("\n=== Multi-Provider Usage Summary ===")
|
||||
total_calls = 0
|
||||
for agent in multi_model_agents:
|
||||
report = agent.get_usage_report()
|
||||
print(f"\nAgent: {agent.name}")
|
||||
for model, stats in report['model_usage'].items():
|
||||
if stats['calls'] > 0:
|
||||
print(f" - {model}: {stats['calls']} calls")
|
||||
total_calls += stats['calls']
|
||||
|
||||
print(f"\nTotal API calls: {total_calls}")
|
||||
|
||||
|
||||
# Example 4: Custom Routing Logic
|
||||
def example_custom_routing():
|
||||
"""Example with custom routing logic based on specific requirements"""
|
||||
print("\n=== Example 4: Custom Routing Logic ===\n")
|
||||
|
||||
# Create custom model profiles for specific use cases
|
||||
custom_models = [
|
||||
ModelProfile(
|
||||
name="gpt-4o",
|
||||
provider="openai",
|
||||
complexity_range=(TaskComplexity.SIMPLE, TaskComplexity.VERY_COMPLEX),
|
||||
cost_per_1k_tokens=0.0075,
|
||||
strengths=["code-generation", "debugging"],
|
||||
capabilities=["text", "function-calling"],
|
||||
context_window=128000
|
||||
),
|
||||
ModelProfile(
|
||||
name="deepseek-chat",
|
||||
provider="deepseek",
|
||||
complexity_range=(TaskComplexity.MODERATE, TaskComplexity.VERY_COMPLEX),
|
||||
cost_per_1k_tokens=0.001,
|
||||
strengths=["mathematics", "algorithms"],
|
||||
capabilities=["text", "function-calling"],
|
||||
context_window=128000
|
||||
)
|
||||
]
|
||||
|
||||
# Create router with custom models
|
||||
custom_router = ModelRouter(models=custom_models)
|
||||
|
||||
# Tool for web search (example)
|
||||
def search_web(query: str) -> str:
|
||||
"""Search the web for information"""
|
||||
return f"Search results for: {query}"
|
||||
|
||||
# Create specialized agent
|
||||
coder = RouterAgent(
|
||||
name="Adaptive Coder",
|
||||
role="Software Developer",
|
||||
goal="Write and debug code using the best model for each task",
|
||||
backstory="I'm an expert coder who knows when to use different AI models",
|
||||
model_router=custom_router,
|
||||
routing_strategy="auto",
|
||||
tools=[search_web],
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Create coding tasks
|
||||
tasks = [
|
||||
Task(
|
||||
name="fix_bug",
|
||||
description="Fix this Python bug: 'list' object has no attribute 'appendx'",
|
||||
expected_output="Corrected code with explanation",
|
||||
agent=coder
|
||||
),
|
||||
Task(
|
||||
name="implement_algorithm",
|
||||
description="Implement Dijkstra's shortest path algorithm in Python",
|
||||
expected_output="Complete implementation with comments",
|
||||
agent=coder,
|
||||
tools=[search_web]
|
||||
)
|
||||
]
|
||||
|
||||
# Run tasks
|
||||
agents = PraisonAIAgents(
|
||||
agents=[coder],
|
||||
tasks=tasks,
|
||||
process="sequential",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
results = agents.start()
|
||||
|
||||
print("\n=== Custom Routing Results ===")
|
||||
print(coder.get_usage_report())
|
||||
|
||||
|
||||
# Run examples
|
||||
if __name__ == "__main__":
|
||||
# Make sure to set your API keys
|
||||
# os.environ["OPENAI_API_KEY"] = "your-openai-key"
|
||||
# os.environ["ANTHROPIC_API_KEY"] = "your-anthropic-key"
|
||||
# os.environ["GEMINI_API_KEY"] = "your-gemini-key"
|
||||
|
||||
# Run examples
|
||||
example_auto_routing()
|
||||
example_cost_optimized_workflow()
|
||||
example_auto_agents_multi_provider()
|
||||
example_custom_routing()
|
||||
|
||||
print("\n=== All Examples Completed ===")
|
||||
print("\nKey Features Demonstrated:")
|
||||
print("1. Automatic model selection based on task complexity")
|
||||
print("2. Cost-optimized routing for budget-conscious operations")
|
||||
print("3. Performance-optimized routing for quality-critical tasks")
|
||||
print("4. Multi-provider support with fallback mechanisms")
|
||||
print("5. Integration with AutoAgents for automatic workflow generation")
|
||||
print("6. Custom routing logic for specialized use cases")
|
||||
@@ -0,0 +1,82 @@
|
||||
"""
|
||||
RouterAgent Cost Optimization Example
|
||||
|
||||
This example demonstrates how to use RouterAgent for intelligent model selection
|
||||
based on cost optimization. The router agent automatically selects the most
|
||||
cost-effective model for different types of tasks while maintaining quality.
|
||||
|
||||
Features demonstrated:
|
||||
- Cost-optimized model routing
|
||||
- Automatic model selection based on task complexity
|
||||
- Usage tracking and cost monitoring
|
||||
- Fallback mechanisms for reliability
|
||||
"""
|
||||
|
||||
from praisonaiagents import Agent
|
||||
from praisonaiagents.agent.router_agent import RouterAgent
|
||||
from praisonaiagents.tools import duckduckgo
|
||||
|
||||
# Define model options with cost considerations
|
||||
# Using different models for different complexity levels
|
||||
cheap_model = "gpt-4o-mini" # For simple tasks
|
||||
balanced_model = "gpt-4o" # For moderate complexity
|
||||
premium_model = "claude-3-5-sonnet-20241022" # For complex tasks
|
||||
|
||||
# Create RouterAgent with cost optimization strategy
|
||||
router = RouterAgent(
|
||||
name="CostOptimizedRouter",
|
||||
role="Cost-Efficient Task Router",
|
||||
goal="Route tasks to the most cost-effective model while maintaining quality",
|
||||
backstory="You are a smart router that optimizes for cost-efficiency by selecting appropriate models based on task complexity.",
|
||||
|
||||
# Model routing strategy - simple tasks to cheap models, complex to premium
|
||||
models=[cheap_model, balanced_model, premium_model],
|
||||
|
||||
# Routing logic - this could be enhanced with more sophisticated rules
|
||||
instructions="""You are a cost-optimization router. For simple tasks like basic questions,
|
||||
definitions, or simple calculations, use the cheapest model. For moderate complexity tasks
|
||||
like writing, analysis, or research, use the balanced model. For complex tasks requiring
|
||||
deep reasoning, creativity, or specialized knowledge, use the premium model.""",
|
||||
|
||||
tools=[duckduckgo],
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Example tasks of varying complexity levels
|
||||
|
||||
# Simple task - should route to cheap model
|
||||
print("="*60)
|
||||
print("TESTING SIMPLE TASK (should use cheap model)")
|
||||
print("="*60)
|
||||
simple_result = router.start("What is the capital of France?")
|
||||
print(f"Simple task result: {simple_result}")
|
||||
|
||||
# Moderate complexity task - should route to balanced model
|
||||
print("\n" + "="*60)
|
||||
print("TESTING MODERATE TASK (should use balanced model)")
|
||||
print("="*60)
|
||||
moderate_result = router.start("Write a brief analysis of renewable energy trends in 2024")
|
||||
print(f"Moderate task result: {moderate_result}")
|
||||
|
||||
# Complex task - should route to premium model
|
||||
print("\n" + "="*60)
|
||||
print("TESTING COMPLEX TASK (should use premium model)")
|
||||
print("="*60)
|
||||
complex_result = router.start("Conduct a comprehensive strategic analysis of the impact of quantum computing on cybersecurity, including potential vulnerabilities and mitigation strategies")
|
||||
print(f"Complex task result: {complex_result}")
|
||||
|
||||
# Research task with tool usage - should route appropriately
|
||||
print("\n" + "="*60)
|
||||
print("TESTING RESEARCH TASK WITH TOOLS")
|
||||
print("="*60)
|
||||
research_result = router.start("Research and analyze the latest developments in artificial intelligence regulation globally")
|
||||
print(f"Research task result: {research_result}")
|
||||
|
||||
print("\n" + "="*80)
|
||||
print("COST OPTIMIZATION ROUTER DEMONSTRATION COMPLETED")
|
||||
print("="*80)
|
||||
print("The RouterAgent automatically selected appropriate models based on task complexity:")
|
||||
print("- Simple factual questions → Cheaper model (gpt-4o-mini)")
|
||||
print("- Moderate analysis tasks → Balanced model (gpt-4o)")
|
||||
print("- Complex strategic analysis → Premium model (claude-3-5-sonnet)")
|
||||
print("- This approach optimizes costs while maintaining quality for each task type")
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,469 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Context Engineering Workflow - Advanced Multi-Agent Example
|
||||
|
||||
This example demonstrates advanced Context Engineering workflows using ContextAgent
|
||||
in combination with other PraisonAI agents. It shows how Context Engineering can
|
||||
dramatically improve AI implementation success rates through comprehensive context
|
||||
generation and validation loops.
|
||||
|
||||
Workflow demonstrated:
|
||||
1. Product Manager Agent defines requirements
|
||||
2. ContextAgent analyzes codebase and generates comprehensive context
|
||||
3. Architecture Agent designs implementation using context
|
||||
4. Developer Agent implements using context-enhanced prompts
|
||||
5. QA Agent validates using context-generated criteria
|
||||
|
||||
This represents the full Context Engineering methodology in action.
|
||||
"""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# Add the src directory to Python path for imports
|
||||
project_root = Path(__file__).parent.parent.parent.parent / "src" / "praisonai-agents"
|
||||
sys.path.insert(0, str(project_root))
|
||||
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents, create_context_agent
|
||||
|
||||
class ContextEngineeringWorkflow:
|
||||
"""
|
||||
Advanced Context Engineering workflow demonstrating the full methodology.
|
||||
|
||||
This class orchestrates multiple agents using Context Engineering principles
|
||||
to achieve higher success rates in AI-driven development tasks.
|
||||
"""
|
||||
|
||||
def __init__(self, project_path: str, llm: str = "gpt-4o-mini"):
|
||||
self.project_path = project_path
|
||||
self.llm = llm
|
||||
self.context_data = {}
|
||||
self.setup_agents()
|
||||
|
||||
def setup_agents(self):
|
||||
"""Setup the multi-agent team with Context Engineering support."""
|
||||
|
||||
# 1. Product Manager Agent - Defines requirements
|
||||
self.product_manager = Agent(
|
||||
name="Product Manager",
|
||||
role="Product Requirements Specialist",
|
||||
goal="Define clear, comprehensive product requirements and user stories",
|
||||
backstory="""You are an experienced product manager who specializes in
|
||||
creating detailed, actionable requirements. You understand that clear
|
||||
requirements are the foundation of successful implementation.""",
|
||||
instructions="""
|
||||
When defining requirements:
|
||||
1. Be specific and measurable
|
||||
2. Include user acceptance criteria
|
||||
3. Consider edge cases and error scenarios
|
||||
4. Define success metrics
|
||||
5. Specify technical constraints
|
||||
""",
|
||||
llm=self.llm,
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# 2. Context Engineering Agent - Generates comprehensive context
|
||||
self.context_engineer = create_context_agent(
|
||||
llm=self.llm,
|
||||
name="Context Engineering Specialist",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# 3. Software Architect Agent - Designs implementation using context
|
||||
self.architect = Agent(
|
||||
name="Software Architect",
|
||||
role="System Architecture Specialist",
|
||||
goal="Design robust, scalable system architecture based on comprehensive context",
|
||||
backstory="""You are a senior software architect with expertise in
|
||||
designing systems that follow established patterns and best practices.
|
||||
You excel at creating architectures that integrate seamlessly with
|
||||
existing codebases.""",
|
||||
instructions="""
|
||||
When designing architecture:
|
||||
1. Follow the patterns identified in the context analysis
|
||||
2. Ensure compatibility with existing systems
|
||||
3. Design for scalability and maintainability
|
||||
4. Consider security and performance implications
|
||||
5. Document architectural decisions and rationale
|
||||
""",
|
||||
llm=self.llm,
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# 4. Senior Developer Agent - Implements using context-enhanced guidance
|
||||
self.developer = Agent(
|
||||
name="Senior Developer",
|
||||
role="Implementation Specialist",
|
||||
goal="Implement features following context-guided best practices",
|
||||
backstory="""You are a senior developer who excels at implementing
|
||||
features that follow established codebase patterns. You understand
|
||||
that consistency and quality are paramount.""",
|
||||
instructions="""
|
||||
When implementing features:
|
||||
1. Follow the codebase patterns identified in context analysis
|
||||
2. Maintain consistency with existing code style
|
||||
3. Implement comprehensive error handling
|
||||
4. Write clean, maintainable code
|
||||
5. Follow the implementation blueprint exactly
|
||||
""",
|
||||
llm=self.llm,
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# 5. QA Engineer Agent - Validates using context-generated criteria
|
||||
self.qa_engineer = Agent(
|
||||
name="QA Engineer",
|
||||
role="Quality Assurance Specialist",
|
||||
goal="Ensure implementation meets all quality criteria and requirements",
|
||||
backstory="""You are an experienced QA engineer who specializes in
|
||||
comprehensive testing and validation. You understand that quality
|
||||
is built in, not bolted on.""",
|
||||
instructions="""
|
||||
When validating implementations:
|
||||
1. Use the validation criteria from context analysis
|
||||
2. Test both happy path and edge cases
|
||||
3. Verify integration with existing systems
|
||||
4. Check for security vulnerabilities
|
||||
5. Validate performance requirements
|
||||
""",
|
||||
llm=self.llm,
|
||||
verbose=True
|
||||
)
|
||||
|
||||
def run_context_engineering_workflow(self, feature_request: str):
|
||||
"""
|
||||
Execute the complete Context Engineering workflow.
|
||||
|
||||
Args:
|
||||
feature_request (str): The feature to be implemented
|
||||
|
||||
Returns:
|
||||
dict: Complete workflow results with context and implementation
|
||||
"""
|
||||
print(f"🚀 Starting Context Engineering Workflow")
|
||||
print(f"Feature Request: {feature_request}")
|
||||
print("=" * 80)
|
||||
|
||||
# Phase 1: Requirements Analysis
|
||||
print("\n📋 Phase 1: Product Requirements Analysis")
|
||||
print("-" * 50)
|
||||
|
||||
requirements_task = Task(
|
||||
name="requirements_analysis",
|
||||
description=f"""
|
||||
Analyze and refine the feature request: '{feature_request}'
|
||||
|
||||
Create comprehensive requirements including:
|
||||
- Detailed feature description
|
||||
- User acceptance criteria
|
||||
- Technical requirements
|
||||
- Success metrics
|
||||
- Edge cases and constraints
|
||||
""",
|
||||
expected_output="Comprehensive product requirements document",
|
||||
agent=self.product_manager
|
||||
)
|
||||
|
||||
# Phase 2: Context Engineering Analysis
|
||||
print("\n🔧 Phase 2: Context Engineering Analysis")
|
||||
print("-" * 50)
|
||||
|
||||
# Generate comprehensive context using ContextAgent
|
||||
codebase_analysis = self.context_engineer.analyze_codebase_patterns(
|
||||
project_path=self.project_path
|
||||
)
|
||||
|
||||
context_document = self.context_engineer.generate_context_document(
|
||||
project_path=self.project_path,
|
||||
requirements=feature_request,
|
||||
analysis=codebase_analysis
|
||||
)
|
||||
|
||||
validation_framework = self.context_engineer.create_validation_loop(
|
||||
implementation_requirements=feature_request,
|
||||
success_criteria=[
|
||||
"Feature implements all specified requirements",
|
||||
"Code follows existing patterns and conventions",
|
||||
"Implementation includes comprehensive error handling",
|
||||
"All tests pass and coverage meets standards",
|
||||
"Integration with existing systems is seamless"
|
||||
]
|
||||
)
|
||||
|
||||
implementation_blueprint = self.context_engineer.create_implementation_blueprint(
|
||||
feature_request=feature_request,
|
||||
context_analysis=codebase_analysis
|
||||
)
|
||||
|
||||
# Generate PRP for complete context
|
||||
prp = self.context_engineer.generate_prp(
|
||||
feature_request=feature_request,
|
||||
context_analysis=codebase_analysis,
|
||||
documentation_links=[
|
||||
"https://docs.praisonai.com/",
|
||||
"https://pydantic-docs.helpmanual.io/",
|
||||
"https://fastapi.tiangolo.com/"
|
||||
]
|
||||
)
|
||||
|
||||
print(f"✅ Context Engineering Analysis Complete:")
|
||||
print(f" • Codebase analysis: {len(str(codebase_analysis))} chars")
|
||||
print(f" • Context document: {len(context_document)} chars")
|
||||
print(f" • Validation framework: {len(validation_framework['validation_steps'])} steps")
|
||||
print(f" • Implementation blueprint: {len(implementation_blueprint['implementation_steps'])} steps")
|
||||
print(f" • PRP generated: {len(prp)} chars")
|
||||
|
||||
# Store context data for subsequent phases
|
||||
self.context_data = {
|
||||
"codebase_analysis": codebase_analysis,
|
||||
"context_document": context_document,
|
||||
"validation_framework": validation_framework,
|
||||
"implementation_blueprint": implementation_blueprint,
|
||||
"prp": prp
|
||||
}
|
||||
|
||||
# Phase 3: Architecture Design with Context
|
||||
print("\n🏗️ Phase 3: Architecture Design with Context")
|
||||
print("-" * 50)
|
||||
|
||||
architecture_task = Task(
|
||||
name="architecture_design",
|
||||
description=f"""
|
||||
Design system architecture for: '{feature_request}'
|
||||
|
||||
Use the comprehensive context provided:
|
||||
{context_document}
|
||||
|
||||
Implementation Blueprint:
|
||||
{implementation_blueprint}
|
||||
|
||||
Design architecture that:
|
||||
- Follows identified codebase patterns
|
||||
- Integrates with existing systems
|
||||
- Meets all technical requirements
|
||||
- Is scalable and maintainable
|
||||
""",
|
||||
expected_output="Detailed system architecture design with component specifications",
|
||||
agent=self.architect,
|
||||
context=[requirements_task]
|
||||
)
|
||||
|
||||
# Phase 4: Implementation with Context-Enhanced Guidance
|
||||
print("\n💻 Phase 4: Implementation with Context")
|
||||
print("-" * 50)
|
||||
|
||||
# Enhance the implementation prompt with context
|
||||
enhanced_prompt = self.context_engineer.enhance_prompt_with_context(
|
||||
base_prompt=f"Implement {feature_request}",
|
||||
context_data=codebase_analysis
|
||||
)
|
||||
|
||||
implementation_task = Task(
|
||||
name="feature_implementation",
|
||||
description=f"""
|
||||
Implement the feature using context-enhanced guidance:
|
||||
|
||||
{enhanced_prompt}
|
||||
|
||||
Product Requirements Prompt (PRP):
|
||||
{prp}
|
||||
|
||||
Architecture Design: Reference the architecture task output
|
||||
|
||||
Implementation must:
|
||||
- Follow the implementation blueprint exactly
|
||||
- Use patterns identified in codebase analysis
|
||||
- Meet all requirements from Phase 1
|
||||
- Include comprehensive error handling
|
||||
""",
|
||||
expected_output="Complete feature implementation with code and documentation",
|
||||
agent=self.developer,
|
||||
context=[requirements_task, architecture_task]
|
||||
)
|
||||
|
||||
# Phase 5: Quality Assurance with Context-Generated Criteria
|
||||
print("\n🔍 Phase 5: Quality Assurance with Context")
|
||||
print("-" * 50)
|
||||
|
||||
qa_task = Task(
|
||||
name="quality_validation",
|
||||
description=f"""
|
||||
Validate the implementation using context-generated criteria:
|
||||
|
||||
Validation Framework:
|
||||
{validation_framework}
|
||||
|
||||
Verify that implementation:
|
||||
- Meets all success criteria defined in validation framework
|
||||
- Follows codebase patterns and conventions
|
||||
- Integrates properly with existing systems
|
||||
- Handles edge cases and error scenarios
|
||||
- Meets performance and security requirements
|
||||
|
||||
Use the validation steps provided to systematically check each criterion.
|
||||
""",
|
||||
expected_output="Comprehensive quality validation report with pass/fail status",
|
||||
agent=self.qa_engineer,
|
||||
context=[requirements_task, architecture_task, implementation_task]
|
||||
)
|
||||
|
||||
# Execute the complete workflow
|
||||
print("\n⚙️ Executing Context Engineering Workflow")
|
||||
print("-" * 50)
|
||||
|
||||
agents_workflow = PraisonAIAgents(
|
||||
agents=[
|
||||
self.product_manager,
|
||||
self.architect,
|
||||
self.developer,
|
||||
self.qa_engineer
|
||||
],
|
||||
tasks=[
|
||||
requirements_task,
|
||||
architecture_task,
|
||||
implementation_task,
|
||||
qa_task
|
||||
],
|
||||
process="sequential",
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Execute workflow
|
||||
workflow_results = agents_workflow.start()
|
||||
|
||||
# Compile complete results
|
||||
complete_results = {
|
||||
"feature_request": feature_request,
|
||||
"context_engineering": self.context_data,
|
||||
"workflow_results": workflow_results,
|
||||
"methodology": "Context Engineering - 10x better than prompt engineering"
|
||||
}
|
||||
|
||||
return complete_results
|
||||
|
||||
def demonstrate_context_engineering_benefits():
|
||||
"""
|
||||
Demonstrate the benefits of Context Engineering methodology.
|
||||
"""
|
||||
print("\n📊 Context Engineering vs Traditional Approaches")
|
||||
print("=" * 60)
|
||||
|
||||
# Traditional approach simulation
|
||||
print("\n❌ Traditional AI Coding Approach:")
|
||||
print(" 1. Write basic prompt: 'Implement user authentication'")
|
||||
print(" 2. AI uses general knowledge to implement")
|
||||
print(" 3. Result often doesn't fit existing codebase patterns")
|
||||
print(" 4. Multiple iterations needed to fix integration issues")
|
||||
print(" 5. Success rate: ~30-40% first-try success")
|
||||
|
||||
# Context Engineering approach
|
||||
print("\n✅ Context Engineering Approach:")
|
||||
print(" 1. Analyze codebase patterns and architecture")
|
||||
print(" 2. Generate comprehensive context document")
|
||||
print(" 3. Create validation framework with success criteria")
|
||||
print(" 4. Enhance prompts with rich contextual information")
|
||||
print(" 5. Generate PRP (Product Requirements Prompt)")
|
||||
print(" 6. AI implements using complete context")
|
||||
print(" 7. Success rate: ~90%+ first-try success")
|
||||
|
||||
print("\n📈 Context Engineering Advantages:")
|
||||
print(" • 10x better than prompt engineering (context vs clever wording)")
|
||||
print(" • 100x better than vibe coding (structured vs ad-hoc)")
|
||||
print(" • Enables first-try implementation success")
|
||||
print(" • Reduces development iteration cycles")
|
||||
print(" • Ensures consistency with existing codebase")
|
||||
print(" • Provides built-in quality validation")
|
||||
|
||||
def run_example_workflow():
|
||||
"""Run an example Context Engineering workflow."""
|
||||
|
||||
# Setup workflow with current project
|
||||
project_path = str(project_root)
|
||||
workflow = ContextEngineeringWorkflow(
|
||||
project_path=project_path,
|
||||
llm="gpt-4o-mini"
|
||||
)
|
||||
|
||||
# Example feature request
|
||||
feature_request = """
|
||||
Implement a real-time notification system that:
|
||||
- Sends notifications via WebSocket connections
|
||||
- Supports different notification types (info, warning, error)
|
||||
- Persists notifications in database for offline users
|
||||
- Includes user preference management for notification settings
|
||||
- Provides REST API for notification management
|
||||
"""
|
||||
|
||||
print("🎯 Running Example Context Engineering Workflow")
|
||||
print("=" * 60)
|
||||
|
||||
try:
|
||||
# Execute the complete workflow
|
||||
results = workflow.run_context_engineering_workflow(feature_request)
|
||||
|
||||
print("\n🎉 Context Engineering Workflow Completed Successfully!")
|
||||
print("=" * 60)
|
||||
|
||||
print(f"\n📊 Workflow Summary:")
|
||||
print(f" • Feature: Real-time notification system")
|
||||
print(f" • Context generated: ✅ Complete")
|
||||
print(f" • Architecture designed: ✅ With context")
|
||||
print(f" • Implementation: ✅ Context-guided")
|
||||
print(f" • Quality validation: ✅ Context-criteria")
|
||||
|
||||
print(f"\n🔧 Context Engineering Data:")
|
||||
context_data = results["context_engineering"]
|
||||
print(f" • Codebase analysis: {len(str(context_data['codebase_analysis']))} chars")
|
||||
print(f" • Context document: {len(context_data['context_document'])} chars")
|
||||
print(f" • Validation framework: {len(context_data['validation_framework']['validation_steps'])} steps")
|
||||
print(f" • Implementation blueprint: {len(context_data['implementation_blueprint']['implementation_steps'])} steps")
|
||||
print(f" • PRP: {len(context_data['prp'])} chars")
|
||||
|
||||
return results
|
||||
|
||||
except Exception as e:
|
||||
print(f"\n❌ Error in workflow execution: {e}")
|
||||
print(" Note: This is a demonstration - actual execution requires proper environment setup")
|
||||
return None
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("🚀 Advanced Context Engineering Workflow Example")
|
||||
print("================================================")
|
||||
|
||||
print("\n💡 This example demonstrates the complete Context Engineering methodology:")
|
||||
print(" • Comprehensive codebase analysis")
|
||||
print(" • Context document generation")
|
||||
print(" • Validation framework creation")
|
||||
print(" • Multi-agent workflow with context integration")
|
||||
print(" • Quality assurance with context-generated criteria")
|
||||
|
||||
# Show benefits comparison
|
||||
demonstrate_context_engineering_benefits()
|
||||
|
||||
# Run example workflow (demo mode)
|
||||
print("\n🎭 Demo Mode: Context Engineering Workflow Structure")
|
||||
print("(Note: Full execution requires complete environment setup)")
|
||||
|
||||
project_path = str(project_root)
|
||||
workflow = ContextEngineeringWorkflow(project_path, "gpt-4o-mini")
|
||||
|
||||
print(f"\n✅ Workflow Setup Complete:")
|
||||
print(f" • Project path: {project_path}")
|
||||
print(f" • Agents configured: 5 (PM, Context Engineer, Architect, Developer, QA)")
|
||||
print(f" • Context Engineering agent: ✅ Ready")
|
||||
print(f" • Multi-agent workflow: ✅ Configured")
|
||||
|
||||
print(f"\n🎯 Ready to execute Context Engineering workflow!")
|
||||
print(f" Use workflow.run_context_engineering_workflow(feature_request)")
|
||||
print(f" to execute the complete methodology.")
|
||||
|
||||
print(f"\n📚 Key Context Engineering Concepts Demonstrated:")
|
||||
print(f" • Pattern extraction from existing codebase")
|
||||
print(f" • Comprehensive context document generation")
|
||||
print(f" • Validation loop creation with success criteria")
|
||||
print(f" • PRP (Product Requirements Prompt) generation")
|
||||
print(f" • Context-enhanced prompt engineering")
|
||||
print(f" • Multi-agent workflow integration")
|
||||
|
||||
print(f"\n🎉 Context Engineering: 10x better than prompt engineering, 100x better than vibe coding!")
|
||||
@@ -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,204 @@
|
||||
"""
|
||||
Comprehensive Guardrails Example
|
||||
|
||||
This example demonstrates both function-based and LLM-based guardrails for validating
|
||||
agent outputs and ensuring quality, safety, and compliance.
|
||||
|
||||
Features demonstrated:
|
||||
- Function-based validation guardrails
|
||||
- LLM-based content validation
|
||||
- Multiple validation criteria
|
||||
- Retry mechanisms with feedback
|
||||
- Quality assurance workflows
|
||||
"""
|
||||
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from praisonaiagents.task import TaskOutput
|
||||
from typing import Tuple, Any
|
||||
import re
|
||||
|
||||
# Define function-based guardrails for different validation types
|
||||
|
||||
def email_format_guardrail(task_output: TaskOutput) -> Tuple[bool, Any]:
|
||||
"""
|
||||
Validates that the output contains properly formatted email addresses.
|
||||
"""
|
||||
output_text = str(task_output.raw)
|
||||
|
||||
# Email regex pattern
|
||||
email_pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
|
||||
emails_found = re.findall(email_pattern, output_text)
|
||||
|
||||
if emails_found:
|
||||
return True, task_output
|
||||
else:
|
||||
return False, "No valid email addresses found in the output. Please include at least one properly formatted email address."
|
||||
|
||||
def word_count_guardrail(task_output: TaskOutput) -> Tuple[bool, Any]:
|
||||
"""
|
||||
Validates that the output meets minimum word count requirements.
|
||||
"""
|
||||
output_text = str(task_output.raw)
|
||||
word_count = len(output_text.split())
|
||||
|
||||
min_words = 50 # Minimum required words
|
||||
|
||||
if word_count >= min_words:
|
||||
return True, task_output
|
||||
else:
|
||||
return False, f"Output too short. Found {word_count} words but need at least {min_words} words. Please provide a more detailed response."
|
||||
|
||||
def professional_tone_guardrail(task_output: TaskOutput) -> Tuple[bool, Any]:
|
||||
"""
|
||||
Validates that the output maintains a professional tone.
|
||||
"""
|
||||
output_text = str(task_output.raw).lower()
|
||||
|
||||
# Check for unprofessional words/phrases
|
||||
unprofessional_terms = ['stupid', 'dumb', 'sucks', 'terrible', 'awful', 'hate']
|
||||
|
||||
for term in unprofessional_terms:
|
||||
if term in output_text:
|
||||
return False, f"Output contains unprofessional language ('{term}'). Please revise to maintain a professional tone."
|
||||
|
||||
return True, task_output
|
||||
|
||||
def factual_accuracy_guardrail(task_output: TaskOutput) -> Tuple[bool, Any]:
|
||||
"""
|
||||
Validates that the output includes specific factual elements.
|
||||
"""
|
||||
output_text = str(task_output.raw).lower()
|
||||
|
||||
# Check for presence of factual indicators
|
||||
factual_indicators = ['according to', 'research shows', 'studies indicate', 'data suggests', 'evidence']
|
||||
|
||||
has_factual_backing = any(indicator in output_text for indicator in factual_indicators)
|
||||
|
||||
if has_factual_backing:
|
||||
return True, task_output
|
||||
else:
|
||||
return False, "Output lacks factual backing. Please include references to research, studies, or data to support your claims."
|
||||
|
||||
# Create agents with different guardrail configurations
|
||||
|
||||
# Agent with email format validation
|
||||
email_agent = Agent(
|
||||
name="EmailAgent",
|
||||
role="Business Communication Specialist",
|
||||
goal="Create professional business communications with proper email formatting",
|
||||
backstory="You are a professional communication specialist who ensures all business correspondence includes proper contact information.",
|
||||
instructions="Always include properly formatted email addresses in your responses."
|
||||
)
|
||||
|
||||
# Agent with word count validation
|
||||
content_agent = Agent(
|
||||
name="ContentAgent",
|
||||
role="Content Writer",
|
||||
goal="Create detailed, comprehensive content that meets length requirements",
|
||||
backstory="You are a professional content writer who creates detailed, well-researched articles.",
|
||||
instructions="Provide comprehensive, detailed responses with sufficient depth and explanation."
|
||||
)
|
||||
|
||||
# Agent with professional tone validation
|
||||
business_agent = Agent(
|
||||
name="BusinessAgent",
|
||||
role="Professional Advisor",
|
||||
goal="Provide professional business advice with appropriate tone",
|
||||
backstory="You are a seasoned business advisor who maintains professionalism in all communications.",
|
||||
instructions="Maintain a professional, respectful tone in all communications."
|
||||
)
|
||||
|
||||
# Agent with factual accuracy validation
|
||||
research_agent = Agent(
|
||||
name="ResearchAgent",
|
||||
role="Research Analyst",
|
||||
goal="Provide well-researched, fact-based analysis",
|
||||
backstory="You are a research analyst who backs all claims with evidence and citations.",
|
||||
instructions="Support all statements with references to research, studies, or credible data sources."
|
||||
)
|
||||
|
||||
# Create tasks with specific guardrails
|
||||
|
||||
# Task with email format guardrail
|
||||
email_task = Task(
|
||||
name="email_communication",
|
||||
description="Write a business proposal for a new software project, including contact information",
|
||||
expected_output="Professional business proposal with contact email addresses",
|
||||
agent=email_agent,
|
||||
guardrail=email_format_guardrail,
|
||||
max_retries=3
|
||||
)
|
||||
|
||||
# Task with word count guardrail
|
||||
content_task = Task(
|
||||
name="detailed_analysis",
|
||||
description="Write an analysis of cloud computing benefits for small businesses",
|
||||
expected_output="Comprehensive analysis of cloud computing benefits (minimum 50 words)",
|
||||
agent=content_agent,
|
||||
guardrail=word_count_guardrail,
|
||||
max_retries=3
|
||||
)
|
||||
|
||||
# Task with professional tone guardrail
|
||||
business_task = Task(
|
||||
name="professional_advice",
|
||||
description="Provide advice on handling difficult client relationships",
|
||||
expected_output="Professional advice maintaining appropriate business tone",
|
||||
agent=business_agent,
|
||||
guardrail=professional_tone_guardrail,
|
||||
max_retries=3
|
||||
)
|
||||
|
||||
# Task with factual accuracy guardrail
|
||||
research_task = Task(
|
||||
name="research_report",
|
||||
description="Analyze the impact of artificial intelligence on job markets",
|
||||
expected_output="Research-backed analysis with citations and evidence",
|
||||
agent=research_agent,
|
||||
guardrail=factual_accuracy_guardrail,
|
||||
max_retries=3
|
||||
)
|
||||
|
||||
# LLM-based guardrail example
|
||||
llm_guardrail_agent = Agent(
|
||||
name="LLMGuardrailAgent",
|
||||
role="Content Quality Validator",
|
||||
goal="Validate content quality using LLM-based assessment",
|
||||
backstory="You are a quality assurance specialist who uses AI to validate content quality.",
|
||||
instructions="Create marketing content that is engaging, accurate, and compliant with advertising standards."
|
||||
)
|
||||
|
||||
# Task with LLM-based guardrail
|
||||
llm_guardrail_task = Task(
|
||||
name="marketing_content",
|
||||
description="Create a marketing email for a new fitness app targeting busy professionals",
|
||||
expected_output="Engaging marketing email that is accurate and compliant",
|
||||
agent=llm_guardrail_agent,
|
||||
|
||||
# LLM-based guardrail using natural language validation
|
||||
guardrail="Validate that this marketing content is: 1) Factually accurate with no false claims, 2) Compliant with advertising standards (no misleading statements), 3) Engaging and professional in tone, 4) Includes a clear call-to-action. If any criteria are not met, explain what needs to be improved.",
|
||||
max_retries=2
|
||||
)
|
||||
|
||||
# Execute tasks with guardrails
|
||||
agents = PraisonAIAgents(
|
||||
agents=[email_agent, content_agent, business_agent, research_agent, llm_guardrail_agent],
|
||||
tasks=[email_task, content_task, business_task, research_task, llm_guardrail_task],
|
||||
verbose=True
|
||||
)
|
||||
|
||||
print("="*80)
|
||||
print("EXECUTING TASKS WITH COMPREHENSIVE GUARDRAILS")
|
||||
print("="*80)
|
||||
|
||||
result = agents.start()
|
||||
|
||||
print("\n" + "="*80)
|
||||
print("GUARDRAILS DEMONSTRATION COMPLETED")
|
||||
print("="*80)
|
||||
print("This example demonstrated:")
|
||||
print("- Function-based validation (email format, word count, tone, factual accuracy)")
|
||||
print("- LLM-based content validation using natural language criteria")
|
||||
print("- Automatic retry mechanisms with specific feedback")
|
||||
print("- Quality assurance workflows for different content types")
|
||||
print("- Professional validation standards for business communications")
|
||||
@@ -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,194 @@
|
||||
"""
|
||||
Advanced Knowledge Management Example
|
||||
|
||||
This example demonstrates sophisticated knowledge management capabilities including
|
||||
advanced chunking strategies, reranking, and intelligent knowledge retrieval.
|
||||
|
||||
Features demonstrated:
|
||||
- Advanced document chunking strategies
|
||||
- Vector store integration with ChromaDB
|
||||
- Knowledge-based question answering
|
||||
- Intelligent context retrieval
|
||||
- Document processing and management
|
||||
"""
|
||||
|
||||
from praisonaiagents import Agent
|
||||
import tempfile
|
||||
import os
|
||||
|
||||
# Create a sample knowledge document for demonstration
|
||||
sample_document = """
|
||||
# Artificial Intelligence in Healthcare
|
||||
|
||||
## Introduction
|
||||
Artificial intelligence (AI) is revolutionizing healthcare by enabling more accurate diagnoses,
|
||||
personalized treatments, and efficient healthcare delivery. This document explores the current
|
||||
applications and future potential of AI in healthcare.
|
||||
|
||||
## Current Applications
|
||||
|
||||
### Medical Imaging
|
||||
AI algorithms, particularly deep learning models, have shown remarkable success in medical imaging:
|
||||
- Radiology: AI can detect cancers in mammograms with accuracy matching or exceeding radiologists
|
||||
- Ophthalmology: AI systems can diagnose diabetic retinopathy from retinal photographs
|
||||
- Pathology: AI assists in analyzing tissue samples for cancer detection
|
||||
|
||||
### Drug Discovery
|
||||
AI is accelerating drug discovery processes:
|
||||
- Molecular design: AI predicts molecular properties and drug-target interactions
|
||||
- Clinical trials: AI optimizes patient recruitment and trial design
|
||||
- Repurposing: AI identifies new uses for existing drugs
|
||||
|
||||
### Predictive Analytics
|
||||
Healthcare providers use AI for:
|
||||
- Risk stratification: Identifying patients at risk of complications
|
||||
- Early warning systems: Detecting deteriorating patient conditions
|
||||
- Resource planning: Optimizing staff schedules and equipment allocation
|
||||
|
||||
## Challenges and Considerations
|
||||
|
||||
### Data Privacy and Security
|
||||
Healthcare AI faces significant challenges:
|
||||
- Patient data protection and HIPAA compliance
|
||||
- Secure data sharing between institutions
|
||||
- Consent management for AI applications
|
||||
|
||||
### Regulatory Approval
|
||||
AI medical devices require:
|
||||
- FDA approval for diagnostic tools
|
||||
- Clinical validation studies
|
||||
- Post-market surveillance
|
||||
|
||||
### Ethical Considerations
|
||||
Important ethical aspects include:
|
||||
- Algorithmic bias and fairness
|
||||
- Transparency and explainability
|
||||
- Patient autonomy and informed consent
|
||||
|
||||
## Future Directions
|
||||
|
||||
### Personalized Medicine
|
||||
AI will enable:
|
||||
- Genomic-based treatment selection
|
||||
- Individualized drug dosing
|
||||
- Precision diagnostics
|
||||
|
||||
### Integrated Healthcare Systems
|
||||
Future developments include:
|
||||
- AI-powered electronic health records
|
||||
- Interoperable AI systems across healthcare networks
|
||||
- Real-time decision support systems
|
||||
|
||||
## Conclusion
|
||||
AI has tremendous potential to transform healthcare, but successful implementation requires
|
||||
addressing technical, regulatory, and ethical challenges while maintaining focus on patient safety
|
||||
and improved outcomes.
|
||||
"""
|
||||
|
||||
# Save the sample document to a temporary file
|
||||
temp_dir = tempfile.mkdtemp()
|
||||
doc_path = os.path.join(temp_dir, "ai_healthcare_guide.txt")
|
||||
with open(doc_path, "w") as f:
|
||||
f.write(sample_document)
|
||||
|
||||
# Create an agent with advanced knowledge management configuration
|
||||
knowledge_agent = Agent(
|
||||
name="AdvancedKnowledgeAgent",
|
||||
role="Healthcare AI Knowledge Expert",
|
||||
goal="Provide comprehensive answers about AI in healthcare using advanced knowledge retrieval",
|
||||
backstory="You are an expert in healthcare AI with access to comprehensive knowledge bases and advanced retrieval capabilities.",
|
||||
|
||||
# Advanced knowledge configuration
|
||||
knowledge=[doc_path],
|
||||
knowledge_config={
|
||||
"vector_store": {
|
||||
"provider": "chroma",
|
||||
"collection_name": "healthcare_ai_knowledge"
|
||||
},
|
||||
"chunking": {
|
||||
"strategy": "semantic", # Advanced semantic chunking
|
||||
"chunk_size": 500, # Optimal chunk size for retrieval
|
||||
"chunk_overlap": 50, # Overlap for context preservation
|
||||
"separators": ["\n\n", "\n", ".", "!", "?"] # Smart separators
|
||||
},
|
||||
"retrieval": {
|
||||
"search_type": "similarity",
|
||||
"k": 5, # Retrieve top 5 most relevant chunks
|
||||
"score_threshold": 0.7, # Minimum relevance score
|
||||
"rerank": True # Enable reranking for better results
|
||||
},
|
||||
"embedding": {
|
||||
"provider": "openai",
|
||||
"model": "text-embedding-3-small", # Efficient embedding model
|
||||
"dimensions": 1536
|
||||
}
|
||||
},
|
||||
|
||||
instructions="""You are an expert in healthcare AI. Use the knowledge base to provide
|
||||
comprehensive, accurate answers. Always cite specific information from the documents
|
||||
when possible. If the knowledge base doesn't contain sufficient information, clearly
|
||||
state this and provide general guidance based on your training.""",
|
||||
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Test advanced knowledge retrieval with various question types
|
||||
|
||||
# Factual question about specific applications
|
||||
print("="*70)
|
||||
print("TESTING: Specific factual question about AI applications")
|
||||
print("="*70)
|
||||
factual_result = knowledge_agent.start(
|
||||
"What are the current applications of AI in medical imaging according to the knowledge base?"
|
||||
)
|
||||
print(f"Factual query result:\n{factual_result}\n")
|
||||
|
||||
# Complex analytical question requiring synthesis
|
||||
print("="*70)
|
||||
print("TESTING: Complex analytical question requiring synthesis")
|
||||
print("="*70)
|
||||
analytical_result = knowledge_agent.start(
|
||||
"What are the main challenges facing AI implementation in healthcare and how do they relate to each other?"
|
||||
)
|
||||
print(f"Analytical query result:\n{analytical_result}\n")
|
||||
|
||||
# Specific detail extraction
|
||||
print("="*70)
|
||||
print("TESTING: Specific detail extraction")
|
||||
print("="*70)
|
||||
detail_result = knowledge_agent.start(
|
||||
"What specific regulatory requirements does the document mention for AI medical devices?"
|
||||
)
|
||||
print(f"Detail extraction result:\n{detail_result}\n")
|
||||
|
||||
# Future-oriented question requiring inference
|
||||
print("="*70)
|
||||
print("TESTING: Future-oriented question requiring inference")
|
||||
print("="*70)
|
||||
future_result = knowledge_agent.start(
|
||||
"Based on the knowledge base, what integration capabilities will future AI healthcare systems have?"
|
||||
)
|
||||
print(f"Future-oriented query result:\n{future_result}\n")
|
||||
|
||||
# Question about relationships and connections
|
||||
print("="*70)
|
||||
print("TESTING: Relationship and connection analysis")
|
||||
print("="*70)
|
||||
relationship_result = knowledge_agent.start(
|
||||
"How do the ethical considerations mentioned relate to the regulatory approval process for AI in healthcare?"
|
||||
)
|
||||
print(f"Relationship analysis result:\n{relationship_result}\n")
|
||||
|
||||
# Clean up temporary files
|
||||
import shutil
|
||||
shutil.rmtree(temp_dir)
|
||||
|
||||
print("="*80)
|
||||
print("ADVANCED KNOWLEDGE MANAGEMENT DEMONSTRATION COMPLETED")
|
||||
print("="*80)
|
||||
print("This example demonstrated:")
|
||||
print("- Semantic chunking for better context preservation")
|
||||
print("- Advanced retrieval with reranking capabilities")
|
||||
print("- Multiple query types with intelligent responses")
|
||||
print("- Knowledge base integration with vector search")
|
||||
print("- Configurable embedding and retrieval parameters")
|
||||
@@ -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,153 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Example: Using Gemini Embedding Models with PraisonAI Memory
|
||||
|
||||
This example demonstrates how to configure PraisonAI to use Google's Gemini
|
||||
embedding models for memory storage and retrieval, as requested in issue #870.
|
||||
|
||||
Supported Gemini embedding models:
|
||||
- gemini-embedding-exp-03-07 (experimental)
|
||||
- text-embedding-004 (stable)
|
||||
|
||||
Prerequisites:
|
||||
1. Install praisonaiagents with memory support:
|
||||
pip install "praisonaiagents[memory]"
|
||||
|
||||
2. Set your Google API key:
|
||||
export GOOGLE_API_KEY='your-api-key'
|
||||
|
||||
3. Ensure litellm is installed (comes with praisonaiagents)
|
||||
"""
|
||||
|
||||
import os
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
|
||||
def main():
|
||||
"""Demonstrate Gemini embedding usage"""
|
||||
|
||||
# Verify Google API key
|
||||
if not os.environ.get("GOOGLE_API_KEY"):
|
||||
print("Error: GOOGLE_API_KEY environment variable not set")
|
||||
print("Please set it with: export GOOGLE_API_KEY='your-api-key'")
|
||||
return
|
||||
|
||||
print("=== Gemini Embedding Example ===\n")
|
||||
|
||||
# Create agents for different tasks
|
||||
researcher = Agent(
|
||||
name="Research Agent",
|
||||
role="Information Researcher",
|
||||
goal="Research and store important information about topics",
|
||||
backstory="Expert at analyzing and documenting information with semantic understanding",
|
||||
llm="gpt-4o-mini" # Using GPT for chat, Gemini for embeddings
|
||||
)
|
||||
|
||||
retriever = Agent(
|
||||
name="Retrieval Agent",
|
||||
role="Information Retriever",
|
||||
goal="Retrieve relevant information from memory using semantic search",
|
||||
backstory="Specialist in finding and presenting stored information",
|
||||
llm="gpt-4o-mini"
|
||||
)
|
||||
|
||||
# Task 1: Store information with semantic meaning
|
||||
store_task = Task(
|
||||
description="""
|
||||
Research and store the following information:
|
||||
1. Gemini is Google's family of multimodal AI models
|
||||
2. Gemini models support text, image, video, and audio understanding
|
||||
3. The embedding models provide semantic representations of text
|
||||
4. Gemini Ultra is the largest and most capable model
|
||||
5. Gemini was announced in December 2023
|
||||
|
||||
Store each fact with its semantic meaning preserved.
|
||||
""",
|
||||
expected_output="Confirmation that all facts have been stored in memory",
|
||||
agent=researcher
|
||||
)
|
||||
|
||||
# Task 2: Semantic retrieval test
|
||||
retrieve_task = Task(
|
||||
description="""
|
||||
Using semantic search, find information about:
|
||||
1. Google's AI capabilities
|
||||
2. Multimodal understanding features
|
||||
3. When was Google's latest AI announced
|
||||
|
||||
Note: Use semantic similarity, not exact keyword matching.
|
||||
""",
|
||||
expected_output="Retrieved information based on semantic meaning",
|
||||
agent=retriever
|
||||
)
|
||||
|
||||
# Configure with Gemini embeddings
|
||||
# Option 1: Using stable text-embedding-004
|
||||
agents = PraisonAIAgents(
|
||||
agents=[researcher, retriever],
|
||||
tasks=[store_task, retrieve_task],
|
||||
verbose=True,
|
||||
memory=True,
|
||||
embedder={
|
||||
"provider": "gemini",
|
||||
"config": {
|
||||
"model": "text-embedding-004",
|
||||
# Optional: specify task type for better results
|
||||
# "task_type": "RETRIEVAL_DOCUMENT"
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
# Alternative: Using experimental model with advanced features
|
||||
# agents = PraisonAIAgents(
|
||||
# agents=[researcher, retriever],
|
||||
# tasks=[store_task, retrieve_task],
|
||||
# verbose=True,
|
||||
# memory=True,
|
||||
# embedder={
|
||||
# "provider": "gemini",
|
||||
# "config": {
|
||||
# "model": "gemini-embedding-exp-03-07",
|
||||
# # Task types: SEMANTIC_SIMILARITY, CLASSIFICATION, CLUSTERING,
|
||||
# # RETRIEVAL_DOCUMENT, RETRIEVAL_QUERY, QUESTION_ANSWERING,
|
||||
# # FACT_VERIFICATION
|
||||
# "task_type": "RETRIEVAL_DOCUMENT"
|
||||
# }
|
||||
# }
|
||||
# )
|
||||
|
||||
# Execute the workflow
|
||||
print("Starting agents with Gemini embeddings...\n")
|
||||
result = agents.start()
|
||||
|
||||
# Demonstrate direct memory access with Gemini embeddings
|
||||
print("\n=== Direct Memory Search Example ===\n")
|
||||
|
||||
if agents.shared_memory:
|
||||
# Search queries that test semantic understanding
|
||||
queries = [
|
||||
"What are Google's latest AI innovations?",
|
||||
"Explain multimodal AI capabilities",
|
||||
"Large language model features"
|
||||
]
|
||||
|
||||
for query in queries:
|
||||
print(f"\nSearching for: '{query}'")
|
||||
results = agents.shared_memory.search_long_term(query, limit=3)
|
||||
|
||||
if results:
|
||||
print(f"Found {len(results)} semantically similar results:")
|
||||
for i, result in enumerate(results, 1):
|
||||
print(f"\n{i}. Relevance Score: {result.get('score', 0):.3f}")
|
||||
print(f" Content: {result.get('text', '')[:150]}...")
|
||||
else:
|
||||
print("No results found")
|
||||
|
||||
print("\n=== Example Complete ===")
|
||||
print("\nKey Points:")
|
||||
print("1. Gemini embeddings provide semantic understanding of text")
|
||||
print("2. Results are based on meaning, not just keyword matching")
|
||||
print("3. Different task types can optimize embedding quality")
|
||||
print("4. Compatible with LiteLLM for easy integration")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,165 @@
|
||||
# Gemini Embedding Support in PraisonAI
|
||||
|
||||
This document describes how to use Google's Gemini embedding models with PraisonAI's memory system.
|
||||
|
||||
## Overview
|
||||
|
||||
PraisonAI now supports configurable embedding models through LiteLLM, including Google's Gemini embedding models. This allows you to use models like `text-embedding-004` or `gemini-embedding-exp-03-07` for semantic search and memory storage.
|
||||
|
||||
## Configuration
|
||||
|
||||
### Default Configuration (OpenAI)
|
||||
|
||||
By default, PraisonAI uses OpenAI's `text-embedding-3-small` model:
|
||||
|
||||
```python
|
||||
from praisonaiagents import PraisonAIAgents
|
||||
|
||||
agents = PraisonAIAgents(
|
||||
agents=[...],
|
||||
tasks=[...],
|
||||
memory=True # Uses default OpenAI embeddings
|
||||
)
|
||||
```
|
||||
|
||||
### Using Gemini Embeddings
|
||||
|
||||
To use Gemini embeddings, configure the `embedder` parameter:
|
||||
|
||||
```python
|
||||
from praisonaiagents import PraisonAIAgents
|
||||
|
||||
agents = PraisonAIAgents(
|
||||
agents=[...],
|
||||
tasks=[...],
|
||||
memory=True,
|
||||
embedder={
|
||||
"provider": "gemini",
|
||||
"config": {
|
||||
"model": "text-embedding-004" # or "gemini-embedding-exp-03-07"
|
||||
}
|
||||
}
|
||||
)
|
||||
```
|
||||
|
||||
## Prerequisites
|
||||
|
||||
1. **API Key**: Set your Google API key:
|
||||
```bash
|
||||
export GOOGLE_API_KEY='your-api-key'
|
||||
```
|
||||
|
||||
2. **Dependencies**: Ensure you have the memory dependencies installed:
|
||||
```bash
|
||||
pip install "praisonaiagents[memory]"
|
||||
```
|
||||
|
||||
## Supported Models
|
||||
|
||||
### Gemini Embedding Models
|
||||
|
||||
- `text-embedding-004` - Stable embedding model
|
||||
- `gemini-embedding-exp-03-07` - Experimental model with advanced features
|
||||
|
||||
### Task Types (Optional)
|
||||
|
||||
Gemini models support task-specific optimizations:
|
||||
- `SEMANTIC_SIMILARITY`
|
||||
- `CLASSIFICATION`
|
||||
- `CLUSTERING`
|
||||
- `RETRIEVAL_DOCUMENT`
|
||||
- `RETRIEVAL_QUERY`
|
||||
- `QUESTION_ANSWERING`
|
||||
- `FACT_VERIFICATION`
|
||||
|
||||
Example with task type:
|
||||
```python
|
||||
embedder={
|
||||
"provider": "gemini",
|
||||
"config": {
|
||||
"model": "text-embedding-004",
|
||||
"task_type": "RETRIEVAL_DOCUMENT"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Complete Example
|
||||
|
||||
```python
|
||||
import os
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
|
||||
# Ensure Google API key is set
|
||||
os.environ["GOOGLE_API_KEY"] = "your-api-key"
|
||||
|
||||
# Create agents
|
||||
researcher = Agent(
|
||||
name="Researcher",
|
||||
role="Information Researcher",
|
||||
goal="Store information with semantic understanding",
|
||||
llm="gpt-4o-mini"
|
||||
)
|
||||
|
||||
# Create task
|
||||
task = Task(
|
||||
description="Research and store information about AI advancements",
|
||||
expected_output="Confirmation of stored information",
|
||||
agent=researcher
|
||||
)
|
||||
|
||||
# Initialize with Gemini embeddings
|
||||
agents = PraisonAIAgents(
|
||||
agents=[researcher],
|
||||
tasks=[task],
|
||||
memory=True,
|
||||
embedder={
|
||||
"provider": "gemini",
|
||||
"config": {
|
||||
"model": "text-embedding-004"
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
# Run the agents
|
||||
agents.start()
|
||||
```
|
||||
|
||||
## Backward Compatibility
|
||||
|
||||
The implementation maintains full backward compatibility:
|
||||
|
||||
1. **No embedder config**: Uses default OpenAI `text-embedding-3-small`
|
||||
2. **Existing configs**: Continue to work without modification
|
||||
3. **Other providers**: Supports any embedding model available through LiteLLM
|
||||
|
||||
## Memory Configuration with Mem0
|
||||
|
||||
When using Mem0 as the memory provider, the embedder configuration is passed through:
|
||||
|
||||
```python
|
||||
memory_config = {
|
||||
"provider": "mem0",
|
||||
"config": {
|
||||
"api_key": "your-mem0-key",
|
||||
"embedder": {
|
||||
"provider": "gemini",
|
||||
"config": {
|
||||
"model": "text-embedding-004"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
1. **API Key Error**: Ensure `GOOGLE_API_KEY` is set in your environment
|
||||
2. **Model Not Found**: Verify the model name is correct
|
||||
3. **LiteLLM Error**: Ensure litellm is installed and up to date
|
||||
4. **Embedding Size Mismatch**: When switching models, you may need to clear the vector database as different models produce different embedding dimensions
|
||||
|
||||
## See Also
|
||||
|
||||
- [Gemini API Documentation](https://ai.google.dev/gemini-api/docs/embeddings)
|
||||
- [LiteLLM Embedding Models](https://docs.litellm.ai/docs/embedding/supported_embedding)
|
||||
- Example: `/examples/python/memory/gemini-embedding-example.py`
|
||||
@@ -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?")
|
||||
@@ -0,0 +1,215 @@
|
||||
# Gemini Internal Tools Examples
|
||||
|
||||
This directory contains examples demonstrating how to use Google Gemini's built-in internal tools through PraisonAI. These tools are natively supported by Gemini models and provide powerful capabilities without requiring external tool implementations.
|
||||
|
||||
## Available Internal Tools
|
||||
|
||||
### 1. Google Search (`googleSearch`)
|
||||
- **Purpose**: Real-time web search with automatic result grounding
|
||||
- **Use Cases**: Current events, latest information, fact-checking
|
||||
- **Example**: `gemini-google-search.py`
|
||||
|
||||
### 2. URL Context (`urlContext`)
|
||||
- **Purpose**: Fetch and analyze content from specific URLs
|
||||
- **Use Cases**: Document analysis, web content summarization, research
|
||||
- **Example**: `gemini-url-context.py`
|
||||
|
||||
### 3. Code Execution (`codeExecution`)
|
||||
- **Purpose**: Execute Python code snippets within the conversation
|
||||
- **Use Cases**: Calculations, data analysis, code validation
|
||||
- **Example**: `gemini-code-execution.py`
|
||||
|
||||
## Prerequisites
|
||||
|
||||
1. **Gemini API Key**: Set your Google AI Studio API key
|
||||
```bash
|
||||
export GEMINI_API_KEY="your-api-key-here"
|
||||
```
|
||||
|
||||
2. **Compatible Model**: Use Gemini models that support internal tools:
|
||||
- `gemini/gemini-2.0-flash` (recommended)
|
||||
- `gemini/gemini-2.0-flash-thinking-exp`
|
||||
- Other Gemini 2.0+ models
|
||||
|
||||
3. **PraisonAI Installation**: Ensure you have the latest version
|
||||
```bash
|
||||
pip install "praisonaiagents[llm]"
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
### Individual Tool Examples
|
||||
|
||||
1. **Google Search Example** (`gemini-google-search.py`)
|
||||
```python
|
||||
agent = Agent(
|
||||
instructions="Research assistant with web search",
|
||||
llm="gemini/gemini-2.0-flash",
|
||||
tools=[{"googleSearch": {}}]
|
||||
)
|
||||
|
||||
response = agent.start("What's the latest news about AI?")
|
||||
```
|
||||
|
||||
2. **URL Context Example** (`gemini-url-context.py`)
|
||||
```python
|
||||
agent = Agent(
|
||||
instructions="Content analyzer",
|
||||
llm="gemini/gemini-2.0-flash",
|
||||
tools=[{"urlContext": {}}]
|
||||
)
|
||||
|
||||
response = agent.start("Summarize this: https://example.com/article")
|
||||
```
|
||||
|
||||
3. **Code Execution Example** (`gemini-code-execution.py`)
|
||||
```python
|
||||
agent = Agent(
|
||||
instructions="Data analyst with code execution",
|
||||
llm="gemini/gemini-2.0-flash",
|
||||
tools=[{"codeExecution": {}}]
|
||||
)
|
||||
|
||||
response = agent.start("Calculate compound interest for $10,000 at 5% for 10 years")
|
||||
```
|
||||
|
||||
### Combined Tools Example
|
||||
|
||||
**All Tools Together** (`gemini-internal-tools-combined.py`)
|
||||
```python
|
||||
agent = Agent(
|
||||
instructions="Advanced research assistant",
|
||||
llm="gemini/gemini-2.0-flash",
|
||||
tools=[
|
||||
{"googleSearch": {}},
|
||||
{"urlContext": {}},
|
||||
{"codeExecution": {}}
|
||||
]
|
||||
)
|
||||
|
||||
# Now the agent can search, analyze URLs, and execute code as needed
|
||||
```
|
||||
|
||||
## How It Works
|
||||
|
||||
### PraisonAI Integration
|
||||
|
||||
PraisonAI's tool system is designed to pass tools directly to LiteLLM without modification:
|
||||
|
||||
1. **Tool Definition**: Define tools using the special internal tool syntax
|
||||
```python
|
||||
tools=[{"googleSearch": {}}] # Special format for internal tools
|
||||
```
|
||||
|
||||
2. **Pass-Through**: PraisonAI passes these tools directly to LiteLLM
|
||||
3. **Execution**: LiteLLM sends them to Gemini as internal tool configurations
|
||||
4. **Results**: Gemini executes the tools natively and returns integrated responses
|
||||
|
||||
### Mixing with External Tools
|
||||
|
||||
You can combine internal tools with custom external tools:
|
||||
|
||||
```python
|
||||
def custom_calculator(expression: str) -> str:
|
||||
"""Custom calculator function - safely evaluates basic math expressions"""
|
||||
import ast
|
||||
import operator
|
||||
|
||||
# Define safe operations
|
||||
ops = {
|
||||
ast.Add: operator.add,
|
||||
ast.Sub: operator.sub,
|
||||
ast.Mult: operator.mul,
|
||||
ast.Div: operator.truediv,
|
||||
ast.Pow: operator.pow,
|
||||
ast.USub: operator.neg,
|
||||
}
|
||||
|
||||
def eval_expr(node):
|
||||
if isinstance(node, ast.Constant): # Numbers
|
||||
return node.value
|
||||
elif isinstance(node, ast.BinOp): # Binary operations
|
||||
return ops[type(node.op)](eval_expr(node.left), eval_expr(node.right))
|
||||
elif isinstance(node, ast.UnaryOp): # Unary operations
|
||||
return ops[type(node.op)](eval_expr(node.operand))
|
||||
else:
|
||||
raise TypeError(f"Unsupported operation: {type(node)}")
|
||||
|
||||
try:
|
||||
return str(eval_expr(ast.parse(expression, mode='eval').body))
|
||||
except Exception as e:
|
||||
return f"Error: {e}"
|
||||
|
||||
agent = Agent(
|
||||
tools=[
|
||||
{"googleSearch": {}}, # Internal tool
|
||||
{"codeExecution": {}}, # Internal tool
|
||||
custom_calculator # External tool
|
||||
]
|
||||
)
|
||||
```
|
||||
|
||||
## Running the Examples
|
||||
|
||||
1. **Set API Key**:
|
||||
```bash
|
||||
export GEMINI_API_KEY="your-api-key"
|
||||
```
|
||||
|
||||
2. **Run Individual Examples**:
|
||||
```bash
|
||||
python gemini-google-search.py
|
||||
python gemini-url-context.py
|
||||
python gemini-code-execution.py
|
||||
```
|
||||
|
||||
3. **Run Combined Example**:
|
||||
```bash
|
||||
python gemini-internal-tools-combined.py
|
||||
```
|
||||
|
||||
## Benefits Over External Tools
|
||||
|
||||
### Advantages of Internal Tools
|
||||
|
||||
1. **Native Integration**: No need to implement or maintain external tool code
|
||||
2. **Optimized Performance**: Tools are executed within Gemini's environment
|
||||
3. **Automatic Grounding**: Search results are automatically integrated into responses
|
||||
4. **No Rate Limits**: No separate API calls or rate limiting concerns
|
||||
5. **Security**: Code execution is sandboxed within Gemini's environment
|
||||
|
||||
### When to Use External Tools
|
||||
|
||||
- When you need specific custom logic
|
||||
- When you require integration with private APIs
|
||||
- When you need persistent data storage
|
||||
- When you want full control over tool behavior
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
1. **API Key Error**: Ensure `GEMINI_API_KEY` is set correctly
|
||||
2. **Model Not Supported**: Use Gemini 2.0+ models for internal tools
|
||||
3. **Tool Not Available**: Some tools may have regional or quota restrictions
|
||||
|
||||
### Debug Mode
|
||||
|
||||
Enable verbose logging to see tool usage:
|
||||
```python
|
||||
agent = Agent(
|
||||
# ... config
|
||||
verbose=True # Shows detailed tool usage
|
||||
)
|
||||
```
|
||||
|
||||
## References
|
||||
|
||||
- [Gemini API: Google Search Grounding](https://ai.google.dev/gemini-api/docs/google-search)
|
||||
- [Gemini API: URL Context](https://ai.google.dev/gemini-api/docs/url-context)
|
||||
- [Gemini API: Code Execution](https://ai.google.dev/gemini-api/docs/code-execution)
|
||||
- [LiteLLM Gemini Provider Documentation](https://docs.litellm.ai/docs/providers/gemini)
|
||||
|
||||
## Contributing
|
||||
|
||||
If you create additional examples or find improvements, please contribute back to the PraisonAI project!
|
||||
@@ -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,99 @@
|
||||
"""
|
||||
Gemini Code Execution Tool Example
|
||||
|
||||
This example demonstrates how to use Gemini's built-in Code Execution functionality
|
||||
through PraisonAI. The Code Execution tool allows the model to run Python code
|
||||
snippets directly within the conversation for dynamic computation and validation.
|
||||
|
||||
Prerequisites:
|
||||
- Set GEMINI_API_KEY environment variable
|
||||
- Use a Gemini model that supports internal tools (gemini-2.0-flash, etc.)
|
||||
|
||||
Features:
|
||||
- Direct Python code execution within the model
|
||||
- Real-time calculations and data processing
|
||||
- Code validation and testing
|
||||
- Mathematical computations and visualizations
|
||||
"""
|
||||
|
||||
from praisonaiagents import Agent
|
||||
|
||||
# Ensure you have your Gemini API key set
|
||||
# import os; os.environ["GEMINI_API_KEY"] = "your-api-key-here"
|
||||
|
||||
def main():
|
||||
# Create agent with Code Execution internal tool
|
||||
agent = Agent(
|
||||
instructions="""You are a data analyst and programmer that can execute Python code.
|
||||
Use the Code Execution tool to perform calculations, analyze data, create visualizations,
|
||||
and validate logic. Always show your work by executing relevant code snippets.""",
|
||||
|
||||
llm="gemini/gemini-2.0-flash",
|
||||
|
||||
# Enable Code Execution internal tool
|
||||
tools=[{"codeExecution": {}}],
|
||||
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Example tasks that benefit from code execution
|
||||
tasks = [
|
||||
"Calculate the compound interest on $10,000 invested at 5% annual rate for 10 years, compounded monthly. Show the calculation step by step.",
|
||||
|
||||
"Generate the first 20 Fibonacci numbers and find their sum. Also calculate the ratio of consecutive Fibonacci numbers.",
|
||||
|
||||
"Create a simple linear regression model for the data points: (1,2), (2,4), (3,6), (4,8), (5,10). Calculate the R-squared value.",
|
||||
|
||||
"Solve the quadratic equation 2x² + 5x - 3 = 0 using the quadratic formula. Verify the solutions by substituting back.",
|
||||
|
||||
"Calculate the statistical summary (mean, median, mode, standard deviation) for this dataset: [12, 15, 18, 12, 20, 25, 18, 12, 22, 30, 15, 18]",
|
||||
|
||||
"Write a function to check if a number is prime, then find all prime numbers between 1 and 100.",
|
||||
|
||||
"Calculate the area under the curve y = x² from x = 0 to x = 5 using numerical integration (trapezoidal rule)."
|
||||
]
|
||||
|
||||
print("=== Gemini Code Execution Tool Demo ===\n")
|
||||
|
||||
for i, task in enumerate(tasks, 1):
|
||||
print(f"Task {i}: {task}")
|
||||
print("-" * 80)
|
||||
|
||||
try:
|
||||
response = agent.start(task)
|
||||
print(f"Response: {response}")
|
||||
print("\n" + "="*100 + "\n")
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error: {e}")
|
||||
print("\n" + "="*100 + "\n")
|
||||
|
||||
def demonstrate_direct_usage():
|
||||
"""
|
||||
Example of how the Code Execution tool works at the LiteLLM level
|
||||
(for reference - this requires direct LiteLLM usage)
|
||||
"""
|
||||
print("=== Direct LiteLLM Code Execution Usage (Reference) ===")
|
||||
print("""
|
||||
# This is how it works at the LiteLLM level:
|
||||
|
||||
import litellm
|
||||
import os
|
||||
|
||||
os.environ["GEMINI_API_KEY"] = "your-api-key"
|
||||
|
||||
response = litellm.completion(
|
||||
model="gemini/gemini-2.0-flash",
|
||||
messages=[{
|
||||
"role": "user",
|
||||
"content": "Calculate the factorial of 10 and show the code"
|
||||
}],
|
||||
tools=[{"codeExecution": {}}],
|
||||
)
|
||||
|
||||
print(response.choices[0].message.content)
|
||||
""")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
demonstrate_direct_usage()
|
||||
@@ -0,0 +1,63 @@
|
||||
"""
|
||||
Gemini Google Search Tool Example
|
||||
|
||||
This example demonstrates how to use Gemini's built-in Google Search functionality
|
||||
through PraisonAI. The Google Search tool allows the model to perform real-time
|
||||
web searches and ground responses in current information.
|
||||
|
||||
Prerequisites:
|
||||
- Set GEMINI_API_KEY environment variable
|
||||
- Use a Gemini model that supports internal tools (gemini-2.0-flash, etc.)
|
||||
|
||||
Features:
|
||||
- Real-time web search capabilities
|
||||
- Automatic grounding of responses in search results
|
||||
- No need to implement external search tools
|
||||
"""
|
||||
|
||||
from praisonaiagents import Agent
|
||||
|
||||
# Ensure you have your Gemini API key set
|
||||
# import os; os.environ["GEMINI_API_KEY"] = "your-api-key-here"
|
||||
|
||||
def main():
|
||||
# Create agent with Google Search internal tool
|
||||
agent = Agent(
|
||||
instructions="""You are a research assistant that can search the web for current information.
|
||||
Use the Google Search tool to find up-to-date information when answering questions.
|
||||
Always cite your sources and indicate when information comes from search results.""",
|
||||
|
||||
llm="gemini/gemini-2.0-flash",
|
||||
|
||||
# Enable Google Search internal tool
|
||||
tools=[{"googleSearch": {}}],
|
||||
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Example queries that benefit from real-time search
|
||||
queries = [
|
||||
"What's the latest news about AI developments this week?",
|
||||
"What's the current weather in San Francisco?",
|
||||
"What are the latest stock prices for major tech companies?",
|
||||
"What are the most recent breakthroughs in quantum computing?",
|
||||
"Who won the latest major sports championships?"
|
||||
]
|
||||
|
||||
print("=== Gemini Google Search Tool Demo ===\n")
|
||||
|
||||
for i, query in enumerate(queries, 1):
|
||||
print(f"Query {i}: {query}")
|
||||
print("-" * 50)
|
||||
|
||||
try:
|
||||
response = agent.start(query)
|
||||
print(f"Response: {response}")
|
||||
print("\n" + "="*80 + "\n")
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error: {e}")
|
||||
print("\n" + "="*80 + "\n")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,187 @@
|
||||
"""
|
||||
Gemini Internal Tools Combined Example
|
||||
|
||||
This example demonstrates how to use all three of Gemini's built-in internal tools
|
||||
together through PraisonAI:
|
||||
1. Google Search - for real-time web information
|
||||
2. URL Context - for analyzing web content
|
||||
3. Code Execution - for computations and analysis
|
||||
|
||||
Prerequisites:
|
||||
- Set GEMINI_API_KEY environment variable
|
||||
- Use a Gemini model that supports internal tools (gemini-2.0-flash, etc.)
|
||||
|
||||
Features:
|
||||
- Multi-tool agent combining search, content analysis, and computation
|
||||
- Real-world research and analysis workflows
|
||||
- Comprehensive data gathering and processing capabilities
|
||||
"""
|
||||
|
||||
from praisonaiagents import Agent
|
||||
|
||||
# Ensure you have your Gemini API key set
|
||||
# import os; os.environ["GEMINI_API_KEY"] = "your-api-key-here"
|
||||
|
||||
def main():
|
||||
# Create agent with all Gemini internal tools enabled
|
||||
agent = Agent(
|
||||
instructions="""You are an advanced research and analysis assistant with access to:
|
||||
1. Google Search - for finding current information
|
||||
2. URL Context - for analyzing web content
|
||||
3. Code Execution - for calculations and data processing
|
||||
|
||||
Use these tools strategically to provide comprehensive, well-researched, and
|
||||
analytically sound responses. Always show your work and cite sources.""",
|
||||
|
||||
llm="gemini/gemini-2.0-flash",
|
||||
|
||||
# Enable all three Gemini internal tools
|
||||
tools=[
|
||||
{"googleSearch": {}},
|
||||
{"urlContext": {}},
|
||||
{"codeExecution": {}}
|
||||
],
|
||||
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Complex tasks that benefit from multiple internal tools
|
||||
complex_tasks = [
|
||||
"""Research the current market cap of the top 5 technology companies,
|
||||
then calculate their combined market value and determine what percentage
|
||||
each company represents of the total. Present the results in a formatted table.""",
|
||||
|
||||
"""Find recent research papers about large language models from arXiv,
|
||||
analyze the abstracts of 2-3 papers, and calculate the average number
|
||||
of authors across these papers.""",
|
||||
|
||||
"""Look up the current population of the 10 largest cities in the world,
|
||||
then calculate statistical measures (mean, median, standard deviation)
|
||||
and create a simple visualization of the data distribution.""",
|
||||
|
||||
"""Research the latest Python release notes, analyze the key new features,
|
||||
and write example code demonstrating 2-3 of the most important new features.""",
|
||||
|
||||
"""Find information about recent climate data, analyze a specific dataset
|
||||
or report, and perform calculations to show trends or comparisons over time."""
|
||||
]
|
||||
|
||||
print("=== Gemini Combined Internal Tools Demo ===\n")
|
||||
|
||||
for i, task in enumerate(complex_tasks, 1):
|
||||
print(f"Complex Task {i}:")
|
||||
print(task)
|
||||
print("-" * 100)
|
||||
|
||||
try:
|
||||
response = agent.start(task)
|
||||
print(f"Response: {response}")
|
||||
print("\n" + "="*120 + "\n")
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error: {e}")
|
||||
print("\n" + "="*120 + "\n")
|
||||
|
||||
def demonstrate_tool_synergy():
|
||||
"""
|
||||
Example showing how the tools work together for a research workflow
|
||||
"""
|
||||
print("=== Tool Synergy Example ===")
|
||||
|
||||
agent = Agent(
|
||||
instructions="""You are a market research analyst. Use all available tools
|
||||
to gather information, analyze content, and perform calculations as needed.""",
|
||||
|
||||
llm="gemini/gemini-2.0-flash",
|
||||
tools=[
|
||||
{"googleSearch": {}},
|
||||
{"urlContext": {}},
|
||||
{"codeExecution": {}}
|
||||
],
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Multi-step research task
|
||||
research_query = """
|
||||
Conduct a mini market analysis on electric vehicle adoption:
|
||||
1. Search for recent statistics on global EV sales
|
||||
2. Find and analyze a recent report or article about EV market trends
|
||||
3. Calculate the year-over-year growth rate if you can find data for multiple years
|
||||
4. Provide a summary with key insights and numerical analysis
|
||||
"""
|
||||
|
||||
print("Research Query:", research_query)
|
||||
print("-" * 80)
|
||||
|
||||
try:
|
||||
response = agent.start(research_query)
|
||||
print(f"Research Results: {response}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error: {e}")
|
||||
|
||||
def show_configuration_options():
|
||||
"""
|
||||
Show different ways to configure the internal tools
|
||||
"""
|
||||
print("\n=== Configuration Examples ===")
|
||||
print("""
|
||||
# Basic usage (all tools with default settings)
|
||||
tools=[
|
||||
{"googleSearch": {}},
|
||||
{"urlContext": {}},
|
||||
{"codeExecution": {}}
|
||||
]
|
||||
|
||||
# Can also be used individually
|
||||
tools=[{"googleSearch": {}}] # Only Google Search
|
||||
tools=[{"urlContext": {}}] # Only URL Context
|
||||
tools=[{"codeExecution": {}}] # Only Code Execution
|
||||
|
||||
# Mix with custom tools
|
||||
from praisonaiagents import Agent
|
||||
|
||||
def custom_calculator(expression: str) -> str:
|
||||
'''Custom calculator function - safely evaluates basic math expressions'''
|
||||
import ast
|
||||
import operator
|
||||
|
||||
# Define safe operations
|
||||
ops = {
|
||||
ast.Add: operator.add,
|
||||
ast.Sub: operator.sub,
|
||||
ast.Mult: operator.mul,
|
||||
ast.Div: operator.truediv,
|
||||
ast.Pow: operator.pow,
|
||||
ast.USub: operator.neg,
|
||||
}
|
||||
|
||||
def eval_expr(node):
|
||||
if isinstance(node, ast.Constant): # Numbers
|
||||
return node.value
|
||||
elif isinstance(node, ast.BinOp): # Binary operations
|
||||
return ops[type(node.op)](eval_expr(node.left), eval_expr(node.right))
|
||||
elif isinstance(node, ast.UnaryOp): # Unary operations
|
||||
return ops[type(node.op)](eval_expr(node.operand))
|
||||
else:
|
||||
raise TypeError(f"Unsupported operation: {type(node)}")
|
||||
|
||||
try:
|
||||
return str(eval_expr(ast.parse(expression, mode='eval').body))
|
||||
except Exception as e:
|
||||
return f"Error: {e}"
|
||||
|
||||
agent = Agent(
|
||||
tools=[
|
||||
{"googleSearch": {}}, # Gemini internal tool
|
||||
{"codeExecution": {}}, # Gemini internal tool
|
||||
custom_calculator # Custom external tool
|
||||
]
|
||||
)
|
||||
""")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
print("\n" + "="*50)
|
||||
demonstrate_tool_synergy()
|
||||
show_configuration_options()
|
||||
@@ -0,0 +1,115 @@
|
||||
"""
|
||||
Gemini URL Context Tool Example
|
||||
|
||||
This example demonstrates how to use Gemini's built-in URL Context functionality
|
||||
through PraisonAI. The URL Context tool allows the model to fetch and analyze
|
||||
content from specific URLs in real-time.
|
||||
|
||||
Prerequisites:
|
||||
- Set GEMINI_API_KEY environment variable
|
||||
- Use a Gemini model that supports internal tools (gemini-2.0-flash, etc.)
|
||||
|
||||
Features:
|
||||
- Real-time URL content fetching
|
||||
- Automatic content analysis and summarization
|
||||
- Support for various web content types
|
||||
- Access to URL metadata through response.model_extra
|
||||
"""
|
||||
|
||||
from praisonaiagents import Agent
|
||||
|
||||
# Ensure you have your Gemini API key set
|
||||
# import os; os.environ["GEMINI_API_KEY"] = "your-api-key-here"
|
||||
|
||||
def main():
|
||||
# Create agent with URL Context internal tool
|
||||
agent = Agent(
|
||||
instructions="""You are a content analyst that can fetch and analyze web content.
|
||||
Use the URL Context tool to access and analyze content from provided URLs.
|
||||
Provide detailed summaries, extract key information, and answer questions about the content.""",
|
||||
|
||||
llm="gemini/gemini-2.0-flash",
|
||||
|
||||
# Enable URL Context internal tool
|
||||
tools=[{"urlContext": {}}],
|
||||
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Example URLs for analysis
|
||||
url_tasks = [
|
||||
{
|
||||
"url": "https://ai.google.dev/gemini-api/docs/models",
|
||||
"task": "Summarize the key information about Gemini models and their capabilities"
|
||||
},
|
||||
{
|
||||
"url": "https://github.com/MervinPraison/PraisonAI",
|
||||
"task": "Analyze this GitHub repository and explain what PraisonAI does"
|
||||
},
|
||||
{
|
||||
"url": "https://docs.python.org/3/tutorial/introduction.html",
|
||||
"task": "Extract the main learning objectives from this Python tutorial"
|
||||
},
|
||||
{
|
||||
"url": "https://arxiv.org/abs/2301.00234",
|
||||
"task": "Provide a summary of this research paper's abstract and key contributions"
|
||||
}
|
||||
]
|
||||
|
||||
print("=== Gemini URL Context Tool Demo ===\n")
|
||||
|
||||
for i, item in enumerate(url_tasks, 1):
|
||||
print(f"Analysis {i}: {item['url']}")
|
||||
print(f"Task: {item['task']}")
|
||||
print("-" * 50)
|
||||
|
||||
# Combine URL and task in the query
|
||||
query = f"{item['task']}: {item['url']}"
|
||||
|
||||
try:
|
||||
response = agent.start(query)
|
||||
print(f"Analysis: {response}")
|
||||
|
||||
# Note: URL metadata access requires direct LiteLLM response
|
||||
# In PraisonAI, this would need to be accessed through the LLM response
|
||||
print(f"\nAnalyzed URL: {item['url']}")
|
||||
print("\n" + "="*80 + "\n")
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error: {e}")
|
||||
print("\n" + "="*80 + "\n")
|
||||
|
||||
def demonstrate_direct_usage():
|
||||
"""
|
||||
Example of how the URL Context tool works at the LiteLLM level
|
||||
(for reference - this requires direct LiteLLM usage)
|
||||
"""
|
||||
print("=== Direct LiteLLM URL Context Usage (Reference) ===")
|
||||
print("""
|
||||
# This is how it works at the LiteLLM level:
|
||||
|
||||
import litellm
|
||||
import os
|
||||
|
||||
os.environ["GEMINI_API_KEY"] = "your-api-key"
|
||||
|
||||
response = litellm.completion(
|
||||
model="gemini/gemini-2.0-flash",
|
||||
messages=[{
|
||||
"role": "user",
|
||||
"content": "Summarize this document: https://ai.google.dev/gemini-api/docs/models"
|
||||
}],
|
||||
tools=[{"urlContext": {}}],
|
||||
)
|
||||
|
||||
# Access URL metadata
|
||||
if hasattr(response, 'model_extra') and 'vertex_ai_url_context_metadata' in response.model_extra:
|
||||
url_context_metadata = response.model_extra['vertex_ai_url_context_metadata']
|
||||
urlMetadata = url_context_metadata[0]['urlMetadata'][0]
|
||||
print(f"Retrieved URL: {urlMetadata['retrievedUrl']}")
|
||||
print(f"Retrieval Status: {urlMetadata['urlRetrievalStatus']}")
|
||||
""")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
demonstrate_direct_usage()
|
||||
@@ -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?")
|
||||
@@ -0,0 +1,13 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a competitor intelligence AI agent. "
|
||||
"Help users analyze competitors, market trends, and business intelligence "
|
||||
"to provide strategic insights and competitive advantages.",
|
||||
llm="xai/grok-4"
|
||||
)
|
||||
|
||||
response = agent.start(
|
||||
"I need to analyze my main competitor's pricing strategy and market positioning. "
|
||||
"Can you help me gather insights?"
|
||||
)
|
||||
@@ -0,0 +1,13 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a finance AI agent. "
|
||||
"Help users with financial analysis, investment strategies, "
|
||||
"budget planning, and market trend analysis for informed decision making.",
|
||||
llm="xai/grok-4"
|
||||
)
|
||||
|
||||
response = agent.start(
|
||||
"I need to analyze my investment portfolio and create a diversification strategy. "
|
||||
"Can you help me optimize my financial planning?"
|
||||
)
|
||||
@@ -0,0 +1,13 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a game design AI agent. "
|
||||
"Help users with game concept development, mechanics design, "
|
||||
"and creative storytelling for various gaming platforms and genres.",
|
||||
llm="xai/grok-4"
|
||||
)
|
||||
|
||||
response = agent.start(
|
||||
"I want to create a mobile puzzle game concept. "
|
||||
"Can you help me design engaging gameplay mechanics and story elements?"
|
||||
)
|
||||
@@ -0,0 +1,13 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a legal AI agent. "
|
||||
"Help users with legal document analysis, contract review, "
|
||||
"and legal advice while ensuring compliance and risk assessment.",
|
||||
llm="xai/grok-4"
|
||||
)
|
||||
|
||||
response = agent.start(
|
||||
"I need to review a software licensing agreement. "
|
||||
"Can you help me identify potential risks and key terms?"
|
||||
)
|
||||
@@ -0,0 +1,13 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a recruitment AI agent. "
|
||||
"Help users with candidate screening, job posting optimization, "
|
||||
"and recruitment process automation to find the best talent.",
|
||||
llm="xai/grok-4"
|
||||
)
|
||||
|
||||
response = agent.start(
|
||||
"I need to create a job posting for a senior software engineer position. "
|
||||
"Can you help me write an attractive and comprehensive job description?"
|
||||
)
|
||||
@@ -0,0 +1,13 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are an AI services agency agent. "
|
||||
"Help users with comprehensive business services including marketing, "
|
||||
"content creation, strategy, and operational optimization using CrewAI framework.",
|
||||
llm="xai/grok-4"
|
||||
)
|
||||
|
||||
response = agent.start(
|
||||
"I need help with my startup's marketing strategy and content creation. "
|
||||
"Can you provide a comprehensive plan?"
|
||||
)
|
||||
@@ -0,0 +1,13 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are an AI teaching agent. "
|
||||
"Help users with educational content creation, lesson planning, "
|
||||
"and personalized learning experiences across various subjects.",
|
||||
llm="xai/grok-4"
|
||||
)
|
||||
|
||||
response = agent.start(
|
||||
"I need to create a lesson plan for teaching Python programming to beginners. "
|
||||
"Can you help me design an engaging curriculum?"
|
||||
)
|
||||
@@ -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.
@@ -0,0 +1,13 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a multi MCP AI agent. "
|
||||
"Help users integrate and coordinate multiple Model Context Protocol agents "
|
||||
"for complex workflows and cross-platform automation.",
|
||||
llm="xai/grok-4"
|
||||
)
|
||||
|
||||
response = agent.start(
|
||||
"I need to coordinate multiple tools and services for my project. "
|
||||
"Can you help me set up an integrated workflow using MCP agents?"
|
||||
)
|
||||
@@ -0,0 +1,13 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a multimodal coding AI agent. "
|
||||
"Help users with code generation, review, and debugging "
|
||||
"by analyzing both text and visual inputs like screenshots and diagrams.",
|
||||
llm="xai/grok-4"
|
||||
)
|
||||
|
||||
response = agent.start(
|
||||
"I have a screenshot of a UI design and need to generate the corresponding HTML/CSS code. "
|
||||
"Can you help me create the frontend code?"
|
||||
)
|
||||
@@ -0,0 +1,13 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a multimodal design AI agent. "
|
||||
"Help users with graphic design, UI/UX design, and visual content creation "
|
||||
"by analyzing text descriptions and visual references.",
|
||||
llm="xai/grok-4"
|
||||
)
|
||||
|
||||
response = agent.start(
|
||||
"I need to create a logo for my tech startup. "
|
||||
"Can you help me design a modern and professional logo concept?"
|
||||
)
|
||||
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?")
|
||||
@@ -0,0 +1,11 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are an audio tour creation AI agent. "
|
||||
"Help users create engaging audio tours, guided experiences, and interactive storytelling content. "
|
||||
"Provide guidance on script writing, audio production, location-based content, and immersive experiences.",
|
||||
llm="openrouter/moonshotai/kimi-k2"
|
||||
)
|
||||
|
||||
response = agent.start("Hello! I'm your audio tour creation assistant. "
|
||||
"How can I help you create captivating audio experiences today?")
|
||||
@@ -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?")
|
||||
Loaded 100 of 285 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user