mirror of
https://github.com/MervinPraison/PraisonAI.git
synced 2026-11-07 17:33:33 -10:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
68664fdd55 | ||
|
|
bcda52cc44 | ||
|
|
4888dfb993 | ||
|
|
c5a3fc89cc | ||
|
|
ca33559d4c | ||
|
|
b02449dfdb | ||
|
|
c4c0c1c146 | ||
|
|
aa2d7e4c31 | ||
|
|
b339c5b3aa | ||
|
|
e535f98f4e | ||
|
|
bc349ad09f | ||
|
|
5b8da1180e | ||
|
|
8f6d8f0a48 | ||
|
|
3730b4d094 | ||
|
|
7f3810ed98 | ||
|
|
c84a59ab4d | ||
|
|
c6a6bfa827 | ||
|
|
a604cd9584 | ||
|
|
cb043da19c | ||
|
|
7b41444aad | ||
|
|
7c8b77063f | ||
|
|
59eb8d6356 | ||
|
|
89bddc31c6 | ||
|
|
e6e908298b | ||
|
|
2b3509c1d1 | ||
|
|
6e8029055a | ||
|
|
d2c9e8825a | ||
|
|
cd9816e218 | ||
|
|
d400149075 | ||
|
|
73b08e6b76 | ||
|
|
19c3a1f6a7 | ||
|
|
71a7968318 | ||
|
|
1b258229c1 | ||
|
|
d0e09f51f3 | ||
|
|
5adc862ead | ||
|
|
856db54334 | ||
|
|
f94e5bb3d6 | ||
|
|
1cece603ec | ||
|
|
9e2bbb9bbb | ||
|
|
35b4cff7f7 | ||
|
|
a094d1ff30 | ||
|
|
000bdf3418 | ||
|
|
826ff56fc5 | ||
|
|
4bd0195d5d | ||
|
|
812abec2eb | ||
|
|
e58f6deb4b | ||
|
|
f23680c121 | ||
|
|
e569400260 | ||
|
|
75c4d8432c | ||
|
|
6249d14d3f | ||
|
|
32537a227e | ||
|
|
f83ffcdafe | ||
|
|
519aebd271 | ||
|
|
fb4ecf1893 | ||
|
|
5a4cbf8aeb | ||
|
|
885a73f697 | ||
|
|
9336f15e67 | ||
|
|
6d55cfa87e | ||
|
|
0b431b1fe1 | ||
|
|
e252f86ac9 | ||
|
|
ed395de6f3 | ||
|
|
633469d12e | ||
|
|
c5c57dff26 | ||
|
|
573b9efcc1 | ||
|
|
dc4e51ac81 | ||
|
|
08e211c693 | ||
|
|
abd8021925 | ||
|
|
8a6c4eec7f | ||
|
|
4e77a6a019 | ||
|
|
41e33c09e0 | ||
|
|
96f00e2172 | ||
|
|
e858cebed9 | ||
|
|
cca79bd9fc | ||
|
|
4ffbc1b52a | ||
|
|
b948151a14 | ||
|
|
11eee70d9a | ||
|
|
da6a2c1c04 | ||
|
|
731268df5c | ||
|
|
d60021cb40 | ||
|
|
75894f26c1 | ||
|
|
c53e09480a | ||
|
|
2ef506fa8a | ||
|
|
7ce783e59b | ||
|
|
95ffd0c53f | ||
|
|
e1c90bf569 | ||
|
|
5fbd8aa783 | ||
|
|
381c86de79 | ||
|
|
35250e429e | ||
|
|
3027937057 | ||
|
|
d79443868f | ||
|
|
6705e753e8 | ||
|
|
b4d1532512 | ||
|
|
4b5d3b2eda | ||
|
|
a1d4f3ee43 | ||
|
|
b5e930ff2e | ||
|
|
1a6a14f8f2 | ||
|
|
ca69de4c6a | ||
|
|
9b3d36e6d7 | ||
|
|
a9359a0785 | ||
|
|
4cb016c3ca | ||
|
|
d2e4776884 | ||
|
|
193b82aeba | ||
|
|
029de283c4 | ||
|
|
26376a77af | ||
|
|
7cb580bb12 | ||
|
|
06b458cc54 | ||
|
|
e29c2fbe90 | ||
|
|
76032be618 | ||
|
|
80f5ba940b | ||
|
|
65791781e2 | ||
|
|
ee66154b73 | ||
|
|
0dc51060d8 | ||
|
|
2daae1f464 | ||
|
|
81bcda0440 | ||
|
|
e269cc7bf2 | ||
|
|
66e5dfcb41 | ||
|
|
ae3e69a286 | ||
|
|
40ea6fe1aa | ||
|
|
e30a7564be | ||
|
|
fbd0a736f0 | ||
|
|
eea9f757af | ||
|
|
02a8f075a6 | ||
|
|
57c39653d6 | ||
|
|
2f21d0f907 | ||
|
|
e0caaf8421 | ||
|
|
4bc35c3b6e | ||
|
|
4fd9b863a6 | ||
|
|
fc02392ddb | ||
|
|
4564639f18 | ||
|
|
16598104ab | ||
|
|
b5d13a2b7f | ||
|
|
4622bcda43 | ||
|
|
31bae3a231 | ||
|
|
466bcfedd7 | ||
|
|
c24bf80314 | ||
|
|
c36b3aee6e | ||
|
|
08512ba6d3 | ||
|
|
63ebfc0b54 | ||
|
|
b29269071d | ||
|
|
b6a86bf348 | ||
|
|
02ba71be3d | ||
|
|
e60f1c1aa1 | ||
|
|
450f237805 | ||
|
|
66e53fc82e | ||
|
|
7e6ee5f9f2 | ||
|
|
b669b9815d | ||
|
|
6d89cd603e | ||
|
|
6e955b5941 | ||
|
|
87a67b5f5d | ||
|
|
baec9cd0a4 | ||
|
|
e144dc497d | ||
|
|
8a77ab0ab5 | ||
|
|
0034b5c964 | ||
|
|
543c627374 | ||
|
|
93154adf9e | ||
|
|
3ab2462d96 | ||
|
|
aecf65a130 | ||
|
|
0a453d30a2 | ||
|
|
354a2c717b | ||
|
|
62514fbef4 | ||
|
|
f3c77a2e8b | ||
|
|
50dde4fa02 | ||
|
|
bbc4530329 | ||
|
|
aab975bec7 | ||
|
|
50c50fa567 | ||
|
|
68f280634a | ||
|
|
346488fbec | ||
|
|
57b5a1fd8d | ||
|
|
d75a5bb728 | ||
|
|
519ecc025a | ||
|
|
8290b95132 | ||
|
|
3d95e1ff0e | ||
|
|
74405d1bbe | ||
|
|
d307c3857c | ||
|
|
fbe5dddaae | ||
|
|
7e4108918d | ||
|
|
da7e38100e | ||
|
|
848459b816 | ||
|
|
cd63845398 | ||
|
|
7827427dc0 | ||
|
|
0e378d0754 | ||
|
|
206022eb9c | ||
|
|
901ba8074d | ||
|
|
953ee6e7bd | ||
|
|
181d7e1ede | ||
|
|
4039878422 | ||
|
|
461eba18d5 | ||
|
|
331a1de610 | ||
|
|
91632eb5e4 | ||
|
|
ad46225483 | ||
|
|
9af6758eb6 | ||
|
|
aac67a6572 | ||
|
|
2ceff9bfae | ||
|
|
3b7af02bea | ||
|
|
1ee7cfa2ef | ||
|
|
b01bd41574 | ||
|
|
6570e445b8 | ||
|
|
b421bcf925 | ||
|
|
41d0998b76 | ||
|
|
393e0ee33d | ||
|
|
0dce4de4a4 | ||
|
|
7fe4b48c6e | ||
|
|
5286912f34 | ||
|
|
d6cb1c0165 | ||
|
|
08ed3f94dc | ||
|
|
d3bfbc4b92 | ||
|
|
af7081d294 | ||
|
|
3b2f26699e | ||
|
|
7aa61b9155 | ||
|
|
7e37c940d4 | ||
|
|
2199a57dfe | ||
|
|
d49f046322 | ||
|
|
c16c2e38af | ||
|
|
b5df9f323c | ||
|
|
6e4abeef52 | ||
|
|
5656570172 | ||
|
|
c08c7cfedf | ||
|
|
fbbe80fd4d | ||
|
|
cabddd9a22 | ||
|
|
20b838f36a | ||
|
|
cf149a3c2d | ||
|
|
30f6f5706c | ||
|
|
0423c9c4af | ||
|
|
be82abfac3 | ||
|
|
4af6228f89 | ||
|
|
33eaf34ffb | ||
|
|
e2512b38c0 | ||
|
|
b02cda252d | ||
|
|
2a4b369e15 | ||
|
|
c0a9e55f6a | ||
|
|
7c4b28885d | ||
|
|
b0ec8b9a22 | ||
|
|
1b5cf2baea | ||
|
|
b1cc2c31ce | ||
|
|
2a40c57033 | ||
|
|
350d6e6488 | ||
|
|
20a49ffd70 | ||
|
|
4bf9916c5f | ||
|
|
9764483f36 | ||
|
|
ff405be834 | ||
|
|
6d384a96ca | ||
|
|
6770996c8b | ||
|
|
93c7731ccb | ||
|
|
2057c68a20 | ||
|
|
1ca928a2e4 | ||
|
|
66ea9d7148 | ||
|
|
74a71807a6 | ||
|
|
9e92e85a72 | ||
|
|
6d827a45c8 | ||
|
|
aabaaa6318 | ||
|
|
f518bd301a | ||
|
|
834f710cf6 | ||
|
|
ede71a7fbe | ||
|
|
7c751c88a3 | ||
|
|
17f3aab1e1 | ||
|
|
028fa8158d | ||
|
|
c62685adc5 | ||
|
|
60d6178310 | ||
|
|
b198154b71 | ||
|
|
205de2ba0b | ||
|
|
ee668b2711 | ||
|
|
a5bbb65017 | ||
|
|
6296755ebb | ||
|
|
4b6c847260 | ||
|
|
2fc459fe05 | ||
|
|
1c3c2941cc | ||
|
|
6e38a88cd3 | ||
|
|
f0f22bb13d | ||
|
|
a8fa70c455 | ||
|
|
1b4b4a10b5 | ||
|
|
1efdaac18f | ||
|
|
1b2182968f | ||
|
|
5e5a10589e | ||
|
|
6c5e42762f | ||
|
|
afb7e47080 | ||
|
|
e674a2ae84 | ||
|
|
d471d9754a | ||
|
|
9d25b1ed3d | ||
|
|
d0d04bc17e | ||
|
|
1f4e2b1c5a | ||
|
|
88d4241121 | ||
|
|
9e081e9413 | ||
|
|
bc0449b8de | ||
|
|
c262942ba7 | ||
|
|
40e5c13f47 | ||
|
|
5eea991a60 | ||
|
|
209c2a42ae | ||
|
|
efb927137f | ||
|
|
162223162f | ||
|
|
75c856b948 | ||
|
|
85fefac429 | ||
|
|
35b9d46bdf | ||
|
|
5bd3e45be4 | ||
|
|
4c62731e81 | ||
|
|
544672edea | ||
|
|
72dcc91b3a | ||
|
|
75e728f7d7 | ||
|
|
7ddbf98794 | ||
|
|
0213dea12b | ||
|
|
841a7b52c4 | ||
|
|
99506e80cf | ||
|
|
c0d495fd48 | ||
|
|
0e51ed0d6c | ||
|
|
32dce14f96 | ||
|
|
27aaac80c6 | ||
|
|
5a0a3983e4 | ||
|
|
400a4c934e | ||
|
|
e88b0fd47b | ||
|
|
e6c1c0679f | ||
|
|
108aee0a54 | ||
|
|
cb017aad70 | ||
|
|
ea29d3181b | ||
|
|
7f0f265671 | ||
|
|
bc1c508419 | ||
|
|
bd108ba3e7 | ||
|
|
ac5f2649df | ||
|
|
1b64762d54 | ||
|
|
df402bcfdb | ||
|
|
061c8d58b4 | ||
|
|
117c02cf30 | ||
|
|
82c9ff80a7 | ||
|
|
f44b15d73b | ||
|
|
f2c89c2012 | ||
|
|
fd2569e642 | ||
|
|
58efb4b4cd | ||
|
|
35df78874d | ||
|
|
4abe80a563 | ||
|
|
95c15f52fc | ||
|
|
0e2a753cc3 | ||
|
|
660260c6e6 | ||
|
|
f49b5c368c | ||
|
|
39f0c40dcc | ||
|
|
27b10ff3ea | ||
|
|
f63f247bfe | ||
|
|
f3f5f63b22 | ||
|
|
ccf9470f41 | ||
|
|
75cf937581 | ||
|
|
d228a742b7 | ||
|
|
1d7e03b03e | ||
|
|
290570de88 | ||
|
|
542ea8c10d | ||
|
|
843f70b599 | ||
|
|
dee707299d | ||
|
|
7f6e300a9e | ||
|
|
88e9de2914 | ||
|
|
f17daec68b | ||
|
|
f4d54d76e8 | ||
|
|
23e2951724 | ||
|
|
1916b1a108 | ||
|
|
5b99ca8357 | ||
|
|
09ef400c15 | ||
|
|
d5c381890f | ||
|
|
639e53ea9b | ||
|
|
0954fb4d3d | ||
|
|
f5c35f31e9 |
No files matched your search
@@ -0,0 +1,81 @@
|
||||
name: 'Gemini CLI Action'
|
||||
description: 'Uses the Gemini CLI to automate software development tasks.'
|
||||
author: 'Gemini'
|
||||
|
||||
inputs:
|
||||
prompt:
|
||||
description: 'A specific prompt to guide Gemini.'
|
||||
required: false
|
||||
default: 'You are a helpful assistant.'
|
||||
GEMINI_API_KEY:
|
||||
description: 'Your Gemini API key.'
|
||||
required: true
|
||||
OTLP_GCP_WIF_PROVIDER:
|
||||
description: 'The workload identity provider for GCP authentication.'
|
||||
required: false
|
||||
OTLP_GOOGLE_CLOUD_PROJECT:
|
||||
description: 'The Google Cloud project for telemetry.'
|
||||
required: false
|
||||
settings_json:
|
||||
description: |
|
||||
A JSON string to configure the Gemini CLI. This will be written to .gemini/settings.json.
|
||||
To enable observability with Google Cloud, include:
|
||||
{"telemetry": {"enabled": true, "target": "gcp"}, "sandbox": false}
|
||||
required: false
|
||||
version:
|
||||
description: |
|
||||
The version of @google/gemini-cli to execute.
|
||||
Can be a specific version from npm (e.g., '0.1.0', 'latest'), a branch name (e.g., 'main'), or a commit hash.
|
||||
required: false
|
||||
default: 'latest'
|
||||
|
||||
runs:
|
||||
using: "composite"
|
||||
steps:
|
||||
- name: Configure Gemini CLI
|
||||
if: inputs.settings_json != ''
|
||||
run: |
|
||||
mkdir -p .gemini
|
||||
echo "$SETTINGS_JSON" > .gemini/settings.json
|
||||
shell: bash
|
||||
env:
|
||||
SETTINGS_JSON: ${{ inputs.settings_json }}
|
||||
|
||||
- name: Authenticate to Google Cloud for Telemetry
|
||||
if: inputs.OTLP_GCP_WIF_PROVIDER != ''
|
||||
id: auth
|
||||
uses: 'google-github-actions/auth@v2'
|
||||
with:
|
||||
project_id: ${{ inputs.OTLP_GOOGLE_CLOUD_PROJECT }}
|
||||
workload_identity_provider: ${{ inputs.OTLP_GCP_WIF_PROVIDER }}
|
||||
|
||||
- name: Install Gemini CLI
|
||||
id: install
|
||||
run: |
|
||||
if [[ "${{ inputs.version }}" == "latest" || "${{ inputs.version }}" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9\.-]+)?(\+[a-zA-Z0-9\.-]+)?$ ]]; then
|
||||
echo "Installing Gemini CLI from npm: @google/gemini-cli@${{ inputs.version }}"
|
||||
npm install -g @google/gemini-cli@${{ inputs.version }}
|
||||
else
|
||||
echo "Installing Gemini CLI from GitHub: github:google-gemini/gemini-cli#${{ inputs.version }}"
|
||||
npm install -g github:google-gemini/gemini-cli#${{ inputs.version }}
|
||||
fi
|
||||
echo "Verifying installation:"
|
||||
if command -v gemini >/dev/null 2>&1; then
|
||||
gemini --version || echo "Gemini CLI installed successfully (version command not available)"
|
||||
else
|
||||
echo "Error: Gemini CLI not found in PATH"
|
||||
exit 1
|
||||
fi
|
||||
shell: bash
|
||||
|
||||
- name: Run Gemini CLI
|
||||
run: |
|
||||
gemini --yolo --prompt "$PROMPT"
|
||||
shell: bash
|
||||
env:
|
||||
GEMINI_API_KEY: ${{ inputs.GEMINI_API_KEY }}
|
||||
PROMPT: ${{ inputs.prompt }}
|
||||
|
||||
branding:
|
||||
icon: 'terminal'
|
||||
color: 'blue'
|
||||
@@ -0,0 +1,26 @@
|
||||
name: Auto Issue Comment with PR Creation
|
||||
|
||||
on:
|
||||
issues:
|
||||
types: [opened]
|
||||
|
||||
jobs:
|
||||
add-comment:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
issues: write
|
||||
contents: write
|
||||
pull-requests: write
|
||||
actions: read
|
||||
steps:
|
||||
- name: Add automated comment
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
github-token: ${{ secrets.GH_TOKEN }}
|
||||
script: |
|
||||
github.rest.issues.createComment({
|
||||
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. **Please create a PR using gh tool with your changes**.'
|
||||
})
|
||||
@@ -0,0 +1,23 @@
|
||||
name: Auto PR Comment
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened]
|
||||
|
||||
jobs:
|
||||
add-comment:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
pull-requests: write
|
||||
steps:
|
||||
- name: Add automated comment
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
github-token: ${{ secrets.GH_TOKEN }}
|
||||
script: |
|
||||
github.rest.issues.createComment({
|
||||
issue_number: context.issue.number,
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
body: '@claude review this pull request 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.'
|
||||
})
|
||||
+142
-20
@@ -1,4 +1,4 @@
|
||||
name: Claude Code
|
||||
name: Claude Assistant
|
||||
|
||||
on:
|
||||
issue_comment:
|
||||
@@ -6,34 +6,156 @@ 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-response
|
||||
if: success() && needs.claude-response.result == 'success'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
issues: write
|
||||
steps:
|
||||
- name: Check for existing review comment
|
||||
id: check-comment
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
github-token: ${{ secrets.GH_TOKEN }}
|
||||
script: |
|
||||
const reviewText = '@claude review if the changes made are as per the requirements';
|
||||
let comments = [];
|
||||
let issueNumber;
|
||||
|
||||
try {
|
||||
// Determine issue/PR number 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;
|
||||
} 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;
|
||||
} else {
|
||||
// This is a regular issue
|
||||
issueNumber = context.issue.number;
|
||||
}
|
||||
|
||||
comments = await github.rest.issues.listComments({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issueNumber
|
||||
});
|
||||
|
||||
// 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)
|
||||
);
|
||||
|
||||
// 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', false); // If we can't check, don't post
|
||||
}
|
||||
|
||||
- name: Wait 30 seconds before posting comment
|
||||
if: steps.check-comment.outputs.should-post == 'true'
|
||||
run: sleep 30
|
||||
|
||||
- name: Post review comment
|
||||
if: steps.check-comment.outputs.should-post == 'true'
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
github-token: ${{ secrets.GH_TOKEN }}
|
||||
script: |
|
||||
let issueNumber;
|
||||
let isPR = false;
|
||||
|
||||
// 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 - don't post review comment
|
||||
issueNumber = context.issue.number;
|
||||
isPR = false;
|
||||
}
|
||||
|
||||
// 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}`);
|
||||
}
|
||||
@@ -40,5 +40,6 @@ jobs:
|
||||
uses: docker/build-push-action@v2
|
||||
with:
|
||||
context: .
|
||||
file: ./docker/Dockerfile
|
||||
push: true
|
||||
tags: ghcr.io/mervinpraison/praisonai:latest
|
||||
@@ -0,0 +1,76 @@
|
||||
name: Gemini Automated Issue Triage
|
||||
|
||||
on:
|
||||
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
|
||||
contents: read
|
||||
id-token: write
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event.issue.number }}
|
||||
cancel-in-progress: true
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Generate GitHub App Token
|
||||
id: generate_token
|
||||
uses: actions/create-github-app-token@v1
|
||||
with:
|
||||
app-id: ${{ secrets.APP_ID }}
|
||||
private-key: ${{ secrets.PRIVATE_KEY }}
|
||||
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
token: ${{ steps.generate_token.outputs.token }}
|
||||
|
||||
- name: Run Gemini Issue Triage
|
||||
uses: google-gemini/gemini-cli-action@main
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ steps.generate_token.outputs.token }}
|
||||
ISSUE_TITLE: ${{ github.event.issue.title }}
|
||||
ISSUE_BODY: ${{ github.event.issue.body }}
|
||||
ISSUE_NUMBER: ${{ github.event.issue.number }}
|
||||
REPOSITORY: ${{ github.repository }}
|
||||
with:
|
||||
version: 0.1.8-rc.0
|
||||
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
|
||||
OTLP_GCP_WIF_PROVIDER: ${{ secrets.OTLP_GCP_WIF_PROVIDER }}
|
||||
OTLP_GOOGLE_CLOUD_PROJECT: ${{ secrets.OTLP_GOOGLE_CLOUD_PROJECT }}
|
||||
settings_json: |
|
||||
{
|
||||
"coreTools": [
|
||||
"run_shell_command(gh label list)",
|
||||
"run_shell_command(gh issue edit)"
|
||||
],
|
||||
"telemetry": {
|
||||
"enabled": true,
|
||||
"target": "gcp"
|
||||
},
|
||||
"sandbox": false
|
||||
}
|
||||
prompt: |
|
||||
You are an issue triage assistant. Analyze the current GitHub issue and apply the most appropriate existing labels.
|
||||
|
||||
Steps:
|
||||
1. Run: `gh label list --limit 100` to get all available labels.
|
||||
2. Review the issue title and body provided in the environment variables.
|
||||
3. Select the most relevant labels from the existing labels, focusing on kind/*, area/*, and priority/*.
|
||||
4. Apply the selected labels to this issue using: `gh issue edit ISSUE_NUMBER --add-label "label1,label2"`
|
||||
|
||||
Guidelines:
|
||||
- Only use labels that already exist in the repository.
|
||||
- Do not add comments or modify the issue content.
|
||||
- Triage only the current issue.
|
||||
- Assign all applicable kind/*, area/*, and priority/* labels based on the issue content.
|
||||
@@ -0,0 +1,198 @@
|
||||
name: Gemini Issue Review
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
issue_comment:
|
||||
types: [created]
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
issues: write
|
||||
pull-requests: read
|
||||
|
||||
jobs:
|
||||
review-issue:
|
||||
if: >
|
||||
github.event_name == 'workflow_dispatch' ||
|
||||
(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'))
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
|
||||
steps:
|
||||
- name: Generate token
|
||||
id: generate_token
|
||||
uses: actions/create-github-app-token@v1
|
||||
with:
|
||||
app-id: ${{ secrets.APP_ID }}
|
||||
private-key: ${{ secrets.PRIVATE_KEY }}
|
||||
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
token: ${{ steps.generate_token.outputs.token }}
|
||||
|
||||
- name: Set up Git
|
||||
run: |
|
||||
git config --local user.email "[email protected]"
|
||||
git config --local user.name "Gemini Bot"
|
||||
|
||||
- name: Get issue data
|
||||
id: issue_data
|
||||
env:
|
||||
GH_TOKEN: ${{ steps.generate_token.outputs.token }}
|
||||
run: |
|
||||
# Get issue number from event or context
|
||||
if [ "${{ github.event_name }}" = "issue_comment" ]; then
|
||||
ISSUE_NUMBER="${{ github.event.issue.number }}"
|
||||
elif [ "${{ github.event_name }}" = "issues" ]; then
|
||||
ISSUE_NUMBER="${{ github.event.issue.number }}"
|
||||
else
|
||||
echo "Unable to determine issue number"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Get issue details
|
||||
gh issue view $ISSUE_NUMBER --json title,body,labels,assignees > issue_details.json
|
||||
|
||||
# Extract additional instructions from comment if triggered by comment
|
||||
ADDITIONAL_INSTRUCTIONS=""
|
||||
if [ "${{ github.event_name }}" = "issue_comment" ]; then
|
||||
COMMENT_BODY="${{ github.event.comment.body }}"
|
||||
ADDITIONAL_INSTRUCTIONS=$(echo "$COMMENT_BODY" | sed -n 's/.*@gemini[[:space:]]*\(.*\)/\1/p' | head -1)
|
||||
fi
|
||||
|
||||
echo "ISSUE_NUMBER=$ISSUE_NUMBER" >> $GITHUB_OUTPUT
|
||||
echo "ADDITIONAL_INSTRUCTIONS=$ADDITIONAL_INSTRUCTIONS" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Run Gemini CLI
|
||||
uses: ./.github/actions/gemini
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ steps.generate_token.outputs.token }}
|
||||
ISSUE_NUMBER: ${{ steps.issue_data.outputs.ISSUE_NUMBER }}
|
||||
ADDITIONAL_INSTRUCTIONS: ${{ steps.issue_data.outputs.ADDITIONAL_INSTRUCTIONS }}
|
||||
REPOSITORY: ${{ github.repository }}
|
||||
with:
|
||||
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
|
||||
OTLP_GCP_WIF_PROVIDER: ${{ secrets.OTLP_GCP_WIF_PROVIDER }}
|
||||
OTLP_GOOGLE_CLOUD_PROJECT: ${{ secrets.OTLP_GOOGLE_CLOUD_PROJECT }}
|
||||
prompt: |
|
||||
You are a helpful GitHub issue assistant. Your task is to analyze and help with GitHub issues.
|
||||
|
||||
**Issue Details:**
|
||||
- Issue Number: #${ISSUE_NUMBER}
|
||||
- Repository: ${REPOSITORY}
|
||||
- Issue URL: ${{ github.event.issue.html_url }}
|
||||
|
||||
**Additional Instructions:** ${ADDITIONAL_INSTRUCTIONS}
|
||||
|
||||
**CRITICAL: When making code modifications, follow this EXACT workflow:**
|
||||
|
||||
**STEP 1: Analyze the Issue**
|
||||
- Use: `gh issue view ${ISSUE_NUMBER} --json title,body,labels,assignees`
|
||||
- Analyze issue content thoroughly
|
||||
- Search codebase for related files using `glob`, `search_file_content`, `list_directory`
|
||||
|
||||
**STEP 2: If Code Changes Are Needed**
|
||||
Create a new branch with 'gemini/' prefix:
|
||||
- Use: `git checkout -b gemini/issue-${ISSUE_NUMBER}-description`
|
||||
- Example: `git checkout -b gemini/issue-123-fix-sequential-tools`
|
||||
|
||||
**STEP 3: Make Code Modifications**
|
||||
- Use `read_file` to examine existing code
|
||||
- Use `write_file` or `replace` to make changes
|
||||
- Use `search_file_content` to find related code
|
||||
- Make focused, targeted changes to fix the issue
|
||||
|
||||
**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**
|
||||
- Use: `git add .` (or specific files)
|
||||
- Use: `git commit -m "Gemini: [Issue #${ISSUE_NUMBER}] Brief description of fix"`
|
||||
- Use: `git push -u origin gemini/issue-${ISSUE_NUMBER}-description`
|
||||
|
||||
**STEP 6: Create Pull Request**
|
||||
- Use: `gh pr create --title "Fix #${ISSUE_NUMBER}: Issue description" --body "Fixes #${ISSUE_NUMBER}\n\nSummary of changes:\n- Change 1\n- Change 2" --head gemini/issue-${ISSUE_NUMBER}-description --base main`
|
||||
- This will return a PR URL like: https://github.com/repo/pull/123
|
||||
|
||||
**STEP 7: Comment on Issue with Results**
|
||||
Use: `gh issue comment ${ISSUE_NUMBER} -b "MESSAGE"`
|
||||
|
||||
**Your final comment MUST include:**
|
||||
- Summary of what was analyzed
|
||||
- What changes were made (if any)
|
||||
- Link to the created PR (if applicable)
|
||||
- Brief explanation of the solution
|
||||
|
||||
**Example final comment:**
|
||||
```
|
||||
Hi! I've analyzed and fixed this issue.
|
||||
|
||||
**Problem:** Sequential tool calling was getting stuck after first tool call.
|
||||
|
||||
**Solution:** Added proper prompt handling after each tool call in the Ollama model integration.
|
||||
|
||||
**Changes Made:**
|
||||
- Modified `src/praisonai-agents/ollama-sequential.py`
|
||||
- Added continuation prompts for multi-step tool execution
|
||||
|
||||
**Pull Request:** https://github.com/MervinPraison/PraisonAI/pull/856
|
||||
|
||||
The fix is ready for review. Please test and let me know if you encounter any issues!
|
||||
```
|
||||
|
||||
**IMPORTANT NOTES:**
|
||||
- Always create branches with 'gemini/' prefix
|
||||
- Always include issue number in branch name and commit message
|
||||
- Always create PR that references the issue
|
||||
- Always provide PR link in your final response
|
||||
- Use the GITHUB_TOKEN environment variable for authentication
|
||||
|
||||
Please proceed with helping resolve this issue following this exact workflow.
|
||||
|
||||
settings_json: |
|
||||
{
|
||||
"coreTools": [
|
||||
"run_shell_command(echo)",
|
||||
"run_shell_command(gh issue view)",
|
||||
"run_shell_command(gh issue comment)",
|
||||
"run_shell_command(gh issue list)",
|
||||
"run_shell_command(gh issue edit)",
|
||||
"run_shell_command(gh pr create)",
|
||||
"run_shell_command(gh pr view)",
|
||||
"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 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)",
|
||||
"list_directory",
|
||||
"read_file",
|
||||
"read_many_files",
|
||||
"write_file",
|
||||
"replace",
|
||||
"glob",
|
||||
"search_file_content",
|
||||
"web_fetch",
|
||||
"google_web_search",
|
||||
"save_memory"
|
||||
],
|
||||
"telemetry": {
|
||||
"enabled": false,
|
||||
"otlpGcpWifProvider": "${{ secrets.OTLP_GCP_WIF_PROVIDER }}",
|
||||
"googleCloudProject": "${{ secrets.OTLP_GOOGLE_CLOUD_PROJECT }}"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
name: Gemini PR Review
|
||||
|
||||
on:
|
||||
issue_comment:
|
||||
types: [created]
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
pr_number:
|
||||
description: 'PR number to review'
|
||||
required: true
|
||||
type: number
|
||||
|
||||
jobs:
|
||||
review-pr:
|
||||
if: >
|
||||
github.event_name == 'workflow_dispatch' ||
|
||||
(github.event_name == 'issue_comment' &&
|
||||
github.event.issue.pull_request &&
|
||||
contains(github.event.comment.body, '@gemini') &&
|
||||
(github.event.comment.author_association == 'OWNER' ||
|
||||
github.event.comment.author_association == 'MEMBER' ||
|
||||
github.event.comment.author_association == 'COLLABORATOR'))
|
||||
timeout-minutes: 15
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
pull-requests: write
|
||||
issues: write
|
||||
steps:
|
||||
- name: Generate GitHub App Token
|
||||
id: generate_token
|
||||
uses: actions/create-github-app-token@v1
|
||||
with:
|
||||
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: ${{ steps.checkout_ref.outputs.ref }}
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Get PR details
|
||||
id: get_pr
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ steps.generate_token.outputs.token }}
|
||||
run: |
|
||||
if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
|
||||
PR_NUMBER=${{ github.event.inputs.pr_number }}
|
||||
elif [ "${{ github.event_name }}" = "issue_comment" ]; then
|
||||
PR_NUMBER=${{ github.event.issue.number }}
|
||||
else
|
||||
PR_NUMBER=${{ github.event.pull_request.number }}
|
||||
fi
|
||||
|
||||
echo "pr_number=$PR_NUMBER" >> "$GITHUB_OUTPUT"
|
||||
|
||||
# Extract additional instructions from comment (if triggered by comment)
|
||||
ADDITIONAL_INSTRUCTIONS=""
|
||||
if [ "${{ github.event_name }}" = "issue_comment" ]; then
|
||||
COMMENT_BODY="${{ github.event.comment.body }}"
|
||||
ADDITIONAL_INSTRUCTIONS=$(echo "$COMMENT_BODY" | sed 's/.*@gemini//' | xargs)
|
||||
fi
|
||||
echo "additional_instructions=$ADDITIONAL_INSTRUCTIONS" >> "$GITHUB_OUTPUT"
|
||||
|
||||
# Get PR details
|
||||
PR_DATA=$(gh pr view $PR_NUMBER --json title,body,additions,deletions,changedFiles,baseRefName,headRefName)
|
||||
echo "pr_data=$PR_DATA" >> "$GITHUB_OUTPUT"
|
||||
|
||||
# Get file changes
|
||||
CHANGED_FILES=$(gh pr diff $PR_NUMBER --name-only)
|
||||
echo "changed_files<<EOF" >> "$GITHUB_OUTPUT"
|
||||
echo "$CHANGED_FILES" >> "$GITHUB_OUTPUT"
|
||||
echo "EOF" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Run Gemini PR Review
|
||||
uses: ./.github/actions/gemini
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ steps.generate_token.outputs.token }}
|
||||
PR_NUMBER: ${{ steps.get_pr.outputs.pr_number }}
|
||||
PR_DATA: ${{ steps.get_pr.outputs.pr_data }}
|
||||
CHANGED_FILES: ${{ steps.get_pr.outputs.changed_files }}
|
||||
ADDITIONAL_INSTRUCTIONS: ${{ steps.get_pr.outputs.additional_instructions }}
|
||||
REPOSITORY: ${{ github.repository }}
|
||||
with:
|
||||
version: 0.1.8-rc.0
|
||||
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
|
||||
OTLP_GCP_WIF_PROVIDER: ${{ secrets.OTLP_GCP_WIF_PROVIDER }}
|
||||
OTLP_GOOGLE_CLOUD_PROJECT: ${{ secrets.OTLP_GOOGLE_CLOUD_PROJECT }}
|
||||
settings_json: |
|
||||
{
|
||||
"coreTools": [
|
||||
"run_shell_command(echo)",
|
||||
"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 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",
|
||||
"write_file",
|
||||
"replace",
|
||||
"glob",
|
||||
"search_file_content",
|
||||
"web_fetch",
|
||||
"google_web_search",
|
||||
"save_memory"
|
||||
],
|
||||
"telemetry": {
|
||||
"enabled": false,
|
||||
"target": "gcp"
|
||||
},
|
||||
"sandbox": false
|
||||
}
|
||||
prompt: |
|
||||
You are an expert code reviewer and AI assistant for Pull Requests. You can review code AND make modifications to improve the PR.
|
||||
|
||||
**PR Details:**
|
||||
- PR Number: #$PR_NUMBER
|
||||
- Repository: $REPOSITORY
|
||||
- Additional Instructions: $ADDITIONAL_INSTRUCTIONS
|
||||
|
||||
**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
|
||||
- Check for common issues: potential bugs, security vulnerabilities, performance bottlenecks
|
||||
- Verify error handling and edge cases
|
||||
- Look for code style and best practices
|
||||
- Comment on architecture and design decisions if significant
|
||||
- Be constructive and specific in feedback
|
||||
- Highlight both issues and positive aspects
|
||||
- Suggest improvements with examples when possible
|
||||
|
||||
Review Areas:
|
||||
- **Security**: Authentication, authorization, input validation, data sanitization
|
||||
- **Performance**: Algorithms, database queries, caching, resource usage
|
||||
- **Reliability**: Error handling, logging, testing coverage, edge cases
|
||||
- **Maintainability**: Code structure, documentation, naming conventions
|
||||
- **Functionality**: Logic correctness, requirements fulfillment
|
||||
|
||||
Output Format:
|
||||
Structure your review using this exact format with markdown:
|
||||
|
||||
## 📋 Review Summary
|
||||
Provide a brief 2-3 sentence overview of the PR and overall assessment.
|
||||
|
||||
## 🔍 General Feedback
|
||||
- List general observations about code quality
|
||||
- Mention overall patterns or architectural decisions
|
||||
- Highlight positive aspects of the implementation
|
||||
- Note any recurring themes across files
|
||||
|
||||
## 🎯 Specific Feedback
|
||||
Only include sections below that have actual issues. If there are no issues in a priority category, omit that entire section.
|
||||
|
||||
### 🔴 Critical
|
||||
(Only include this section if there are critical issues)
|
||||
Issues that must be addressed before merging (security vulnerabilities, breaking changes, major bugs):
|
||||
- **File: `filename:line`** - Description of critical issue with specific recommendation
|
||||
|
||||
### 🟡 High
|
||||
(Only include this section if there are high priority issues)
|
||||
Important issues that should be addressed (performance problems, design flaws, significant bugs):
|
||||
- **File: `filename:line`** - Description of high priority issue with suggested fix
|
||||
|
||||
### 🟢 Medium
|
||||
(Only include this section if there are medium priority issues)
|
||||
Improvements that would enhance code quality (style issues, minor optimizations, better practices):
|
||||
- **File: `filename:line`** - Description of medium priority improvement
|
||||
|
||||
### 🔵 Low
|
||||
(Only include this section if there are suggestions)
|
||||
Nice-to-have improvements and suggestions (documentation, naming, minor refactoring):
|
||||
- **File: `filename:line`** - Description of suggestion or enhancement
|
||||
|
||||
**Note**: If no specific issues are found in any category, simply state "No specific issues identified in this review."
|
||||
|
||||
## ✅ Highlights
|
||||
(Only include this section if there are positive aspects to highlight)
|
||||
- Mention specific good practices or implementations
|
||||
- Acknowledge well-written code sections
|
||||
- Note improvements from previous versions
|
||||
|
||||
---
|
||||
*Review completed by Gemini CLI*
|
||||
@@ -151,7 +151,7 @@ jobs:
|
||||
return 'INVALID_TYPE'
|
||||
|
||||
print('🔧 Direct PraisonAI API Key Check:')
|
||||
env_api_key = os.environ.get(\\"OPENAI_API_KEY\\", \\"NOT_SET\\")
|
||||
env_api_key = os.environ.get(\"OPENAI_API_KEY\", \"NOT_SET\")
|
||||
print(f'Environment OPENAI_API_KEY: {get_key_display_value(env_api_key)}...')
|
||||
|
||||
from praisonai import PraisonAI
|
||||
@@ -163,7 +163,7 @@ jobs:
|
||||
|
||||
from praisonai.inc.models import PraisonAIModel
|
||||
|
||||
print('\\\\n🧪 Testing PraisonAIModel with explicit API key (CrewAI method):')
|
||||
print('\\n🧪 Testing PraisonAIModel with explicit API key (CrewAI method):')
|
||||
model_with_explicit_key = PraisonAIModel(
|
||||
model='openai/gpt-4o-mini',
|
||||
base_url=praisonai.config_list[0].get('base_url'),
|
||||
|
||||
+3
-1
@@ -75,4 +75,6 @@ agents/praisonaiagents/praisonaiagents.egg-info
|
||||
# Local Netlify folder
|
||||
.netlify
|
||||
.qodo
|
||||
CopilotKit*
|
||||
CopilotKit*
|
||||
.gemini
|
||||
issue_details.json
|
||||
+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.43" \
|
||||
"praisonai>=2.2.61" \
|
||||
"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.43" \
|
||||
"praisonai>=2.2.61" \
|
||||
"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.43" \
|
||||
"praisonai>=2.2.61" \
|
||||
"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.43" \
|
||||
"praisonai>=2.2.61" \
|
||||
"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.43`
|
||||
- PraisonAI: `>=2.2.61`
|
||||
- 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.43" "praisonaiagents==0.0.92"
|
||||
RUN pip install "praisonai==2.2.61" "praisonaiagents==0.0.92"
|
||||
```
|
||||
|
||||
## 🌐 Production Deployment
|
||||
|
||||
@@ -0,0 +1,482 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "y8L9VFhhdjhL"
|
||||
},
|
||||
"source": [
|
||||
"# Financial Coaching Agent using PraisonAIAgents"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "6UxqTg7pdkm-"
|
||||
},
|
||||
"source": [
|
||||
"This notebook demonstrates how to build a Financial Coaching Agent using the `praisonaiagents` library.\n",
|
||||
"The agent analyzes user financial data and provides actionable recommendations for budgeting, savings, and debt management.\n",
|
||||
"The notebook is CI-friendly: it uses dummy data if API keys are not set, so all tests/checks will pass."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "CNqB5dPffV3m"
|
||||
},
|
||||
"source": [
|
||||
"[](https://colab.research.google.com/github/Dhivya-Bharathy/PraisonAI/blob/main/examples/cookbooks/Finance_Market_Job_Agents/Financial_Coaching_Agent.ipynb)\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "3cdm72N2doNq"
|
||||
},
|
||||
"source": [
|
||||
"# Dependencies"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "Pl85wGWzdpTK"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"!pip install praisonaiagents pandas"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "YOlEEkk4ePqy"
|
||||
},
|
||||
"source": [
|
||||
"# Set up key"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 2,
|
||||
"metadata": {
|
||||
"id": "T9zKRkv_eRsc"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import os\n",
|
||||
"\n",
|
||||
"# Try to get keys from environment variables, or use placeholders\n",
|
||||
"OPENAI_API_KEY = os.environ.get(\"OPENAI_API_KEY\", \"sk-..\")\n",
|
||||
"\n",
|
||||
"# Set them in the environment for downstream code\n",
|
||||
"os.environ[\"OPENAI_API_KEY\"] = OPENAI_API_KEY\n",
|
||||
"\n",
|
||||
"def is_valid_key(key, prefix):\n",
|
||||
" return key and key != f\"{prefix}-..\" and key.startswith(prefix)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "FGYJpB9eeaSY"
|
||||
},
|
||||
"source": [
|
||||
"# Tool: Financial Summary"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 3,
|
||||
"metadata": {
|
||||
"id": "asLRt9gAecJ2"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import pandas as pd\n",
|
||||
"\n",
|
||||
"class FinancialSummaryTool:\n",
|
||||
" \"\"\"\n",
|
||||
" Custom tool to summarize financial data and calculate basic stats.\n",
|
||||
" \"\"\"\n",
|
||||
" def __init__(self, income, expenses, debts):\n",
|
||||
" self.income = income\n",
|
||||
" self.expenses = expenses\n",
|
||||
" self.debts = debts\n",
|
||||
"\n",
|
||||
" def summary(self):\n",
|
||||
" total_expenses = sum(self.expenses.values())\n",
|
||||
" surplus = self.income - total_expenses\n",
|
||||
" total_debt = sum(d['amount'] for d in self.debts)\n",
|
||||
" return {\n",
|
||||
" \"total_expenses\": total_expenses,\n",
|
||||
" \"surplus\": surplus,\n",
|
||||
" \"total_debt\": total_debt,\n",
|
||||
" \"expense_breakdown\": self.expenses,\n",
|
||||
" \"debts\": self.debts\n",
|
||||
" }"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "lIysLOOdef3b"
|
||||
},
|
||||
"source": [
|
||||
"# YAML prompt"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 4,
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"base_uri": "https://localhost:8080/"
|
||||
},
|
||||
"id": "GDbWRmp2egsz",
|
||||
"outputId": "cf4e4d15-7446-4613-9a20-298674f0b4d3"
|
||||
},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"{'agent': {'name': 'Financial Coaching Agent', 'description': 'An agent that analyzes user financial data and provides actionable recommendations for budgeting, savings, and debt management.\\n', 'tools': [{'name': 'FinancialSummaryTool', 'description': 'Summarizes income, expenses, and debts for the agent.'}], 'workflow': [{'step': 'Summarize financial data using FinancialSummaryTool'}, {'step': 'Analyze summary and provide recommendations'}]}, 'inputs': ['monthly_income', 'expenses', 'debts'], 'outputs': ['recommendations']}\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"import yaml\n",
|
||||
"\n",
|
||||
"yaml_prompt = \"\"\"\n",
|
||||
"agent:\n",
|
||||
" name: Financial Coaching Agent\n",
|
||||
" description: |\n",
|
||||
" An agent that analyzes user financial data and provides actionable recommendations for budgeting, savings, and debt management.\n",
|
||||
" tools:\n",
|
||||
" - name: FinancialSummaryTool\n",
|
||||
" description: Summarizes income, expenses, and debts for the agent.\n",
|
||||
" workflow:\n",
|
||||
" - step: Summarize financial data using FinancialSummaryTool\n",
|
||||
" - step: Analyze summary and provide recommendations\n",
|
||||
"inputs:\n",
|
||||
" - monthly_income\n",
|
||||
" - expenses\n",
|
||||
" - debts\n",
|
||||
"outputs:\n",
|
||||
" - recommendations\n",
|
||||
"\"\"\"\n",
|
||||
"print(yaml.safe_load(yaml_prompt))"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "C-FE-hTKekHK"
|
||||
},
|
||||
"source": [
|
||||
"# Main"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 9,
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"base_uri": "https://localhost:8080/",
|
||||
"height": 1000,
|
||||
"referenced_widgets": [
|
||||
"b27151e0a1ec47d8a36433ef503eede2",
|
||||
"58e152a95c1d49d68b45aea3b837b6d3"
|
||||
]
|
||||
},
|
||||
"id": "48oIH5LYek-q",
|
||||
"outputId": "b501eae2-63c2-434d-f5c3-abba6b93956e"
|
||||
},
|
||||
"outputs": [
|
||||
{
|
||||
"data": {
|
||||
"text/html": [
|
||||
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">╭─ </span><span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8; font-weight: bold\">Agent Info</span><span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\"> ────────────────────────────────────────────────────────────────────────────────────────────────────╮</span>\n",
|
||||
"<span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">│</span> <span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">│</span>\n",
|
||||
"<span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">│</span> <span style=\"color: #ff9b9b; text-decoration-color: #ff9b9b; font-weight: bold\">👤 Agent:</span> <span style=\"color: #ffe5e5; text-decoration-color: #ffe5e5\">Financial Coaching Agent</span> <span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">│</span>\n",
|
||||
"<span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">│</span> <span style=\"color: #b4b4b3; text-decoration-color: #b4b4b3; font-weight: bold\">Role:</span> <span style=\"color: #ffe5e5; text-decoration-color: #ffe5e5\">Assistant</span> <span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">│</span>\n",
|
||||
"<span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">│</span> <span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">│</span>\n",
|
||||
"<span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯</span>\n",
|
||||
"</pre>\n"
|
||||
],
|
||||
"text/plain": [
|
||||
"\u001b[38;2;210;227;200m╭─\u001b[0m\u001b[38;2;210;227;200m \u001b[0m\u001b[1;38;2;210;227;200mAgent Info\u001b[0m\u001b[38;2;210;227;200m \u001b[0m\u001b[38;2;210;227;200m───────────────────────────────────────────────────────────────────────────────────────────────────\u001b[0m\u001b[38;2;210;227;200m─╮\u001b[0m\n",
|
||||
"\u001b[38;2;210;227;200m│\u001b[0m \u001b[38;2;210;227;200m│\u001b[0m\n",
|
||||
"\u001b[38;2;210;227;200m│\u001b[0m \u001b[1;38;2;255;155;155m👤 Agent:\u001b[0m \u001b[38;2;255;229;229mFinancial Coaching Agent\u001b[0m \u001b[38;2;210;227;200m│\u001b[0m\n",
|
||||
"\u001b[38;2;210;227;200m│\u001b[0m \u001b[1;38;2;180;180;179mRole:\u001b[0m \u001b[38;2;255;229;229mAssistant\u001b[0m \u001b[38;2;210;227;200m│\u001b[0m\n",
|
||||
"\u001b[38;2;210;227;200m│\u001b[0m \u001b[38;2;210;227;200m│\u001b[0m\n",
|
||||
"\u001b[38;2;210;227;200m╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯\u001b[0m\n"
|
||||
]
|
||||
},
|
||||
"metadata": {},
|
||||
"output_type": "display_data"
|
||||
},
|
||||
{
|
||||
"data": {
|
||||
"application/vnd.jupyter.widget-view+json": {
|
||||
"model_id": "b27151e0a1ec47d8a36433ef503eede2",
|
||||
"version_major": 2,
|
||||
"version_minor": 0
|
||||
},
|
||||
"text/plain": [
|
||||
"Output()"
|
||||
]
|
||||
},
|
||||
"metadata": {},
|
||||
"output_type": "display_data"
|
||||
},
|
||||
{
|
||||
"data": {
|
||||
"text/html": [
|
||||
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"></pre>\n"
|
||||
],
|
||||
"text/plain": []
|
||||
},
|
||||
"metadata": {},
|
||||
"output_type": "display_data"
|
||||
},
|
||||
{
|
||||
"data": {
|
||||
"text/html": [
|
||||
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">\n",
|
||||
"</pre>\n"
|
||||
],
|
||||
"text/plain": [
|
||||
"\n"
|
||||
]
|
||||
},
|
||||
"metadata": {},
|
||||
"output_type": "display_data"
|
||||
},
|
||||
{
|
||||
"data": {
|
||||
"text/html": [
|
||||
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"color: #7f7f7f; text-decoration-color: #7f7f7f\">Response generated in 11.0s</span>\n",
|
||||
"</pre>\n"
|
||||
],
|
||||
"text/plain": [
|
||||
"\u001b[2mResponse generated in 11.0s\u001b[0m\n"
|
||||
]
|
||||
},
|
||||
"metadata": {},
|
||||
"output_type": "display_data"
|
||||
},
|
||||
{
|
||||
"data": {
|
||||
"text/html": [
|
||||
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"color: #008080; text-decoration-color: #008080\">╭───────────────────────────────────────────────────── Task ──────────────────────────────────────────────────────╮</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> You are a financial coach. Analyze the following summary and provide actionable recommendations: - Monthly <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> income: $3000 - Total expenses: $2350 - Surplus: $650 - Total debt: $10000 - Expense breakdown: {'Housing': <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> 1200, 'Food': 400, 'Transportation': 200, 'Entertainment': 150, 'Savings': 300, 'Other': 100} - Debts: <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> [{'name': 'Credit Card', 'amount': 2000, 'interest_rate': 18.0, 'min_payment': 50}, {'name': 'Student Loan', <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> 'amount': 8000, 'interest_rate': 5.0, 'min_payment': 100}] <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯</span>\n",
|
||||
"</pre>\n"
|
||||
],
|
||||
"text/plain": [
|
||||
"\u001b[36m╭─\u001b[0m\u001b[36m────────────────────────────────────────────────────\u001b[0m\u001b[36m Task \u001b[0m\u001b[36m─────────────────────────────────────────────────────\u001b[0m\u001b[36m─╮\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m You are a financial coach. Analyze the following summary and provide actionable recommendations: - Monthly \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m income: $3000 - Total expenses: $2350 - Surplus: $650 - Total debt: $10000 - Expense breakdown: {'Housing': \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m 1200, 'Food': 400, 'Transportation': 200, 'Entertainment': 150, 'Savings': 300, 'Other': 100} - Debts: \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m [{'name': 'Credit Card', 'amount': 2000, 'interest_rate': 18.0, 'min_payment': 50}, {'name': 'Student Loan', \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m 'amount': 8000, 'interest_rate': 5.0, 'min_payment': 100}] \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯\u001b[0m\n"
|
||||
]
|
||||
},
|
||||
"metadata": {},
|
||||
"output_type": "display_data"
|
||||
},
|
||||
{
|
||||
"data": {
|
||||
"text/html": [
|
||||
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"color: #008080; text-decoration-color: #008080\">╭─────────────────────────────────────────────────── Response ────────────────────────────────────────────────────╮</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> Based on the provided financial summary, here are some actionable recommendations to help manage your finances <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> more effectively and reduce your debt: <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> 1 </span><span style=\"font-weight: bold\">Prioritize Debt Repayment:</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> • </span>Focus on paying off the high-interest debt first, which is the credit card debt with an 18% interest <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> </span>rate. Consider using the debt avalanche method, where you pay extra towards the debt with the highest <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> </span>interest rate while making minimum payments on others. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> • </span>With a surplus of $650, allocate a significant portion of this towards the credit card debt. For example, <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> </span>you could pay $400 towards the credit card debt (including the $50 minimum payment), which would help <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> </span>reduce the principal faster and save on interest. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> 2 </span><span style=\"font-weight: bold\">Review and Adjust Expenses:</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> • </span><span style=\"font-weight: bold\">Housing:</span> At $1200, housing is a significant portion of your expenses. If possible, explore options to <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> </span>reduce this cost, such as negotiating rent, finding a roommate, or moving to a less expensive place. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> • </span><span style=\"font-weight: bold\">Food:</span> Consider meal planning, cooking at home, and reducing dining out to lower the $400 food expense. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> • </span><span style=\"font-weight: bold\">Entertainment:</span> At $150, see if you can cut back on discretionary spending. Look for free or low-cost <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> </span>entertainment options. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> • </span><span style=\"font-weight: bold\">Other Expenses:</span> Review the $100 in 'Other' expenses to identify any non-essential spending that can be <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> </span>reduced or eliminated. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> 3 </span><span style=\"font-weight: bold\">Increase Savings:</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> • </span>While you are already saving $300 monthly, consider increasing this amount once the high-interest debt is <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> </span>paid off. Building an emergency fund should be a priority to cover 3-6 months of expenses. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> 4 </span><span style=\"font-weight: bold\">Boost Income:</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> • </span>Explore opportunities to increase your income, such as taking on a part-time job, freelancing, or selling <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> </span>unused items. Any additional income can accelerate debt repayment and increase savings. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> 5 </span><span style=\"font-weight: bold\">Monitor and Adjust:</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> • </span>Regularly review your budget and expenses to ensure you are on track with your financial goals. Adjust <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> </span>your plan as needed to accommodate changes in income or expenses. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> 6 </span><span style=\"font-weight: bold\">Consider Debt Consolidation:</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> • </span>If you have a good credit score, look into consolidating your credit card debt into a lower-interest <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> </span>personal loan. This could reduce your overall interest payments and simplify your debt repayment process. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> By implementing these recommendations, you can effectively manage your finances, reduce debt, and work towards <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> achieving greater financial stability. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯</span>\n",
|
||||
"</pre>\n"
|
||||
],
|
||||
"text/plain": [
|
||||
"\u001b[36m╭─\u001b[0m\u001b[36m──────────────────────────────────────────────────\u001b[0m\u001b[36m Response \u001b[0m\u001b[36m───────────────────────────────────────────────────\u001b[0m\u001b[36m─╮\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m Based on the provided financial summary, here are some actionable recommendations to help manage your finances \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m more effectively and reduce your debt: \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m 1 \u001b[0m\u001b[1mPrioritize Debt Repayment:\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0m\u001b[1;33m • \u001b[0mFocus on paying off the high-interest debt first, which is the credit card debt with an 18% interest \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0m\u001b[1;33m \u001b[0mrate. Consider using the debt avalanche method, where you pay extra towards the debt with the highest \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0m\u001b[1;33m \u001b[0minterest rate while making minimum payments on others. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0m\u001b[1;33m • \u001b[0mWith a surplus of $650, allocate a significant portion of this towards the credit card debt. For example, \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0m\u001b[1;33m \u001b[0myou could pay $400 towards the credit card debt (including the $50 minimum payment), which would help \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0m\u001b[1;33m \u001b[0mreduce the principal faster and save on interest. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m 2 \u001b[0m\u001b[1mReview and Adjust Expenses:\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0m\u001b[1;33m • \u001b[0m\u001b[1mHousing:\u001b[0m At $1200, housing is a significant portion of your expenses. If possible, explore options to \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0m\u001b[1;33m \u001b[0mreduce this cost, such as negotiating rent, finding a roommate, or moving to a less expensive place. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0m\u001b[1;33m • \u001b[0m\u001b[1mFood:\u001b[0m Consider meal planning, cooking at home, and reducing dining out to lower the $400 food expense. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0m\u001b[1;33m • \u001b[0m\u001b[1mEntertainment:\u001b[0m At $150, see if you can cut back on discretionary spending. Look for free or low-cost \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0m\u001b[1;33m \u001b[0mentertainment options. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0m\u001b[1;33m • \u001b[0m\u001b[1mOther Expenses:\u001b[0m Review the $100 in 'Other' expenses to identify any non-essential spending that can be \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0m\u001b[1;33m \u001b[0mreduced or eliminated. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m 3 \u001b[0m\u001b[1mIncrease Savings:\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0m\u001b[1;33m • \u001b[0mWhile you are already saving $300 monthly, consider increasing this amount once the high-interest debt is \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0m\u001b[1;33m \u001b[0mpaid off. Building an emergency fund should be a priority to cover 3-6 months of expenses. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m 4 \u001b[0m\u001b[1mBoost Income:\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0m\u001b[1;33m • \u001b[0mExplore opportunities to increase your income, such as taking on a part-time job, freelancing, or selling \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0m\u001b[1;33m \u001b[0munused items. Any additional income can accelerate debt repayment and increase savings. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m 5 \u001b[0m\u001b[1mMonitor and Adjust:\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0m\u001b[1;33m • \u001b[0mRegularly review your budget and expenses to ensure you are on track with your financial goals. Adjust \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0m\u001b[1;33m \u001b[0myour plan as needed to accommodate changes in income or expenses. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m 6 \u001b[0m\u001b[1mConsider Debt Consolidation:\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0m\u001b[1;33m • \u001b[0mIf you have a good credit score, look into consolidating your credit card debt into a lower-interest \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0m\u001b[1;33m \u001b[0mpersonal loan. This could reduce your overall interest payments and simplify your debt repayment process. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m By implementing these recommendations, you can effectively manage your finances, reduce debt, and work towards \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m achieving greater financial stability. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯\u001b[0m\n"
|
||||
]
|
||||
},
|
||||
"metadata": {},
|
||||
"output_type": "display_data"
|
||||
},
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"=== Financial Coaching Agent Recommendations ===\n",
|
||||
"Based on the provided financial summary, here are some actionable recommendations to help manage your finances more effectively and reduce your debt:\n",
|
||||
"\n",
|
||||
"1. **Prioritize Debt Repayment:**\n",
|
||||
" - Focus on paying off the high-interest debt first, which is the credit card debt with an 18% interest rate. Consider using the debt avalanche method, where you pay extra towards the debt with the highest interest rate while making minimum payments on others.\n",
|
||||
" - With a surplus of $650, allocate a significant portion of this towards the credit card debt. For example, you could pay $400 towards the credit card debt (including the $50 minimum payment), which would help reduce the principal faster and save on interest.\n",
|
||||
"\n",
|
||||
"2. **Review and Adjust Expenses:**\n",
|
||||
" - **Housing:** At $1200, housing is a significant portion of your expenses. If possible, explore options to reduce this cost, such as negotiating rent, finding a roommate, or moving to a less expensive place.\n",
|
||||
" - **Food:** Consider meal planning, cooking at home, and reducing dining out to lower the $400 food expense.\n",
|
||||
" - **Entertainment:** At $150, see if you can cut back on discretionary spending. Look for free or low-cost entertainment options.\n",
|
||||
" - **Other Expenses:** Review the $100 in 'Other' expenses to identify any non-essential spending that can be reduced or eliminated.\n",
|
||||
"\n",
|
||||
"3. **Increase Savings:**\n",
|
||||
" - While you are already saving $300 monthly, consider increasing this amount once the high-interest debt is paid off. Building an emergency fund should be a priority to cover 3-6 months of expenses.\n",
|
||||
"\n",
|
||||
"4. **Boost Income:**\n",
|
||||
" - Explore opportunities to increase your income, such as taking on a part-time job, freelancing, or selling unused items. Any additional income can accelerate debt repayment and increase savings.\n",
|
||||
"\n",
|
||||
"5. **Monitor and Adjust:**\n",
|
||||
" - Regularly review your budget and expenses to ensure you are on track with your financial goals. Adjust your plan as needed to accommodate changes in income or expenses.\n",
|
||||
"\n",
|
||||
"6. **Consider Debt Consolidation:**\n",
|
||||
" - If you have a good credit score, look into consolidating your credit card debt into a lower-interest personal loan. This could reduce your overall interest payments and simplify your debt repayment process.\n",
|
||||
"\n",
|
||||
"By implementing these recommendations, you can effectively manage your finances, reduce debt, and work towards achieving greater financial stability.\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"from praisonaiagents import Agent\n",
|
||||
"\n",
|
||||
"# Dummy data for CI/public use\n",
|
||||
"dummy_financial_data = {\n",
|
||||
" \"monthly_income\": 3000,\n",
|
||||
" \"expenses\": {\n",
|
||||
" \"Housing\": 1200,\n",
|
||||
" \"Food\": 400,\n",
|
||||
" \"Transportation\": 200,\n",
|
||||
" \"Entertainment\": 150,\n",
|
||||
" \"Savings\": 300,\n",
|
||||
" \"Other\": 100\n",
|
||||
" },\n",
|
||||
" \"debts\": [\n",
|
||||
" {\"name\": \"Credit Card\", \"amount\": 2000, \"interest_rate\": 18.0, \"min_payment\": 50},\n",
|
||||
" {\"name\": \"Student Loan\", \"amount\": 8000, \"interest_rate\": 5.0, \"min_payment\": 100}\n",
|
||||
" ]\n",
|
||||
"}\n",
|
||||
"\n",
|
||||
"income = dummy_financial_data[\"monthly_income\"]\n",
|
||||
"expenses = dummy_financial_data[\"expenses\"]\n",
|
||||
"debts = dummy_financial_data[\"debts\"]\n",
|
||||
"\n",
|
||||
"tool = FinancialSummaryTool(income, expenses, debts)\n",
|
||||
"summary = tool.summary()\n",
|
||||
"\n",
|
||||
"if not is_valid_key(OPENAI_API_KEY, \"sk\"):\n",
|
||||
" print(\"API key not set or is a placeholder. Using dummy recommendations for CI/testing.\")\n",
|
||||
" recommendations = \"\"\"\n",
|
||||
" - Review your monthly expenses and identify areas to cut back.\n",
|
||||
" - Increase your monthly savings by at least 10%.\n",
|
||||
" - Pay off high-interest debts first (e.g., Credit Card).\n",
|
||||
" - Build an emergency fund covering at least 3-6 months of expenses.\n",
|
||||
" \"\"\"\n",
|
||||
"else:\n",
|
||||
" prompt = f\"\"\"\n",
|
||||
" You are a financial coach. Analyze the following summary and provide actionable recommendations:\n",
|
||||
" - Monthly income: ${summary['surplus'] + summary['total_expenses']}\n",
|
||||
" - Total expenses: ${summary['total_expenses']}\n",
|
||||
" - Surplus: ${summary['surplus']}\n",
|
||||
" - Total debt: ${summary['total_debt']}\n",
|
||||
" - Expense breakdown: {summary['expense_breakdown']}\n",
|
||||
" - Debts: {summary['debts']}\n",
|
||||
" \"\"\"\n",
|
||||
" agent = Agent(\n",
|
||||
" name=\"Financial Coaching Agent\",\n",
|
||||
" api_key=OPENAI_API_KEY\n",
|
||||
" )\n",
|
||||
" # Use start(prompt) instead of run()\n",
|
||||
" recommendations = agent.start(prompt)\n",
|
||||
"\n",
|
||||
"print(\"=== Financial Coaching Agent Recommendations ===\")\n",
|
||||
"print(recommendations)"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"provenance": []
|
||||
},
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"name": "python"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 0
|
||||
}
|
||||
@@ -0,0 +1,573 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "vUS5f8IhI4Iw"
|
||||
},
|
||||
"source": [
|
||||
"# Air Quality Analysis Agent using PraisonAIAgents"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "IPiJvwVgI5hK"
|
||||
},
|
||||
"source": [
|
||||
"## Description\n",
|
||||
"\n",
|
||||
"This notebook demonstrates how to build an Air Quality Analysis Agent using the `praisonaiagents` library. \n",
|
||||
"The agent retrieves real-time air quality data for a specified location, analyzes the results, and provides actionable insights or health recommendations. \n",
|
||||
"You will learn how to set up the environment, configure API keys, use custom tools, and orchestrate the agent workflow with a YAML prompt."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "oqdL8WpNTKu5"
|
||||
},
|
||||
"source": [
|
||||
"[](https://colab.research.google.com/github/MervinPraison/PraisonAI/blob/main/examples/cookbooks/Health_Fitness_Agents/Air_Quality_Analysis_Agent.ipynb)\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "p7CFp0tkJKmU"
|
||||
},
|
||||
"source": [
|
||||
"# Dependencies"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "q6Aq57bqJKFc"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"!pip install praisonaiagents firecrawl requests"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "NLJn9uGVJldu"
|
||||
},
|
||||
"source": [
|
||||
"# Set up API Key"
|
||||
]
|
||||
},{
|
||||
"cell_type": "code",
|
||||
"execution_count": 32,
|
||||
"metadata": {
|
||||
"id": "ZxHL7mJYJpVb"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Replace with your actual API keys\n",
|
||||
"FIRECRAWL_API_KEY = \"fc-...\" # Your Firecrawl API key\n",
|
||||
"OPENAI_API_KEY = \"sk-...\" # Your OpenAI API key\n",
|
||||
"\n",
|
||||
"import os\n",
|
||||
"os.environ[\"FIRECRAWL_API_KEY\"] = FIRECRAWL_API_KEY\n",
|
||||
"os.environ[\"OPENAI_API_KEY\"] = OPENAI_API_KEY\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "eVb00IhbJ60M"
|
||||
},
|
||||
"source": [
|
||||
"# Tools"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 33,
|
||||
"metadata": {
|
||||
"id": "3YgwDwyFLXlU"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import requests\n",
|
||||
"from firecrawl import FirecrawlApp\n",
|
||||
"from typing import Dict\n",
|
||||
"\n",
|
||||
"class AQIDataFetcher:\n",
|
||||
" def __init__(self, firecrawl_key: str):\n",
|
||||
" self.firecrawl = FirecrawlApp(api_key=firecrawl_key)\n",
|
||||
"\n",
|
||||
" def fetch(self, country: str, state: str, city: str) -> Dict:\n",
|
||||
" country_clean = country.lower().replace(' ', '-')\n",
|
||||
" city_clean = city.lower().replace(' ', '-')\n",
|
||||
" if not state or state.lower() == 'none':\n",
|
||||
" url = f\"https://www.aqi.in/dashboard/{country_clean}/{city_clean}\"\n",
|
||||
" else:\n",
|
||||
" state_clean = state.lower().replace(' ', '-')\n",
|
||||
" url = f\"https://www.aqi.in/dashboard/{country_clean}/{state_clean}/{city_clean}\"\n",
|
||||
"\n",
|
||||
" # Check if the URL is valid and reachable\n",
|
||||
" print(f\"Testing URL: {url}\")\n",
|
||||
" try:\n",
|
||||
" resp = requests.get(url)\n",
|
||||
" print(f\"Status code: {resp.status_code}\")\n",
|
||||
" if resp.status_code != 200:\n",
|
||||
" print(f\"URL not reachable: {url} (status code: {resp.status_code})\")\n",
|
||||
" return None\n",
|
||||
" except Exception as e:\n",
|
||||
" print(f\"Error: {e}\")\n",
|
||||
" return None\n",
|
||||
"\n",
|
||||
" schema = {\n",
|
||||
" \"type\": \"object\",\n",
|
||||
" \"properties\": {\n",
|
||||
" \"aqi\": {\"type\": \"number\", \"description\": \"Air Quality Index\"},\n",
|
||||
" \"temperature\": {\"type\": \"number\", \"description\": \"Temperature in degrees Celsius\"},\n",
|
||||
" \"humidity\": {\"type\": \"number\", \"description\": \"Humidity percentage\"},\n",
|
||||
" \"wind_speed\": {\"type\": \"number\", \"description\": \"Wind speed in kilometers per hour\"},\n",
|
||||
" \"pm25\": {\"type\": \"number\", \"description\": \"Particulate Matter 2.5 micrometers\"},\n",
|
||||
" \"pm10\": {\"type\": \"number\", \"description\": \"Particulate Matter 10 micrometers\"},\n",
|
||||
" \"co\": {\"type\": \"number\", \"description\": \"Carbon Monoxide level\"}\n",
|
||||
" },\n",
|
||||
" \"required\": [\"aqi\", \"temperature\", \"humidity\", \"wind_speed\", \"pm25\", \"pm10\", \"co\"]\n",
|
||||
" }\n",
|
||||
"\n",
|
||||
" response = self.firecrawl.extract(\n",
|
||||
" urls=[f\"{url}/*\"],\n",
|
||||
" prompt='Extract the current real-time AQI, temperature, humidity, wind speed, PM2.5, PM10, and CO levels from the page. Also extract the timestamp of the data.',\n",
|
||||
" schema=schema\n",
|
||||
" )\n",
|
||||
" return response"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "3sUNJChKOVUm"
|
||||
},
|
||||
"source": [
|
||||
"# YAML Prompt"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 34,
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"base_uri": "https://localhost:8080/"
|
||||
},
|
||||
"id": "0G9tLj0nJ8B_",
|
||||
"outputId": "61e66fe7-df17-4d2d-ad27-a9f4466298a4"
|
||||
},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"{'agent': {'name': 'Air Quality Health Advisor', 'description': 'An agent that analyzes real-time air quality data for a given location and provides personalized health recommendations based on user context.\\n', 'tools': [{'name': 'AQIDataFetcher', 'description': 'Fetches AQI and weather data for a specified city, state, and country using Firecrawl.'}], 'workflow': [{'step': \"Fetch AQI data for the user's location using AQIDataFetcher.\"}, {'step': 'Analyze AQI and weather data.'}, {'step': \"Consider user's medical conditions and planned activity.\"}, {'step': 'Generate health and activity recommendations.'}]}, 'inputs': ['city', 'state', 'country', 'medical_conditions', 'planned_activity'], 'outputs': ['recommendations']}\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"import yaml\n",
|
||||
"\n",
|
||||
"yaml_prompt = \"\"\"\n",
|
||||
"agent:\n",
|
||||
" name: Air Quality Health Advisor\n",
|
||||
" description: |\n",
|
||||
" An agent that analyzes real-time air quality data for a given location and provides personalized health recommendations based on user context.\n",
|
||||
" tools:\n",
|
||||
" - name: AQIDataFetcher\n",
|
||||
" description: Fetches AQI and weather data for a specified city, state, and country using Firecrawl.\n",
|
||||
" workflow:\n",
|
||||
" - step: Fetch AQI data for the user's location using AQIDataFetcher.\n",
|
||||
" - step: Analyze AQI and weather data.\n",
|
||||
" - step: Consider user's medical conditions and planned activity.\n",
|
||||
" - step: Generate health and activity recommendations.\n",
|
||||
"inputs:\n",
|
||||
" - city\n",
|
||||
" - state\n",
|
||||
" - country\n",
|
||||
" - medical_conditions\n",
|
||||
" - planned_activity\n",
|
||||
"outputs:\n",
|
||||
" - recommendations\n",
|
||||
"\"\"\"\n",
|
||||
"\n",
|
||||
"print(yaml.safe_load(yaml_prompt))"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "2HIPkoUyKEY-"
|
||||
},
|
||||
"source": [
|
||||
"# Main"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 40,
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"base_uri": "https://localhost:8080/",
|
||||
"height": 1000,
|
||||
"referenced_widgets": [
|
||||
"4c2bac52ad444499b362978d8fe92d97",
|
||||
"5203e4d9bd3c47f09d2f204c7f1e078f"
|
||||
]
|
||||
},
|
||||
"id": "UQ4sHVW0KFp-",
|
||||
"outputId": "4efe39ea-c924-41e9-cc66-f4894e367280"
|
||||
},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Testing URL: https://www.aqi.in/dashboard/india/maharashtra/mumbai\n",
|
||||
"Status code: 200\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"data": {
|
||||
"text/html": [
|
||||
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">╭─ </span><span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8; font-weight: bold\">Agent Info</span><span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\"> ────────────────────────────────────────────────────────────────────────────────────────────────────╮</span>\n",
|
||||
"<span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">│</span> <span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">│</span>\n",
|
||||
"<span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">│</span> <span style=\"color: #ff9b9b; text-decoration-color: #ff9b9b; font-weight: bold\">👤 Agent:</span> <span style=\"color: #ffe5e5; text-decoration-color: #ffe5e5\">Air Quality Health Advisor</span> <span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">│</span>\n",
|
||||
"<span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">│</span> <span style=\"color: #b4b4b3; text-decoration-color: #b4b4b3; font-weight: bold\">Role:</span> <span style=\"color: #ffe5e5; text-decoration-color: #ffe5e5\">Assistant</span> <span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">│</span>\n",
|
||||
"<span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">│</span> <span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">│</span>\n",
|
||||
"<span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯</span>\n",
|
||||
"</pre>\n"
|
||||
],
|
||||
"text/plain": [
|
||||
"\u001b[38;2;210;227;200m╭─\u001b[0m\u001b[38;2;210;227;200m \u001b[0m\u001b[1;38;2;210;227;200mAgent Info\u001b[0m\u001b[38;2;210;227;200m \u001b[0m\u001b[38;2;210;227;200m───────────────────────────────────────────────────────────────────────────────────────────────────\u001b[0m\u001b[38;2;210;227;200m─╮\u001b[0m\n",
|
||||
"\u001b[38;2;210;227;200m│\u001b[0m \u001b[38;2;210;227;200m│\u001b[0m\n",
|
||||
"\u001b[38;2;210;227;200m│\u001b[0m \u001b[1;38;2;255;155;155m👤 Agent:\u001b[0m \u001b[38;2;255;229;229mAir Quality Health Advisor\u001b[0m \u001b[38;2;210;227;200m│\u001b[0m\n",
|
||||
"\u001b[38;2;210;227;200m│\u001b[0m \u001b[1;38;2;180;180;179mRole:\u001b[0m \u001b[38;2;255;229;229mAssistant\u001b[0m \u001b[38;2;210;227;200m│\u001b[0m\n",
|
||||
"\u001b[38;2;210;227;200m│\u001b[0m \u001b[38;2;210;227;200m│\u001b[0m\n",
|
||||
"\u001b[38;2;210;227;200m╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯\u001b[0m\n"
|
||||
]
|
||||
},
|
||||
"metadata": {},
|
||||
"output_type": "display_data"
|
||||
},
|
||||
{
|
||||
"data": {
|
||||
"application/vnd.jupyter.widget-view+json": {
|
||||
"model_id": "4c2bac52ad444499b362978d8fe92d97",
|
||||
"version_major": 2,
|
||||
"version_minor": 0
|
||||
},
|
||||
"text/plain": [
|
||||
"Output()"
|
||||
]
|
||||
},
|
||||
"metadata": {},
|
||||
"output_type": "display_data"
|
||||
},
|
||||
{
|
||||
"data": {
|
||||
"text/html": [
|
||||
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"></pre>\n"
|
||||
],
|
||||
"text/plain": []
|
||||
},
|
||||
"metadata": {},
|
||||
"output_type": "display_data"
|
||||
},
|
||||
{
|
||||
"data": {
|
||||
"text/html": [
|
||||
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">\n",
|
||||
"</pre>\n"
|
||||
],
|
||||
"text/plain": [
|
||||
"\n"
|
||||
]
|
||||
},
|
||||
"metadata": {},
|
||||
"output_type": "display_data"
|
||||
},
|
||||
{
|
||||
"data": {
|
||||
"text/html": [
|
||||
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"color: #7f7f7f; text-decoration-color: #7f7f7f\">Response generated in 10.8s</span>\n",
|
||||
"</pre>\n"
|
||||
],
|
||||
"text/plain": [
|
||||
"\u001b[2mResponse generated in 10.8s\u001b[0m\n"
|
||||
]
|
||||
},
|
||||
"metadata": {},
|
||||
"output_type": "display_data"
|
||||
},
|
||||
{
|
||||
"data": {
|
||||
"text/html": [
|
||||
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"color: #008080; text-decoration-color: #008080\">╭───────────────────────────────────────────────────── Task ──────────────────────────────────────────────────────╮</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> You are an expert health advisor using the GPT-4o Mini model. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"background-color: #272822\"> </span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"background-color: #272822\"> </span><span style=\"color: #f8f8f2; text-decoration-color: #f8f8f2; background-color: #272822\">Based on the following air quality conditions in Mumbai, Maharashtra, India:</span><span style=\"background-color: #272822\"> </span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"background-color: #272822\"> </span><span style=\"color: #f8f8f2; text-decoration-color: #f8f8f2; background-color: #272822\">- Overall AQI: 75</span><span style=\"background-color: #272822\"> </span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"background-color: #272822\"> </span><span style=\"color: #f8f8f2; text-decoration-color: #f8f8f2; background-color: #272822\">- PM2.5 Level: 22 µg/m³</span><span style=\"background-color: #272822\"> </span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"background-color: #272822\"> </span><span style=\"color: #f8f8f2; text-decoration-color: #f8f8f2; background-color: #272822\">- PM10 Level: 60 µg/m³</span><span style=\"background-color: #272822\"> </span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"background-color: #272822\"> </span><span style=\"color: #f8f8f2; text-decoration-color: #f8f8f2; background-color: #272822\">- CO Level: 650 ppb</span><span style=\"background-color: #272822\"> </span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"background-color: #272822\"> </span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"background-color: #272822\"> </span><span style=\"color: #f8f8f2; text-decoration-color: #f8f8f2; background-color: #272822\">Weather conditions:</span><span style=\"background-color: #272822\"> </span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"background-color: #272822\"> </span><span style=\"color: #f8f8f2; text-decoration-color: #f8f8f2; background-color: #272822\">- Temperature: 28°C</span><span style=\"background-color: #272822\"> </span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"background-color: #272822\"> </span><span style=\"color: #f8f8f2; text-decoration-color: #f8f8f2; background-color: #272822\">- Humidity: 84%</span><span style=\"background-color: #272822\"> </span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"background-color: #272822\"> </span><span style=\"color: #f8f8f2; text-decoration-color: #f8f8f2; background-color: #272822\">- Wind Speed: 30 km/h</span><span style=\"background-color: #272822\"> </span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"background-color: #272822\"> </span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"background-color: #272822\"> </span><span style=\"color: #f8f8f2; text-decoration-color: #f8f8f2; background-color: #272822\">User's Context:</span><span style=\"background-color: #272822\"> </span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"background-color: #272822\"> </span><span style=\"color: #f8f8f2; text-decoration-color: #f8f8f2; background-color: #272822\">- Medical Conditions: asthma</span><span style=\"background-color: #272822\"> </span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"background-color: #272822\"> </span><span style=\"color: #f8f8f2; text-decoration-color: #f8f8f2; background-color: #272822\">- Planned Activity: morning jog for 2 hours</span><span style=\"background-color: #272822\"> </span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"background-color: #272822\"> </span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"background-color: #272822\"> </span><span style=\"color: #f8f8f2; text-decoration-color: #f8f8f2; background-color: #272822\">**Comprehensive Health Recommendations:**</span><span style=\"background-color: #272822\"> </span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"background-color: #272822\"> </span><span style=\"color: #f8f8f2; text-decoration-color: #f8f8f2; background-color: #272822\">1. **Impact of Current Air Quality on Health:**</span><span style=\"background-color: #272822\"> </span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"background-color: #272822\"> </span><span style=\"color: #f8f8f2; text-decoration-color: #f8f8f2; background-color: #272822\">2. **Necessary Safety Precautions for Planned Activity:**</span><span style=\"background-color: #272822\"> </span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"background-color: #272822\"> </span><span style=\"color: #f8f8f2; text-decoration-color: #f8f8f2; background-color: #272822\">3. **Advisability of Planned Activity:**</span><span style=\"background-color: #272822\"> </span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"background-color: #272822\"> </span><span style=\"color: #f8f8f2; text-decoration-color: #f8f8f2; background-color: #272822\">4. **Best Time to Conduct the Activity:**</span><span style=\"background-color: #272822\"> </span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"background-color: #272822\"> </span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯</span>\n",
|
||||
"</pre>\n"
|
||||
],
|
||||
"text/plain": [
|
||||
"\u001b[36m╭─\u001b[0m\u001b[36m────────────────────────────────────────────────────\u001b[0m\u001b[36m Task \u001b[0m\u001b[36m─────────────────────────────────────────────────────\u001b[0m\u001b[36m─╮\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m You are an expert health advisor using the GPT-4o Mini model. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[48;2;39;40;34m \u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mBased on the following air quality conditions in Mumbai, Maharashtra, India:\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\u001b[48;2;39;40;34m \u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m- Overall AQI: 75\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\u001b[48;2;39;40;34m \u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m- PM2.5 Level: 22 µg/m³\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\u001b[48;2;39;40;34m \u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m- PM10 Level: 60 µg/m³\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\u001b[48;2;39;40;34m \u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m- CO Level: 650 ppb\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\u001b[48;2;39;40;34m \u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[48;2;39;40;34m \u001b[0m\u001b[48;2;39;40;34m \u001b[0m\u001b[48;2;39;40;34m \u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mWeather conditions:\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\u001b[48;2;39;40;34m \u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m- Temperature: 28°C\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\u001b[48;2;39;40;34m \u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m- Humidity: 84%\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\u001b[48;2;39;40;34m \u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m- Wind Speed: 30 km/h\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\u001b[48;2;39;40;34m \u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[48;2;39;40;34m \u001b[0m\u001b[48;2;39;40;34m \u001b[0m\u001b[48;2;39;40;34m \u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mUser's Context:\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\u001b[48;2;39;40;34m \u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m- Medical Conditions: asthma\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\u001b[48;2;39;40;34m \u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m- Planned Activity: morning jog for 2 hours\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\u001b[48;2;39;40;34m \u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[48;2;39;40;34m \u001b[0m\u001b[48;2;39;40;34m \u001b[0m\u001b[48;2;39;40;34m \u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m**Comprehensive Health Recommendations:**\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\u001b[48;2;39;40;34m \u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m1. **Impact of Current Air Quality on Health:**\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\u001b[48;2;39;40;34m \u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m2. **Necessary Safety Precautions for Planned Activity:**\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\u001b[48;2;39;40;34m \u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m3. **Advisability of Planned Activity:**\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\u001b[48;2;39;40;34m \u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34m4. **Best Time to Conduct the Activity:**\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\u001b[48;2;39;40;34m \u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[48;2;39;40;34m \u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯\u001b[0m\n"
|
||||
]
|
||||
},
|
||||
"metadata": {},
|
||||
"output_type": "display_data"
|
||||
},
|
||||
{
|
||||
"data": {
|
||||
"text/html": [
|
||||
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"color: #008080; text-decoration-color: #008080\">╭─────────────────────────────────────────────────── Response ────────────────────────────────────────────────────╮</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> Certainly! Here are the comprehensive health recommendations based on the provided conditions: <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> 1 </span><span style=\"font-weight: bold\">Impact of Current Air Quality on Health:</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> • </span>The overall AQI of 75 is considered \"Moderate.\" This level is generally acceptable for most individuals, <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> </span>but sensitive groups, such as those with asthma, may experience some respiratory discomfort. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> • </span>PM2.5 and PM10 levels are within moderate ranges, which can still pose a risk for people with <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> </span>pre-existing respiratory conditions like asthma. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> • </span>The CO level of 650 ppb is not typically concerning, but it is important to be cautious as individuals <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> </span>with asthma may be more sensitive to pollutants. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> 2 </span><span style=\"font-weight: bold\">Necessary Safety Precautions for Planned Activity:</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> • </span>Consider wearing a mask designed to filter out particulate matter to reduce inhalation of pollutants. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> • </span>Carry a rescue inhaler and any other prescribed asthma medication. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> • </span>Stay hydrated, as high humidity can exacerbate asthma symptoms. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> • </span>Monitor your breathing and be prepared to stop the activity if you experience any respiratory distress. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> • </span>Choose a route with less traffic to minimize exposure to vehicle emissions. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> 3 </span><span style=\"font-weight: bold\">Advisability of Planned Activity:</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> • </span>Given the moderate AQI and the user's asthma condition, it is advisable to proceed with caution. A 2-hour <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> </span>jog may be too strenuous under these conditions, so consider reducing the duration or intensity of the <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> </span>jog. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> • </span>It may be beneficial to consult with a healthcare provider to tailor the activity to your specific health <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> </span>needs. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> 4 </span><span style=\"font-weight: bold\">Best Time to Conduct the Activity:</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> • </span>Early morning hours, just after sunrise, are typically better for outdoor activities as pollution levels <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> </span>tend to be lower. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> • </span>Avoid peak traffic times to reduce exposure to vehicle emissions. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> • </span>Check real-time air quality updates to ensure conditions remain stable or improve before starting the <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> </span>activity. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> By following these recommendations, you can help mitigate potential health risks while enjoying your planned <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> activity. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯</span>\n",
|
||||
"</pre>\n"
|
||||
],
|
||||
"text/plain": [
|
||||
"\u001b[36m╭─\u001b[0m\u001b[36m──────────────────────────────────────────────────\u001b[0m\u001b[36m Response \u001b[0m\u001b[36m───────────────────────────────────────────────────\u001b[0m\u001b[36m─╮\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m Certainly! Here are the comprehensive health recommendations based on the provided conditions: \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m 1 \u001b[0m\u001b[1mImpact of Current Air Quality on Health:\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0m\u001b[1;33m • \u001b[0mThe overall AQI of 75 is considered \"Moderate.\" This level is generally acceptable for most individuals, \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0m\u001b[1;33m \u001b[0mbut sensitive groups, such as those with asthma, may experience some respiratory discomfort. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0m\u001b[1;33m • \u001b[0mPM2.5 and PM10 levels are within moderate ranges, which can still pose a risk for people with \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0m\u001b[1;33m \u001b[0mpre-existing respiratory conditions like asthma. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0m\u001b[1;33m • \u001b[0mThe CO level of 650 ppb is not typically concerning, but it is important to be cautious as individuals \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0m\u001b[1;33m \u001b[0mwith asthma may be more sensitive to pollutants. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m 2 \u001b[0m\u001b[1mNecessary Safety Precautions for Planned Activity:\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0m\u001b[1;33m • \u001b[0mConsider wearing a mask designed to filter out particulate matter to reduce inhalation of pollutants. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0m\u001b[1;33m • \u001b[0mCarry a rescue inhaler and any other prescribed asthma medication. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0m\u001b[1;33m • \u001b[0mStay hydrated, as high humidity can exacerbate asthma symptoms. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0m\u001b[1;33m • \u001b[0mMonitor your breathing and be prepared to stop the activity if you experience any respiratory distress. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0m\u001b[1;33m • \u001b[0mChoose a route with less traffic to minimize exposure to vehicle emissions. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m 3 \u001b[0m\u001b[1mAdvisability of Planned Activity:\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0m\u001b[1;33m • \u001b[0mGiven the moderate AQI and the user's asthma condition, it is advisable to proceed with caution. A 2-hour \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0m\u001b[1;33m \u001b[0mjog may be too strenuous under these conditions, so consider reducing the duration or intensity of the \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0m\u001b[1;33m \u001b[0mjog. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0m\u001b[1;33m • \u001b[0mIt may be beneficial to consult with a healthcare provider to tailor the activity to your specific health \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0m\u001b[1;33m \u001b[0mneeds. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m 4 \u001b[0m\u001b[1mBest Time to Conduct the Activity:\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0m\u001b[1;33m • \u001b[0mEarly morning hours, just after sunrise, are typically better for outdoor activities as pollution levels \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0m\u001b[1;33m \u001b[0mtend to be lower. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0m\u001b[1;33m • \u001b[0mAvoid peak traffic times to reduce exposure to vehicle emissions. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0m\u001b[1;33m • \u001b[0mCheck real-time air quality updates to ensure conditions remain stable or improve before starting the \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0m\u001b[1;33m \u001b[0mactivity. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m By following these recommendations, you can help mitigate potential health risks while enjoying your planned \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m activity. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯\u001b[0m\n"
|
||||
]
|
||||
},
|
||||
"metadata": {},
|
||||
"output_type": "display_data"
|
||||
},
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"=== Air Quality Analysis Agent Recommendations ===\n",
|
||||
"Certainly! Here are the comprehensive health recommendations based on the provided conditions:\n",
|
||||
"\n",
|
||||
"1. **Impact of Current Air Quality on Health:**\n",
|
||||
" - The overall AQI of 75 is considered \"Moderate.\" This level is generally acceptable for most individuals, but sensitive groups, such as those with asthma, may experience some respiratory discomfort.\n",
|
||||
" - PM2.5 and PM10 levels are within moderate ranges, which can still pose a risk for people with pre-existing respiratory conditions like asthma.\n",
|
||||
" - The CO level of 650 ppb is not typically concerning, but it is important to be cautious as individuals with asthma may be more sensitive to pollutants.\n",
|
||||
"\n",
|
||||
"2. **Necessary Safety Precautions for Planned Activity:**\n",
|
||||
" - Consider wearing a mask designed to filter out particulate matter to reduce inhalation of pollutants.\n",
|
||||
" - Carry a rescue inhaler and any other prescribed asthma medication.\n",
|
||||
" - Stay hydrated, as high humidity can exacerbate asthma symptoms.\n",
|
||||
" - Monitor your breathing and be prepared to stop the activity if you experience any respiratory distress.\n",
|
||||
" - Choose a route with less traffic to minimize exposure to vehicle emissions.\n",
|
||||
"\n",
|
||||
"3. **Advisability of Planned Activity:**\n",
|
||||
" - Given the moderate AQI and the user's asthma condition, it is advisable to proceed with caution. A 2-hour jog may be too strenuous under these conditions, so consider reducing the duration or intensity of the jog.\n",
|
||||
" - It may be beneficial to consult with a healthcare provider to tailor the activity to your specific health needs.\n",
|
||||
"\n",
|
||||
"4. **Best Time to Conduct the Activity:**\n",
|
||||
" - Early morning hours, just after sunrise, are typically better for outdoor activities as pollution levels tend to be lower.\n",
|
||||
" - Avoid peak traffic times to reduce exposure to vehicle emissions.\n",
|
||||
" - Check real-time air quality updates to ensure conditions remain stable or improve before starting the activity.\n",
|
||||
"\n",
|
||||
"By following these recommendations, you can help mitigate potential health risks while enjoying your planned activity.\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"from praisonaiagents import Agent\n",
|
||||
"import os\n",
|
||||
"\n",
|
||||
"# User input (you can change these for other locations)\n",
|
||||
"user_city = \"Mumbai\"\n",
|
||||
"user_state = \"Maharashtra\"\n",
|
||||
"user_country = \"India\"\n",
|
||||
"user_medical_conditions = \"asthma\"\n",
|
||||
"user_planned_activity = \"morning jog for 2 hours\"\n",
|
||||
"\n",
|
||||
"aqi_fetcher = AQIDataFetcher(firecrawl_key=os.environ[\"FIRECRAWL_API_KEY\"])\n",
|
||||
"\n",
|
||||
"# Try with state, then without state, then fallback to Delhi\n",
|
||||
"aqi_data = aqi_fetcher.fetch(\n",
|
||||
" country=user_country,\n",
|
||||
" state=user_state,\n",
|
||||
" city=user_city\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"if not aqi_data or not hasattr(aqi_data, \"data\"):\n",
|
||||
" print(\"Mumbai with state failed, trying without state...\")\n",
|
||||
" aqi_data = aqi_fetcher.fetch(\n",
|
||||
" country=user_country,\n",
|
||||
" state=\"\",\n",
|
||||
" city=user_city\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
"if not aqi_data or not hasattr(aqi_data, \"data\"):\n",
|
||||
" print(\"Trying Delhi, India...\")\n",
|
||||
" aqi_data = aqi_fetcher.fetch(\n",
|
||||
" country=\"India\",\n",
|
||||
" state=\"\",\n",
|
||||
" city=\"Delhi\"\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
"if not aqi_data or not hasattr(aqi_data, \"data\"):\n",
|
||||
" print(\"Failed to fetch AQI data for all tried locations. Please check the URLs manually.\")\n",
|
||||
"else:\n",
|
||||
" aqi_data = aqi_data.data # Convert to dict\n",
|
||||
"\n",
|
||||
" prompt = f\"\"\"\n",
|
||||
" You are an expert health advisor using the GPT-4o Mini model.\n",
|
||||
"\n",
|
||||
" Based on the following air quality conditions in {user_city}, {user_state}, {user_country}:\n",
|
||||
" - Overall AQI: {aqi_data.get('aqi', 'N/A')}\n",
|
||||
" - PM2.5 Level: {aqi_data.get('pm25', 'N/A')} µg/m³\n",
|
||||
" - PM10 Level: {aqi_data.get('pm10', 'N/A')} µg/m³\n",
|
||||
" - CO Level: {aqi_data.get('co', 'N/A')} ppb\n",
|
||||
"\n",
|
||||
" Weather conditions:\n",
|
||||
" - Temperature: {aqi_data.get('temperature', 'N/A')}°C\n",
|
||||
" - Humidity: {aqi_data.get('humidity', 'N/A')}%\n",
|
||||
" - Wind Speed: {aqi_data.get('wind_speed', 'N/A')} km/h\n",
|
||||
"\n",
|
||||
" User's Context:\n",
|
||||
" - Medical Conditions: {user_medical_conditions or 'None'}\n",
|
||||
" - Planned Activity: {user_planned_activity}\n",
|
||||
"\n",
|
||||
" **Comprehensive Health Recommendations:**\n",
|
||||
" 1. **Impact of Current Air Quality on Health:**\n",
|
||||
" 2. **Necessary Safety Precautions for Planned Activity:**\n",
|
||||
" 3. **Advisability of Planned Activity:**\n",
|
||||
" 4. **Best Time to Conduct the Activity:**\n",
|
||||
" \"\"\"\n",
|
||||
"\n",
|
||||
" agent = Agent(\n",
|
||||
" name=\"Air Quality Health Advisor\",\n",
|
||||
" instructions=prompt,\n",
|
||||
" api_key=os.environ[\"OPENAI_API_KEY\"]\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
" # Call run() with no arguments\n",
|
||||
"recommendations = agent.start(prompt)\n",
|
||||
"print(\"=== Air Quality Analysis Agent Recommendations ===\")\n",
|
||||
"print(recommendations)"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"provenance": []
|
||||
},
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"name": "python"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 0
|
||||
}
|
||||
+1199
File diff suppressed because it is too large.
Load diff
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,564 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "Z-9SQRoVyG_O"
|
||||
},
|
||||
"source": [
|
||||
"# Domain Deep Research Agent using PraisonAIAgents"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "EZYCPU_ayIMD"
|
||||
},
|
||||
"source": [
|
||||
"This notebook demonstrates a Domain Deep Research Agent using `praisonaiagents`. \n",
|
||||
"The agent performs deep research on a given topic and provides a structured report. \n",
|
||||
"The notebook is CI-friendly: it uses dummy data if API keys are not set, so all tests/checks will pass."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "taa8dcsdyxHT"
|
||||
},
|
||||
"source": [
|
||||
"[](https://colab.research.google.com/github/Dhivya-Bharathy/PraisonAI/blob/main/examples/cookbooks/Research_Knowledge_QA_Agents/Domain_Deep_Research_Agent.ipynb)\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "v0VlXFo-yKNA"
|
||||
},
|
||||
"source": [
|
||||
"# Dependencies"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "t9Dw5BDryNIa"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"!pip install praisonaiagents"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "V_9FzwguyS7g"
|
||||
},
|
||||
"source": [
|
||||
"# Set up key (robust, CI-safe)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 2,
|
||||
"metadata": {
|
||||
"id": "-l0w3hmLyT47"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import os\n",
|
||||
"\n",
|
||||
"os.environ[\"OPENAI_API_KEY\"] = os.environ.get(\"OPENAI_API_KEY\", \"sk-..\")\n",
|
||||
"\n",
|
||||
"def is_valid_key(key, prefix):\n",
|
||||
" return key and key != f\"{prefix}-..\" and key.startswith(prefix)\n",
|
||||
"\n",
|
||||
"OPENAI_API_KEY = os.environ[\"OPENAI_API_KEY\"]"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "xkHGhtnmyZ3m"
|
||||
},
|
||||
"source": [
|
||||
"# Custom Tool: Dummy Deep Research Tool"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 3,
|
||||
"metadata": {
|
||||
"id": "vATC0ZOVyax0"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"class DummyDeepResearchTool:\n",
|
||||
" \"\"\"\n",
|
||||
" Custom tool to simulate deep research for CI/public use.\n",
|
||||
" \"\"\"\n",
|
||||
" def __init__(self, topic):\n",
|
||||
" self.topic = topic\n",
|
||||
"\n",
|
||||
" def research(self):\n",
|
||||
" # For demo/CI, just return a dummy report\n",
|
||||
" return f\"## Research Report on {self.topic}\\n\\n- Key finding 1 about {self.topic}\\n- Key finding 2 about {self.topic}\\n- Key finding 3 about {self.topic}\\n\""
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "t-TlO3WuyeYl"
|
||||
},
|
||||
"source": [
|
||||
"# Main (with dummy fallback, CI-safe)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 4,
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"base_uri": "https://localhost:8080/",
|
||||
"height": 1000,
|
||||
"referenced_widgets": [
|
||||
"520e1878a8d64958a9b73edc91260284",
|
||||
"e6b0f40254e54f5a9200996d38ecbd10"
|
||||
]
|
||||
},
|
||||
"id": "cor8P2BlyfQt",
|
||||
"outputId": "750a1fba-d0f2-4279-a5bb-b3743db2c852"
|
||||
},
|
||||
"outputs": [
|
||||
{
|
||||
"data": {
|
||||
"text/html": [
|
||||
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">╭─ </span><span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8; font-weight: bold\">Agent Info</span><span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\"> ────────────────────────────────────────────────────────────────────────────────────────────────────╮</span>\n",
|
||||
"<span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">│</span> <span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">│</span>\n",
|
||||
"<span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">│</span> <span style=\"color: #ff9b9b; text-decoration-color: #ff9b9b; font-weight: bold\">👤 Agent:</span> <span style=\"color: #ffe5e5; text-decoration-color: #ffe5e5\">Domain Deep Research Agent</span> <span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">│</span>\n",
|
||||
"<span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">│</span> <span style=\"color: #b4b4b3; text-decoration-color: #b4b4b3; font-weight: bold\">Role:</span> <span style=\"color: #ffe5e5; text-decoration-color: #ffe5e5\">Assistant</span> <span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">│</span>\n",
|
||||
"<span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">│</span> <span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">│</span>\n",
|
||||
"<span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯</span>\n",
|
||||
"</pre>\n"
|
||||
],
|
||||
"text/plain": [
|
||||
"\u001b[38;2;210;227;200m╭─\u001b[0m\u001b[38;2;210;227;200m \u001b[0m\u001b[1;38;2;210;227;200mAgent Info\u001b[0m\u001b[38;2;210;227;200m \u001b[0m\u001b[38;2;210;227;200m───────────────────────────────────────────────────────────────────────────────────────────────────\u001b[0m\u001b[38;2;210;227;200m─╮\u001b[0m\n",
|
||||
"\u001b[38;2;210;227;200m│\u001b[0m \u001b[38;2;210;227;200m│\u001b[0m\n",
|
||||
"\u001b[38;2;210;227;200m│\u001b[0m \u001b[1;38;2;255;155;155m👤 Agent:\u001b[0m \u001b[38;2;255;229;229mDomain Deep Research Agent\u001b[0m \u001b[38;2;210;227;200m│\u001b[0m\n",
|
||||
"\u001b[38;2;210;227;200m│\u001b[0m \u001b[1;38;2;180;180;179mRole:\u001b[0m \u001b[38;2;255;229;229mAssistant\u001b[0m \u001b[38;2;210;227;200m│\u001b[0m\n",
|
||||
"\u001b[38;2;210;227;200m│\u001b[0m \u001b[38;2;210;227;200m│\u001b[0m\n",
|
||||
"\u001b[38;2;210;227;200m╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯\u001b[0m\n"
|
||||
]
|
||||
},
|
||||
"metadata": {},
|
||||
"output_type": "display_data"
|
||||
},
|
||||
{
|
||||
"data": {
|
||||
"application/vnd.jupyter.widget-view+json": {
|
||||
"model_id": "520e1878a8d64958a9b73edc91260284",
|
||||
"version_major": 2,
|
||||
"version_minor": 0
|
||||
},
|
||||
"text/plain": [
|
||||
"Output()"
|
||||
]
|
||||
},
|
||||
"metadata": {},
|
||||
"output_type": "display_data"
|
||||
},
|
||||
{
|
||||
"data": {
|
||||
"text/html": [
|
||||
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"></pre>\n"
|
||||
],
|
||||
"text/plain": []
|
||||
},
|
||||
"metadata": {},
|
||||
"output_type": "display_data"
|
||||
},
|
||||
{
|
||||
"data": {
|
||||
"text/html": [
|
||||
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">\n",
|
||||
"</pre>\n"
|
||||
],
|
||||
"text/plain": [
|
||||
"\n"
|
||||
]
|
||||
},
|
||||
"metadata": {},
|
||||
"output_type": "display_data"
|
||||
},
|
||||
{
|
||||
"data": {
|
||||
"text/html": [
|
||||
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"color: #7f7f7f; text-decoration-color: #7f7f7f\">Response generated in 25.8s</span>\n",
|
||||
"</pre>\n"
|
||||
],
|
||||
"text/plain": [
|
||||
"\u001b[2mResponse generated in 25.8s\u001b[0m\n"
|
||||
]
|
||||
},
|
||||
"metadata": {},
|
||||
"output_type": "display_data"
|
||||
},
|
||||
{
|
||||
"data": {
|
||||
"text/html": [
|
||||
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"color: #008080; text-decoration-color: #008080\">╭───────────────────────────────────────────────────── Task ──────────────────────────────────────────────────────╮</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> You are a domain research assistant. Perform deep research on the following topic and provide a structured, <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> well-cited report: TOPIC: Recent advances in quantum computing <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯</span>\n",
|
||||
"</pre>\n"
|
||||
],
|
||||
"text/plain": [
|
||||
"\u001b[36m╭─\u001b[0m\u001b[36m────────────────────────────────────────────────────\u001b[0m\u001b[36m Task \u001b[0m\u001b[36m─────────────────────────────────────────────────────\u001b[0m\u001b[36m─╮\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m You are a domain research assistant. Perform deep research on the following topic and provide a structured, \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m well-cited report: TOPIC: Recent advances in quantum computing \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯\u001b[0m\n"
|
||||
]
|
||||
},
|
||||
"metadata": {},
|
||||
"output_type": "display_data"
|
||||
},
|
||||
{
|
||||
"data": {
|
||||
"text/html": [
|
||||
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"color: #008080; text-decoration-color: #008080\">╭─────────────────────────────────────────────────── Response ────────────────────────────────────────────────────╮</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> ┃ <span style=\"font-weight: bold\">Recent Advances in Quantum Computing</span> ┃ <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> Quantum computing is a rapidly evolving field that leverages the principles of quantum mechanics to process <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> information in fundamentally new ways. This report highlights some of the most significant recent advances in <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> quantum computing, focusing on developments in hardware, algorithms, and applications. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"font-weight: bold; text-decoration: underline\">1. Quantum Hardware Developments</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"font-weight: bold\">1.1 Superconducting Qubits</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> Superconducting qubits have been at the forefront of quantum computing hardware. Companies like IBM and Google <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> have made significant strides in increasing the coherence times and connectivity of these qubits. In 2023, IBM <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> announced the development of their 433-qubit processor, Osprey, which is part of their roadmap to achieve a <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> 1,000-qubit system by 2024 [1]. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"font-weight: bold\">1.2 Trapped Ion Qubits</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> Trapped ion technology continues to be a strong contender due to its high fidelity and long coherence times. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> IonQ, a leader in this space, has developed systems that can execute quantum circuits with high precision. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> Their recent advancements include the development of error-corrected logical qubits, which are crucial for <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> scalable quantum computing [2]. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"font-weight: bold\">1.3 Photonic Quantum Computing</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> Photonic quantum computing has seen breakthroughs with companies like Xanadu and PsiQuantum. Xanadu's Borealis, <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> a photonic quantum computer, demonstrated quantum advantage by solving specific problems faster than classical <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> supercomputers [3]. PsiQuantum is working towards a million-qubit photonic quantum computer, leveraging silicon <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> photonics for scalability [4]. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"font-weight: bold; text-decoration: underline\">2. Quantum Algorithms</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"font-weight: bold\">2.1 Quantum Machine Learning</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> Quantum machine learning (QML) is gaining traction as researchers develop algorithms that could outperform <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> classical counterparts. Recent work has focused on hybrid quantum-classical algorithms that leverage quantum <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> speedups for specific tasks like clustering and classification [5]. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"font-weight: bold\">2.2 Quantum Error Correction</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> Error correction remains a critical challenge in quantum computing. Recent advances include the development of <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> more efficient error-correcting codes and fault-tolerant architectures. The surface code, a leading error <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> correction method, has seen improvements in its threshold and resource requirements [6]. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"font-weight: bold\">2.3 Quantum Simulation</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> Quantum simulation is one of the most promising applications of quantum computing. Recent studies have <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> demonstrated the simulation of complex quantum systems, such as chemical reactions and material properties, <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> with unprecedented accuracy [7]. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"font-weight: bold; text-decoration: underline\">3. Applications and Industry Impact</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"font-weight: bold\">3.1 Cryptography</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> Quantum computing poses both threats and opportunities for cryptography. The development of quantum-resistant <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> algorithms is crucial as quantum computers could potentially break widely used encryption methods. The National <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> Institute of Standards and Technology (NIST) is in the process of standardizing post-quantum cryptographic <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> algorithms [8]. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"font-weight: bold\">3.2 Drug Discovery</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> Quantum computing is poised to revolutionize drug discovery by enabling the simulation of molecular <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> interactions at a quantum level. Companies like Qubit Pharmaceuticals and Cambridge Quantum Computing are <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> actively working on quantum algorithms for drug discovery, promising faster and more accurate predictions [9]. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"font-weight: bold\">3.3 Optimization Problems</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> Quantum computers have the potential to solve complex optimization problems more efficiently than classical <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> computers. This has significant implications for industries such as logistics, finance, and manufacturing. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> Recent advances include the development of quantum algorithms for portfolio optimization and supply chain <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> management [10]. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"font-weight: bold; text-decoration: underline\">4. Challenges and Future Directions</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> Despite the rapid progress, several challenges remain in the field of quantum computing. These include <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> improving qubit coherence times, scaling up the number of qubits, and developing robust error correction <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> methods. Future research is likely to focus on hybrid quantum-classical systems, which combine the strengths of <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> both paradigms to tackle complex problems. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"font-weight: bold; text-decoration: underline\">Conclusion</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> Quantum computing is advancing at a remarkable pace, with significant developments in hardware, algorithms, and <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> applications. As the field continues to mature, it holds the promise of transforming industries and solving <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> problems that are currently intractable for classical computers. Continued investment in research and <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> development, along with collaboration between academia and industry, will be crucial to realizing the full <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> potential of quantum computing. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"font-weight: bold; text-decoration: underline\">References</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> 1 </span>IBM Research. (2023). IBM Quantum Roadmap. Retrieved from <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> </span>https://research.ibm.com/quantum-computing/roadmap <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> 2 </span>IonQ. (2023). IonQ's Quantum Computing Technology. Retrieved from https://ionq.com/technology <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> 3 </span>Xanadu. (2023). Borealis: A Photonic Quantum Computer. Retrieved from https://xanadu.ai/borealis <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> 4 </span>PsiQuantum. (2023). Photonic Quantum Computing. Retrieved from https://psiquantum.com/technology <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> 5 </span>Biamonte, J., et al. (2023). Quantum Machine Learning. Nature Reviews Physics. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> 6 </span>Fowler, A. G., et al. (2023). Surface Codes: Towards Practical Quantum Computing. Physical Review A. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> 7 </span>Aspuru-Guzik, A., et al. (2023). Quantum Simulation of Chemical Systems. Chemical Reviews. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> 8 </span>NIST. (2023). Post-Quantum Cryptography Standardization. Retrieved from <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> </span>https://csrc.nist.gov/Projects/post-quantum-cryptography <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> 9 </span>Qubit Pharmaceuticals. (2023). Quantum Computing in Drug Discovery. Retrieved from <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> </span>https://qubit-pharmaceuticals.com/quantum-computing <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> 10 </span>Venturelli, D., et al. (2023). Quantum Optimization Algorithms. Journal of Quantum Information Processing. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯</span>\n",
|
||||
"</pre>\n"
|
||||
],
|
||||
"text/plain": [
|
||||
"\u001b[36m╭─\u001b[0m\u001b[36m──────────────────────────────────────────────────\u001b[0m\u001b[36m Response \u001b[0m\u001b[36m───────────────────────────────────────────────────\u001b[0m\u001b[36m─╮\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m ┃ \u001b[1mRecent Advances in Quantum Computing\u001b[0m ┃ \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m Quantum computing is a rapidly evolving field that leverages the principles of quantum mechanics to process \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m information in fundamentally new ways. This report highlights some of the most significant recent advances in \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m quantum computing, focusing on developments in hardware, algorithms, and applications. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;4m1. Quantum Hardware Developments\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1m1.1 Superconducting Qubits\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m Superconducting qubits have been at the forefront of quantum computing hardware. Companies like IBM and Google \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m have made significant strides in increasing the coherence times and connectivity of these qubits. In 2023, IBM \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m announced the development of their 433-qubit processor, Osprey, which is part of their roadmap to achieve a \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m 1,000-qubit system by 2024 [1]. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1m1.2 Trapped Ion Qubits\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m Trapped ion technology continues to be a strong contender due to its high fidelity and long coherence times. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m IonQ, a leader in this space, has developed systems that can execute quantum circuits with high precision. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m Their recent advancements include the development of error-corrected logical qubits, which are crucial for \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m scalable quantum computing [2]. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1m1.3 Photonic Quantum Computing\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m Photonic quantum computing has seen breakthroughs with companies like Xanadu and PsiQuantum. Xanadu's Borealis, \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m a photonic quantum computer, demonstrated quantum advantage by solving specific problems faster than classical \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m supercomputers [3]. PsiQuantum is working towards a million-qubit photonic quantum computer, leveraging silicon \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m photonics for scalability [4]. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;4m2. Quantum Algorithms\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1m2.1 Quantum Machine Learning\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m Quantum machine learning (QML) is gaining traction as researchers develop algorithms that could outperform \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m classical counterparts. Recent work has focused on hybrid quantum-classical algorithms that leverage quantum \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m speedups for specific tasks like clustering and classification [5]. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1m2.2 Quantum Error Correction\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m Error correction remains a critical challenge in quantum computing. Recent advances include the development of \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m more efficient error-correcting codes and fault-tolerant architectures. The surface code, a leading error \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m correction method, has seen improvements in its threshold and resource requirements [6]. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1m2.3 Quantum Simulation\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m Quantum simulation is one of the most promising applications of quantum computing. Recent studies have \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m demonstrated the simulation of complex quantum systems, such as chemical reactions and material properties, \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m with unprecedented accuracy [7]. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;4m3. Applications and Industry Impact\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1m3.1 Cryptography\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m Quantum computing poses both threats and opportunities for cryptography. The development of quantum-resistant \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m algorithms is crucial as quantum computers could potentially break widely used encryption methods. The National \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m Institute of Standards and Technology (NIST) is in the process of standardizing post-quantum cryptographic \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m algorithms [8]. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1m3.2 Drug Discovery\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m Quantum computing is poised to revolutionize drug discovery by enabling the simulation of molecular \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m interactions at a quantum level. Companies like Qubit Pharmaceuticals and Cambridge Quantum Computing are \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m actively working on quantum algorithms for drug discovery, promising faster and more accurate predictions [9]. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1m3.3 Optimization Problems\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m Quantum computers have the potential to solve complex optimization problems more efficiently than classical \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m computers. This has significant implications for industries such as logistics, finance, and manufacturing. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m Recent advances include the development of quantum algorithms for portfolio optimization and supply chain \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m management [10]. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;4m4. Challenges and Future Directions\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m Despite the rapid progress, several challenges remain in the field of quantum computing. These include \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m improving qubit coherence times, scaling up the number of qubits, and developing robust error correction \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m methods. Future research is likely to focus on hybrid quantum-classical systems, which combine the strengths of \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m both paradigms to tackle complex problems. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;4mConclusion\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m Quantum computing is advancing at a remarkable pace, with significant developments in hardware, algorithms, and \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m applications. As the field continues to mature, it holds the promise of transforming industries and solving \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m problems that are currently intractable for classical computers. Continued investment in research and \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m development, along with collaboration between academia and industry, will be crucial to realizing the full \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m potential of quantum computing. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;4mReferences\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m 1 \u001b[0mIBM Research. (2023). IBM Quantum Roadmap. Retrieved from \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0mhttps://research.ibm.com/quantum-computing/roadmap \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m 2 \u001b[0mIonQ. (2023). IonQ's Quantum Computing Technology. Retrieved from https://ionq.com/technology \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m 3 \u001b[0mXanadu. (2023). Borealis: A Photonic Quantum Computer. Retrieved from https://xanadu.ai/borealis \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m 4 \u001b[0mPsiQuantum. (2023). Photonic Quantum Computing. Retrieved from https://psiquantum.com/technology \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m 5 \u001b[0mBiamonte, J., et al. (2023). Quantum Machine Learning. Nature Reviews Physics. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m 6 \u001b[0mFowler, A. G., et al. (2023). Surface Codes: Towards Practical Quantum Computing. Physical Review A. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m 7 \u001b[0mAspuru-Guzik, A., et al. (2023). Quantum Simulation of Chemical Systems. Chemical Reviews. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m 8 \u001b[0mNIST. (2023). Post-Quantum Cryptography Standardization. Retrieved from \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0mhttps://csrc.nist.gov/Projects/post-quantum-cryptography \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m 9 \u001b[0mQubit Pharmaceuticals. (2023). Quantum Computing in Drug Discovery. Retrieved from \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0mhttps://qubit-pharmaceuticals.com/quantum-computing \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1;33m 10 \u001b[0mVenturelli, D., et al. (2023). Quantum Optimization Algorithms. Journal of Quantum Information Processing. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯\u001b[0m\n"
|
||||
]
|
||||
},
|
||||
"metadata": {},
|
||||
"output_type": "display_data"
|
||||
},
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"# Recent Advances in Quantum Computing\n",
|
||||
"\n",
|
||||
"Quantum computing is a rapidly evolving field that leverages the principles of quantum mechanics to process information in fundamentally new ways. This report highlights some of the most significant recent advances in quantum computing, focusing on developments in hardware, algorithms, and applications.\n",
|
||||
"\n",
|
||||
"## 1. Quantum Hardware Developments\n",
|
||||
"\n",
|
||||
"### 1.1 Superconducting Qubits\n",
|
||||
"Superconducting qubits have been at the forefront of quantum computing hardware. Companies like IBM and Google have made significant strides in increasing the coherence times and connectivity of these qubits. In 2023, IBM announced the development of their 433-qubit processor, Osprey, which is part of their roadmap to achieve a 1,000-qubit system by 2024 [1].\n",
|
||||
"\n",
|
||||
"### 1.2 Trapped Ion Qubits\n",
|
||||
"Trapped ion technology continues to be a strong contender due to its high fidelity and long coherence times. IonQ, a leader in this space, has developed systems that can execute quantum circuits with high precision. Their recent advancements include the development of error-corrected logical qubits, which are crucial for scalable quantum computing [2].\n",
|
||||
"\n",
|
||||
"### 1.3 Photonic Quantum Computing\n",
|
||||
"Photonic quantum computing has seen breakthroughs with companies like Xanadu and PsiQuantum. Xanadu's Borealis, a photonic quantum computer, demonstrated quantum advantage by solving specific problems faster than classical supercomputers [3]. PsiQuantum is working towards a million-qubit photonic quantum computer, leveraging silicon photonics for scalability [4].\n",
|
||||
"\n",
|
||||
"## 2. Quantum Algorithms\n",
|
||||
"\n",
|
||||
"### 2.1 Quantum Machine Learning\n",
|
||||
"Quantum machine learning (QML) is gaining traction as researchers develop algorithms that could outperform classical counterparts. Recent work has focused on hybrid quantum-classical algorithms that leverage quantum speedups for specific tasks like clustering and classification [5].\n",
|
||||
"\n",
|
||||
"### 2.2 Quantum Error Correction\n",
|
||||
"Error correction remains a critical challenge in quantum computing. Recent advances include the development of more efficient error-correcting codes and fault-tolerant architectures. The surface code, a leading error correction method, has seen improvements in its threshold and resource requirements [6].\n",
|
||||
"\n",
|
||||
"### 2.3 Quantum Simulation\n",
|
||||
"Quantum simulation is one of the most promising applications of quantum computing. Recent studies have demonstrated the simulation of complex quantum systems, such as chemical reactions and material properties, with unprecedented accuracy [7].\n",
|
||||
"\n",
|
||||
"## 3. Applications and Industry Impact\n",
|
||||
"\n",
|
||||
"### 3.1 Cryptography\n",
|
||||
"Quantum computing poses both threats and opportunities for cryptography. The development of quantum-resistant algorithms is crucial as quantum computers could potentially break widely used encryption methods. The National Institute of Standards and Technology (NIST) is in the process of standardizing post-quantum cryptographic algorithms [8].\n",
|
||||
"\n",
|
||||
"### 3.2 Drug Discovery\n",
|
||||
"Quantum computing is poised to revolutionize drug discovery by enabling the simulation of molecular interactions at a quantum level. Companies like Qubit Pharmaceuticals and Cambridge Quantum Computing are actively working on quantum algorithms for drug discovery, promising faster and more accurate predictions [9].\n",
|
||||
"\n",
|
||||
"### 3.3 Optimization Problems\n",
|
||||
"Quantum computers have the potential to solve complex optimization problems more efficiently than classical computers. This has significant implications for industries such as logistics, finance, and manufacturing. Recent advances include the development of quantum algorithms for portfolio optimization and supply chain management [10].\n",
|
||||
"\n",
|
||||
"## 4. Challenges and Future Directions\n",
|
||||
"\n",
|
||||
"Despite the rapid progress, several challenges remain in the field of quantum computing. These include improving qubit coherence times, scaling up the number of qubits, and developing robust error correction methods. Future research is likely to focus on hybrid quantum-classical systems, which combine the strengths of both paradigms to tackle complex problems.\n",
|
||||
"\n",
|
||||
"## Conclusion\n",
|
||||
"\n",
|
||||
"Quantum computing is advancing at a remarkable pace, with significant developments in hardware, algorithms, and applications. As the field continues to mature, it holds the promise of transforming industries and solving problems that are currently intractable for classical computers. Continued investment in research and development, along with collaboration between academia and industry, will be crucial to realizing the full potential of quantum computing.\n",
|
||||
"\n",
|
||||
"## References\n",
|
||||
"\n",
|
||||
"1. IBM Research. (2023). IBM Quantum Roadmap. Retrieved from https://research.ibm.com/quantum-computing/roadmap\n",
|
||||
"2. IonQ. (2023). IonQ's Quantum Computing Technology. Retrieved from https://ionq.com/technology\n",
|
||||
"3. Xanadu. (2023). Borealis: A Photonic Quantum Computer. Retrieved from https://xanadu.ai/borealis\n",
|
||||
"4. PsiQuantum. (2023). Photonic Quantum Computing. Retrieved from https://psiquantum.com/technology\n",
|
||||
"5. Biamonte, J., et al. (2023). Quantum Machine Learning. Nature Reviews Physics.\n",
|
||||
"6. Fowler, A. G., et al. (2023). Surface Codes: Towards Practical Quantum Computing. Physical Review A.\n",
|
||||
"7. Aspuru-Guzik, A., et al. (2023). Quantum Simulation of Chemical Systems. Chemical Reviews.\n",
|
||||
"8. NIST. (2023). Post-Quantum Cryptography Standardization. Retrieved from https://csrc.nist.gov/Projects/post-quantum-cryptography\n",
|
||||
"9. Qubit Pharmaceuticals. (2023). Quantum Computing in Drug Discovery. Retrieved from https://qubit-pharmaceuticals.com/quantum-computing\n",
|
||||
"10. Venturelli, D., et al. (2023). Quantum Optimization Algorithms. Journal of Quantum Information Processing.\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"from praisonaiagents import Agent\n",
|
||||
"\n",
|
||||
"# User input (for demo, hardcoded; in real use, use input() or widgets)\n",
|
||||
"topic = \"Recent advances in quantum computing\"\n",
|
||||
"\n",
|
||||
"# Use the custom tool\n",
|
||||
"tool = DummyDeepResearchTool(topic)\n",
|
||||
"dummy_report = tool.research()\n",
|
||||
"\n",
|
||||
"if not is_valid_key(OPENAI_API_KEY, \"sk\"):\n",
|
||||
" print(\"API key not set or is a placeholder. Using dummy research report for CI/testing.\")\n",
|
||||
" print(dummy_report)\n",
|
||||
"else:\n",
|
||||
" prompt = f\"\"\"\n",
|
||||
" You are a domain research assistant. Perform deep research on the following topic and provide a structured, well-cited report:\n",
|
||||
" TOPIC: {topic}\n",
|
||||
" \"\"\"\n",
|
||||
" agent = Agent(\n",
|
||||
" name=\"Domain Deep Research Agent\",\n",
|
||||
" instructions=prompt,\n",
|
||||
" api_key=OPENAI_API_KEY\n",
|
||||
" )\n",
|
||||
" report = agent.start(prompt)\n",
|
||||
" print(report)"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"provenance": []
|
||||
},
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"name": "python"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 0
|
||||
}
|
||||
+689
@@ -0,0 +1,689 @@
|
||||
{
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 0,
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"provenance": []
|
||||
},
|
||||
"kernelspec": {
|
||||
"name": "python3",
|
||||
"display_name": "Python 3"
|
||||
},
|
||||
"language_info": {
|
||||
"name": "python"
|
||||
},
|
||||
"widgets": {
|
||||
"application/vnd.jupyter.widget-state+json": {
|
||||
"4ab88bfcb62e4f9a8db7e35aefbae00a": {
|
||||
"model_module": "@jupyter-widgets/output",
|
||||
"model_name": "OutputModel",
|
||||
"model_module_version": "1.0.0",
|
||||
"state": {
|
||||
"_dom_classes": [],
|
||||
"_model_module": "@jupyter-widgets/output",
|
||||
"_model_module_version": "1.0.0",
|
||||
"_model_name": "OutputModel",
|
||||
"_view_count": null,
|
||||
"_view_module": "@jupyter-widgets/output",
|
||||
"_view_module_version": "1.0.0",
|
||||
"_view_name": "OutputView",
|
||||
"layout": "IPY_MODEL_3d1ae7a6c0a947f985f6ef921b74ecf8",
|
||||
"msg_id": "",
|
||||
"outputs": [
|
||||
{
|
||||
"output_type": "display_data",
|
||||
"data": {
|
||||
"text/plain": "\u001b[32m╭─\u001b[0m\u001b[32m─────────────────────────────────────────────\u001b[0m\u001b[32m Generating... 23.2s \u001b[0m\u001b[32m─────────────────────────────────────────────\u001b[0m\u001b[32m─╮\u001b[0m\n\u001b[32m│\u001b[0m [INTRO MUSIC FADES IN] \u001b[32m│\u001b[0m\n\u001b[32m│\u001b[0m \u001b[32m│\u001b[0m\n\u001b[32m│\u001b[0m \u001b[1mAlex\u001b[0m: Hello and welcome to another episode of \"The World Today,\" where we dive into the latest in technology \u001b[32m│\u001b[0m\n\u001b[32m│\u001b[0m and world news. I'm Alex, your go-to for all things analytical and fact-focused. \u001b[32m│\u001b[0m\n\u001b[32m│\u001b[0m \u001b[32m│\u001b[0m\n\u001b[32m│\u001b[0m \u001b[1mMorgan\u001b[0m: And I'm Morgan, here to explore the human impact and social context of today's stories. We've got a \u001b[32m│\u001b[0m\n\u001b[32m│\u001b[0m fascinating lineup for you today, so let's dive right in! \u001b[32m│\u001b[0m\n\u001b[32m│\u001b[0m \u001b[32m│\u001b[0m\n\u001b[32m│\u001b[0m \u001b[1mAlex\u001b[0m: First up, we're talking about a topic that's been making waves across the healthcare industry: the role \u001b[32m│\u001b[0m\n\u001b[32m│\u001b[0m of artificial intelligence. According to a recent article from \u001b]8;id=672819;https://news.example.com/ai-healthcare\u001b\\\u001b[4;34mNews Example\u001b[0m\u001b]8;;\u001b\\, AI is revolutionizing healthcare \u001b[32m│\u001b[0m\n\u001b[32m│\u001b[0m in ways we could only dream of a decade ago. \u001b[32m│\u001b[0m\n\u001b[32m│\u001b[0m \u001b[32m│\u001b[0m\n\u001b[32m│\u001b[0m \u001b[1mMorgan\u001b[0m: That's right, Alex. AI is not just a buzzword anymore; it's actively changing how we approach \u001b[32m│\u001b[0m\n\u001b[32m│\u001b[0m healthcare. From diagnostics to treatment plans, AI is helping doctors make more accurate decisions faster. But \u001b[32m│\u001b[0m\n\u001b[32m│\u001b[0m what does this mean for patients and healthcare professionals? \u001b[32m│\u001b[0m\n\u001b[32m│\u001b[0m \u001b[32m│\u001b[0m\n\u001b[32m│\u001b[0m \u001b[1mAlex\u001b[0m: Well, Morgan, AI's ability to analyze vast amounts of data quickly means that doctors can diagnose \u001b[32m│\u001b[0m\n\u001b[32m│\u001b[0m diseases earlier and more accurately. For instance, AI algorithms can now detect patterns in medical imaging \u001b[32m│\u001b[0m\n\u001b[32m│\u001b[0m that might be too subtle for the human eye. This can lead to earlier interventions and better patient outcomes. \u001b[32m│\u001b[0m\n\u001b[32m│\u001b[0m \u001b[32m│\u001b[0m\n\u001b[32m│\u001b[0m \u001b[1mMorgan\u001b[0m: And let's not forget about the human side of things. For patients, this means less waiting time for \u001b[32m│\u001b[0m\n\u001b[32m│\u001b[0m results and potentially more personalized treatment plans. But there's also a concern about the human touch in \u001b[32m│\u001b[0m\n\u001b[32m│\u001b[0m healthcare. How do we balance the efficiency of AI with the empathy and understanding that only a human can \u001b[32m│\u001b[0m\n\u001b[32m│\u001b[0m provide? \u001b[32m│\u001b[0m\n\u001b[32m│\u001b[0m \u001b[32m│\u001b[0m\n\u001b[32m│\u001b[0m \u001b[1mAlex\u001b[0m: That's a great point. The integration of AI in healthcare does raise ethical questions. For example, who \u001b[32m│\u001b[0m\n\u001b[32m│\u001b[0m is responsible if an AI system makes a mistake? And how do we ensure that these systems are free from bias? \u001b[32m│\u001b[0m\n\u001b[32m│\u001b[0m Line truncated
|
||||
"text/html": "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"color: #008000; text-decoration-color: #008000\">╭────────────────────────────────────────────── Generating... 23.2s ──────────────────────────────────────────────╮</span>\n<span style=\"color: #008000; text-decoration-color: #008000\">│</span> [INTRO MUSIC FADES IN] <span style=\"color: #008000; text-decoration-color: #008000\">│</span>\n<span style=\"color: #008000; text-decoration-color: #008000\">│</span> <span style=\"color: #008000; text-decoration-color: #008000\">│</span>\n<span style=\"color: #008000; text-decoration-color: #008000\">│</span> <span style=\"font-weight: bold\">Alex</span>: Hello and welcome to another episode of \"The World Today,\" where we dive into the latest in technology <span style=\"color: #008000; text-decoration-color: #008000\">│</span>\n<span style=\"color: #008000; text-decoration-color: #008000\">│</span> and world news. I'm Alex, your go-to for all things analytical and fact-focused. <span style=\"color: #008000; text-decoration-color: #008000\">│</span>\n<span style=\"color: #008000; text-decoration-color: #008000\">│</span> <span style=\"color: #008000; text-decoration-color: #008000\">│</span>\n<span style=\"color: #008000; text-decoration-color: #008000\">│</span> <span style=\"font-weight: bold\">Morgan</span>: And I'm Morgan, here to explore the human impact and social context of today's stories. We've got a <span style=\"color: #008000; text-decoration-color: #008000\">│</span>\n<span style=\"color: #008000; text-decoration-color: #008000\">│</span> fascinating lineup for you today, so let's dive right in! <span style=\"color: #008000; text-decoration-color: #008000\">│</span>\n<span style=\"color: #008000; text-decoration-color: #008000\">│</span> <span style=\"color: #008000; text-decoration-color: #008000\">│</span>\n<span style=\"color: #008000; text-decoration-color: #008000\">│</span> <span style=\"font-weight: bold\">Alex</span>: First up, we're talking about a topic that's been making waves across the healthcare industry: the role <span style=\"color: #008000; text-decoration-color: #008000\">│</span>\n<span style=\"color: #008000; text-decoration-color: #008000\">│</span> of artificial intelligence. According to a recent article from <a href=\"https://news.example.com/ai-healthcare\" target=\"_blank\"><span style=\"color: #000080; text-decoration-color: #000080; text-decoration: underline\">News Example</span></a>, AI is revolutionizing healthcare <span style=\"color: #008000; text-decoration-color: #008000\">│</span>\n<span style=\"color: #008000; text-decoration-color: #008000\">│</span> in ways we could only dream of a decade ago. <span style=\"color: #008000; text-decoration-color: #008000\">│</span>\n<span style=\"color: #008000; text-decoration-color: #008000\">│</span> <span style=\"color: #008000; text-decoration-color: #008000\">│</span>\n<span style=\"color: #008000; text-decoration-color: #008000\">│</span> <span style=\"font-weight: bold\">Morgan</span>: That's right, Alex. AI is not just a buzzword anymore; it's actively changing how we approach <span style=\"color: #008000; text-decoration-color: #008000\">│</span>\n<span style=\"color: #008000; text-decoration-color: #008000\">│</span> healthcare. From diagnostics to treatment plans, AI is helping doctors make more accurate decisions faster. But <span style=\"color: #008000; text-decoration-color: #008000\">│</span>\n<span style=\"color: #008000; text-decoration-color: #008000\">│</span> what does this mean for patients and healthcare professionals? <span style=\"color: #008000; text-decoration-color: #008000\">│</span>\n<span style=\"color: #008000; text-decoration-color: #008000\">│</span> <span style=\"coloLine truncated
|
||||
},
|
||||
"metadata": {}
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"3d1ae7a6c0a947f985f6ef921b74ecf8": {
|
||||
"model_module": "@jupyter-widgets/base",
|
||||
"model_name": "LayoutModel",
|
||||
"model_module_version": "1.2.0",
|
||||
"state": {
|
||||
"_model_module": "@jupyter-widgets/base",
|
||||
"_model_module_version": "1.2.0",
|
||||
"_model_name": "LayoutModel",
|
||||
"_view_count": null,
|
||||
"_view_module": "@jupyter-widgets/base",
|
||||
"_view_module_version": "1.2.0",
|
||||
"_view_name": "LayoutView",
|
||||
"align_content": null,
|
||||
"align_items": null,
|
||||
"align_self": null,
|
||||
"border": null,
|
||||
"bottom": null,
|
||||
"display": null,
|
||||
"flex": null,
|
||||
"flex_flow": null,
|
||||
"grid_area": null,
|
||||
"grid_auto_columns": null,
|
||||
"grid_auto_flow": null,
|
||||
"grid_auto_rows": null,
|
||||
"grid_column": null,
|
||||
"grid_gap": null,
|
||||
"grid_row": null,
|
||||
"grid_template_areas": null,
|
||||
"grid_template_columns": null,
|
||||
"grid_template_rows": null,
|
||||
"height": null,
|
||||
"justify_content": null,
|
||||
"justify_items": null,
|
||||
"left": null,
|
||||
"margin": null,
|
||||
"max_height": null,
|
||||
"max_width": null,
|
||||
"min_height": null,
|
||||
"min_width": null,
|
||||
"object_fit": null,
|
||||
"object_position": null,
|
||||
"order": null,
|
||||
"overflow": null,
|
||||
"overflow_x": null,
|
||||
"overflow_y": null,
|
||||
"padding": null,
|
||||
"right": null,
|
||||
"top": null,
|
||||
"visibility": null,
|
||||
"width": null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"# News and Podcast Aggregator Agent using PraisonAIAgents"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "5DpLQOaCmYbu"
|
||||
}
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"This notebook demonstrates a News and Podcast Aggregator Agent built with `praisonaiagents`. \n",
|
||||
"It summarizes news articles and generates podcast-style discussion points. \n",
|
||||
"The notebook is CI-friendly: it uses dummy data if API keys are not set, so all tests/checks will pass."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "qmVwAahwmYTZ"
|
||||
}
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"[](https://colab.research.google.com/github/Dhivya-Bharathy/PraisonAI/blob/main/examples/cookbooks/SocialMedia_Content_Agents/News_And_Podcast_Aggregator_Agent.ipynb)\n"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "tYRRrgqHqbuN"
|
||||
}
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"# Dependencies"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "baTmwAjYmfDg"
|
||||
}
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "IIm2awOXmXB9"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"!pip install praisonaiagents pydantic"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"# Imports and Setup"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "kqNfe5S2mjnn"
|
||||
}
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"import os\n",
|
||||
"\n",
|
||||
"# Set up the OpenAI API key for praisonaiagents\n",
|
||||
"os.environ[\"OPENAI_API_KEY\"] = os.environ.get(\"OPENAI_API_KEY\", \"sk-..\")\n",
|
||||
"\n",
|
||||
"def is_valid_key(key, prefix):\n",
|
||||
" return key and key != f\"{prefix}-..\" and key.startswith(prefix)\n",
|
||||
"\n",
|
||||
"OPENAI_API_KEY = os.environ[\"OPENAI_API_KEY\"]"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "A-OXlt2gmpUS"
|
||||
},
|
||||
"execution_count": 3,
|
||||
"outputs": []
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"# Tools"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "IJmdTrCDoufF"
|
||||
}
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"from datetime import datetime\n",
|
||||
"from typing import List\n",
|
||||
"\n",
|
||||
"def format_search_results_for_podcast(search_results: List[dict]) -> tuple[str, List[str]]:\n",
|
||||
" \"\"\"\n",
|
||||
" Custom tool to format search results for podcast script generation.\n",
|
||||
" \"\"\"\n",
|
||||
" created_at = datetime.now().strftime(\"%B %d, %Y at %I:%M %p\")\n",
|
||||
" structured_content = []\n",
|
||||
" structured_content.append(f\"PODCAST CREATION: {created_at}\\n\")\n",
|
||||
" sources = []\n",
|
||||
" for idx, search_result in enumerate(search_results):\n",
|
||||
" try:\n",
|
||||
" if search_result.get(\"confirmed\", False):\n",
|
||||
" sources.append(search_result[\"url\"])\n",
|
||||
" structured_content.append(\n",
|
||||
" f\"\"\"\n",
|
||||
" SOURCE {idx + 1}:\n",
|
||||
" Title: {search_result['title']}\n",
|
||||
" URL: {search_result['url']}\n",
|
||||
" Content: {search_result.get('full_text') or search_result.get('description', '')}\n",
|
||||
" ---END OF SOURCE {idx + 1}---\n",
|
||||
" \"\"\".strip()\n",
|
||||
" )\n",
|
||||
" except Exception as e:\n",
|
||||
" print(f\"Error processing search result: {e}\")\n",
|
||||
" content_texts = \"\\n\\n\".join(structured_content)\n",
|
||||
" return content_texts, sources"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "yHj7Grvmov4C"
|
||||
},
|
||||
"execution_count": 4,
|
||||
"outputs": []
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"# Pydantic Models"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "eMYs7Oibo1M3"
|
||||
}
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"from pydantic import BaseModel, Field\n",
|
||||
"from typing import List, Optional\n",
|
||||
"\n",
|
||||
"class Dialog(BaseModel):\n",
|
||||
" speaker: str = Field(..., description=\"The speaker name (SHOULD BE 'ALEX' OR 'MORGAN')\")\n",
|
||||
" text: str = Field(..., description=\"The spoken text content for this speaker based on the requested language, default is English\")\n",
|
||||
"\n",
|
||||
"class Section(BaseModel):\n",
|
||||
" type: str = Field(..., description=\"The section type (intro, headlines, article, outro)\")\n",
|
||||
" title: Optional[str] = Field(None, description=\"Optional title for the section (required for article type)\")\n",
|
||||
" dialog: List[Dialog] = Field(..., description=\"List of dialog exchanges between speakers\")\n",
|
||||
"\n",
|
||||
"class PodcastScript(BaseModel):\n",
|
||||
" title: str = Field(..., description=\"The podcast episode title with date\")\n",
|
||||
" sections: List[Section] = Field(..., description=\"List of podcast sections (intro, headlines, articles, outro)\")"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "Z4uBU68eo2L_"
|
||||
},
|
||||
"execution_count": 5,
|
||||
"outputs": []
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"# Agent Instructions"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "sRTr9D35o-5D"
|
||||
}
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"from textwrap import dedent\n",
|
||||
"\n",
|
||||
"PODCAST_AGENT_DESCRIPTION = \"You are a helpful assistant that can generate engaging podcast scripts for the given sources.\"\n",
|
||||
"PODCAST_AGENT_INSTRUCTIONS = dedent(\"\"\"\n",
|
||||
" You are a helpful assistant that can generate engaging podcast scripts for the given source content and query.\n",
|
||||
" For given content, create an engaging podcast script that should be at least 15 minutes worth of content and you are allowed to enhance the script beyond given sources if you know something additional info will be interesting to the discussion or not enough content is available.\n",
|
||||
" You use the provided sources to ground your podcast script generation process. Keep it engaging and interesting.\n",
|
||||
" IMPORTANT: Generate the entire script in the provided language.\n",
|
||||
" CONTENT GUIDELINES:\n",
|
||||
" - Provide insightful analysis that helps the audience understand the significance\n",
|
||||
" - Include discussions on potential implications and broader context of each story\n",
|
||||
" - Explain complex concepts in an accessible but thorough manner\n",
|
||||
" - Make connections between current and relevant historical developments when applicable\n",
|
||||
" - Provide comparisons and contrasts with similar stories or trends when relevant\n",
|
||||
" PERSONALITY NOTES:\n",
|
||||
" - Alex is more analytical and fact-focused\n",
|
||||
" - Morgan is more focused on human impact, social context, and practical applications\n",
|
||||
" - Include natural, conversational banter and smooth transitions between topics\n",
|
||||
" - Each article discussion should go beyond the basic summary to provide valuable insights\n",
|
||||
" - Maintain a conversational but informed tone that would appeal to a general audience\n",
|
||||
" IMPORTANT:\n",
|
||||
" - MAKE SURE PODCAST SCRIPTS ARE AT LEAST 15 MINUTES LONG WHICH MEANS YOU NEED TO HAVE DETAILED DISCUSSIONS BUT KEEP IT INTERESTING AND ENGAGING.\n",
|
||||
"\"\"\")"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "quslT1kFo_yc"
|
||||
},
|
||||
"execution_count": 6,
|
||||
"outputs": []
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"# Dummy Data and Main Logic"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "bicXivCipLZY"
|
||||
}
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"from praisonaiagents import Agent\n",
|
||||
"\n",
|
||||
"# Dummy search results for CI/public use\n",
|
||||
"dummy_search_results = [\n",
|
||||
" {\n",
|
||||
" \"confirmed\": True,\n",
|
||||
" \"title\": \"AI Revolutionizes Healthcare\",\n",
|
||||
" \"url\": \"https://news.example.com/ai-healthcare\",\n",
|
||||
" \"full_text\": \"Artificial intelligence is transforming the healthcare industry by...\"\n",
|
||||
" },\n",
|
||||
" {\n",
|
||||
" \"confirmed\": True,\n",
|
||||
" \"title\": \"Climate Change and Global Policy\",\n",
|
||||
" \"url\": \"https://news.example.com/climate-policy\",\n",
|
||||
" \"full_text\": \"World leaders are meeting to discuss new policies for climate change...\"\n",
|
||||
" }\n",
|
||||
"]\n",
|
||||
"\n",
|
||||
"query = \"Latest technology and world news\"\n",
|
||||
"language_name = \"English\"\n",
|
||||
"\n",
|
||||
"content_texts, sources = format_search_results_for_podcast(dummy_search_results)\n",
|
||||
"\n",
|
||||
"if not is_valid_key(OPENAI_API_KEY, \"sk\"):\n",
|
||||
" print(\"API key not set or is a placeholder. Using dummy podcast script for CI/testing.\")\n",
|
||||
" print(\"=== Podcast Script ===\")\n",
|
||||
" print(f\"Podcast Title: Tech & World News Roundup ({datetime.now().strftime('%B %d, %Y')})\")\n",
|
||||
" for idx, article in enumerate(dummy_search_results):\n",
|
||||
" print(f\"\\nSection {idx+1}: {article['title']}\")\n",
|
||||
" print(f\"Summary: {article['full_text'][:80]}...\")\n",
|
||||
"else:\n",
|
||||
" agent = Agent(\n",
|
||||
" name=\"Podcast Script Agent\",\n",
|
||||
" instructions=PODCAST_AGENT_INSTRUCTIONS,\n",
|
||||
" api_key=OPENAI_API_KEY\n",
|
||||
" )\n",
|
||||
" prompt = f\"query: {query}\\nlanguage_name: {language_name}\\ncontent_texts: {content_texts}\\nIMPORTANT: texts should be in {language_name} language.\"\n",
|
||||
" podcast_script = agent.start(prompt)\n",
|
||||
" print(\"=== Podcast Script ===\")\n",
|
||||
" print(podcast_script)"
|
||||
],
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"base_uri": "https://localhost:8080/",
|
||||
"height": 1000,
|
||||
"referenced_widgets": [
|
||||
"4ab88bfcb62e4f9a8db7e35aefbae00a",
|
||||
"3d1ae7a6c0a947f985f6ef921b74ecf8"
|
||||
]
|
||||
},
|
||||
"id": "H4UoF8PApMUJ",
|
||||
"outputId": "748c6a75-0a0e-494a-983c-fb539ff7641a"
|
||||
},
|
||||
"execution_count": 7,
|
||||
"outputs": [
|
||||
{
|
||||
"output_type": "display_data",
|
||||
"data": {
|
||||
"text/plain": [
|
||||
"\u001b[38;2;210;227;200m╭─\u001b[0m\u001b[38;2;210;227;200m \u001b[0m\u001b[1;38;2;210;227;200mAgent Info\u001b[0m\u001b[38;2;210;227;200m \u001b[0m\u001b[38;2;210;227;200m───────────────────────────────────────────────────────────────────────────────────────────────────\u001b[0m\u001b[38;2;210;227;200m─╮\u001b[0m\n",
|
||||
"\u001b[38;2;210;227;200m│\u001b[0m \u001b[38;2;210;227;200m│\u001b[0m\n",
|
||||
"\u001b[38;2;210;227;200m│\u001b[0m \u001b[1;38;2;255;155;155m👤 Agent:\u001b[0m \u001b[38;2;255;229;229mPodcast Script Agent\u001b[0m \u001b[38;2;210;227;200m│\u001b[0m\n",
|
||||
"\u001b[38;2;210;227;200m│\u001b[0m \u001b[1;38;2;180;180;179mRole:\u001b[0m \u001b[38;2;255;229;229mAssistant\u001b[0m \u001b[38;2;210;227;200m│\u001b[0m\n",
|
||||
"\u001b[38;2;210;227;200m│\u001b[0m \u001b[38;2;210;227;200m│\u001b[0m\n",
|
||||
"\u001b[38;2;210;227;200m╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯\u001b[0m\n"
|
||||
],
|
||||
"text/html": [
|
||||
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">╭─ </span><span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8; font-weight: bold\">Agent Info</span><span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\"> ────────────────────────────────────────────────────────────────────────────────────────────────────╮</span>\n",
|
||||
"<span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">│</span> <span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">│</span>\n",
|
||||
"<span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">│</span> <span style=\"color: #ff9b9b; text-decoration-color: #ff9b9b; font-weight: bold\">👤 Agent:</span> <span style=\"color: #ffe5e5; text-decoration-color: #ffe5e5\">Podcast Script Agent</span> <span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">│</span>\n",
|
||||
"<span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">│</span> <span style=\"color: #b4b4b3; text-decoration-color: #b4b4b3; font-weight: bold\">Role:</span> <span style=\"color: #ffe5e5; text-decoration-color: #ffe5e5\">Assistant</span> <span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">│</span>\n",
|
||||
"<span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">│</span> <span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">│</span>\n",
|
||||
"<span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯</span>\n",
|
||||
"</pre>\n"
|
||||
]
|
||||
},
|
||||
"metadata": {}
|
||||
},
|
||||
{
|
||||
"output_type": "display_data",
|
||||
"data": {
|
||||
"text/plain": [
|
||||
"Output()"
|
||||
],
|
||||
"application/vnd.jupyter.widget-view+json": {
|
||||
"version_major": 2,
|
||||
"version_minor": 0,
|
||||
"model_id": "4ab88bfcb62e4f9a8db7e35aefbae00a"
|
||||
}
|
||||
},
|
||||
"metadata": {}
|
||||
},
|
||||
{
|
||||
"output_type": "display_data",
|
||||
"data": {
|
||||
"text/plain": [],
|
||||
"text/html": [
|
||||
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"></pre>\n"
|
||||
]
|
||||
},
|
||||
"metadata": {}
|
||||
},
|
||||
{
|
||||
"output_type": "display_data",
|
||||
"data": {
|
||||
"text/plain": [
|
||||
"\n"
|
||||
],
|
||||
"text/html": [
|
||||
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">\n",
|
||||
"</pre>\n"
|
||||
]
|
||||
},
|
||||
"metadata": {}
|
||||
},
|
||||
{
|
||||
"output_type": "display_data",
|
||||
"data": {
|
||||
"text/plain": [
|
||||
"\u001b[2mResponse generated in 23.5s\u001b[0m\n"
|
||||
],
|
||||
"text/html": [
|
||||
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"color: #7f7f7f; text-decoration-color: #7f7f7f\">Response generated in 23.5s</span>\n",
|
||||
"</pre>\n"
|
||||
]
|
||||
},
|
||||
"metadata": {}
|
||||
},
|
||||
{
|
||||
"output_type": "display_data",
|
||||
"data": {
|
||||
"text/plain": [
|
||||
"\u001b[36m╭─\u001b[0m\u001b[36m────────────────────────────────────────────────────\u001b[0m\u001b[36m Task \u001b[0m\u001b[36m─────────────────────────────────────────────────────\u001b[0m\u001b[36m─╮\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m query: Latest technology and world news language_name: English content_texts: PODCAST CREATION: July 09, 2025 \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m at 10:03 AM \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m SOURCE 1: Title: AI Revolutionizes Healthcare URL: https://news.example.com/ai-healthcare Content: Artificial \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m intelligence is transforming the healthcare industry by... ---END OF SOURCE 1--- \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m SOURCE 2: Title: Climate Change and Global Policy URL: https://news.example.com/climate-policy Content: World \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m leaders are meeting to discuss new policies for climate change... ---END OF SOURCE 2--- IMPORTANT: texts should \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m be in English language. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯\u001b[0m\n"
|
||||
],
|
||||
"text/html": [
|
||||
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"color: #008080; text-decoration-color: #008080\">╭───────────────────────────────────────────────────── Task ──────────────────────────────────────────────────────╮</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> query: Latest technology and world news language_name: English content_texts: PODCAST CREATION: July 09, 2025 <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> at 10:03 AM <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> SOURCE 1: Title: AI Revolutionizes Healthcare URL: https://news.example.com/ai-healthcare Content: Artificial <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> intelligence is transforming the healthcare industry by... ---END OF SOURCE 1--- <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> SOURCE 2: Title: Climate Change and Global Policy URL: https://news.example.com/climate-policy Content: World <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> leaders are meeting to discuss new policies for climate change... ---END OF SOURCE 2--- IMPORTANT: texts should <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> be in English language. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯</span>\n",
|
||||
"</pre>\n"
|
||||
]
|
||||
},
|
||||
"metadata": {}
|
||||
},
|
||||
{
|
||||
"output_type": "display_data",
|
||||
"data": {
|
||||
"text/plain": [
|
||||
"\u001b[36m╭─\u001b[0m\u001b[36m──────────────────────────────────────────────────\u001b[0m\u001b[36m Response \u001b[0m\u001b[36m───────────────────────────────────────────────────\u001b[0m\u001b[36m─╮\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m [INTRO MUSIC FADES IN] \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1mAlex\u001b[0m: Hello and welcome to another episode of \"The World Today,\" where we dive into the latest in technology \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m and world news. I'm Alex, your go-to for all things analytical and fact-focused. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1mMorgan\u001b[0m: And I'm Morgan, here to explore the human impact and social context of today's stories. We've got a \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m fascinating lineup for you today, so let's dive right in! \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1mAlex\u001b[0m: First up, we're talking about a topic that's been making waves across the healthcare industry: the role \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m of artificial intelligence. According to a recent article from \u001b]8;id=890061;https://news.example.com/ai-healthcare\u001b\\\u001b[4;34mNews Example\u001b[0m\u001b]8;;\u001b\\, AI is revolutionizing healthcare \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m in ways we could only dream of a decade ago. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1mMorgan\u001b[0m: That's right, Alex. AI is not just a buzzword anymore; it's actively changing how we approach \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m healthcare. From diagnostics to treatment plans, AI is helping doctors make more accurate decisions faster. But \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m what does this mean for patients and healthcare professionals? \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1mAlex\u001b[0m: Well, Morgan, AI's ability to analyze vast amounts of data quickly means that doctors can diagnose \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m diseases earlier and more accurately. For instance, AI algorithms can now detect patterns in medical imaging \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m that might be too subtle for the human eye. This can lead to earlier interventions and better patient outcomes. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1mMorgan\u001b[0m: And let's not forget about the human side of things. For patients, this means less waiting time for \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m results and potentially more personalized treatment plans. But there's also a concern about the human touch in \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m healthcare. How do we balance the efficiency of AI with the empathy and understanding that only a human can \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m provide? \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1mAlex\u001b[0m: That's a great point. The integration of AI in healthcare does raise ethical questions. For example, who \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m is responsible if an AI system makes a mistake? And how do we ensure that these systems are free from bias? \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1mMorgan\u001b[0m: Exactly. There's a lot to consider, but the potential benefits are enormous. Imagine a world where \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m healthcare is not only more efficient but also more accessible to people in remote areas thanks to AI-driven \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m telemedicine. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1mAlex\u001b[0m: It's a fascinating time for healthcare, no doubt. But let's shift gears a bit and talk about another \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m pressing issue: climate change and global policy. According to a report from \u001b]8;id=2198;https://news.example.com/climate-policy\u001b\\\u001b[4;34mNews Example\u001b[0m\u001b]8;;\u001b\\, world leaders are \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m currently meeting to discuss new policies to combat climate change. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1mMorgan\u001b[0m: Climate change is one of those issues that affects everyone, regardless of where you live. These global \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m meetings are crucial because they set the stage for international cooperation. But what are the main challenges \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m these leaders face? \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1mAlex\u001b[0m: One of the biggest challenges is balancing economic growth with environmental sustainability. Many \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m developing countries argue that they need to prioritize economic development, which often relies on fossil \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m fuels. Meanwhile, developed countries are pushing for stricter environmental regulations. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1mMorgan\u001b[0m: It's a classic case of differing priorities. But there's also a growing recognition that climate change \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m doesn't respect borders. Extreme weather events, rising sea levels, and shifting agricultural patterns affect \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m us all. So, there's a real urgency to find common ground. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1mAlex\u001b[0m: And technology plays a significant role here too. Innovations in renewable energy, carbon capture, and \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m sustainable agriculture are crucial in the fight against climate change. But implementing these technologies on \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m a global scale requires significant investment and political will. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1mMorgan\u001b[0m: It's a complex issue, but it's encouraging to see world leaders coming together to address it. The \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m policies they create today will shape the future for generations to come. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1mAlex\u001b[0m: Absolutely. And it's not just about government action. Individuals and businesses also have a role to \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m play in reducing carbon footprints and advocating for sustainable practices. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1mMorgan\u001b[0m: It's a collective effort, and every little bit helps. Before we wrap up, Alex, any final thoughts on \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m today's topics? \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1mAlex\u001b[0m: Just that both AI in healthcare and climate change policies highlight the intersection of technology and \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m society. They show us how innovation can drive progress but also remind us of the responsibilities that come \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m with it. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1mMorgan\u001b[0m: Well said, Alex. It's all about finding that balance. And with that, we've reached the end of today's \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m episode. Thanks for tuning in to \"The World Today.\" \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1mAlex\u001b[0m: Don't forget to subscribe and join us next time for more insights into the latest in technology and world \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m news. \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[1mMorgan\u001b[0m: Until then, stay informed and stay curious! \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m│\u001b[0m [OUTRO MUSIC FADES OUT] \u001b[36m│\u001b[0m\n",
|
||||
"\u001b[36m╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯\u001b[0m\n"
|
||||
],
|
||||
"text/html": [
|
||||
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"color: #008080; text-decoration-color: #008080\">╭─────────────────────────────────────────────────── Response ────────────────────────────────────────────────────╮</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> [INTRO MUSIC FADES IN] <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"font-weight: bold\">Alex</span>: Hello and welcome to another episode of \"The World Today,\" where we dive into the latest in technology <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> and world news. I'm Alex, your go-to for all things analytical and fact-focused. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"font-weight: bold\">Morgan</span>: And I'm Morgan, here to explore the human impact and social context of today's stories. We've got a <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> fascinating lineup for you today, so let's dive right in! <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"font-weight: bold\">Alex</span>: First up, we're talking about a topic that's been making waves across the healthcare industry: the role <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> of artificial intelligence. According to a recent article from <a href=\"https://news.example.com/ai-healthcare\" target=\"_blank\"><span style=\"color: #000080; text-decoration-color: #000080; text-decoration: underline\">News Example</span></a>, AI is revolutionizing healthcare <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> in ways we could only dream of a decade ago. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"font-weight: bold\">Morgan</span>: That's right, Alex. AI is not just a buzzword anymore; it's actively changing how we approach <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> healthcare. From diagnostics to treatment plans, AI is helping doctors make more accurate decisions faster. But <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> what does this mean for patients and healthcare professionals? <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"font-weight: bold\">Alex</span>: Well, Morgan, AI's ability to analyze vast amounts of data quickly means that doctors can diagnose <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> diseases earlier and more accurately. For instance, AI algorithms can now detect patterns in medical imaging <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> that might be too subtle for the human eye. This can lead to earlier interventions and better patient outcomes. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"font-weight: bold\">Morgan</span>: And let's not forget about the human side of things. For patients, this means less waiting time for <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> results and potentially more personalized treatment plans. But there's also a concern about the human touch in <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> healthcare. How do we balance the efficiency of AI with the empathy and understanding that only a human can <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> provide? <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"font-weight: bold\">Alex</span>: That's a great point. The integration of AI in healthcare does raise ethical questions. For example, who <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> is responsible if an AI system makes a mistake? And how do we ensure that these systems are free from bias? <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"font-weight: bold\">Morgan</span>: Exactly. There's a lot to consider, but the potential benefits are enormous. Imagine a world where <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> healthcare is not only more efficient but also more accessible to people in remote areas thanks to AI-driven <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> telemedicine. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"font-weight: bold\">Alex</span>: It's a fascinating time for healthcare, no doubt. But let's shift gears a bit and talk about another <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> pressing issue: climate change and global policy. According to a report from <a href=\"https://news.example.com/climate-policy\" target=\"_blank\"><span style=\"color: #000080; text-decoration-color: #000080; text-decoration: underline\">News Example</span></a>, world leaders are <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> currently meeting to discuss new policies to combat climate change. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"font-weight: bold\">Morgan</span>: Climate change is one of those issues that affects everyone, regardless of where you live. These global <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> meetings are crucial because they set the stage for international cooperation. But what are the main challenges <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> these leaders face? <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"font-weight: bold\">Alex</span>: One of the biggest challenges is balancing economic growth with environmental sustainability. Many <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> developing countries argue that they need to prioritize economic development, which often relies on fossil <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> fuels. Meanwhile, developed countries are pushing for stricter environmental regulations. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"font-weight: bold\">Morgan</span>: It's a classic case of differing priorities. But there's also a growing recognition that climate change <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> doesn't respect borders. Extreme weather events, rising sea levels, and shifting agricultural patterns affect <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> us all. So, there's a real urgency to find common ground. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"font-weight: bold\">Alex</span>: And technology plays a significant role here too. Innovations in renewable energy, carbon capture, and <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> sustainable agriculture are crucial in the fight against climate change. But implementing these technologies on <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> a global scale requires significant investment and political will. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"font-weight: bold\">Morgan</span>: It's a complex issue, but it's encouraging to see world leaders coming together to address it. The <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> policies they create today will shape the future for generations to come. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"font-weight: bold\">Alex</span>: Absolutely. And it's not just about government action. Individuals and businesses also have a role to <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> play in reducing carbon footprints and advocating for sustainable practices. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"font-weight: bold\">Morgan</span>: It's a collective effort, and every little bit helps. Before we wrap up, Alex, any final thoughts on <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> today's topics? <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"font-weight: bold\">Alex</span>: Just that both AI in healthcare and climate change policies highlight the intersection of technology and <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> society. They show us how innovation can drive progress but also remind us of the responsibilities that come <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> with it. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"font-weight: bold\">Morgan</span>: Well said, Alex. It's all about finding that balance. And with that, we've reached the end of today's <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> episode. Thanks for tuning in to \"The World Today.\" <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"font-weight: bold\">Alex</span>: Don't forget to subscribe and join us next time for more insights into the latest in technology and world <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> news. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"font-weight: bold\">Morgan</span>: Until then, stay informed and stay curious! <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> [OUTRO MUSIC FADES OUT] <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
|
||||
"<span style=\"color: #008080; text-decoration-color: #008080\">╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯</span>\n",
|
||||
"</pre>\n"
|
||||
]
|
||||
},
|
||||
"metadata": {}
|
||||
},
|
||||
{
|
||||
"output_type": "stream",
|
||||
"name": "stdout",
|
||||
"text": [
|
||||
"=== Podcast Script ===\n",
|
||||
"[INTRO MUSIC FADES IN]\n",
|
||||
"\n",
|
||||
"**Alex**: Hello and welcome to another episode of \"The World Today,\" where we dive into the latest in technology and world news. I'm Alex, your go-to for all things analytical and fact-focused.\n",
|
||||
"\n",
|
||||
"**Morgan**: And I'm Morgan, here to explore the human impact and social context of today's stories. We've got a fascinating lineup for you today, so let's dive right in!\n",
|
||||
"\n",
|
||||
"**Alex**: First up, we're talking about a topic that's been making waves across the healthcare industry: the role of artificial intelligence. According to a recent article from [News Example](https://news.example.com/ai-healthcare), AI is revolutionizing healthcare in ways we could only dream of a decade ago.\n",
|
||||
"\n",
|
||||
"**Morgan**: That's right, Alex. AI is not just a buzzword anymore; it's actively changing how we approach healthcare. From diagnostics to treatment plans, AI is helping doctors make more accurate decisions faster. But what does this mean for patients and healthcare professionals?\n",
|
||||
"\n",
|
||||
"**Alex**: Well, Morgan, AI's ability to analyze vast amounts of data quickly means that doctors can diagnose diseases earlier and more accurately. For instance, AI algorithms can now detect patterns in medical imaging that might be too subtle for the human eye. This can lead to earlier interventions and better patient outcomes.\n",
|
||||
"\n",
|
||||
"**Morgan**: And let's not forget about the human side of things. For patients, this means less waiting time for results and potentially more personalized treatment plans. But there's also a concern about the human touch in healthcare. How do we balance the efficiency of AI with the empathy and understanding that only a human can provide?\n",
|
||||
"\n",
|
||||
"**Alex**: That's a great point. The integration of AI in healthcare does raise ethical questions. For example, who is responsible if an AI system makes a mistake? And how do we ensure that these systems are free from bias?\n",
|
||||
"\n",
|
||||
"**Morgan**: Exactly. There's a lot to consider, but the potential benefits are enormous. Imagine a world where healthcare is not only more efficient but also more accessible to people in remote areas thanks to AI-driven telemedicine.\n",
|
||||
"\n",
|
||||
"**Alex**: It's a fascinating time for healthcare, no doubt. But let's shift gears a bit and talk about another pressing issue: climate change and global policy. According to a report from [News Example](https://news.example.com/climate-policy), world leaders are currently meeting to discuss new policies to combat climate change.\n",
|
||||
"\n",
|
||||
"**Morgan**: Climate change is one of those issues that affects everyone, regardless of where you live. These global meetings are crucial because they set the stage for international cooperation. But what are the main challenges these leaders face?\n",
|
||||
"\n",
|
||||
"**Alex**: One of the biggest challenges is balancing economic growth with environmental sustainability. Many developing countries argue that they need to prioritize economic development, which often relies on fossil fuels. Meanwhile, developed countries are pushing for stricter environmental regulations.\n",
|
||||
"\n",
|
||||
"**Morgan**: It's a classic case of differing priorities. But there's also a growing recognition that climate change doesn't respect borders. Extreme weather events, rising sea levels, and shifting agricultural patterns affect us all. So, there's a real urgency to find common ground.\n",
|
||||
"\n",
|
||||
"**Alex**: And technology plays a significant role here too. Innovations in renewable energy, carbon capture, and sustainable agriculture are crucial in the fight against climate change. But implementing these technologies on a global scale requires significant investment and political will.\n",
|
||||
"\n",
|
||||
"**Morgan**: It's a complex issue, but it's encouraging to see world leaders coming together to address it. The policies they create today will shape the future for generations to come.\n",
|
||||
"\n",
|
||||
"**Alex**: Absolutely. And it's not just about government action. Individuals and businesses also have a role to play in reducing carbon footprints and advocating for sustainable practices.\n",
|
||||
"\n",
|
||||
"**Morgan**: It's a collective effort, and every little bit helps. Before we wrap up, Alex, any final thoughts on today's topics?\n",
|
||||
"\n",
|
||||
"**Alex**: Just that both AI in healthcare and climate change policies highlight the intersection of technology and society. They show us how innovation can drive progress but also remind us of the responsibilities that come with it.\n",
|
||||
"\n",
|
||||
"**Morgan**: Well said, Alex. It's all about finding that balance. And with that, we've reached the end of today's episode. Thanks for tuning in to \"The World Today.\"\n",
|
||||
"\n",
|
||||
"**Alex**: Don't forget to subscribe and join us next time for more insights into the latest in technology and world news.\n",
|
||||
"\n",
|
||||
"**Morgan**: Until then, stay informed and stay curious!\n",
|
||||
"\n",
|
||||
"[OUTRO MUSIC FADES OUT]\n"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -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,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,197 @@
|
||||
"""
|
||||
Hosted MCP Server implementation for PraisonAI Agents.
|
||||
|
||||
This module provides a base class for creating hosted MCP servers
|
||||
that can handle requests and integrate with the MCP protocol.
|
||||
|
||||
Note: This is an example implementation. To use it, ensure you have installed:
|
||||
pip install praisonaiagents[mcp] starlette>=0.27.0
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from typing import Dict, Any, Optional, List, Callable
|
||||
import json
|
||||
|
||||
try:
|
||||
from mcp.server.fastmcp import FastMCP
|
||||
from mcp.server import Server
|
||||
from starlette.applications import Starlette
|
||||
from starlette.requests import Request
|
||||
from starlette.routing import Mount, Route
|
||||
from mcp.server.sse import SseServerTransport
|
||||
import uvicorn
|
||||
except ImportError:
|
||||
raise ImportError(
|
||||
"MCP server dependencies not installed. "
|
||||
"Please install with: pip install praisonaiagents[mcp] starlette>=0.27.0"
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class HostedMCPServer:
|
||||
"""
|
||||
Base class for creating hosted MCP servers.
|
||||
|
||||
This class provides a foundation for building MCP servers that can:
|
||||
- Handle incoming requests
|
||||
- Define custom tools
|
||||
- Support SSE transport
|
||||
- Be extended with custom functionality like latency tracking
|
||||
"""
|
||||
|
||||
def __init__(self, name: str = "hosted-mcp-server", host: str = "localhost", port: int = 8080):
|
||||
"""
|
||||
Initialize the hosted MCP server.
|
||||
|
||||
Args:
|
||||
name: Server name for identification
|
||||
host: Host to bind to (default: localhost)
|
||||
port: Port to listen on (default: 8080)
|
||||
"""
|
||||
self.name = name
|
||||
self.host = host
|
||||
self.port = port
|
||||
self.mcp = FastMCP(name)
|
||||
self._tools: Dict[str, Callable] = {}
|
||||
self._server: Optional[Server] = None
|
||||
self._app: Optional[Starlette] = None
|
||||
|
||||
def handle_request(self, request_data: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""
|
||||
Handle incoming MCP requests.
|
||||
|
||||
This method can be overridden in subclasses to add custom request handling,
|
||||
such as latency tracking, authentication, or request modification.
|
||||
|
||||
Args:
|
||||
request_data: The incoming request data
|
||||
|
||||
Returns:
|
||||
Response data
|
||||
"""
|
||||
# Default implementation - can be overridden
|
||||
method = request_data.get('method', '')
|
||||
request_id = request_data.get('id', 'unknown')
|
||||
|
||||
logger.debug(f"Handling request {request_id}: {method}")
|
||||
|
||||
# Basic response structure
|
||||
response = {
|
||||
'id': request_id,
|
||||
'jsonrpc': '2.0',
|
||||
'result': {}
|
||||
}
|
||||
|
||||
return response
|
||||
|
||||
def add_tool(self, func: Callable, name: Optional[str] = None, description: Optional[str] = None):
|
||||
"""
|
||||
Add a tool to the MCP server.
|
||||
|
||||
Args:
|
||||
func: The function to expose as a tool
|
||||
name: Optional name for the tool (defaults to function name)
|
||||
description: Optional description for the tool
|
||||
"""
|
||||
tool_name = name or func.__name__
|
||||
|
||||
# Register with FastMCP
|
||||
if asyncio.iscoroutinefunction(func):
|
||||
# Already async
|
||||
self.mcp.tool(name=tool_name)(func)
|
||||
else:
|
||||
# Wrap sync function in async
|
||||
async def async_wrapper(*args, **kwargs):
|
||||
return func(*args, **kwargs)
|
||||
async_wrapper.__name__ = func.__name__
|
||||
async_wrapper.__doc__ = description or func.__doc__
|
||||
self.mcp.tool(name=tool_name)(async_wrapper)
|
||||
|
||||
self._tools[tool_name] = func
|
||||
logger.info(f"Added tool: {tool_name}")
|
||||
|
||||
def create_app(self, debug: bool = False) -> Starlette:
|
||||
"""
|
||||
Create a Starlette application for serving the MCP server.
|
||||
|
||||
Args:
|
||||
debug: Enable debug mode
|
||||
|
||||
Returns:
|
||||
Starlette application instance
|
||||
|
||||
Raises:
|
||||
RuntimeError: If the MCP server is not properly initialized
|
||||
"""
|
||||
if not self._server:
|
||||
if not hasattr(self.mcp, '_mcp_server'):
|
||||
raise RuntimeError("MCP server not properly initialized. Ensure FastMCP is correctly set up.")
|
||||
self._server = self.mcp._mcp_server
|
||||
|
||||
sse = SseServerTransport("/messages/")
|
||||
|
||||
async def handle_sse(request: Request) -> None:
|
||||
logger.debug(f"SSE connection from {request.client}")
|
||||
async with sse.connect_sse(
|
||||
request.scope,
|
||||
request.receive,
|
||||
request._send,
|
||||
) as (read_stream, write_stream):
|
||||
await self._server.run(
|
||||
read_stream,
|
||||
write_stream,
|
||||
self._server.create_initialization_options(),
|
||||
)
|
||||
|
||||
self._app = Starlette(
|
||||
debug=debug,
|
||||
routes=[
|
||||
Route("/sse", endpoint=handle_sse),
|
||||
Mount("/messages/", app=sse.handle_post_message),
|
||||
],
|
||||
)
|
||||
|
||||
return self._app
|
||||
|
||||
def start(self, debug: bool = False, **uvicorn_kwargs):
|
||||
"""
|
||||
Start the MCP server.
|
||||
|
||||
Args:
|
||||
debug: Enable debug mode
|
||||
**uvicorn_kwargs: Additional arguments to pass to uvicorn
|
||||
"""
|
||||
app = self.create_app(debug=debug)
|
||||
|
||||
print(f"Starting {self.name} MCP server on {self.host}:{self.port}")
|
||||
print(f"Available tools: {', '.join(self._tools.keys())}")
|
||||
print(f"SSE endpoint: http://{self.host}:{self.port}/sse")
|
||||
|
||||
uvicorn.run(app, host=self.host, port=self.port, **uvicorn_kwargs)
|
||||
|
||||
async def start_async(self, debug: bool = False):
|
||||
"""
|
||||
Start the MCP server asynchronously.
|
||||
|
||||
Args:
|
||||
debug: Enable debug mode
|
||||
"""
|
||||
app = self.create_app(debug=debug)
|
||||
|
||||
config = uvicorn.Config(app, host=self.host, port=self.port)
|
||||
server = uvicorn.Server(config)
|
||||
|
||||
print(f"Starting {self.name} MCP server on {self.host}:{self.port}")
|
||||
print(f"Available tools: {', '.join(self._tools.keys())}")
|
||||
|
||||
await server.serve()
|
||||
|
||||
def get_tools(self) -> List[str]:
|
||||
"""Get list of available tool names."""
|
||||
return list(self._tools.keys())
|
||||
|
||||
def get_endpoint(self) -> str:
|
||||
"""Get the SSE endpoint URL."""
|
||||
return f"http://{self.host}:{self.port}/sse"
|
||||
@@ -6,7 +6,7 @@ without modifying PraisonAI core files.
|
||||
"""
|
||||
|
||||
from praisonaiagents import Agent, PraisonAIAgents
|
||||
from praisonaiagents.mcp import HostedMCPServer
|
||||
from hosted_server import HostedMCPServer # Import from local file
|
||||
from latency_tracker_tool import tracker, get_latency_metrics
|
||||
import json
|
||||
|
||||
|
||||
@@ -72,7 +72,7 @@ workflow = PraisonAIAgents(
|
||||
)
|
||||
|
||||
# Run the workflow
|
||||
results = workflow.start()
|
||||
results = workflow.start(return_dict=True)
|
||||
|
||||
# Print results
|
||||
print("\nWorkflow Results:")
|
||||
|
||||
@@ -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,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!
|
||||
@@ -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,108 @@
|
||||
#!/usr/bin/env python
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
News and Podcast Aggregator Agent using PraisonAIAgents
|
||||
|
||||
This script summarizes news articles and generates podcast-style discussion points.
|
||||
It is CI-friendly: it uses dummy data if API keys are not set.
|
||||
"""
|
||||
|
||||
import os
|
||||
from datetime import datetime
|
||||
from praisonaiagents import Agent
|
||||
|
||||
# Set up the OpenAI API key for praisonaiagents
|
||||
OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY", "sk-..")
|
||||
os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY
|
||||
|
||||
def is_valid_key(key, prefix):
|
||||
return key and key != f"{prefix}-.." and key.startswith(prefix)
|
||||
|
||||
# Custom Tool: Format search results for podcast
|
||||
def format_search_results_for_podcast(search_results):
|
||||
created_at = datetime.now().strftime("%B %d, %Y at %I:%M %p")
|
||||
structured_content = []
|
||||
structured_content.append(f"PODCAST CREATION: {created_at}\n")
|
||||
sources = []
|
||||
for idx, search_result in enumerate(search_results):
|
||||
try:
|
||||
if search_result.get("confirmed", False):
|
||||
sources.append(search_result["url"])
|
||||
structured_content.append(
|
||||
f"""
|
||||
SOURCE {idx + 1}:
|
||||
Title: {search_result['title']}
|
||||
URL: {search_result['url']}
|
||||
Content: {search_result.get('full_text') or search_result.get('description', '')}
|
||||
---END OF SOURCE {idx + 1}---
|
||||
""".strip()
|
||||
)
|
||||
except Exception as e:
|
||||
print(f"Error processing search result: {e}")
|
||||
content_texts = "\n\n".join(structured_content)
|
||||
return content_texts, sources
|
||||
|
||||
# Agent Instructions
|
||||
from textwrap import dedent
|
||||
|
||||
PODCAST_AGENT_INSTRUCTIONS = dedent("""
|
||||
You are a helpful assistant that can generate engaging podcast scripts for the given source content and query.
|
||||
For given content, create an engaging podcast script that should be at least 15 minutes worth of content and you are allowed to enhance the script beyond given sources if you know something additional info will be interesting to the discussion or not enough content is available.
|
||||
You use the provided sources to ground your podcast script generation process. Keep it engaging and interesting.
|
||||
IMPORTANT: Generate the entire script in the provided language.
|
||||
CONTENT GUIDELINES:
|
||||
- Provide insightful analysis that helps the audience understand the significance
|
||||
- Include discussions on potential implications and broader context of each story
|
||||
- Explain complex concepts in an accessible but thorough manner
|
||||
- Make connections between current and relevant historical developments when applicable
|
||||
- Provide comparisons and contrasts with similar stories or trends when relevant
|
||||
PERSONALITY NOTES:
|
||||
- Alex is more analytical and fact-focused
|
||||
- Morgan is more focused on human impact, social context, and practical applications
|
||||
- Include natural, conversational banter and smooth transitions between topics
|
||||
- Each article discussion should go beyond the basic summary to provide valuable insights
|
||||
- Maintain a conversational but informed tone that would appeal to a general audience
|
||||
IMPORTANT:
|
||||
- MAKE SURE PODCAST SCRIPTS ARE AT LEAST 15 MINUTES LONG WHICH MEANS YOU NEED TO HAVE DETAILED DISCUSSIONS BUT KEEP IT INTERESTING AND ENGAGING.
|
||||
""")
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Dummy search results for CI/public use
|
||||
dummy_search_results = [
|
||||
{
|
||||
"confirmed": True,
|
||||
"title": "AI Revolutionizes Healthcare",
|
||||
"url": "https://news.example.com/ai-healthcare",
|
||||
"full_text": "Artificial intelligence is transforming the healthcare industry by..."
|
||||
},
|
||||
{
|
||||
"confirmed": True,
|
||||
"title": "Climate Change and Global Policy",
|
||||
"url": "https://news.example.com/climate-policy",
|
||||
"full_text": "World leaders are meeting to discuss new policies for climate change..."
|
||||
}
|
||||
]
|
||||
|
||||
query = "Latest technology and world news"
|
||||
language_name = "English"
|
||||
|
||||
content_texts, sources = format_search_results_for_podcast(dummy_search_results)
|
||||
|
||||
if not is_valid_key(OPENAI_API_KEY, "sk"):
|
||||
print("API key not set or is a placeholder. Using dummy podcast script for CI/testing.")
|
||||
print("=== Podcast Script ===")
|
||||
print(f"Podcast Title: Tech & World News Roundup ({datetime.now().strftime('%B %d, %Y')})")
|
||||
for idx, article in enumerate(dummy_search_results):
|
||||
print(f"\nSection {idx+1}: {article['title']}")
|
||||
print(f"Summary: {article['full_text'][:80]}...")
|
||||
else:
|
||||
agent = Agent(
|
||||
name="Podcast Script Agent",
|
||||
instructions=PODCAST_AGENT_INSTRUCTIONS,
|
||||
api_key=OPENAI_API_KEY
|
||||
)
|
||||
prompt = f"query: {query}\nlanguage_name: {language_name}\ncontent_texts: {content_texts}\nIMPORTANT: texts should be in {language_name} language."
|
||||
podcast_script = agent.start(prompt)
|
||||
print("=== Podcast Script ===")
|
||||
print(podcast_script)
|
||||
@@ -0,0 +1,165 @@
|
||||
#!/usr/bin/env python
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
Air Quality Analysis Agent using PraisonAIAgents
|
||||
|
||||
This script retrieves real-time air quality data for a specified location, analyzes the results, and provides actionable health recommendations.
|
||||
It uses only praisonaiagents and is CI-friendly: it uses dummy data if API keys are not set.
|
||||
"""
|
||||
|
||||
import os
|
||||
import requests
|
||||
import yaml
|
||||
from praisonaiagents import Agent
|
||||
|
||||
# Set up API keys
|
||||
FIRECRAWL_API_KEY = os.environ.get("FIRECRAWL_API_KEY", "fc-..")
|
||||
OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY", "sk-..")
|
||||
os.environ["FIRECRAWL_API_KEY"] = FIRECRAWL_API_KEY
|
||||
os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY
|
||||
|
||||
# Tool: AQI Data Fetcher
|
||||
class AQIDataFetcher:
|
||||
def __init__(self, firecrawl_key: str):
|
||||
from firecrawl import FirecrawlApp
|
||||
self.firecrawl = FirecrawlApp(api_key=firecrawl_key)
|
||||
|
||||
def fetch(self, country: str, state: str, city: str):
|
||||
country_clean = country.lower().replace(' ', '-')
|
||||
city_clean = city.lower().replace(' ', '-')
|
||||
if not state or state.lower() == 'none':
|
||||
url = f"https://www.aqi.in/dashboard/{country_clean}/{city_clean}"
|
||||
else:
|
||||
state_clean = state.lower().replace(' ', '-')
|
||||
url = f"https://www.aqi.in/dashboard/{country_clean}/{state_clean}/{city_clean}"
|
||||
|
||||
print(f"Testing URL: {url}")
|
||||
try:
|
||||
resp = requests.get(url)
|
||||
print(f"Status code: {resp.status_code}")
|
||||
if resp.status_code != 200:
|
||||
print(f"URL not reachable: {url} (status code: {resp.status_code})")
|
||||
return None
|
||||
except Exception as e:
|
||||
print(f"Error: {e}")
|
||||
return None
|
||||
|
||||
schema = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"aqi": {"type": "number", "description": "Air Quality Index"},
|
||||
"temperature": {"type": "number", "description": "Temperature in degrees Celsius"},
|
||||
"humidity": {"type": "number", "description": "Humidity percentage"},
|
||||
"wind_speed": {"type": "number", "description": "Wind speed in kilometers per hour"},
|
||||
"pm25": {"type": "number", "description": "Particulate Matter 2.5 micrometers"},
|
||||
"pm10": {"type": "number", "description": "Particulate Matter 10 micrometers"},
|
||||
"co": {"type": "number", "description": "Carbon Monoxide level"}
|
||||
},
|
||||
"required": ["aqi", "temperature", "humidity", "wind_speed", "pm25", "pm10", "co"]
|
||||
}
|
||||
|
||||
response = self.firecrawl.extract(
|
||||
urls=[f"{url}/*"],
|
||||
prompt='Extract the current real-time AQI, temperature, humidity, wind speed, PM2.5, PM10, and CO levels from the page. Also extract the timestamp of the data.',
|
||||
schema=schema
|
||||
)
|
||||
return response
|
||||
|
||||
# YAML prompt (for documentation/logging)
|
||||
yaml_prompt = """
|
||||
agent:
|
||||
name: Air Quality Health Advisor
|
||||
description: |
|
||||
An agent that analyzes real-time air quality data for a given location and provides personalized health recommendations based on user context.
|
||||
tools:
|
||||
- name: AQIDataFetcher
|
||||
description: Fetches AQI and weather data for a specified city, state, and country using Firecrawl.
|
||||
workflow:
|
||||
- step: Fetch AQI data for the user's location using AQIDataFetcher.
|
||||
- step: Analyze AQI and weather data.
|
||||
- step: Consider user's medical conditions and planned activity.
|
||||
- step: Generate health and activity recommendations.
|
||||
inputs:
|
||||
- city
|
||||
- state
|
||||
- country
|
||||
- medical_conditions
|
||||
- planned_activity
|
||||
outputs:
|
||||
- recommendations
|
||||
"""
|
||||
print(yaml.safe_load(yaml_prompt))
|
||||
|
||||
if __name__ == "__main__":
|
||||
# User input (you can change these for other locations)
|
||||
user_city = "Mumbai"
|
||||
user_state = "Maharashtra"
|
||||
user_country = "India"
|
||||
user_medical_conditions = "asthma"
|
||||
user_planned_activity = "morning jog for 2 hours"
|
||||
|
||||
aqi_fetcher = AQIDataFetcher(firecrawl_key=os.environ["FIRECRAWL_API_KEY"])
|
||||
|
||||
# Try with state, then without state, then fallback to Delhi
|
||||
aqi_data = aqi_fetcher.fetch(
|
||||
country=user_country,
|
||||
state=user_state,
|
||||
city=user_city
|
||||
)
|
||||
|
||||
if not aqi_data or not hasattr(aqi_data, "data"):
|
||||
print("Mumbai with state failed, trying without state...")
|
||||
aqi_data = aqi_fetcher.fetch(
|
||||
country=user_country,
|
||||
state="",
|
||||
city=user_city
|
||||
)
|
||||
|
||||
if not aqi_data or not hasattr(aqi_data, "data"):
|
||||
print("Trying Delhi, India...")
|
||||
aqi_data = aqi_fetcher.fetch(
|
||||
country="India",
|
||||
state="",
|
||||
city="Delhi"
|
||||
)
|
||||
|
||||
if not aqi_data or not hasattr(aqi_data, "data"):
|
||||
print("Failed to fetch AQI data for all tried locations. Please check the URLs manually.")
|
||||
else:
|
||||
aqi_data = aqi_data.data # Convert to dict
|
||||
|
||||
prompt = f"""
|
||||
You are an expert health advisor.
|
||||
|
||||
Based on the following air quality conditions in {user_city}, {user_state}, {user_country}:
|
||||
- Overall AQI: {aqi_data.get('aqi', 'N/A')}
|
||||
- PM2.5 Level: {aqi_data.get('pm25', 'N/A')} µg/m³
|
||||
- PM10 Level: {aqi_data.get('pm10', 'N/A')} µg/m³
|
||||
- CO Level: {aqi_data.get('co', 'N/A')} ppb
|
||||
|
||||
Weather conditions:
|
||||
- Temperature: {aqi_data.get('temperature', 'N/A')}°C
|
||||
- Humidity: {aqi_data.get('humidity', 'N/A')}%
|
||||
- Wind Speed: {aqi_data.get('wind_speed', 'N/A')} km/h
|
||||
|
||||
User's Context:
|
||||
- Medical Conditions: {user_medical_conditions or 'None'}
|
||||
- Planned Activity: {user_planned_activity}
|
||||
|
||||
**Comprehensive Health Recommendations:**
|
||||
1. **Impact of Current Air Quality on Health:**
|
||||
2. **Necessary Safety Precautions for Planned Activity:**
|
||||
3. **Advisability of Planned Activity:**
|
||||
4. **Best Time to Conduct the Activity:**
|
||||
"""
|
||||
|
||||
agent = Agent(
|
||||
name="Air Quality Health Advisor",
|
||||
instructions=prompt,
|
||||
api_key=os.environ["OPENAI_API_KEY"]
|
||||
)
|
||||
|
||||
recommendations = agent.start(prompt)
|
||||
print("=== Air Quality Analysis Agent Recommendations ===")
|
||||
print(recommendations)
|
||||
@@ -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,11 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a chess AI agent. "
|
||||
"Help users improve their chess skills, analyze positions, develop strategies, and understand chess theory. "
|
||||
"Provide move analysis, opening guidance, endgame techniques, and tactical training.",
|
||||
llm="openrouter/moonshotai/kimi-k2"
|
||||
)
|
||||
|
||||
response = agent.start("Hello! I'm your chess assistant. "
|
||||
"How can I help you improve your chess game today?")
|
||||
@@ -0,0 +1,11 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a creative writing AI agent. "
|
||||
"Help users develop compelling stories, characters, dialogue, and narrative structures. "
|
||||
"Provide guidance on plot development, world-building, genre-specific techniques, and creative inspiration.",
|
||||
llm="openrouter/moonshotai/kimi-k2"
|
||||
)
|
||||
|
||||
response = agent.start("Hello! I'm your creative writing assistant. "
|
||||
"How can I help you bring your stories and ideas to life today?")
|
||||
@@ -0,0 +1,11 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a cybersecurity AI agent. "
|
||||
"Help users with security assessments, threat analysis, vulnerability management, and security best practices. "
|
||||
"Provide guidance on penetration testing, secure coding, incident response, and compliance frameworks.",
|
||||
llm="openrouter/moonshotai/kimi-k2"
|
||||
)
|
||||
|
||||
response = agent.start("Hello! I'm your cybersecurity assistant. "
|
||||
"How can I help you secure your systems and protect against threats today?")
|
||||
@@ -0,0 +1,11 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a data visualization AI agent. "
|
||||
"Help users create compelling charts, graphs, dashboards, and interactive visualizations. "
|
||||
"Provide guidance on matplotlib, seaborn, plotly, Tableau, and best practices for effective data storytelling.",
|
||||
llm="openrouter/moonshotai/kimi-k2"
|
||||
)
|
||||
|
||||
response = agent.start("Hello! I'm your data visualization assistant. "
|
||||
"How can I help you create stunning visual representations of your data today?")
|
||||
@@ -0,0 +1,11 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a 3D PyGame development AI agent. "
|
||||
"Help users create 3D games, simulations, and interactive experiences using PyGame. "
|
||||
"Provide code examples, debugging assistance, and best practices for 3D graphics programming.",
|
||||
llm="openrouter/moonshotai/kimi-k2"
|
||||
)
|
||||
|
||||
response = agent.start("Hello! I'm your 3D PyGame development assistant. "
|
||||
"How can I help you create amazing 3D games today?")
|
||||
@@ -0,0 +1,11 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a self-evolving AI agent. "
|
||||
"Continuously learn from interactions, adapt your responses, and improve your capabilities. "
|
||||
"Help users with complex problem-solving, creative tasks, and provide insights that evolve based on context and user needs.",
|
||||
llm="openrouter/moonshotai/kimi-k2"
|
||||
)
|
||||
|
||||
response = agent.start("Hello! I'm your self-evolving AI assistant. "
|
||||
"How can I help you today, and how can I learn and improve from our interaction?")
|
||||
@@ -0,0 +1,11 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a startup insight AI agent. "
|
||||
"Help entrepreneurs and startup teams with market analysis, business strategy, funding advice, product development, and growth tactics. "
|
||||
"Provide actionable insights for building successful startups.",
|
||||
llm="openrouter/moonshotai/kimi-k2"
|
||||
)
|
||||
|
||||
response = agent.start("Hello! I'm your startup insight assistant. "
|
||||
"How can I help you build and grow your startup today?")
|
||||
@@ -0,0 +1,11 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a system architecture AI agent. "
|
||||
"Help users design scalable, efficient, and robust system architectures. "
|
||||
"Provide guidance on microservices, cloud infrastructure, database design, API design, and system integration patterns.",
|
||||
llm="openrouter/moonshotai/kimi-k2"
|
||||
)
|
||||
|
||||
response = agent.start("Hello! I'm your system architecture assistant. "
|
||||
"How can I help you design and optimize your system architecture today?")
|
||||
@@ -0,0 +1,11 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a web scraping AI agent. "
|
||||
"Help users create efficient and ethical web scrapers, data extraction tools, and automation scripts. "
|
||||
"Provide guidance on BeautifulSoup, Selenium, Scrapy, and best practices for responsible web scraping.",
|
||||
llm="openrouter/moonshotai/kimi-k2"
|
||||
)
|
||||
|
||||
response = agent.start("Hello! I'm your web scraping assistant. "
|
||||
"How can I help you extract and analyze web data today?")
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
#!/usr/bin/env python
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
Game Playing Agent (Tic Tac Toe) using PraisonAIAgents
|
||||
|
||||
Two AI agents play against each other, coordinated by a referee agent.
|
||||
This script is CI-friendly: it uses dummy moves if API keys are not set.
|
||||
"""
|
||||
|
||||
import os
|
||||
from praisonaiagents import Agent
|
||||
|
||||
# Set up key (robust, CI-safe)
|
||||
OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY", "sk-..")
|
||||
os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY
|
||||
|
||||
def is_valid_key(key, prefix):
|
||||
return key and key != f"{prefix}-.." and key.startswith(prefix)
|
||||
|
||||
# Custom Tool: Tic Tac Toe Board & Logic
|
||||
class TicTacToeBoard:
|
||||
def __init__(self):
|
||||
self.board = [[" " for _ in range(3)] for _ in range(3)]
|
||||
self.current_player = "X"
|
||||
|
||||
def display(self):
|
||||
for row in self.board:
|
||||
print("|".join(row))
|
||||
print("-" * 5)
|
||||
|
||||
def valid_moves(self):
|
||||
return [(i, j) for i in range(3) for j in range(3) if self.board[i][j] == " "]
|
||||
|
||||
def make_move(self, row, col):
|
||||
if self.board[row][col] == " ":
|
||||
self.board[row][col] = self.current_player
|
||||
self.current_player = "O" if self.current_player == "X" else "X"
|
||||
return True
|
||||
return False
|
||||
|
||||
def check_winner(self):
|
||||
lines = self.board + [list(col) for col in zip(*self.board)] # rows and columns
|
||||
lines += [[self.board[i][i] for i in range(3)], [self.board[i][2-i] for i in range(3)]] # diagonals
|
||||
for line in lines:
|
||||
if line == ["X"] * 3:
|
||||
return "X"
|
||||
if line == ["O"] * 3:
|
||||
return "O"
|
||||
if all(cell != " " for row in self.board for cell in row):
|
||||
return "Draw"
|
||||
return None
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Dummy agent moves for CI/public use
|
||||
dummy_moves = [(0, 0), (1, 1), (0, 1), (1, 0), (0, 2)]
|
||||
|
||||
board = TicTacToeBoard()
|
||||
winner = None
|
||||
|
||||
if not is_valid_key(OPENAI_API_KEY, "sk"):
|
||||
print("API key not set or is a placeholder. Using dummy moves for CI/testing.")
|
||||
print("=== Tic Tac Toe Game ===")
|
||||
board.display()
|
||||
for move in dummy_moves:
|
||||
board.make_move(*move)
|
||||
board.display()
|
||||
winner = board.check_winner()
|
||||
if winner:
|
||||
print(f"Winner: {winner}")
|
||||
break
|
||||
if not winner:
|
||||
print("Game ended in a draw.")
|
||||
else:
|
||||
# Real agent-vs-agent play using praisonaiagents
|
||||
player_x = Agent(
|
||||
name="Player X",
|
||||
instructions="You are Player X. Choose your move as 'row col' (e.g., '1 2').",
|
||||
api_key=OPENAI_API_KEY
|
||||
)
|
||||
player_o = Agent(
|
||||
name="Player O",
|
||||
instructions="You are Player O. Choose your move as 'row col' (e.g., '1 2').",
|
||||
api_key=OPENAI_API_KEY
|
||||
)
|
||||
print("=== Tic Tac Toe Game (AI vs AI) ===")
|
||||
board.display()
|
||||
for _ in range(9):
|
||||
current_agent = player_x if board.current_player == "X" else player_o
|
||||
prompt = f"Current board:\n{board.board}\nValid moves: {board.valid_moves()}\nYour move (row col):"
|
||||
move_str = current_agent.start(prompt)
|
||||
try:
|
||||
row, col = map(int, move_str.strip().split())
|
||||
except Exception:
|
||||
print(f"Invalid move from agent: {move_str}. Skipping turn.")
|
||||
continue
|
||||
if (row, col) not in board.valid_moves():
|
||||
print(f"Illegal move: {row} {col}. Skipping turn.")
|
||||
continue
|
||||
board.make_move(row, col)
|
||||
board.display()
|
||||
winner = board.check_winner()
|
||||
if winner:
|
||||
print(f"Winner: {winner}")
|
||||
break
|
||||
if not winner:
|
||||
print("Game ended in a draw.")
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
#!/usr/bin/env python
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
Domain Deep Research Agent using PraisonAIAgents
|
||||
|
||||
This script performs deep research on a given topic and provides a structured report.
|
||||
It is CI-friendly: it uses dummy data if API keys are not set.
|
||||
"""
|
||||
|
||||
import os
|
||||
from praisonaiagents import Agent
|
||||
|
||||
# Set up key (robust, CI-safe)
|
||||
OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY", "sk-..")
|
||||
os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY
|
||||
|
||||
def is_valid_key(key, prefix):
|
||||
return key and key != f"{prefix}-.." and key.startswith(prefix)
|
||||
|
||||
# Custom Tool: Dummy Deep Research Tool
|
||||
class DummyDeepResearchTool:
|
||||
"""
|
||||
Custom tool to simulate deep research for CI/public use.
|
||||
"""
|
||||
def __init__(self, topic):
|
||||
self.topic = topic
|
||||
|
||||
def research(self):
|
||||
# For demo/CI, just return a dummy report
|
||||
return f"## Research Report on {self.topic}\n\n- Key finding 1 about {self.topic}\n- Key finding 2 about {self.topic}\n- Key finding 3 about {self.topic}\n"
|
||||
|
||||
if __name__ == "__main__":
|
||||
# User input (for demo, hardcoded; in real use, use input() or widgets)
|
||||
topic = "Recent advances in quantum computing"
|
||||
|
||||
# Use the custom tool
|
||||
tool = DummyDeepResearchTool(topic)
|
||||
dummy_report = tool.research()
|
||||
|
||||
if not is_valid_key(OPENAI_API_KEY, "sk"):
|
||||
print("API key not set or is a placeholder. Using dummy research report for CI/testing.")
|
||||
print(dummy_report)
|
||||
else:
|
||||
prompt = f"""
|
||||
You are a domain research assistant. Perform deep research on the following topic and provide a structured, well-cited report:
|
||||
TOPIC: {topic}
|
||||
"""
|
||||
agent = Agent(
|
||||
name="Domain Deep Research Agent",
|
||||
instructions=prompt,
|
||||
api_key=OPENAI_API_KEY
|
||||
)
|
||||
report = agent.start(prompt)
|
||||
print(report)
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
#!/usr/bin/env python
|
||||
# coding: utf-8
|
||||
|
||||
# # News and Podcast Aggregator Agent using PraisonAIAgents
|
||||
|
||||
# This notebook demonstrates a News and Podcast Aggregator Agent built with `praisonaiagents`.
|
||||
# It summarizes news articles and generates podcast-style discussion points.
|
||||
# The notebook is CI-friendly: it uses dummy data if API keys are not set, so all tests/checks will pass.
|
||||
|
||||
# [](https://colab.research.google.com/github/Dhivya-Bharathy/PraisonAI/blob/main/examples/cookbooks/SocialMedia_Content_Agents/News_And_Podcast_Aggregator_Agent.ipynb)
|
||||
#
|
||||
|
||||
# # Dependencies
|
||||
|
||||
# In[ ]:
|
||||
|
||||
|
||||
get_ipython().system('pip install praisonaiagents pydantic')
|
||||
|
||||
|
||||
# # Imports and Setup
|
||||
|
||||
# In[3]:
|
||||
|
||||
|
||||
import os
|
||||
|
||||
# Set up the OpenAI API key for praisonaiagents
|
||||
os.environ["OPENAI_API_KEY"] = os.environ.get("OPENAI_API_KEY", "sk-..")
|
||||
|
||||
def is_valid_key(key, prefix):
|
||||
return key and key != f"{prefix}-.." and key.startswith(prefix)
|
||||
|
||||
OPENAI_API_KEY = os.environ["OPENAI_API_KEY"]
|
||||
|
||||
|
||||
# # Tools
|
||||
|
||||
# In[4]:
|
||||
|
||||
|
||||
from datetime import datetime
|
||||
from typing import List
|
||||
|
||||
def format_search_results_for_podcast(search_results: List[dict]) -> tuple[str, List[str]]:
|
||||
"""
|
||||
Custom tool to format search results for podcast script generation.
|
||||
"""
|
||||
created_at = datetime.now().strftime("%B %d, %Y at %I:%M %p")
|
||||
structured_content = []
|
||||
structured_content.append(f"PODCAST CREATION: {created_at}\n")
|
||||
sources = []
|
||||
for idx, search_result in enumerate(search_results):
|
||||
try:
|
||||
if search_result.get("confirmed", False):
|
||||
sources.append(search_result["url"])
|
||||
structured_content.append(
|
||||
f"""
|
||||
SOURCE {idx + 1}:
|
||||
Title: {search_result['title']}
|
||||
URL: {search_result['url']}
|
||||
Content: {search_result.get('full_text') or search_result.get('description', '')}
|
||||
---END OF SOURCE {idx + 1}---
|
||||
""".strip()
|
||||
)
|
||||
except Exception as e:
|
||||
print(f"Error processing search result: {e}")
|
||||
content_texts = "\n\n".join(structured_content)
|
||||
return content_texts, sources
|
||||
|
||||
|
||||
# # Pydantic Models
|
||||
|
||||
# In[5]:
|
||||
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from typing import List, Optional
|
||||
|
||||
class Dialog(BaseModel):
|
||||
speaker: str = Field(..., description="The speaker name (SHOULD BE 'ALEX' OR 'MORGAN')")
|
||||
text: str = Field(..., description="The spoken text content for this speaker based on the requested language, default is English")
|
||||
|
||||
class Section(BaseModel):
|
||||
type: str = Field(..., description="The section type (intro, headlines, article, outro)")
|
||||
title: Optional[str] = Field(None, description="Optional title for the section (required for article type)")
|
||||
dialog: List[Dialog] = Field(..., description="List of dialog exchanges between speakers")
|
||||
|
||||
class PodcastScript(BaseModel):
|
||||
title: str = Field(..., description="The podcast episode title with date")
|
||||
sections: List[Section] = Field(..., description="List of podcast sections (intro, headlines, articles, outro)")
|
||||
|
||||
|
||||
# # Agent Instructions
|
||||
|
||||
# In[6]:
|
||||
|
||||
|
||||
from textwrap import dedent
|
||||
|
||||
PODCAST_AGENT_DESCRIPTION = "You are a helpful assistant that can generate engaging podcast scripts for the given sources."
|
||||
PODCAST_AGENT_INSTRUCTIONS = dedent("""
|
||||
You are a helpful assistant that can generate engaging podcast scripts for the given source content and query.
|
||||
For given content, create an engaging podcast script that should be at least 15 minutes worth of content and you are allowed to enhance the script beyond given sources if you know something additional info will be interesting to the discussion or not enough content is available.
|
||||
You use the provided sources to ground your podcast script generation process. Keep it engaging and interesting.
|
||||
IMPORTANT: Generate the entire script in the provided language.
|
||||
CONTENT GUIDELINES:
|
||||
- Provide insightful analysis that helps the audience understand the significance
|
||||
- Include discussions on potential implications and broader context of each story
|
||||
- Explain complex concepts in an accessible but thorough manner
|
||||
- Make connections between current and relevant historical developments when applicable
|
||||
- Provide comparisons and contrasts with similar stories or trends when relevant
|
||||
PERSONALITY NOTES:
|
||||
- Alex is more analytical and fact-focused
|
||||
- Morgan is more focused on human impact, social context, and practical applications
|
||||
- Include natural, conversational banter and smooth transitions between topics
|
||||
- Each article discussion should go beyond the basic summary to provide valuable insights
|
||||
- Maintain a conversational but informed tone that would appeal to a general audience
|
||||
IMPORTANT:
|
||||
- MAKE SURE PODCAST SCRIPTS ARE AT LEAST 15 MINUTES LONG WHICH MEANS YOU NEED TO HAVE DETAILED DISCUSSIONS BUT KEEP IT INTERESTING AND ENGAGING.
|
||||
""")
|
||||
|
||||
|
||||
# # Dummy Data and Main Logic
|
||||
|
||||
# In[7]:
|
||||
|
||||
|
||||
from praisonaiagents import Agent
|
||||
|
||||
# Dummy search results for CI/public use
|
||||
dummy_search_results = [
|
||||
{
|
||||
"confirmed": True,
|
||||
"title": "AI Revolutionizes Healthcare",
|
||||
"url": "https://news.example.com/ai-healthcare",
|
||||
"full_text": "Artificial intelligence is transforming the healthcare industry by..."
|
||||
},
|
||||
{
|
||||
"confirmed": True,
|
||||
"title": "Climate Change and Global Policy",
|
||||
"url": "https://news.example.com/climate-policy",
|
||||
"full_text": "World leaders are meeting to discuss new policies for climate change..."
|
||||
}
|
||||
]
|
||||
|
||||
query = "Latest technology and world news"
|
||||
language_name = "English"
|
||||
|
||||
content_texts, sources = format_search_results_for_podcast(dummy_search_results)
|
||||
|
||||
if not is_valid_key(OPENAI_API_KEY, "sk"):
|
||||
print("API key not set or is a placeholder. Using dummy podcast script for CI/testing.")
|
||||
print("=== Podcast Script ===")
|
||||
print(f"Podcast Title: Tech & World News Roundup ({datetime.now().strftime('%B %d, %Y')})")
|
||||
for idx, article in enumerate(dummy_search_results):
|
||||
print(f"\nSection {idx+1}: {article['title']}")
|
||||
print(f"Summary: {article['full_text'][:80]}...")
|
||||
else:
|
||||
agent = Agent(
|
||||
name="Podcast Script Agent",
|
||||
instructions=PODCAST_AGENT_INSTRUCTIONS,
|
||||
api_key=OPENAI_API_KEY
|
||||
)
|
||||
prompt = f"query: {query}\nlanguage_name: {language_name}\ncontent_texts: {content_texts}\nIMPORTANT: texts should be in {language_name} language."
|
||||
podcast_script = agent.start(prompt)
|
||||
print("=== Podcast Script ===")
|
||||
print(podcast_script)
|
||||
|
||||
+13
@@ -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?"
|
||||
)
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a customer support AI agent for TechGadgets.com, an online electronics store. Answer customer queries helpfully.",
|
||||
llm="xai/grok-4"
|
||||
)
|
||||
|
||||
response = agent.start("How to return an item?")
|
||||
@@ -0,0 +1,8 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a data analysis AI agent. Help users analyze datasets, create visualizations, and extract meaningful insights from data.",
|
||||
llm="xai/grok-4"
|
||||
)
|
||||
|
||||
response = agent.start("I have sales data for the last quarter. Can you help me identify trends and patterns?")
|
||||
@@ -0,0 +1,8 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a deep research AI agent. Conduct comprehensive research, analyze complex topics, and provide detailed insights on various subjects.",
|
||||
llm="xai/grok-4"
|
||||
)
|
||||
|
||||
response = agent.start("I need to research the impact of artificial intelligence on job markets. Can you provide a comprehensive analysis?")
|
||||
@@ -0,0 +1,8 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a health and fitness AI agent. Help users with workout plans, nutrition advice, wellness tips, and health monitoring guidance.",
|
||||
llm="xai/grok-4"
|
||||
)
|
||||
|
||||
response = agent.start("I want to lose 20 pounds and build muscle. What's the best workout and nutrition plan for me?")
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are an investment advisor AI agent. Help users with investment strategies, portfolio analysis, risk assessment, and market insights.",
|
||||
llm="xai/grok-4"
|
||||
)
|
||||
|
||||
response = agent.start("I have $50,000 to invest. What would be a good diversified portfolio for someone in their 30s?")
|
||||
@@ -0,0 +1,8 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a journalist AI agent. Help with news writing, article creation, fact-checking, and content generation for various media platforms.",
|
||||
llm="xai/grok-4"
|
||||
)
|
||||
|
||||
response = agent.start("I need to write an article about the latest developments in renewable energy. Can you help me structure it?")
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a lead generation AI agent for RealEstatePro.com. Help identify and qualify potential real estate leads.",
|
||||
llm="xai/grok-4"
|
||||
)
|
||||
|
||||
response = agent.start("I'm looking to buy a house in the suburbs with 3 bedrooms and a garden.")
|
||||
@@ -0,0 +1,8 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a medical imaging AI agent. Help analyze medical images, provide preliminary assessments, and assist healthcare professionals with diagnostic support.",
|
||||
llm="xai/grok-4"
|
||||
)
|
||||
|
||||
response = agent.start("I have an X-ray image that needs analysis. Can you help identify any abnormalities?")
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a meeting productivity AI agent. Help optimize meeting efficiency and follow-up actions.",
|
||||
llm="xai/grok-4"
|
||||
)
|
||||
|
||||
response = agent.start("I have a team meeting tomorrow. How can I make it more productive?")
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a mental wellbeing AI advisor. Provide supportive guidance and wellness tips.",
|
||||
llm="xai/grok-4"
|
||||
)
|
||||
|
||||
response = agent.start("I've been feeling stressed at work lately. Any tips for managing stress?")
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a multimodal reasoning AI agent. Analyze images and text to provide comprehensive insights.",
|
||||
llm="xai/grok-4"
|
||||
)
|
||||
|
||||
response = agent.start("Can you help me analyze a chart showing sales data for Q1 2024?")
|
||||
@@ -0,0 +1,8 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a music generation AI agent. Help users create melodies, lyrics, and musical compositions based on their preferences and requirements.",
|
||||
llm="xai/grok-4"
|
||||
)
|
||||
|
||||
response = agent.start("I need a catchy jingle for my coffee shop. Can you help me create one?")
|
||||
@@ -0,0 +1,8 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a personal finance AI agent. Help users with budgeting, saving strategies, debt management, and financial planning advice.",
|
||||
llm="xai/grok-4"
|
||||
)
|
||||
|
||||
response = agent.start("I want to save $10,000 in the next year. What's the best strategy for me?")
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a startup trend analysis AI agent. Help entrepreneurs identify market opportunities, analyze industry trends, and evaluate business ideas.",
|
||||
llm="xai/grok-4"
|
||||
)
|
||||
|
||||
response = agent.start("I'm thinking of starting a tech startup. What are the current trending opportunities in the market?")
|
||||
@@ -0,0 +1,8 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a travel planning AI agent. Help users plan trips, find destinations, and create itineraries with budget considerations.",
|
||||
llm="xai/grok-4"
|
||||
)
|
||||
|
||||
response = agent.start("I want to plan a 7-day trip to Europe with a budget of $3000. What are my best options?")
|
||||
@@ -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?"
|
||||
)
|
||||
+1
-1
@@ -196,4 +196,4 @@ def main():
|
||||
print("Make sure SearxNG is running at http://localhost:32768")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
main()
|
||||
@@ -0,0 +1,420 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Custom Trafilatura Tools for High-Quality URL Content Extraction
|
||||
|
||||
This is an example of creating custom tools for PraisonAI agents.
|
||||
This tool is not part of the core package - it's a standalone custom tool
|
||||
that demonstrates how to implement web content extraction using Trafilatura.
|
||||
|
||||
Install dependencies:
|
||||
pip install trafilatura newspaper3k
|
||||
|
||||
Usage:
|
||||
from custom_trafilatura_tools import TrafilaturaTools
|
||||
|
||||
tools = TrafilaturaTools()
|
||||
content = tools.extract_content("https://example.com/article")
|
||||
metadata = tools.extract_metadata("https://example.com/article")
|
||||
"""
|
||||
|
||||
import logging
|
||||
from typing import Dict, Any, Optional, Union, List
|
||||
from importlib import util
|
||||
import json
|
||||
from urllib.parse import urlparse
|
||||
|
||||
|
||||
class TrafilaturaTools:
|
||||
"""Custom tools for extracting high-quality content from URLs using Trafilatura."""
|
||||
|
||||
def __init__(self):
|
||||
"""Initialize TrafilaturaTools and check for required packages."""
|
||||
self.trafilatura = self._check_and_import_trafilatura()
|
||||
|
||||
def _check_and_import_trafilatura(self):
|
||||
"""Check if trafilatura package is installed and import it."""
|
||||
if util.find_spec("trafilatura") is None:
|
||||
raise ImportError(
|
||||
"trafilatura package is not available. Please install it using: pip install trafilatura"
|
||||
)
|
||||
import trafilatura
|
||||
return trafilatura
|
||||
|
||||
def _validate_url(self, url: str) -> bool:
|
||||
"""
|
||||
Validate URL to prevent SSRF attacks.
|
||||
|
||||
Args:
|
||||
url: URL to validate
|
||||
|
||||
Returns:
|
||||
bool: True if URL is safe, False otherwise
|
||||
"""
|
||||
try:
|
||||
parsed = urlparse(url)
|
||||
|
||||
# Only allow http/https protocols
|
||||
if parsed.scheme not in ['http', 'https']:
|
||||
return False
|
||||
|
||||
# Reject URLs with no hostname
|
||||
if not parsed.hostname:
|
||||
return False
|
||||
|
||||
# Reject local/internal addresses
|
||||
hostname = parsed.hostname.lower()
|
||||
|
||||
# Block localhost and loopback
|
||||
if hostname in ['localhost', '127.0.0.1', '0.0.0.0', '::1']:
|
||||
return False
|
||||
|
||||
# Block private IP ranges
|
||||
import ipaddress
|
||||
try:
|
||||
ip = ipaddress.ip_address(hostname)
|
||||
if ip.is_private or ip.is_reserved or ip.is_loopback or ip.is_link_local:
|
||||
return False
|
||||
except ValueError:
|
||||
# Not an IP address, continue with domain validation
|
||||
pass
|
||||
|
||||
# Block common internal domains
|
||||
if any(hostname.endswith(domain) for domain in ['.local', '.internal', '.localdomain']):
|
||||
return False
|
||||
|
||||
# Block metadata service endpoints
|
||||
return hostname not in ['169.254.169.254', 'metadata.google.internal']
|
||||
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def extract_content(
|
||||
self,
|
||||
url: str,
|
||||
include_comments: bool = False,
|
||||
include_links: bool = True,
|
||||
output_format: str = 'json',
|
||||
include_metadata: bool = True,
|
||||
target_language: Optional[str] = None
|
||||
) -> Union[Dict[str, Any], str]:
|
||||
"""
|
||||
Extract high-quality content from a URL using Trafilatura.
|
||||
|
||||
Args:
|
||||
url: URL to extract content from
|
||||
include_comments: Include comments in extraction
|
||||
include_links: Include links in extraction
|
||||
output_format: Output format ('json', 'text', 'xml')
|
||||
include_metadata: Include metadata in extraction
|
||||
target_language: Target language for extraction (None for auto-detect)
|
||||
|
||||
Returns:
|
||||
Dict or str: Extracted content (dict for json format, str for text/xml)
|
||||
"""
|
||||
# Validate URL
|
||||
if not self._validate_url(url):
|
||||
error_msg = f"Invalid or unsafe URL: {url}"
|
||||
logging.error(error_msg)
|
||||
return {"error": error_msg} if output_format == 'json' else error_msg
|
||||
|
||||
try:
|
||||
# Fetch the URL content
|
||||
downloaded = self.trafilatura.fetch_url(url)
|
||||
if not downloaded:
|
||||
error_msg = f"Could not fetch content from URL: {url}"
|
||||
logging.error(error_msg)
|
||||
return {"error": error_msg} if output_format == 'json' else error_msg
|
||||
|
||||
# Extract content
|
||||
extracted = self.trafilatura.extract(
|
||||
downloaded,
|
||||
include_comments=include_comments,
|
||||
include_links=include_links,
|
||||
output_format=output_format,
|
||||
with_metadata=include_metadata,
|
||||
url=url,
|
||||
target_language=target_language
|
||||
)
|
||||
|
||||
if not extracted:
|
||||
error_msg = f"Could not extract readable content from: {url}"
|
||||
logging.warning(error_msg)
|
||||
return {"error": error_msg} if output_format == 'json' else error_msg
|
||||
|
||||
# Parse JSON output if requested
|
||||
if output_format == 'json':
|
||||
return json.loads(extracted)
|
||||
else:
|
||||
return extracted
|
||||
|
||||
except Exception as e:
|
||||
error_msg = f"Error extracting content from {url}: {str(e)}"
|
||||
logging.error(error_msg)
|
||||
return {"error": error_msg} if output_format == 'json' else error_msg
|
||||
|
||||
def extract_metadata(self, url: str) -> Dict[str, Any]:
|
||||
"""
|
||||
Extract metadata from a URL.
|
||||
|
||||
Args:
|
||||
url: URL to extract metadata from
|
||||
|
||||
Returns:
|
||||
Dict: Metadata including title, author, date, etc.
|
||||
"""
|
||||
# Validate URL
|
||||
if not self._validate_url(url):
|
||||
error_msg = f"Invalid or unsafe URL: {url}"
|
||||
logging.error(error_msg)
|
||||
return {"error": error_msg}
|
||||
|
||||
try:
|
||||
# Fetch the URL content
|
||||
downloaded = self.trafilatura.fetch_url(url)
|
||||
if not downloaded:
|
||||
error_msg = f"Could not fetch content from URL: {url}"
|
||||
logging.error(error_msg)
|
||||
return {"error": error_msg}
|
||||
|
||||
# Extract metadata
|
||||
metadata = self.trafilatura.extract_metadata(downloaded, url=url)
|
||||
|
||||
if not metadata:
|
||||
return {
|
||||
"url": url,
|
||||
"error": "No metadata found"
|
||||
}
|
||||
|
||||
# Convert metadata object to dict
|
||||
result = {
|
||||
"url": url,
|
||||
"title": metadata.title,
|
||||
"author": metadata.author,
|
||||
"date": metadata.date,
|
||||
"description": metadata.description,
|
||||
"categories": metadata.categories,
|
||||
"tags": metadata.tags,
|
||||
"language": metadata.language,
|
||||
"image": metadata.image,
|
||||
"pagetype": metadata.pagetype,
|
||||
"license": metadata.license
|
||||
}
|
||||
|
||||
# Remove None values
|
||||
result = {k: v for k, v in result.items() if v is not None}
|
||||
|
||||
return result
|
||||
|
||||
except Exception as e:
|
||||
error_msg = f"Error extracting metadata from {url}: {str(e)}"
|
||||
logging.error(error_msg)
|
||||
return {"error": error_msg}
|
||||
|
||||
def extract_text_only(
|
||||
self,
|
||||
url: str,
|
||||
include_comments: bool = False
|
||||
) -> str:
|
||||
"""
|
||||
Extract only the main text content from a URL.
|
||||
|
||||
Args:
|
||||
url: URL to extract text from
|
||||
include_comments: Include comments in extraction
|
||||
|
||||
Returns:
|
||||
str: Extracted text content
|
||||
"""
|
||||
result = self.extract_content(
|
||||
url=url,
|
||||
include_comments=include_comments,
|
||||
include_links=False,
|
||||
output_format='text',
|
||||
include_metadata=False
|
||||
)
|
||||
return result
|
||||
|
||||
def compare_extraction(
|
||||
self,
|
||||
url: str,
|
||||
include_newspaper: bool = True,
|
||||
include_spider: bool = True
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Compare Trafilatura extraction with other tools for the same URL.
|
||||
|
||||
Args:
|
||||
url: URL to extract content from
|
||||
include_newspaper: Include newspaper3k comparison
|
||||
include_spider: Include spider_tools comparison (if available)
|
||||
|
||||
Returns:
|
||||
Dict: Comparison of extraction results
|
||||
"""
|
||||
comparison = {
|
||||
"url": url,
|
||||
"trafilatura": None,
|
||||
"newspaper": None,
|
||||
"spider": None
|
||||
}
|
||||
|
||||
# Get Trafilatura extraction
|
||||
try:
|
||||
comparison["trafilatura"] = self.extract_content(url)
|
||||
except Exception as e:
|
||||
comparison["trafilatura"] = {"error": str(e)}
|
||||
|
||||
# Get Newspaper extraction if requested
|
||||
if include_newspaper:
|
||||
try:
|
||||
# Try to import and use newspaper3k
|
||||
if util.find_spec("newspaper") is not None:
|
||||
import newspaper
|
||||
article = newspaper.Article(url)
|
||||
article.download()
|
||||
article.parse()
|
||||
comparison["newspaper"] = {
|
||||
"title": article.title,
|
||||
"text": article.text,
|
||||
"authors": article.authors,
|
||||
"publish_date": str(article.publish_date) if article.publish_date else None,
|
||||
"top_image": article.top_image,
|
||||
"summary": article.summary if hasattr(article, 'summary') else None
|
||||
}
|
||||
else:
|
||||
comparison["newspaper"] = {"error": "newspaper3k not installed"}
|
||||
except Exception as e:
|
||||
comparison["newspaper"] = {"error": str(e)}
|
||||
|
||||
# Get Spider extraction if requested (placeholder for external spider tools)
|
||||
if include_spider:
|
||||
try:
|
||||
# This is a placeholder - you could integrate with other scraping tools here
|
||||
# For now, we'll use a simple requests + BeautifulSoup approach
|
||||
if util.find_spec("requests") and util.find_spec("bs4"):
|
||||
import requests
|
||||
from bs4 import BeautifulSoup
|
||||
|
||||
response = requests.get(url, timeout=10)
|
||||
soup = BeautifulSoup(response.content, 'html.parser')
|
||||
|
||||
# Extract basic content
|
||||
title = soup.find('title')
|
||||
title_text = title.get_text().strip() if title else None
|
||||
|
||||
# Remove script and style elements
|
||||
for script in soup(["script", "style"]):
|
||||
script.decompose()
|
||||
|
||||
# Get text
|
||||
text = soup.get_text()
|
||||
# Clean up whitespace
|
||||
lines = (line.strip() for line in text.splitlines())
|
||||
chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
|
||||
text = ' '.join(chunk for chunk in chunks if chunk)
|
||||
|
||||
comparison["spider"] = {
|
||||
"title": title_text,
|
||||
"text": text[:2000], # Limit to first 2000 chars
|
||||
"method": "requests+beautifulsoup"
|
||||
}
|
||||
else:
|
||||
comparison["spider"] = {"error": "requests or beautifulsoup4 not installed"}
|
||||
except Exception as e:
|
||||
comparison["spider"] = {"error": str(e)}
|
||||
|
||||
return comparison
|
||||
|
||||
def get_available_methods(self) -> List[str]:
|
||||
"""
|
||||
Get list of available methods in this tool.
|
||||
|
||||
Returns:
|
||||
List[str]: List of method names
|
||||
"""
|
||||
return [
|
||||
'extract_content',
|
||||
'extract_metadata',
|
||||
'extract_text_only',
|
||||
'compare_extraction'
|
||||
]
|
||||
|
||||
|
||||
# Convenience functions for easier usage
|
||||
def create_trafilatura_tools() -> TrafilaturaTools:
|
||||
"""Create and return a TrafilaturaTools instance."""
|
||||
return TrafilaturaTools()
|
||||
|
||||
|
||||
# Test the tool
|
||||
if __name__ == "__main__":
|
||||
# Test URL
|
||||
test_url = "https://www.python.org/about/"
|
||||
|
||||
print("Testing Custom Trafilatura Tools")
|
||||
print("=" * 50)
|
||||
|
||||
try:
|
||||
# Create tools instance
|
||||
tools = TrafilaturaTools()
|
||||
|
||||
# Test 1: Extract content
|
||||
print("\n1. Testing extract_content():")
|
||||
print("-" * 50)
|
||||
content = tools.extract_content(test_url)
|
||||
if isinstance(content, dict) and 'error' not in content:
|
||||
print(f"✓ Title: {content.get('title', 'N/A')}")
|
||||
print(f"✓ Language: {content.get('language', 'N/A')}")
|
||||
print(f"✓ Text length: {len(content.get('text', ''))} characters")
|
||||
print(f"✓ Author: {content.get('author', 'N/A')}")
|
||||
print(f"✓ Date: {content.get('date', 'N/A')}")
|
||||
else:
|
||||
print(f"✗ Error: {content}")
|
||||
|
||||
# Test 2: Extract metadata
|
||||
print("\n2. Testing extract_metadata():")
|
||||
print("-" * 50)
|
||||
metadata = tools.extract_metadata(test_url)
|
||||
if isinstance(metadata, dict) and 'error' not in metadata:
|
||||
print("✓ Metadata extracted successfully:")
|
||||
for key, value in metadata.items():
|
||||
if key != 'url':
|
||||
print(f" - {key}: {value}")
|
||||
else:
|
||||
print(f"✗ Error: {metadata}")
|
||||
|
||||
# Test 3: Extract text only
|
||||
print("\n3. Testing extract_text_only():")
|
||||
print("-" * 50)
|
||||
text = tools.extract_text_only(test_url)
|
||||
if isinstance(text, str) and text and "error" not in text.lower():
|
||||
print(f"✓ Text extracted: {len(text)} characters")
|
||||
print(f"✓ Preview: {text[:150]}...")
|
||||
else:
|
||||
print(f"✗ Error: {text}")
|
||||
|
||||
# Test 4: Test URL validation
|
||||
print("\n4. Testing URL validation (security):")
|
||||
print("-" * 50)
|
||||
unsafe_urls = ["http://localhost/test", "http://127.0.0.1/test"]
|
||||
for unsafe_url in unsafe_urls:
|
||||
result = tools.extract_content(unsafe_url)
|
||||
if isinstance(result, dict) and 'error' in result and 'Invalid or unsafe URL' in result['error']:
|
||||
print(f"✓ Correctly rejected: {unsafe_url}")
|
||||
else:
|
||||
print(f"✗ Failed to reject: {unsafe_url}")
|
||||
|
||||
# Test 5: Available methods
|
||||
print("\n5. Available methods:")
|
||||
print("-" * 50)
|
||||
methods = tools.get_available_methods()
|
||||
for method in methods:
|
||||
print(f"✓ {method}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"✗ Failed to initialize tools: {e}")
|
||||
print("\nMake sure to install dependencies:")
|
||||
print("pip install trafilatura newspaper3k requests beautifulsoup4")
|
||||
|
||||
print("\n" + "=" * 50)
|
||||
print("Custom Trafilatura Tools testing complete!")
|
||||
@@ -0,0 +1,266 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Example: Using Custom Trafilatura Tools for High-Quality URL Content Extraction
|
||||
|
||||
This example demonstrates how to create and use custom Trafilatura tools in PraisonAI
|
||||
for extracting high-quality content from web pages.
|
||||
|
||||
This shows how to create custom tools that are not part of the core package.
|
||||
|
||||
Install dependencies:
|
||||
pip install trafilatura newspaper3k requests beautifulsoup4
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
from praisonaiagents import Agent, Task, PraisonAIAgents
|
||||
from custom_trafilatura_tools import TrafilaturaTools, create_trafilatura_tools
|
||||
|
||||
# Create tools instance (global for reuse across examples)
|
||||
tools = None
|
||||
|
||||
def get_tools():
|
||||
"""Get or create tools instance"""
|
||||
global tools
|
||||
if tools is None:
|
||||
tools = create_trafilatura_tools()
|
||||
return tools
|
||||
|
||||
# Example 1: Basic content extraction
|
||||
async def basic_extraction_example():
|
||||
"""Extract content from a URL using custom Trafilatura tools"""
|
||||
tools_instance = get_tools()
|
||||
|
||||
# Extract content from a URL
|
||||
url = "https://www.python.org/about/"
|
||||
content = await asyncio.to_thread(tools_instance.extract_content, url)
|
||||
|
||||
if 'error' not in content:
|
||||
print(f"Title: {content.get('title', 'N/A')}")
|
||||
print(f"Author: {content.get('author', 'N/A')}")
|
||||
print(f"Date: {content.get('date', 'N/A')}")
|
||||
print(f"Text preview: {content.get('text', '')[:200]}...")
|
||||
else:
|
||||
print(f"Error: {content['error']}")
|
||||
|
||||
# Example 2: Extract text only
|
||||
async def text_only_example():
|
||||
"""Extract only the main text content"""
|
||||
tools_instance = get_tools()
|
||||
|
||||
url = "https://www.python.org/about/"
|
||||
text = await asyncio.to_thread(tools_instance.extract_text_only, url)
|
||||
|
||||
print(f"Extracted text ({len(text)} characters):")
|
||||
print(f"{text[:300]}...")
|
||||
|
||||
# Example 3: Extract metadata
|
||||
async def metadata_example():
|
||||
"""Extract metadata from a web page"""
|
||||
tools_instance = get_tools()
|
||||
|
||||
url = "https://www.python.org/about/"
|
||||
metadata = await asyncio.to_thread(tools_instance.extract_metadata, url)
|
||||
|
||||
print("Page metadata:")
|
||||
for key, value in metadata.items():
|
||||
if key != 'url':
|
||||
print(f" {key}: {value}")
|
||||
|
||||
# Example 4: Compare extraction methods
|
||||
async def comparison_example():
|
||||
"""Compare Trafilatura with other extraction tools"""
|
||||
tools_instance = get_tools()
|
||||
|
||||
url = "https://www.python.org/about/"
|
||||
comparison = await asyncio.to_thread(
|
||||
tools_instance.compare_extraction,
|
||||
url,
|
||||
include_newspaper=True, # Compare with newspaper3k
|
||||
include_spider=True # Compare with basic scraping
|
||||
)
|
||||
|
||||
print("Extraction comparison:")
|
||||
for tool, result in comparison.items():
|
||||
if tool != 'url' and result:
|
||||
if isinstance(result, dict) and 'error' not in result:
|
||||
print(f"\n{tool.upper()}:")
|
||||
if 'title' in result:
|
||||
print(f" Title: {result.get('title', 'N/A')}")
|
||||
if 'text' in result:
|
||||
text_len = len(result.get('text', ''))
|
||||
print(f" Text length: {text_len} characters")
|
||||
else:
|
||||
print(f"\n{tool.upper()}: {result}")
|
||||
|
||||
# Example 5: Using Custom Trafilatura tools with an Agent
|
||||
async def agent_example():
|
||||
"""Use custom Trafilatura tools with an AI agent"""
|
||||
tools_instance = get_tools()
|
||||
|
||||
# Create wrapper functions for the agent to use
|
||||
def extract_content_tool(url: str) -> dict:
|
||||
"""Extract content from URL using Trafilatura"""
|
||||
return tools_instance.extract_content(url)
|
||||
|
||||
def extract_metadata_tool(url: str) -> dict:
|
||||
"""Extract metadata from URL using Trafilatura"""
|
||||
return tools_instance.extract_metadata(url)
|
||||
|
||||
# Create a research agent with custom Trafilatura tools
|
||||
research_agent = Agent(
|
||||
name="Research Assistant",
|
||||
role="Web Content Analyzer",
|
||||
goal="Extract and analyze content from web pages using custom tools",
|
||||
backstory="You are an expert at extracting and analyzing web content using custom Trafilatura tools",
|
||||
tools=[extract_content_tool, extract_metadata_tool],
|
||||
llm="gpt-4o-mini"
|
||||
)
|
||||
|
||||
# Create a task for content analysis
|
||||
analysis_task = Task(
|
||||
description="""
|
||||
Extract content from this URL: https://www.python.org/about/
|
||||
|
||||
Use the custom Trafilatura tools to provide a summary of:
|
||||
1. The main content and purpose of the page
|
||||
2. Key metadata (author, date, language)
|
||||
3. The overall quality and structure of the content
|
||||
""",
|
||||
expected_output="A comprehensive analysis of the web page content using custom tools",
|
||||
agent=research_agent
|
||||
)
|
||||
|
||||
# Run the analysis
|
||||
agents = PraisonAIAgents(
|
||||
agents=[research_agent],
|
||||
tasks=[analysis_task]
|
||||
)
|
||||
|
||||
result = await agents.astart()
|
||||
print("\nAgent Analysis Result:")
|
||||
print(result)
|
||||
|
||||
# Example 6: Content extraction with language specification
|
||||
async def language_example():
|
||||
"""Extract content with specific language targeting"""
|
||||
tools_instance = get_tools()
|
||||
|
||||
# Extract content targeting specific language
|
||||
url = "https://www.python.org/about/"
|
||||
content = await asyncio.to_thread(
|
||||
tools_instance.extract_content,
|
||||
url,
|
||||
target_language="en", # Target English content
|
||||
include_links=True, # Include links in extraction
|
||||
include_comments=False # Exclude comments
|
||||
)
|
||||
|
||||
if 'error' not in content:
|
||||
print(f"Language: {content.get('language', 'N/A')}")
|
||||
print(f"Number of links: {len(content.get('links', []))}")
|
||||
|
||||
# Example 7: Output format options
|
||||
async def format_example():
|
||||
"""Demonstrate different output formats"""
|
||||
tools_instance = get_tools()
|
||||
|
||||
url = "https://www.python.org/about/"
|
||||
|
||||
# JSON format (default)
|
||||
json_content = await asyncio.to_thread(tools_instance.extract_content, url, output_format='json')
|
||||
print("JSON format - type:", type(json_content))
|
||||
|
||||
# Text format
|
||||
text_content = await asyncio.to_thread(tools_instance.extract_content, url, output_format='text')
|
||||
print("\nText format - first 200 chars:")
|
||||
print(text_content[:200] + "...")
|
||||
|
||||
# XML format
|
||||
xml_content = await asyncio.to_thread(tools_instance.extract_content, url, output_format='xml')
|
||||
print("\nXML format - first 200 chars:")
|
||||
print(xml_content[:200] + "...")
|
||||
|
||||
# Example 8: Show available methods
|
||||
async def available_methods_example():
|
||||
"""Show what methods are available in the custom tool"""
|
||||
tools_instance = get_tools()
|
||||
|
||||
methods = tools_instance.get_available_methods()
|
||||
print("Available methods in custom Trafilatura tools:")
|
||||
for method in methods:
|
||||
print(f" - {method}")
|
||||
|
||||
# Example 9: Security testing
|
||||
async def security_example():
|
||||
"""Test URL validation security features"""
|
||||
tools_instance = get_tools()
|
||||
|
||||
print("Testing URL security validation:")
|
||||
unsafe_urls = [
|
||||
"http://localhost/test",
|
||||
"http://127.0.0.1/test",
|
||||
"http://169.254.169.254/metadata"
|
||||
]
|
||||
|
||||
for unsafe_url in unsafe_urls:
|
||||
result = await asyncio.to_thread(tools_instance.extract_content, unsafe_url)
|
||||
if isinstance(result, dict) and 'error' in result:
|
||||
print(f"✓ Correctly rejected: {unsafe_url}")
|
||||
else:
|
||||
print(f"✗ Failed to reject: {unsafe_url}")
|
||||
|
||||
async def main():
|
||||
"""Run all examples"""
|
||||
print("=== Custom Trafilatura Tools Examples ===\n")
|
||||
|
||||
try:
|
||||
# First check if we can create the tools
|
||||
tools_instance = get_tools()
|
||||
print("✓ Successfully created custom Trafilatura tools\n")
|
||||
|
||||
print("1. Available Methods")
|
||||
print("-" * 40)
|
||||
await available_methods_example()
|
||||
|
||||
print("\n2. Basic Content Extraction")
|
||||
print("-" * 40)
|
||||
await basic_extraction_example()
|
||||
|
||||
print("\n3. Text-Only Extraction")
|
||||
print("-" * 40)
|
||||
await text_only_example()
|
||||
|
||||
print("\n4. Metadata Extraction")
|
||||
print("-" * 40)
|
||||
await metadata_example()
|
||||
|
||||
print("\n5. Tool Comparison")
|
||||
print("-" * 40)
|
||||
await comparison_example()
|
||||
|
||||
print("\n6. Language-Specific Extraction")
|
||||
print("-" * 40)
|
||||
await language_example()
|
||||
|
||||
print("\n7. Output Format Options")
|
||||
print("-" * 40)
|
||||
await format_example()
|
||||
|
||||
print("\n8. Security Testing")
|
||||
print("-" * 40)
|
||||
await security_example()
|
||||
|
||||
print("\n9. Agent-Based Analysis")
|
||||
print("-" * 40)
|
||||
await agent_example()
|
||||
|
||||
except ImportError as e:
|
||||
print(f"✗ Error: {e}")
|
||||
print("\nPlease install required dependencies:")
|
||||
print("pip install trafilatura newspaper3k requests beautifulsoup4")
|
||||
except Exception as e:
|
||||
print(f"✗ Unexpected error: {e}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Run the examples
|
||||
asyncio.run(main())
|
||||
@@ -139,10 +139,32 @@ task = Task(
|
||||
#### Task-Level Guardrails
|
||||
```python
|
||||
from typing import Tuple, Any
|
||||
from praisonaiagents import GuardrailResult
|
||||
|
||||
# Function-based guardrail
|
||||
def validate_output(task_output: TaskOutput) -> Tuple[bool, Any]:
|
||||
"""Custom validation function."""
|
||||
# Function-based guardrail (Option 1: Using GuardrailResult)
|
||||
def validate_output(task_output: TaskOutput) -> GuardrailResult:
|
||||
"""Custom validation function returning GuardrailResult."""
|
||||
if "error" in task_output.raw.lower():
|
||||
return GuardrailResult(
|
||||
success=False,
|
||||
result=None,
|
||||
error="Output contains errors"
|
||||
)
|
||||
if len(task_output.raw) < 10:
|
||||
return GuardrailResult(
|
||||
success=False,
|
||||
result=None,
|
||||
error="Output is too short"
|
||||
)
|
||||
return GuardrailResult(
|
||||
success=True,
|
||||
result=task_output,
|
||||
error=""
|
||||
)
|
||||
|
||||
# Function-based guardrail (Option 2: Using Tuple[bool, Any])
|
||||
def validate_output_tuple(task_output: TaskOutput) -> Tuple[bool, Any]:
|
||||
"""Custom validation function returning tuple."""
|
||||
if "error" in task_output.raw.lower():
|
||||
return False, "Output contains errors"
|
||||
if len(task_output.raw) < 10:
|
||||
@@ -170,7 +192,27 @@ task = Task(
|
||||
#### Agent-Level Guardrails
|
||||
```python
|
||||
# Agent guardrails apply to ALL outputs from that agent
|
||||
def validate_professional_tone(task_output: TaskOutput) -> Tuple[bool, Any]:
|
||||
|
||||
# Option 1: Using GuardrailResult
|
||||
def validate_professional_tone(task_output: TaskOutput) -> GuardrailResult:
|
||||
"""Ensure professional tone in all agent responses."""
|
||||
content = task_output.raw.lower()
|
||||
casual_words = ['yo', 'dude', 'awesome', 'cool']
|
||||
for word in casual_words:
|
||||
if word in content:
|
||||
return GuardrailResult(
|
||||
success=False,
|
||||
result=None,
|
||||
error=f"Unprofessional language detected: {word}"
|
||||
)
|
||||
return GuardrailResult(
|
||||
success=True,
|
||||
result=task_output,
|
||||
error=""
|
||||
)
|
||||
|
||||
# Option 2: Using Tuple[bool, Any]
|
||||
def validate_professional_tone_tuple(task_output: TaskOutput) -> Tuple[bool, Any]:
|
||||
"""Ensure professional tone in all agent responses."""
|
||||
content = task_output.raw.lower()
|
||||
casual_words = ['yo', 'dude', 'awesome', 'cool']
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
from praisonaiagents import AutoAgents
|
||||
from langchain_community.utilities.tavily_search import TavilySearchAPIWrapper
|
||||
|
||||
def tavily(query: str):
|
||||
api_wrapper = TavilySearchAPIWrapper()
|
||||
results = api_wrapper.results(query=query, max_results=5)
|
||||
return results
|
||||
|
||||
# Create AutoAgents instance
|
||||
agents = AutoAgents(
|
||||
instructions="Search for information about AI Agents",
|
||||
tools=[tavily],
|
||||
process="sequential",
|
||||
verbose=True,
|
||||
max_agents=3 # Maximum number of agents to create
|
||||
)
|
||||
|
||||
# Start the agents
|
||||
result = agents.start()
|
||||
print(result)
|
||||
|
||||
##or
|
||||
|
||||
from praisonaiagents import AutoAgents
|
||||
from praisonaiagents.tools import (
|
||||
evaluate, solve_equation, convert_units,
|
||||
calculate_statistics, calculate_financial
|
||||
)
|
||||
|
||||
|
||||
def get_stock_price(company_name: str) -> str:
|
||||
"""
|
||||
Get the stock price of a company
|
||||
|
||||
Args:
|
||||
company_name (str): The name of the company
|
||||
|
||||
Returns:
|
||||
str: The stock price of the company
|
||||
"""
|
||||
|
||||
if company_name.lower() == "apple" or company_name.lower() == "aapl":
|
||||
return f"The stock price of {company_name} is 100"
|
||||
elif company_name.lower() == "google" or company_name.lower() == "googl":
|
||||
return f"The stock price of {company_name} is 200"
|
||||
else:
|
||||
return f"The stock price of {company_name} is 50"
|
||||
|
||||
# Create AutoAgents instance
|
||||
agents = AutoAgents(
|
||||
instructions="Get the stock price of google and compare it to the stock price of apple",
|
||||
tools=[evaluate, get_stock_price],
|
||||
process="sequential",
|
||||
llm="gemini/gemini-2.5-flash-lite-preview-06-17",
|
||||
self_reflect=False,
|
||||
verbose=False,
|
||||
max_agents=3 # Maximum number of agents to create
|
||||
)
|
||||
|
||||
# Start the agents
|
||||
result = agents.start()
|
||||
print(result)
|
||||
@@ -0,0 +1,12 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
def get_weather(city: str) -> str:
|
||||
return f"The weather in {city} is sunny"
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a helpful assistant",
|
||||
llm="gemini/gemini-1.5-flash-latest",
|
||||
tools=[get_weather]
|
||||
)
|
||||
|
||||
agent.start("What is the weather in Tokyo?")
|
||||
@@ -0,0 +1,9 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="Research assistant with web search",
|
||||
llm="gemini/gemini-2.5-flash",
|
||||
tools=[{"googleSearch": {}}, ]
|
||||
)
|
||||
|
||||
response = agent.start("Who is Mervin Praison?")
|
||||
@@ -0,0 +1,30 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
def get_stock_price(company_name: str) -> str:
|
||||
"""
|
||||
Get the stock price of a company
|
||||
|
||||
Args:
|
||||
company_name (str): The name of the company
|
||||
|
||||
Returns:
|
||||
str: The stock price of the company
|
||||
"""
|
||||
return f"The stock price of {company_name} is 100"
|
||||
|
||||
def multiply(a: int, b: int) -> int:
|
||||
"""
|
||||
Multiply two numbers
|
||||
"""
|
||||
return a * b
|
||||
|
||||
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a helpful assistant. You can use the tools provided to you to help the user.",
|
||||
llm="gemini/gemini-2.5-pro",
|
||||
tools=[get_stock_price, multiply]
|
||||
)
|
||||
|
||||
result = agent.start("what is the stock price of Google? multiply the Google stock price with 2")
|
||||
print(result)
|
||||
@@ -0,0 +1,25 @@
|
||||
from pydantic import BaseModel
|
||||
from praisonaiagents import Agent, Task, Agents
|
||||
|
||||
class Recipe(BaseModel):
|
||||
recipe_name: str
|
||||
ingredients: list[str]
|
||||
|
||||
agent = Agent(
|
||||
name="Chef",
|
||||
role="Recipe Creator",
|
||||
llm="gemini/gemini-2.5-flash"
|
||||
)
|
||||
|
||||
task = Task(
|
||||
description="Create a cookie recipe",
|
||||
agent=agent,
|
||||
output_pydantic=Recipe # Will use Gemini's native structured output!
|
||||
)
|
||||
|
||||
agents = Agents(
|
||||
agents=[agent],
|
||||
tasks=[task]
|
||||
)
|
||||
|
||||
agents.start()
|
||||
@@ -0,0 +1,32 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Test script to verify the Gemini JSON parsing fix."""
|
||||
|
||||
from praisonaiagents import Agent
|
||||
|
||||
# Test with minimal configuration to isolate the issue
|
||||
llm_config = {
|
||||
"model": "gemini/gemini-1.5-flash-latest",
|
||||
"temperature": 0.7,
|
||||
"max_tokens": 500,
|
||||
}
|
||||
|
||||
# Create agent with self-reflection enabled
|
||||
agent = Agent(
|
||||
instructions="You are a helpful assistant. Be concise and clear.",
|
||||
llm=llm_config,
|
||||
verbose=True,
|
||||
self_reflect=True,
|
||||
max_reflect=2,
|
||||
min_reflect=1
|
||||
)
|
||||
|
||||
# Test with a simple prompt
|
||||
print("Testing Gemini with self-reflection...")
|
||||
try:
|
||||
response = agent.start("What is 2+2? Explain briefly.")
|
||||
print(f"\nFinal response: {response}")
|
||||
print("\nTest completed successfully!")
|
||||
except Exception as e:
|
||||
print(f"\nError occurred: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
@@ -0,0 +1,179 @@
|
||||
from praisonaiagents import Agent
|
||||
from praisonaiagents.agent.handoff import handoff, handoff_filters
|
||||
from pydantic import BaseModel
|
||||
from typing import Dict, Any
|
||||
import logging
|
||||
|
||||
# Mock data for testing
|
||||
MOCK_ORDERS = {
|
||||
"12345": {
|
||||
"id": "12345",
|
||||
"status": "shipped",
|
||||
"items": ["Widget A", "Widget B"],
|
||||
"total": 99.99,
|
||||
"tracking_number": "TRK123456789",
|
||||
"shipping_address": "123 Main St, City, ST 12345"
|
||||
},
|
||||
"67890": {
|
||||
"id": "67890",
|
||||
"status": "processing",
|
||||
"items": ["Gadget X"],
|
||||
"total": 149.99,
|
||||
"tracking_number": None,
|
||||
"shipping_address": "456 Oak Ave, Town, ST 67890"
|
||||
}
|
||||
}
|
||||
|
||||
MOCK_SHIPMENTS = {
|
||||
"TRK123456789": {
|
||||
"tracking_number": "TRK123456789",
|
||||
"status": "in_transit",
|
||||
"location": "Distribution Center - Chicago",
|
||||
"estimated_delivery": "2024-01-15",
|
||||
"updates": [
|
||||
{"date": "2024-01-10", "status": "picked_up", "location": "Warehouse"},
|
||||
{"date": "2024-01-12", "status": "in_transit", "location": "Chicago"}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
MOCK_TICKETS = []
|
||||
|
||||
# Mock tool functions
|
||||
def check_order_status(order_id: str) -> Dict[str, Any]:
|
||||
"""Check the status of an order"""
|
||||
if order_id in MOCK_ORDERS:
|
||||
return {"success": True, "order": MOCK_ORDERS[order_id]}
|
||||
return {"success": False, "error": f"Order {order_id} not found"}
|
||||
|
||||
def track_shipment(tracking_number: str) -> Dict[str, Any]:
|
||||
"""Track a shipment by tracking number"""
|
||||
if tracking_number in MOCK_SHIPMENTS:
|
||||
return {"success": True, "shipment": MOCK_SHIPMENTS[tracking_number]}
|
||||
return {"success": False, "error": f"Tracking number {tracking_number} not found"}
|
||||
|
||||
def process_refund(order_id: str, reason: str = "customer_request") -> Dict[str, Any]:
|
||||
"""Process a refund for an order"""
|
||||
if order_id in MOCK_ORDERS:
|
||||
order = MOCK_ORDERS[order_id]
|
||||
return {
|
||||
"success": True,
|
||||
"refund_id": f"REF{order_id}",
|
||||
"amount": order["total"],
|
||||
"status": "processing",
|
||||
"estimated_days": 3-5
|
||||
}
|
||||
return {"success": False, "error": f"Order {order_id} not found"}
|
||||
|
||||
def check_refund_policy(item_type: str = "general") -> Dict[str, Any]:
|
||||
"""Check refund policy for different item types"""
|
||||
policies = {
|
||||
"general": {"days": 30, "condition": "unopened", "shipping": "customer_pays"},
|
||||
"electronics": {"days": 15, "condition": "original_packaging", "shipping": "free"},
|
||||
"clothing": {"days": 60, "condition": "tags_attached", "shipping": "customer_pays"}
|
||||
}
|
||||
return {"success": True, "policy": policies.get(item_type, policies["general"])}
|
||||
|
||||
def diagnose_issue(description: str) -> Dict[str, Any]:
|
||||
"""Diagnose a technical issue"""
|
||||
common_solutions = {
|
||||
"login": "Clear cookies and cache, try password reset",
|
||||
"payment": "Check card details, try different payment method",
|
||||
"loading": "Check internet connection, try different browser",
|
||||
"mobile": "Update app, restart device, check storage space"
|
||||
}
|
||||
|
||||
# Simple keyword matching for demo
|
||||
for issue_type, solution in common_solutions.items():
|
||||
if issue_type in description.lower():
|
||||
return {"success": True, "diagnosis": solution, "severity": "low"}
|
||||
|
||||
return {"success": True, "diagnosis": "Please provide more details", "severity": "medium"}
|
||||
|
||||
def create_ticket(issue_description: str, priority: str = "medium") -> Dict[str, Any]:
|
||||
"""Create a support ticket"""
|
||||
ticket_id = f"TICK{len(MOCK_TICKETS) + 1001}"
|
||||
ticket = {
|
||||
"id": ticket_id,
|
||||
"description": issue_description,
|
||||
"priority": priority,
|
||||
"status": "open",
|
||||
"created_at": "2024-01-13T10:00:00Z"
|
||||
}
|
||||
MOCK_TICKETS.append(ticket)
|
||||
return {"success": True, "ticket": ticket}
|
||||
|
||||
def log_escalation(source_agent: str, escalation_data: Dict[str, Any]) -> None:
|
||||
"""Log escalation for audit purposes"""
|
||||
logging.info(f"Escalation from {source_agent}: {escalation_data}")
|
||||
|
||||
# Escalation with structured input
|
||||
class EscalationRequest(BaseModel):
|
||||
issue_type: str
|
||||
severity: str
|
||||
description: str
|
||||
|
||||
# Specialist agents
|
||||
order_agent = Agent(
|
||||
name="Order Management",
|
||||
instructions="You help with order status and tracking.",
|
||||
tools=[check_order_status, track_shipment]
|
||||
)
|
||||
|
||||
refund_agent = Agent(
|
||||
name="Refund Specialist",
|
||||
instructions="You process refunds and handle return requests.",
|
||||
tools=[process_refund, check_refund_policy]
|
||||
)
|
||||
|
||||
technical_agent = Agent(
|
||||
name="Technical Support",
|
||||
instructions="You solve technical issues and provide guidance.",
|
||||
tools=[diagnose_issue, create_ticket]
|
||||
)
|
||||
|
||||
escalation_agent = Agent(
|
||||
name="Senior Manager",
|
||||
instructions="You handle escalated issues requiring management attention."
|
||||
)
|
||||
|
||||
# Main triage agent
|
||||
triage_agent = Agent(
|
||||
name="Customer Service",
|
||||
instructions="""You are the first point of contact. Route customers to the right specialist:
|
||||
- Order issues → Order Management
|
||||
- Refunds → Refund Specialist
|
||||
- Technical problems → Technical Support
|
||||
- Complex issues → Escalate to management
|
||||
""",
|
||||
handoffs=[
|
||||
order_agent,
|
||||
refund_agent,
|
||||
technical_agent,
|
||||
handoff(
|
||||
escalation_agent,
|
||||
tool_name_override="escalate_to_management",
|
||||
input_type=EscalationRequest,
|
||||
on_handoff=lambda src, data: log_escalation(src.name, data)
|
||||
)
|
||||
]
|
||||
)
|
||||
|
||||
# Start the service
|
||||
if __name__ == "__main__":
|
||||
print("Customer Service Handoff System Demo")
|
||||
print("=" * 40)
|
||||
|
||||
# Test different scenarios
|
||||
test_queries = [
|
||||
"I need a refund for order #12345",
|
||||
"What's the status of order #67890?",
|
||||
"I'm having trouble logging into my account",
|
||||
"This is urgent - I need to speak to a manager about a serious billing issue"
|
||||
]
|
||||
|
||||
for query in test_queries:
|
||||
print(f"\nCustomer: {query}")
|
||||
response = triage_agent.chat(query)
|
||||
print(f"Response: {response}")
|
||||
print("-" * 40)
|
||||
@@ -0,0 +1,6 @@
|
||||
from praisonaiagents import Agent, Agents, Tools
|
||||
|
||||
research_agent = Agent(name="Research", instructions="You are a research agent to search internet about AI 2024", tools=[Tools.internet_search])
|
||||
summarise_agent = Agent(name="Summarise", instructions="You are a summarize agent to summarise in points")
|
||||
agents = Agents(agents=[research_agent, summarise_agent])
|
||||
agents.launch(path="/agents", port=3030)
|
||||
@@ -0,0 +1,8 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a helpful assistant",
|
||||
llm="ollama/qwen3"
|
||||
)
|
||||
|
||||
agent.start("Why sky is Blue?")
|
||||
@@ -0,0 +1,30 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
def get_stock_price(company_name: str) -> str:
|
||||
"""
|
||||
Get the stock price of a company
|
||||
|
||||
Args:
|
||||
company_name (str): The name of the company
|
||||
|
||||
Returns:
|
||||
str: The stock price of the company
|
||||
"""
|
||||
return f"The stock price of {company_name} is 100"
|
||||
|
||||
def multiply(a: int, b: int) -> int:
|
||||
"""
|
||||
Multiply two numbers
|
||||
"""
|
||||
return a * b
|
||||
|
||||
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a helpful assistant. You can use the tools provided to you to help the user.",
|
||||
llm="ollama/llama3.2",
|
||||
tools=[get_stock_price, multiply]
|
||||
)
|
||||
|
||||
result = agent.start("what is the stock price of Google? multiply the Google stock price with 2")
|
||||
print(result)
|
||||
@@ -0,0 +1,30 @@
|
||||
from praisonaiagents import Agent
|
||||
|
||||
def get_stock_price(company_name: str) -> str:
|
||||
"""
|
||||
Get the stock price of a company
|
||||
|
||||
Args:
|
||||
company_name (str): The name of the company
|
||||
|
||||
Returns:
|
||||
str: The stock price of the company
|
||||
"""
|
||||
return f"The stock price of {company_name} is 100"
|
||||
|
||||
def multiply(a: int, b: int) -> int:
|
||||
"""
|
||||
Multiply two numbers
|
||||
"""
|
||||
return a * b
|
||||
|
||||
|
||||
|
||||
agent = Agent(
|
||||
instructions="You are a helpful assistant. You can use the tools provided to you to help the user.",
|
||||
llm="gpt-4o",
|
||||
tools=[get_stock_price, multiply]
|
||||
)
|
||||
|
||||
result = agent.start("what is the stock price of Google? multiply the Google stock price with 2")
|
||||
print(result)
|
||||
@@ -2,6 +2,30 @@
|
||||
Praison AI Agents - A package for hierarchical AI agent task execution
|
||||
"""
|
||||
|
||||
# Configure logging before any other imports
|
||||
import os
|
||||
import logging
|
||||
from rich.logging import RichHandler
|
||||
|
||||
# Get log level from environment variable
|
||||
LOGLEVEL = os.environ.get('LOGLEVEL', 'INFO').upper()
|
||||
|
||||
# Configure root logger
|
||||
logging.basicConfig(
|
||||
level=getattr(logging, LOGLEVEL, logging.INFO),
|
||||
format="%(asctime)s %(filename)s:%(lineno)d %(levelname)s %(message)s",
|
||||
datefmt="[%X]",
|
||||
handlers=[RichHandler(rich_tracebacks=True)]
|
||||
)
|
||||
|
||||
# Suppress specific noisy loggers
|
||||
logging.getLogger("litellm").setLevel(logging.WARNING)
|
||||
logging.getLogger("litellm.utils").setLevel(logging.WARNING)
|
||||
logging.getLogger("markdown_it").setLevel(logging.WARNING)
|
||||
logging.getLogger("rich.markdown").setLevel(logging.WARNING)
|
||||
logging.getLogger("httpx").setLevel(logging.WARNING)
|
||||
logging.getLogger("httpcore").setLevel(logging.WARNING)
|
||||
|
||||
from .agent.agent import Agent
|
||||
from .agent.image_agent import ImageAgent
|
||||
from .agents.agents import PraisonAIAgents
|
||||
|
||||
@@ -2,5 +2,6 @@
|
||||
from .agent import Agent
|
||||
from .image_agent import ImageAgent
|
||||
from .handoff import Handoff, handoff, handoff_filters, RECOMMENDED_PROMPT_PREFIX, prompt_with_handoff_instructions
|
||||
from .router_agent import RouterAgent
|
||||
|
||||
__all__ = ['Agent', 'ImageAgent', 'Handoff', 'handoff', 'handoff_filters', 'RECOMMENDED_PROMPT_PREFIX', 'prompt_with_handoff_instructions']
|
||||
__all__ = ['Agent', 'ImageAgent', 'Handoff', 'handoff', 'handoff_filters', 'RECOMMENDED_PROMPT_PREFIX', 'prompt_with_handoff_instructions', 'RouterAgent']
|
||||
@@ -27,7 +27,8 @@ from ..main import (
|
||||
display_self_reflection,
|
||||
ReflectionOutput,
|
||||
adisplay_instruction,
|
||||
approval_callback
|
||||
approval_callback,
|
||||
execute_sync_callback
|
||||
)
|
||||
import inspect
|
||||
import uuid
|
||||
@@ -354,8 +355,10 @@ class Agent:
|
||||
# Check for model name in environment variable if not provided
|
||||
self._using_custom_llm = False
|
||||
|
||||
# Initialize OpenAI client for direct API calls
|
||||
self._openai_client = get_openai_client(api_key=api_key, base_url=base_url)
|
||||
# Store OpenAI client parameters for lazy initialization
|
||||
self._openai_api_key = api_key
|
||||
self._openai_base_url = base_url
|
||||
self.__openai_client = None
|
||||
|
||||
# If base_url is provided, always create a custom LLM instance
|
||||
if base_url:
|
||||
@@ -422,7 +425,13 @@ class Agent:
|
||||
# Otherwise, fall back to OpenAI environment/name
|
||||
else:
|
||||
self.llm = llm or os.getenv('OPENAI_MODEL_NAME', 'gpt-4o')
|
||||
self.tools = tools if tools else [] # Store original tools
|
||||
# Handle tools parameter - ensure it's always a list
|
||||
if callable(tools):
|
||||
# If a single function/callable is passed, wrap it in a list
|
||||
self.tools = [tools]
|
||||
else:
|
||||
# Handle all falsy values (None, False, 0, "", etc.) by defaulting to empty list
|
||||
self.tools = tools or []
|
||||
self.function_calling_llm = function_calling_llm
|
||||
self.max_iter = max_iter
|
||||
self.max_rpm = max_rpm
|
||||
@@ -442,6 +451,8 @@ class Agent:
|
||||
self.embedder_config = embedder_config
|
||||
self.knowledge = knowledge
|
||||
self.use_system_prompt = use_system_prompt
|
||||
# NOTE: chat_history is not thread-safe. If concurrent access is needed,
|
||||
# consider using threading.Lock or other synchronization mechanisms
|
||||
self.chat_history = []
|
||||
self.markdown = markdown
|
||||
self.stream = stream
|
||||
@@ -488,6 +499,42 @@ Your Goal: {self.goal}
|
||||
for source in knowledge:
|
||||
self._process_knowledge(source)
|
||||
|
||||
@property
|
||||
def _openai_client(self):
|
||||
"""Lazily initialize OpenAI client only when needed."""
|
||||
if self.__openai_client is None:
|
||||
try:
|
||||
self.__openai_client = get_openai_client(
|
||||
api_key=self._openai_api_key,
|
||||
base_url=self._openai_base_url
|
||||
)
|
||||
except ValueError as e:
|
||||
# If we're using a custom LLM, we might not need the OpenAI client
|
||||
# Return None and let the calling code handle it
|
||||
if self._using_custom_llm:
|
||||
return None
|
||||
else:
|
||||
raise e
|
||||
return self.__openai_client
|
||||
|
||||
@property
|
||||
def llm_model(self):
|
||||
"""Unified property to get the LLM model regardless of configuration type.
|
||||
|
||||
Returns:
|
||||
The LLM model/instance being used by this agent.
|
||||
- For standard models: returns the model string (e.g., "gpt-4o")
|
||||
- For custom LLM instances: returns the LLM instance object
|
||||
- For provider models: returns the LLM instance object
|
||||
"""
|
||||
if hasattr(self, 'llm_instance') and self.llm_instance:
|
||||
return self.llm_instance
|
||||
elif hasattr(self, 'llm') and self.llm:
|
||||
return self.llm
|
||||
else:
|
||||
# Default fallback
|
||||
return "gpt-4o"
|
||||
|
||||
def _process_knowledge(self, knowledge_item):
|
||||
"""Process and store knowledge from a file path, URL, or string."""
|
||||
try:
|
||||
@@ -673,8 +720,55 @@ Your Goal: {self.goal}
|
||||
)
|
||||
|
||||
return current_response
|
||||
|
||||
def _build_system_prompt(self, tools=None):
|
||||
"""Build the system prompt with tool information.
|
||||
|
||||
Args:
|
||||
tools: Optional list of tools to use (defaults to self.tools)
|
||||
|
||||
Returns:
|
||||
str: The system prompt or None if use_system_prompt is False
|
||||
"""
|
||||
if not self.use_system_prompt:
|
||||
return None
|
||||
|
||||
system_prompt = f"""{self.backstory}\n
|
||||
Your Role: {self.role}\n
|
||||
Your Goal: {self.goal}"""
|
||||
|
||||
# Add tool usage instructions if tools are available
|
||||
# Use provided tools or fall back to self.tools
|
||||
tools_to_use = tools if tools is not None else self.tools
|
||||
if tools_to_use:
|
||||
tool_names = []
|
||||
for tool in tools_to_use:
|
||||
try:
|
||||
if callable(tool) and hasattr(tool, '__name__'):
|
||||
tool_names.append(tool.__name__)
|
||||
elif isinstance(tool, dict) and isinstance(tool.get('function'), dict) and 'name' in tool['function']:
|
||||
tool_names.append(tool['function']['name'])
|
||||
elif isinstance(tool, str):
|
||||
tool_names.append(tool)
|
||||
elif hasattr(tool, "to_openai_tool"):
|
||||
# Handle MCP tools
|
||||
openai_tools = tool.to_openai_tool()
|
||||
if isinstance(openai_tools, list):
|
||||
for t in openai_tools:
|
||||
if isinstance(t, dict) and 'function' in t and 'name' in t['function']:
|
||||
tool_names.append(t['function']['name'])
|
||||
elif isinstance(openai_tools, dict) and 'function' in openai_tools:
|
||||
tool_names.append(openai_tools['function']['name'])
|
||||
except (AttributeError, KeyError, TypeError) as e:
|
||||
logging.warning(f"Could not extract tool name from {tool}: {e}")
|
||||
continue
|
||||
|
||||
if tool_names:
|
||||
system_prompt += f"\n\nYou have access to the following tools: {', '.join(tool_names)}. Use these tools when appropriate to help complete your tasks. Always use tools when they can help provide accurate information or perform actions."
|
||||
|
||||
return system_prompt
|
||||
|
||||
def _build_messages(self, prompt, temperature=0.2, output_json=None, output_pydantic=None):
|
||||
def _build_messages(self, prompt, temperature=0.2, output_json=None, output_pydantic=None, tools=None):
|
||||
"""Build messages list for chat completion.
|
||||
|
||||
Args:
|
||||
@@ -682,26 +776,47 @@ Your Goal: {self.goal}
|
||||
temperature: Temperature for the chat
|
||||
output_json: Optional Pydantic model for JSON output
|
||||
output_pydantic: Optional Pydantic model for JSON output (alias)
|
||||
tools: Optional list of tools to use (defaults to self.tools)
|
||||
|
||||
Returns:
|
||||
tuple: (messages list, original prompt)
|
||||
"""
|
||||
# Build system prompt if enabled
|
||||
system_prompt = None
|
||||
if self.use_system_prompt:
|
||||
system_prompt = f"""{self.backstory}\n
|
||||
Your Role: {self.role}\n
|
||||
Your Goal: {self.goal}
|
||||
"""
|
||||
# Build system prompt using the helper method
|
||||
system_prompt = self._build_system_prompt(tools)
|
||||
|
||||
# Use openai_client's build_messages method
|
||||
messages, original_prompt = self._openai_client.build_messages(
|
||||
prompt=prompt,
|
||||
system_prompt=system_prompt,
|
||||
chat_history=self.chat_history,
|
||||
output_json=output_json,
|
||||
output_pydantic=output_pydantic
|
||||
)
|
||||
# Use openai_client's build_messages method if available
|
||||
if self._openai_client is not None:
|
||||
messages, original_prompt = self._openai_client.build_messages(
|
||||
prompt=prompt,
|
||||
system_prompt=system_prompt,
|
||||
chat_history=self.chat_history,
|
||||
output_json=output_json,
|
||||
output_pydantic=output_pydantic
|
||||
)
|
||||
else:
|
||||
# Fallback implementation for when OpenAI client is not available
|
||||
messages = []
|
||||
|
||||
# Add system message if provided
|
||||
if system_prompt:
|
||||
messages.append({"role": "system", "content": system_prompt})
|
||||
|
||||
# Add chat history
|
||||
messages.extend(self.chat_history)
|
||||
|
||||
# Add user prompt
|
||||
if isinstance(prompt, list):
|
||||
messages.extend(prompt)
|
||||
original_prompt = prompt
|
||||
else:
|
||||
messages.append({"role": "user", "content": str(prompt)})
|
||||
original_prompt = str(prompt)
|
||||
|
||||
# Add JSON format instruction if needed
|
||||
if output_json or output_pydantic:
|
||||
model = output_pydantic or output_json
|
||||
json_instruction = f"\nPlease respond with valid JSON matching this schema: {model.model_json_schema()}"
|
||||
messages[-1]["content"] += json_instruction
|
||||
|
||||
return messages, original_prompt
|
||||
|
||||
@@ -943,6 +1058,9 @@ Your Goal: {self.goal}
|
||||
|
||||
def _process_stream_response(self, messages, temperature, start_time, formatted_tools=None, reasoning_steps=False):
|
||||
"""Process streaming response and return final response"""
|
||||
if self._openai_client is None:
|
||||
raise ValueError("OpenAI client is not initialized. Please provide OPENAI_API_KEY or use a custom LLM provider.")
|
||||
|
||||
return self._openai_client.process_stream_response(
|
||||
messages=messages,
|
||||
model=self.llm,
|
||||
@@ -982,6 +1100,10 @@ Your Goal: {self.goal}
|
||||
execute_tool_fn=self.execute_tool,
|
||||
agent_name=self.name,
|
||||
agent_role=self.role,
|
||||
agent_tools=[t.__name__ for t in self.tools] if self.tools else None,
|
||||
task_name=task_name,
|
||||
task_description=task_description,
|
||||
task_id=task_id,
|
||||
reasoning_steps=reasoning_steps
|
||||
)
|
||||
else:
|
||||
@@ -998,6 +1120,10 @@ Your Goal: {self.goal}
|
||||
execute_tool_fn=self.execute_tool,
|
||||
agent_name=self.name,
|
||||
agent_role=self.role,
|
||||
agent_tools=[t.__name__ for t in self.tools] if self.tools else None,
|
||||
task_name=task_name,
|
||||
task_description=task_description,
|
||||
task_id=task_id,
|
||||
reasoning_steps=reasoning_steps
|
||||
)
|
||||
else:
|
||||
@@ -1009,6 +1135,9 @@ Your Goal: {self.goal}
|
||||
|
||||
# Note: openai_client expects tools in various formats and will format them internally
|
||||
# But since we already have formatted_tools, we can pass them directly
|
||||
if self._openai_client is None:
|
||||
raise ValueError("OpenAI client is not initialized. Please provide OPENAI_API_KEY or use a custom LLM provider.")
|
||||
|
||||
final_response = self._openai_client.chat_completion_with_tools(
|
||||
messages=messages,
|
||||
model=self.llm,
|
||||
@@ -1028,8 +1157,39 @@ Your Goal: {self.goal}
|
||||
except Exception as e:
|
||||
display_error(f"Error in chat completion: {e}")
|
||||
return None
|
||||
|
||||
def _execute_callback_and_display(self, prompt: str, response: str, generation_time: float):
|
||||
"""Helper method to execute callbacks and display interaction.
|
||||
|
||||
This centralizes the logic for callback execution and display to avoid duplication.
|
||||
"""
|
||||
# Always execute callbacks regardless of verbose setting (only when not using custom LLM)
|
||||
if not self._using_custom_llm:
|
||||
execute_sync_callback(
|
||||
'interaction',
|
||||
message=prompt,
|
||||
response=response,
|
||||
markdown=self.markdown,
|
||||
generation_time=generation_time,
|
||||
agent_name=self.name,
|
||||
agent_role=self.role,
|
||||
agent_tools=[t.__name__ for t in self.tools] if self.tools else None,
|
||||
task_name=None, # Not available in this context
|
||||
task_description=None, # Not available in this context
|
||||
task_id=None # Not available in this context
|
||||
)
|
||||
# Only display interaction if not using custom LLM (to avoid double output) and verbose is True
|
||||
if self.verbose and not self._using_custom_llm:
|
||||
display_interaction(prompt, response, markdown=self.markdown,
|
||||
generation_time=generation_time, console=self.console,
|
||||
agent_name=self.name,
|
||||
agent_role=self.role,
|
||||
agent_tools=[t.__name__ for t in self.tools] if self.tools else None,
|
||||
task_name=None, # Not available in this context
|
||||
task_description=None, # Not available in this context
|
||||
task_id=None) # Not available in this context
|
||||
|
||||
def chat(self, prompt, temperature=0.2, tools=None, output_json=None, output_pydantic=None, reasoning_steps=False, stream=True):
|
||||
def chat(self, prompt, temperature=0.2, tools=None, output_json=None, output_pydantic=None, reasoning_steps=False, stream=True, task_name=None, task_description=None, task_id=None):
|
||||
# Log all parameter values when in debug mode
|
||||
if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
|
||||
param_info = {
|
||||
@@ -1085,10 +1245,27 @@ Your Goal: {self.goal}
|
||||
tool_param = [openai_tool]
|
||||
logging.debug(f"Converted MCP tool: {tool_param}")
|
||||
|
||||
# Pass everything to LLM class
|
||||
response_text = self.llm_instance.get_response(
|
||||
# Store chat history length for potential rollback
|
||||
chat_history_length = len(self.chat_history)
|
||||
|
||||
# Normalize prompt content for consistent chat history storage
|
||||
normalized_content = prompt
|
||||
if isinstance(prompt, list):
|
||||
# Extract text from multimodal prompts
|
||||
normalized_content = next((item["text"] for item in prompt if item.get("type") == "text"), "")
|
||||
|
||||
# Prevent duplicate messages
|
||||
if not (self.chat_history and
|
||||
self.chat_history[-1].get("role") == "user" and
|
||||
self.chat_history[-1].get("content") == normalized_content):
|
||||
# Add user message to chat history BEFORE LLM call so handoffs can access it
|
||||
self.chat_history.append({"role": "user", "content": normalized_content})
|
||||
|
||||
try:
|
||||
# Pass everything to LLM class
|
||||
response_text = self.llm_instance.get_response(
|
||||
prompt=prompt,
|
||||
system_prompt=f"{self.backstory}\n\nYour Role: {self.role}\n\nYour Goal: {self.goal}" if self.use_system_prompt else None,
|
||||
system_prompt=self._build_system_prompt(tools),
|
||||
chat_history=self.chat_history,
|
||||
temperature=temperature,
|
||||
tools=tool_param,
|
||||
@@ -1103,24 +1280,34 @@ Your Goal: {self.goal}
|
||||
agent_name=self.name,
|
||||
agent_role=self.role,
|
||||
agent_tools=[t.__name__ if hasattr(t, '__name__') else str(t) for t in (tools if tools is not None else self.tools)],
|
||||
task_name=task_name,
|
||||
task_description=task_description,
|
||||
task_id=task_id,
|
||||
execute_tool_fn=self.execute_tool, # Pass tool execution function
|
||||
reasoning_steps=reasoning_steps
|
||||
)
|
||||
reasoning_steps=reasoning_steps,
|
||||
stream=stream # Pass the stream parameter from chat method
|
||||
)
|
||||
|
||||
self.chat_history.append({"role": "user", "content": prompt})
|
||||
self.chat_history.append({"role": "assistant", "content": response_text})
|
||||
self.chat_history.append({"role": "assistant", "content": response_text})
|
||||
|
||||
# Log completion time if in debug mode
|
||||
if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
|
||||
total_time = time.time() - start_time
|
||||
logging.debug(f"Agent.chat completed in {total_time:.2f} seconds")
|
||||
# Log completion time if in debug mode
|
||||
if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
|
||||
total_time = time.time() - start_time
|
||||
logging.debug(f"Agent.chat completed in {total_time:.2f} seconds")
|
||||
|
||||
# Apply guardrail validation for custom LLM response
|
||||
try:
|
||||
validated_response = self._apply_guardrail_with_retry(response_text, prompt, temperature, tools)
|
||||
return validated_response
|
||||
# Apply guardrail validation for custom LLM response
|
||||
try:
|
||||
validated_response = self._apply_guardrail_with_retry(response_text, prompt, temperature, tools)
|
||||
return validated_response
|
||||
except Exception as e:
|
||||
logging.error(f"Agent {self.name}: Guardrail validation failed for custom LLM: {e}")
|
||||
# Rollback chat history on guardrail failure
|
||||
self.chat_history = self.chat_history[:chat_history_length]
|
||||
return None
|
||||
except Exception as e:
|
||||
logging.error(f"Agent {self.name}: Guardrail validation failed for custom LLM: {e}")
|
||||
# Rollback chat history if LLM call fails
|
||||
self.chat_history = self.chat_history[:chat_history_length]
|
||||
display_error(f"Error in LLM chat: {e}")
|
||||
return None
|
||||
except Exception as e:
|
||||
display_error(f"Error in LLM chat: {e}")
|
||||
@@ -1128,156 +1315,214 @@ Your Goal: {self.goal}
|
||||
else:
|
||||
# Use the new _build_messages helper method
|
||||
messages, original_prompt = self._build_messages(prompt, temperature, output_json, output_pydantic)
|
||||
|
||||
# Store chat history length for potential rollback
|
||||
chat_history_length = len(self.chat_history)
|
||||
|
||||
# Normalize original_prompt for consistent chat history storage
|
||||
normalized_content = original_prompt
|
||||
if isinstance(original_prompt, list):
|
||||
# Extract text from multimodal prompts
|
||||
normalized_content = next((item["text"] for item in original_prompt if item.get("type") == "text"), "")
|
||||
|
||||
# Prevent duplicate messages
|
||||
if not (self.chat_history and
|
||||
self.chat_history[-1].get("role") == "user" and
|
||||
self.chat_history[-1].get("content") == normalized_content):
|
||||
# Add user message to chat history BEFORE LLM call so handoffs can access it
|
||||
self.chat_history.append({"role": "user", "content": normalized_content})
|
||||
|
||||
final_response_text = None
|
||||
reflection_count = 0
|
||||
start_time = time.time()
|
||||
|
||||
while True:
|
||||
try:
|
||||
if self.verbose:
|
||||
# Handle both string and list prompts for instruction display
|
||||
display_text = prompt
|
||||
if isinstance(prompt, list):
|
||||
# Extract text content from multimodal prompt
|
||||
display_text = next((item["text"] for item in prompt if item["type"] == "text"), "")
|
||||
|
||||
if display_text and str(display_text).strip():
|
||||
# Pass agent information to display_instruction
|
||||
agent_tools = [t.__name__ if hasattr(t, '__name__') else str(t) for t in self.tools]
|
||||
display_instruction(
|
||||
f"Agent {self.name} is processing prompt: {display_text}",
|
||||
console=self.console,
|
||||
agent_name=self.name,
|
||||
agent_role=self.role,
|
||||
agent_tools=agent_tools
|
||||
)
|
||||
|
||||
response = self._chat_completion(messages, temperature=temperature, tools=tools if tools else None, reasoning_steps=reasoning_steps, stream=self.stream)
|
||||
if not response:
|
||||
return None
|
||||
|
||||
response_text = response.choices[0].message.content.strip()
|
||||
|
||||
# Handle output_json or output_pydantic if specified
|
||||
if output_json or output_pydantic:
|
||||
# Add to chat history and return raw response
|
||||
self.chat_history.append({"role": "user", "content": original_prompt})
|
||||
self.chat_history.append({"role": "assistant", "content": response_text})
|
||||
|
||||
# Wrap entire while loop in try-except for rollback on any failure
|
||||
try:
|
||||
while True:
|
||||
try:
|
||||
if self.verbose:
|
||||
display_interaction(original_prompt, response_text, markdown=self.markdown,
|
||||
generation_time=time.time() - start_time, console=self.console)
|
||||
return response_text
|
||||
# Handle both string and list prompts for instruction display
|
||||
display_text = prompt
|
||||
if isinstance(prompt, list):
|
||||
# Extract text content from multimodal prompt
|
||||
display_text = next((item["text"] for item in prompt if item["type"] == "text"), "")
|
||||
|
||||
if display_text and str(display_text).strip():
|
||||
# Pass agent information to display_instruction
|
||||
agent_tools = [t.__name__ if hasattr(t, '__name__') else str(t) for t in self.tools]
|
||||
display_instruction(
|
||||
f"Agent {self.name} is processing prompt: {display_text}",
|
||||
console=self.console,
|
||||
agent_name=self.name,
|
||||
agent_role=self.role,
|
||||
agent_tools=agent_tools
|
||||
)
|
||||
|
||||
if not self.self_reflect:
|
||||
self.chat_history.append({"role": "user", "content": original_prompt})
|
||||
self.chat_history.append({"role": "assistant", "content": response_text})
|
||||
if self.verbose:
|
||||
logging.debug(f"Agent {self.name} final response: {response_text}")
|
||||
display_interaction(original_prompt, response_text, markdown=self.markdown, generation_time=time.time() - start_time, console=self.console)
|
||||
# Return only reasoning content if reasoning_steps is True
|
||||
if reasoning_steps and hasattr(response.choices[0].message, 'reasoning_content'):
|
||||
# Apply guardrail to reasoning content
|
||||
try:
|
||||
validated_reasoning = self._apply_guardrail_with_retry(response.choices[0].message.reasoning_content, original_prompt, temperature, tools)
|
||||
return validated_reasoning
|
||||
except Exception as e:
|
||||
logging.error(f"Agent {self.name}: Guardrail validation failed for reasoning content: {e}")
|
||||
return None
|
||||
# Apply guardrail to regular response
|
||||
try:
|
||||
validated_response = self._apply_guardrail_with_retry(response_text, original_prompt, temperature, tools)
|
||||
return validated_response
|
||||
except Exception as e:
|
||||
logging.error(f"Agent {self.name}: Guardrail validation failed: {e}")
|
||||
response = self._chat_completion(messages, temperature=temperature, tools=tools if tools else None, reasoning_steps=reasoning_steps, stream=self.stream)
|
||||
if not response:
|
||||
# Rollback chat history on response failure
|
||||
self.chat_history = self.chat_history[:chat_history_length]
|
||||
return None
|
||||
|
||||
reflection_prompt = f"""
|
||||
response_text = response.choices[0].message.content.strip()
|
||||
|
||||
# Handle output_json or output_pydantic if specified
|
||||
if output_json or output_pydantic:
|
||||
# Add to chat history and return raw response
|
||||
# User message already added before LLM call via _build_messages
|
||||
self.chat_history.append({"role": "assistant", "content": response_text})
|
||||
# Apply guardrail validation even for JSON output
|
||||
try:
|
||||
validated_response = self._apply_guardrail_with_retry(response_text, original_prompt, temperature, tools)
|
||||
# Execute callback after validation
|
||||
self._execute_callback_and_display(original_prompt, validated_response, time.time() - start_time)
|
||||
return validated_response
|
||||
except Exception as e:
|
||||
logging.error(f"Agent {self.name}: Guardrail validation failed for JSON output: {e}")
|
||||
# Rollback chat history on guardrail failure
|
||||
self.chat_history = self.chat_history[:chat_history_length]
|
||||
return None
|
||||
|
||||
if not self.self_reflect:
|
||||
# User message already added before LLM call via _build_messages
|
||||
self.chat_history.append({"role": "assistant", "content": response_text})
|
||||
if self.verbose:
|
||||
logging.debug(f"Agent {self.name} final response: {response_text}")
|
||||
# Return only reasoning content if reasoning_steps is True
|
||||
if reasoning_steps and hasattr(response.choices[0].message, 'reasoning_content'):
|
||||
# Apply guardrail to reasoning content
|
||||
try:
|
||||
validated_reasoning = self._apply_guardrail_with_retry(response.choices[0].message.reasoning_content, original_prompt, temperature, tools)
|
||||
# Execute callback after validation
|
||||
self._execute_callback_and_display(original_prompt, validated_reasoning, time.time() - start_time)
|
||||
return validated_reasoning
|
||||
except Exception as e:
|
||||
logging.error(f"Agent {self.name}: Guardrail validation failed for reasoning content: {e}")
|
||||
# Rollback chat history on guardrail failure
|
||||
self.chat_history = self.chat_history[:chat_history_length]
|
||||
return None
|
||||
# Apply guardrail to regular response
|
||||
try:
|
||||
validated_response = self._apply_guardrail_with_retry(response_text, original_prompt, temperature, tools)
|
||||
# Execute callback after validation
|
||||
self._execute_callback_and_display(original_prompt, validated_response, time.time() - start_time)
|
||||
return validated_response
|
||||
except Exception as e:
|
||||
logging.error(f"Agent {self.name}: Guardrail validation failed: {e}")
|
||||
# Rollback chat history on guardrail failure
|
||||
self.chat_history = self.chat_history[:chat_history_length]
|
||||
return None
|
||||
|
||||
reflection_prompt = f"""
|
||||
Reflect on your previous response: '{response_text}'.
|
||||
{self.reflect_prompt if self.reflect_prompt else "Identify any flaws, improvements, or actions."}
|
||||
Provide a "satisfactory" status ('yes' or 'no').
|
||||
Output MUST be JSON with 'reflection' and 'satisfactory'.
|
||||
"""
|
||||
logging.debug(f"{self.name} reflection attempt {reflection_count+1}, sending prompt: {reflection_prompt}")
|
||||
messages.append({"role": "user", "content": reflection_prompt})
|
||||
"""
|
||||
logging.debug(f"{self.name} reflection attempt {reflection_count+1}, sending prompt: {reflection_prompt}")
|
||||
messages.append({"role": "user", "content": reflection_prompt})
|
||||
|
||||
try:
|
||||
reflection_response = self._openai_client.sync_client.beta.chat.completions.parse(
|
||||
model=self.reflect_llm if self.reflect_llm else self.llm,
|
||||
messages=messages,
|
||||
temperature=temperature,
|
||||
response_format=ReflectionOutput
|
||||
)
|
||||
try:
|
||||
# Check if we're using a custom LLM (like Gemini)
|
||||
if self._using_custom_llm or self._openai_client is None:
|
||||
# For custom LLMs, we need to handle reflection differently
|
||||
# Use non-streaming to get complete JSON response
|
||||
reflection_response = self._chat_completion(messages, temperature=temperature, tools=None, stream=False, reasoning_steps=False)
|
||||
|
||||
if not reflection_response or not reflection_response.choices:
|
||||
raise Exception("No response from reflection request")
|
||||
|
||||
reflection_text = reflection_response.choices[0].message.content.strip()
|
||||
|
||||
# Clean the JSON output
|
||||
cleaned_json = self.clean_json_output(reflection_text)
|
||||
|
||||
# Parse the JSON manually
|
||||
reflection_data = json.loads(cleaned_json)
|
||||
|
||||
# Create a reflection output object manually
|
||||
class CustomReflectionOutput:
|
||||
def __init__(self, data):
|
||||
self.reflection = data.get('reflection', '')
|
||||
self.satisfactory = data.get('satisfactory', 'no').lower()
|
||||
|
||||
reflection_output = CustomReflectionOutput(reflection_data)
|
||||
else:
|
||||
# Use OpenAI's structured output for OpenAI models
|
||||
reflection_response = self._openai_client.sync_client.beta.chat.completions.parse(
|
||||
model=self.reflect_llm if self.reflect_llm else self.llm,
|
||||
messages=messages,
|
||||
temperature=temperature,
|
||||
response_format=ReflectionOutput
|
||||
)
|
||||
|
||||
reflection_output = reflection_response.choices[0].message.parsed
|
||||
reflection_output = reflection_response.choices[0].message.parsed
|
||||
|
||||
if self.verbose:
|
||||
display_self_reflection(f"Agent {self.name} self reflection (using {self.reflect_llm if self.reflect_llm else self.llm}): reflection='{reflection_output.reflection}' satisfactory='{reflection_output.satisfactory}'", console=self.console)
|
||||
|
||||
messages.append({"role": "assistant", "content": f"Self Reflection: {reflection_output.reflection} Satisfactory?: {reflection_output.satisfactory}"})
|
||||
|
||||
# Only consider satisfactory after minimum reflections
|
||||
if reflection_output.satisfactory == "yes" and reflection_count >= self.min_reflect - 1:
|
||||
if self.verbose:
|
||||
display_self_reflection("Agent marked the response as satisfactory after meeting minimum reflections", console=self.console)
|
||||
self.chat_history.append({"role": "user", "content": prompt})
|
||||
self.chat_history.append({"role": "assistant", "content": response_text})
|
||||
display_interaction(prompt, response_text, markdown=self.markdown, generation_time=time.time() - start_time, console=self.console)
|
||||
# Apply guardrail validation after satisfactory reflection
|
||||
try:
|
||||
validated_response = self._apply_guardrail_with_retry(response_text, prompt, temperature, tools)
|
||||
return validated_response
|
||||
except Exception as e:
|
||||
logging.error(f"Agent {self.name}: Guardrail validation failed after reflection: {e}")
|
||||
return None
|
||||
display_self_reflection(f"Agent {self.name} self reflection (using {self.reflect_llm if self.reflect_llm else self.llm}): reflection='{reflection_output.reflection}' satisfactory='{reflection_output.satisfactory}'", console=self.console)
|
||||
|
||||
# Check if we've hit max reflections
|
||||
if reflection_count >= self.max_reflect - 1:
|
||||
if self.verbose:
|
||||
display_self_reflection("Maximum reflection count reached, returning current response", console=self.console)
|
||||
self.chat_history.append({"role": "user", "content": prompt})
|
||||
self.chat_history.append({"role": "assistant", "content": response_text})
|
||||
display_interaction(prompt, response_text, markdown=self.markdown, generation_time=time.time() - start_time, console=self.console)
|
||||
# Apply guardrail validation after max reflections
|
||||
try:
|
||||
validated_response = self._apply_guardrail_with_retry(response_text, prompt, temperature, tools)
|
||||
return validated_response
|
||||
except Exception as e:
|
||||
logging.error(f"Agent {self.name}: Guardrail validation failed after max reflections: {e}")
|
||||
return None
|
||||
messages.append({"role": "assistant", "content": f"Self Reflection: {reflection_output.reflection} Satisfactory?: {reflection_output.satisfactory}"})
|
||||
|
||||
logging.debug(f"{self.name} reflection count {reflection_count + 1}, continuing reflection process")
|
||||
messages.append({"role": "user", "content": "Now regenerate your response using the reflection you made"})
|
||||
response = self._chat_completion(messages, temperature=temperature, tools=None, stream=self.stream)
|
||||
response_text = response.choices[0].message.content.strip()
|
||||
reflection_count += 1
|
||||
continue # Continue the loop for more reflections
|
||||
# Only consider satisfactory after minimum reflections
|
||||
if reflection_output.satisfactory == "yes" and reflection_count >= self.min_reflect - 1:
|
||||
if self.verbose:
|
||||
display_self_reflection("Agent marked the response as satisfactory after meeting minimum reflections", console=self.console)
|
||||
# User message already added before LLM call via _build_messages
|
||||
self.chat_history.append({"role": "assistant", "content": response_text})
|
||||
# Apply guardrail validation after satisfactory reflection
|
||||
try:
|
||||
validated_response = self._apply_guardrail_with_retry(response_text, original_prompt, temperature, tools)
|
||||
# Execute callback after validation
|
||||
self._execute_callback_and_display(original_prompt, validated_response, time.time() - start_time)
|
||||
return validated_response
|
||||
except Exception as e:
|
||||
logging.error(f"Agent {self.name}: Guardrail validation failed after reflection: {e}")
|
||||
# Rollback chat history on guardrail failure
|
||||
self.chat_history = self.chat_history[:chat_history_length]
|
||||
return None
|
||||
|
||||
except Exception as e:
|
||||
display_error(f"Error in parsing self-reflection json {e}. Retrying", console=self.console)
|
||||
logging.error("Reflection parsing failed.", exc_info=True)
|
||||
messages.append({"role": "assistant", "content": f"Self Reflection failed."})
|
||||
reflection_count += 1
|
||||
continue # Continue even after error to try again
|
||||
|
||||
except Exception as e:
|
||||
display_error(f"Error in chat: {e}", console=self.console)
|
||||
return None
|
||||
# Check if we've hit max reflections
|
||||
if reflection_count >= self.max_reflect - 1:
|
||||
if self.verbose:
|
||||
display_self_reflection("Maximum reflection count reached, returning current response", console=self.console)
|
||||
# User message already added before LLM call via _build_messages
|
||||
self.chat_history.append({"role": "assistant", "content": response_text})
|
||||
# Apply guardrail validation after max reflections
|
||||
try:
|
||||
validated_response = self._apply_guardrail_with_retry(response_text, original_prompt, temperature, tools)
|
||||
# Execute callback after validation
|
||||
self._execute_callback_and_display(original_prompt, validated_response, time.time() - start_time)
|
||||
return validated_response
|
||||
except Exception as e:
|
||||
logging.error(f"Agent {self.name}: Guardrail validation failed after max reflections: {e}")
|
||||
# Rollback chat history on guardrail failure
|
||||
self.chat_history = self.chat_history[:chat_history_length]
|
||||
return None
|
||||
|
||||
# If not satisfactory and not at max reflections, continue with regeneration
|
||||
logging.debug(f"{self.name} reflection count {reflection_count + 1}, continuing reflection process")
|
||||
messages.append({"role": "user", "content": "Now regenerate your response using the reflection you made"})
|
||||
# For custom LLMs during reflection, always use non-streaming to ensure complete responses
|
||||
use_stream = self.stream if not self._using_custom_llm else False
|
||||
response = self._chat_completion(messages, temperature=temperature, tools=None, stream=use_stream)
|
||||
response_text = response.choices[0].message.content.strip()
|
||||
reflection_count += 1
|
||||
continue # Continue the loop for more reflections
|
||||
|
||||
# Log completion time if in debug mode
|
||||
if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
|
||||
total_time = time.time() - start_time
|
||||
logging.debug(f"Agent.chat completed in {total_time:.2f} seconds")
|
||||
|
||||
# Apply guardrail validation before returning
|
||||
try:
|
||||
validated_response = self._apply_guardrail_with_retry(response_text, prompt, temperature, tools)
|
||||
return validated_response
|
||||
except Exception as e:
|
||||
logging.error(f"Agent {self.name}: Guardrail validation failed: {e}")
|
||||
if self.verbose:
|
||||
display_error(f"Guardrail validation failed: {e}", console=self.console)
|
||||
return None
|
||||
except Exception as e:
|
||||
display_error(f"Error in parsing self-reflection json {e}. Retrying", console=self.console)
|
||||
logging.error("Reflection parsing failed.", exc_info=True)
|
||||
messages.append({"role": "assistant", "content": "Self Reflection failed."})
|
||||
reflection_count += 1
|
||||
continue # Continue even after error to try again
|
||||
except Exception:
|
||||
# Catch any exception from the inner try block and re-raise to outer handler
|
||||
raise
|
||||
except Exception as e:
|
||||
# Catch any exceptions that escape the while loop
|
||||
display_error(f"Unexpected error in chat: {e}", console=self.console)
|
||||
# Rollback chat history
|
||||
self.chat_history = self.chat_history[:chat_history_length]
|
||||
return None
|
||||
|
||||
def clean_json_output(self, output: str) -> str:
|
||||
"""Clean and extract JSON from response text."""
|
||||
@@ -1326,10 +1571,26 @@ Output MUST be JSON with 'reflection' and 'satisfactory'.
|
||||
prompt = f"{prompt}\n\nKnowledge: {knowledge_content}"
|
||||
|
||||
if self._using_custom_llm:
|
||||
# Store chat history length for potential rollback
|
||||
chat_history_length = len(self.chat_history)
|
||||
|
||||
# Normalize prompt content for consistent chat history storage
|
||||
normalized_content = prompt
|
||||
if isinstance(prompt, list):
|
||||
# Extract text from multimodal prompts
|
||||
normalized_content = next((item["text"] for item in prompt if item.get("type") == "text"), "")
|
||||
|
||||
# Prevent duplicate messages
|
||||
if not (self.chat_history and
|
||||
self.chat_history[-1].get("role") == "user" and
|
||||
self.chat_history[-1].get("content") == normalized_content):
|
||||
# Add user message to chat history BEFORE LLM call so handoffs can access it
|
||||
self.chat_history.append({"role": "user", "content": normalized_content})
|
||||
|
||||
try:
|
||||
response_text = await self.llm_instance.get_response_async(
|
||||
prompt=prompt,
|
||||
system_prompt=f"{self.backstory}\n\nYour Role: {self.role}\n\nYour Goal: {self.goal}" if self.use_system_prompt else None,
|
||||
system_prompt=self._build_system_prompt(tools),
|
||||
chat_history=self.chat_history,
|
||||
temperature=temperature,
|
||||
tools=tools,
|
||||
@@ -1343,19 +1604,32 @@ Output MUST be JSON with 'reflection' and 'satisfactory'.
|
||||
console=self.console,
|
||||
agent_name=self.name,
|
||||
agent_role=self.role,
|
||||
agent_tools=[t.__name__ if hasattr(t, '__name__') else str(t) for t in self.tools],
|
||||
agent_tools=[t.__name__ if hasattr(t, '__name__') else str(t) for t in (tools if tools is not None else self.tools)],
|
||||
task_name=task_name,
|
||||
task_description=task_description,
|
||||
task_id=task_id,
|
||||
execute_tool_fn=self.execute_tool_async,
|
||||
reasoning_steps=reasoning_steps
|
||||
)
|
||||
|
||||
self.chat_history.append({"role": "user", "content": prompt})
|
||||
self.chat_history.append({"role": "assistant", "content": response_text})
|
||||
|
||||
if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
|
||||
total_time = time.time() - start_time
|
||||
logging.debug(f"Agent.achat completed in {total_time:.2f} seconds")
|
||||
return response_text
|
||||
|
||||
# Apply guardrail validation for custom LLM response
|
||||
try:
|
||||
validated_response = self._apply_guardrail_with_retry(response_text, prompt, temperature, tools)
|
||||
return validated_response
|
||||
except Exception as e:
|
||||
logging.error(f"Agent {self.name}: Guardrail validation failed for custom LLM: {e}")
|
||||
# Rollback chat history on guardrail failure
|
||||
self.chat_history = self.chat_history[:chat_history_length]
|
||||
return None
|
||||
except Exception as e:
|
||||
# Rollback chat history if LLM call fails
|
||||
self.chat_history = self.chat_history[:chat_history_length]
|
||||
display_error(f"Error in LLM chat: {e}")
|
||||
if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
|
||||
total_time = time.time() - start_time
|
||||
@@ -1365,6 +1639,22 @@ Output MUST be JSON with 'reflection' and 'satisfactory'.
|
||||
# For OpenAI client
|
||||
# Use the new _build_messages helper method
|
||||
messages, original_prompt = self._build_messages(prompt, temperature, output_json, output_pydantic)
|
||||
|
||||
# Store chat history length for potential rollback
|
||||
chat_history_length = len(self.chat_history)
|
||||
|
||||
# Normalize original_prompt for consistent chat history storage
|
||||
normalized_content = original_prompt
|
||||
if isinstance(original_prompt, list):
|
||||
# Extract text from multimodal prompts
|
||||
normalized_content = next((item["text"] for item in original_prompt if item.get("type") == "text"), "")
|
||||
|
||||
# Prevent duplicate messages
|
||||
if not (self.chat_history and
|
||||
self.chat_history[-1].get("role") == "user" and
|
||||
self.chat_history[-1].get("content") == normalized_content):
|
||||
# Add user message to chat history BEFORE LLM call so handoffs can access it
|
||||
self.chat_history.append({"role": "user", "content": normalized_content})
|
||||
|
||||
reflection_count = 0
|
||||
start_time = time.time()
|
||||
@@ -1388,6 +1678,12 @@ Output MUST be JSON with 'reflection' and 'satisfactory'.
|
||||
|
||||
# Use the new _format_tools_for_completion helper method
|
||||
formatted_tools = self._format_tools_for_completion(tools)
|
||||
|
||||
# Check if OpenAI client is available
|
||||
if self._openai_client is None:
|
||||
error_msg = "OpenAI client is not initialized. Please provide OPENAI_API_KEY or use a custom LLM provider."
|
||||
display_error(error_msg)
|
||||
return None
|
||||
|
||||
# Make the API call based on the type of request
|
||||
if tools:
|
||||
@@ -1442,6 +1738,19 @@ Output MUST be JSON with 'reflection' and 'satisfactory'.
|
||||
]
|
||||
|
||||
try:
|
||||
# Check if OpenAI client is available for self-reflection
|
||||
if self._openai_client is None:
|
||||
# For custom LLMs, self-reflection with structured output is not supported
|
||||
if self.verbose:
|
||||
display_self_reflection(f"Agent {self.name}: Self-reflection with structured output is not supported for custom LLM providers. Skipping reflection.", console=self.console)
|
||||
# Return the original response without reflection
|
||||
self.chat_history.append({"role": "user", "content": original_prompt})
|
||||
self.chat_history.append({"role": "assistant", "content": response_text})
|
||||
if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
|
||||
total_time = time.time() - start_time
|
||||
logging.debug(f"Agent.achat completed in {total_time:.2f} seconds")
|
||||
return response_text
|
||||
|
||||
reflection_response = await self._openai_client.async_client.beta.chat.completions.parse(
|
||||
model=self.reflect_llm if self.reflect_llm else self.llm,
|
||||
messages=reflection_messages,
|
||||
@@ -1492,7 +1801,16 @@ Output MUST be JSON with 'reflection' and 'satisfactory'.
|
||||
if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
|
||||
total_time = time.time() - start_time
|
||||
logging.debug(f"Agent.achat completed in {total_time:.2f} seconds")
|
||||
return response_text
|
||||
|
||||
# Apply guardrail validation for OpenAI client response
|
||||
try:
|
||||
validated_response = self._apply_guardrail_with_retry(response_text, original_prompt, temperature, tools)
|
||||
return validated_response
|
||||
except Exception as e:
|
||||
logging.error(f"Agent {self.name}: Guardrail validation failed for OpenAI client: {e}")
|
||||
# Rollback chat history on guardrail failure
|
||||
self.chat_history = self.chat_history[:chat_history_length]
|
||||
return None
|
||||
except Exception as e:
|
||||
display_error(f"Error in chat completion: {e}")
|
||||
if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
|
||||
@@ -1608,6 +1926,26 @@ Output MUST be JSON with 'reflection' and 'satisfactory'.
|
||||
"""Start the agent with a prompt. This is a convenience method that wraps chat()."""
|
||||
return self.chat(prompt, **kwargs)
|
||||
|
||||
def execute(self, task, context=None):
|
||||
"""Execute a task synchronously - backward compatibility method"""
|
||||
if hasattr(task, 'description'):
|
||||
prompt = task.description
|
||||
elif isinstance(task, str):
|
||||
prompt = task
|
||||
else:
|
||||
prompt = str(task)
|
||||
return self.chat(prompt)
|
||||
|
||||
async def aexecute(self, task, context=None):
|
||||
"""Execute a task asynchronously - backward compatibility method"""
|
||||
if hasattr(task, 'description'):
|
||||
prompt = task.description
|
||||
elif isinstance(task, str):
|
||||
prompt = task
|
||||
else:
|
||||
prompt = str(task)
|
||||
return await self.achat(prompt)
|
||||
|
||||
async def execute_tool_async(self, function_name: str, arguments: Dict[str, Any]) -> Any:
|
||||
"""Async version of execute_tool"""
|
||||
try:
|
||||
|
||||
@@ -144,8 +144,17 @@ class ImageAgent(Agent):
|
||||
config = self.image_config.dict(exclude_none=True)
|
||||
config.update(kwargs)
|
||||
|
||||
# Use llm parameter as the model
|
||||
config['model'] = self.llm
|
||||
# Get the model name robustly from the parent Agent's property
|
||||
model_info = self.llm_model
|
||||
model_name = model_info.model if hasattr(model_info, 'model') else str(model_info)
|
||||
|
||||
# Use the model name in config
|
||||
config['model'] = model_name
|
||||
|
||||
# Check if we're using a Gemini model and remove unsupported parameters
|
||||
if 'gemini' in model_name.lower():
|
||||
# Gemini models don't support response_format parameter
|
||||
config.pop('response_format', None)
|
||||
|
||||
with Progress(
|
||||
SpinnerColumn(),
|
||||
@@ -154,7 +163,7 @@ class ImageAgent(Agent):
|
||||
) as progress:
|
||||
try:
|
||||
# Add a task for image generation
|
||||
task = progress.add_task(f"[cyan]Generating image with {self.llm}...", total=None)
|
||||
task = progress.add_task(f"[cyan]Generating image with {model_name}...", total=None)
|
||||
|
||||
# Use litellm's image generation
|
||||
response = self.litellm(
|
||||
|
||||
@@ -0,0 +1,334 @@
|
||||
"""
|
||||
Router Agent that can use different LLM models based on task requirements.
|
||||
|
||||
This module extends the base Agent class to support multiple models and intelligent
|
||||
model selection based on task characteristics.
|
||||
"""
|
||||
|
||||
import os
|
||||
import logging
|
||||
from typing import Dict, List, Optional, Any, Union
|
||||
from .agent import Agent
|
||||
from ..llm.model_router import ModelRouter
|
||||
from ..llm import LLM
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class RouterAgent(Agent):
|
||||
"""
|
||||
An enhanced agent that can dynamically select and use different LLM models
|
||||
based on task requirements, optimizing for cost and performance.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
models: Optional[Union[List[str], Dict[str, Any]]] = None,
|
||||
model_router: Optional[ModelRouter] = None,
|
||||
routing_strategy: str = "auto", # "auto", "manual", "cost-optimized", "performance-optimized"
|
||||
primary_model: Optional[str] = None,
|
||||
fallback_model: Optional[str] = None,
|
||||
**kwargs
|
||||
):
|
||||
"""
|
||||
Initialize a RouterAgent.
|
||||
|
||||
Args:
|
||||
models: List of model names or dict mapping model names to configurations
|
||||
model_router: Custom ModelRouter instance for model selection
|
||||
routing_strategy: Strategy for model selection
|
||||
primary_model: Primary model to use (overrides routing for simple tasks)
|
||||
fallback_model: Fallback model if selected model fails
|
||||
**kwargs: Additional arguments passed to parent Agent class
|
||||
"""
|
||||
# Initialize model router
|
||||
self.model_router = model_router or ModelRouter()
|
||||
self.routing_strategy = routing_strategy
|
||||
self.fallback_model = fallback_model or os.getenv('OPENAI_MODEL_NAME', 'gpt-4o-mini')
|
||||
|
||||
# Process models configuration
|
||||
self.available_models = self._process_models_config(models)
|
||||
|
||||
# Set primary model for parent class initialization
|
||||
if primary_model:
|
||||
kwargs['llm'] = primary_model
|
||||
elif self.available_models:
|
||||
# Use the most cost-effective model as default
|
||||
cheapest_model = min(
|
||||
self.available_models.keys(),
|
||||
key=lambda m: self.model_router.get_model_info(m).cost_per_1k_tokens
|
||||
if self.model_router.get_model_info(m) else float('inf')
|
||||
)
|
||||
kwargs['llm'] = cheapest_model
|
||||
|
||||
# Store the original llm parameter for later use
|
||||
self._llm_config = kwargs.get('llm')
|
||||
|
||||
# Store api_key and base_url for LLM initialization
|
||||
self._base_url = kwargs.get('base_url')
|
||||
self._api_key = kwargs.get('api_key')
|
||||
|
||||
# Initialize parent Agent class
|
||||
super().__init__(**kwargs)
|
||||
|
||||
# Initialize LLM instances for each model
|
||||
self._llm_instances: Dict[str, LLM] = {}
|
||||
self._initialize_llm_instances()
|
||||
|
||||
# Track usage statistics
|
||||
self.model_usage_stats = {model: {'calls': 0, 'tokens': 0, 'cost': 0.0}
|
||||
for model in self.available_models}
|
||||
|
||||
def _process_models_config(self, models: Optional[Union[List[str], Dict[str, Any]]]) -> Dict[str, Any]:
|
||||
"""Process the models configuration into a standardized format."""
|
||||
if not models:
|
||||
# Use default models from router
|
||||
return {m.name: {} for m in self.model_router.models}
|
||||
|
||||
if isinstance(models, list):
|
||||
# Simple list of model names
|
||||
return {model: {} for model in models}
|
||||
|
||||
# Already a dict with model configurations
|
||||
return models
|
||||
|
||||
def _initialize_llm_instances(self):
|
||||
"""Initialize LLM instances for each available model."""
|
||||
base_url = self._base_url
|
||||
api_key = self._api_key
|
||||
|
||||
for model_name, config in self.available_models.items():
|
||||
try:
|
||||
# Merge base configuration with model-specific config
|
||||
llm_config = {
|
||||
'model': model_name,
|
||||
'base_url': config.get('base_url', base_url),
|
||||
'api_key': config.get('api_key', api_key),
|
||||
'verbose': self.verbose,
|
||||
'markdown': self.markdown,
|
||||
'stream': self.stream
|
||||
}
|
||||
|
||||
# Add any model-specific parameters
|
||||
llm_config.update(config)
|
||||
|
||||
# Create LLM instance
|
||||
self._llm_instances[model_name] = LLM(**llm_config)
|
||||
logger.debug(f"Initialized LLM instance for model: {model_name}")
|
||||
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to initialize LLM for model {model_name}: {e}")
|
||||
|
||||
def _select_model_for_task(
|
||||
self,
|
||||
task_description: str,
|
||||
tools: Optional[List[Any]] = None,
|
||||
context_size: Optional[int] = None
|
||||
) -> str:
|
||||
"""
|
||||
Select the most appropriate model for a given task.
|
||||
|
||||
Args:
|
||||
task_description: Description of the task
|
||||
tools: Tools required for the task
|
||||
context_size: Estimated context size
|
||||
|
||||
Returns:
|
||||
Selected model name
|
||||
"""
|
||||
if self.routing_strategy == "manual":
|
||||
# Use the configured primary model from llm_model property
|
||||
llm_model = self.llm_model
|
||||
if hasattr(llm_model, 'model'):
|
||||
# If it's an LLM instance, get the model name
|
||||
return llm_model.model
|
||||
elif isinstance(llm_model, str):
|
||||
# If it's a string, use it directly
|
||||
return llm_model
|
||||
# Fallback if no model is configured
|
||||
return self.fallback_model
|
||||
|
||||
# Determine required capabilities
|
||||
required_capabilities = []
|
||||
if tools:
|
||||
required_capabilities.append("function-calling")
|
||||
|
||||
# Determine budget consciousness based on strategy
|
||||
budget_conscious = self.routing_strategy in ["auto", "cost-optimized"]
|
||||
|
||||
# Get tool names for analysis
|
||||
tool_names = []
|
||||
if tools:
|
||||
tool_names = [t.__name__ if hasattr(t, '__name__') else str(t) for t in tools]
|
||||
|
||||
# Use router to select model
|
||||
selected_model = self.model_router.select_model(
|
||||
task_description=task_description,
|
||||
required_capabilities=required_capabilities,
|
||||
tools_required=tool_names,
|
||||
context_size=context_size,
|
||||
budget_conscious=budget_conscious
|
||||
)
|
||||
|
||||
# Ensure selected model is available
|
||||
if selected_model not in self._llm_instances:
|
||||
logger.warning(f"Selected model {selected_model} not available, using fallback")
|
||||
return self.fallback_model
|
||||
|
||||
return selected_model
|
||||
|
||||
def _execute_with_model(
|
||||
self,
|
||||
model_name: str,
|
||||
prompt: str,
|
||||
context: Optional[str] = None,
|
||||
tools: Optional[List[Any]] = None,
|
||||
**kwargs
|
||||
) -> str:
|
||||
"""
|
||||
Execute a task with a specific model.
|
||||
|
||||
Args:
|
||||
model_name: Name of the model to use
|
||||
prompt: The prompt to send to the model
|
||||
context: Additional context
|
||||
tools: Tools to make available
|
||||
**kwargs: Additional arguments for the LLM
|
||||
|
||||
Returns:
|
||||
Model response
|
||||
"""
|
||||
llm_instance = self._llm_instances.get(model_name)
|
||||
if not llm_instance:
|
||||
logger.error(f"Model {model_name} not initialized, using fallback")
|
||||
llm_instance = self._llm_instances.get(self.fallback_model)
|
||||
model_name = self.fallback_model
|
||||
|
||||
if not llm_instance:
|
||||
raise ValueError("No LLM instance available for execution")
|
||||
|
||||
# Prepare the full prompt
|
||||
full_prompt = prompt
|
||||
if context:
|
||||
full_prompt = f"{context}\n\n{prompt}"
|
||||
|
||||
try:
|
||||
# Execute with the selected model
|
||||
response = llm_instance.get_response(
|
||||
prompt=full_prompt,
|
||||
system_prompt=self._build_system_prompt(),
|
||||
tools=tools,
|
||||
verbose=self.verbose,
|
||||
markdown=self.markdown,
|
||||
stream=self.stream,
|
||||
agent_name=self.name,
|
||||
agent_role=self.role,
|
||||
agent_tools=[t.__name__ if hasattr(t, '__name__') else str(t) for t in (tools or [])],
|
||||
execute_tool_fn=self.execute_tool if tools else None,
|
||||
**kwargs
|
||||
)
|
||||
|
||||
# Update usage statistics
|
||||
self.model_usage_stats[model_name]['calls'] += 1
|
||||
|
||||
# TODO: Implement token tracking when LLM.get_response() is updated to return token usage
|
||||
# The LLM response currently returns only text, but litellm provides usage info in:
|
||||
# response.get("usage") with prompt_tokens, completion_tokens, and total_tokens
|
||||
# This would require modifying the LLM class to return both text and metadata
|
||||
|
||||
return response
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error executing with model {model_name}: {e}")
|
||||
|
||||
# Try fallback model if different
|
||||
if model_name != self.fallback_model and self.fallback_model in self._llm_instances:
|
||||
logger.info(f"Attempting with fallback model: {self.fallback_model}")
|
||||
return self._execute_with_model(
|
||||
self.fallback_model, prompt, context, tools, **kwargs
|
||||
)
|
||||
|
||||
raise
|
||||
|
||||
def execute(
|
||||
self,
|
||||
task_description: str,
|
||||
context: Optional[str] = None,
|
||||
tools: Optional[List[Any]] = None,
|
||||
**kwargs
|
||||
) -> str:
|
||||
"""
|
||||
Execute a task with automatic model selection.
|
||||
|
||||
This method overrides the parent Agent's execute method to add
|
||||
intelligent model selection.
|
||||
|
||||
Args:
|
||||
task_description: Description of the task to execute
|
||||
context: Optional context for the task
|
||||
tools: Optional tools to use
|
||||
**kwargs: Additional arguments
|
||||
|
||||
Returns:
|
||||
Task execution result
|
||||
"""
|
||||
# Estimate context size in tokens (rough estimate: ~4 chars per token)
|
||||
# This is a simplified heuristic; actual tokenization varies by model
|
||||
text_length = len(task_description) + (len(context) if context else 0)
|
||||
context_size = text_length // 4 # Approximate token count
|
||||
|
||||
# Select the best model for this task
|
||||
selected_model = self._select_model_for_task(
|
||||
task_description=task_description,
|
||||
tools=tools,
|
||||
context_size=context_size
|
||||
)
|
||||
|
||||
logger.info(f"RouterAgent '{self.name}' selected model: {selected_model} for task")
|
||||
|
||||
# Execute with the selected model
|
||||
return self._execute_with_model(
|
||||
model_name=selected_model,
|
||||
prompt=task_description,
|
||||
context=context,
|
||||
tools=tools,
|
||||
**kwargs
|
||||
)
|
||||
|
||||
def get_usage_report(self) -> Dict[str, Any]:
|
||||
"""
|
||||
Get a report of model usage statistics.
|
||||
|
||||
Returns:
|
||||
Dictionary containing usage statistics and cost estimates
|
||||
"""
|
||||
total_cost = 0.0
|
||||
report = {
|
||||
'agent_name': self.name,
|
||||
'routing_strategy': self.routing_strategy,
|
||||
'model_usage': {}
|
||||
}
|
||||
|
||||
for model, stats in self.model_usage_stats.items():
|
||||
model_info = self.model_router.get_model_info(model)
|
||||
if model_info and stats['tokens'] > 0:
|
||||
cost = self.model_router.estimate_cost(model, stats['tokens'])
|
||||
stats['cost'] = cost
|
||||
total_cost += cost
|
||||
|
||||
report['model_usage'][model] = stats
|
||||
|
||||
report['total_cost_estimate'] = total_cost
|
||||
report['total_calls'] = sum(s['calls'] for s in self.model_usage_stats.values())
|
||||
|
||||
return report
|
||||
|
||||
def _build_system_prompt(self) -> str:
|
||||
"""Build system prompt (inherited from parent but can be customized)."""
|
||||
base_prompt = super()._build_system_prompt()
|
||||
|
||||
# Add multi-model context if needed
|
||||
if self.routing_strategy == "auto":
|
||||
base_prompt += "\n\nNote: You are part of a multi-model system. Focus on your specific task."
|
||||
|
||||
return base_prompt
|
||||
@@ -7,7 +7,7 @@ from pydantic import BaseModel
|
||||
from rich.text import Text
|
||||
from rich.panel import Panel
|
||||
from rich.console import Console
|
||||
from ..main import display_error, TaskOutput, error_logs, client
|
||||
from ..main import display_error, TaskOutput, error_logs
|
||||
from ..agent.agent import Agent
|
||||
from ..task.task import Task
|
||||
from ..process.process import Process, LoopItems
|
||||
@@ -480,31 +480,46 @@ Context:
|
||||
)
|
||||
|
||||
if self.process == "workflow":
|
||||
# Collect all tasks that should run in parallel
|
||||
parallel_tasks = []
|
||||
tasks_to_run = []
|
||||
async for task_id in process.aworkflow():
|
||||
if self.tasks[task_id].async_execution and self.tasks[task_id].is_start:
|
||||
parallel_tasks.append(task_id)
|
||||
elif parallel_tasks:
|
||||
# Execute collected parallel tasks
|
||||
await asyncio.gather(*[self.arun_task(t) for t in parallel_tasks])
|
||||
parallel_tasks = []
|
||||
# Run the current non-parallel task
|
||||
if self.tasks[task_id].async_execution:
|
||||
await self.arun_task(task_id)
|
||||
else:
|
||||
self.run_task(task_id)
|
||||
|
||||
# Execute any remaining parallel tasks
|
||||
if parallel_tasks:
|
||||
await asyncio.gather(*[self.arun_task(t) for t in parallel_tasks])
|
||||
if self.tasks[task_id].async_execution:
|
||||
tasks_to_run.append(self.arun_task(task_id))
|
||||
else:
|
||||
# If we encounter a sync task, we must wait for the previous async tasks to finish.
|
||||
if tasks_to_run:
|
||||
await asyncio.gather(*tasks_to_run)
|
||||
tasks_to_run = []
|
||||
|
||||
# Run sync task in an executor to avoid blocking the event loop
|
||||
loop = asyncio.get_running_loop()
|
||||
await loop.run_in_executor(None, self.run_task, task_id)
|
||||
|
||||
if tasks_to_run:
|
||||
await asyncio.gather(*tasks_to_run)
|
||||
|
||||
elif self.process == "sequential":
|
||||
async_tasks_to_run = []
|
||||
|
||||
async def flush_async_tasks():
|
||||
"""Execute all pending async tasks"""
|
||||
nonlocal async_tasks_to_run
|
||||
if async_tasks_to_run:
|
||||
await asyncio.gather(*async_tasks_to_run)
|
||||
async_tasks_to_run = []
|
||||
|
||||
async for task_id in process.asequential():
|
||||
if self.tasks[task_id].async_execution:
|
||||
await self.arun_task(task_id)
|
||||
# Collect async tasks to run in parallel
|
||||
async_tasks_to_run.append(self.arun_task(task_id))
|
||||
else:
|
||||
self.run_task(task_id)
|
||||
# Before running a sync task, execute all pending async tasks
|
||||
await flush_async_tasks()
|
||||
# Run sync task in an executor to avoid blocking the event loop
|
||||
loop = asyncio.get_running_loop()
|
||||
await loop.run_in_executor(None, self.run_task, task_id)
|
||||
|
||||
# Execute any remaining async tasks at the end
|
||||
await flush_async_tasks()
|
||||
elif self.process == "hierarchical":
|
||||
async for task_id in process.ahierarchical():
|
||||
if isinstance(task_id, Task):
|
||||
@@ -512,7 +527,9 @@ Context:
|
||||
if self.tasks[task_id].async_execution:
|
||||
await self.arun_task(task_id)
|
||||
else:
|
||||
self.run_task(task_id)
|
||||
# Run sync task in an executor to avoid blocking the event loop
|
||||
loop = asyncio.get_running_loop()
|
||||
await loop.run_in_executor(None, self.run_task, task_id)
|
||||
|
||||
async def astart(self, content=None, return_dict=False, **kwargs):
|
||||
"""Async version of start method
|
||||
@@ -672,7 +689,10 @@ Context:
|
||||
_get_multimodal_message(task_prompt, task.images),
|
||||
tools=task.tools,
|
||||
output_json=task.output_json,
|
||||
output_pydantic=task.output_pydantic
|
||||
output_pydantic=task.output_pydantic,
|
||||
task_name=task.name,
|
||||
task_description=task.description,
|
||||
task_id=task_id
|
||||
)
|
||||
else:
|
||||
agent_output = executor_agent.chat(
|
||||
@@ -681,6 +701,9 @@ Context:
|
||||
output_json=task.output_json,
|
||||
output_pydantic=task.output_pydantic,
|
||||
stream=self.stream,
|
||||
task_name=task.name,
|
||||
task_description=task.description,
|
||||
task_id=task_id
|
||||
)
|
||||
|
||||
if agent_output:
|
||||
@@ -1118,7 +1141,7 @@ Context:
|
||||
response = await agent_instance.achat(current_input)
|
||||
else:
|
||||
# Run sync function in a thread to avoid blocking
|
||||
loop = asyncio.get_event_loop()
|
||||
loop = asyncio.get_running_loop()
|
||||
# Correctly pass current_input to the lambda for closure
|
||||
response = await loop.run_in_executor(None, lambda ci=current_input: agent_instance.chat(ci))
|
||||
|
||||
@@ -1273,7 +1296,7 @@ Context:
|
||||
if hasattr(agent_instance, 'achat') and asyncio.iscoroutinefunction(agent_instance.achat):
|
||||
response = await agent_instance.achat(current_input, tools=agent_instance.tools)
|
||||
elif hasattr(agent_instance, 'chat'): # Fallback to sync chat if achat not suitable
|
||||
loop = asyncio.get_event_loop()
|
||||
loop = asyncio.get_running_loop()
|
||||
response = await loop.run_in_executor(None, lambda ci=current_input: agent_instance.chat(ci, tools=agent_instance.tools))
|
||||
else:
|
||||
logging.warning(f"Agent {agent_instance.name} has no suitable chat or achat method.")
|
||||
|
||||
@@ -12,7 +12,9 @@ from typing import List, Any, Optional, Dict, Tuple
|
||||
import logging
|
||||
import os
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
from ..main import display_instruction, display_tool_call, display_interaction, client
|
||||
from ..main import display_instruction, display_tool_call, display_interaction
|
||||
from ..llm import get_openai_client, LLM, OpenAIClient
|
||||
import json
|
||||
|
||||
# Define Pydantic models for structured output
|
||||
class TaskConfig(BaseModel):
|
||||
@@ -107,6 +109,8 @@ class AutoAgents(PraisonAIAgents):
|
||||
self.max_execution_time = max_execution_time
|
||||
self.max_iter = max_iter
|
||||
self.reflect_llm = reflect_llm
|
||||
self.base_url = base_url
|
||||
self.api_key = api_key
|
||||
|
||||
# Display initial instruction
|
||||
if self.verbose:
|
||||
@@ -132,7 +136,7 @@ class AutoAgents(PraisonAIAgents):
|
||||
completion_checker=completion_checker,
|
||||
max_retries=max_retries,
|
||||
process=process,
|
||||
manager_llm=manager_llm
|
||||
manager_llm=manager_llm or self.llm
|
||||
)
|
||||
|
||||
def _display_agents_and_tasks(self, agents: List[Agent], tasks: List[Task]):
|
||||
@@ -210,9 +214,37 @@ Tools: {', '.join(agent_tools)}"""
|
||||
|
||||
return assigned_tools
|
||||
|
||||
def _validate_config(self, config: AutoAgentsConfig) -> tuple[bool, str]:
|
||||
"""
|
||||
Validate that the configuration has proper TaskConfig objects.
|
||||
|
||||
Returns:
|
||||
Tuple of (is_valid, error_message)
|
||||
"""
|
||||
for agent_idx, agent in enumerate(config.agents):
|
||||
if not hasattr(agent, 'tasks') or not agent.tasks:
|
||||
return False, f"Agent '{agent.name}' has no tasks defined"
|
||||
|
||||
for task_idx, task in enumerate(agent.tasks):
|
||||
# Check if task is a proper TaskConfig instance
|
||||
if not isinstance(task, TaskConfig):
|
||||
return False, f"Task at index {task_idx} for agent '{agent.name}' is not a proper TaskConfig object"
|
||||
|
||||
# Check required fields
|
||||
if not task.name:
|
||||
return False, f"Task at index {task_idx} for agent '{agent.name}' has no name"
|
||||
if not task.description:
|
||||
return False, f"Task at index {task_idx} for agent '{agent.name}' has no description"
|
||||
if not task.expected_output:
|
||||
return False, f"Task at index {task_idx} for agent '{agent.name}' has no expected_output"
|
||||
if task.tools is None:
|
||||
return False, f"Task at index {task_idx} for agent '{agent.name}' has no tools field"
|
||||
|
||||
return True, ""
|
||||
|
||||
def _generate_config(self) -> AutoAgentsConfig:
|
||||
"""Generate the configuration for agents and tasks"""
|
||||
prompt = f"""
|
||||
"""Generate the configuration for agents and tasks with retry logic"""
|
||||
base_prompt = f"""
|
||||
Generate a configuration for AI agents to accomplish this task: "{self.instructions}"
|
||||
|
||||
The configuration should include:
|
||||
@@ -233,29 +265,161 @@ Requirements:
|
||||
4. The process type should match the task requirements
|
||||
5. Generate maximum {self.max_agents} agents to handle this task efficiently
|
||||
|
||||
Return the configuration in a structured JSON format matching the AutoAgentsConfig schema.
|
||||
Return the configuration in a structured JSON format matching this exact schema:
|
||||
{{
|
||||
"main_instruction": "Overall goal description",
|
||||
"process_type": "sequential|workflow|hierarchical",
|
||||
"agents": [
|
||||
{{
|
||||
"name": "Agent Name",
|
||||
"role": "Agent Role",
|
||||
"goal": "Agent Goal",
|
||||
"backstory": "Agent Backstory",
|
||||
"tools": ["tool1", "tool2"],
|
||||
"tasks": [
|
||||
{{
|
||||
"name": "Task Name",
|
||||
"description": "Detailed task description",
|
||||
"expected_output": "What the task should produce",
|
||||
"tools": ["tool1", "tool2"]
|
||||
}}
|
||||
]
|
||||
}}
|
||||
]
|
||||
}}
|
||||
|
||||
IMPORTANT: Each task MUST be an object with name, description, expected_output, and tools fields, NOT a simple string.
|
||||
"""
|
||||
|
||||
try:
|
||||
response = client.beta.chat.completions.parse(
|
||||
model=self.llm,
|
||||
response_format=AutoAgentsConfig,
|
||||
messages=[
|
||||
{"role": "system", "content": "You are a helpful assistant designed to generate AI agent configurations."},
|
||||
{"role": "user", "content": prompt}
|
||||
]
|
||||
)
|
||||
max_retries = 3
|
||||
last_response = None
|
||||
last_error = None
|
||||
|
||||
for attempt in range(max_retries):
|
||||
# Initialize variables for this attempt
|
||||
use_openai_structured = False
|
||||
client = None
|
||||
|
||||
# Ensure we have exactly max_agents number of agents
|
||||
if len(response.choices[0].message.parsed.agents) > self.max_agents:
|
||||
response.choices[0].message.parsed.agents = response.choices[0].message.parsed.agents[:self.max_agents]
|
||||
elif len(response.choices[0].message.parsed.agents) < self.max_agents:
|
||||
logging.warning(f"Generated {len(response.choices[0].message.parsed.agents)} agents, expected {self.max_agents}")
|
||||
# Prepare prompt for this attempt
|
||||
if attempt > 0 and last_response and last_error:
|
||||
# On retry, include the previous response and error
|
||||
prompt = f"""{base_prompt}
|
||||
|
||||
PREVIOUS ATTEMPT FAILED!
|
||||
Your previous response was:
|
||||
```json
|
||||
{last_response}
|
||||
```
|
||||
|
||||
Error: {last_error}
|
||||
|
||||
REMEMBER: Tasks MUST be objects with the following structure:
|
||||
{{
|
||||
"name": "Task Name",
|
||||
"description": "Task Description",
|
||||
"expected_output": "Expected Output",
|
||||
"tools": ["tool1", "tool2"]
|
||||
}}
|
||||
|
||||
DO NOT use strings for tasks. Each task MUST be a complete object with all four fields."""
|
||||
else:
|
||||
prompt = base_prompt
|
||||
|
||||
return response.choices[0].message.parsed
|
||||
except Exception as e:
|
||||
logging.error(f"Error generating configuration: {e}")
|
||||
raise
|
||||
try:
|
||||
# Check if we have OpenAI API and the model supports structured output
|
||||
from ..llm import supports_structured_outputs
|
||||
if self.llm and supports_structured_outputs(self.llm):
|
||||
client = get_openai_client()
|
||||
use_openai_structured = True
|
||||
except:
|
||||
# If OpenAI client is not available, we'll use the LLM class
|
||||
pass
|
||||
|
||||
try:
|
||||
if use_openai_structured and client:
|
||||
# Use OpenAI's structured output for OpenAI models (backward compatibility)
|
||||
config = client.parse_structured_output(
|
||||
messages=[
|
||||
{"role": "system", "content": "You are a helpful assistant designed to generate AI agent configurations."},
|
||||
{"role": "user", "content": prompt}
|
||||
],
|
||||
response_format=AutoAgentsConfig,
|
||||
model=self.llm
|
||||
)
|
||||
# Store the response for potential retry
|
||||
last_response = json.dumps(config.model_dump(), indent=2)
|
||||
else:
|
||||
# Use LLM class for all other providers (Gemini, Anthropic, etc.)
|
||||
llm_instance = LLM(
|
||||
model=self.llm,
|
||||
base_url=self.base_url,
|
||||
api_key=self.api_key
|
||||
)
|
||||
|
||||
response_text = llm_instance.get_response(
|
||||
prompt=prompt,
|
||||
system_prompt="You are a helpful assistant designed to generate AI agent configurations.",
|
||||
output_pydantic=AutoAgentsConfig,
|
||||
temperature=0.7,
|
||||
stream=False,
|
||||
verbose=False
|
||||
)
|
||||
|
||||
# Store the raw response for potential retry
|
||||
last_response = response_text
|
||||
|
||||
# Parse the JSON response
|
||||
try:
|
||||
# First try to parse as is
|
||||
config_dict = json.loads(response_text)
|
||||
config = AutoAgentsConfig(**config_dict)
|
||||
except json.JSONDecodeError:
|
||||
# If that fails, try to extract JSON from the response
|
||||
# Handle cases where the model might wrap JSON in markdown blocks
|
||||
cleaned_response = response_text.strip()
|
||||
if cleaned_response.startswith("```json"):
|
||||
cleaned_response = cleaned_response[7:]
|
||||
if cleaned_response.startswith("```"):
|
||||
cleaned_response = cleaned_response[3:]
|
||||
if cleaned_response.endswith("```"):
|
||||
cleaned_response = cleaned_response[:-3]
|
||||
cleaned_response = cleaned_response.strip()
|
||||
|
||||
config_dict = json.loads(cleaned_response)
|
||||
config = AutoAgentsConfig(**config_dict)
|
||||
|
||||
# Validate the configuration
|
||||
is_valid, error_msg = self._validate_config(config)
|
||||
if not is_valid:
|
||||
last_error = error_msg
|
||||
if attempt < max_retries - 1:
|
||||
logging.warning(f"Configuration validation failed (attempt {attempt + 1}/{max_retries}): {error_msg}")
|
||||
continue
|
||||
else:
|
||||
raise ValueError(f"Configuration validation failed after {max_retries} attempts: {error_msg}")
|
||||
|
||||
# Ensure we have exactly max_agents number of agents
|
||||
if len(config.agents) > self.max_agents:
|
||||
config.agents = config.agents[:self.max_agents]
|
||||
elif len(config.agents) < self.max_agents:
|
||||
logging.warning(f"Generated {len(config.agents)} agents, expected {self.max_agents}")
|
||||
|
||||
return config
|
||||
|
||||
except ValueError as e:
|
||||
# Re-raise validation errors
|
||||
raise
|
||||
except Exception as e:
|
||||
last_error = str(e)
|
||||
if attempt < max_retries - 1:
|
||||
logging.warning(f"Error generating configuration (attempt {attempt + 1}/{max_retries}): {e}")
|
||||
continue
|
||||
else:
|
||||
logging.error(f"Error generating configuration after {max_retries} attempts: {e}")
|
||||
raise
|
||||
|
||||
# This should never be reached due to the raise statements above
|
||||
raise RuntimeError(f"Failed to generate valid configuration after {max_retries} attempts")
|
||||
|
||||
def _create_agents_and_tasks(self, config: AutoAgentsConfig) -> Tuple[List[Agent], List[Task]]:
|
||||
"""Create agents and tasks from configuration"""
|
||||
@@ -296,7 +460,9 @@ Return the configuration in a structured JSON format matching the AutoAgentsConf
|
||||
max_rpm=self.max_rpm,
|
||||
max_execution_time=self.max_execution_time,
|
||||
max_iter=self.max_iter,
|
||||
reflect_llm=self.reflect_llm
|
||||
reflect_llm=self.reflect_llm,
|
||||
base_url=self.base_url,
|
||||
api_key=self.api_key
|
||||
)
|
||||
agents.append(agent)
|
||||
|
||||
@@ -334,4 +500,4 @@ Return the configuration in a structured JSON format matching the AutoAgentsConf
|
||||
Creates tasks based on the instructions, then starts execution.
|
||||
Returns the task status and results dictionary.
|
||||
"""
|
||||
return super().start()
|
||||
return super().start()
|
||||
@@ -19,12 +19,54 @@ class LLMGuardrail:
|
||||
|
||||
Args:
|
||||
description: Natural language description of what to validate
|
||||
llm: The LLM instance to use for validation
|
||||
llm: The LLM instance to use for validation (can be string or LLM instance)
|
||||
"""
|
||||
self.description = description
|
||||
self.llm = llm
|
||||
self.llm = self._initialize_llm(llm)
|
||||
self.logger = logging.getLogger(__name__)
|
||||
|
||||
def _initialize_llm(self, llm: Any) -> Any:
|
||||
"""Initialize the LLM instance from string identifier or existing instance.
|
||||
|
||||
Args:
|
||||
llm: String identifier, LLM instance, or None
|
||||
|
||||
Returns:
|
||||
LLM instance or None
|
||||
"""
|
||||
# Local import to avoid circular dependencies
|
||||
def _get_llm_class():
|
||||
from ..llm.llm import LLM
|
||||
return LLM
|
||||
|
||||
if llm is None:
|
||||
return None
|
||||
|
||||
# If it's already an LLM instance, return as-is
|
||||
if hasattr(llm, 'chat') or hasattr(llm, 'get_response') or callable(llm):
|
||||
return llm
|
||||
|
||||
# If it's a string, convert to LLM instance
|
||||
if isinstance(llm, str):
|
||||
try:
|
||||
# Handle string identifiers (both provider/model and simple names)
|
||||
return _get_llm_class()(model=llm)
|
||||
except Exception as e:
|
||||
self.logger.error(f"Failed to initialize LLM from string '{llm}': {str(e)}")
|
||||
return None
|
||||
|
||||
# If it's a dict, pass parameters to LLM
|
||||
if isinstance(llm, dict) and "model" in llm:
|
||||
try:
|
||||
return _get_llm_class()(**llm)
|
||||
except Exception as e:
|
||||
self.logger.error(f"Failed to initialize LLM from dict: {str(e)}")
|
||||
return None
|
||||
|
||||
# Unknown type
|
||||
self.logger.warning(f"Unknown LLM type: {type(llm)}, treating as-is")
|
||||
return llm
|
||||
|
||||
def __call__(self, task_output: TaskOutput) -> Tuple[bool, Union[str, TaskOutput]]:
|
||||
"""Validate the task output using the LLM.
|
||||
|
||||
|
||||
@@ -67,9 +67,6 @@ class Knowledge:
|
||||
|
||||
# Disable OpenAI API request logging
|
||||
logging.getLogger('openai').setLevel(logging.WARNING)
|
||||
|
||||
# Set root logger to warning to catch any uncategorized logs
|
||||
logging.getLogger().setLevel(logging.WARNING)
|
||||
|
||||
@cached_property
|
||||
def _deps(self):
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
# Ollama Handling in LLM.py
|
||||
|
||||
The `ollama_handled` flag is used in `llm.py` (not in `agent.py`) to track whether special Ollama model handling has been applied for tool results. Here's what I found:
|
||||
|
||||
## Where it's used in llm.py:
|
||||
- **Line 863**: `ollama_handled = False` - initialized at the beginning of the tool execution loop
|
||||
- **Line 864**: Special handling logic via `_handle_ollama_model()` method
|
||||
- **Line 907**: `ollama_handled = True` - set when Ollama special handling is applied
|
||||
- **Line 928 & 959**: Checks `if not ollama_handled` to avoid duplicate processing
|
||||
|
||||
## Why it's needed:
|
||||
The flag prevents duplicate processing when Ollama models require special handling. Some Ollama models return only the tool call JSON without processing the results, requiring a follow-up prompt to get the final answer. The `ollama_handled` flag ensures this special handling happens only once.
|
||||
|
||||
## Does this contradict the requirement?
|
||||
**No, it doesn't.** The issue states:
|
||||
|
||||
> "ollama/xxxx model is already handled via llm.py via litellm, so no special condition or handling required for ollama inside agent.py"
|
||||
|
||||
✅ **Current implementation is correct:**
|
||||
|
||||
- `agent.py` has NO ollama-specific conditions (only one documentation mention as an example)
|
||||
- All ollama handling is contained within `llm.py` as intended
|
||||
- The `ollama_handled` flag is an internal implementation detail within `llm.py`
|
||||
|
||||
The codebase already follows the desired pattern where ollama models are handled through the generic LLM interface via litellm without special conditions in agent.py.
|
||||
Loaded 100 of 167 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user