mirror of
https://github.com/MervinPraison/PraisonAI.git
synced 2026-11-08 08:11:07 -10:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a8b1948fc0 | ||
|
|
56f815c1b1 | ||
|
|
6b30977d9e | ||
|
|
4966ec1ae1 | ||
|
|
c31870a991 | ||
|
|
67f4a89062 | ||
|
|
a898bbb7d1 | ||
|
|
107d33deb7 | ||
|
|
9d963e4eeb | ||
|
|
56b296b8d6 | ||
|
|
fddf999688 | ||
|
|
6374aba783 | ||
|
|
9408d699e8 | ||
|
|
6358671ab9 | ||
|
|
f5bd55bb9a | ||
|
|
a93c571f33 | ||
|
|
8ea0e4c831 | ||
|
|
8a1dc24794 | ||
|
|
b331229578 | ||
|
|
7af52735cf | ||
|
|
2902fec42e | ||
|
|
64f752a8e0 | ||
|
|
d994fb5047 | ||
|
|
760fb9530b | ||
|
|
de165975b0 | ||
|
|
dfd74a2fe7 | ||
|
|
9265ca08a2 | ||
|
|
665df753fd | ||
|
|
94d991f4ec | ||
|
|
632cf68423 | ||
|
|
d956c605f7 | ||
|
|
7e3de10f32 | ||
|
|
79883f1af2 | ||
|
|
a098eb0150 | ||
|
|
b9ce3b4ccb | ||
|
|
58b44280df | ||
|
|
4dba09d6b1 | ||
|
|
a538513bec | ||
|
|
4fb79207cf | ||
|
|
0b444fae34 | ||
|
|
bd34e45bbc | ||
|
|
f4f051e57e | ||
|
|
3c2610cc3c | ||
|
|
9788454134 | ||
|
|
e618004e60 | ||
|
|
384803ba8e | ||
|
|
d3bb366a51 | ||
|
|
e579e84b52 | ||
|
|
61440403f5 | ||
|
|
b615782175 | ||
|
|
35199979f0 | ||
|
|
eeb77cfd20 | ||
|
|
00d7994601 | ||
|
|
10aa49addc | ||
|
|
79c9cf8bf9 | ||
|
|
a9416fb7fc | ||
|
|
547b40ee72 | ||
|
|
4fc35d1b10 | ||
|
|
c72d74987b | ||
|
|
430ec6571a | ||
|
|
e88288773a | ||
|
|
9af03e3fef | ||
|
|
1d22818662 |
No files matched your search
@@ -0,0 +1,9 @@
|
||||
FROM node:20-alpine
|
||||
|
||||
RUN npm install -g @anthropic-ai/claude-code
|
||||
|
||||
WORKDIR /app
|
||||
COPY entrypoint.sh .
|
||||
RUN chmod +x entrypoint.sh
|
||||
|
||||
ENTRYPOINT ["/app/entrypoint.sh"]
|
||||
@@ -0,0 +1,20 @@
|
||||
name: "Claude Code Action"
|
||||
description: "Custom Claude Code runner for PraisonAI"
|
||||
|
||||
inputs:
|
||||
anthropic_api_key:
|
||||
required: true
|
||||
description: "Anthropic API key"
|
||||
github_token:
|
||||
required: true
|
||||
description: "GitHub token for repo access"
|
||||
|
||||
runs:
|
||||
using: "docker"
|
||||
image: "ghcr.io/mervinpraison/praisonai-claudecode:latest"
|
||||
env:
|
||||
ANTHROPIC_API_KEY: ${{ inputs.anthropic_api_key }}
|
||||
GITHUB_TOKEN: ${{ inputs.github_token }}
|
||||
args:
|
||||
- "--anthropic-api-key=${{ inputs.anthropic_api_key }}"
|
||||
- "--github-token=${{ inputs.github_token }}"
|
||||
@@ -0,0 +1,21 @@
|
||||
#!/bin/sh
|
||||
|
||||
set -e
|
||||
|
||||
echo "Running Claude Code in CI mode..."
|
||||
|
||||
# Extract GitHub context and create a smart prompt
|
||||
PROMPT="Analyse the GitHub issue or PR context and generate a smart response based on the repository context."
|
||||
|
||||
# Set environment variables from arguments
|
||||
export ANTHROPIC_API_KEY="${1#--anthropic-api-key=}"
|
||||
export GITHUB_TOKEN="${2#--github-token=}"
|
||||
|
||||
# Verify environment variables
|
||||
if [ -z "$ANTHROPIC_API_KEY" ] || [ -z "$GITHUB_TOKEN" ]; then
|
||||
echo "Error: Required environment variables are not set"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Run Claude with the prompt
|
||||
claude -p "$PROMPT"
|
||||
@@ -0,0 +1,117 @@
|
||||
name: "Claude Code Action"
|
||||
description: "Run Claude Code in GitHub Actions workflows"
|
||||
|
||||
inputs:
|
||||
github_token:
|
||||
description: "GitHub token with repo and issues permissions"
|
||||
required: true
|
||||
anthropic_api_key:
|
||||
description: "Anthropic API key"
|
||||
required: true
|
||||
prompt:
|
||||
description: "The prompt to send to Claude Code"
|
||||
required: false
|
||||
default: ""
|
||||
prompt_file:
|
||||
description: "Path to a file containing the prompt to send to Claude Code"
|
||||
required: false
|
||||
default: ""
|
||||
allowed_tools:
|
||||
description: "Comma-separated list of allowed tools for Claude Code to use"
|
||||
required: false
|
||||
default: ""
|
||||
output_file:
|
||||
description: "File to save Claude Code output to (optional)"
|
||||
required: false
|
||||
default: ""
|
||||
timeout_minutes:
|
||||
description: "Timeout in minutes for Claude Code execution"
|
||||
required: false
|
||||
default: "10"
|
||||
install_github_mcp:
|
||||
description: "Whether to install the GitHub MCP server"
|
||||
required: false
|
||||
default: "false"
|
||||
|
||||
runs:
|
||||
using: "composite"
|
||||
steps:
|
||||
- name: Install Claude Code
|
||||
shell: bash
|
||||
run: npm install -g @anthropic-ai/claude-code
|
||||
|
||||
- name: Install GitHub MCP Server
|
||||
if: inputs.install_github_mcp == 'true'
|
||||
shell: bash
|
||||
run: |
|
||||
claude mcp add-json github '{
|
||||
"command": "docker",
|
||||
"args": [
|
||||
"run",
|
||||
"-i",
|
||||
"--rm",
|
||||
"-e",
|
||||
"GITHUB_PERSONAL_ACCESS_TOKEN",
|
||||
"ghcr.io/github/github-mcp-server:sha-ff3036d"
|
||||
],
|
||||
"env": {
|
||||
"GITHUB_PERSONAL_ACCESS_TOKEN": "${{ inputs.GITHUB_TOKEN }}"
|
||||
}
|
||||
}'
|
||||
|
||||
- name: Prepare Prompt File
|
||||
shell: bash
|
||||
id: prepare_prompt
|
||||
run: |
|
||||
if [ -z "${{ inputs.prompt }}" ] && [ -z "${{ inputs.prompt_file }}" ]; then
|
||||
echo "::error::Neither 'prompt' nor 'prompt_file' was provided. At least one is required."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ ! -z "${{ inputs.prompt_file }}" ]; then
|
||||
if [ ! -f "${{ inputs.prompt_file }}" ]; then
|
||||
echo "::error::Prompt file '${{ inputs.prompt_file }}' does not exist."
|
||||
exit 1
|
||||
fi
|
||||
PROMPT_PATH="${{ inputs.prompt_file }}"
|
||||
else
|
||||
mkdir -p /tmp/claude-action
|
||||
PROMPT_PATH="/tmp/claude-action/prompt.txt"
|
||||
echo "${{ inputs.prompt }}" > "$PROMPT_PATH"
|
||||
fi
|
||||
|
||||
if [ ! -s "$PROMPT_PATH" ]; then
|
||||
echo "::error::Prompt is empty. Please provide a non-empty prompt."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "PROMPT_PATH=$PROMPT_PATH" >> $GITHUB_ENV
|
||||
|
||||
- name: Run Claude Code
|
||||
shell: bash
|
||||
id: run_claude
|
||||
run: |
|
||||
timeout_seconds=$((${{ inputs.timeout_minutes }} * 60))
|
||||
|
||||
if [ -z "${{ inputs.output_file }}" ]; then
|
||||
timeout $timeout_seconds claude \
|
||||
-p \
|
||||
--verbose \
|
||||
--output-format stream-json \
|
||||
"$(cat ${{ env.PROMPT_PATH }})" \
|
||||
${{ inputs.allowed_tools != '' && format('--allowedTools "{0}"', inputs.allowed_tools) || '' }}
|
||||
else
|
||||
timeout $timeout_seconds claude \
|
||||
-p \
|
||||
--verbose \
|
||||
--output-format stream-json \
|
||||
"$(cat ${{ env.PROMPT_PATH }})" \
|
||||
${{ inputs.allowed_tools != '' && format('--allowedTools "{0}"', inputs.allowed_tools) || '' }} | tee output.txt
|
||||
|
||||
jq -s '.' output.txt > output.json
|
||||
jq -r '.[-1].result' output.json > "${{ inputs.output_file }}"
|
||||
echo "Complete output saved to output.json, final response saved to ${{ inputs.output_file }}"
|
||||
fi
|
||||
env:
|
||||
ANTHROPIC_API_KEY: ${{ inputs.anthropic_api_key }}
|
||||
GITHUB_TOKEN: ${{ inputs.github_token }}
|
||||
@@ -0,0 +1,39 @@
|
||||
name: Build Claude Code Image
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
version:
|
||||
description: 'Image version tag'
|
||||
required: true
|
||||
default: 'latest'
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Build and push Docker image
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: ./.github/actions/claude-code-action
|
||||
push: true
|
||||
tags: ghcr.io/mervinpraison/praisonai-claudecode:${{ inputs.version }}
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
provenance: false
|
||||
@@ -23,15 +23,60 @@ jobs:
|
||||
pull-requests: read
|
||||
issues: read
|
||||
id-token: write
|
||||
packages: read
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 1
|
||||
|
||||
- name: Debug Environment
|
||||
run: |
|
||||
echo "=== Environment Debug ==="
|
||||
echo "GITHUB_ACTOR: $GITHUB_ACTOR"
|
||||
echo "GITHUB_REPOSITORY: $GITHUB_REPOSITORY"
|
||||
echo "GITHUB_REPOSITORY_OWNER: $GITHUB_REPOSITORY_OWNER"
|
||||
echo "GITHUB_TOKEN exists: $([ -n "$GITHUB_TOKEN" ] && echo "yes" || echo "no")"
|
||||
echo "GITHUB_TOKEN length: ${#GITHUB_TOKEN}"
|
||||
|
||||
- name: Check Package Visibility
|
||||
run: |
|
||||
echo "=== Checking Package Visibility ==="
|
||||
curl -s -H "Authorization: Bearer $GITHUB_TOKEN" \
|
||||
-H "Accept: application/vnd.github.v3+json" \
|
||||
"https://api.github.com/users/MervinPraison/packages/container/praisonai-claudecode" \
|
||||
|| echo "Package API call failed"
|
||||
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Test Docker Authentication
|
||||
run: |
|
||||
echo "=== Testing Docker Authentication ==="
|
||||
echo "Checking ~/.docker/config.json"
|
||||
cat ~/.docker/config.json | jq '.' || echo "No docker config found"
|
||||
echo "=== Testing Registry Access ==="
|
||||
curl -s -H "Authorization: Bearer $GITHUB_TOKEN" \
|
||||
"https://ghcr.io/v2/" || echo "Registry access failed"
|
||||
|
||||
- name: Test Docker Pull
|
||||
run: |
|
||||
echo "=== Testing Docker Pull ==="
|
||||
echo "Attempting to pull image: ghcr.io/mervinpraison/praisonai-claudecode:latest"
|
||||
docker pull ghcr.io/mervinpraison/praisonai-claudecode:latest || echo "Pull failed with exit code: $?"
|
||||
echo "=== Checking Docker Images ==="
|
||||
docker images | grep praisonai-claudecode || echo "No images found"
|
||||
|
||||
- name: Run Claude Code
|
||||
id: claude
|
||||
uses: anthropics/claude-code-action@beta
|
||||
uses: ./.github/actions/claude-code-action
|
||||
with:
|
||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
+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.31" \
|
||||
"praisonai>=2.2.33" \
|
||||
"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.31" \
|
||||
"praisonai>=2.2.33" \
|
||||
"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.31" \
|
||||
"praisonai>=2.2.33" \
|
||||
"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.31" \
|
||||
"praisonai>=2.2.33" \
|
||||
"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.31`
|
||||
- PraisonAI: `>=2.2.33`
|
||||
- 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.31" "praisonaiagents==0.0.92"
|
||||
RUN pip install "praisonai==2.2.33" "praisonaiagents==0.0.92"
|
||||
```
|
||||
|
||||
## 🌐 Production Deployment
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
framework: ag2
|
||||
topic: "Research the latest developments in AI agents"
|
||||
|
||||
# Install: pip install "praisonai[ag2]"
|
||||
# Run: praisonai --framework ag2 examples/ag2/ag2_basic.yaml
|
||||
# or praisonai run examples/ag2/ag2_basic.yaml --framework ag2
|
||||
|
||||
roles:
|
||||
research_agent:
|
||||
role: "AI Research Specialist"
|
||||
goal: "Research and summarise the latest developments in AI agent frameworks"
|
||||
backstory: |
|
||||
You are an experienced AI researcher with deep knowledge of multi-agent
|
||||
systems, large language models, and the latest trends in AI tooling.
|
||||
You excel at synthesising complex technical topics into clear summaries.
|
||||
tasks:
|
||||
research_task:
|
||||
description: |
|
||||
Research and summarise the latest developments in AI agent frameworks
|
||||
for the topic: {topic}
|
||||
|
||||
Focus on:
|
||||
1. Key frameworks and their unique capabilities
|
||||
2. Recent innovations and improvements
|
||||
3. Community adoption and ecosystem growth
|
||||
4. Practical use cases and success stories
|
||||
expected_output: |
|
||||
A concise research summary covering the key developments,
|
||||
major frameworks, and practical insights. Include 3-5 bullet
|
||||
points of the most important findings.
|
||||
@@ -0,0 +1,42 @@
|
||||
framework: ag2
|
||||
topic: "Cloud-native AI deployment strategies on AWS"
|
||||
|
||||
# AG2 exclusive feature: native AWS Bedrock support via LLMConfig(api_type="bedrock")
|
||||
#
|
||||
# Prerequisites:
|
||||
# pip install "praisonai[ag2]"
|
||||
# aws configure (or set AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_DEFAULT_REGION)
|
||||
#
|
||||
# Run:
|
||||
# praisonai --framework ag2 examples/ag2/ag2_bedrock.yaml
|
||||
#
|
||||
# The AG2 adapter detects api_type="bedrock" from the llm config and uses
|
||||
# LLMConfig(api_type="bedrock", model=...) — no OPENAI_API_KEY required.
|
||||
# AWS credentials are sourced from boto3 (env vars, ~/.aws/credentials, IAM role).
|
||||
|
||||
roles:
|
||||
cloud_architect:
|
||||
role: "AWS Cloud Architect"
|
||||
goal: "Design and explain cloud-native AI deployment strategies on AWS"
|
||||
backstory: |
|
||||
You are an AWS Solutions Architect specialising in AI/ML workloads.
|
||||
You have deep expertise in Amazon Bedrock, SageMaker, ECS, and Lambda,
|
||||
and you help organisations deploy AI agents at scale securely and cost-effectively.
|
||||
llm:
|
||||
model: "bedrock/anthropic.claude-3-5-sonnet-20241022-v2:0"
|
||||
api_type: "bedrock"
|
||||
aws_region: "us-east-1"
|
||||
tasks:
|
||||
architecture_task:
|
||||
description: |
|
||||
Design a cloud-native deployment strategy for AI agents on AWS for: {topic}
|
||||
|
||||
Cover:
|
||||
1. Recommended AWS services (Bedrock, ECS, Lambda, etc.)
|
||||
2. Scalability and cost optimisation patterns
|
||||
3. Security and compliance considerations
|
||||
4. A simple reference architecture overview
|
||||
expected_output: |
|
||||
A concise architecture guide with service recommendations,
|
||||
a high-level deployment diagram description, and key
|
||||
best practices for production AI agent deployments on AWS.
|
||||
@@ -0,0 +1,54 @@
|
||||
framework: ag2
|
||||
topic: "The impact of open-source AI on enterprise software development"
|
||||
|
||||
# Install: pip install "praisonai[ag2]"
|
||||
# Run: praisonai --framework ag2 examples/ag2/ag2_multi_agent.yaml
|
||||
# or praisonai run examples/ag2/ag2_multi_agent.yaml --framework ag2
|
||||
#
|
||||
# This example demonstrates AG2's GroupChat multi-agent coordination.
|
||||
# Both agents participate in a collaborative conversation managed by
|
||||
# a GroupChatManager until the task is complete.
|
||||
|
||||
roles:
|
||||
researcher:
|
||||
role: "Research Specialist"
|
||||
goal: "Gather and analyse information on the given topic"
|
||||
backstory: |
|
||||
You are a meticulous researcher who excels at finding relevant
|
||||
information, analysing trends, and presenting data-backed insights.
|
||||
You always cite your reasoning and structure your findings clearly.
|
||||
tasks:
|
||||
research_task:
|
||||
description: |
|
||||
Research the topic: {topic}
|
||||
|
||||
Investigate:
|
||||
1. Current state and adoption rates
|
||||
2. Key players and projects driving the trend
|
||||
3. Technical advantages and challenges
|
||||
4. Business impact and cost implications
|
||||
expected_output: |
|
||||
A structured research briefing with findings on the topic,
|
||||
including key data points, trends, and technical observations.
|
||||
|
||||
writer:
|
||||
role: "Technical Content Writer"
|
||||
goal: "Transform research findings into clear, engaging written content"
|
||||
backstory: |
|
||||
You are a skilled technical writer who turns complex research into
|
||||
accessible, well-structured articles. You focus on clarity, logical
|
||||
flow, and actionable takeaways for a professional audience.
|
||||
tasks:
|
||||
writing_task:
|
||||
description: |
|
||||
Using the research findings provided by the Research Specialist,
|
||||
write a concise article on: {topic}
|
||||
|
||||
The article should:
|
||||
1. Open with a compelling hook
|
||||
2. Present key findings logically
|
||||
3. Include practical implications for developers
|
||||
4. Close with a forward-looking conclusion
|
||||
expected_output: |
|
||||
A 400-500 word article suitable for a technical blog,
|
||||
with clear sections, professional tone, and concrete takeaways.
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,134 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "441900e0"
|
||||
},
|
||||
"source": [
|
||||
"# 🧠 Mistral v0.3 (7B) Conversational Agent\n",
|
||||
"A conceptual demo notebook to illustrate the workflow and output of the Mistral model, even if it doesn't run on Colab Free Tier."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "b4ba0b88"
|
||||
},
|
||||
"source": [
|
||||
"## 📄 Description\n",
|
||||
"This notebook showcases the typical flow of using Mistral v0.3 (7B) for conversational tasks. While the model is too large for Google Colab Free Tier, this version visually explains what the code would do.\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"[](https://colab.research.google.com/github/DhivyaBharathy-web/PraisonAI/blob/main/examples/cookbooks/Mistral_v0_3_Conversational_Demo.ipynb)\n"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "yzXURvxIlIDD"
|
||||
}
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"# 📦 Dependencies"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "IUQSTocQk7ml"
|
||||
}
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "6f2afc57"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"\n",
|
||||
"!pip install transformers accelerate torch\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "9d5dad27"
|
||||
},
|
||||
"source": [
|
||||
"## 🛠 Tools Used\n",
|
||||
"- 🤗 Transformers: For loading the model and tokenizer.\n",
|
||||
"- PyTorch: For model inference.\n",
|
||||
"- Accelerate: To manage device placement (CPU/GPU).\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "cd936b40"
|
||||
},
|
||||
"source": [
|
||||
"## 🧾 YAML Prompt Format (Conceptual)\n",
|
||||
"```yaml\n",
|
||||
"task: conversation\n",
|
||||
"input: \"What's the capital of France?\"\n",
|
||||
"history: []\n",
|
||||
"temperature: 0.7\n",
|
||||
"top_p: 0.9\n",
|
||||
"```\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "8abaaa62"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# 🧠 Main Inference Logic (Illustrative)\n",
|
||||
"from transformers import AutoModelForCausalLM, AutoTokenizer\n",
|
||||
"import torch\n",
|
||||
"\n",
|
||||
"model_id = \"mistralai/Mistral-7B-Instruct-v0.3\"\n",
|
||||
"tokenizer = AutoTokenizer.from_pretrained(model_id)\n",
|
||||
"model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float16, device_map=\"auto\")\n",
|
||||
"\n",
|
||||
"prompt = \"What's the capital of France?\"\n",
|
||||
"inputs = tokenizer(prompt, return_tensors=\"pt\").to(model.device)\n",
|
||||
"outputs = model.generate(**inputs, max_new_tokens=100)\n",
|
||||
"response = tokenizer.decode(outputs[0], skip_special_tokens=True)\n",
|
||||
"print(response)\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "def486c6"
|
||||
},
|
||||
"source": [
|
||||
"## 📤 Output (Example)\n",
|
||||
"> \"The capital of France is Paris.\"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"accelerator": "GPU",
|
||||
"colab": {
|
||||
"gpuType": "T4",
|
||||
"provenance": []
|
||||
},
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"name": "python"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 0
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,170 @@
|
||||
# Remote Agent Connectivity
|
||||
|
||||
This directory contains examples demonstrating PraisonAI's remote agent connectivity feature, which allows you to connect to agents running on different servers, similar to Google ADK's agent connectivity pattern.
|
||||
|
||||
## Overview
|
||||
|
||||
The remote agent connectivity feature enables:
|
||||
- **Direct agent-to-agent connectivity** across networks
|
||||
- **Session-based communication** with remote agents
|
||||
- **Google ADK-like API patterns** for familiar usage
|
||||
- **Automatic connection management** and error handling
|
||||
|
||||
## Quick Start
|
||||
|
||||
### 1. Start a Remote Agent Server
|
||||
|
||||
```bash
|
||||
# Start a simple remote agent server
|
||||
python remote_agent_server.py
|
||||
|
||||
# Or start multiple agents on one server
|
||||
python remote_agent_server.py --multiple
|
||||
```
|
||||
|
||||
### 2. Connect from Client
|
||||
|
||||
```python
|
||||
from praisonaiagents import Session
|
||||
|
||||
# Connect to remote agent (similar to Google ADK)
|
||||
session = Session(agent_url="192.168.1.10:8000/agent")
|
||||
|
||||
# Send messages to the remote agent
|
||||
response = session.chat("Hello from the client!")
|
||||
print(response)
|
||||
|
||||
# Alternative method (Google ADK pattern)
|
||||
response = session.send_message("What can you help me with?")
|
||||
print(response)
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
- **`remote_agent_server.py`** - Set up agents as remote servers
|
||||
- **`remote_agent_example.py`** - Connect to and communicate with remote agents
|
||||
|
||||
## API Comparison
|
||||
|
||||
### Google ADK Pattern
|
||||
```python
|
||||
from adk.agent import Agent
|
||||
from adk.session import Session
|
||||
|
||||
session = Session(agent_url="192.168.1.10:8000")
|
||||
response = session.send_message("Hello!")
|
||||
```
|
||||
|
||||
### PraisonAI Pattern
|
||||
```python
|
||||
from praisonaiagents import Session
|
||||
|
||||
session = Session(agent_url="192.168.1.10:8000/agent")
|
||||
response = session.chat("Hello!")
|
||||
# OR
|
||||
response = session.send_message("Hello!") # Google ADK compatibility
|
||||
```
|
||||
|
||||
## Key Features
|
||||
|
||||
### ✅ **Seamless Connectivity**
|
||||
- Automatic protocol detection (http/https)
|
||||
- Connection testing and validation
|
||||
- Configurable timeouts
|
||||
|
||||
### ✅ **Error Handling**
|
||||
- Clear error messages for connection issues
|
||||
- Graceful handling of network problems
|
||||
- Appropriate fallbacks for unavailable services
|
||||
|
||||
### ✅ **Backward Compatibility**
|
||||
- Existing local agent functionality unchanged
|
||||
- Session API works for both local and remote scenarios
|
||||
- No breaking changes to current code
|
||||
|
||||
### ✅ **Flexible Configuration**
|
||||
- Support for IP:port format (`192.168.1.10:8000`)
|
||||
- Full URL format (`http://server.com:8000/agent`)
|
||||
- Customizable endpoints and paths
|
||||
|
||||
## Usage Patterns
|
||||
|
||||
### Single Remote Agent
|
||||
```python
|
||||
# Connect to a specific remote agent
|
||||
session = Session(agent_url="192.168.1.10:8000/agent")
|
||||
response = session.chat("Hello from remote client!")
|
||||
```
|
||||
|
||||
### Multiple Remote Agents
|
||||
```python
|
||||
# Connect to different specialized agents
|
||||
research_session = Session(agent_url="192.168.1.10:8000/research")
|
||||
coding_session = Session(agent_url="192.168.1.10:8000/coding")
|
||||
|
||||
research_response = research_session.chat("Find info about AI trends")
|
||||
coding_response = coding_session.chat("Help me debug this Python code")
|
||||
```
|
||||
|
||||
### Error Handling
|
||||
```python
|
||||
try:
|
||||
session = Session(agent_url="192.168.1.10:8000/agent")
|
||||
response = session.chat("Test message")
|
||||
print(f"Response: {response}")
|
||||
except ConnectionError as e:
|
||||
print(f"Failed to connect: {e}")
|
||||
```
|
||||
|
||||
## Network Configuration
|
||||
|
||||
### Server Setup
|
||||
```python
|
||||
# Create and launch agent server
|
||||
agent = Agent(name="RemoteAgent", role="Assistant")
|
||||
agent.launch(path="/agent", port=8000, host="0.0.0.0")
|
||||
```
|
||||
|
||||
### Client Connection
|
||||
```python
|
||||
# Connect from any network location
|
||||
session = Session(agent_url="<server-ip>:8000/agent")
|
||||
```
|
||||
|
||||
## Limitations for Remote Sessions
|
||||
|
||||
When using remote agent sessions, certain local operations are not available:
|
||||
- **Memory operations** (`session.memory.*`)
|
||||
- **Knowledge operations** (`session.knowledge.*`)
|
||||
- **Local agent creation** (`session.Agent(...)`)
|
||||
- **State management** (`session.save_state/restore_state`)
|
||||
|
||||
This design keeps remote and local operations clearly separated.
|
||||
|
||||
## Testing
|
||||
|
||||
Run the examples to test the functionality:
|
||||
|
||||
```bash
|
||||
# Terminal 1: Start server
|
||||
python remote_agent_server.py
|
||||
|
||||
# Terminal 2: Test client (update IP as needed)
|
||||
python remote_agent_example.py
|
||||
```
|
||||
|
||||
## Integration with Existing Code
|
||||
|
||||
The remote connectivity feature integrates seamlessly with existing PraisonAI code:
|
||||
|
||||
```python
|
||||
# Existing local code works unchanged
|
||||
local_session = Session(session_id="local_chat")
|
||||
local_agent = local_session.Agent(name="LocalAgent", role="Assistant")
|
||||
|
||||
# New remote connectivity
|
||||
remote_session = Session(agent_url="remote-server:8000/agent")
|
||||
remote_response = remote_session.chat("Hello from remote!")
|
||||
```
|
||||
|
||||
This provides a smooth migration path for applications that need to scale across multiple servers.
|
||||
@@ -0,0 +1,141 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Remote Agent Connectivity Example
|
||||
|
||||
This example demonstrates how to connect to agents running on remote servers,
|
||||
similar to Google ADK's agent connectivity pattern.
|
||||
|
||||
Usage:
|
||||
1. First, start a remote agent server:
|
||||
python remote_agent_server.py
|
||||
|
||||
2. Then run this client to connect to it:
|
||||
python remote_agent_example.py
|
||||
"""
|
||||
|
||||
from praisonaiagents import Session
|
||||
import time
|
||||
|
||||
def example_remote_agent_connection():
|
||||
"""
|
||||
Example demonstrating remote agent connectivity similar to Google ADK.
|
||||
"""
|
||||
print("🌐 Remote Agent Connectivity Example")
|
||||
print("=" * 50)
|
||||
|
||||
# Example 1: Connect to remote agent using IP:port format
|
||||
try:
|
||||
print("\n1. Connecting to remote agent at 192.168.1.10:8000...")
|
||||
|
||||
# Create a session with remote agent URL (similar to Google ADK)
|
||||
session = Session(agent_url="192.168.1.10:8000/agent")
|
||||
|
||||
print(f"✅ Connected! Session: {session}")
|
||||
|
||||
# Send a message to the remote agent
|
||||
response = session.chat("Hello from the client!")
|
||||
print(f"📨 Sent: 'Hello from the client!'")
|
||||
print(f"📨 Received: {response}")
|
||||
|
||||
# Send another message using the alias method (Google ADK pattern)
|
||||
response = session.send_message("What can you help me with?")
|
||||
print(f"📨 Sent: 'What can you help me with?'")
|
||||
print(f"📨 Received: {response}")
|
||||
|
||||
except ConnectionError as e:
|
||||
print(f"❌ Connection failed: {e}")
|
||||
print("💡 Make sure the remote agent server is running at 192.168.1.10:8000")
|
||||
|
||||
# Example 2: Connect to localhost for testing
|
||||
try:
|
||||
print("\n2. Connecting to localhost for testing...")
|
||||
|
||||
# Connect to local server (for testing)
|
||||
session = Session(agent_url="localhost:8000/agent")
|
||||
|
||||
print(f"✅ Connected! Session: {session}")
|
||||
|
||||
# Test the connection
|
||||
response = session.chat("Test message")
|
||||
print(f"📨 Response: {response}")
|
||||
|
||||
except ConnectionError as e:
|
||||
print(f"❌ Connection failed: {e}")
|
||||
print("💡 Start a local agent server first with: python remote_agent_server.py")
|
||||
|
||||
def example_error_handling():
|
||||
"""
|
||||
Example demonstrating error handling for remote sessions.
|
||||
"""
|
||||
print("\n\n🚨 Error Handling Examples")
|
||||
print("=" * 50)
|
||||
|
||||
try:
|
||||
# Create a remote session
|
||||
session = Session(agent_url="localhost:8000/agent")
|
||||
|
||||
# These operations are not available for remote sessions
|
||||
print("\n❌ Attempting to access memory (should fail)...")
|
||||
session.memory.store_short_term("test")
|
||||
|
||||
except ConnectionError:
|
||||
print("⚠️ Cannot connect to remote agent (expected if server not running)")
|
||||
except ValueError as e:
|
||||
print(f"✅ Correctly caught error: {e}")
|
||||
|
||||
try:
|
||||
session = Session(agent_url="localhost:8000/agent")
|
||||
print("\n❌ Attempting to create local agent (should fail)...")
|
||||
agent = session.Agent(name="Test", role="Assistant")
|
||||
|
||||
except ConnectionError:
|
||||
print("⚠️ Cannot connect to remote agent (expected if server not running)")
|
||||
except ValueError as e:
|
||||
print(f"✅ Correctly caught error: {e}")
|
||||
|
||||
def comparison_with_google_adk():
|
||||
"""
|
||||
Shows the comparison between Google ADK and PraisonAI patterns.
|
||||
"""
|
||||
print("\n\n🔄 Comparison with Google ADK")
|
||||
print("=" * 50)
|
||||
|
||||
print("\n📋 Google ADK Pattern:")
|
||||
print("""
|
||||
from adk.agent import Agent
|
||||
from adk.session import Session
|
||||
|
||||
# Connect to remote agent
|
||||
session = Session(agent_url="192.168.1.10:8000")
|
||||
response = session.send_message("Hello from client!")
|
||||
""")
|
||||
|
||||
print("📋 PraisonAI Pattern:")
|
||||
print("""
|
||||
from praisonaiagents import Session
|
||||
|
||||
# Connect to remote agent
|
||||
session = Session(agent_url="192.168.1.10:8000/agent")
|
||||
response = session.chat("Hello from client!")
|
||||
# OR
|
||||
response = session.send_message("Hello from client!")
|
||||
""")
|
||||
|
||||
print("✨ Key similarities:")
|
||||
print("• Direct agent URL connectivity")
|
||||
print("• Simple session-based API")
|
||||
print("• Similar message sending patterns")
|
||||
print("• Error handling for connection issues")
|
||||
|
||||
if __name__ == "__main__":
|
||||
example_remote_agent_connection()
|
||||
example_error_handling()
|
||||
comparison_with_google_adk()
|
||||
|
||||
print("\n\n🎯 Summary")
|
||||
print("=" * 50)
|
||||
print("✅ Remote agent connectivity implemented")
|
||||
print("✅ Google ADK-like API pattern supported")
|
||||
print("✅ Backward compatibility maintained")
|
||||
print("✅ Proper error handling for remote sessions")
|
||||
print("\n💡 To test with a real server, run remote_agent_server.py first!")
|
||||
@@ -0,0 +1,103 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Remote Agent Server Example
|
||||
|
||||
This example demonstrates how to set up an agent as a remote server
|
||||
that can be accessed by other clients using the Session(agent_url=...) pattern.
|
||||
|
||||
Usage:
|
||||
python remote_agent_server.py
|
||||
|
||||
Then connect from another machine/process:
|
||||
python remote_agent_example.py
|
||||
"""
|
||||
|
||||
from praisonaiagents import Agent
|
||||
import time
|
||||
|
||||
def setup_remote_agent_server():
|
||||
"""
|
||||
Set up an agent as a remote server accessible via HTTP API.
|
||||
"""
|
||||
print("🚀 Setting up Remote Agent Server")
|
||||
print("=" * 50)
|
||||
|
||||
# Create an agent that will serve as the remote agent
|
||||
agent = Agent(
|
||||
name="RemoteAssistant",
|
||||
role="Helpful Remote AI Assistant",
|
||||
goal="Assist users with their queries via remote connections",
|
||||
backstory="I am an AI assistant running on a remote server, ready to help clients connect and interact with me.",
|
||||
llm="gpt-4o-mini", # or any other supported model
|
||||
verbose=True
|
||||
)
|
||||
|
||||
print(f"📝 Created agent: {agent}")
|
||||
print(f"🔧 Agent details:")
|
||||
print(f" • Name: {agent.name}")
|
||||
print(f" • Role: {agent.role}")
|
||||
print(f" • Goal: {agent.goal}")
|
||||
|
||||
# Launch the agent as an HTTP API server
|
||||
print(f"\n🌐 Launching agent server...")
|
||||
print(f"📡 Server will be accessible at:")
|
||||
print(f" • Local: http://localhost:8000/agent")
|
||||
print(f" • Network: http://<your-ip>:8000/agent")
|
||||
print(f"\n🔗 Clients can connect using:")
|
||||
print(f" session = Session(agent_url='<server-ip>:8000/agent')")
|
||||
print(f"\n⏹️ Press Ctrl+C to stop the server")
|
||||
print("=" * 50)
|
||||
|
||||
# This will start the HTTP server and block until interrupted
|
||||
try:
|
||||
agent.launch(path="/agent", port=8000, host="0.0.0.0")
|
||||
except KeyboardInterrupt:
|
||||
print("\n\n🛑 Server stopped by user")
|
||||
except Exception as e:
|
||||
print(f"\n❌ Server error: {e}")
|
||||
|
||||
def setup_multiple_agents():
|
||||
"""
|
||||
Example of setting up multiple agents on the same server.
|
||||
"""
|
||||
print("🚀 Setting up Multiple Remote Agents")
|
||||
print("=" * 50)
|
||||
|
||||
# Create different specialized agents
|
||||
research_agent = Agent(
|
||||
name="ResearchAgent",
|
||||
role="Research Specialist",
|
||||
instructions="You are a research specialist who helps with finding and analyzing information."
|
||||
)
|
||||
|
||||
coding_agent = Agent(
|
||||
name="CodingAgent",
|
||||
role="Programming Assistant",
|
||||
instructions="You are a programming assistant who helps with coding questions and debugging."
|
||||
)
|
||||
|
||||
# Launch them on different endpoints
|
||||
print("🌐 Launching multiple agents:")
|
||||
print("📡 Research Agent: http://localhost:8000/research")
|
||||
print("📡 Coding Agent: http://localhost:8000/coding")
|
||||
print("\n🔗 Connect using:")
|
||||
print(" research_session = Session(agent_url='localhost:8000/research')")
|
||||
print(" coding_session = Session(agent_url='localhost:8000/coding')")
|
||||
|
||||
try:
|
||||
# Launch both agents (this will start the server)
|
||||
research_agent.launch(path="/research", port=8000, host="0.0.0.0")
|
||||
coding_agent.launch(path="/coding", port=8000, host="0.0.0.0")
|
||||
except KeyboardInterrupt:
|
||||
print("\n\n🛑 Server stopped by user")
|
||||
|
||||
if __name__ == "__main__":
|
||||
import sys
|
||||
|
||||
if len(sys.argv) > 1 and sys.argv[1] == "--multiple":
|
||||
setup_multiple_agents()
|
||||
else:
|
||||
setup_remote_agent_server()
|
||||
|
||||
print("\n\n✅ Remote agent server example completed!")
|
||||
print("💡 Tip: Use --multiple flag to run multiple agents example")
|
||||
@@ -368,11 +368,97 @@ class Agent:
|
||||
max_reflect: int = 3,
|
||||
min_reflect: int = 1,
|
||||
reflect_llm: Optional[str] = None,
|
||||
reflect_prompt: Optional[str] = None,
|
||||
user_id: Optional[str] = None,
|
||||
reasoning_steps: bool = False,
|
||||
guardrail: Optional[Union[Callable[['TaskOutput'], Tuple[bool, Any]], str]] = None,
|
||||
max_guardrail_retries: int = 3
|
||||
):
|
||||
"""Initialize an Agent instance.
|
||||
|
||||
Args:
|
||||
name (Optional[str], optional): Name of the agent used for identification and logging.
|
||||
If None, defaults to "Agent". Defaults to None.
|
||||
role (Optional[str], optional): Role or job title that defines the agent's expertise
|
||||
and behavior patterns. Examples: "Data Analyst", "Content Writer". Defaults to None.
|
||||
goal (Optional[str], optional): Primary objective or goal the agent aims to achieve.
|
||||
Defines the agent's purpose and success criteria. Defaults to None.
|
||||
backstory (Optional[str], optional): Background story or context that shapes the agent's
|
||||
personality and decision-making approach. Defaults to None.
|
||||
instructions (Optional[str], optional): Direct instructions that override role, goal,
|
||||
and backstory when provided. Used for simple, task-specific agents. Defaults to None.
|
||||
llm (Optional[Union[str, Any]], optional): Language model configuration. Can be a model
|
||||
name string (e.g., "gpt-4o", "anthropic/claude-3-sonnet") or a configured LLM object.
|
||||
Defaults to environment variable OPENAI_MODEL_NAME or "gpt-4o".
|
||||
tools (Optional[List[Any]], optional): List of tools, functions, or capabilities
|
||||
available to the agent for task execution. Can include callables, tool objects,
|
||||
or MCP instances. Defaults to None.
|
||||
function_calling_llm (Optional[Any], optional): Dedicated language model for function
|
||||
calling operations. If None, uses the main llm parameter. Defaults to None.
|
||||
max_iter (int, optional): Maximum number of iterations the agent can perform during
|
||||
task execution to prevent infinite loops. Defaults to 20.
|
||||
max_rpm (Optional[int], optional): Maximum requests per minute to rate limit API calls
|
||||
and prevent quota exhaustion. If None, no rate limiting is applied. Defaults to None.
|
||||
max_execution_time (Optional[int], optional): Maximum execution time in seconds for
|
||||
agent operations before timeout. If None, no time limit is enforced. Defaults to None.
|
||||
memory (Optional[Any], optional): Memory system for storing and retrieving information
|
||||
across conversations. Requires memory dependencies to be installed. Defaults to None.
|
||||
verbose (bool, optional): Enable detailed logging and status updates during agent
|
||||
execution for debugging and monitoring. Defaults to True.
|
||||
allow_delegation (bool, optional): Allow the agent to delegate tasks to other agents
|
||||
or sub-processes when appropriate. Defaults to False.
|
||||
step_callback (Optional[Any], optional): Callback function called after each step
|
||||
of agent execution for custom monitoring or intervention. Defaults to None.
|
||||
cache (bool, optional): Enable caching of responses and computations to improve
|
||||
performance and reduce API costs. Defaults to True.
|
||||
system_template (Optional[str], optional): Custom template for system prompts that
|
||||
overrides the default system prompt generation. Defaults to None.
|
||||
prompt_template (Optional[str], optional): Template for formatting user prompts
|
||||
before sending to the language model. Defaults to None.
|
||||
response_template (Optional[str], optional): Template for formatting agent responses
|
||||
before returning to the user. Defaults to None.
|
||||
allow_code_execution (Optional[bool], optional): Enable the agent to execute code
|
||||
snippets during task completion. Use with caution for security. Defaults to False.
|
||||
max_retry_limit (int, optional): Maximum number of retry attempts for failed operations
|
||||
before giving up. Helps handle transient errors. Defaults to 2.
|
||||
respect_context_window (bool, optional): Automatically manage context window size
|
||||
to prevent token limit errors with large conversations. Defaults to True.
|
||||
code_execution_mode (Literal["safe", "unsafe"], optional): Safety mode for code execution.
|
||||
"safe" restricts dangerous operations, "unsafe" allows full code execution. Defaults to "safe".
|
||||
embedder_config (Optional[Dict[str, Any]], optional): Configuration dictionary for
|
||||
text embedding models used in knowledge retrieval and similarity search. Defaults to None.
|
||||
knowledge (Optional[List[str]], optional): List of knowledge sources (file paths, URLs,
|
||||
or text content) to be processed and made available to the agent. Defaults to None.
|
||||
knowledge_config (Optional[Dict[str, Any]], optional): Configuration for knowledge
|
||||
processing and retrieval system including chunking and indexing parameters. Defaults to None.
|
||||
use_system_prompt (Optional[bool], optional): Whether to include system prompts in
|
||||
conversations to establish agent behavior and context. Defaults to True.
|
||||
markdown (bool, optional): Enable markdown formatting in agent responses for better
|
||||
readability and structure. Defaults to True.
|
||||
self_reflect (bool, optional): Enable self-reflection capabilities where the agent
|
||||
evaluates and improves its own responses. Defaults to False.
|
||||
max_reflect (int, optional): Maximum number of self-reflection iterations to prevent
|
||||
excessive reflection loops. Defaults to 3.
|
||||
min_reflect (int, optional): Minimum number of self-reflection iterations required
|
||||
before accepting a response as satisfactory. Defaults to 1.
|
||||
reflect_llm (Optional[str], optional): Dedicated language model for self-reflection
|
||||
operations. If None, uses the main llm parameter. Defaults to None.
|
||||
reflect_prompt (Optional[str], optional): Custom prompt template for self-reflection
|
||||
that guides the agent's self-evaluation process. Defaults to None.
|
||||
user_id (Optional[str], optional): Unique identifier for the user or session to
|
||||
enable personalized responses and memory isolation. Defaults to "praison".
|
||||
reasoning_steps (bool, optional): Enable step-by-step reasoning output to show the
|
||||
agent's thought process during problem solving. Defaults to False.
|
||||
guardrail (Optional[Union[Callable[['TaskOutput'], Tuple[bool, Any]], str]], optional):
|
||||
Safety mechanism to validate agent outputs. Can be a validation function or
|
||||
description string for LLM-based validation. Defaults to None.
|
||||
max_guardrail_retries (int, optional): Maximum number of retry attempts when guardrail
|
||||
validation fails before giving up. Defaults to 3.
|
||||
|
||||
Raises:
|
||||
ValueError: If all of name, role, goal, backstory, and instructions are None.
|
||||
ImportError: If memory or LLM features are requested but dependencies are not installed.
|
||||
"""
|
||||
# Add check at start if memory is requested
|
||||
if memory is not None:
|
||||
try:
|
||||
@@ -470,6 +556,7 @@ class Agent:
|
||||
self.markdown = markdown
|
||||
self.max_reflect = max_reflect
|
||||
self.min_reflect = min_reflect
|
||||
self.reflect_prompt = reflect_prompt
|
||||
# Use the same model selection logic for reflect_llm
|
||||
self.reflect_llm = reflect_llm or os.getenv('OPENAI_MODEL_NAME', 'gpt-4o')
|
||||
self.console = Console() # Create a single console instance for the agent
|
||||
@@ -1230,7 +1317,7 @@ Your Goal: {self.goal}
|
||||
|
||||
reflection_prompt = f"""
|
||||
Reflect on your previous response: '{response_text}'.
|
||||
Identify any flaws, improvements, or actions.
|
||||
{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'.
|
||||
"""
|
||||
@@ -1328,7 +1415,7 @@ Output MUST be JSON with 'reflection' and 'satisfactory'.
|
||||
return cleaned
|
||||
|
||||
async def achat(self, prompt: str, temperature=0.2, tools=None, output_json=None, output_pydantic=None, reasoning_steps=False):
|
||||
"""Async version of chat method. TODO: Requires Syncing with chat method."""
|
||||
"""Async version of chat method with self-reflection support."""
|
||||
# Log all parameter values when in debug mode
|
||||
if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
|
||||
param_info = {
|
||||
@@ -1501,10 +1588,79 @@ Your Goal: {self.goal}
|
||||
messages=messages,
|
||||
temperature=temperature
|
||||
)
|
||||
|
||||
response_text = response.choices[0].message.content
|
||||
|
||||
# Handle self-reflection if enabled
|
||||
if self.self_reflect:
|
||||
reflection_count = 0
|
||||
|
||||
while True:
|
||||
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'.
|
||||
"""
|
||||
|
||||
# Add reflection prompt to messages
|
||||
reflection_messages = messages + [
|
||||
{"role": "assistant", "content": response_text},
|
||||
{"role": "user", "content": reflection_prompt}
|
||||
]
|
||||
|
||||
try:
|
||||
reflection_response = await async_client.beta.chat.completions.parse(
|
||||
model=self.reflect_llm if self.reflect_llm else self.llm,
|
||||
messages=reflection_messages,
|
||||
temperature=temperature,
|
||||
response_format=ReflectionOutput
|
||||
)
|
||||
|
||||
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)
|
||||
|
||||
# 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)
|
||||
break
|
||||
|
||||
# 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)
|
||||
break
|
||||
|
||||
# Regenerate response based on reflection
|
||||
regenerate_messages = reflection_messages + [
|
||||
{"role": "assistant", "content": f"Self Reflection: {reflection_output.reflection} Satisfactory?: {reflection_output.satisfactory}"},
|
||||
{"role": "user", "content": "Now regenerate your response using the reflection you made"}
|
||||
]
|
||||
|
||||
new_response = await async_client.chat.completions.create(
|
||||
model=self.llm,
|
||||
messages=regenerate_messages,
|
||||
temperature=temperature
|
||||
)
|
||||
response_text = new_response.choices[0].message.content
|
||||
reflection_count += 1
|
||||
|
||||
except Exception as e:
|
||||
if self.verbose:
|
||||
display_error(f"Error in parsing self-reflection json {e}. Retrying", console=self.console)
|
||||
logging.error("Reflection parsing failed.", exc_info=True)
|
||||
reflection_count += 1
|
||||
if reflection_count >= self.max_reflect:
|
||||
break
|
||||
continue
|
||||
|
||||
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.choices[0].message.content
|
||||
return response_text
|
||||
except Exception as e:
|
||||
display_error(f"Error in chat completion: {e}")
|
||||
if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
|
||||
|
||||
@@ -7,6 +7,9 @@ session API for developers building stateful agent applications.
|
||||
|
||||
import os
|
||||
import uuid
|
||||
import requests
|
||||
import json
|
||||
import time
|
||||
from typing import Any, Dict, List, Optional
|
||||
from .agent import Agent
|
||||
from .memory import Memory
|
||||
@@ -22,68 +25,90 @@ class Session:
|
||||
- Memory operations (short-term, long-term, user-specific)
|
||||
- Knowledge base operations
|
||||
- Agent state management
|
||||
- Remote agent connectivity
|
||||
|
||||
Example:
|
||||
Examples:
|
||||
# Local session with agent
|
||||
session = Session(session_id="chat_123", user_id="user_456")
|
||||
agent = session.Agent(name="Assistant", role="Helpful AI")
|
||||
|
||||
# Create stateful agent
|
||||
agent = session.Agent(
|
||||
name="Assistant",
|
||||
role="Helpful AI",
|
||||
memory=True
|
||||
)
|
||||
# Remote agent session (similar to Google ADK)
|
||||
session = Session(agent_url="192.168.1.10:8000/agent")
|
||||
response = session.chat("Hello from remote client!")
|
||||
|
||||
# Save session state
|
||||
session.save_state({"conversation_topic": "AI research"})
|
||||
|
||||
# Restore state later
|
||||
session.restore_state()
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
session_id: Optional[str] = None,
|
||||
user_id: Optional[str] = None,
|
||||
agent_url: Optional[str] = None,
|
||||
memory_config: Optional[Dict[str, Any]] = None,
|
||||
knowledge_config: Optional[Dict[str, Any]] = None
|
||||
knowledge_config: Optional[Dict[str, Any]] = None,
|
||||
timeout: int = 30
|
||||
):
|
||||
"""
|
||||
Initialize a new session with optional persistence.
|
||||
Initialize a new session with optional persistence or remote agent connectivity.
|
||||
|
||||
Args:
|
||||
session_id: Unique session identifier. Auto-generated if None.
|
||||
user_id: User identifier for user-specific memory operations.
|
||||
agent_url: URL of remote agent for direct connectivity (e.g., "192.168.1.10:8000/agent")
|
||||
memory_config: Configuration for memory system (defaults to RAG)
|
||||
knowledge_config: Configuration for knowledge base system
|
||||
knowledge_config: Configuration for knowledge base system
|
||||
timeout: HTTP timeout for remote agent calls (default: 30 seconds)
|
||||
"""
|
||||
self.session_id = session_id or str(uuid.uuid4())[:8]
|
||||
self.user_id = user_id or "default_user"
|
||||
self.agent_url = agent_url
|
||||
self.timeout = timeout
|
||||
self.is_remote = agent_url is not None
|
||||
|
||||
# Initialize memory with sensible defaults
|
||||
default_memory_config = {
|
||||
"provider": "rag",
|
||||
"use_embedding": True,
|
||||
"rag_db_path": f".praison/sessions/{self.session_id}/chroma_db"
|
||||
}
|
||||
if memory_config:
|
||||
default_memory_config.update(memory_config)
|
||||
self.memory_config = default_memory_config
|
||||
# Validate agent_url format
|
||||
if self.is_remote:
|
||||
if not self.agent_url.startswith(('http://', 'https://')):
|
||||
# Assume http if no protocol specified
|
||||
self.agent_url = f"http://{self.agent_url}"
|
||||
# Test connectivity to remote agent
|
||||
self._test_remote_connection()
|
||||
|
||||
# Initialize knowledge with session-specific config
|
||||
default_knowledge_config = knowledge_config or {}
|
||||
self.knowledge_config = default_knowledge_config
|
||||
# Initialize memory with sensible defaults (only for local sessions)
|
||||
if not self.is_remote:
|
||||
default_memory_config = {
|
||||
"provider": "rag",
|
||||
"use_embedding": True,
|
||||
"rag_db_path": f".praison/sessions/{self.session_id}/chroma_db"
|
||||
}
|
||||
if memory_config:
|
||||
default_memory_config.update(memory_config)
|
||||
self.memory_config = default_memory_config
|
||||
|
||||
# Create session directory
|
||||
os.makedirs(f".praison/sessions/{self.session_id}", exist_ok=True)
|
||||
# Initialize knowledge with session-specific config
|
||||
default_knowledge_config = knowledge_config or {}
|
||||
self.knowledge_config = default_knowledge_config
|
||||
|
||||
# Initialize components lazily
|
||||
self._memory = None
|
||||
self._knowledge = None
|
||||
self._agents_instance = None
|
||||
# Create session directory
|
||||
os.makedirs(f".praison/sessions/{self.session_id}", exist_ok=True)
|
||||
|
||||
# Initialize components lazily
|
||||
self._memory = None
|
||||
self._knowledge = None
|
||||
self._agents_instance = None
|
||||
else:
|
||||
# For remote sessions, disable local memory/knowledge
|
||||
self.memory_config = {}
|
||||
self.knowledge_config = {}
|
||||
self._memory = None
|
||||
self._knowledge = None
|
||||
self._agents_instance = None
|
||||
|
||||
@property
|
||||
def memory(self) -> Memory:
|
||||
"""Lazy-loaded memory instance"""
|
||||
if self.is_remote:
|
||||
raise ValueError("Memory operations are not available for remote agent sessions")
|
||||
if self._memory is None:
|
||||
self._memory = Memory(config=self.memory_config)
|
||||
return self._memory
|
||||
@@ -91,6 +116,8 @@ class Session:
|
||||
@property
|
||||
def knowledge(self) -> Knowledge:
|
||||
"""Lazy-loaded knowledge instance"""
|
||||
if self.is_remote:
|
||||
raise ValueError("Knowledge operations are not available for remote agent sessions")
|
||||
if self._knowledge is None:
|
||||
self._knowledge = Knowledge(config=self.knowledge_config)
|
||||
return self._knowledge
|
||||
@@ -119,7 +146,13 @@ class Session:
|
||||
|
||||
Returns:
|
||||
Configured Agent instance
|
||||
|
||||
Raises:
|
||||
ValueError: If this is a remote session (use chat() instead)
|
||||
"""
|
||||
if self.is_remote:
|
||||
raise ValueError("Cannot create local agents in remote sessions. Use chat() to communicate with the remote agent.")
|
||||
|
||||
agent_kwargs = {
|
||||
"name": name,
|
||||
"role": role,
|
||||
@@ -150,7 +183,12 @@ class Session:
|
||||
|
||||
Args:
|
||||
state_data: Dictionary of state data to save
|
||||
|
||||
Raises:
|
||||
ValueError: If this is a remote session
|
||||
"""
|
||||
if self.is_remote:
|
||||
raise ValueError("State operations are not available for remote agent sessions")
|
||||
state_text = f"Session state: {state_data}"
|
||||
self.memory.store_short_term(
|
||||
text=state_text,
|
||||
@@ -168,7 +206,12 @@ class Session:
|
||||
|
||||
Returns:
|
||||
Dictionary of restored state data
|
||||
|
||||
Raises:
|
||||
ValueError: If this is a remote session
|
||||
"""
|
||||
if self.is_remote:
|
||||
raise ValueError("State operations are not available for remote agent sessions")
|
||||
# Use metadata-based search for better SQLite compatibility
|
||||
results = self.memory.search_short_term(
|
||||
query=f"type:session_state",
|
||||
@@ -284,7 +327,105 @@ class Session:
|
||||
max_items=max_items
|
||||
)
|
||||
|
||||
def _test_remote_connection(self) -> None:
|
||||
"""
|
||||
Test connectivity to the remote agent.
|
||||
|
||||
Raises:
|
||||
ConnectionError: If unable to connect to the remote agent
|
||||
"""
|
||||
try:
|
||||
# Try a simple GET request to check if the server is responding
|
||||
test_url = self.agent_url.rstrip('/') + '/health' if '/health' not in self.agent_url else self.agent_url
|
||||
response = requests.get(test_url, timeout=self.timeout)
|
||||
if response.status_code != 200:
|
||||
# If health endpoint fails, try the main endpoint
|
||||
response = requests.head(self.agent_url, timeout=self.timeout)
|
||||
if response.status_code not in [200, 405]: # 405 = Method Not Allowed is OK
|
||||
raise ConnectionError(f"Remote agent returned status code: {response.status_code}")
|
||||
print(f"✅ Successfully connected to remote agent at {self.agent_url}")
|
||||
except requests.exceptions.Timeout:
|
||||
raise ConnectionError(f"Timeout connecting to remote agent at {self.agent_url}")
|
||||
except requests.exceptions.ConnectionError:
|
||||
raise ConnectionError(f"Failed to connect to remote agent at {self.agent_url}")
|
||||
except Exception as e:
|
||||
raise ConnectionError(f"Error connecting to remote agent: {str(e)}")
|
||||
|
||||
def chat(self, message: str, **kwargs) -> str:
|
||||
"""
|
||||
Send a message to the remote agent or handle local session.
|
||||
|
||||
Args:
|
||||
message: The message to send to the agent
|
||||
**kwargs: Additional parameters for the request
|
||||
|
||||
Returns:
|
||||
The agent's response
|
||||
|
||||
Raises:
|
||||
ValueError: If this is not a remote session
|
||||
ConnectionError: If unable to communicate with remote agent
|
||||
"""
|
||||
if not self.is_remote:
|
||||
raise ValueError("chat() method is only available for remote agent sessions. Use Agent.chat() for local agents.")
|
||||
|
||||
try:
|
||||
# Prepare the request payload
|
||||
payload = {
|
||||
"query": message,
|
||||
"session_id": self.session_id,
|
||||
"user_id": self.user_id,
|
||||
**kwargs
|
||||
}
|
||||
|
||||
# Send POST request to the remote agent
|
||||
response = requests.post(
|
||||
self.agent_url,
|
||||
json=payload,
|
||||
headers={"Content-Type": "application/json"},
|
||||
timeout=self.timeout
|
||||
)
|
||||
|
||||
# Check if request was successful
|
||||
response.raise_for_status()
|
||||
|
||||
# Parse the response
|
||||
result = response.json()
|
||||
|
||||
# Extract the agent's response
|
||||
if isinstance(result, dict):
|
||||
return result.get("response", str(result))
|
||||
else:
|
||||
return str(result)
|
||||
|
||||
except requests.exceptions.Timeout:
|
||||
raise ConnectionError(f"Timeout communicating with remote agent at {self.agent_url}")
|
||||
except requests.exceptions.ConnectionError:
|
||||
raise ConnectionError(f"Failed to communicate with remote agent at {self.agent_url}")
|
||||
except requests.exceptions.HTTPError as e:
|
||||
raise ConnectionError(f"HTTP error from remote agent: {e}")
|
||||
except json.JSONDecodeError:
|
||||
# If response is not JSON, return the raw text
|
||||
return response.text
|
||||
except Exception as e:
|
||||
raise ConnectionError(f"Error communicating with remote agent: {str(e)}")
|
||||
|
||||
def send_message(self, message: str, **kwargs) -> str:
|
||||
"""
|
||||
Alias for chat() method to match Google ADK pattern.
|
||||
|
||||
Args:
|
||||
message: The message to send to the agent
|
||||
**kwargs: Additional parameters for the request
|
||||
|
||||
Returns:
|
||||
The agent's response
|
||||
"""
|
||||
return self.chat(message, **kwargs)
|
||||
|
||||
def __str__(self) -> str:
|
||||
if self.is_remote:
|
||||
return f"Session(id='{self.session_id}', user='{self.user_id}', remote_agent='{self.agent_url}')"
|
||||
return f"Session(id='{self.session_id}', user='{self.user_id}')"
|
||||
|
||||
def __repr__(self) -> str:
|
||||
|
||||
@@ -86,7 +86,9 @@ class MinimalTelemetry:
|
||||
self._posthog = Posthog(
|
||||
project_api_key='phc_skZpl3eFLQJ4iYjsERNMbCO6jfeSJi2vyZlPahKgxZ7',
|
||||
host='https://eu.i.posthog.com',
|
||||
disable_geoip=True
|
||||
disable_geoip=True,
|
||||
on_error=lambda e: self.logger.debug(f"PostHog error: {e}"),
|
||||
sync_mode=False # Use async mode to prevent blocking
|
||||
)
|
||||
except:
|
||||
self._posthog = None
|
||||
@@ -220,6 +222,7 @@ class MinimalTelemetry:
|
||||
'$geoip_disable': True
|
||||
}
|
||||
)
|
||||
# Don't flush here - let PostHog handle it asynchronously
|
||||
except:
|
||||
pass
|
||||
|
||||
@@ -227,6 +230,25 @@ class MinimalTelemetry:
|
||||
for key in self._metrics:
|
||||
if isinstance(self._metrics[key], int):
|
||||
self._metrics[key] = 0
|
||||
|
||||
def shutdown(self):
|
||||
"""
|
||||
Shutdown telemetry and ensure all events are sent.
|
||||
"""
|
||||
if not self.enabled:
|
||||
return
|
||||
|
||||
# Final flush
|
||||
self.flush()
|
||||
|
||||
# Shutdown PostHog if available
|
||||
if hasattr(self, '_posthog') and self._posthog:
|
||||
try:
|
||||
# Force a synchronous flush before shutdown
|
||||
self._posthog.flush()
|
||||
self._posthog.shutdown()
|
||||
except:
|
||||
pass
|
||||
|
||||
|
||||
# Global telemetry instance
|
||||
|
||||
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "praisonaiagents"
|
||||
version = "0.0.104"
|
||||
version = "0.0.106"
|
||||
description = "Praison AI agents for completing complex tasks with Self Reflection Agents"
|
||||
requires-python = ">=3.10"
|
||||
authors = [
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
pydantic
|
||||
rich
|
||||
openai>=1.30.0
|
||||
posthog>=3.0.0
|
||||
|
||||
# Memory dependencies
|
||||
chromadb>=0.5.23
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Test PostHog integration after fix.
|
||||
"""
|
||||
|
||||
import os
|
||||
import time
|
||||
|
||||
# Ensure telemetry is enabled
|
||||
for var in ['PRAISONAI_TELEMETRY_DISABLED', 'PRAISONAI_DISABLE_TELEMETRY', 'DO_NOT_TRACK']:
|
||||
if var in os.environ:
|
||||
del os.environ[var]
|
||||
|
||||
print("=== Testing PostHog Fix ===\n")
|
||||
|
||||
# Test PostHog directly first
|
||||
print("1. Testing PostHog directly:")
|
||||
try:
|
||||
from posthog import Posthog
|
||||
|
||||
# Create PostHog client
|
||||
ph = Posthog(
|
||||
project_api_key='phc_skZpl3eFLQJ4iYjsERNMbCO6jfeSJi2vyZlPahKgxZ7',
|
||||
host='https://eu.i.posthog.com'
|
||||
)
|
||||
|
||||
# Send test event
|
||||
ph.capture('test-user', 'direct_test', {'timestamp': time.time()})
|
||||
|
||||
# Flush and shutdown properly
|
||||
ph.flush()
|
||||
ph.shutdown()
|
||||
|
||||
print("✓ Direct PostHog test successful\n")
|
||||
except Exception as e:
|
||||
print(f"✗ Direct PostHog test failed: {e}\n")
|
||||
|
||||
# Test telemetry module
|
||||
print("2. Testing telemetry module:")
|
||||
from praisonaiagents.telemetry.telemetry import MinimalTelemetry
|
||||
|
||||
# Create telemetry instance
|
||||
telemetry = MinimalTelemetry(enabled=True)
|
||||
|
||||
# Track events
|
||||
telemetry.track_agent_execution("TestAgent", success=True)
|
||||
telemetry.track_task_completion("TestTask", success=True)
|
||||
telemetry.track_tool_usage("TestTool", success=True)
|
||||
|
||||
print(f"✓ Events tracked")
|
||||
print(f"✓ PostHog client available: {telemetry._posthog is not None}")
|
||||
|
||||
# Flush
|
||||
print("\n3. Flushing telemetry...")
|
||||
telemetry.flush()
|
||||
print("✓ Flush completed")
|
||||
|
||||
# Shutdown
|
||||
print("\n4. Shutting down telemetry...")
|
||||
telemetry.shutdown()
|
||||
print("✓ Shutdown completed")
|
||||
|
||||
print("\n=== Test Complete ===")
|
||||
print("\nPostHog should now be receiving data properly!")
|
||||
print("The fix adds:")
|
||||
print("1. posthog.flush() call in the flush() method")
|
||||
print("2. shutdown() method that properly closes the connection")
|
||||
Generated
+1
-1
@@ -2374,7 +2374,7 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "praisonaiagents"
|
||||
version = "0.0.104"
|
||||
version = "0.0.106"
|
||||
source = { editable = "." }
|
||||
dependencies = [
|
||||
{ name = "mcp" },
|
||||
|
||||
@@ -1,6 +1,16 @@
|
||||
OPENAI_MODEL_NAME="gpt-4o"
|
||||
# OpenAI / compatible API
|
||||
OPENAI_API_KEY="Enter your API key"
|
||||
OPENAI_MODEL_NAME="gpt-4o"
|
||||
OPENAI_API_BASE="https://api.openai.com/v1"
|
||||
|
||||
# AG2 framework (uses same OPENAI_* vars above, or override below)
|
||||
# MODEL_NAME=gpt-4o-mini
|
||||
|
||||
# AWS Bedrock (for ag2_bedrock.yaml example)
|
||||
# AWS_DEFAULT_REGION=us-east-1
|
||||
# AWS_ACCESS_KEY_ID=your-access-key
|
||||
# AWS_SECRET_ACCESS_KEY=your-secret-key
|
||||
|
||||
# Chainlit (optional)
|
||||
CHAINLIT_USERNAME=admin
|
||||
CHAINLIT_USERNAME=admin
|
||||
CHAINLIT_AUTH_SECRET="chainlit create-secret to create"
|
||||
CHAINLIT_AUTH_SECRET="chainlit create-secret to create"
|
||||
@@ -3,8 +3,8 @@ class Praisonai < Formula
|
||||
|
||||
desc "AI tools for various AI applications"
|
||||
homepage "https://github.com/MervinPraison/PraisonAI"
|
||||
url "https://github.com/MervinPraison/PraisonAI/archive/refs/tags/v2.2.31.tar.gz"
|
||||
sha256 `curl -sL https://github.com/MervinPraison/PraisonAI/archive/refs/tags/v2.2.31.tar.gz | shasum -a 256`.split.first
|
||||
url "https://github.com/MervinPraison/PraisonAI/archive/refs/tags/v2.2.33.tar.gz"
|
||||
sha256 `curl -sL https://github.com/MervinPraison/PraisonAI/archive/refs/tags/v2.2.33.tar.gz | shasum -a 256`.split.first
|
||||
license "MIT"
|
||||
|
||||
depends_on "[email protected]"
|
||||
|
||||
@@ -41,6 +41,16 @@ try:
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
AG2_AVAILABLE = False
|
||||
try:
|
||||
import importlib.metadata as _importlib_metadata
|
||||
_importlib_metadata.distribution('ag2')
|
||||
from autogen import LLMConfig as _AG2LLMConfig # noqa: F401 — AG2-exclusive class
|
||||
AG2_AVAILABLE = True
|
||||
del _AG2LLMConfig, _importlib_metadata
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
import agentops
|
||||
AGENTOPS_AVAILABLE = True
|
||||
@@ -51,7 +61,7 @@ except ImportError:
|
||||
pass
|
||||
|
||||
# Only try to import praisonai_tools if either CrewAI or AutoGen is available
|
||||
if CREWAI_AVAILABLE or AUTOGEN_AVAILABLE or PRAISONAI_AVAILABLE:
|
||||
if CREWAI_AVAILABLE or AUTOGEN_AVAILABLE or PRAISONAI_AVAILABLE or AG2_AVAILABLE:
|
||||
try:
|
||||
from praisonai_tools import (
|
||||
CodeDocsSearchTool, CSVSearchTool, DirectorySearchTool, DOCXSearchTool, DirectoryReadTool,
|
||||
@@ -127,6 +137,8 @@ class AgentsGenerator:
|
||||
raise ImportError("AutoGen is not installed. Please install it with 'pip install praisonai[autogen]'")
|
||||
elif framework == "praisonai" and not PRAISONAI_AVAILABLE:
|
||||
raise ImportError("PraisonAI is not installed. Please install it with 'pip install praisonaiagents'")
|
||||
elif framework == "ag2" and not AG2_AVAILABLE:
|
||||
raise ImportError("AG2 is not installed. Please install it with 'pip install praisonai[ag2]'")
|
||||
|
||||
def is_function_or_decorated(self, obj):
|
||||
"""
|
||||
@@ -274,7 +286,7 @@ class AgentsGenerator:
|
||||
tools_dict = {}
|
||||
|
||||
# Only try to use praisonai_tools if it's available and needed
|
||||
if PRAISONAI_TOOLS_AVAILABLE and (CREWAI_AVAILABLE or AUTOGEN_AVAILABLE or PRAISONAI_AVAILABLE):
|
||||
if PRAISONAI_TOOLS_AVAILABLE and (CREWAI_AVAILABLE or AUTOGEN_AVAILABLE or PRAISONAI_AVAILABLE or AG2_AVAILABLE):
|
||||
tools_dict = {
|
||||
'CodeDocsSearchTool': CodeDocsSearchTool(),
|
||||
'CSVSearchTool': CSVSearchTool(),
|
||||
@@ -327,6 +339,12 @@ class AgentsGenerator:
|
||||
if AGENTOPS_AVAILABLE:
|
||||
agentops.init(os.environ.get("AGENTOPS_API_KEY"), default_tags=["praisonai"])
|
||||
return self._run_praisonai(config, topic, tools_dict)
|
||||
elif framework == "ag2":
|
||||
if not AG2_AVAILABLE:
|
||||
raise ImportError("AG2 is not installed. Please install it with 'pip install praisonai[ag2]'")
|
||||
if AGENTOPS_AVAILABLE:
|
||||
agentops.init(os.environ.get("AGENTOPS_API_KEY"), default_tags=["ag2"])
|
||||
return self._run_ag2(config, topic, tools_dict)
|
||||
else: # framework=crewai
|
||||
if not CREWAI_AVAILABLE:
|
||||
raise ImportError("CrewAI is not installed. Please install it with 'pip install praisonai[crewai]'")
|
||||
@@ -407,6 +425,150 @@ class AgentsGenerator:
|
||||
|
||||
return result
|
||||
|
||||
def _run_ag2(self, config, topic, tools_dict):
|
||||
"""
|
||||
Run agents using the AG2 framework (community fork of AutoGen, PyPI: ag2).
|
||||
|
||||
AG2 installs under the 'autogen' namespace — there is no 'import ag2'.
|
||||
Uses LLMConfig context manager + AssistantAgent + GroupChat pattern.
|
||||
|
||||
Args:
|
||||
config (dict): Configuration dictionary parsed from YAML
|
||||
topic (str): The topic/task to process
|
||||
tools_dict (dict): Dictionary of available tools
|
||||
|
||||
Returns:
|
||||
str: Result prefixed with '### AG2 Output ###'
|
||||
"""
|
||||
import re
|
||||
from autogen import (
|
||||
AssistantAgent, UserProxyAgent, GroupChat, GroupChatManager, LLMConfig
|
||||
)
|
||||
|
||||
model_config = self.config_list[0] if self.config_list else {}
|
||||
|
||||
# Allow YAML top-level llm block to override config_list values
|
||||
yaml_llm = config.get("llm", {}) or {}
|
||||
# Also check first role's llm block as a fallback
|
||||
first_role_llm = {}
|
||||
for role_details in config.get("roles", {}).values():
|
||||
first_role_llm = role_details.get("llm", {}) or {}
|
||||
break
|
||||
|
||||
# Priority: YAML top-level llm > first role llm > config_list > env vars
|
||||
def _resolve(key, env_var=None, default=None):
|
||||
return (yaml_llm.get(key) or first_role_llm.get(key)
|
||||
or model_config.get(key)
|
||||
or (os.environ.get(env_var) if env_var else None)
|
||||
or default)
|
||||
|
||||
api_type = _resolve("api_type", default="openai").lower()
|
||||
model_name = _resolve("model", default="gpt-4o-mini")
|
||||
api_key = _resolve("api_key", env_var="OPENAI_API_KEY")
|
||||
# Fix #3: also check OPENAI_API_BASE for consistency with rest of codebase
|
||||
base_url = (model_config.get("base_url")
|
||||
or yaml_llm.get("base_url")
|
||||
or os.environ.get("OPENAI_BASE_URL")
|
||||
or os.environ.get("OPENAI_API_BASE"))
|
||||
|
||||
# Build LLMConfig — pass a config dict; Bedrock needs no api_key
|
||||
if api_type == "bedrock":
|
||||
llm_config_entry = {"api_type": "bedrock", "model": model_name}
|
||||
else:
|
||||
llm_config_entry = {"model": model_name}
|
||||
if api_key:
|
||||
llm_config_entry["api_key"] = api_key
|
||||
if base_url and base_url not in ("https://api.openai.com/v1", "https://api.openai.com/v1/"):
|
||||
llm_config_entry["base_url"] = base_url
|
||||
llm_config = LLMConfig(llm_config_entry)
|
||||
|
||||
user_proxy = UserProxyAgent(
|
||||
name="User",
|
||||
human_input_mode="NEVER",
|
||||
is_termination_msg=lambda x: "TERMINATE" in (x.get("content") or ""),
|
||||
code_execution_config=False,
|
||||
)
|
||||
|
||||
# Create one AssistantAgent per role, passing llm_config directly
|
||||
ag2_agent_entries = []
|
||||
for role, details in config["roles"].items():
|
||||
agent_name = details.get("role", role).replace("{topic}", topic)
|
||||
backstory = details.get("backstory", "").replace("{topic}", topic)
|
||||
agent_name_safe = re.sub(r"[^a-zA-Z0-9_\-]", "_", agent_name)
|
||||
assistant = AssistantAgent(
|
||||
name=agent_name_safe,
|
||||
system_message=backstory + "\nWhen the task is done, reply 'TERMINATE'.",
|
||||
llm_config=llm_config,
|
||||
)
|
||||
ag2_agent_entries.append((role, details, assistant))
|
||||
|
||||
# Register tools via AG2 decorator pattern
|
||||
for role, details, assistant in ag2_agent_entries:
|
||||
for tool_name in details.get("tools", []):
|
||||
tool = tools_dict.get(tool_name)
|
||||
if tool is None:
|
||||
continue
|
||||
func = tool if callable(tool) else getattr(tool, "run", None)
|
||||
if func is None:
|
||||
continue
|
||||
|
||||
def make_tool_fn(f):
|
||||
def tool_fn(**kwargs):
|
||||
return f(**kwargs) if callable(f) else str(f)
|
||||
tool_fn.__name__ = tool_name
|
||||
return tool_fn
|
||||
|
||||
wrapped = make_tool_fn(func)
|
||||
assistant.register_for_llm(description=f"Tool: {tool_name}")(wrapped)
|
||||
user_proxy.register_for_execution()(wrapped)
|
||||
|
||||
all_assistants = [a for _, _, a in ag2_agent_entries]
|
||||
if not all_assistants:
|
||||
return "### AG2 Output ###\nNo agents created from configuration."
|
||||
|
||||
# Build initial message from all task descriptions
|
||||
task_lines = []
|
||||
for role, details, _ in ag2_agent_entries:
|
||||
for task_name, task_details in details.get("tasks", {}).items():
|
||||
desc = task_details.get("description", "").replace("{topic}", topic)
|
||||
if desc:
|
||||
task_lines.append(desc)
|
||||
initial_message = "\n".join(task_lines) if task_lines else topic
|
||||
|
||||
groupchat = GroupChat(
|
||||
agents=[user_proxy] + all_assistants,
|
||||
messages=[],
|
||||
max_round=12,
|
||||
)
|
||||
manager = GroupChatManager(groupchat=groupchat, llm_config=llm_config)
|
||||
|
||||
try:
|
||||
chat_result = user_proxy.initiate_chat(manager, message=initial_message)
|
||||
except Exception as e:
|
||||
return f"### AG2 Error ###\n{str(e)}"
|
||||
|
||||
# Prefer ChatResult.summary if available, otherwise scan messages
|
||||
result_content = ""
|
||||
summary = getattr(chat_result, "summary", None)
|
||||
if summary and isinstance(summary, str) and summary.strip():
|
||||
result_content = re.sub(r'[\s\.\,]*TERMINATE[\s\.\,]*$', '', summary, flags=re.IGNORECASE).strip().rstrip('.')
|
||||
|
||||
if not result_content:
|
||||
for msg in reversed(groupchat.messages):
|
||||
# Skip the initial user proxy message
|
||||
if msg.get("name") == "User":
|
||||
continue
|
||||
content = (msg.get("content") or "").strip()
|
||||
if content:
|
||||
result_content = re.sub(r'[\s\.\,]*TERMINATE[\s\.\,]*$', '', content, flags=re.IGNORECASE).strip().rstrip('.')
|
||||
if result_content:
|
||||
break
|
||||
|
||||
if not result_content:
|
||||
result_content = "Task completed."
|
||||
|
||||
return f"### AG2 Output ###\n{result_content}"
|
||||
|
||||
def _run_crewai(self, config, topic, tools_dict):
|
||||
"""
|
||||
Run agents using the CrewAI framework.
|
||||
|
||||
@@ -32,6 +32,16 @@ try:
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
AG2_AVAILABLE = False
|
||||
try:
|
||||
import importlib.metadata as _importlib_metadata
|
||||
_importlib_metadata.distribution('ag2')
|
||||
from autogen import LLMConfig as _AG2LLMConfig # noqa: F401 — AG2-exclusive class
|
||||
AG2_AVAILABLE = True
|
||||
del _AG2LLMConfig, _importlib_metadata
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
from praisonai_tools import (
|
||||
CodeDocsSearchTool, CSVSearchTool, DirectorySearchTool, DOCXSearchTool,
|
||||
@@ -83,6 +93,11 @@ AutoGen is not installed. Please install with:
|
||||
Praisonai is not installed. Please install with:
|
||||
pip install praisonaiagents
|
||||
""")
|
||||
elif framework == "ag2" and not AG2_AVAILABLE:
|
||||
raise ImportError("""
|
||||
AG2 is not installed. Please install with:
|
||||
pip install "praisonai[ag2]"
|
||||
""")
|
||||
|
||||
# Only show tools message if using a framework and tools are needed
|
||||
if (framework in ["crewai", "autogen"]) and not PRAISONAI_TOOLS_AVAILABLE:
|
||||
|
||||
@@ -24,8 +24,8 @@ config_list = [
|
||||
agent_file = "test.yaml"
|
||||
|
||||
actions=[
|
||||
cl.Action(name="run", payload="run", label="✅ Run"),
|
||||
cl.Action(name="modify", payload="modify", label="🔧 Modify"),
|
||||
cl.Action(name="run", payload={"value": "run"}, label="run"),
|
||||
cl.Action(name="modify", payload={"value": "modify"}, label="Modify"),
|
||||
]
|
||||
|
||||
@cl.action_callback("run")
|
||||
|
||||
@@ -529,6 +529,7 @@ class PraisonAI:
|
||||
parser.add_argument("--call", action="store_true", help="Start the PraisonAI Call server")
|
||||
parser.add_argument("--public", action="store_true", help="Use ngrok to expose the server publicly (only with --call)")
|
||||
parser.add_argument("--merge", action="store_true", help="Merge existing agents.yaml with auto-generated agents instead of overwriting")
|
||||
parser.add_argument("--claudecode", action="store_true", help="Enable Claude Code integration for file modifications and coding tasks")
|
||||
|
||||
# If we're in a test environment, parse with empty args to avoid pytest interference
|
||||
if in_test_env:
|
||||
@@ -549,6 +550,10 @@ class PraisonAI:
|
||||
if args.command == 'code':
|
||||
args.ui = 'chainlit'
|
||||
args.code = True
|
||||
|
||||
# Handle --claudecode flag for code command
|
||||
if getattr(args, 'claudecode', False):
|
||||
os.environ["PRAISONAI_CLAUDECODE_ENABLED"] = "true"
|
||||
if args.command == 'realtime':
|
||||
args.realtime = True
|
||||
if args.command == 'call':
|
||||
|
||||
@@ -56,7 +56,7 @@ class CloudDeployer:
|
||||
file.write("FROM python:3.11-slim\n")
|
||||
file.write("WORKDIR /app\n")
|
||||
file.write("COPY . .\n")
|
||||
file.write("RUN pip install flask praisonai==2.2.31 gunicorn markdown\n")
|
||||
file.write("RUN pip install flask praisonai==2.2.33 gunicorn markdown\n")
|
||||
file.write("EXPOSE 8080\n")
|
||||
file.write('CMD ["gunicorn", "-b", "0.0.0.0:8080", "api:app"]\n')
|
||||
|
||||
|
||||
@@ -17,8 +17,8 @@ config_list = [
|
||||
]
|
||||
|
||||
actions = [
|
||||
cl.Action(name="run", payload="run", label="✅ Run"),
|
||||
cl.Action(name="modify", payload="modify", label="🔧 Modify"),
|
||||
cl.Action(name="run", payload={"value": "run"}, label="run"),
|
||||
cl.Action(name="modify", payload={"value": "modify"}, label="Modify"),
|
||||
]
|
||||
|
||||
@cl.action_callback("run")
|
||||
@@ -819,4 +819,4 @@ async def on_settings_update(settings):
|
||||
await on_settings_update(settings)
|
||||
except Exception as e:
|
||||
logger.error(f"Final retry failed: {str(e)}")
|
||||
await cl.Message(content=f"Failed to update settings after retries: {str(e)}").send()
|
||||
await cl.Message(content=f"Failed to update settings after retries: {str(e)}").send()
|
||||
@@ -13,16 +13,25 @@ from PIL import Image
|
||||
from context import ContextGatherer
|
||||
from tavily import TavilyClient
|
||||
from crawl4ai import AsyncWebCrawler
|
||||
import subprocess
|
||||
|
||||
# Local application/library imports
|
||||
import chainlit as cl
|
||||
from chainlit.input_widget import TextInput
|
||||
from chainlit.input_widget import TextInput, Switch
|
||||
from chainlit.types import ThreadDict
|
||||
import chainlit.data as cl_data
|
||||
from litellm import acompletion
|
||||
import litellm
|
||||
from db import DatabaseManager
|
||||
|
||||
# PraisonAI Agents imports
|
||||
try:
|
||||
from praisonaiagents import Agent
|
||||
PRAISONAI_AGENTS_AVAILABLE = True
|
||||
except ImportError:
|
||||
PRAISONAI_AGENTS_AVAILABLE = False
|
||||
# Fallback to litellm for backward compatibility
|
||||
from litellm import acompletion
|
||||
import litellm
|
||||
|
||||
# Load environment variables
|
||||
load_dotenv()
|
||||
|
||||
@@ -41,14 +50,131 @@ logger.addHandler(console_handler)
|
||||
# Set the logging level for the logger
|
||||
logger.setLevel(log_level)
|
||||
|
||||
# Configure litellm same as in llm.py
|
||||
litellm.set_verbose = False
|
||||
litellm.success_callback = []
|
||||
litellm._async_success_callback = []
|
||||
litellm.callbacks = []
|
||||
litellm.drop_params = True
|
||||
litellm.modify_params = True
|
||||
litellm.suppress_debug_messages = True
|
||||
# Configure litellm for backward compatibility (only if praisonaiagents not available)
|
||||
if not PRAISONAI_AGENTS_AVAILABLE:
|
||||
import litellm
|
||||
litellm.set_verbose = False
|
||||
litellm.success_callback = []
|
||||
litellm._async_success_callback = []
|
||||
litellm.callbacks = []
|
||||
litellm.drop_params = True
|
||||
litellm.modify_params = True
|
||||
litellm.suppress_debug_messages = True
|
||||
|
||||
# Claude Code Tool Function
|
||||
async def claude_code_tool(query: str) -> str:
|
||||
"""
|
||||
Execute Claude Code CLI commands for file modifications and coding tasks.
|
||||
|
||||
Args:
|
||||
query: The user's request that requires file modifications or coding assistance
|
||||
|
||||
Returns:
|
||||
The output from Claude Code execution
|
||||
"""
|
||||
try:
|
||||
# Check if the current working directory is a git repository
|
||||
repo_path = os.environ.get("PRAISONAI_CODE_REPO_PATH", ".")
|
||||
|
||||
# Try to detect if git is available and if we're in a git repo
|
||||
git_available = False
|
||||
try:
|
||||
subprocess.run(["git", "status"], cwd=repo_path, capture_output=True, check=True)
|
||||
git_available = True
|
||||
except (subprocess.CalledProcessError, FileNotFoundError):
|
||||
git_available = False
|
||||
|
||||
# Build Claude Code command
|
||||
claude_cmd = ["claude", "--dangerously-skip-permissions", "-p", query]
|
||||
|
||||
# Check if it's a continuation (simple heuristic)
|
||||
user_session_context = cl.user_session.get("claude_code_context", False)
|
||||
if user_session_context:
|
||||
claude_cmd.insert(1, "--continue")
|
||||
|
||||
# Execute Claude Code command
|
||||
result = subprocess.run(
|
||||
claude_cmd,
|
||||
cwd=repo_path,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=300 # 5 minutes timeout
|
||||
)
|
||||
|
||||
# Set context for future requests
|
||||
cl.user_session.set("claude_code_context", True)
|
||||
|
||||
output = result.stdout
|
||||
if result.stderr:
|
||||
output += f"\n\nErrors:\n{result.stderr}"
|
||||
|
||||
# If git is available and changes were made, try to create a branch and PR
|
||||
if git_available and result.returncode == 0:
|
||||
try:
|
||||
# Check for changes
|
||||
git_status = subprocess.run(
|
||||
["git", "status", "--porcelain"],
|
||||
cwd=repo_path,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=True
|
||||
)
|
||||
|
||||
if git_status.stdout.strip():
|
||||
# Create a branch for the changes
|
||||
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
branch_name = f"claude-code-{timestamp}"
|
||||
|
||||
# Create and switch to new branch
|
||||
subprocess.run(["git", "checkout", "-b", branch_name], cwd=repo_path, check=True)
|
||||
|
||||
# Add and commit changes
|
||||
subprocess.run(["git", "add", "."], cwd=repo_path, check=True)
|
||||
commit_message = f"Claude Code changes: {query[:50]}..."
|
||||
subprocess.run(
|
||||
["git", "commit", "-m", commit_message],
|
||||
cwd=repo_path,
|
||||
check=True
|
||||
)
|
||||
|
||||
# Push to remote (if configured)
|
||||
try:
|
||||
subprocess.run(
|
||||
["git", "push", "-u", "origin", branch_name],
|
||||
cwd=repo_path,
|
||||
check=True
|
||||
)
|
||||
|
||||
# Generate PR URL (assuming GitHub)
|
||||
remote_url = subprocess.run(
|
||||
["git", "config", "--get", "remote.origin.url"],
|
||||
cwd=repo_path,
|
||||
capture_output=True,
|
||||
text=True
|
||||
)
|
||||
|
||||
if remote_url.returncode == 0:
|
||||
repo_url = remote_url.stdout.strip()
|
||||
if repo_url.endswith(".git"):
|
||||
repo_url = repo_url[:-4]
|
||||
if "github.com" in repo_url:
|
||||
pr_url = f"{repo_url}/compare/main...{branch_name}?quick_pull=1"
|
||||
output += f"\n\n📋 **Pull Request Created:**\n{pr_url}"
|
||||
|
||||
except subprocess.CalledProcessError:
|
||||
output += f"\n\n🌲 **Branch created:** {branch_name} (push manually if needed)"
|
||||
|
||||
except subprocess.CalledProcessError as e:
|
||||
output += f"\n\nGit operations failed: {e}"
|
||||
|
||||
return output
|
||||
|
||||
except subprocess.TimeoutExpired:
|
||||
return "Claude Code execution timed out after 5 minutes."
|
||||
except subprocess.CalledProcessError as e:
|
||||
return f"Claude Code execution failed: {e}\nStdout: {e.stdout}\nStderr: {e.stderr}"
|
||||
except Exception as e:
|
||||
return f"Error executing Claude Code: {str(e)}"
|
||||
|
||||
CHAINLIT_AUTH_SECRET = os.getenv("CHAINLIT_AUTH_SECRET")
|
||||
|
||||
@@ -109,6 +235,12 @@ async def start():
|
||||
model_name = os.getenv("MODEL_NAME", "gpt-4o-mini")
|
||||
cl.user_session.set("model_name", model_name)
|
||||
logger.debug(f"Model name: {model_name}")
|
||||
|
||||
# Load Claude Code setting (check CLI flag first, then database setting)
|
||||
claude_code_enabled = os.getenv("PRAISONAI_CLAUDECODE_ENABLED", "false").lower() == "true"
|
||||
if not claude_code_enabled:
|
||||
claude_code_enabled = (load_setting("claude_code_enabled") or "false").lower() == "true"
|
||||
|
||||
settings = cl.ChatSettings(
|
||||
[
|
||||
TextInput(
|
||||
@@ -116,6 +248,11 @@ async def start():
|
||||
label="Enter the Model Name",
|
||||
placeholder="e.g., gpt-4o-mini",
|
||||
initial=model_name
|
||||
),
|
||||
Switch(
|
||||
id="claude_code_enabled",
|
||||
label="Enable Claude Code (file modifications & coding)",
|
||||
initial=claude_code_enabled
|
||||
)
|
||||
]
|
||||
)
|
||||
@@ -134,10 +271,13 @@ async def setup_agent(settings):
|
||||
logger.debug(settings)
|
||||
cl.user_session.set("settings", settings)
|
||||
model_name = settings["model_name"]
|
||||
claude_code_enabled = settings.get("claude_code_enabled", False)
|
||||
cl.user_session.set("model_name", model_name)
|
||||
cl.user_session.set("claude_code_enabled", claude_code_enabled)
|
||||
|
||||
# Save in settings table
|
||||
save_setting("model_name", model_name)
|
||||
save_setting("claude_code_enabled", str(claude_code_enabled).lower())
|
||||
|
||||
# Save in thread metadata
|
||||
thread_id = cl.user_session.get("thread_id")
|
||||
@@ -152,6 +292,7 @@ async def setup_agent(settings):
|
||||
metadata = {}
|
||||
|
||||
metadata["model_name"] = model_name
|
||||
metadata["claude_code_enabled"] = claude_code_enabled
|
||||
|
||||
# Always store metadata as a dictionary
|
||||
await cl_data._data_layer.update_thread(thread_id, metadata=metadata)
|
||||
@@ -221,6 +362,7 @@ tools = [{
|
||||
@cl.on_message
|
||||
async def main(message: cl.Message):
|
||||
model_name = load_setting("model_name") or os.getenv("MODEL_NAME") or "gpt-4o-mini"
|
||||
claude_code_enabled = cl.user_session.get("claude_code_enabled", False)
|
||||
message_history = cl.user_session.get("message_history", [])
|
||||
repo_path_to_use = os.environ.get("PRAISONAI_CODE_REPO_PATH", ".")
|
||||
gatherer = ContextGatherer(directory=repo_path_to_use)
|
||||
@@ -258,6 +400,87 @@ Context:
|
||||
msg = cl.Message(content="")
|
||||
await msg.send()
|
||||
|
||||
# Use PraisonAI Agents if available, otherwise fallback to litellm
|
||||
if PRAISONAI_AGENTS_AVAILABLE:
|
||||
await handle_with_praisonai_agents(message, user_message, model_name, claude_code_enabled, msg, image)
|
||||
else:
|
||||
await handle_with_litellm(user_message, model_name, message_history, msg, image)
|
||||
|
||||
async def handle_with_praisonai_agents(message, user_message, model_name, claude_code_enabled, msg, image):
|
||||
"""Handle message using PraisonAI Agents framework with optional Claude Code tool"""
|
||||
try:
|
||||
# Prepare tools list
|
||||
available_tools = []
|
||||
|
||||
# Add Tavily search tool if API key available
|
||||
if tavily_api_key:
|
||||
available_tools.append(tavily_web_search)
|
||||
|
||||
# Add Claude Code tool if enabled
|
||||
if claude_code_enabled:
|
||||
available_tools.append(claude_code_tool)
|
||||
|
||||
# Create agent instructions
|
||||
instructions = """You are a helpful AI assistant. Use the available tools when needed to provide comprehensive responses.
|
||||
|
||||
If Claude Code tool is available and the user's request involves:
|
||||
- File modifications, code changes, or implementation tasks
|
||||
- Creating, editing, or debugging code
|
||||
- Project setup or development tasks
|
||||
- Git operations or version control
|
||||
|
||||
Then use the Claude Code tool to handle those requests.
|
||||
|
||||
For informational questions, explanations, or general conversations, respond normally without using Claude Code."""
|
||||
|
||||
# Create agent
|
||||
agent = Agent(
|
||||
name="PraisonAI Assistant",
|
||||
instructions=instructions,
|
||||
llm=model_name,
|
||||
tools=available_tools if available_tools else None
|
||||
)
|
||||
|
||||
# Execute agent with streaming
|
||||
full_response = ""
|
||||
|
||||
# Use agent's streaming capabilities if available
|
||||
try:
|
||||
# For now, use synchronous execution and stream the result
|
||||
# TODO: Implement proper streaming when PraisonAI agents support it
|
||||
result = agent.start(user_message)
|
||||
|
||||
# Stream the response character by character for better UX
|
||||
if hasattr(result, 'raw'):
|
||||
response_text = result.raw
|
||||
else:
|
||||
response_text = str(result)
|
||||
|
||||
for char in response_text:
|
||||
await msg.stream_token(char)
|
||||
full_response += char
|
||||
# Small delay to make streaming visible
|
||||
await asyncio.sleep(0.01)
|
||||
|
||||
except Exception as e:
|
||||
error_response = f"Error executing agent: {str(e)}"
|
||||
for char in error_response:
|
||||
await msg.stream_token(char)
|
||||
full_response += char
|
||||
await asyncio.sleep(0.01)
|
||||
|
||||
msg.content = full_response
|
||||
await msg.update()
|
||||
|
||||
except Exception as e:
|
||||
error_msg = f"Failed to use PraisonAI Agents: {str(e)}"
|
||||
logger.error(error_msg)
|
||||
await msg.stream_token(error_msg)
|
||||
msg.content = error_msg
|
||||
await msg.update()
|
||||
|
||||
async def handle_with_litellm(user_message, model_name, message_history, msg, image):
|
||||
"""Fallback handler using litellm for backward compatibility"""
|
||||
# Prepare the completion parameters using the helper function
|
||||
completion_params = _build_completion_params(
|
||||
model_name,
|
||||
@@ -279,7 +502,7 @@ Context:
|
||||
]
|
||||
}
|
||||
# Use a vision-capable model when an image is present
|
||||
completion_params["model"] = "gpt-4-vision-preview" # Adjust this to your actual vision-capable model
|
||||
completion_params["model"] = "gpt-4-vision-preview"
|
||||
|
||||
# Only add tools and tool_choice if Tavily API key is available and no image is uploaded
|
||||
if tavily_api_key:
|
||||
@@ -412,6 +635,10 @@ async def send_count():
|
||||
async def on_chat_resume(thread: ThreadDict):
|
||||
logger.info(f"Resuming chat: {thread['id']}")
|
||||
model_name = load_setting("model_name") or os.getenv("MODEL_NAME") or "gpt-4o-mini"
|
||||
# Load Claude Code setting (check CLI flag first, then database setting)
|
||||
claude_code_enabled = os.getenv("PRAISONAI_CLAUDECODE_ENABLED", "false").lower() == "true"
|
||||
if not claude_code_enabled:
|
||||
claude_code_enabled = (load_setting("claude_code_enabled") or "false").lower() == "true"
|
||||
logger.debug(f"Model name: {model_name}")
|
||||
settings = cl.ChatSettings(
|
||||
[
|
||||
@@ -420,6 +647,11 @@ async def on_chat_resume(thread: ThreadDict):
|
||||
label="Enter the Model Name",
|
||||
placeholder="e.g., gpt-4o-mini",
|
||||
initial=model_name
|
||||
),
|
||||
Switch(
|
||||
id="claude_code_enabled",
|
||||
label="Enable Claude Code (file modifications & coding)",
|
||||
initial=claude_code_enabled
|
||||
)
|
||||
]
|
||||
)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "PraisonAI"
|
||||
version = "2.2.31"
|
||||
version = "2.2.33"
|
||||
description = "PraisonAI is an AI Agents Framework with Self Reflection. PraisonAI application combines PraisonAI Agents, AutoGen, and CrewAI into a low-code solution for building and managing multi-agent LLM systems, focusing on simplicity, customisation, and efficient human-agent collaboration."
|
||||
readme = "README.md"
|
||||
license = ""
|
||||
@@ -12,7 +12,7 @@ dependencies = [
|
||||
"rich>=13.7",
|
||||
"markdown>=3.5",
|
||||
"pyparsing>=3.0.0",
|
||||
"praisonaiagents>=0.0.104",
|
||||
"praisonaiagents>=0.0.106",
|
||||
"python-dotenv>=0.19.0",
|
||||
"instructor>=1.3.3",
|
||||
"PyYAML>=6.0",
|
||||
@@ -92,10 +92,11 @@ call = [
|
||||
train = []
|
||||
crewai = ["crewai>=0.32.0", "praisonai-tools>=0.0.15"]
|
||||
autogen = ["pyautogen>=0.2.19", "praisonai-tools>=0.0.15", "crewai"]
|
||||
ag2 = ["ag2>=0.11.0", "praisonai-tools>=0.0.15"]
|
||||
|
||||
[tool.poetry]
|
||||
name = "PraisonAI"
|
||||
version = "2.2.31"
|
||||
version = "2.2.33"
|
||||
description = "PraisonAI is an AI Agents Framework with Self Reflection. PraisonAI application combines PraisonAI Agents, AutoGen, and CrewAI into a low-code solution for building and managing multi-agent LLM systems, focusing on simplicity, customisation, and efficient human-agent collaboration."
|
||||
authors = ["Mervin Praison"]
|
||||
license = ""
|
||||
@@ -113,12 +114,13 @@ python = ">=3.10,<3.13"
|
||||
rich = ">=13.7"
|
||||
markdown = ">=3.5"
|
||||
pyparsing = ">=3.0.0"
|
||||
praisonaiagents = ">=0.0.104"
|
||||
praisonaiagents = ">=0.0.106"
|
||||
python-dotenv = ">=0.19.0"
|
||||
instructor = ">=1.3.3"
|
||||
PyYAML = ">=6.0"
|
||||
mcp = ">=1.6.0"
|
||||
pyautogen = {version = ">=0.2.19", optional = true}
|
||||
ag2 = {version = ">=0.11.0", optional = true}
|
||||
crewai = {version = ">=0.32.0", optional = true}
|
||||
praisonai-tools = {version = ">=0.0.15", optional = true}
|
||||
chainlit = {version = "==2.5.5", optional = true}
|
||||
@@ -277,6 +279,7 @@ call = [
|
||||
]
|
||||
crewai = ["crewai", "praisonai-tools"]
|
||||
autogen = ["pyautogen", "praisonai-tools", "crewai"]
|
||||
ag2 = ["ag2", "praisonai-tools"]
|
||||
|
||||
[tool.poetry-dynamic-versioning]
|
||||
enable = true
|
||||
|
||||
@@ -0,0 +1,291 @@
|
||||
# Claude Code Integration with PraisonAI Agents
|
||||
|
||||
This document describes the integration of Claude Code with PraisonAI Agents, allowing AI agents to intelligently decide when to use Claude Code for file modifications and coding tasks.
|
||||
|
||||
## Overview
|
||||
|
||||
The refactored implementation replaces direct `litellm` usage with `praisonaiagents`, making Claude Code a custom tool that the AI agent can choose to use based on the user's request. This provides better intelligence and flexibility while maintaining backward compatibility.
|
||||
|
||||
## Key Features
|
||||
|
||||
### 🤖 Agent-Driven Decision Making
|
||||
- AI agent intelligently decides when to use Claude Code vs. regular responses
|
||||
- No manual detection logic - the agent understands context
|
||||
- Automatic tool selection based on request type
|
||||
|
||||
### 🔧 Claude Code as a Custom Tool
|
||||
- Claude Code is implemented as a tool function for PraisonAI Agents
|
||||
- Executes `claude --dangerously-skip-permissions -p "query"`
|
||||
- Supports `--continue` flag for conversation continuity
|
||||
- Git operations with automatic branch creation and PR URLs
|
||||
|
||||
### ⚙️ Flexible Configuration
|
||||
- CLI flag: `praisonai code --claudecode`
|
||||
- UI toggle: "Enable Claude Code (file modifications & coding)"
|
||||
- Environment variable: `PRAISONAI_CLAUDECODE_ENABLED=true`
|
||||
|
||||
### 🔄 Backward Compatibility
|
||||
- Falls back to `litellm` if `praisonaiagents` is not available
|
||||
- Maintains all existing functionality
|
||||
- No breaking changes to existing workflows
|
||||
|
||||
## Architecture
|
||||
|
||||
### Agent Instructions
|
||||
|
||||
The agent receives these instructions to guide tool usage:
|
||||
|
||||
```
|
||||
You are a helpful AI assistant. Use the available tools when needed to provide comprehensive responses.
|
||||
|
||||
If Claude Code tool is available and the user's request involves:
|
||||
- File modifications, code changes, or implementation tasks
|
||||
- Creating, editing, or debugging code
|
||||
- Project setup or development tasks
|
||||
- Git operations or version control
|
||||
|
||||
Then use the Claude Code tool to handle those requests.
|
||||
|
||||
For informational questions, explanations, or general conversations, respond normally without using Claude Code.
|
||||
```
|
||||
|
||||
### Tool Function: `claude_code_tool`
|
||||
|
||||
```python
|
||||
async def claude_code_tool(query: str) -> str:
|
||||
"""
|
||||
Execute Claude Code CLI commands for file modifications and coding tasks.
|
||||
|
||||
Args:
|
||||
query: The user's request that requires file modifications or coding assistance
|
||||
|
||||
Returns:
|
||||
The output from Claude Code execution
|
||||
"""
|
||||
```
|
||||
|
||||
**Features:**
|
||||
- Executes Claude Code with `--dangerously-skip-permissions`
|
||||
- Supports conversation continuity with `--continue` flag
|
||||
- Automatic git branch creation and management
|
||||
- PR URL generation for GitHub repositories
|
||||
- 5-minute timeout for long operations
|
||||
- Comprehensive error handling
|
||||
|
||||
### Available Tools
|
||||
|
||||
When Claude Code is enabled, the agent has access to:
|
||||
|
||||
1. **Claude Code Tool** - For file modifications and coding tasks
|
||||
2. **Tavily Web Search** - For internet research (if API key configured)
|
||||
|
||||
The agent decides which tool(s) to use based on the user's request.
|
||||
|
||||
## Usage
|
||||
|
||||
### Command Line Interface
|
||||
|
||||
```bash
|
||||
# Enable Claude Code integration
|
||||
praisonai code --claudecode
|
||||
|
||||
# Use regular mode (no Claude Code)
|
||||
praisonai code
|
||||
```
|
||||
|
||||
### Environment Variables
|
||||
|
||||
```bash
|
||||
# Force enable Claude Code (overrides UI setting)
|
||||
export PRAISONAI_CLAUDECODE_ENABLED=true
|
||||
|
||||
# Set repository path (defaults to current directory)
|
||||
export PRAISONAI_CODE_REPO_PATH=/path/to/your/repo
|
||||
```
|
||||
|
||||
### UI Settings
|
||||
|
||||
In the PraisonAI Code UI, you can:
|
||||
- Toggle "Enable Claude Code (file modifications & coding)" switch
|
||||
- Setting is saved to database for persistence
|
||||
- CLI flag takes precedence over UI setting
|
||||
|
||||
## Examples
|
||||
|
||||
### File Modification Request
|
||||
**User:** "Create a new Python function to calculate fibonacci numbers"
|
||||
|
||||
**Agent Decision:** Uses Claude Code tool → Creates/modifies files → Returns implementation details
|
||||
|
||||
### Informational Request
|
||||
**User:** "How does fibonacci algorithm work?"
|
||||
|
||||
**Agent Decision:** Responds normally → Provides explanation without file modifications
|
||||
|
||||
### Mixed Request
|
||||
**User:** "Explain how sorting works and implement quicksort in Python"
|
||||
|
||||
**Agent Decision:** May use Claude Code tool for implementation → Provides both explanation and code files
|
||||
|
||||
## Git Integration
|
||||
|
||||
When Claude Code makes changes and git is available:
|
||||
|
||||
1. **Automatic Branch Creation:** Creates `claude-code-YYYYMMDD_HHMMSS` branch
|
||||
2. **Commit Changes:** Commits all modifications with descriptive message
|
||||
3. **Remote Push:** Pushes branch to remote repository (if configured)
|
||||
4. **PR URL Generation:** Generates GitHub PR creation URL
|
||||
|
||||
Example output:
|
||||
```
|
||||
📋 **Pull Request Created:**
|
||||
https://github.com/user/repo/compare/main...claude-code-20241210_143022?quick_pull=1
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
### Graceful Degradation
|
||||
- If `praisonaiagents` unavailable → Falls back to `litellm`
|
||||
- If Claude Code CLI unavailable → Agent works without the tool
|
||||
- If git unavailable → Code changes without git operations
|
||||
- Network issues → Continues with local operations
|
||||
|
||||
### Error Messages
|
||||
- Clear error reporting in streaming responses
|
||||
- Timeout handling for long operations
|
||||
- Detailed logging for debugging
|
||||
|
||||
## Implementation Details
|
||||
|
||||
### File Structure
|
||||
```
|
||||
src/praisonai/praisonai/
|
||||
├── cli.py # Added --claudecode flag
|
||||
└── ui/
|
||||
└── code.py # Refactored to use praisonaiagents
|
||||
```
|
||||
|
||||
### Key Functions
|
||||
|
||||
1. **`handle_with_praisonai_agents()`** - Main agent execution handler
|
||||
2. **`handle_with_litellm()`** - Fallback for backward compatibility
|
||||
3. **`claude_code_tool()`** - Claude Code tool implementation
|
||||
4. **Settings management** - UI toggles and persistence
|
||||
|
||||
### Dependencies
|
||||
|
||||
**Required:**
|
||||
- `praisonaiagents` - Core agent framework
|
||||
- `subprocess` - For Claude Code CLI execution
|
||||
- `chainlit` - UI framework
|
||||
|
||||
**Optional:**
|
||||
- `tavily` - Web search capability
|
||||
- `git` - Version control operations
|
||||
- `claude` CLI - File modification capabilities
|
||||
|
||||
## Testing
|
||||
|
||||
Use the included test script to verify the integration:
|
||||
|
||||
```bash
|
||||
python test_claude_code_integration.py
|
||||
```
|
||||
|
||||
Tests verify:
|
||||
- Import functionality
|
||||
- PraisonAI Agents availability
|
||||
- Claude Code CLI availability
|
||||
- Environment variable configuration
|
||||
- Basic tool execution
|
||||
|
||||
## Migration Guide
|
||||
|
||||
### From Previous Implementation
|
||||
|
||||
The previous implementation used direct Claude Code detection logic. The new implementation:
|
||||
|
||||
1. **Replaces detection logic** with agent intelligence
|
||||
2. **Maintains same UI/CLI interfaces** for easy migration
|
||||
3. **Preserves all existing functionality** while adding flexibility
|
||||
4. **Requires no user workflow changes**
|
||||
|
||||
### Upgrading
|
||||
|
||||
1. Ensure `praisonaiagents` is installed
|
||||
2. Update PraisonAI to include the refactored code
|
||||
3. Use `--claudecode` flag or UI toggle as before
|
||||
4. Existing settings and workflows continue working
|
||||
|
||||
## Best Practices
|
||||
|
||||
### When to Enable Claude Code
|
||||
- File modification projects
|
||||
- Code development workflows
|
||||
- Repository maintenance tasks
|
||||
- Implementation and debugging sessions
|
||||
|
||||
### When to Disable Claude Code
|
||||
- Read-only analysis
|
||||
- Documentation-only sessions
|
||||
- Learning and educational content
|
||||
- General Q&A conversations
|
||||
|
||||
### Configuration Recommendations
|
||||
- Use CLI flag for development sessions
|
||||
- Use UI toggle for mixed workflows
|
||||
- Set environment variables for CI/CD integration
|
||||
- Configure repository path for multi-project setups
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
**Agent doesn't use Claude Code tool:**
|
||||
- Verify Claude Code is enabled (`--claudecode` flag or UI toggle)
|
||||
- Check that request involves file modifications
|
||||
- Ensure `praisonaiagents` is installed
|
||||
|
||||
**Claude Code tool fails:**
|
||||
- Verify `claude` CLI is installed and in PATH
|
||||
- Check repository permissions
|
||||
- Confirm git repository status (if git operations needed)
|
||||
|
||||
**Fallback to litellm:**
|
||||
- Install `praisonaiagents`: `pip install praisonaiagents`
|
||||
- Check import errors in logs
|
||||
- Verify Python environment compatibility
|
||||
|
||||
### Debug Information
|
||||
|
||||
Enable verbose logging:
|
||||
```bash
|
||||
export LOGLEVEL=DEBUG
|
||||
praisonai code --claudecode
|
||||
```
|
||||
|
||||
Check environment:
|
||||
```python
|
||||
import os
|
||||
print("Claude Code enabled:", os.getenv("PRAISONAI_CLAUDECODE_ENABLED"))
|
||||
print("Repo path:", os.getenv("PRAISONAI_CODE_REPO_PATH"))
|
||||
```
|
||||
|
||||
## Future Enhancements
|
||||
|
||||
### Planned Features
|
||||
- Real-time streaming from PraisonAI Agents
|
||||
- Enhanced git workflow integration
|
||||
- Multi-repository support
|
||||
- Advanced tool coordination
|
||||
- Performance optimizations
|
||||
|
||||
### Extension Points
|
||||
- Additional coding tools integration
|
||||
- Custom agent instructions
|
||||
- Workflow templates
|
||||
- Integration with other development tools
|
||||
|
||||
---
|
||||
|
||||
For technical support or questions, please refer to the main PraisonAI documentation or submit issues to the repository.
|
||||
Whitespace-only changes.
@@ -0,0 +1,477 @@
|
||||
"""
|
||||
AG2 Mock Integration Tests — verifies PraisonAI correctly orchestrates AG2 agents.
|
||||
|
||||
Uses mocked AG2 responses — no real LLM API calls are made.
|
||||
Fast: all tests should complete in < 1s each.
|
||||
|
||||
Run:
|
||||
pytest tests/integration/ag2/test_ag2_integration.py -v
|
||||
"""
|
||||
|
||||
import pytest
|
||||
import os
|
||||
import sys
|
||||
from unittest.mock import patch, MagicMock
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../../../"))
|
||||
|
||||
# Stub heavy dependencies that auto.py (develop branch) imports at module level
|
||||
# so that tests can import praisonai without a full installation.
|
||||
for _stub in ("instructor",):
|
||||
if _stub not in sys.modules:
|
||||
sys.modules[_stub] = MagicMock()
|
||||
|
||||
import importlib as _importlib
|
||||
if "openai" not in sys.modules:
|
||||
try:
|
||||
_importlib.import_module("openai")
|
||||
except ImportError:
|
||||
_mock_openai = MagicMock()
|
||||
_mock_openai.__version__ = "1.0.0"
|
||||
sys.modules["openai"] = _mock_openai
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Fixtures
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@pytest.fixture
|
||||
def single_agent_yaml():
|
||||
return """
|
||||
framework: ag2
|
||||
topic: Write a short poem about Python
|
||||
roles:
|
||||
poet:
|
||||
role: "Creative Poet"
|
||||
goal: "Write elegant and concise poems"
|
||||
backstory: "You are a creative poet who loves Python and technology."
|
||||
tasks:
|
||||
write_poem:
|
||||
description: "Write a short 4-line poem about Python programming"
|
||||
expected_output: "A 4-line poem about Python"
|
||||
"""
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def multi_agent_yaml():
|
||||
return """
|
||||
framework: ag2
|
||||
topic: Explain why open-source AI matters
|
||||
roles:
|
||||
researcher:
|
||||
role: "Research Analyst"
|
||||
goal: "Research and gather key facts"
|
||||
backstory: "Expert in technology research and trend analysis."
|
||||
tasks:
|
||||
research:
|
||||
description: "Research why open-source AI matters"
|
||||
expected_output: "Key facts and data points"
|
||||
writer:
|
||||
role: "Technical Writer"
|
||||
goal: "Write clear technical content"
|
||||
backstory: "Professional technical writer with 10 years experience."
|
||||
tasks:
|
||||
write:
|
||||
description: "Write a clear explanation of why open-source AI matters"
|
||||
expected_output: "A 200-word explanation"
|
||||
"""
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_ag2_classes():
|
||||
"""Mock all AG2 classes used in _run_ag2."""
|
||||
mock_llm_config = MagicMock()
|
||||
mock_llm_config.__enter__ = MagicMock(return_value=mock_llm_config)
|
||||
mock_llm_config.__exit__ = MagicMock(return_value=False)
|
||||
|
||||
mock_assistant = MagicMock()
|
||||
mock_assistant.name = "test_agent"
|
||||
|
||||
mock_user_proxy = MagicMock()
|
||||
mock_user_proxy.name = "User"
|
||||
|
||||
mock_groupchat = MagicMock()
|
||||
mock_groupchat.messages = [
|
||||
{
|
||||
"name": "test_agent",
|
||||
"role": "assistant",
|
||||
"content": "Task completed successfully. TERMINATE",
|
||||
}
|
||||
]
|
||||
|
||||
mock_manager = MagicMock()
|
||||
|
||||
return {
|
||||
"llm_config": mock_llm_config,
|
||||
"assistant": mock_assistant,
|
||||
"user_proxy": mock_user_proxy,
|
||||
"groupchat": mock_groupchat,
|
||||
"manager": mock_manager,
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# AG2 import detection
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestAG2Import:
|
||||
|
||||
@pytest.mark.integration
|
||||
def test_ag2_distribution_available(self):
|
||||
"""ag2 PyPI distribution should be findable when installed.
|
||||
|
||||
Note: ag2 installs under the 'autogen' namespace — 'import ag2' does NOT work.
|
||||
Detection uses importlib.metadata to check the 'ag2' distribution name.
|
||||
"""
|
||||
import importlib.metadata
|
||||
try:
|
||||
dist = importlib.metadata.distribution('ag2')
|
||||
assert dist.metadata['Name'] == 'ag2'
|
||||
except importlib.metadata.PackageNotFoundError:
|
||||
pytest.skip("ag2 not installed — skipping AG2 integration tests")
|
||||
|
||||
@pytest.mark.integration
|
||||
def test_autogen_namespace_importable_with_ag2(self):
|
||||
"""When ag2 is installed, autogen namespace classes are importable."""
|
||||
try:
|
||||
from autogen import AssistantAgent, UserProxyAgent, GroupChat, LLMConfig
|
||||
assert AssistantAgent is not None
|
||||
assert UserProxyAgent is not None
|
||||
assert GroupChat is not None
|
||||
assert LLMConfig is not None
|
||||
except ImportError:
|
||||
pytest.skip("ag2 not installed — autogen namespace not available")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Single-agent flow (mocked)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestAG2SingleAgentFlow:
|
||||
|
||||
@pytest.mark.integration
|
||||
def test_single_agent_yaml_initialises_praisonai(self, single_agent_yaml, mock_ag2_classes):
|
||||
"""PraisonAI initialises correctly with framework='ag2' from YAML."""
|
||||
import tempfile
|
||||
|
||||
with tempfile.NamedTemporaryFile(mode="w", suffix=".yaml", delete=False) as f:
|
||||
f.write(single_agent_yaml)
|
||||
yaml_path = f.name
|
||||
|
||||
try:
|
||||
with patch("praisonai.agents_generator.AG2_AVAILABLE", True), \
|
||||
patch("praisonai.agents_generator.PRAISONAI_AVAILABLE", True):
|
||||
try:
|
||||
from praisonai import PraisonAI
|
||||
ai = PraisonAI(agent_file=yaml_path, framework="ag2")
|
||||
assert ai.framework == "ag2"
|
||||
except ImportError as e:
|
||||
pytest.skip(f"PraisonAI not available: {e}")
|
||||
finally:
|
||||
os.unlink(yaml_path)
|
||||
|
||||
@pytest.mark.integration
|
||||
def test_single_agent_run_returns_ag2_output(self, mock_ag2_classes):
|
||||
"""_run_ag2 executes single-agent flow and returns '### AG2 Output ###'."""
|
||||
config = {
|
||||
"framework": "ag2",
|
||||
"topic": "Write a poem",
|
||||
"roles": {
|
||||
"poet": {
|
||||
"role": "Creative Poet",
|
||||
"goal": "Write poems",
|
||||
"backstory": "A creative poet.",
|
||||
"tasks": {
|
||||
"task1": {
|
||||
"description": "Write a poem about Python",
|
||||
"expected_output": "A short poem",
|
||||
}
|
||||
},
|
||||
"tools": [],
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
m = mock_ag2_classes
|
||||
with patch("praisonai.agents_generator.AG2_AVAILABLE", True), \
|
||||
patch("praisonai.agents_generator.CREWAI_AVAILABLE", False), \
|
||||
patch("praisonai.agents_generator.AUTOGEN_AVAILABLE", False), \
|
||||
patch("praisonai.agents_generator.PRAISONAI_AVAILABLE", True):
|
||||
try:
|
||||
from praisonai.agents_generator import AgentsGenerator
|
||||
except ImportError as e:
|
||||
pytest.skip(f"AgentsGenerator not available: {e}")
|
||||
|
||||
gen = AgentsGenerator(
|
||||
agent_file="agents.yaml",
|
||||
framework="ag2",
|
||||
config_list=[{"model": "gpt-4o-mini", "api_key": "sk-test"}],
|
||||
)
|
||||
|
||||
with patch("autogen.LLMConfig", create=True, return_value=m["llm_config"]), \
|
||||
patch("autogen.AssistantAgent", create=True, return_value=m["assistant"]), \
|
||||
patch("autogen.UserProxyAgent", create=True, return_value=m["user_proxy"]), \
|
||||
patch("autogen.GroupChat", create=True, return_value=m["groupchat"]), \
|
||||
patch("autogen.GroupChatManager", create=True, return_value=m["manager"]):
|
||||
|
||||
result = gen._run_ag2(config, "Write a poem", {})
|
||||
|
||||
assert "### AG2 Output ###" in result
|
||||
assert "Task completed successfully" in result
|
||||
|
||||
@pytest.mark.integration
|
||||
def test_single_agent_calls_initiate_chat(self, mock_ag2_classes):
|
||||
"""user_proxy.initiate_chat is called with the manager and initial message."""
|
||||
config = {
|
||||
"framework": "ag2",
|
||||
"topic": "Test topic",
|
||||
"roles": {
|
||||
"agent": {
|
||||
"role": "Agent",
|
||||
"goal": "Help",
|
||||
"backstory": "Helpful agent.",
|
||||
"tasks": {
|
||||
"t": {"description": "Do the task", "expected_output": "Done"}
|
||||
},
|
||||
"tools": [],
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
m = mock_ag2_classes
|
||||
with patch("praisonai.agents_generator.AG2_AVAILABLE", True), \
|
||||
patch("praisonai.agents_generator.CREWAI_AVAILABLE", False), \
|
||||
patch("praisonai.agents_generator.AUTOGEN_AVAILABLE", False), \
|
||||
patch("praisonai.agents_generator.PRAISONAI_AVAILABLE", True):
|
||||
try:
|
||||
from praisonai.agents_generator import AgentsGenerator
|
||||
except ImportError as e:
|
||||
pytest.skip(f"AgentsGenerator not available: {e}")
|
||||
|
||||
gen = AgentsGenerator(
|
||||
agent_file="agents.yaml",
|
||||
framework="ag2",
|
||||
config_list=[{"model": "gpt-4o-mini", "api_key": "sk-test"}],
|
||||
)
|
||||
|
||||
with patch("autogen.LLMConfig", create=True, return_value=m["llm_config"]), \
|
||||
patch("autogen.AssistantAgent", create=True, return_value=m["assistant"]), \
|
||||
patch("autogen.UserProxyAgent", create=True, return_value=m["user_proxy"]), \
|
||||
patch("autogen.GroupChat", create=True, return_value=m["groupchat"]), \
|
||||
patch("autogen.GroupChatManager", create=True, return_value=m["manager"]):
|
||||
|
||||
gen._run_ag2(config, "Test topic", {})
|
||||
|
||||
m["user_proxy"].initiate_chat.assert_called_once()
|
||||
call_args = m["user_proxy"].initiate_chat.call_args
|
||||
# First positional arg should be the manager
|
||||
assert call_args[0][0] is m["manager"]
|
||||
# message kwarg should be non-empty (task description or topic)
|
||||
message = call_args[1].get("message", "")
|
||||
assert message != ""
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Multi-agent GroupChat flow (mocked)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestAG2MultiAgentGroupChatFlow:
|
||||
|
||||
@pytest.mark.integration
|
||||
def test_multi_agent_creates_correct_number_of_assistants(self, multi_agent_yaml, mock_ag2_classes):
|
||||
"""Two roles in YAML → two AssistantAgents created."""
|
||||
config = {
|
||||
"framework": "ag2",
|
||||
"topic": "Explain open-source AI",
|
||||
"roles": {
|
||||
"researcher": {
|
||||
"role": "Research Analyst", "goal": "Research", "backstory": "Analyst.",
|
||||
"tasks": {"r": {"description": "Research it", "expected_output": "Facts"}},
|
||||
"tools": [],
|
||||
},
|
||||
"writer": {
|
||||
"role": "Technical Writer", "goal": "Write", "backstory": "Writer.",
|
||||
"tasks": {"w": {"description": "Write it", "expected_output": "Article"}},
|
||||
"tools": [],
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
m = mock_ag2_classes
|
||||
assistant_call_count = [0]
|
||||
|
||||
def count_assistant(**kwargs):
|
||||
assistant_call_count[0] += 1
|
||||
a = MagicMock()
|
||||
a.name = kwargs.get("name", f"agent_{assistant_call_count[0]}")
|
||||
return a
|
||||
|
||||
with patch("praisonai.agents_generator.AG2_AVAILABLE", True), \
|
||||
patch("praisonai.agents_generator.CREWAI_AVAILABLE", False), \
|
||||
patch("praisonai.agents_generator.AUTOGEN_AVAILABLE", False), \
|
||||
patch("praisonai.agents_generator.PRAISONAI_AVAILABLE", True):
|
||||
try:
|
||||
from praisonai.agents_generator import AgentsGenerator
|
||||
except ImportError as e:
|
||||
pytest.skip(f"AgentsGenerator not available: {e}")
|
||||
|
||||
gen = AgentsGenerator(
|
||||
agent_file="agents.yaml",
|
||||
framework="ag2",
|
||||
config_list=[{"model": "gpt-4o-mini", "api_key": "sk-test"}],
|
||||
)
|
||||
|
||||
with patch("autogen.LLMConfig", create=True, return_value=m["llm_config"]), \
|
||||
patch("autogen.AssistantAgent", create=True, side_effect=count_assistant), \
|
||||
patch("autogen.UserProxyAgent", create=True, return_value=m["user_proxy"]), \
|
||||
patch("autogen.GroupChat", create=True, return_value=m["groupchat"]), \
|
||||
patch("autogen.GroupChatManager", create=True, return_value=m["manager"]):
|
||||
|
||||
gen._run_ag2(config, "Explain open-source AI", {})
|
||||
|
||||
assert assistant_call_count[0] == 2
|
||||
|
||||
@pytest.mark.integration
|
||||
def test_multi_agent_groupchat_max_round_set(self, mock_ag2_classes):
|
||||
"""GroupChat is created with max_round parameter."""
|
||||
config = {
|
||||
"framework": "ag2",
|
||||
"topic": "Test",
|
||||
"roles": {
|
||||
"a": {
|
||||
"role": "Agent", "goal": "Help", "backstory": "Helper.",
|
||||
"tasks": {"t": {"description": "Do", "expected_output": "Done"}},
|
||||
"tools": [],
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
m = mock_ag2_classes
|
||||
groupchat_kwargs = {}
|
||||
|
||||
def capture_groupchat(**kwargs):
|
||||
groupchat_kwargs.update(kwargs)
|
||||
return m["groupchat"]
|
||||
|
||||
with patch("praisonai.agents_generator.AG2_AVAILABLE", True), \
|
||||
patch("praisonai.agents_generator.CREWAI_AVAILABLE", False), \
|
||||
patch("praisonai.agents_generator.AUTOGEN_AVAILABLE", False), \
|
||||
patch("praisonai.agents_generator.PRAISONAI_AVAILABLE", True):
|
||||
try:
|
||||
from praisonai.agents_generator import AgentsGenerator
|
||||
except ImportError as e:
|
||||
pytest.skip(f"AgentsGenerator not available: {e}")
|
||||
|
||||
gen = AgentsGenerator(
|
||||
agent_file="agents.yaml",
|
||||
framework="ag2",
|
||||
config_list=[{"model": "gpt-4o-mini", "api_key": "sk-test"}],
|
||||
)
|
||||
|
||||
with patch("autogen.LLMConfig", create=True, return_value=m["llm_config"]), \
|
||||
patch("autogen.AssistantAgent", create=True, return_value=m["assistant"]), \
|
||||
patch("autogen.UserProxyAgent", create=True, return_value=m["user_proxy"]), \
|
||||
patch("autogen.GroupChat", create=True, side_effect=capture_groupchat), \
|
||||
patch("autogen.GroupChatManager", create=True, return_value=m["manager"]):
|
||||
|
||||
gen._run_ag2(config, "Test", {})
|
||||
|
||||
assert "max_round" in groupchat_kwargs
|
||||
assert groupchat_kwargs["max_round"] > 0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Backward-compatibility: existing autogen/crewai paths unaffected
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestAG2BackwardCompatibility:
|
||||
|
||||
@pytest.mark.integration
|
||||
def test_autogen_framework_still_works(self):
|
||||
"""framework='autogen' dispatches to _run_autogen, not _run_ag2."""
|
||||
import yaml
|
||||
|
||||
with patch("praisonai.agents_generator.AUTOGEN_AVAILABLE", True), \
|
||||
patch("praisonai.agents_generator.AG2_AVAILABLE", False), \
|
||||
patch("praisonai.agents_generator.CREWAI_AVAILABLE", False), \
|
||||
patch("praisonai.agents_generator.PRAISONAI_AVAILABLE", True):
|
||||
try:
|
||||
from praisonai.agents_generator import AgentsGenerator
|
||||
except ImportError as e:
|
||||
pytest.skip(f"AgentsGenerator not available: {e}")
|
||||
|
||||
gen = AgentsGenerator(
|
||||
agent_file="agents.yaml",
|
||||
framework="autogen",
|
||||
config_list=[{"model": "gpt-4o-mini", "api_key": "sk-test"}],
|
||||
)
|
||||
assert gen.framework == "autogen"
|
||||
|
||||
gen.agent_yaml = yaml.dump({
|
||||
"framework": "autogen",
|
||||
"topic": "Test",
|
||||
"roles": {
|
||||
"agent": {
|
||||
"role": "Agent", "goal": "Help", "backstory": "Helper.",
|
||||
"tasks": {"t": {"description": "Do", "expected_output": "Done"}},
|
||||
"tools": [],
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
# Verify _run_ag2 is NOT called when framework='autogen'
|
||||
with patch.object(gen, "_run_ag2") as mock_run_ag2, \
|
||||
patch.object(gen, "_run_autogen", return_value="autogen result") as mock_run_autogen:
|
||||
gen.generate_crew_and_kickoff()
|
||||
|
||||
mock_run_ag2.assert_not_called()
|
||||
mock_run_autogen.assert_called_once()
|
||||
|
||||
@pytest.mark.integration
|
||||
def test_ag2_framework_dispatches_to_run_ag2(self, mock_ag2_classes):
|
||||
"""framework='ag2' dispatches to _run_ag2 and NOT to _run_autogen."""
|
||||
import yaml
|
||||
|
||||
m = mock_ag2_classes
|
||||
with patch("praisonai.agents_generator.AG2_AVAILABLE", True), \
|
||||
patch("praisonai.agents_generator.CREWAI_AVAILABLE", False), \
|
||||
patch("praisonai.agents_generator.AUTOGEN_AVAILABLE", False), \
|
||||
patch("praisonai.agents_generator.PRAISONAI_AVAILABLE", True):
|
||||
try:
|
||||
from praisonai.agents_generator import AgentsGenerator
|
||||
except ImportError as e:
|
||||
pytest.skip(f"AgentsGenerator not available: {e}")
|
||||
|
||||
gen = AgentsGenerator(
|
||||
agent_file="agents.yaml",
|
||||
framework="ag2",
|
||||
config_list=[{"model": "gpt-4o-mini", "api_key": "sk-test"}],
|
||||
)
|
||||
|
||||
gen.agent_yaml = yaml.dump({
|
||||
"framework": "ag2",
|
||||
"topic": "Test",
|
||||
"roles": {
|
||||
"agent": {
|
||||
"role": "Agent", "goal": "Help", "backstory": "Helper.",
|
||||
"tasks": {"t": {"description": "Do", "expected_output": "Done"}},
|
||||
"tools": [],
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
with patch.object(gen, "_run_autogen") as mock_autogen, \
|
||||
patch("autogen.LLMConfig", create=True, return_value=m["llm_config"]), \
|
||||
patch("autogen.AssistantAgent", create=True, return_value=m["assistant"]), \
|
||||
patch("autogen.UserProxyAgent", create=True, return_value=m["user_proxy"]), \
|
||||
patch("autogen.GroupChat", create=True, return_value=m["groupchat"]), \
|
||||
patch("autogen.GroupChatManager", create=True, return_value=m["manager"]):
|
||||
|
||||
result = gen.generate_crew_and_kickoff()
|
||||
|
||||
mock_autogen.assert_not_called()
|
||||
assert "### AG2 Output ###" in result
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
pytest.main([__file__, "-v"])
|
||||
@@ -0,0 +1,98 @@
|
||||
"""
|
||||
Example of AG2 tool registration for use with PraisonAI's --framework ag2.
|
||||
|
||||
AG2 (community fork of AutoGen, PyPI package: ag2) installs under the
|
||||
'autogen' namespace but is a distinct package from pyautogen/pyautogen2.
|
||||
|
||||
Usage with PraisonAI:
|
||||
pip install "praisonai[ag2]"
|
||||
praisonai --framework ag2 agents.yaml
|
||||
|
||||
Standalone run:
|
||||
python tests/source/ag2_function_tools.py
|
||||
"""
|
||||
from typing import Annotated, Literal
|
||||
import os
|
||||
|
||||
# ag2 installs under the 'autogen' namespace
|
||||
from autogen import (
|
||||
AssistantAgent,
|
||||
UserProxyAgent,
|
||||
GroupChat,
|
||||
GroupChatManager,
|
||||
LLMConfig,
|
||||
)
|
||||
|
||||
Operator = Literal["+", "-", "*", "/"]
|
||||
|
||||
|
||||
def calculator(
|
||||
a: Annotated[int, "First operand"],
|
||||
b: Annotated[int, "Second operand"],
|
||||
operator: Annotated[Operator, "Arithmetic operator: +, -, *, /"],
|
||||
) -> int:
|
||||
"""Perform basic arithmetic operations."""
|
||||
if operator == "+":
|
||||
return a + b
|
||||
elif operator == "-":
|
||||
return a - b
|
||||
elif operator == "*":
|
||||
return a * b
|
||||
elif operator == "/":
|
||||
if b == 0:
|
||||
raise ValueError("Division by zero")
|
||||
return int(a / b)
|
||||
else:
|
||||
raise ValueError(f"Invalid operator: {operator}")
|
||||
|
||||
|
||||
# Build LLMConfig — AG2 uses a context manager pattern so agents
|
||||
# created inside the 'with' block automatically inherit the config.
|
||||
llm_config = LLMConfig(
|
||||
api_type="openai",
|
||||
model=os.environ.get("MODEL_NAME", "gpt-4o-mini"),
|
||||
api_key=os.environ.get("OPENAI_API_KEY"),
|
||||
)
|
||||
|
||||
# Create AssistantAgent inside llm_config context
|
||||
with llm_config:
|
||||
assistant = AssistantAgent(
|
||||
name="Calculator_Assistant",
|
||||
system_message=(
|
||||
"You are a helpful AI assistant that can perform arithmetic calculations. "
|
||||
"Use the calculator tool when math operations are needed. "
|
||||
"Return 'TERMINATE' when the task is done."
|
||||
),
|
||||
)
|
||||
|
||||
# UserProxyAgent does not use LLM — created outside context
|
||||
user_proxy = UserProxyAgent(
|
||||
name="User",
|
||||
human_input_mode="NEVER",
|
||||
is_termination_msg=lambda msg: (
|
||||
msg.get("content") is not None and "TERMINATE" in msg["content"]
|
||||
),
|
||||
code_execution_config=False,
|
||||
)
|
||||
|
||||
# AG2 tool registration pattern:
|
||||
# @agent.register_for_llm(description="...") — exposes tool schema to the LLM
|
||||
# @user_proxy.register_for_execution() — tells user_proxy to execute it
|
||||
|
||||
|
||||
@assistant.register_for_llm(description="A simple calculator for arithmetic operations.")
|
||||
@user_proxy.register_for_execution()
|
||||
def calculator_tool(
|
||||
a: Annotated[int, "First operand"],
|
||||
b: Annotated[int, "Second operand"],
|
||||
operator: Annotated[Operator, "Arithmetic operator"],
|
||||
) -> int:
|
||||
return calculator(a, b, operator)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
chat_result = user_proxy.initiate_chat(
|
||||
assistant,
|
||||
message="What is (44232 + 13312 / (232 - 32)) * 5?",
|
||||
)
|
||||
print(f"\nResult: {chat_result.summary}")
|
||||
@@ -0,0 +1,542 @@
|
||||
"""
|
||||
Unit tests for the AG2 framework integration in PraisonAI.
|
||||
|
||||
Tests cover:
|
||||
- AG2 availability detection (AG2_AVAILABLE flag)
|
||||
- Framework validation in AgentsGenerator.__init__
|
||||
- _run_ag2 method: config parsing, agent creation, tool handling
|
||||
- LLMConfig construction (OpenAI and Bedrock paths)
|
||||
|
||||
All external calls are mocked — no real LLM API calls made.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
import os
|
||||
import sys
|
||||
from unittest.mock import patch, MagicMock, call
|
||||
import importlib
|
||||
|
||||
# Ensure src is on path
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../../"))
|
||||
|
||||
# Stub heavy dependencies that auto.py (develop branch) imports at module level
|
||||
# so that tests can import praisonai without a full installation.
|
||||
for _stub in ("instructor",):
|
||||
if _stub not in sys.modules:
|
||||
sys.modules[_stub] = MagicMock()
|
||||
|
||||
# openai is installed (required by ag2/autogen internals), but auto.py also
|
||||
# imports it at module level. Ensure it's really loaded, not a mock.
|
||||
import importlib as _importlib
|
||||
if "openai" not in sys.modules:
|
||||
try:
|
||||
_importlib.import_module("openai")
|
||||
except ImportError:
|
||||
_mock_openai = MagicMock()
|
||||
_mock_openai.__version__ = "1.0.0"
|
||||
sys.modules["openai"] = _mock_openai
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _make_config(roles=None, framework="ag2", topic="Test topic"):
|
||||
"""Build a minimal agents config dict."""
|
||||
if roles is None:
|
||||
roles = {
|
||||
"researcher": {
|
||||
"role": "Researcher",
|
||||
"goal": "Research things",
|
||||
"backstory": "You are a researcher.",
|
||||
"tasks": {
|
||||
"task1": {
|
||||
"description": "Research {topic}",
|
||||
"expected_output": "A research report",
|
||||
}
|
||||
},
|
||||
"tools": [],
|
||||
}
|
||||
}
|
||||
return {"framework": framework, "topic": topic, "roles": roles}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# AG2_AVAILABLE flag detection
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestAG2AvailabilityFlag:
|
||||
|
||||
def test_ag2_available_false_when_not_installed(self):
|
||||
"""AG2_AVAILABLE is False when 'ag2' distribution is not found."""
|
||||
import importlib.metadata as meta
|
||||
original_fn = meta.distribution
|
||||
|
||||
def raise_not_found(name):
|
||||
if name == 'ag2':
|
||||
raise meta.PackageNotFoundError('ag2')
|
||||
return original_fn(name)
|
||||
|
||||
# Verify detection logic directly without relying on cached module state
|
||||
ag2_detected = True
|
||||
try:
|
||||
with patch('importlib.metadata.distribution', side_effect=raise_not_found):
|
||||
meta.distribution('ag2')
|
||||
except meta.PackageNotFoundError:
|
||||
ag2_detected = False
|
||||
assert ag2_detected is False
|
||||
|
||||
def test_ag2_available_true_when_installed(self):
|
||||
"""AG2_AVAILABLE is True when 'ag2' distribution and LLMConfig are present."""
|
||||
import importlib.metadata as meta
|
||||
try:
|
||||
dist = meta.distribution('ag2')
|
||||
assert dist is not None
|
||||
from autogen import LLMConfig # noqa: F401
|
||||
except (meta.PackageNotFoundError, ImportError):
|
||||
pytest.skip("ag2 not installed — skipping")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# AgentsGenerator.__init__ framework validation
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestAgentsGeneratorAG2Validation:
|
||||
|
||||
def _make_generator(self, framework, ag2_available=True):
|
||||
"""Create AgentsGenerator with mocked availability flags."""
|
||||
with patch("praisonai.agents_generator.AG2_AVAILABLE", ag2_available), \
|
||||
patch("praisonai.agents_generator.CREWAI_AVAILABLE", False), \
|
||||
patch("praisonai.agents_generator.AUTOGEN_AVAILABLE", False), \
|
||||
patch("praisonai.agents_generator.PRAISONAI_AVAILABLE", True):
|
||||
from praisonai.agents_generator import AgentsGenerator
|
||||
return AgentsGenerator(
|
||||
agent_file="agents.yaml",
|
||||
framework=framework,
|
||||
config_list=[{"model": "gpt-4o-mini", "api_key": "test-key"}],
|
||||
)
|
||||
|
||||
def test_ag2_framework_accepted_when_available(self):
|
||||
"""No ImportError when framework='ag2' and AG2 is installed."""
|
||||
gen = self._make_generator("ag2", ag2_available=True)
|
||||
assert gen.framework == "ag2"
|
||||
|
||||
def test_ag2_framework_raises_when_not_available(self):
|
||||
"""ImportError raised with helpful message when ag2 not installed."""
|
||||
with pytest.raises(ImportError, match="AG2 is not installed"):
|
||||
self._make_generator("ag2", ag2_available=False)
|
||||
|
||||
def test_autogen_framework_unaffected(self):
|
||||
"""Existing autogen framework path still works independently."""
|
||||
with patch("praisonai.agents_generator.AG2_AVAILABLE", False), \
|
||||
patch("praisonai.agents_generator.AUTOGEN_AVAILABLE", True), \
|
||||
patch("praisonai.agents_generator.CREWAI_AVAILABLE", False), \
|
||||
patch("praisonai.agents_generator.PRAISONAI_AVAILABLE", True):
|
||||
from praisonai.agents_generator import AgentsGenerator
|
||||
gen = AgentsGenerator(
|
||||
agent_file="agents.yaml",
|
||||
framework="autogen",
|
||||
config_list=[{"model": "gpt-4o-mini", "api_key": "test-key"}],
|
||||
)
|
||||
assert gen.framework == "autogen"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# _run_ag2: LLMConfig construction
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestRunAG2LLMConfig:
|
||||
|
||||
def _make_gen_with_config(self, config_list):
|
||||
"""Build an AgentsGenerator instance with given config_list."""
|
||||
with patch("praisonai.agents_generator.AG2_AVAILABLE", True), \
|
||||
patch("praisonai.agents_generator.CREWAI_AVAILABLE", False), \
|
||||
patch("praisonai.agents_generator.AUTOGEN_AVAILABLE", False), \
|
||||
patch("praisonai.agents_generator.PRAISONAI_AVAILABLE", True):
|
||||
from praisonai.agents_generator import AgentsGenerator
|
||||
return AgentsGenerator(
|
||||
agent_file="agents.yaml",
|
||||
framework="ag2",
|
||||
config_list=config_list,
|
||||
)
|
||||
|
||||
@patch("praisonai.agents_generator.AG2_AVAILABLE", True)
|
||||
def test_openai_llm_config_constructed(self):
|
||||
"""LLMConfig is built with api_type='openai' for standard config."""
|
||||
gen = self._make_gen_with_config([
|
||||
{"model": "gpt-4o-mini", "api_key": "sk-test", "api_type": "openai"}
|
||||
])
|
||||
|
||||
mock_llm_config = MagicMock()
|
||||
mock_llm_config.__enter__ = MagicMock(return_value=mock_llm_config)
|
||||
mock_llm_config.__exit__ = MagicMock(return_value=False)
|
||||
|
||||
mock_assistant = MagicMock()
|
||||
mock_user_proxy = MagicMock()
|
||||
mock_groupchat = MagicMock()
|
||||
mock_groupchat.messages = [{"name": "Researcher", "content": "Done. TERMINATE", "role": "assistant"}]
|
||||
mock_manager = MagicMock()
|
||||
|
||||
with patch("praisonai.agents_generator.AG2_AVAILABLE", True), \
|
||||
patch("autogen.LLMConfig", create=True, return_value=mock_llm_config) as mock_llmcfg, \
|
||||
patch("autogen.AssistantAgent", create=True, return_value=mock_assistant), \
|
||||
patch("autogen.UserProxyAgent", create=True, return_value=mock_user_proxy), \
|
||||
patch("autogen.GroupChat", create=True, return_value=mock_groupchat), \
|
||||
patch("autogen.GroupChatManager", create=True, return_value=mock_manager):
|
||||
|
||||
config = _make_config()
|
||||
gen._run_ag2(config, "Test topic", {})
|
||||
|
||||
mock_llmcfg.assert_called_once()
|
||||
# LLMConfig is called with a positional dict arg
|
||||
call_args = mock_llmcfg.call_args[0][0]
|
||||
assert call_args.get("model") == "gpt-4o-mini"
|
||||
assert call_args.get("api_key") == "sk-test"
|
||||
|
||||
@patch("praisonai.agents_generator.AG2_AVAILABLE", True)
|
||||
def test_bedrock_llm_config_constructed(self):
|
||||
"""LLMConfig uses api_type='bedrock' when config specifies bedrock."""
|
||||
gen = self._make_gen_with_config([
|
||||
{
|
||||
"model": "anthropic.claude-3-5-sonnet-20241022-v2:0",
|
||||
"api_type": "bedrock",
|
||||
}
|
||||
])
|
||||
|
||||
mock_llm_config = MagicMock()
|
||||
mock_llm_config.__enter__ = MagicMock(return_value=mock_llm_config)
|
||||
mock_llm_config.__exit__ = MagicMock(return_value=False)
|
||||
|
||||
mock_assistant = MagicMock()
|
||||
mock_user_proxy = MagicMock()
|
||||
mock_groupchat = MagicMock()
|
||||
mock_groupchat.messages = [{"name": "Agent", "content": "Report ready. TERMINATE", "role": "assistant"}]
|
||||
mock_manager = MagicMock()
|
||||
|
||||
with patch("autogen.LLMConfig", create=True, return_value=mock_llm_config) as mock_llmcfg, \
|
||||
patch("autogen.AssistantAgent", create=True, return_value=mock_assistant), \
|
||||
patch("autogen.UserProxyAgent", create=True, return_value=mock_user_proxy), \
|
||||
patch("autogen.GroupChat", create=True, return_value=mock_groupchat), \
|
||||
patch("autogen.GroupChatManager", create=True, return_value=mock_manager):
|
||||
|
||||
config = _make_config()
|
||||
gen._run_ag2(config, "AWS deployment", {})
|
||||
|
||||
mock_llmcfg.assert_called_once()
|
||||
# LLMConfig is called with a positional dict arg
|
||||
call_args = mock_llmcfg.call_args[0][0]
|
||||
assert call_args.get("api_type") == "bedrock"
|
||||
assert "api_key" not in call_args # no api_key for bedrock
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# _run_ag2: agent and GroupChat creation
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestRunAG2AgentCreation:
|
||||
|
||||
def _make_gen(self):
|
||||
with patch("praisonai.agents_generator.AG2_AVAILABLE", True), \
|
||||
patch("praisonai.agents_generator.CREWAI_AVAILABLE", False), \
|
||||
patch("praisonai.agents_generator.AUTOGEN_AVAILABLE", False), \
|
||||
patch("praisonai.agents_generator.PRAISONAI_AVAILABLE", True):
|
||||
from praisonai.agents_generator import AgentsGenerator
|
||||
return AgentsGenerator(
|
||||
agent_file="agents.yaml",
|
||||
framework="ag2",
|
||||
config_list=[{"model": "gpt-4o-mini", "api_key": "sk-test"}],
|
||||
)
|
||||
|
||||
def test_assistant_created_per_role(self):
|
||||
"""One AssistantAgent is created for each role in the config."""
|
||||
gen = self._make_gen()
|
||||
config = _make_config(roles={
|
||||
"role_a": {
|
||||
"role": "Agent A", "goal": "Goal A", "backstory": "Backstory A",
|
||||
"tasks": {"t1": {"description": "Do A", "expected_output": "A done"}},
|
||||
"tools": [],
|
||||
},
|
||||
"role_b": {
|
||||
"role": "Agent B", "goal": "Goal B", "backstory": "Backstory B",
|
||||
"tasks": {"t2": {"description": "Do B", "expected_output": "B done"}},
|
||||
"tools": [],
|
||||
},
|
||||
})
|
||||
|
||||
mock_llm_config = MagicMock()
|
||||
mock_llm_config.__enter__ = MagicMock(return_value=mock_llm_config)
|
||||
mock_llm_config.__exit__ = MagicMock(return_value=False)
|
||||
|
||||
created_agents = []
|
||||
|
||||
def fake_assistant(**kwargs):
|
||||
m = MagicMock()
|
||||
m.name = kwargs.get("name", "agent")
|
||||
created_agents.append(m)
|
||||
return m
|
||||
|
||||
mock_user_proxy = MagicMock()
|
||||
mock_groupchat = MagicMock()
|
||||
mock_groupchat.messages = [{"name": "Agent A", "content": "Done. TERMINATE", "role": "assistant"}]
|
||||
mock_manager = MagicMock()
|
||||
|
||||
with patch("autogen.LLMConfig", create=True, return_value=mock_llm_config), \
|
||||
patch("autogen.AssistantAgent", create=True, side_effect=fake_assistant), \
|
||||
patch("autogen.UserProxyAgent", create=True, return_value=mock_user_proxy), \
|
||||
patch("autogen.GroupChat", create=True, return_value=mock_groupchat), \
|
||||
patch("autogen.GroupChatManager", create=True, return_value=mock_manager):
|
||||
|
||||
gen._run_ag2(config, "Test", {})
|
||||
|
||||
assert len(created_agents) == 2
|
||||
|
||||
def test_groupchat_includes_user_proxy_and_assistants(self):
|
||||
"""GroupChat receives user_proxy + all assistants."""
|
||||
gen = self._make_gen()
|
||||
config = _make_config()
|
||||
|
||||
mock_llm_config = MagicMock()
|
||||
mock_llm_config.__enter__ = MagicMock(return_value=mock_llm_config)
|
||||
mock_llm_config.__exit__ = MagicMock(return_value=False)
|
||||
|
||||
mock_assistant = MagicMock()
|
||||
mock_assistant.name = "Researcher"
|
||||
mock_user_proxy = MagicMock()
|
||||
mock_user_proxy.name = "User"
|
||||
mock_groupchat = MagicMock()
|
||||
mock_groupchat.messages = [{"name": "Researcher", "content": "Done. TERMINATE", "role": "assistant"}]
|
||||
mock_manager = MagicMock()
|
||||
|
||||
groupchat_call_args = {}
|
||||
|
||||
def capture_groupchat(**kwargs):
|
||||
groupchat_call_args.update(kwargs)
|
||||
return mock_groupchat
|
||||
|
||||
with patch("autogen.LLMConfig", create=True, return_value=mock_llm_config), \
|
||||
patch("autogen.AssistantAgent", create=True, return_value=mock_assistant), \
|
||||
patch("autogen.UserProxyAgent", create=True, return_value=mock_user_proxy), \
|
||||
patch("autogen.GroupChat", create=True, side_effect=capture_groupchat), \
|
||||
patch("autogen.GroupChatManager", create=True, return_value=mock_manager):
|
||||
|
||||
gen._run_ag2(config, "Test", {})
|
||||
|
||||
agents_in_groupchat = groupchat_call_args.get("agents", [])
|
||||
assert mock_user_proxy in agents_in_groupchat
|
||||
assert mock_assistant in agents_in_groupchat
|
||||
|
||||
def test_empty_roles_returns_no_agents_message(self):
|
||||
"""Returns a clear message when no roles are defined in config."""
|
||||
gen = self._make_gen()
|
||||
config = _make_config(roles={})
|
||||
|
||||
mock_llm_config = MagicMock()
|
||||
mock_llm_config.__enter__ = MagicMock(return_value=mock_llm_config)
|
||||
mock_llm_config.__exit__ = MagicMock(return_value=False)
|
||||
mock_user_proxy = MagicMock()
|
||||
|
||||
with patch("autogen.LLMConfig", create=True, return_value=mock_llm_config), \
|
||||
patch("autogen.AssistantAgent"), \
|
||||
patch("autogen.UserProxyAgent", create=True, return_value=mock_user_proxy):
|
||||
|
||||
result = gen._run_ag2(config, "Test", {})
|
||||
|
||||
assert "No agents" in result
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# _run_ag2: system message composition
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestRunAG2SystemMessage:
|
||||
|
||||
def _make_gen(self):
|
||||
with patch("praisonai.agents_generator.AG2_AVAILABLE", True), \
|
||||
patch("praisonai.agents_generator.CREWAI_AVAILABLE", False), \
|
||||
patch("praisonai.agents_generator.AUTOGEN_AVAILABLE", False), \
|
||||
patch("praisonai.agents_generator.PRAISONAI_AVAILABLE", True):
|
||||
from praisonai.agents_generator import AgentsGenerator
|
||||
return AgentsGenerator(
|
||||
agent_file="agents.yaml",
|
||||
framework="ag2",
|
||||
config_list=[{"model": "gpt-4o-mini", "api_key": "sk-test"}],
|
||||
)
|
||||
|
||||
def test_system_message_contains_backstory(self):
|
||||
"""AssistantAgent system_message includes the backstory from YAML."""
|
||||
gen = self._make_gen()
|
||||
config = _make_config(roles={
|
||||
"agent1": {
|
||||
"role": "Expert",
|
||||
"goal": "Help users",
|
||||
"backstory": "A unique backstory for testing purposes.",
|
||||
"tasks": {"t": {"description": "Do it", "expected_output": "Done"}},
|
||||
"tools": [],
|
||||
}
|
||||
})
|
||||
|
||||
mock_llm_config = MagicMock()
|
||||
mock_llm_config.__enter__ = MagicMock(return_value=mock_llm_config)
|
||||
mock_llm_config.__exit__ = MagicMock(return_value=False)
|
||||
mock_user_proxy = MagicMock()
|
||||
mock_groupchat = MagicMock()
|
||||
mock_groupchat.messages = [{"name": "Expert", "content": "Done. TERMINATE", "role": "assistant"}]
|
||||
mock_manager = MagicMock()
|
||||
|
||||
assistant_kwargs = {}
|
||||
|
||||
def capture_assistant(**kwargs):
|
||||
assistant_kwargs.update(kwargs)
|
||||
m = MagicMock()
|
||||
m.name = kwargs.get("name", "agent")
|
||||
return m
|
||||
|
||||
with patch("autogen.LLMConfig", create=True, return_value=mock_llm_config), \
|
||||
patch("autogen.AssistantAgent", create=True, side_effect=capture_assistant), \
|
||||
patch("autogen.UserProxyAgent", create=True, return_value=mock_user_proxy), \
|
||||
patch("autogen.GroupChat", create=True, return_value=mock_groupchat), \
|
||||
patch("autogen.GroupChatManager", create=True, return_value=mock_manager):
|
||||
|
||||
gen._run_ag2(config, "Test", {})
|
||||
|
||||
assert "A unique backstory for testing purposes." in assistant_kwargs.get("system_message", "")
|
||||
assert "TERMINATE" in assistant_kwargs.get("system_message", "")
|
||||
|
||||
def test_agent_name_sanitised(self):
|
||||
"""Agent names with special characters are sanitised for AG2 compatibility."""
|
||||
gen = self._make_gen()
|
||||
config = _make_config(roles={
|
||||
"agent1": {
|
||||
"role": "AI & ML Expert (2024)", # contains special chars
|
||||
"goal": "Help",
|
||||
"backstory": "Expert.",
|
||||
"tasks": {"t": {"description": "Do it", "expected_output": "Done"}},
|
||||
"tools": [],
|
||||
}
|
||||
})
|
||||
|
||||
mock_llm_config = MagicMock()
|
||||
mock_llm_config.__enter__ = MagicMock(return_value=mock_llm_config)
|
||||
mock_llm_config.__exit__ = MagicMock(return_value=False)
|
||||
mock_user_proxy = MagicMock()
|
||||
mock_groupchat = MagicMock()
|
||||
mock_groupchat.messages = [{"name": "AI___ML_Expert__2024_", "content": "Done. TERMINATE", "role": "assistant"}]
|
||||
mock_manager = MagicMock()
|
||||
created_name = {}
|
||||
|
||||
def capture_assistant(**kwargs):
|
||||
created_name["name"] = kwargs.get("name", "")
|
||||
m = MagicMock()
|
||||
m.name = created_name["name"]
|
||||
return m
|
||||
|
||||
with patch("autogen.LLMConfig", create=True, return_value=mock_llm_config), \
|
||||
patch("autogen.AssistantAgent", create=True, side_effect=capture_assistant), \
|
||||
patch("autogen.UserProxyAgent", create=True, return_value=mock_user_proxy), \
|
||||
patch("autogen.GroupChat", create=True, return_value=mock_groupchat), \
|
||||
patch("autogen.GroupChatManager", create=True, return_value=mock_manager):
|
||||
|
||||
gen._run_ag2(config, "Test", {})
|
||||
|
||||
name = created_name.get("name", "")
|
||||
# Should not contain special chars that would break AG2
|
||||
import re
|
||||
assert re.match(r"^[a-zA-Z0-9_\-]+$", name), f"Name '{name}' contains invalid characters"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# _run_ag2: output extraction
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestRunAG2OutputExtraction:
|
||||
|
||||
def _make_gen(self):
|
||||
with patch("praisonai.agents_generator.AG2_AVAILABLE", True), \
|
||||
patch("praisonai.agents_generator.CREWAI_AVAILABLE", False), \
|
||||
patch("praisonai.agents_generator.AUTOGEN_AVAILABLE", False), \
|
||||
patch("praisonai.agents_generator.PRAISONAI_AVAILABLE", True):
|
||||
from praisonai.agents_generator import AgentsGenerator
|
||||
return AgentsGenerator(
|
||||
agent_file="agents.yaml",
|
||||
framework="ag2",
|
||||
config_list=[{"model": "gpt-4o-mini", "api_key": "sk-test"}],
|
||||
)
|
||||
|
||||
def _run_with_messages(self, messages):
|
||||
gen = self._make_gen()
|
||||
config = _make_config()
|
||||
|
||||
mock_llm_config = MagicMock()
|
||||
mock_assistant = MagicMock()
|
||||
mock_assistant.name = "Researcher"
|
||||
mock_user_proxy = MagicMock()
|
||||
# chat_result with no summary so extraction falls back to messages
|
||||
mock_chat_result = MagicMock()
|
||||
mock_chat_result.summary = None
|
||||
mock_user_proxy.initiate_chat.return_value = mock_chat_result
|
||||
mock_groupchat = MagicMock()
|
||||
mock_groupchat.messages = messages
|
||||
mock_manager = MagicMock()
|
||||
|
||||
with patch("autogen.LLMConfig", create=True, return_value=mock_llm_config), \
|
||||
patch("autogen.AssistantAgent", create=True, return_value=mock_assistant), \
|
||||
patch("autogen.UserProxyAgent", create=True, return_value=mock_user_proxy), \
|
||||
patch("autogen.GroupChat", create=True, return_value=mock_groupchat), \
|
||||
patch("autogen.GroupChatManager", create=True, return_value=mock_manager):
|
||||
|
||||
return gen._run_ag2(config, "Test", {})
|
||||
|
||||
def test_output_prefixed_with_ag2_header(self):
|
||||
"""Result always starts with '### AG2 Output ###'."""
|
||||
result = self._run_with_messages([
|
||||
{"name": "Researcher", "content": "Here are my findings. TERMINATE", "role": "assistant"}
|
||||
])
|
||||
assert result.startswith("### AG2 Output ###")
|
||||
|
||||
def test_terminate_marker_stripped_from_output(self):
|
||||
"""TERMINATE keyword is removed from the extracted output."""
|
||||
result = self._run_with_messages([
|
||||
{"name": "Researcher", "content": "Detailed findings here. TERMINATE", "role": "assistant"}
|
||||
])
|
||||
assert "TERMINATE" not in result
|
||||
assert "Detailed findings here" in result
|
||||
|
||||
def test_user_messages_skipped_in_extraction(self):
|
||||
"""User proxy messages are not included in the extracted output."""
|
||||
result = self._run_with_messages([
|
||||
{"name": "User", "content": "This is the user message", "role": "user"},
|
||||
{"name": "Researcher", "content": "This is the agent response. TERMINATE", "role": "assistant"},
|
||||
])
|
||||
assert "This is the user message" not in result
|
||||
assert "This is the agent response" in result
|
||||
|
||||
def test_execution_error_returns_error_message(self):
|
||||
"""Exception during initiate_chat returns a '### AG2 Error ###' message."""
|
||||
gen = self._make_gen()
|
||||
config = _make_config()
|
||||
|
||||
mock_llm_config = MagicMock()
|
||||
mock_llm_config.__enter__ = MagicMock(return_value=mock_llm_config)
|
||||
mock_llm_config.__exit__ = MagicMock(return_value=False)
|
||||
mock_assistant = MagicMock()
|
||||
mock_assistant.name = "Researcher"
|
||||
mock_user_proxy = MagicMock()
|
||||
mock_user_proxy.initiate_chat.side_effect = RuntimeError("Connection failed")
|
||||
mock_groupchat = MagicMock()
|
||||
mock_groupchat.messages = []
|
||||
mock_manager = MagicMock()
|
||||
|
||||
with patch("autogen.LLMConfig", create=True, return_value=mock_llm_config), \
|
||||
patch("autogen.AssistantAgent", create=True, return_value=mock_assistant), \
|
||||
patch("autogen.UserProxyAgent", create=True, return_value=mock_user_proxy), \
|
||||
patch("autogen.GroupChat", create=True, return_value=mock_groupchat), \
|
||||
patch("autogen.GroupChatManager", create=True, return_value=mock_manager):
|
||||
|
||||
result = gen._run_ag2(config, "Test", {})
|
||||
|
||||
assert "### AG2 Error ###" in result
|
||||
assert "Connection failed" in result
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
pytest.main([__file__, "-v"])
|
||||
@@ -0,0 +1,138 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Test script for Claude Code integration with PraisonAI Agents
|
||||
|
||||
This script tests the basic functionality of the refactored Claude Code integration
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import asyncio
|
||||
import unittest
|
||||
|
||||
# Add the src directory to the path for imports
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src', 'praisonai'))
|
||||
|
||||
def test_claude_code_tool_import():
|
||||
"""Test that we can import the Claude Code tool function"""
|
||||
try:
|
||||
from praisonai.ui.code import claude_code_tool
|
||||
print("✅ Successfully imported claude_code_tool")
|
||||
return True
|
||||
except ImportError as e:
|
||||
print(f"❌ Failed to import claude_code_tool: {e}")
|
||||
return False
|
||||
|
||||
def test_praisonai_agents_import():
|
||||
"""Test praisonaiagents import availability"""
|
||||
try:
|
||||
from praisonaiagents import Agent
|
||||
print("✅ PraisonAI Agents is available")
|
||||
return True
|
||||
except ImportError as e:
|
||||
print(f"⚠️ PraisonAI Agents not available (fallback to litellm): {e}")
|
||||
return False
|
||||
|
||||
def test_claude_code_availability():
|
||||
"""Test if Claude Code CLI is available"""
|
||||
import subprocess
|
||||
try:
|
||||
result = subprocess.run(['claude', '--version'], capture_output=True, text=True, timeout=10)
|
||||
if result.returncode == 0:
|
||||
print(f"✅ Claude Code CLI is available: {result.stdout.strip()}")
|
||||
return True
|
||||
else:
|
||||
print(f"❌ Claude Code CLI returned error: {result.stderr}")
|
||||
return False
|
||||
except FileNotFoundError:
|
||||
print("⚠️ Claude Code CLI not found in PATH")
|
||||
return False
|
||||
except subprocess.TimeoutExpired:
|
||||
print("⚠️ Claude Code CLI check timed out")
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f"⚠️ Error checking Claude Code CLI: {e}")
|
||||
return False
|
||||
|
||||
async def test_claude_code_tool_execution():
|
||||
"""Test basic Claude Code tool execution (simple query)"""
|
||||
try:
|
||||
from praisonai.ui.code import claude_code_tool
|
||||
|
||||
# Test with a simple query that shouldn't modify files
|
||||
test_query = "What is the current directory?"
|
||||
result = await claude_code_tool(test_query)
|
||||
|
||||
print(f"✅ Claude Code tool executed successfully")
|
||||
print(f"Query: {test_query}")
|
||||
print(f"Result (first 100 chars): {str(result)[:100]}...")
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"❌ Claude Code tool execution failed: {e}")
|
||||
return False
|
||||
|
||||
def test_environment_variables():
|
||||
"""Test that environment variables are properly set"""
|
||||
test_vars = [
|
||||
"PRAISONAI_CLAUDECODE_ENABLED",
|
||||
"PRAISONAI_CODE_REPO_PATH"
|
||||
]
|
||||
|
||||
print("Environment Variables:")
|
||||
for var in test_vars:
|
||||
value = os.getenv(var, "NOT_SET")
|
||||
print(f" {var}: {value}")
|
||||
|
||||
return True
|
||||
|
||||
async def run_tests():
|
||||
"""Run all tests"""
|
||||
print("🧪 Testing Claude Code Integration with PraisonAI Agents")
|
||||
print("=" * 60)
|
||||
|
||||
tests = [
|
||||
("Import Claude Code Tool", test_claude_code_tool_import),
|
||||
("Import PraisonAI Agents", test_praisonai_agents_import),
|
||||
("Environment Variables", test_environment_variables),
|
||||
("Claude Code CLI Availability", test_claude_code_availability),
|
||||
]
|
||||
|
||||
results = {}
|
||||
for test_name, test_func in tests:
|
||||
print(f"\n🔍 {test_name}:")
|
||||
try:
|
||||
results[test_name] = test_func()
|
||||
except Exception as e:
|
||||
print(f"❌ Test failed with exception: {e}")
|
||||
results[test_name] = False
|
||||
|
||||
# Only test Claude Code tool execution if CLI is available
|
||||
if results.get("Claude Code CLI Availability", False):
|
||||
print(f"\n🔍 Claude Code Tool Execution:")
|
||||
try:
|
||||
results["Claude Code Tool Execution"] = await test_claude_code_tool_execution()
|
||||
except Exception as e:
|
||||
print(f"❌ Test failed with exception: {e}")
|
||||
results["Claude Code Tool Execution"] = False
|
||||
|
||||
# Summary
|
||||
print("\n" + "=" * 60)
|
||||
print("📊 Test Summary:")
|
||||
passed = sum(1 for result in results.values() if result)
|
||||
total = len(results)
|
||||
|
||||
for test_name, result in results.items():
|
||||
status = "✅ PASS" if result else "❌ FAIL"
|
||||
print(f" {status} {test_name}")
|
||||
|
||||
print(f"\nResults: {passed}/{total} tests passed")
|
||||
|
||||
if passed == total:
|
||||
print("🎉 All tests passed! Integration is working correctly.")
|
||||
else:
|
||||
print("⚠️ Some tests failed. Please check the implementation.")
|
||||
|
||||
return passed == total
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(run_tests())
|
||||
@@ -0,0 +1,128 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Quick test for the remote agent connectivity feature.
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src', 'praisonai-agents'))
|
||||
|
||||
from praisonaiagents import Session
|
||||
|
||||
def test_remote_session_creation():
|
||||
"""Test creating a remote session."""
|
||||
print("🧪 Testing remote session creation...")
|
||||
|
||||
try:
|
||||
# This should fail gracefully since there's no server running
|
||||
session = Session(agent_url="localhost:8000/agent")
|
||||
print(f"❌ Unexpected: Session created without server: {session}")
|
||||
except ConnectionError as e:
|
||||
print(f"✅ Expected connection error: {e}")
|
||||
except Exception as e:
|
||||
print(f"❌ Unexpected error: {e}")
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
def test_local_session_backwards_compatibility():
|
||||
"""Test that local sessions still work as before."""
|
||||
print("\n🧪 Testing local session backwards compatibility...")
|
||||
|
||||
try:
|
||||
# This should work as before
|
||||
session = Session(session_id="test_local")
|
||||
print(f"✅ Local session created: {session}")
|
||||
|
||||
# Test that it's not remote
|
||||
if session.is_remote:
|
||||
print("❌ Local session incorrectly marked as remote")
|
||||
return False
|
||||
|
||||
print("✅ Local session correctly identified")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Error creating local session: {e}")
|
||||
return False
|
||||
|
||||
def test_remote_session_restrictions():
|
||||
"""Test that remote sessions properly restrict local operations."""
|
||||
print("\n🧪 Testing remote session restrictions...")
|
||||
|
||||
try:
|
||||
# Create a mock remote session (will fail connection but that's OK for testing restrictions)
|
||||
session = Session(agent_url="mock://fake-server:8000/agent")
|
||||
except ConnectionError:
|
||||
# Create the session object manually for testing restrictions
|
||||
session = Session.__new__(Session)
|
||||
session.session_id = "test_remote"
|
||||
session.user_id = "test_user"
|
||||
session.agent_url = "mock://fake-server:8000/agent"
|
||||
session.timeout = 30
|
||||
session.is_remote = True
|
||||
session.memory_config = {}
|
||||
session.knowledge_config = {}
|
||||
session._memory = None
|
||||
session._knowledge = None
|
||||
session._agents_instance = None
|
||||
|
||||
# Test memory restriction
|
||||
try:
|
||||
_ = session.memory
|
||||
print("❌ Memory access should be restricted for remote sessions")
|
||||
return False
|
||||
except ValueError as e:
|
||||
print(f"✅ Memory properly restricted: {e}")
|
||||
|
||||
# Test knowledge restriction
|
||||
try:
|
||||
_ = session.knowledge
|
||||
print("❌ Knowledge access should be restricted for remote sessions")
|
||||
return False
|
||||
except ValueError as e:
|
||||
print(f"✅ Knowledge properly restricted: {e}")
|
||||
|
||||
# Test agent creation restriction
|
||||
try:
|
||||
session.Agent(name="Test", role="Assistant")
|
||||
print("❌ Agent creation should be restricted for remote sessions")
|
||||
return False
|
||||
except ValueError as e:
|
||||
print(f"✅ Agent creation properly restricted: {e}")
|
||||
|
||||
return True
|
||||
|
||||
def main():
|
||||
"""Run all tests."""
|
||||
print("🚀 Testing Remote Agent Connectivity Implementation")
|
||||
print("=" * 60)
|
||||
|
||||
tests = [
|
||||
test_remote_session_creation,
|
||||
test_local_session_backwards_compatibility,
|
||||
test_remote_session_restrictions
|
||||
]
|
||||
|
||||
passed = 0
|
||||
total = len(tests)
|
||||
|
||||
for test in tests:
|
||||
if test():
|
||||
passed += 1
|
||||
else:
|
||||
print("❌ Test failed!")
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print(f"📊 Test Results: {passed}/{total} tests passed")
|
||||
|
||||
if passed == total:
|
||||
print("🎉 All tests passed! Remote agent connectivity is working correctly.")
|
||||
return True
|
||||
else:
|
||||
print("⚠️ Some tests failed. Check the implementation.")
|
||||
return False
|
||||
|
||||
if __name__ == "__main__":
|
||||
success = main()
|
||||
sys.exit(0 if success else 1)
|
||||
Generated
+5
-5
@@ -3931,7 +3931,7 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "praisonai"
|
||||
version = "2.2.31"
|
||||
version = "2.2.33"
|
||||
source = { editable = "." }
|
||||
dependencies = [
|
||||
{ name = "instructor" },
|
||||
@@ -4073,7 +4073,7 @@ requires-dist = [
|
||||
{ name = "plotly", marker = "extra == 'realtime'", specifier = ">=5.24.0" },
|
||||
{ name = "praisonai-tools", marker = "extra == 'autogen'", specifier = ">=0.0.15" },
|
||||
{ name = "praisonai-tools", marker = "extra == 'crewai'", specifier = ">=0.0.15" },
|
||||
{ name = "praisonaiagents", specifier = ">=0.0.104" },
|
||||
{ name = "praisonaiagents", specifier = ">=0.0.106" },
|
||||
{ name = "pyautogen", marker = "extra == 'autogen'", specifier = ">=0.2.19" },
|
||||
{ name = "pydantic", marker = "extra == 'chat'", specifier = "<=2.10.1" },
|
||||
{ name = "pydantic", marker = "extra == 'code'", specifier = "<=2.10.1" },
|
||||
@@ -4130,7 +4130,7 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "praisonaiagents"
|
||||
version = "0.0.104"
|
||||
version = "0.0.106"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "mcp" },
|
||||
@@ -4139,9 +4139,9 @@ dependencies = [
|
||||
{ name = "pydantic" },
|
||||
{ name = "rich" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/d1/e5/f7f0f4a6c2ce517332b0799f6081cc4d3b8016a3a8bc12df61d50004012a/praisonaiagents-0.0.104.tar.gz", hash = "sha256:88239bc9de3f6a6777bac13695d844aa9b3c8968d973e7ee1d3cf31d3ff9ac8b", size = 150329 }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/81/9a/7b488726d34ebf7f98c27dd3e730ed0ca14dec7e63f9cb8fe4129aaf0e24/praisonaiagents-0.0.106.tar.gz", hash = "sha256:0fecb0df6c1ace618374a3d78eb6f03a058e70c606449069363cda0505a59487", size = 154663 }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/54/53/34c367bf701082690194cc823c4e36784efd24fa07488022906153f48b0e/praisonaiagents-0.0.104-py3-none-any.whl", hash = "sha256:37a0ae97c63aa1cece4f5db67f7cc09b0e3d2b5ea7ba8d021062ee41edd03743", size = 171834 },
|
||||
{ url = "https://files.pythonhosted.org/packages/3f/75/6d56dbb2a03a4d0160ba6f3ebe60b468e3ee859f31c2833ac9d03130bdaf/praisonaiagents-0.0.106-py3-none-any.whl", hash = "sha256:504c4e11558bc21b8757efba8211b231c7ee235c46cbaafe02038fa493124f83", size = 175597 },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
Reference in new issue
Block a user