Compare commits
75 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
43b2c03c91 | ||
|
|
eebe995826 | ||
|
|
5e854b9d1d | ||
|
|
0c96e42f51 | ||
|
|
2d98cb715f | ||
|
|
16df8a9a1b | ||
|
|
ecdd0cc917 | ||
|
|
f4878452f6 | ||
|
|
8654988f57 | ||
|
|
09eea12250 | ||
|
|
07d4fb18f3 | ||
|
|
0b12acd4ac | ||
|
|
a33881759c | ||
|
|
139497e1fa | ||
|
|
2bbe2c90ac | ||
|
|
e200ce6490 | ||
|
|
13b68095e6 | ||
|
|
7940876e6f | ||
|
|
17d72238c7 | ||
|
|
22a771abd8 | ||
|
|
1656fda8da | ||
|
|
6bf0ea52e0 | ||
|
|
add128f4d5 | ||
|
|
958eeec4a6 | ||
|
|
18c6865926 | ||
|
|
3622260c11 | ||
|
|
0ca6b4f3e9 | ||
|
|
2a80bdf7a3 | ||
|
|
198eb57032 | ||
|
|
9ab001c35e | ||
|
|
0dbf6d1c13 | ||
|
|
6cfff4cc95 | ||
|
|
98c559e1ce | ||
|
|
6a9f329def | ||
|
|
b29d8d108e | ||
|
|
72e4b7865a | ||
|
|
ef5e84859d | ||
|
|
ae62a557d3 | ||
|
|
86de80a998 | ||
|
|
2bac2b3824 | ||
|
|
3185233233 | ||
|
|
48597bdf30 | ||
|
|
b53746dd1f | ||
|
|
ebbbf62df5 | ||
|
|
d0f40e7d35 | ||
|
|
15a4ec7e33 | ||
|
|
6c0dfae9bf | ||
|
|
48d15a6128 | ||
|
|
7ddbce89d0 | ||
|
|
cf07f732c2 | ||
|
|
897d3dc9ea | ||
|
|
8438e75dff | ||
|
|
a099575620 | ||
|
|
37c17c9e3d | ||
|
|
7e013787ed | ||
|
|
984b3b28ba | ||
|
|
80f04ada32 | ||
|
|
3dd6971fce | ||
|
|
02cbda22dd | ||
|
|
e3e40ede2b | ||
|
|
0c3d2fdbe2 | ||
|
|
6be09de87d | ||
|
|
1e00887167 | ||
|
|
705791d17f | ||
|
|
0ec9bbdc13 | ||
|
|
146c28ae27 | ||
|
|
fc61fb062e | ||
|
|
a46402fd08 | ||
|
|
47307a1045 | ||
|
|
b21e355ce1 | ||
|
|
0c69df107e | ||
|
|
4800807783 | ||
|
|
71ecc8f35b | ||
|
|
782c2aceff | ||
|
|
ff27fb157c |
13
.env.example
13
.env.example
@@ -34,9 +34,22 @@ JWT_EXPIRATION_TIME=3600
|
||||
# Encryption key for API keys
|
||||
ENCRYPTION_KEY="your-encryption-key"
|
||||
|
||||
# Email provider settings
|
||||
EMAIL_PROVIDER="sendgrid"
|
||||
|
||||
# SendGrid
|
||||
SENDGRID_API_KEY="your-sendgrid-api-key"
|
||||
EMAIL_FROM="noreply@yourdomain.com"
|
||||
|
||||
# SMTP settings
|
||||
SMTP_HOST="your-smtp-host"
|
||||
SMTP_FROM="noreply-smtp@yourdomain.com"
|
||||
SMTP_USER="your-smtp-username"
|
||||
SMTP_PASSWORD="your-smtp-password"
|
||||
SMTP_PORT=587
|
||||
SMTP_USE_TLS=true
|
||||
SMTP_USE_SSL=false
|
||||
|
||||
APP_URL="https://yourdomain.com"
|
||||
|
||||
LANGFUSE_PUBLIC_KEY="your-langfuse-public-key"
|
||||
|
||||
48
.github/workflows/docker-image.yml
vendored
Normal file
48
.github/workflows/docker-image.yml
vendored
Normal file
@@ -0,0 +1,48 @@
|
||||
name: Build Docker image
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "*.*.*"
|
||||
|
||||
jobs:
|
||||
build_deploy:
|
||||
name: Build and Deploy
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Docker meta
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: evoapicloud/evo-ai
|
||||
tags: type=semver,pattern=v{{version}}
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
|
||||
- name: Build and push
|
||||
id: docker_build
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
|
||||
- name: Image digest
|
||||
run: echo ${{ steps.docker_build.outputs.digest }}
|
||||
48
.github/workflows/publish_docker_image_homolog.yml
vendored
Normal file
48
.github/workflows/publish_docker_image_homolog.yml
vendored
Normal file
@@ -0,0 +1,48 @@
|
||||
name: Build Docker image
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- develop
|
||||
|
||||
jobs:
|
||||
build_deploy:
|
||||
name: Build and Deploy
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Docker meta
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: evoapicloud/evo-ai
|
||||
tags: homolog
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
|
||||
- name: Build and push
|
||||
id: docker_build
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
|
||||
- name: Image digest
|
||||
run: echo ${{ steps.docker_build.outputs.digest }}
|
||||
48
.github/workflows/publish_docker_image_latest.yml
vendored
Normal file
48
.github/workflows/publish_docker_image_latest.yml
vendored
Normal file
@@ -0,0 +1,48 @@
|
||||
name: Build Docker image
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
build_deploy:
|
||||
name: Build and Deploy
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Docker meta
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: evoapicloud/evo-ai
|
||||
tags: latest
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
|
||||
- name: Build and push
|
||||
id: docker_build
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
|
||||
- name: Image digest
|
||||
run: echo ${{ steps.docker_build.outputs.digest }}
|
||||
83
CHANGELOG.md
Normal file
83
CHANGELOG.md
Normal file
@@ -0,0 +1,83 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to this project will be documented in this file.
|
||||
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [0.0.10] - 2025-05-15
|
||||
|
||||
### Added
|
||||
|
||||
- Add Task Agent for structured single-task execution
|
||||
- Improve context management in agent execution
|
||||
- Add file support for A2A protocol (Agent-to-Agent) endpoints
|
||||
- Implement multimodal content processing in A2A messages
|
||||
- Add SMTP email provider support as alternative to SendGrid
|
||||
|
||||
## [0.0.9] - 2025-05-13
|
||||
|
||||
### Added
|
||||
|
||||
- Add API key sharing and flexible authentication for chat routes
|
||||
|
||||
### Changed
|
||||
|
||||
- Enhance user authentication with detailed error handling
|
||||
|
||||
## [0.0.8] - 2025-05-13
|
||||
|
||||
### Changed
|
||||
|
||||
- Update author information in multiple files
|
||||
|
||||
## [0.0.7] - 2025-05-13
|
||||
|
||||
### Added
|
||||
|
||||
- Docker image CI workflow for automated builds and pushes
|
||||
- GitHub Container Registry (GHCR) integration
|
||||
- Automated image tagging based on branch and commit
|
||||
- Docker Buildx setup for multi-platform builds
|
||||
- Cache optimization for faster builds
|
||||
- Automated image publishing on push to main and develop branches
|
||||
|
||||
## [0.0.6] - 2025-05-13
|
||||
|
||||
### Added
|
||||
|
||||
- Initial public release of Evo AI platform
|
||||
- FastAPI-based backend API
|
||||
- JWT authentication with email verification
|
||||
- Agent management (LLM, A2A, Sequential, Parallel, Loop, Workflow)
|
||||
- Agent 2 Agent (A2A) protocol support (Google A2A spec)
|
||||
- MCP server integration and management
|
||||
- Custom tools management for agents
|
||||
- Folder-based agent organization
|
||||
- Secure API key management with encryption
|
||||
- PostgreSQL and Redis integration
|
||||
- Email notifications (SendGrid) with Jinja2 templates
|
||||
- Audit log system for administrative actions
|
||||
- LangGraph integration for workflow agents
|
||||
- OpenTelemetry tracing and Langfuse integration
|
||||
- Docker and Docker Compose support
|
||||
- English documentation and codebase
|
||||
|
||||
### Changed
|
||||
|
||||
- N/A
|
||||
|
||||
### Fixed
|
||||
|
||||
- N/A
|
||||
|
||||
### Security
|
||||
|
||||
- JWT tokens with expiration and resource-based access control
|
||||
- Secure password hashing (bcrypt)
|
||||
- Account lockout after multiple failed login attempts
|
||||
- Email verification and password reset flows
|
||||
|
||||
---
|
||||
|
||||
Older versions and future releases will be listed here.
|
||||
201
LICENSE
Normal file
201
LICENSE
Normal file
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2025 Evolution API
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
237
README.md
237
README.md
@@ -11,9 +11,10 @@ The Evo AI platform allows:
|
||||
- Client management
|
||||
- MCP server configuration
|
||||
- Custom tools management
|
||||
- **[Google Agent Development Kit (ADK)](https://google.github.io/adk-docs/)**: Base framework for agent development, providing support for LLM Agents, Sequential Agents, Loop Agents, Parallel Agents and Custom Agents
|
||||
- JWT authentication with email verification
|
||||
- **Agent 2 Agent (A2A) Protocol Support**: Interoperability between AI agents following Google's A2A specification
|
||||
- **Workflow Agent with LangGraph**: Building complex agent workflows with LangGraph and ReactFlow
|
||||
- **[Agent 2 Agent (A2A) Protocol Support](https://developers.googleblog.com/en/a2a-a-new-era-of-agent-interoperability/)**: Interoperability between AI agents following Google's A2A specification
|
||||
- **[Workflow Agent with LangGraph](https://www.langchain.com/langgraph)**: Building complex agent workflows with LangGraph and ReactFlow
|
||||
- **Secure API Key Management**: Encrypted storage of API keys with Fernet encryption
|
||||
- **Agent Organization**: Folder structure for organizing agents by categories
|
||||
|
||||
@@ -30,6 +31,8 @@ Agent based on language models like GPT-4, Claude, etc. Can be configured with t
|
||||
"client_id": "{{client_id}}",
|
||||
"name": "personal_assistant",
|
||||
"description": "Specialized personal assistant",
|
||||
"role": "Personal Assistant",
|
||||
"goal": "Help users with daily tasks and provide relevant information",
|
||||
"type": "llm",
|
||||
"model": "gpt-4",
|
||||
"api_key_id": "stored-api-key-uuid",
|
||||
@@ -150,6 +153,39 @@ Executes sub-agents in a custom workflow defined by a graph structure. This agen
|
||||
|
||||
The workflow structure is built using ReactFlow in the frontend, allowing visual creation and editing of complex agent workflows with nodes (representing agents or decision points) and edges (representing flow connections).
|
||||
|
||||
### 7. Task Agent
|
||||
|
||||
Executes a specific task using a target agent. Task Agent provides a streamlined approach for structured task execution, where the agent_id specifies which agent will process the task, and the task description can include dynamic content placeholders.
|
||||
|
||||
```json
|
||||
{
|
||||
"client_id": "{{client_id}}",
|
||||
"name": "web_search_task",
|
||||
"type": "task",
|
||||
"folder_id": "folder_id (optional)",
|
||||
"config": {
|
||||
"tasks": [
|
||||
{
|
||||
"agent_id": "search-agent-uuid",
|
||||
"description": "Search the web for information about {content}",
|
||||
"expected_output": "Comprehensive search results with relevant information"
|
||||
}
|
||||
],
|
||||
"sub_agents": ["post-processing-agent-uuid"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Key features of Task Agent:
|
||||
|
||||
- Passes structured task instructions to the designated agent
|
||||
- Supports variable content using {content} placeholder in the task description
|
||||
- Provides clear task definition with instructions and expected output format
|
||||
- Can execute sub-agents after the main task is completed
|
||||
- Simplifies orchestration for single-focused task execution
|
||||
|
||||
Task Agent is ideal for scenarios where you need to execute a specific, well-defined task with clear instructions and expectations.
|
||||
|
||||
### Common Characteristics
|
||||
|
||||
- All agent types can have sub-agents
|
||||
@@ -160,7 +196,7 @@ The workflow structure is built using ReactFlow in the frontend, allowing visual
|
||||
|
||||
### MCP Server Configuration
|
||||
|
||||
Agents can be integrated with MCP (Model Control Protocol) servers for distributed processing:
|
||||
Agents can be integrated with MCP (Model Context Protocol) servers for distributed processing:
|
||||
|
||||
```json
|
||||
{
|
||||
@@ -295,12 +331,57 @@ Authorization: Bearer your-token-jwt
|
||||
- **Uvicorn**: ASGI server
|
||||
- **Redis**: Cache and session management
|
||||
- **JWT**: Secure token authentication
|
||||
- **SendGrid**: Email service for notifications
|
||||
- **SendGrid/SMTP**: Email service for notifications (configurable)
|
||||
- **Jinja2**: Template engine for email rendering
|
||||
- **Bcrypt**: Password hashing and security
|
||||
- **LangGraph**: Framework for building stateful, multi-agent workflows
|
||||
- **ReactFlow**: Library for building node-based visual workflows
|
||||
|
||||
## 📊 Langfuse Integration (Tracing & Observability)
|
||||
|
||||
Evo AI platform natively supports integration with [Langfuse](https://langfuse.com/) for detailed tracing of agent executions, prompts, model responses, and tool calls, using the OpenTelemetry (OTel) standard.
|
||||
|
||||
### Why use Langfuse?
|
||||
|
||||
- Visual dashboard for agent traces, prompts, and executions
|
||||
- Detailed analytics for debugging and evaluating LLM apps
|
||||
- Easy integration with Google ADK and other frameworks
|
||||
|
||||
### How it works
|
||||
|
||||
- Every agent execution (including streaming) is automatically traced via OpenTelemetry spans
|
||||
- Data is sent to Langfuse, where it can be visualized and analyzed
|
||||
|
||||
### How to configure
|
||||
|
||||
1. **Set environment variables in your `.env`:**
|
||||
|
||||
```env
|
||||
LANGFUSE_PUBLIC_KEY="pk-lf-..." # Your Langfuse public key
|
||||
LANGFUSE_SECRET_KEY="sk-lf-..." # Your Langfuse secret key
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT="https://cloud.langfuse.com/api/public/otel" # (or us.cloud... for US region)
|
||||
```
|
||||
|
||||
> **Attention:** Do not swap the keys! `pk-...` is public, `sk-...` is secret.
|
||||
|
||||
2. **Automatic initialization**
|
||||
|
||||
- Tracing is automatically initialized when the application starts (`src/main.py`).
|
||||
- Agent execution functions are already instrumented with spans (`src/services/agent_runner.py`).
|
||||
|
||||
3. **View in the Langfuse dashboard**
|
||||
- Access your Langfuse dashboard to see real-time traces.
|
||||
|
||||
### Troubleshooting
|
||||
|
||||
- **401 Error (Invalid credentials):**
|
||||
- Check if the keys are correct and not swapped in your `.env`.
|
||||
- Make sure the endpoint matches your region (EU or US).
|
||||
- **Context error in async generator:**
|
||||
- The code is already adjusted to avoid OpenTelemetry context issues in async generators.
|
||||
- **Questions about integration:**
|
||||
- See the [official Langfuse documentation - Google ADK](https://langfuse.com/docs/integrations/google-adk)
|
||||
|
||||
## 🤖 Agent 2 Agent (A2A) Protocol Support
|
||||
|
||||
Evo AI implements the Google's Agent 2 Agent (A2A) protocol, enabling seamless communication and interoperability between AI agents. This implementation includes:
|
||||
@@ -310,7 +391,7 @@ Evo AI implements the Google's Agent 2 Agent (A2A) protocol, enabling seamless c
|
||||
- **Standardized Communication**: Agents can communicate using a common protocol regardless of their underlying implementation
|
||||
- **Interoperability**: Support for agents built with different frameworks and technologies
|
||||
- **Well-Known Endpoints**: Standardized endpoints for agent discovery and interaction
|
||||
- **Task Management**: Support for task-based interactions between agents
|
||||
- **Task Management**: Support for task creation, execution, and status tracking
|
||||
- **State Management**: Tracking of agent states and conversation history
|
||||
- **Authentication**: Secure API key-based authentication for agent interactions
|
||||
|
||||
@@ -381,24 +462,23 @@ Before starting, make sure you have the following installed:
|
||||
|
||||
You'll also need the following accounts/API keys:
|
||||
|
||||
- **OpenAI API Key**: Or API key from another AI provider
|
||||
- **SendGrid Account**: For email functionality
|
||||
- **Google API Key**: If using Google's A2A protocol implementation
|
||||
|
||||
## 📋 Requirements
|
||||
|
||||
- Python 3.10+
|
||||
- PostgreSQL
|
||||
- Redis
|
||||
- OpenAI API Key (or other AI provider)
|
||||
- SendGrid Account (for email sending)
|
||||
- Email provider:
|
||||
- SendGrid Account (if using SendGrid email provider)
|
||||
- SMTP Server (if using SMTP email provider)
|
||||
|
||||
## 🔧 Installation
|
||||
|
||||
1. Clone the repository:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/your-username/evo-ai.git
|
||||
git clone https://github.com/EvolutionAPI/evo-ai.git
|
||||
cd evo-ai
|
||||
```
|
||||
|
||||
@@ -446,11 +526,26 @@ make alembic-upgrade
|
||||
make seed-all
|
||||
```
|
||||
|
||||
## 🖥️ Frontend Installation
|
||||
|
||||
After installing Evo AI (the backend), you need to install the frontend to access the web interface:
|
||||
|
||||
1. Clone the frontend repository:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/EvolutionAPI/evo-ai-frontend.git
|
||||
cd evo-ai-frontend
|
||||
```
|
||||
|
||||
2. Follow the installation instructions in the frontend repository's README to set up and run the web interface.
|
||||
|
||||
> The backend (API) and frontend are separate projects. Make sure both are running for full platform functionality.
|
||||
|
||||
## 🚀 Getting Started
|
||||
|
||||
After installation, follow these steps to set up your first agent:
|
||||
|
||||
1. **Configure MCP Server**: Set up your Model Control Protocol server configuration first
|
||||
1. **Configure MCP Server**: Set up your Model Context Protocol server configuration first
|
||||
2. **Create Client or Register**: Create a new client or register a user account
|
||||
3. **Create Agents**: Set up the agents according to your needs (LLM, A2A, Sequential, Parallel, Loop, or Workflow)
|
||||
|
||||
@@ -473,11 +568,23 @@ JWT_SECRET_KEY="your-jwt-secret-key"
|
||||
JWT_ALGORITHM="HS256"
|
||||
JWT_EXPIRATION_TIME=30 # In seconds
|
||||
|
||||
# SendGrid for emails
|
||||
# Email provider configuration
|
||||
EMAIL_PROVIDER="sendgrid" # Options: "sendgrid" or "smtp"
|
||||
|
||||
# SendGrid (if EMAIL_PROVIDER=sendgrid)
|
||||
SENDGRID_API_KEY="your-sendgrid-api-key"
|
||||
EMAIL_FROM="noreply@yourdomain.com"
|
||||
APP_URL="https://yourdomain.com"
|
||||
|
||||
# SMTP (if EMAIL_PROVIDER=smtp)
|
||||
SMTP_FROM="noreply-smtp@yourdomain.com"
|
||||
SMTP_USER="your-smtp-username"
|
||||
SMTP_PASSWORD="your-smtp-password"
|
||||
SMTP_HOST="your-smtp-host"
|
||||
SMTP_PORT=587
|
||||
SMTP_USE_TLS=true
|
||||
SMTP_USE_SSL=false
|
||||
|
||||
# Encryption for API keys
|
||||
ENCRYPTION_KEY="your-encryption-key"
|
||||
```
|
||||
@@ -590,54 +697,6 @@ make run-prod # For production with multiple workers
|
||||
|
||||
The API will be available at `http://localhost:8000`
|
||||
|
||||
## 📚 API Documentation
|
||||
|
||||
The interactive API documentation is available at:
|
||||
|
||||
- Swagger UI: `http://localhost:8000/docs`
|
||||
- ReDoc: `http://localhost:8000/redoc`
|
||||
|
||||
## 📊 Logs and Audit
|
||||
|
||||
- Logs are stored in the `logs/` directory with the following format:
|
||||
- `{logger_name}_{date}.log`
|
||||
- The system maintains audit logs for important administrative actions
|
||||
- Each action is recorded with information such as user, IP, date/time, and details
|
||||
|
||||
## 🤝 Contributing
|
||||
|
||||
We welcome contributions from the community! Here's how you can help:
|
||||
|
||||
1. Fork the project
|
||||
2. Create a feature branch (`git checkout -b feature/AmazingFeature`)
|
||||
3. Make your changes and add tests if possible
|
||||
4. Run tests and make sure they pass
|
||||
5. Commit your changes following conventional commits format (`feat: add amazing feature`)
|
||||
6. Push to the branch (`git push origin feature/AmazingFeature`)
|
||||
7. Open a Pull Request
|
||||
|
||||
Please read our [Contributing Guidelines](CONTRIBUTING.md) for more details.
|
||||
|
||||
## 📄 License
|
||||
|
||||
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
|
||||
|
||||
## 📊 Stargazers
|
||||
|
||||
[](https://github.com/your-username/evo-ai/stargazers)
|
||||
|
||||
## 🔄 Forks
|
||||
|
||||
[](https://github.com/your-username/evo-ai/network/members)
|
||||
|
||||
## 🙏 Acknowledgments
|
||||
|
||||
- [FastAPI](https://fastapi.tiangolo.com/)
|
||||
- [SQLAlchemy](https://www.sqlalchemy.org/)
|
||||
- [Google ADK](https://github.com/google/adk)
|
||||
- [LangGraph](https://github.com/langchain-ai/langgraph)
|
||||
- [ReactFlow](https://reactflow.dev/)
|
||||
|
||||
## 👨💻 Development Commands
|
||||
|
||||
```bash
|
||||
@@ -742,8 +801,12 @@ The main environment variables used by the API container:
|
||||
- `POSTGRES_CONNECTION_STRING`: PostgreSQL connection string
|
||||
- `REDIS_HOST`: Redis host (use "redis" when running with Docker)
|
||||
- `JWT_SECRET_KEY`: Secret key for JWT token generation
|
||||
- `SENDGRID_API_KEY`: SendGrid API key for sending emails
|
||||
- `EMAIL_FROM`: Email used as sender
|
||||
- `EMAIL_PROVIDER`: Email provider to use ("sendgrid" or "smtp")
|
||||
- `SENDGRID_API_KEY`: SendGrid API key (if using SendGrid)
|
||||
- `EMAIL_FROM`: Email used as sender (for SendGrid)
|
||||
- `SMTP_FROM`: Email used as sender (for SMTP)
|
||||
- `SMTP_HOST`, `SMTP_PORT`, `SMTP_USER`, `SMTP_PASSWORD`: SMTP server configuration
|
||||
- `SMTP_USE_TLS`, `SMTP_USE_SSL`: SMTP security settings
|
||||
- `APP_URL`: Base URL of the application
|
||||
|
||||
## 🔒 Secure API Key Management
|
||||
@@ -891,3 +954,53 @@ GET /api/v1/agents?folder_id=folder-uuid
|
||||
Authorization: Bearer your-token-jwt
|
||||
x-client-id: client-uuid
|
||||
```
|
||||
|
||||
## 📚 API Documentation
|
||||
|
||||
The interactive API documentation is available at:
|
||||
|
||||
- Swagger UI: `http://localhost:8000/docs`
|
||||
- ReDoc: `http://localhost:8000/redoc`
|
||||
|
||||
## 📊 Logs and Audit
|
||||
|
||||
- Logs are stored in the `logs/` directory with the following format:
|
||||
- `{logger_name}_{date}.log`
|
||||
- The system maintains audit logs for important administrative actions
|
||||
- Each action is recorded with information such as user, IP, date/time, and details
|
||||
|
||||
## 🤝 Contributing
|
||||
|
||||
We welcome contributions from the community! Here's how you can help:
|
||||
|
||||
1. Fork the project
|
||||
2. Create a feature branch (`git checkout -b feature/AmazingFeature`)
|
||||
3. Make your changes and add tests if possible
|
||||
4. Run tests and make sure they pass
|
||||
5. Commit your changes following conventional commits format (`feat: add amazing feature`)
|
||||
6. Push to the branch (`git push origin feature/AmazingFeature`)
|
||||
7. Open a Pull Request
|
||||
|
||||
Please read our [Contributing Guidelines](CONTRIBUTING.md) for more details.
|
||||
|
||||
## 📄 License
|
||||
|
||||
This project is licensed under the [Apache License 2.0](./LICENSE).
|
||||
|
||||
The use of the name, logo, or trademark "Evolution API" is protected and not automatically granted by the license. See section 6 (Trademarks) of the license for details about trademark usage.
|
||||
|
||||
## 📊 Stargazers
|
||||
|
||||
[](https://github.com/EvolutionAPI/evo-ai/stargazers)
|
||||
|
||||
## 🔄 Forks
|
||||
|
||||
[](https://github.com/EvolutionAPI/evo-ai/network/members)
|
||||
|
||||
## 🙏 Acknowledgments
|
||||
|
||||
- [FastAPI](https://fastapi.tiangolo.com/)
|
||||
- [SQLAlchemy](https://www.sqlalchemy.org/)
|
||||
- [Google ADK](https://github.com/google/adk)
|
||||
- [LangGraph](https://github.com/langchain-ai/langgraph)
|
||||
- [ReactFlow](https://reactflow.dev/)
|
||||
|
||||
41
conftest.py
41
conftest.py
@@ -1,3 +1,32 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: conftest.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy import create_engine
|
||||
@@ -22,11 +51,11 @@ TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engin
|
||||
def db_session():
|
||||
"""Creates a fresh database session for each test."""
|
||||
Base.metadata.create_all(bind=engine) # Create tables
|
||||
|
||||
|
||||
connection = engine.connect()
|
||||
transaction = connection.begin()
|
||||
session = TestingSessionLocal(bind=connection)
|
||||
|
||||
|
||||
# Use our test database instead of the standard one
|
||||
def override_get_db():
|
||||
try:
|
||||
@@ -34,11 +63,11 @@ def db_session():
|
||||
session.commit()
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
|
||||
app.dependency_overrides[get_db] = override_get_db
|
||||
|
||||
|
||||
yield session # The test will run here
|
||||
|
||||
|
||||
# Teardown
|
||||
transaction.rollback()
|
||||
connection.close()
|
||||
@@ -50,4 +79,4 @@ def db_session():
|
||||
def client(db_session):
|
||||
"""Creates a FastAPI TestClient with database session fixture."""
|
||||
with TestClient(app) as test_client:
|
||||
yield test_client
|
||||
yield test_client
|
||||
|
||||
@@ -2,6 +2,7 @@ version: "3.8"
|
||||
|
||||
services:
|
||||
api:
|
||||
image: evo-ai-api:latest
|
||||
build: .
|
||||
container_name: evo-ai-api
|
||||
depends_on:
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
"""add_task_agent_type_agents_table
|
||||
|
||||
Revision ID: 2df073c7b564
|
||||
Revises: 611d84e70bb2
|
||||
Create Date: 2025-05-14 11:46:39.573247
|
||||
|
||||
"""
|
||||
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = "2df073c7b564"
|
||||
down_revision: Union[str, None] = "611d84e70bb2"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""Upgrade schema."""
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_constraint("check_agent_type", "agents", type_="check")
|
||||
op.create_check_constraint(
|
||||
"check_agent_type",
|
||||
"agents",
|
||||
"type IN ('llm', 'sequential', 'parallel', 'loop', 'a2a', 'workflow', 'crew_ai', 'task')",
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""Downgrade schema."""
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_constraint("check_agent_type", "agents", type_="check")
|
||||
op.create_check_constraint(
|
||||
"check_agent_type",
|
||||
"agents",
|
||||
"type IN ('llm', 'sequential', 'parallel', 'loop', 'a2a', 'workflow', 'crew_ai')",
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
@@ -0,0 +1,34 @@
|
||||
"""add_crew_ai_coluns_agents_table
|
||||
|
||||
Revision ID: 611d84e70bb2
|
||||
Revises: bdc5d363e2e1
|
||||
Create Date: 2025-05-14 07:31:08.741620
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = '611d84e70bb2'
|
||||
down_revision: Union[str, None] = 'bdc5d363e2e1'
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""Upgrade schema."""
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.add_column('agents', sa.Column('role', sa.String(), nullable=True))
|
||||
op.add_column('agents', sa.Column('goal', sa.Text(), nullable=True))
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""Downgrade schema."""
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_column('agents', 'goal')
|
||||
op.drop_column('agents', 'role')
|
||||
# ### end Alembic commands ###
|
||||
@@ -0,0 +1,43 @@
|
||||
"""add_crew_ai_agent_type_agents_table
|
||||
|
||||
Revision ID: bdc5d363e2e1
|
||||
Revises: 6db4a526335b
|
||||
Create Date: 2025-05-14 06:23:14.701878
|
||||
|
||||
"""
|
||||
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = "bdc5d363e2e1"
|
||||
down_revision: Union[str, None] = "6db4a526335b"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""Upgrade schema."""
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_constraint("check_agent_type", "agents", type_="check")
|
||||
op.create_check_constraint(
|
||||
"check_agent_type",
|
||||
"agents",
|
||||
"type IN ('llm', 'sequential', 'parallel', 'loop', 'a2a', 'workflow', 'crew_ai')",
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""Downgrade schema."""
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_constraint("check_agent_type", "agents", type_="check")
|
||||
op.create_check_constraint(
|
||||
"check_agent_type",
|
||||
"agents",
|
||||
"type IN ('llm', 'sequential', 'parallel', 'loop', 'a2a', 'workflow')",
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
@@ -8,14 +8,14 @@ version = "1.0.0"
|
||||
description = "API for executing AI agents"
|
||||
readme = "README.md"
|
||||
authors = [
|
||||
{name = "EvoAI Team", email = "admin@evoai.com"}
|
||||
{name = "Davidson Gomes", email = "contato@evolution-api.com"}
|
||||
]
|
||||
requires-python = ">=3.10"
|
||||
license = {text = "Proprietary"}
|
||||
license = {text = "Apache-2.0"}
|
||||
classifiers = [
|
||||
"Programming Language :: Python :: 3",
|
||||
"Programming Language :: Python :: 3.10",
|
||||
"License :: Other/Proprietary License",
|
||||
"License :: OSI Approved :: Apache Software License",
|
||||
"Operating System :: OS Independent",
|
||||
]
|
||||
|
||||
@@ -30,7 +30,7 @@ dependencies = [
|
||||
"google-cloud-aiplatform==1.90.0",
|
||||
"python-dotenv==1.1.0",
|
||||
"google-adk==0.3.0",
|
||||
"litellm==1.68.1",
|
||||
"litellm>=1.68.0,<1.69.0",
|
||||
"python-multipart==0.0.20",
|
||||
"alembic==1.15.2",
|
||||
"asyncpg==0.30.0",
|
||||
|
||||
@@ -1,3 +1,32 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: run_seeders.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
"""
|
||||
Main script to run all seeders in sequence.
|
||||
Checks dependencies between seeders and runs them in the correct order.
|
||||
|
||||
@@ -1,3 +1,32 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: admin_seeder.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
"""
|
||||
Script to create an initial admin user:
|
||||
- Email: admin@evoai.com
|
||||
|
||||
@@ -1,3 +1,32 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: client_seeder.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
"""
|
||||
Script to create a demo client:
|
||||
- Name: Demo Client
|
||||
|
||||
@@ -1,3 +1,32 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: mcp_server_seeder.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
"""
|
||||
Script to create default MCP servers:
|
||||
- Brave Search
|
||||
|
||||
@@ -1,3 +1,32 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: tool_seeder.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
"""
|
||||
Script to create default tools:
|
||||
-
|
||||
|
||||
@@ -1,7 +1,37 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: a2a_routes.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
"""
|
||||
Routes for the A2A (Agent-to-Agent) protocol.
|
||||
|
||||
This module implements the standard A2A routes according to the specification.
|
||||
Supports both text messages and file uploads through the message parts mechanism.
|
||||
"""
|
||||
|
||||
import uuid
|
||||
@@ -63,7 +93,39 @@ async def process_a2a_request(
|
||||
db: Session = Depends(get_db),
|
||||
a2a_service: A2AService = Depends(get_a2a_service),
|
||||
):
|
||||
"""Processes an A2A request."""
|
||||
"""
|
||||
Processes an A2A request.
|
||||
|
||||
Supports both text messages and file uploads. For file uploads,
|
||||
include file parts in the message following the A2A protocol format:
|
||||
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"id": "request-id",
|
||||
"method": "tasks/send",
|
||||
"params": {
|
||||
"id": "task-id",
|
||||
"sessionId": "session-id",
|
||||
"message": {
|
||||
"role": "user",
|
||||
"parts": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "Analyze this image"
|
||||
},
|
||||
{
|
||||
"type": "file",
|
||||
"file": {
|
||||
"name": "example.jpg",
|
||||
"mimeType": "image/jpeg",
|
||||
"bytes": "base64-encoded-content"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
"""
|
||||
# Verify the API key
|
||||
if not verify_api_key(db, x_api_key):
|
||||
raise HTTPException(status_code=401, detail="Invalid API key")
|
||||
@@ -71,10 +133,60 @@ async def process_a2a_request(
|
||||
# Process the request
|
||||
try:
|
||||
request_body = await request.json()
|
||||
|
||||
debug_request_body = {}
|
||||
if "method" in request_body:
|
||||
debug_request_body["method"] = request_body["method"]
|
||||
if "id" in request_body:
|
||||
debug_request_body["id"] = request_body["id"]
|
||||
|
||||
logger.info(f"A2A request received: {debug_request_body}")
|
||||
|
||||
# Log if request contains file parts for debugging
|
||||
if isinstance(request_body, dict) and "params" in request_body:
|
||||
params = request_body.get("params", {})
|
||||
message = params.get("message", {})
|
||||
parts = message.get("parts", [])
|
||||
|
||||
logger.info(f"A2A message contains {len(parts)} parts")
|
||||
for i, part in enumerate(parts):
|
||||
if not isinstance(part, dict):
|
||||
logger.warning(f"Part {i+1} is not a dictionary: {type(part)}")
|
||||
continue
|
||||
|
||||
part_type = part.get("type")
|
||||
logger.info(f"Part {i+1} type: {part_type}")
|
||||
|
||||
if part_type == "file":
|
||||
file_info = part.get("file", {})
|
||||
logger.info(
|
||||
f"File part found: {file_info.get('name')} ({file_info.get('mimeType')})"
|
||||
)
|
||||
if "bytes" in file_info:
|
||||
bytes_data = file_info.get("bytes", "")
|
||||
bytes_size = len(bytes_data) * 0.75
|
||||
logger.info(f"File size: ~{bytes_size/1024:.2f} KB")
|
||||
if bytes_data:
|
||||
sample = (
|
||||
bytes_data[:10] + "..."
|
||||
if len(bytes_data) > 10
|
||||
else bytes_data
|
||||
)
|
||||
logger.info(f"Sample of base64 data: {sample}")
|
||||
elif part_type == "text":
|
||||
text_content = part.get("text", "")
|
||||
preview = (
|
||||
text_content[:30] + "..."
|
||||
if len(text_content) > 30
|
||||
else text_content
|
||||
)
|
||||
logger.info(f"Text part found: '{preview}'")
|
||||
|
||||
result = await a2a_service.process_request(agent_id, request_body)
|
||||
|
||||
# If the response is a streaming response, return as EventSourceResponse
|
||||
if hasattr(result, "__aiter__"):
|
||||
logger.info("Returning streaming response")
|
||||
|
||||
async def event_generator():
|
||||
async for item in result:
|
||||
@@ -86,11 +198,15 @@ async def process_a2a_request(
|
||||
return EventSourceResponse(event_generator())
|
||||
|
||||
# Otherwise, return as JSONResponse
|
||||
logger.info("Returning standard JSON response")
|
||||
if hasattr(result, "model_dump"):
|
||||
return JSONResponse(result.model_dump(exclude_none=True))
|
||||
return JSONResponse(result)
|
||||
except Exception as e:
|
||||
logger.error(f"Error processing A2A request: {e}")
|
||||
import traceback
|
||||
|
||||
logger.error(f"Full traceback: {traceback.format_exc()}")
|
||||
return JSONResponse(
|
||||
status_code=500,
|
||||
content={
|
||||
|
||||
@@ -1,3 +1,32 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: admin_routes.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
from typing import List
|
||||
from fastapi import APIRouter, Depends, HTTPException, status, Request
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
@@ -1,3 +1,32 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: agent_routes.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status, Header, Query
|
||||
from sqlalchemy.orm import Session
|
||||
from src.config.database import get_db
|
||||
@@ -531,3 +560,64 @@ async def delete_agent(
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND, detail="Agent not found"
|
||||
)
|
||||
|
||||
|
||||
@router.post("/{agent_id}/share", response_model=Dict[str, str])
|
||||
async def share_agent(
|
||||
agent_id: uuid.UUID,
|
||||
x_client_id: uuid.UUID = Header(..., alias="x-client-id"),
|
||||
db: Session = Depends(get_db),
|
||||
payload: dict = Depends(get_jwt_token),
|
||||
):
|
||||
"""Returns the agent's API key for sharing"""
|
||||
await verify_user_client(payload, db, x_client_id)
|
||||
|
||||
# Verify if the agent exists
|
||||
agent = agent_service.get_agent(db, agent_id)
|
||||
if not agent:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND, detail="Agent not found"
|
||||
)
|
||||
|
||||
# Verify if the agent belongs to the specified client
|
||||
if agent.client_id != x_client_id:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Agent does not belong to the specified client",
|
||||
)
|
||||
|
||||
# Verify if API key exists
|
||||
if not agent.config or not agent.config.get("api_key"):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="This agent does not have an API key",
|
||||
)
|
||||
|
||||
return {"api_key": agent.config["api_key"]}
|
||||
|
||||
|
||||
@router.get("/{agent_id}/shared", response_model=Agent)
|
||||
async def get_shared_agent(
|
||||
agent_id: uuid.UUID,
|
||||
api_key: str = Header(..., alias="x-api-key"),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Get agent details using only API key authentication"""
|
||||
# Verify if the agent exists
|
||||
agent = agent_service.get_agent(db, agent_id)
|
||||
if not agent or not agent.config:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND, detail="Agent not found"
|
||||
)
|
||||
|
||||
# Verify if the API key matches
|
||||
if not agent.config.get("api_key") or agent.config.get("api_key") != api_key:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid API key"
|
||||
)
|
||||
|
||||
# Add agent card URL if not present
|
||||
if not agent.agent_card_url:
|
||||
agent.agent_card_url = agent.agent_card_url_property
|
||||
|
||||
return agent
|
||||
|
||||
@@ -1,3 +1,32 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: auth_routes.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
from src.config.database import get_db
|
||||
@@ -54,8 +83,7 @@ async def register_user(user_data: UserCreate, db: Session = Depends(get_db)):
|
||||
Raises:
|
||||
HTTPException: If there is an error in registration
|
||||
"""
|
||||
# TODO: remover o auto_verify temporariamente para teste
|
||||
user, message = create_user(db, user_data, is_admin=False, auto_verify=True)
|
||||
user, message = create_user(db, user_data, is_admin=False, auto_verify=False)
|
||||
if not user:
|
||||
logger.error(f"Error registering user: {message}")
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=message)
|
||||
@@ -163,14 +191,36 @@ async def login_for_access_token(form_data: UserLogin, db: Session = Depends(get
|
||||
Raises:
|
||||
HTTPException: If credentials are invalid
|
||||
"""
|
||||
user = authenticate_user(db, form_data.email, form_data.password)
|
||||
user, reason = authenticate_user(db, form_data.email, form_data.password)
|
||||
if not user:
|
||||
logger.warning(f"Login attempt with invalid credentials: {form_data.email}")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid email or password",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
if reason == "user_not_found" or reason == "invalid_password":
|
||||
logger.warning(f"Login attempt with invalid credentials: {form_data.email}")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid email or password",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
elif reason == "email_not_verified":
|
||||
logger.warning(f"Login attempt with unverified email: {form_data.email}")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Email not verified",
|
||||
)
|
||||
elif reason == "inactive_user":
|
||||
logger.warning(f"Login attempt with inactive user: {form_data.email}")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="User account is inactive",
|
||||
)
|
||||
else:
|
||||
logger.warning(
|
||||
f"Login attempt failed for {form_data.email} (reason: {reason})"
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid email or password",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
access_token = create_access_token(user)
|
||||
logger.info(f"Login successful for user: {user.email}")
|
||||
|
||||
@@ -1,3 +1,34 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: chat_routes.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
import uuid
|
||||
import base64
|
||||
from fastapi import (
|
||||
APIRouter,
|
||||
Depends,
|
||||
@@ -5,6 +36,7 @@ from fastapi import (
|
||||
status,
|
||||
WebSocket,
|
||||
WebSocketDisconnect,
|
||||
Header,
|
||||
)
|
||||
from sqlalchemy.orm import Session
|
||||
from src.config.database import get_db
|
||||
@@ -16,7 +48,7 @@ from src.core.jwt_middleware import (
|
||||
from src.services import (
|
||||
agent_service,
|
||||
)
|
||||
from src.schemas.chat import ChatRequest, ChatResponse, ErrorResponse
|
||||
from src.schemas.chat import ChatRequest, ChatResponse, ErrorResponse, FileData
|
||||
from src.services.agent_runner import run_agent, run_agent_stream
|
||||
from src.core.exceptions import AgentNotFoundError
|
||||
from src.services.service_providers import (
|
||||
@@ -28,6 +60,7 @@ from src.services.service_providers import (
|
||||
from datetime import datetime
|
||||
import logging
|
||||
import json
|
||||
from typing import Optional, Dict, List, Any
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -38,6 +71,59 @@ router = APIRouter(
|
||||
)
|
||||
|
||||
|
||||
async def get_agent_by_api_key(
|
||||
agent_id: str,
|
||||
api_key: Optional[str] = Header(None, alias="x-api-key"),
|
||||
authorization: Optional[str] = Header(None),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Flexible authentication for chat routes, allowing JWT or API key"""
|
||||
if authorization:
|
||||
# Try to authenticate with JWT token first
|
||||
try:
|
||||
# Extract token from Authorization header if needed
|
||||
token = (
|
||||
authorization.replace("Bearer ", "")
|
||||
if authorization.startswith("Bearer ")
|
||||
else authorization
|
||||
)
|
||||
payload = await get_jwt_token(token)
|
||||
agent = agent_service.get_agent(db, agent_id)
|
||||
if not agent:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Agent not found",
|
||||
)
|
||||
|
||||
# Verify if the user has access to the agent's client
|
||||
await verify_user_client(payload, db, agent.client_id)
|
||||
return agent
|
||||
except Exception as e:
|
||||
logger.warning(f"JWT authentication failed: {str(e)}")
|
||||
# If JWT fails, continue to try with API key
|
||||
|
||||
# Try to authenticate with API key
|
||||
if not api_key:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Authentication required (JWT or API key)",
|
||||
)
|
||||
|
||||
agent = agent_service.get_agent(db, agent_id)
|
||||
if not agent or not agent.config:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND, detail="Agent not found"
|
||||
)
|
||||
|
||||
# Verify if the API key matches
|
||||
if not agent.config.get("api_key") or agent.config.get("api_key") != api_key:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid API key"
|
||||
)
|
||||
|
||||
return agent
|
||||
|
||||
|
||||
@router.websocket("/ws/{agent_id}/{external_id}")
|
||||
async def websocket_chat(
|
||||
websocket: WebSocket,
|
||||
@@ -53,32 +139,49 @@ async def websocket_chat(
|
||||
# Wait for authentication message
|
||||
try:
|
||||
auth_data = await websocket.receive_json()
|
||||
logger.info(f"Received authentication data: {auth_data}")
|
||||
logger.info(f"Authentication data received: {auth_data}")
|
||||
|
||||
if not auth_data.get("type") == "authorization" or not auth_data.get(
|
||||
"token"
|
||||
if not (
|
||||
auth_data.get("type") == "authorization"
|
||||
and (auth_data.get("token") or auth_data.get("api_key"))
|
||||
):
|
||||
logger.warning("Invalid authentication message")
|
||||
await websocket.close(code=status.WS_1008_POLICY_VIOLATION)
|
||||
return
|
||||
|
||||
token = auth_data["token"]
|
||||
# Verify the token
|
||||
payload = await get_jwt_token_ws(token)
|
||||
if not payload:
|
||||
logger.warning("Invalid token")
|
||||
await websocket.close(code=status.WS_1008_POLICY_VIOLATION)
|
||||
return
|
||||
|
||||
# Verify if the agent belongs to the user's client
|
||||
# Verify if the agent exists
|
||||
agent = agent_service.get_agent(db, agent_id)
|
||||
if not agent:
|
||||
logger.warning(f"Agent {agent_id} not found")
|
||||
await websocket.close(code=status.WS_1008_POLICY_VIOLATION)
|
||||
return
|
||||
|
||||
# Verify if the user has access to the agent (via client)
|
||||
await verify_user_client(payload, db, agent.client_id)
|
||||
# Verify authentication
|
||||
is_authenticated = False
|
||||
|
||||
# Try with JWT token
|
||||
if auth_data.get("token"):
|
||||
try:
|
||||
payload = await get_jwt_token_ws(auth_data["token"])
|
||||
if payload:
|
||||
# Verify if the user has access to the agent
|
||||
await verify_user_client(payload, db, agent.client_id)
|
||||
is_authenticated = True
|
||||
except Exception as e:
|
||||
logger.warning(f"JWT authentication failed: {str(e)}")
|
||||
|
||||
# If JWT fails, try with API key
|
||||
if not is_authenticated and auth_data.get("api_key"):
|
||||
if agent.config and agent.config.get("api_key") == auth_data.get(
|
||||
"api_key"
|
||||
):
|
||||
is_authenticated = True
|
||||
else:
|
||||
logger.warning("Invalid API key")
|
||||
|
||||
if not is_authenticated:
|
||||
await websocket.close(code=status.WS_1008_POLICY_VIOLATION)
|
||||
return
|
||||
|
||||
logger.info(
|
||||
f"WebSocket connection established for agent {agent_id} and external_id {external_id}"
|
||||
@@ -93,6 +196,29 @@ async def websocket_chat(
|
||||
if not message:
|
||||
continue
|
||||
|
||||
files = None
|
||||
if data.get("files") and isinstance(data.get("files"), list):
|
||||
try:
|
||||
files = []
|
||||
for file_data in data.get("files"):
|
||||
if (
|
||||
isinstance(file_data, dict)
|
||||
and file_data.get("filename")
|
||||
and file_data.get("content_type")
|
||||
and file_data.get("data")
|
||||
):
|
||||
files.append(
|
||||
FileData(
|
||||
filename=file_data.get("filename"),
|
||||
content_type=file_data.get("content_type"),
|
||||
data=file_data.get("data"),
|
||||
)
|
||||
)
|
||||
logger.info(f"Processed {len(files)} files via WebSocket")
|
||||
except Exception as e:
|
||||
logger.error(f"Error processing files: {str(e)}")
|
||||
files = None
|
||||
|
||||
async for chunk in run_agent_stream(
|
||||
agent_id=agent_id,
|
||||
external_id=external_id,
|
||||
@@ -101,6 +227,7 @@ async def websocket_chat(
|
||||
artifacts_service=artifacts_service,
|
||||
memory_service=memory_service,
|
||||
db=db,
|
||||
files=files,
|
||||
):
|
||||
await websocket.send_json(
|
||||
{"message": json.loads(chunk), "turn_complete": False}
|
||||
@@ -145,21 +272,11 @@ async def websocket_chat(
|
||||
)
|
||||
async def chat(
|
||||
request: ChatRequest,
|
||||
_=Depends(get_agent_by_api_key),
|
||||
db: Session = Depends(get_db),
|
||||
payload: dict = Depends(get_jwt_token),
|
||||
):
|
||||
# Verify if the agent belongs to the user's client
|
||||
agent = agent_service.get_agent(db, request.agent_id)
|
||||
if not agent:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND, detail="Agent not found"
|
||||
)
|
||||
|
||||
# Verify if the user has access to the agent (via client)
|
||||
await verify_user_client(payload, db, agent.client_id)
|
||||
|
||||
try:
|
||||
final_response_text = await run_agent(
|
||||
final_response = await run_agent(
|
||||
request.agent_id,
|
||||
request.external_id,
|
||||
request.message,
|
||||
@@ -167,17 +284,19 @@ async def chat(
|
||||
artifacts_service,
|
||||
memory_service,
|
||||
db,
|
||||
files=request.files,
|
||||
)
|
||||
|
||||
return {
|
||||
"response": final_response_text,
|
||||
"response": final_response["final_response"],
|
||||
"message_history": final_response["message_history"],
|
||||
"status": "success",
|
||||
"timestamp": datetime.now().isoformat(),
|
||||
}
|
||||
|
||||
except AgentNotFoundError as e:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e)) from e
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e)
|
||||
)
|
||||
) from e
|
||||
|
||||
@@ -1,3 +1,32 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: client_routes.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from pydantic import BaseModel, EmailStr
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
@@ -1,3 +1,32 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: mcp_server_routes.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
from src.config.database import get_db
|
||||
|
||||
@@ -1,8 +1,38 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: session_routes.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
from src.config.database import get_db
|
||||
from typing import List
|
||||
from typing import List, Optional, Dict, Any
|
||||
import uuid
|
||||
import base64
|
||||
from src.core.jwt_middleware import (
|
||||
get_jwt_token,
|
||||
verify_user_client,
|
||||
@@ -19,7 +49,7 @@ from src.services.session_service import (
|
||||
get_sessions_by_agent,
|
||||
get_sessions_by_client,
|
||||
)
|
||||
from src.services.service_providers import session_service
|
||||
from src.services.service_providers import session_service, artifacts_service
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -89,13 +119,18 @@ async def get_session(
|
||||
|
||||
@router.get(
|
||||
"/{session_id}/messages",
|
||||
response_model=List[Event],
|
||||
)
|
||||
async def get_agent_messages(
|
||||
session_id: str,
|
||||
db: Session = Depends(get_db),
|
||||
payload: dict = Depends(get_jwt_token),
|
||||
):
|
||||
"""
|
||||
Gets messages from a session with embedded artifacts.
|
||||
|
||||
This function loads all messages from a session and processes any references
|
||||
to artifacts, loading them and converting them to base64 for direct use in the frontend.
|
||||
"""
|
||||
# Get the session
|
||||
session = get_session_by_id(session_service, session_id)
|
||||
if not session:
|
||||
@@ -110,7 +145,160 @@ async def get_agent_messages(
|
||||
if agent:
|
||||
await verify_user_client(payload, db, agent.client_id)
|
||||
|
||||
return get_session_events(session_service, session_id)
|
||||
# Parse session ID para obter app_name e user_id
|
||||
parts = session_id.split("_")
|
||||
if len(parts) != 2:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid session ID format"
|
||||
)
|
||||
|
||||
user_id, app_name = parts[0], parts[1]
|
||||
|
||||
events = get_session_events(session_service, session_id)
|
||||
|
||||
processed_events = []
|
||||
for event in events:
|
||||
event_dict = event.dict()
|
||||
|
||||
def process_dict(d):
|
||||
if isinstance(d, dict):
|
||||
for key, value in list(d.items()):
|
||||
if isinstance(value, bytes):
|
||||
try:
|
||||
d[key] = base64.b64encode(value).decode("utf-8")
|
||||
logger.debug(f"Converted bytes field to base64: {key}")
|
||||
except Exception as e:
|
||||
logger.error(f"Error encoding bytes to base64: {str(e)}")
|
||||
d[key] = None
|
||||
elif isinstance(value, dict):
|
||||
process_dict(value)
|
||||
elif isinstance(value, list):
|
||||
for item in value:
|
||||
if isinstance(item, (dict, list)):
|
||||
process_dict(item)
|
||||
elif isinstance(d, list):
|
||||
for i, item in enumerate(d):
|
||||
if isinstance(item, bytes):
|
||||
try:
|
||||
d[i] = base64.b64encode(item).decode("utf-8")
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"Error encoding bytes to base64 in list: {str(e)}"
|
||||
)
|
||||
d[i] = None
|
||||
elif isinstance(item, (dict, list)):
|
||||
process_dict(item)
|
||||
return d
|
||||
|
||||
# Process all event dictionary
|
||||
event_dict = process_dict(event_dict)
|
||||
|
||||
# Process the content parts specifically
|
||||
if event_dict.get("content") and event_dict["content"].get("parts"):
|
||||
for part in event_dict["content"]["parts"]:
|
||||
# Process inlineData if present
|
||||
if part and part.get("inlineData") and part["inlineData"].get("data"):
|
||||
# Check if it's already a string or if it's bytes
|
||||
if isinstance(part["inlineData"]["data"], bytes):
|
||||
# Convert bytes to base64 string
|
||||
part["inlineData"]["data"] = base64.b64encode(
|
||||
part["inlineData"]["data"]
|
||||
).decode("utf-8")
|
||||
logger.debug(
|
||||
f"Converted binary data to base64 in message {event_dict.get('id')}"
|
||||
)
|
||||
|
||||
# Process fileData if present (reference to an artifact)
|
||||
if part and part.get("fileData") and part["fileData"].get("fileId"):
|
||||
try:
|
||||
# Extract the file name from the fileId
|
||||
file_id = part["fileData"]["fileId"]
|
||||
|
||||
# Load the artifact from the artifacts service
|
||||
artifact = artifacts_service.load_artifact(
|
||||
app_name=app_name,
|
||||
user_id=user_id,
|
||||
session_id=session_id,
|
||||
filename=file_id,
|
||||
)
|
||||
|
||||
if artifact and hasattr(artifact, "inline_data"):
|
||||
# Extract the data and MIME type
|
||||
file_bytes = artifact.inline_data.data
|
||||
mime_type = artifact.inline_data.mime_type
|
||||
|
||||
# Add inlineData with the artifact data
|
||||
if not part.get("inlineData"):
|
||||
part["inlineData"] = {}
|
||||
|
||||
# Ensure we're sending a base64 string, not bytes
|
||||
if isinstance(file_bytes, bytes):
|
||||
try:
|
||||
part["inlineData"]["data"] = base64.b64encode(
|
||||
file_bytes
|
||||
).decode("utf-8")
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"Error encoding artifact to base64: {str(e)}"
|
||||
)
|
||||
part["inlineData"]["data"] = None
|
||||
else:
|
||||
part["inlineData"]["data"] = str(file_bytes)
|
||||
|
||||
part["inlineData"]["mimeType"] = mime_type
|
||||
|
||||
logger.debug(
|
||||
f"Loaded artifact {file_id} for message {event_dict.get('id')}"
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Error loading artifact: {str(e)}")
|
||||
# Don't interrupt the flow if an artifact fails
|
||||
|
||||
# Check artifact_delta in actions
|
||||
if event_dict.get("actions") and event_dict["actions"].get("artifact_delta"):
|
||||
artifact_deltas = event_dict["actions"]["artifact_delta"]
|
||||
for filename, version in artifact_deltas.items():
|
||||
try:
|
||||
# Load the artifact
|
||||
artifact = artifacts_service.load_artifact(
|
||||
app_name=app_name,
|
||||
user_id=user_id,
|
||||
session_id=session_id,
|
||||
filename=filename,
|
||||
version=version,
|
||||
)
|
||||
|
||||
if artifact and hasattr(artifact, "inline_data"):
|
||||
# If the event doesn't have an artifacts section, create it
|
||||
if "artifacts" not in event_dict:
|
||||
event_dict["artifacts"] = {}
|
||||
|
||||
# Add the artifact to the event's artifacts list
|
||||
file_bytes = artifact.inline_data.data
|
||||
mime_type = artifact.inline_data.mime_type
|
||||
|
||||
# Ensure the bytes are converted to base64
|
||||
event_dict["artifacts"][filename] = {
|
||||
"data": (
|
||||
base64.b64encode(file_bytes).decode("utf-8")
|
||||
if isinstance(file_bytes, bytes)
|
||||
else str(file_bytes)
|
||||
),
|
||||
"mimeType": mime_type,
|
||||
"version": version,
|
||||
}
|
||||
|
||||
logger.debug(
|
||||
f"Added artifact {filename} (v{version}) to message {event_dict.get('id')}"
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"Error processing artifact_delta {filename}: {str(e)}"
|
||||
)
|
||||
|
||||
processed_events.append(event_dict)
|
||||
|
||||
return processed_events
|
||||
|
||||
|
||||
@router.delete(
|
||||
|
||||
@@ -1,3 +1,32 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: tool_routes.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
from src.config.database import get_db
|
||||
|
||||
@@ -1,3 +1,32 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: database.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
@@ -1,3 +1,32 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: redis.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
"""
|
||||
Redis configuration module.
|
||||
|
||||
|
||||
@@ -1,3 +1,32 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: settings.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
import os
|
||||
from typing import Optional, List
|
||||
from pydantic_settings import BaseSettings
|
||||
@@ -52,9 +81,22 @@ class Settings(BaseSettings):
|
||||
# Encryption settings
|
||||
ENCRYPTION_KEY: str = os.getenv("ENCRYPTION_KEY", secrets.token_urlsafe(32))
|
||||
|
||||
# Email provider settings
|
||||
EMAIL_PROVIDER: str = os.getenv("EMAIL_PROVIDER", "sendgrid")
|
||||
|
||||
# SendGrid settings
|
||||
SENDGRID_API_KEY: str = os.getenv("SENDGRID_API_KEY", "")
|
||||
EMAIL_FROM: str = os.getenv("EMAIL_FROM", "noreply@yourdomain.com")
|
||||
|
||||
# SMTP settings
|
||||
SMTP_HOST: str = os.getenv("SMTP_HOST", "")
|
||||
SMTP_PORT: int = int(os.getenv("SMTP_PORT", 587))
|
||||
SMTP_USER: str = os.getenv("SMTP_USER", "")
|
||||
SMTP_PASSWORD: str = os.getenv("SMTP_PASSWORD", "")
|
||||
SMTP_USE_TLS: bool = os.getenv("SMTP_USE_TLS", "true").lower() == "true"
|
||||
SMTP_USE_SSL: bool = os.getenv("SMTP_USE_SSL", "false").lower() == "true"
|
||||
SMTP_FROM: str = os.getenv("SMTP_FROM", "")
|
||||
|
||||
APP_URL: str = os.getenv("APP_URL", "http://localhost:8000")
|
||||
|
||||
# Server settings
|
||||
|
||||
@@ -1,3 +1,32 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: exceptions.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
from fastapi import HTTPException
|
||||
from typing import Optional, Dict, Any
|
||||
|
||||
|
||||
@@ -1,3 +1,32 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: jwt_middleware.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
from fastapi import HTTPException, Depends, status
|
||||
from fastapi.security import OAuth2PasswordBearer
|
||||
from jose import JWTError, jwt
|
||||
|
||||
29
src/main.py
29
src/main.py
@@ -1,3 +1,32 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: main.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
@@ -1,3 +1,32 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: models.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
import os
|
||||
from sqlalchemy import (
|
||||
Column,
|
||||
@@ -71,6 +100,8 @@ class Agent(Base):
|
||||
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
client_id = Column(UUID(as_uuid=True), ForeignKey("clients.id", ondelete="CASCADE"))
|
||||
name = Column(String, nullable=False)
|
||||
role = Column(String, nullable=True)
|
||||
goal = Column(Text, nullable=True)
|
||||
description = Column(Text, nullable=True)
|
||||
type = Column(String, nullable=False)
|
||||
model = Column(String, nullable=True, default="")
|
||||
@@ -92,7 +123,7 @@ class Agent(Base):
|
||||
|
||||
__table_args__ = (
|
||||
CheckConstraint(
|
||||
"type IN ('llm', 'sequential', 'parallel', 'loop', 'a2a', 'workflow')",
|
||||
"type IN ('llm', 'sequential', 'parallel', 'loop', 'a2a', 'workflow', 'crew_ai', 'task')",
|
||||
name="check_agent_type",
|
||||
),
|
||||
)
|
||||
|
||||
@@ -1,6 +1,35 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: a2a_types.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from enum import Enum
|
||||
from typing import Annotated, Any, Literal
|
||||
from typing import Annotated, Any, Literal, Union, Dict, List, Optional
|
||||
from uuid import uuid4
|
||||
from typing_extensions import Self
|
||||
|
||||
|
||||
@@ -1,8 +1,39 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: agent_config.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
from typing import List, Optional, Dict, Union, Any
|
||||
from pydantic import BaseModel, Field
|
||||
from uuid import UUID
|
||||
import secrets
|
||||
import string
|
||||
import uuid
|
||||
from pydantic import validator
|
||||
|
||||
|
||||
class ToolConfig(BaseModel):
|
||||
@@ -205,3 +236,45 @@ class WorkflowConfig(BaseModel):
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class AgentTask(BaseModel):
|
||||
"""Task configuration for agents"""
|
||||
|
||||
agent_id: Union[UUID, str] = Field(
|
||||
..., description="ID of the agent assigned to this task"
|
||||
)
|
||||
enabled_tools: Optional[List[str]] = Field(
|
||||
default_factory=list, description="List of tool names to be used in the task"
|
||||
)
|
||||
description: str = Field(..., description="Description of the task to be performed")
|
||||
expected_output: str = Field(..., description="Expected output from this task")
|
||||
|
||||
@validator("agent_id")
|
||||
def validate_agent_id(cls, v):
|
||||
if isinstance(v, str):
|
||||
try:
|
||||
return uuid.UUID(v)
|
||||
except ValueError:
|
||||
raise ValueError(f"Invalid UUID format for agent_id: {v}")
|
||||
return v
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class AgentConfig(BaseModel):
|
||||
"""Configuration for agents"""
|
||||
|
||||
tasks: List[AgentTask] = Field(
|
||||
..., description="List of tasks to be performed by the agent"
|
||||
)
|
||||
api_key: Optional[str] = Field(
|
||||
default_factory=generate_api_key, description="API key for the agent"
|
||||
)
|
||||
sub_agents: Optional[List[UUID]] = Field(
|
||||
default_factory=list, description="List of IDs of sub-agents used in agent"
|
||||
)
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
@@ -1,3 +1,32 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: audit.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from typing import Optional, Dict, Any
|
||||
from datetime import datetime
|
||||
|
||||
@@ -1,33 +1,68 @@
|
||||
from pydantic import BaseModel, Field
|
||||
from typing import Dict, Any, Optional
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: chat.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
from pydantic import BaseModel, Field, validator
|
||||
from typing import Dict, List, Optional, Any
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
class FileData(BaseModel):
|
||||
"""Model to represent file data sent in a chat request."""
|
||||
|
||||
filename: str = Field(..., description="File name")
|
||||
content_type: str = Field(..., description="File content type")
|
||||
data: str = Field(..., description="File content encoded in base64")
|
||||
|
||||
|
||||
class ChatRequest(BaseModel):
|
||||
"""Schema for chat requests"""
|
||||
"""Model to represent a chat request."""
|
||||
|
||||
agent_id: str = Field(
|
||||
..., description="ID of the agent that will process the message"
|
||||
agent_id: str = Field(..., description="Agent ID to process the message")
|
||||
external_id: str = Field(..., description="External ID for user identification")
|
||||
message: str = Field(..., description="User message to the agent")
|
||||
files: Optional[List[FileData]] = Field(
|
||||
None, description="List of files attached to the message"
|
||||
)
|
||||
external_id: str = Field(
|
||||
..., description="ID of the external_id that will process the message"
|
||||
)
|
||||
message: str = Field(..., description="User message")
|
||||
|
||||
|
||||
class ChatResponse(BaseModel):
|
||||
"""Schema for chat responses"""
|
||||
"""Model to represent a chat response."""
|
||||
|
||||
response: str = Field(..., description="Agent response")
|
||||
status: str = Field(..., description="Operation status")
|
||||
error: Optional[str] = Field(None, description="Error message, if there is one")
|
||||
timestamp: str = Field(..., description="Timestamp of the response")
|
||||
response: str = Field(..., description="Response generated by the agent")
|
||||
message_history: List[Dict[str, Any]] = Field(
|
||||
default_factory=list, description="Message history"
|
||||
)
|
||||
status: str = Field(..., description="Response status (success/error)")
|
||||
timestamp: str = Field(..., description="Response timestamp")
|
||||
|
||||
|
||||
class ErrorResponse(BaseModel):
|
||||
"""Schema for error responses"""
|
||||
"""Model to represent an error response."""
|
||||
|
||||
error: str = Field(..., description="Error message")
|
||||
status_code: int = Field(..., description="HTTP status code of the error")
|
||||
details: Optional[Dict[str, Any]] = Field(
|
||||
None, description="Additional error details"
|
||||
)
|
||||
detail: str = Field(..., description="Error details")
|
||||
|
||||
@@ -1,10 +1,39 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: schemas.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
from pydantic import BaseModel, Field, validator, UUID4, ConfigDict
|
||||
from typing import Optional, Dict, Any, List
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
import uuid
|
||||
import re
|
||||
from src.schemas.agent_config import LLMConfig
|
||||
from src.schemas.agent_config import LLMConfig, AgentConfig
|
||||
|
||||
|
||||
class ClientBase(BaseModel):
|
||||
@@ -65,8 +94,11 @@ class AgentBase(BaseModel):
|
||||
None, description="Agent name (no spaces or special characters)"
|
||||
)
|
||||
description: Optional[str] = Field(None, description="Agent description")
|
||||
role: Optional[str] = Field(None, description="Agent role in the system")
|
||||
goal: Optional[str] = Field(None, description="Agent goal or objective")
|
||||
type: str = Field(
|
||||
..., description="Agent type (llm, sequential, parallel, loop, a2a, workflow)"
|
||||
...,
|
||||
description="Agent type (llm, sequential, parallel, loop, a2a, workflow, task)",
|
||||
)
|
||||
model: Optional[str] = Field(
|
||||
None, description="Agent model (required only for llm type)"
|
||||
@@ -97,9 +129,17 @@ class AgentBase(BaseModel):
|
||||
|
||||
@validator("type")
|
||||
def validate_type(cls, v):
|
||||
if v not in ["llm", "sequential", "parallel", "loop", "a2a", "workflow"]:
|
||||
if v not in [
|
||||
"llm",
|
||||
"sequential",
|
||||
"parallel",
|
||||
"loop",
|
||||
"a2a",
|
||||
"workflow",
|
||||
"task",
|
||||
]:
|
||||
raise ValueError(
|
||||
"Invalid agent type. Must be: llm, sequential, parallel, loop, a2a or workflow"
|
||||
"Invalid agent type. Must be: llm, sequential, parallel, loop, a2a, workflow or task"
|
||||
)
|
||||
return v
|
||||
|
||||
@@ -159,6 +199,28 @@ class AgentBase(BaseModel):
|
||||
raise ValueError(
|
||||
f'Agent {values["type"]} must have at least one sub-agent'
|
||||
)
|
||||
elif values["type"] == "task":
|
||||
if not isinstance(v, dict):
|
||||
raise ValueError(f'Invalid configuration for agent {values["type"]}')
|
||||
if "tasks" not in v:
|
||||
raise ValueError(f'Agent {values["type"]} must have tasks')
|
||||
if not isinstance(v["tasks"], list):
|
||||
raise ValueError("tasks must be a list")
|
||||
if not v["tasks"]:
|
||||
raise ValueError(f'Agent {values["type"]} must have at least one task')
|
||||
for task in v["tasks"]:
|
||||
if not isinstance(task, dict):
|
||||
raise ValueError("Each task must be a dictionary")
|
||||
required_fields = ["agent_id", "description", "expected_output"]
|
||||
for field in required_fields:
|
||||
if field not in task:
|
||||
raise ValueError(f"Task missing required field: {field}")
|
||||
|
||||
if "sub_agents" in v and v["sub_agents"] is not None:
|
||||
if not isinstance(v["sub_agents"], list):
|
||||
raise ValueError("sub_agents must be a list")
|
||||
|
||||
return v
|
||||
|
||||
return v
|
||||
|
||||
|
||||
@@ -1,3 +1,32 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: streaming.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Dict, List, Optional, Any, Literal
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
@@ -1,3 +1,32 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: user.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
from pydantic import BaseModel, EmailStr, Field
|
||||
from typing import Optional
|
||||
from datetime import datetime
|
||||
|
||||
@@ -1,167 +0,0 @@
|
||||
from google.adk.agents import BaseAgent
|
||||
from google.adk.agents.invocation_context import InvocationContext
|
||||
from google.adk.events import Event
|
||||
from google.genai.types import Content, Part
|
||||
|
||||
from typing import AsyncGenerator, List
|
||||
|
||||
from src.schemas.a2a_types import (
|
||||
SendTaskRequest,
|
||||
Message,
|
||||
TextPart,
|
||||
)
|
||||
|
||||
import httpx
|
||||
|
||||
from uuid import uuid4
|
||||
|
||||
|
||||
class A2ACustomAgent(BaseAgent):
|
||||
"""
|
||||
Custom agent that implements the A2A protocol directly.
|
||||
|
||||
This agent implements the interaction with an external A2A service.
|
||||
"""
|
||||
|
||||
# Field declarations for Pydantic
|
||||
agent_card_url: str
|
||||
timeout: int
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
name: str,
|
||||
agent_card_url: str,
|
||||
timeout: int = 300,
|
||||
sub_agents: List[BaseAgent] = [],
|
||||
**kwargs,
|
||||
):
|
||||
"""
|
||||
Initialize the A2A agent.
|
||||
|
||||
Args:
|
||||
name: Agent name
|
||||
agent_card_url: A2A agent card URL
|
||||
timeout: Maximum execution time (seconds)
|
||||
sub_agents: List of sub-agents to be executed after the A2A agent
|
||||
"""
|
||||
# Initialize base class
|
||||
super().__init__(
|
||||
name=name,
|
||||
agent_card_url=agent_card_url,
|
||||
timeout=timeout,
|
||||
sub_agents=sub_agents,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
print(f"A2A agent initialized for URL: {agent_card_url}")
|
||||
|
||||
async def _run_async_impl(
|
||||
self, ctx: InvocationContext
|
||||
) -> AsyncGenerator[Event, None]:
|
||||
"""
|
||||
Implementation of the A2A protocol according to the Google ADK documentation.
|
||||
|
||||
This method follows the pattern of implementing custom agents,
|
||||
sending the user's message to the A2A service and monitoring the response.
|
||||
"""
|
||||
|
||||
try:
|
||||
# Prepare the base URL for the A2A
|
||||
url = self.agent_card_url
|
||||
|
||||
# Ensure that there is no /.well-known/agent.json in the url
|
||||
if "/.well-known/agent.json" in url:
|
||||
url = url.split("/.well-known/agent.json")[0]
|
||||
|
||||
# 2. Extract the user's message from the context
|
||||
user_message = None
|
||||
|
||||
# Search for the user's message in the session events
|
||||
if ctx.session and hasattr(ctx.session, "events") and ctx.session.events:
|
||||
for event in reversed(ctx.session.events):
|
||||
if event.author == "user" and event.content and event.content.parts:
|
||||
user_message = event.content.parts[0].text
|
||||
print("Message found in session events")
|
||||
break
|
||||
|
||||
# Check in the session state if the message was not found in the events
|
||||
if not user_message and ctx.session and ctx.session.state:
|
||||
if "user_message" in ctx.session.state:
|
||||
user_message = ctx.session.state["user_message"]
|
||||
elif "message" in ctx.session.state:
|
||||
user_message = ctx.session.state["message"]
|
||||
|
||||
# 3. Create and send the task to the A2A agent
|
||||
print(f"Sending task to A2A agent: {user_message[:100]}...")
|
||||
|
||||
# Use the session ID as a stable identifier
|
||||
session_id = (
|
||||
str(ctx.session.id)
|
||||
if ctx.session and hasattr(ctx.session, "id")
|
||||
else str(uuid4())
|
||||
)
|
||||
task_id = str(uuid4())
|
||||
|
||||
try:
|
||||
|
||||
formatted_message: Message = Message(
|
||||
role="user",
|
||||
parts=[TextPart(type="text", text=user_message)],
|
||||
)
|
||||
|
||||
request: SendTaskRequest = SendTaskRequest(
|
||||
params={
|
||||
"message": formatted_message,
|
||||
"sessionId": session_id,
|
||||
"id": task_id,
|
||||
}
|
||||
)
|
||||
|
||||
print(f"Request send task: {request.model_dump()}")
|
||||
|
||||
# REQUEST POST to url when jsonrpc is 2.0
|
||||
task_result = await httpx.AsyncClient().post(
|
||||
url, json=request.model_dump(), timeout=self.timeout
|
||||
)
|
||||
|
||||
print(f"Task response: {task_result.json()}")
|
||||
print(f"Task sent successfully, ID: {task_id}")
|
||||
|
||||
agent_response_parts = task_result.json()["result"]["status"][
|
||||
"message"
|
||||
]["parts"]
|
||||
|
||||
parts = [Part(text=part["text"]) for part in agent_response_parts]
|
||||
|
||||
yield Event(
|
||||
author=self.name,
|
||||
content=Content(role="agent", parts=parts),
|
||||
)
|
||||
|
||||
# Run sub-agents
|
||||
for sub_agent in self.sub_agents:
|
||||
async for event in sub_agent.run_async(ctx):
|
||||
yield event
|
||||
|
||||
except Exception as e:
|
||||
error_msg = f"Error sending request: {str(e)}"
|
||||
print(error_msg)
|
||||
print(f"Error type: {type(e).__name__}")
|
||||
print(f"Error details: {str(e)}")
|
||||
|
||||
yield Event(
|
||||
author=self.name,
|
||||
content=Content(role="agent", parts=[Part(text=error_msg)]),
|
||||
)
|
||||
return
|
||||
|
||||
except Exception as e:
|
||||
# Handle any uncaught error
|
||||
print(f"Error executing A2A agent: {str(e)}")
|
||||
yield Event(
|
||||
author=self.name,
|
||||
content=Content(
|
||||
role="agent",
|
||||
parts=[Part(text=f"Error interacting with A2A agent: {str(e)}")],
|
||||
),
|
||||
)
|
||||
@@ -1,10 +1,43 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: a2a_task_manager.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
import logging
|
||||
import asyncio
|
||||
from collections.abc import AsyncIterable
|
||||
from typing import Dict, Optional
|
||||
from uuid import UUID
|
||||
import json
|
||||
import base64
|
||||
import uuid as uuid_pkg
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
from google.genai.types import Part, Blob
|
||||
|
||||
from src.config.settings import settings
|
||||
from src.services.agent_service import (
|
||||
@@ -46,6 +79,7 @@ from src.schemas.a2a_types import (
|
||||
AgentAuthentication,
|
||||
AgentProvider,
|
||||
)
|
||||
from src.schemas.chat import FileData
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -236,29 +270,48 @@ class A2ATaskManager:
|
||||
) -> JSONRPCResponse:
|
||||
"""Processes a task using the specified agent."""
|
||||
task_params = request.params
|
||||
query = self._extract_user_query(task_params)
|
||||
|
||||
try:
|
||||
# Process the query with the agent
|
||||
result = await self._run_agent(agent, query, task_params.sessionId)
|
||||
query = self._extract_user_query(task_params)
|
||||
result_obj = await self._run_agent(agent, query, task_params.sessionId)
|
||||
|
||||
# Create the response part
|
||||
text_part = {"type": "text", "text": result}
|
||||
parts = [text_part]
|
||||
agent_message = Message(role="agent", parts=parts)
|
||||
|
||||
# Determine the task state
|
||||
task_state = (
|
||||
TaskState.INPUT_REQUIRED
|
||||
if "MISSING_INFO:" in result
|
||||
else TaskState.COMPLETED
|
||||
all_messages = await self._extract_messages_from_history(
|
||||
result_obj.get("message_history", [])
|
||||
)
|
||||
|
||||
# Update the task in the store
|
||||
result = result_obj["final_response"]
|
||||
agent_message = self._create_result_message(result)
|
||||
|
||||
if not all_messages and result:
|
||||
all_messages.append(agent_message)
|
||||
|
||||
task_state = self._determine_task_state(result)
|
||||
|
||||
# Create artifacts for any file content
|
||||
artifacts = []
|
||||
# First, add the main response as an artifact
|
||||
artifacts.append(Artifact(parts=agent_message.parts, index=0))
|
||||
|
||||
# Also add any files from the message history
|
||||
for idx, msg in enumerate(all_messages, 1):
|
||||
for part in msg.parts:
|
||||
if hasattr(part, "type") and part.type == "file":
|
||||
artifacts.append(
|
||||
Artifact(
|
||||
parts=[part],
|
||||
index=idx,
|
||||
name=part.file.name,
|
||||
description=f"File from message {idx}",
|
||||
)
|
||||
)
|
||||
|
||||
task = await self.update_store(
|
||||
task_params.id,
|
||||
TaskStatus(state=task_state, message=agent_message),
|
||||
[Artifact(parts=parts, index=0)],
|
||||
artifacts,
|
||||
)
|
||||
|
||||
await self._update_task_history(
|
||||
task_params.id, task_params.message, all_messages
|
||||
)
|
||||
|
||||
return SendTaskResponse(id=request.id, result=task)
|
||||
@@ -269,12 +322,74 @@ class A2ATaskManager:
|
||||
error=InternalError(message=f"Error processing task: {str(e)}"),
|
||||
)
|
||||
|
||||
async def _extract_messages_from_history(self, agent_history):
|
||||
"""Extracts messages from the agent history."""
|
||||
all_messages = []
|
||||
for message_event in agent_history:
|
||||
try:
|
||||
if (
|
||||
not isinstance(message_event, dict)
|
||||
or "content" not in message_event
|
||||
):
|
||||
continue
|
||||
|
||||
content = message_event.get("content", {})
|
||||
if not isinstance(content, dict):
|
||||
continue
|
||||
|
||||
role = content.get("role", "agent")
|
||||
if role not in ["user", "agent"]:
|
||||
role = "agent"
|
||||
|
||||
parts = content.get("parts", [])
|
||||
if not parts:
|
||||
continue
|
||||
|
||||
if valid_parts := self._validate_message_parts(parts):
|
||||
agent_message = Message(role=role, parts=valid_parts)
|
||||
all_messages.append(agent_message)
|
||||
except Exception as e:
|
||||
logger.error(f"Error processing message history: {e}")
|
||||
return all_messages
|
||||
|
||||
def _validate_message_parts(self, parts):
|
||||
"""Validates and formats message parts."""
|
||||
valid_parts = []
|
||||
for part in parts:
|
||||
if isinstance(part, dict):
|
||||
if "type" not in part and "text" in part:
|
||||
part["type"] = "text"
|
||||
valid_parts.append(part)
|
||||
elif "type" in part:
|
||||
valid_parts.append(part)
|
||||
return valid_parts
|
||||
|
||||
def _create_result_message(self, result):
|
||||
"""Creates a message from the result."""
|
||||
text_part = {"type": "text", "text": result}
|
||||
return Message(role="agent", parts=[text_part])
|
||||
|
||||
def _determine_task_state(self, result):
|
||||
"""Determines the task state based on the result."""
|
||||
return (
|
||||
TaskState.INPUT_REQUIRED
|
||||
if "MISSING_INFO:" in result
|
||||
else TaskState.COMPLETED
|
||||
)
|
||||
|
||||
async def _update_task_history(self, task_id, user_message, agent_messages):
|
||||
"""Updates the task history."""
|
||||
async with self.lock:
|
||||
if task_id in self.tasks:
|
||||
task = self.tasks[task_id]
|
||||
task.history = [user_message] + agent_messages
|
||||
|
||||
async def _stream_task_process(
|
||||
self, request: SendTaskStreamingRequest, agent: Agent
|
||||
) -> AsyncIterable[SendTaskStreamingResponse]:
|
||||
"""Processes a task in streaming mode using the specified agent."""
|
||||
task_params = request.params
|
||||
query = self._extract_user_query(task_params)
|
||||
# Extrair e processar arquivos da mesma forma que no método _process_task
|
||||
query = self._extract_user_query(request.params)
|
||||
|
||||
try:
|
||||
# Send initial processing status
|
||||
@@ -286,14 +401,14 @@ class A2ATaskManager:
|
||||
|
||||
# Update the task with the processing message and inform the WORKING state
|
||||
await self.update_store(
|
||||
task_params.id,
|
||||
request.params.id,
|
||||
TaskStatus(state=TaskState.WORKING, message=processing_message),
|
||||
)
|
||||
|
||||
yield SendTaskStreamingResponse(
|
||||
id=request.id,
|
||||
result=TaskStatusUpdateEvent(
|
||||
id=task_params.id,
|
||||
id=request.params.id,
|
||||
status=TaskStatus(
|
||||
state=TaskState.WORKING,
|
||||
message=processing_message,
|
||||
@@ -302,11 +417,54 @@ class A2ATaskManager:
|
||||
),
|
||||
)
|
||||
|
||||
# Collect the chunks of the agent's response
|
||||
external_id = task_params.sessionId
|
||||
external_id = request.params.sessionId
|
||||
full_response = ""
|
||||
|
||||
# We use the same streaming function used in the WebSocket
|
||||
final_message = None
|
||||
|
||||
# Check for files in the user message and include them as artifacts
|
||||
user_files = []
|
||||
for part in request.params.message.parts:
|
||||
if (
|
||||
hasattr(part, "type")
|
||||
and part.type == "file"
|
||||
and hasattr(part, "file")
|
||||
):
|
||||
user_files.append(
|
||||
Artifact(
|
||||
parts=[part],
|
||||
index=0,
|
||||
name=part.file.name if part.file.name else "file",
|
||||
description="File from user",
|
||||
)
|
||||
)
|
||||
|
||||
# Send artifacts for any user files
|
||||
for artifact in user_files:
|
||||
yield SendTaskStreamingResponse(
|
||||
id=request.id,
|
||||
result=TaskArtifactUpdateEvent(
|
||||
id=request.params.id, artifact=artifact
|
||||
),
|
||||
)
|
||||
|
||||
# Use os arquivos processados do _extract_user_query
|
||||
files = getattr(self, "_last_processed_files", None)
|
||||
|
||||
# Log sobre os arquivos processados
|
||||
if files:
|
||||
logger.info(
|
||||
f"Streaming: Passando {len(files)} arquivos processados para run_agent_stream"
|
||||
)
|
||||
for file_info in files:
|
||||
logger.info(
|
||||
f"Streaming: Arquivo sendo enviado: {file_info.filename} ({file_info.content_type})"
|
||||
)
|
||||
else:
|
||||
logger.warning(
|
||||
"Streaming: Nenhum arquivo processado disponível para enviar ao agente"
|
||||
)
|
||||
|
||||
async for chunk in run_agent_stream(
|
||||
agent_id=str(agent.id),
|
||||
external_id=external_id,
|
||||
@@ -315,48 +473,92 @@ class A2ATaskManager:
|
||||
artifacts_service=artifacts_service,
|
||||
memory_service=memory_service,
|
||||
db=self.db,
|
||||
files=files, # Passar os arquivos processados para o streaming
|
||||
):
|
||||
# Send incremental progress updates
|
||||
update_text_part = {"type": "text", "text": chunk}
|
||||
update_message = Message(role="agent", parts=[update_text_part])
|
||||
try:
|
||||
chunk_data = json.loads(chunk)
|
||||
|
||||
# Update the task with each intermediate message
|
||||
await self.update_store(
|
||||
task_params.id,
|
||||
TaskStatus(state=TaskState.WORKING, message=update_message),
|
||||
)
|
||||
if isinstance(chunk_data, dict) and "content" in chunk_data:
|
||||
content = chunk_data.get("content", {})
|
||||
role = content.get("role", "agent")
|
||||
parts = content.get("parts", [])
|
||||
|
||||
yield SendTaskStreamingResponse(
|
||||
id=request.id,
|
||||
result=TaskStatusUpdateEvent(
|
||||
id=task_params.id,
|
||||
status=TaskStatus(
|
||||
state=TaskState.WORKING,
|
||||
message=update_message,
|
||||
),
|
||||
final=False,
|
||||
),
|
||||
)
|
||||
full_response += chunk
|
||||
if parts:
|
||||
# Modify to handle file parts as well
|
||||
agent_parts = []
|
||||
for part in parts:
|
||||
# Handle different part types
|
||||
if part.get("type") == "text":
|
||||
agent_parts.append(part)
|
||||
full_response += part.get("text", "")
|
||||
elif part.get("inlineData") and part["inlineData"].get(
|
||||
"data"
|
||||
):
|
||||
# Convert inline data to file part
|
||||
mime_type = part["inlineData"].get(
|
||||
"mimeType", "application/octet-stream"
|
||||
)
|
||||
file_name = f"file_{uuid_pkg.uuid4().hex}{self._get_extension_from_mime(mime_type)}"
|
||||
file_part = {
|
||||
"type": "file",
|
||||
"file": {
|
||||
"name": file_name,
|
||||
"mimeType": mime_type,
|
||||
"bytes": part["inlineData"]["data"],
|
||||
},
|
||||
}
|
||||
agent_parts.append(file_part)
|
||||
|
||||
# Determine the task state
|
||||
# Also send as artifact
|
||||
yield SendTaskStreamingResponse(
|
||||
id=request.id,
|
||||
result=TaskArtifactUpdateEvent(
|
||||
id=request.params.id,
|
||||
artifact=Artifact(
|
||||
parts=[file_part],
|
||||
index=0,
|
||||
name=file_name,
|
||||
description=f"Generated {mime_type} file",
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
if agent_parts:
|
||||
update_message = Message(role=role, parts=agent_parts)
|
||||
final_message = update_message
|
||||
|
||||
yield SendTaskStreamingResponse(
|
||||
id=request.id,
|
||||
result=TaskStatusUpdateEvent(
|
||||
id=request.params.id,
|
||||
status=TaskStatus(
|
||||
state=TaskState.WORKING,
|
||||
message=update_message,
|
||||
),
|
||||
final=False,
|
||||
),
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Error processing chunk: {e}, chunk: {chunk}")
|
||||
continue
|
||||
|
||||
# Determine the final state of the task
|
||||
task_state = (
|
||||
TaskState.INPUT_REQUIRED
|
||||
if "MISSING_INFO:" in full_response
|
||||
else TaskState.COMPLETED
|
||||
)
|
||||
|
||||
# Create the final response part
|
||||
final_text_part = {"type": "text", "text": full_response}
|
||||
parts = [final_text_part]
|
||||
final_message = Message(role="agent", parts=parts)
|
||||
# Create the final response if we don't have one yet
|
||||
if not final_message:
|
||||
final_text_part = {"type": "text", "text": full_response}
|
||||
parts = [final_text_part]
|
||||
final_message = Message(role="agent", parts=parts)
|
||||
|
||||
# Create the final artifact from the final response
|
||||
final_artifact = Artifact(parts=parts, index=0)
|
||||
final_artifact = Artifact(parts=final_message.parts, index=0)
|
||||
|
||||
# Update the task in the store with the final response
|
||||
await self.update_store(
|
||||
task_params.id,
|
||||
task = await self.update_store(
|
||||
request.params.id,
|
||||
TaskStatus(state=task_state, message=final_message),
|
||||
[final_artifact],
|
||||
)
|
||||
@@ -365,7 +567,7 @@ class A2ATaskManager:
|
||||
yield SendTaskStreamingResponse(
|
||||
id=request.id,
|
||||
result=TaskArtifactUpdateEvent(
|
||||
id=task_params.id, artifact=final_artifact
|
||||
id=request.params.id, artifact=final_artifact
|
||||
),
|
||||
)
|
||||
|
||||
@@ -373,7 +575,7 @@ class A2ATaskManager:
|
||||
yield SendTaskStreamingResponse(
|
||||
id=request.id,
|
||||
result=TaskStatusUpdateEvent(
|
||||
id=task_params.id,
|
||||
id=request.params.id,
|
||||
status=TaskStatus(state=task_state),
|
||||
final=True,
|
||||
),
|
||||
@@ -385,11 +587,35 @@ class A2ATaskManager:
|
||||
error=InternalError(message=f"Error streaming task process: {str(e)}"),
|
||||
)
|
||||
|
||||
def _get_extension_from_mime(self, mime_type: str) -> str:
|
||||
"""Get a file extension from MIME type."""
|
||||
if not mime_type:
|
||||
return ""
|
||||
|
||||
mime_map = {
|
||||
"image/jpeg": ".jpg",
|
||||
"image/png": ".png",
|
||||
"image/gif": ".gif",
|
||||
"application/pdf": ".pdf",
|
||||
"text/plain": ".txt",
|
||||
"text/html": ".html",
|
||||
"text/csv": ".csv",
|
||||
"application/json": ".json",
|
||||
"application/xml": ".xml",
|
||||
"application/msword": ".doc",
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.document": ".docx",
|
||||
"application/vnd.ms-excel": ".xls",
|
||||
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": ".xlsx",
|
||||
}
|
||||
|
||||
return mime_map.get(mime_type, "")
|
||||
|
||||
async def update_store(
|
||||
self,
|
||||
task_id: str,
|
||||
status: TaskStatus,
|
||||
artifacts: Optional[list[Artifact]] = None,
|
||||
update_history: bool = True,
|
||||
) -> Task:
|
||||
"""Updates the status and artifacts of a task."""
|
||||
async with self.lock:
|
||||
@@ -399,8 +625,8 @@ class A2ATaskManager:
|
||||
task = self.tasks[task_id]
|
||||
task.status = status
|
||||
|
||||
# Add message to history if it exists
|
||||
if status.message is not None:
|
||||
# Add message to history if it exists and update_history is True
|
||||
if status.message is not None and update_history:
|
||||
if task.history is None:
|
||||
task.history = []
|
||||
task.history.append(status.message)
|
||||
@@ -413,37 +639,207 @@ class A2ATaskManager:
|
||||
return task
|
||||
|
||||
def _extract_user_query(self, task_params: TaskSendParams) -> str:
|
||||
"""Extracts the user query from the task parameters."""
|
||||
"""Extracts the user query from the task parameters and processes any files."""
|
||||
if not task_params.message or not task_params.message.parts:
|
||||
raise ValueError("Message or parts are missing in task parameters")
|
||||
|
||||
part = task_params.message.parts[0]
|
||||
if part.type != "text":
|
||||
raise ValueError("Only text parts are supported")
|
||||
# Process file parts first
|
||||
text_parts = []
|
||||
has_files = False
|
||||
file_parts = []
|
||||
|
||||
return part.text
|
||||
logger.info(
|
||||
f"Extracting query from message with {len(task_params.message.parts)} parts"
|
||||
)
|
||||
|
||||
async def _run_agent(self, agent: Agent, query: str, session_id: str) -> str:
|
||||
# Extract text parts and file parts separately
|
||||
for idx, part in enumerate(task_params.message.parts):
|
||||
logger.info(
|
||||
f"Processing part {idx+1}, type: {getattr(part, 'type', 'unknown')}"
|
||||
)
|
||||
if hasattr(part, "type"):
|
||||
if part.type == "text":
|
||||
logger.info(f"Found text part: '{part.text[:50]}...' (truncated)")
|
||||
text_parts.append(part.text)
|
||||
elif part.type == "file":
|
||||
logger.info(
|
||||
f"Found file part: {getattr(getattr(part, 'file', None), 'name', 'unnamed')}"
|
||||
)
|
||||
has_files = True
|
||||
try:
|
||||
processed_file = self._process_file_part(
|
||||
part, task_params.sessionId
|
||||
)
|
||||
if processed_file:
|
||||
file_parts.append(processed_file)
|
||||
except Exception as e:
|
||||
logger.error(f"Error processing file part: {e}")
|
||||
# Continue with other parts even if a file fails
|
||||
else:
|
||||
logger.warning(f"Unknown part type: {part.type}")
|
||||
else:
|
||||
logger.warning(f"Part has no type attribute: {part}")
|
||||
|
||||
# Store the file parts in self for later use
|
||||
self._last_processed_files = file_parts if file_parts else None
|
||||
|
||||
# If we have at least one text part, use that as the query
|
||||
if text_parts:
|
||||
final_query = " ".join(text_parts)
|
||||
logger.info(
|
||||
f"Final query from text parts: '{final_query[:50]}...' (truncated)"
|
||||
)
|
||||
return final_query
|
||||
# If we only have file parts, create a generic query asking for analysis
|
||||
elif has_files:
|
||||
logger.info("No text parts, using generic query for file analysis")
|
||||
return "Analyze the attached files"
|
||||
else:
|
||||
logger.error("No supported content parts found in the message")
|
||||
raise ValueError("No supported content parts found in the message")
|
||||
|
||||
def _process_file_part(self, part, session_id: str):
|
||||
"""Processes a file part and saves it to the artifact service.
|
||||
|
||||
Returns:
|
||||
dict: Processed file information to pass to agent_runner
|
||||
"""
|
||||
if not hasattr(part, "file") or not part.file:
|
||||
logger.warning("File part missing file data")
|
||||
return None
|
||||
|
||||
file_data = part.file
|
||||
|
||||
if not file_data.name:
|
||||
file_data.name = f"file_{uuid_pkg.uuid4().hex}"
|
||||
|
||||
logger.info(f"Processing file {file_data.name} for session {session_id}")
|
||||
|
||||
if file_data.bytes:
|
||||
# Process file data provided as base64 string
|
||||
try:
|
||||
# Convert base64 to bytes
|
||||
logger.info(f"Decoding base64 content for file {file_data.name}")
|
||||
file_bytes = base64.b64decode(file_data.bytes)
|
||||
|
||||
# Determine MIME type based on binary content
|
||||
mime_type = (
|
||||
file_data.mimeType if hasattr(file_data, "mimeType") else None
|
||||
)
|
||||
|
||||
if not mime_type or mime_type == "application/octet-stream":
|
||||
# Detection by byte signature
|
||||
if file_bytes.startswith(b"\xff\xd8\xff"): # JPEG signature
|
||||
mime_type = "image/jpeg"
|
||||
elif file_bytes.startswith(b"\x89PNG\r\n\x1a\n"): # PNG signature
|
||||
mime_type = "image/png"
|
||||
elif file_bytes.startswith(b"GIF87a") or file_bytes.startswith(
|
||||
b"GIF89a"
|
||||
): # GIF
|
||||
mime_type = "image/gif"
|
||||
elif file_bytes.startswith(b"%PDF"): # PDF
|
||||
mime_type = "application/pdf"
|
||||
else:
|
||||
# Fallback to avoid generic type in images
|
||||
if file_data.name.lower().endswith((".jpg", ".jpeg")):
|
||||
mime_type = "image/jpeg"
|
||||
elif file_data.name.lower().endswith(".png"):
|
||||
mime_type = "image/png"
|
||||
elif file_data.name.lower().endswith(".gif"):
|
||||
mime_type = "image/gif"
|
||||
elif file_data.name.lower().endswith(".pdf"):
|
||||
mime_type = "application/pdf"
|
||||
else:
|
||||
mime_type = "application/octet-stream"
|
||||
|
||||
logger.info(
|
||||
f"Decoded file size: {len(file_bytes)} bytes, MIME type: {mime_type}"
|
||||
)
|
||||
|
||||
# Split session_id to get app_name and user_id
|
||||
parts = session_id.split("_")
|
||||
if len(parts) != 2:
|
||||
user_id = session_id
|
||||
app_name = "a2a"
|
||||
else:
|
||||
user_id, app_name = parts
|
||||
|
||||
# Create artifact Part
|
||||
logger.info(f"Creating artifact Part for file {file_data.name}")
|
||||
artifact = Part(inline_data=Blob(mime_type=mime_type, data=file_bytes))
|
||||
|
||||
# Save to artifact service
|
||||
logger.info(
|
||||
f"Saving artifact {file_data.name} to {app_name}/{user_id}/{session_id}"
|
||||
)
|
||||
version = artifacts_service.save_artifact(
|
||||
app_name=app_name,
|
||||
user_id=user_id,
|
||||
session_id=session_id,
|
||||
filename=file_data.name,
|
||||
artifact=artifact,
|
||||
)
|
||||
|
||||
logger.info(
|
||||
f"Successfully saved file {file_data.name} (version {version}) for session {session_id}"
|
||||
)
|
||||
|
||||
# Import the FileData model from the chat schema
|
||||
from src.schemas.chat import FileData
|
||||
|
||||
# Create a FileData object instead of a dictionary
|
||||
# This is compatible with what agent_runner.py expects
|
||||
return FileData(
|
||||
filename=file_data.name,
|
||||
content_type=mime_type,
|
||||
data=file_data.bytes, # Keep the original base64 format
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error processing file data: {str(e)}")
|
||||
# Log more details about the error to help with debugging
|
||||
import traceback
|
||||
|
||||
logger.error(f"Full traceback: {traceback.format_exc()}")
|
||||
raise
|
||||
|
||||
elif file_data.uri:
|
||||
# Handling URIs would require additional implementation
|
||||
# For now, log that we received a URI but can't process it
|
||||
logger.warning(f"File URI references not yet implemented: {file_data.uri}")
|
||||
# Future enhancement: fetch the file from the URI and save it
|
||||
return None
|
||||
|
||||
return None
|
||||
|
||||
async def _run_agent(self, agent: Agent, query: str, session_id: str) -> dict:
|
||||
"""Executes the agent to process the user query."""
|
||||
try:
|
||||
# We use the session_id as external_id to maintain the conversation continuity
|
||||
external_id = session_id
|
||||
files = getattr(self, "_last_processed_files", None)
|
||||
|
||||
if files:
|
||||
logger.info(f"Passing {len(files)} files to run_agent")
|
||||
for file_info in files:
|
||||
logger.info(
|
||||
f"File being sent: {file_info.filename} ({file_info.content_type})"
|
||||
)
|
||||
else:
|
||||
logger.info("No files to pass to run_agent")
|
||||
|
||||
# We call the same function used in the chat API
|
||||
final_response = await run_agent(
|
||||
return await run_agent(
|
||||
agent_id=str(agent.id),
|
||||
external_id=external_id,
|
||||
external_id=session_id,
|
||||
message=query,
|
||||
session_service=session_service,
|
||||
artifacts_service=artifacts_service,
|
||||
memory_service=memory_service,
|
||||
db=self.db,
|
||||
files=files,
|
||||
)
|
||||
|
||||
return final_response
|
||||
except Exception as e:
|
||||
logger.error(f"Error running agent: {e}")
|
||||
raise ValueError(f"Error running agent: {str(e)}")
|
||||
raise ValueError(f"Error running agent: {str(e)}") from e
|
||||
|
||||
def append_task_history(self, task: Task, history_length: int | None) -> Task:
|
||||
"""Returns a copy of the task with the history limited to the specified size."""
|
||||
@@ -451,11 +847,16 @@ class A2ATaskManager:
|
||||
new_task = task.model_copy()
|
||||
|
||||
# Limit the history if requested
|
||||
if history_length is not None:
|
||||
if history_length is not None and new_task.history:
|
||||
if history_length > 0:
|
||||
new_task.history = (
|
||||
new_task.history[-history_length:] if new_task.history else []
|
||||
)
|
||||
if len(new_task.history) > history_length:
|
||||
user_message = new_task.history[0]
|
||||
recent_messages = (
|
||||
new_task.history[-(history_length - 1) :]
|
||||
if history_length > 1
|
||||
else []
|
||||
)
|
||||
new_task.history = [user_message] + recent_messages
|
||||
else:
|
||||
new_task.history = []
|
||||
|
||||
@@ -511,112 +912,11 @@ class A2AService:
|
||||
if not agent:
|
||||
raise ValueError(f"Agent {agent_id} not found")
|
||||
|
||||
# Build the agent card based on the agent's information
|
||||
capabilities = AgentCapabilities(streaming=True)
|
||||
capabilities = AgentCapabilities(
|
||||
streaming=True, pushNotifications=False, stateTransitionHistory=True
|
||||
)
|
||||
|
||||
# List to store all skills
|
||||
skills = []
|
||||
|
||||
# Check if the agent has MCP servers configured
|
||||
if (
|
||||
agent.config
|
||||
and "mcp_servers" in agent.config
|
||||
and agent.config["mcp_servers"]
|
||||
):
|
||||
logger.info(
|
||||
f"Agent {agent_id} has {len(agent.config['mcp_servers'])} MCP servers configured"
|
||||
)
|
||||
|
||||
for mcp_config in agent.config["mcp_servers"]:
|
||||
# Get the MCP server
|
||||
mcp_server_id = mcp_config.get("id")
|
||||
if not mcp_server_id:
|
||||
logger.warning("MCP server configuration missing ID")
|
||||
continue
|
||||
|
||||
logger.info(f"Processing MCP server: {mcp_server_id}")
|
||||
mcp_server = get_mcp_server(self.db, mcp_server_id)
|
||||
if not mcp_server:
|
||||
logger.warning(f"MCP server {mcp_server_id} not found")
|
||||
continue
|
||||
|
||||
# Get the available tools in the MCP server
|
||||
mcp_tools = mcp_config.get("tools", [])
|
||||
logger.info(f"MCP server {mcp_server.name} has tools: {mcp_tools}")
|
||||
|
||||
# Add server tools as skills
|
||||
for tool_name in mcp_tools:
|
||||
logger.info(f"Processing tool: {tool_name}")
|
||||
|
||||
tool_info = None
|
||||
if hasattr(mcp_server, "tools") and isinstance(
|
||||
mcp_server.tools, list
|
||||
):
|
||||
for tool in mcp_server.tools:
|
||||
if isinstance(tool, dict) and tool.get("id") == tool_name:
|
||||
tool_info = tool
|
||||
logger.info(
|
||||
f"Found tool info for {tool_name}: {tool_info}"
|
||||
)
|
||||
break
|
||||
|
||||
if tool_info:
|
||||
# Use the information from the tool
|
||||
skill = AgentSkill(
|
||||
id=tool_info.get("id", f"{agent.id}_{tool_name}"),
|
||||
name=tool_info.get("name", tool_name),
|
||||
description=tool_info.get(
|
||||
"description", f"Tool: {tool_name}"
|
||||
),
|
||||
tags=tool_info.get(
|
||||
"tags", [mcp_server.name, "tool", tool_name]
|
||||
),
|
||||
examples=tool_info.get("examples", []),
|
||||
inputModes=tool_info.get("inputModes", ["text"]),
|
||||
outputModes=tool_info.get("outputModes", ["text"]),
|
||||
)
|
||||
else:
|
||||
# Default skill if tool info not found
|
||||
skill = AgentSkill(
|
||||
id=f"{agent.id}_{tool_name}",
|
||||
name=tool_name,
|
||||
description=f"Tool: {tool_name}",
|
||||
tags=[mcp_server.name, "tool", tool_name],
|
||||
examples=[],
|
||||
inputModes=["text"],
|
||||
outputModes=["text"],
|
||||
)
|
||||
|
||||
skills.append(skill)
|
||||
logger.info(f"Added skill for tool: {tool_name}")
|
||||
|
||||
# Check custom tools
|
||||
if (
|
||||
agent.config
|
||||
and "custom_tools" in agent.config
|
||||
and agent.config["custom_tools"]
|
||||
):
|
||||
custom_tools = agent.config["custom_tools"]
|
||||
|
||||
# Check HTTP tools
|
||||
if "http_tools" in custom_tools and custom_tools["http_tools"]:
|
||||
logger.info(f"Agent has {len(custom_tools['http_tools'])} HTTP tools")
|
||||
for http_tool in custom_tools["http_tools"]:
|
||||
skill = AgentSkill(
|
||||
id=f"{agent.id}_http_{http_tool['name']}",
|
||||
name=http_tool["name"],
|
||||
description=http_tool.get(
|
||||
"description", f"HTTP Tool: {http_tool['name']}"
|
||||
),
|
||||
tags=http_tool.get(
|
||||
"tags", ["http", "custom_tool", http_tool["method"]]
|
||||
),
|
||||
examples=http_tool.get("examples", []),
|
||||
inputModes=http_tool.get("inputModes", ["text"]),
|
||||
outputModes=http_tool.get("outputModes", ["text"]),
|
||||
)
|
||||
skills.append(skill)
|
||||
logger.info(f"Added skill for HTTP tool: {http_tool['name']}")
|
||||
skills = self._get_agent_skills(agent)
|
||||
|
||||
card = AgentCard(
|
||||
name=agent.name,
|
||||
@@ -639,3 +939,134 @@ class A2AService:
|
||||
|
||||
logger.info(f"Generated agent card with {len(skills)} skills")
|
||||
return card
|
||||
|
||||
def _get_agent_skills(self, agent: Agent) -> list[AgentSkill]:
|
||||
"""Extracts the skills of an agent based on its configuration."""
|
||||
skills = []
|
||||
|
||||
if self._has_mcp_servers(agent):
|
||||
skills.extend(self._get_mcp_server_skills(agent))
|
||||
|
||||
if self._has_custom_tools(agent):
|
||||
skills.extend(self._get_custom_tool_skills(agent))
|
||||
|
||||
return skills
|
||||
|
||||
def _has_mcp_servers(self, agent: Agent) -> bool:
|
||||
"""Checks if the agent has MCP servers configured."""
|
||||
return (
|
||||
agent.config
|
||||
and "mcp_servers" in agent.config
|
||||
and agent.config["mcp_servers"]
|
||||
)
|
||||
|
||||
def _has_custom_tools(self, agent: Agent) -> bool:
|
||||
"""Checks if the agent has custom tools configured."""
|
||||
return (
|
||||
agent.config
|
||||
and "custom_tools" in agent.config
|
||||
and agent.config["custom_tools"]
|
||||
)
|
||||
|
||||
def _get_mcp_server_skills(self, agent: Agent) -> list[AgentSkill]:
|
||||
"""Gets the skills of the MCP servers configured for the agent."""
|
||||
skills = []
|
||||
logger.info(
|
||||
f"Agent {agent.id} has {len(agent.config['mcp_servers'])} MCP servers configured"
|
||||
)
|
||||
|
||||
for mcp_config in agent.config["mcp_servers"]:
|
||||
mcp_server_id = mcp_config.get("id")
|
||||
if not mcp_server_id:
|
||||
logger.warning("MCP server configuration missing ID")
|
||||
continue
|
||||
|
||||
mcp_server = get_mcp_server(self.db, mcp_server_id)
|
||||
if not mcp_server:
|
||||
logger.warning(f"MCP server {mcp_server_id} not found")
|
||||
continue
|
||||
|
||||
skills.extend(self._extract_mcp_tool_skills(agent, mcp_server, mcp_config))
|
||||
|
||||
return skills
|
||||
|
||||
def _extract_mcp_tool_skills(
|
||||
self, agent: Agent, mcp_server, mcp_config
|
||||
) -> list[AgentSkill]:
|
||||
"""Extracts skills from MCP tools."""
|
||||
skills = []
|
||||
mcp_tools = mcp_config.get("tools", [])
|
||||
logger.info(f"MCP server {mcp_server.name} has tools: {mcp_tools}")
|
||||
|
||||
for tool_name in mcp_tools:
|
||||
tool_info = self._find_tool_info(mcp_server, tool_name)
|
||||
skill = self._create_tool_skill(
|
||||
agent, tool_name, tool_info, mcp_server.name
|
||||
)
|
||||
skills.append(skill)
|
||||
logger.info(f"Added skill for tool: {tool_name}")
|
||||
|
||||
return skills
|
||||
|
||||
def _find_tool_info(self, mcp_server, tool_name) -> dict:
|
||||
"""Finds information about a tool in an MCP server."""
|
||||
if not hasattr(mcp_server, "tools") or not isinstance(mcp_server.tools, list):
|
||||
return None
|
||||
|
||||
for tool in mcp_server.tools:
|
||||
if isinstance(tool, dict) and tool.get("id") == tool_name:
|
||||
logger.info(f"Found tool info for {tool_name}: {tool}")
|
||||
return tool
|
||||
|
||||
return None
|
||||
|
||||
def _create_tool_skill(
|
||||
self, agent: Agent, tool_name: str, tool_info: dict, server_name: str
|
||||
) -> AgentSkill:
|
||||
"""Creates an AgentSkill object based on the tool information."""
|
||||
if tool_info:
|
||||
return AgentSkill(
|
||||
id=tool_info.get("id", f"{agent.id}_{tool_name}"),
|
||||
name=tool_info.get("name", tool_name),
|
||||
description=tool_info.get("description", f"Tool: {tool_name}"),
|
||||
tags=tool_info.get("tags", [server_name, "tool", tool_name]),
|
||||
examples=tool_info.get("examples", []),
|
||||
inputModes=tool_info.get("inputModes", ["text"]),
|
||||
outputModes=tool_info.get("outputModes", ["text"]),
|
||||
)
|
||||
else:
|
||||
return AgentSkill(
|
||||
id=f"{agent.id}_{tool_name}",
|
||||
name=tool_name,
|
||||
description=f"Tool: {tool_name}",
|
||||
tags=[server_name, "tool", tool_name],
|
||||
examples=[],
|
||||
inputModes=["text"],
|
||||
outputModes=["text"],
|
||||
)
|
||||
|
||||
def _get_custom_tool_skills(self, agent: Agent) -> list[AgentSkill]:
|
||||
"""Gets the skills of the custom tools of the agent."""
|
||||
skills = []
|
||||
custom_tools = agent.config["custom_tools"]
|
||||
|
||||
if "http_tools" in custom_tools and custom_tools["http_tools"]:
|
||||
logger.info(f"Agent has {len(custom_tools['http_tools'])} HTTP tools")
|
||||
for http_tool in custom_tools["http_tools"]:
|
||||
skill = AgentSkill(
|
||||
id=f"{agent.id}_http_{http_tool['name']}",
|
||||
name=http_tool["name"],
|
||||
description=http_tool.get(
|
||||
"description", f"HTTP Tool: {http_tool['name']}"
|
||||
),
|
||||
tags=http_tool.get(
|
||||
"tags", ["http", "custom_tool", http_tool["method"]]
|
||||
),
|
||||
examples=http_tool.get("examples", []),
|
||||
inputModes=http_tool.get("inputModes", ["text"]),
|
||||
outputModes=http_tool.get("outputModes", ["text"]),
|
||||
)
|
||||
skills.append(skill)
|
||||
logger.info(f"Added skill for HTTP tool: {http_tool['name']}")
|
||||
|
||||
return skills
|
||||
|
||||
@@ -1,15 +1,46 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: agent_builder.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
from typing import List, Optional, Tuple
|
||||
from google.adk.agents.llm_agent import LlmAgent
|
||||
from google.adk.agents import SequentialAgent, ParallelAgent, LoopAgent, BaseAgent
|
||||
from google.adk.models.lite_llm import LiteLlm
|
||||
from google.adk.tools.agent_tool import AgentTool
|
||||
from src.schemas.schemas import Agent
|
||||
from src.utils.logger import setup_logger
|
||||
from src.core.exceptions import AgentNotFoundError
|
||||
from src.services.agent_service import get_agent
|
||||
from src.services.custom_tools import CustomToolBuilder
|
||||
from src.services.mcp_service import MCPService
|
||||
from src.services.a2a_agent import A2ACustomAgent
|
||||
from src.services.workflow_agent import WorkflowAgent
|
||||
from src.services.custom_agents.a2a_agent import A2ACustomAgent
|
||||
from src.services.custom_agents.workflow_agent import WorkflowAgent
|
||||
from src.services.custom_agents.task_agent import TaskAgent
|
||||
from src.services.apikey_service import get_decrypted_api_key
|
||||
from sqlalchemy.orm import Session
|
||||
from contextlib import AsyncExitStack
|
||||
@@ -18,6 +49,8 @@ from google.adk.tools import load_memory
|
||||
from datetime import datetime
|
||||
import uuid
|
||||
|
||||
from src.schemas.agent_config import AgentTask
|
||||
|
||||
logger = setup_logger(__name__)
|
||||
|
||||
|
||||
@@ -40,7 +73,7 @@ class AgentBuilder:
|
||||
return agent_tools
|
||||
|
||||
async def _create_llm_agent(
|
||||
self, agent
|
||||
self, agent, enabled_tools: List[str] = []
|
||||
) -> Tuple[LlmAgent, Optional[AsyncExitStack]]:
|
||||
"""Create an LLM agent from the agent data."""
|
||||
# Get custom tools from the configuration
|
||||
@@ -61,6 +94,10 @@ class AgentBuilder:
|
||||
# Combine all tools
|
||||
all_tools = custom_tools + mcp_tools + agent_tools
|
||||
|
||||
if enabled_tools:
|
||||
all_tools = [tool for tool in all_tools if tool.name in enabled_tools]
|
||||
logger.info(f"Enabled tools enabled. Total tools: {len(all_tools)}")
|
||||
|
||||
now = datetime.now()
|
||||
current_datetime = now.strftime("%d/%m/%Y %H:%M")
|
||||
current_day_of_week = now.strftime("%A")
|
||||
@@ -75,6 +112,18 @@ class AgentBuilder:
|
||||
current_time=current_time,
|
||||
)
|
||||
|
||||
# add role on beginning of the prompt
|
||||
if agent.role:
|
||||
formatted_prompt = (
|
||||
f"<agent_role>{agent.role}</agent_role>\n\n{formatted_prompt}"
|
||||
)
|
||||
|
||||
# add goal on beginning of the prompt
|
||||
if agent.goal:
|
||||
formatted_prompt = (
|
||||
f"<agent_goal>{agent.goal}</agent_goal>\n\n{formatted_prompt}"
|
||||
)
|
||||
|
||||
# Check if load_memory is enabled
|
||||
if agent.config.get("load_memory"):
|
||||
all_tools.append(load_memory)
|
||||
@@ -154,6 +203,8 @@ class AgentBuilder:
|
||||
sub_agent, exit_stack = await self.build_a2a_agent(agent)
|
||||
elif agent.type == "workflow":
|
||||
sub_agent, exit_stack = await self.build_workflow_agent(agent)
|
||||
elif agent.type == "task":
|
||||
sub_agent, exit_stack = await self.build_task_agent(agent)
|
||||
elif agent.type == "sequential":
|
||||
sub_agent, exit_stack = await self.build_composite_agent(agent)
|
||||
elif agent.type == "parallel":
|
||||
@@ -172,7 +223,7 @@ class AgentBuilder:
|
||||
return sub_agents
|
||||
|
||||
async def build_llm_agent(
|
||||
self, root_agent
|
||||
self, root_agent, enabled_tools: List[str] = []
|
||||
) -> Tuple[LlmAgent, Optional[AsyncExitStack]]:
|
||||
"""Build an LLM agent with its sub-agents."""
|
||||
logger.info("Creating LLM agent")
|
||||
@@ -184,7 +235,9 @@ class AgentBuilder:
|
||||
)
|
||||
sub_agents = [agent for agent, _ in sub_agents_with_stacks]
|
||||
|
||||
root_llm_agent, exit_stack = await self._create_llm_agent(root_agent)
|
||||
root_llm_agent, exit_stack = await self._create_llm_agent(
|
||||
root_agent, enabled_tools
|
||||
)
|
||||
if sub_agents:
|
||||
root_llm_agent.sub_agents = sub_agents
|
||||
|
||||
@@ -269,6 +322,56 @@ class AgentBuilder:
|
||||
logger.error(f"Error building Workflow agent: {str(e)}")
|
||||
raise ValueError(f"Error building Workflow agent: {str(e)}")
|
||||
|
||||
async def build_task_agent(
|
||||
self, root_agent
|
||||
) -> Tuple[TaskAgent, Optional[AsyncExitStack]]:
|
||||
"""Build a task agent with its sub-agents."""
|
||||
logger.info(f"Creating Task agent: {root_agent.name}")
|
||||
|
||||
agent_config = root_agent.config or {}
|
||||
|
||||
if not agent_config.get("tasks"):
|
||||
raise ValueError("tasks are required for Task agents")
|
||||
|
||||
try:
|
||||
# Get sub-agents if there are any
|
||||
sub_agents = []
|
||||
if root_agent.config.get("sub_agents"):
|
||||
sub_agents_with_stacks = await self._get_sub_agents(
|
||||
root_agent.config.get("sub_agents")
|
||||
)
|
||||
sub_agents = [agent for agent, _ in sub_agents_with_stacks]
|
||||
|
||||
# Additional configurations
|
||||
config = root_agent.config or {}
|
||||
|
||||
# Convert tasks to the expected format by TaskAgent
|
||||
tasks = []
|
||||
for task_config in config.get("tasks", []):
|
||||
task = AgentTask(
|
||||
agent_id=task_config.get("agent_id"),
|
||||
description=task_config.get("description", ""),
|
||||
expected_output=task_config.get("expected_output", ""),
|
||||
enabled_tools=task_config.get("enabled_tools", []),
|
||||
)
|
||||
tasks.append(task)
|
||||
|
||||
# Create the Task agent
|
||||
task_agent = TaskAgent(
|
||||
name=root_agent.name,
|
||||
tasks=tasks,
|
||||
db=self.db,
|
||||
sub_agents=sub_agents,
|
||||
)
|
||||
|
||||
logger.info(f"Task agent created successfully: {root_agent.name}")
|
||||
|
||||
return task_agent, None
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error building Task agent: {str(e)}")
|
||||
raise ValueError(f"Error building Task agent: {str(e)}")
|
||||
|
||||
async def build_composite_agent(
|
||||
self, root_agent
|
||||
) -> Tuple[SequentialAgent | ParallelAgent | LoopAgent, Optional[AsyncExitStack]]:
|
||||
@@ -332,21 +435,24 @@ class AgentBuilder:
|
||||
else:
|
||||
raise ValueError(f"Invalid agent type: {root_agent.type}")
|
||||
|
||||
async def build_agent(self, root_agent) -> Tuple[
|
||||
async def build_agent(self, root_agent, enabled_tools: List[str] = []) -> Tuple[
|
||||
LlmAgent
|
||||
| SequentialAgent
|
||||
| ParallelAgent
|
||||
| LoopAgent
|
||||
| A2ACustomAgent
|
||||
| WorkflowAgent,
|
||||
| WorkflowAgent
|
||||
| TaskAgent,
|
||||
Optional[AsyncExitStack],
|
||||
]:
|
||||
"""Build the appropriate agent based on the type of the root agent."""
|
||||
if root_agent.type == "llm":
|
||||
return await self.build_llm_agent(root_agent)
|
||||
return await self.build_llm_agent(root_agent, enabled_tools)
|
||||
elif root_agent.type == "a2a":
|
||||
return await self.build_a2a_agent(root_agent)
|
||||
elif root_agent.type == "workflow":
|
||||
return await self.build_workflow_agent(root_agent)
|
||||
elif root_agent.type == "task":
|
||||
return await self.build_task_agent(root_agent)
|
||||
else:
|
||||
return await self.build_composite_agent(root_agent)
|
||||
|
||||
@@ -1,5 +1,34 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: agent_runner.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
from google.adk.runners import Runner
|
||||
from google.genai.types import Content, Part
|
||||
from google.genai.types import Content, Part, Blob
|
||||
from google.adk.sessions import DatabaseSessionService
|
||||
from google.adk.memory import InMemoryMemoryService
|
||||
from google.adk.artifacts.in_memory_artifact_service import InMemoryArtifactService
|
||||
@@ -13,6 +42,7 @@ import asyncio
|
||||
import json
|
||||
from src.utils.otel import get_tracer
|
||||
from opentelemetry import trace
|
||||
import base64
|
||||
|
||||
logger = setup_logger(__name__)
|
||||
|
||||
@@ -27,6 +57,7 @@ async def run_agent(
|
||||
db: Session,
|
||||
session_id: Optional[str] = None,
|
||||
timeout: float = 60.0,
|
||||
files: Optional[list] = None,
|
||||
):
|
||||
tracer = get_tracer()
|
||||
with tracer.start_as_current_span(
|
||||
@@ -36,6 +67,7 @@ async def run_agent(
|
||||
"external_id": external_id,
|
||||
"session_id": session_id or f"{external_id}_{agent_id}",
|
||||
"message": message,
|
||||
"has_files": files is not None and len(files) > 0,
|
||||
},
|
||||
):
|
||||
exit_stack = None
|
||||
@@ -45,6 +77,9 @@ async def run_agent(
|
||||
)
|
||||
logger.info(f"Received message: {message}")
|
||||
|
||||
if files and len(files) > 0:
|
||||
logger.info(f"Received {len(files)} files with message")
|
||||
|
||||
get_root_agent = get_agent(db, agent_id)
|
||||
logger.info(
|
||||
f"Root agent found: {get_root_agent.name} (type: {get_root_agent.type})"
|
||||
@@ -65,7 +100,7 @@ async def run_agent(
|
||||
artifact_service=artifacts_service,
|
||||
memory_service=memory_service,
|
||||
)
|
||||
adk_session_id = external_id + "_" + agent_id
|
||||
adk_session_id = f"{external_id}_{agent_id}"
|
||||
if session_id is None:
|
||||
session_id = adk_session_id
|
||||
|
||||
@@ -84,10 +119,68 @@ async def run_agent(
|
||||
session_id=adk_session_id,
|
||||
)
|
||||
|
||||
content = Content(role="user", parts=[Part(text=message)])
|
||||
file_parts = []
|
||||
if files and len(files) > 0:
|
||||
for file_data in files:
|
||||
try:
|
||||
file_bytes = base64.b64decode(file_data.data)
|
||||
|
||||
logger.info(f"DEBUG - Processing file: {file_data.filename}")
|
||||
logger.info(f"DEBUG - File size: {len(file_bytes)} bytes")
|
||||
logger.info(f"DEBUG - MIME type: '{file_data.content_type}'")
|
||||
logger.info(f"DEBUG - First 20 bytes: {file_bytes[:20]}")
|
||||
|
||||
try:
|
||||
file_part = Part(
|
||||
inline_data=Blob(
|
||||
mime_type=file_data.content_type, data=file_bytes
|
||||
)
|
||||
)
|
||||
logger.info(f"DEBUG - Part created successfully")
|
||||
except Exception as part_error:
|
||||
logger.error(
|
||||
f"DEBUG - Error creating Part: {str(part_error)}"
|
||||
)
|
||||
logger.error(
|
||||
f"DEBUG - Error type: {type(part_error).__name__}"
|
||||
)
|
||||
import traceback
|
||||
|
||||
logger.error(
|
||||
f"DEBUG - Stack trace: {traceback.format_exc()}"
|
||||
)
|
||||
raise
|
||||
|
||||
# Save the file in the ArtifactService
|
||||
version = artifacts_service.save_artifact(
|
||||
app_name=agent_id,
|
||||
user_id=external_id,
|
||||
session_id=adk_session_id,
|
||||
filename=file_data.filename,
|
||||
artifact=file_part,
|
||||
)
|
||||
logger.info(
|
||||
f"Saved file {file_data.filename} as version {version}"
|
||||
)
|
||||
|
||||
# Add the Part to the list of parts for the message content
|
||||
file_parts.append(file_part)
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"Error processing file {file_data.filename}: {str(e)}"
|
||||
)
|
||||
|
||||
# Create the content with the text message and the files
|
||||
parts = [Part(text=message)]
|
||||
if file_parts:
|
||||
parts.extend(file_parts)
|
||||
|
||||
content = Content(role="user", parts=parts)
|
||||
logger.info("Starting agent execution")
|
||||
|
||||
final_response_text = "No final response captured."
|
||||
message_history = []
|
||||
|
||||
try:
|
||||
response_queue = asyncio.Queue()
|
||||
execution_completed = asyncio.Event()
|
||||
@@ -104,6 +197,11 @@ async def run_agent(
|
||||
all_responses = []
|
||||
|
||||
async for event in events_async:
|
||||
if event.content and event.content.parts:
|
||||
event_dict = event.dict()
|
||||
event_dict = convert_sets(event_dict)
|
||||
message_history.append(event_dict)
|
||||
|
||||
if (
|
||||
event.content
|
||||
and event.content.parts
|
||||
@@ -176,10 +274,13 @@ async def run_agent(
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error processing request: {str(e)}")
|
||||
raise e
|
||||
raise InternalServerError(str(e)) from e
|
||||
|
||||
logger.info("Agent execution completed successfully")
|
||||
return final_response_text
|
||||
return {
|
||||
"final_response": final_response_text,
|
||||
"message_history": message_history,
|
||||
}
|
||||
except AgentNotFoundError as e:
|
||||
logger.error(f"Error processing request: {str(e)}")
|
||||
raise e
|
||||
@@ -217,6 +318,7 @@ async def run_agent_stream(
|
||||
memory_service: InMemoryMemoryService,
|
||||
db: Session,
|
||||
session_id: Optional[str] = None,
|
||||
files: Optional[list] = None,
|
||||
) -> AsyncGenerator[str, None]:
|
||||
tracer = get_tracer()
|
||||
span = tracer.start_span(
|
||||
@@ -226,6 +328,7 @@ async def run_agent_stream(
|
||||
"external_id": external_id,
|
||||
"session_id": session_id or f"{external_id}_{agent_id}",
|
||||
"message": message,
|
||||
"has_files": files is not None and len(files) > 0,
|
||||
},
|
||||
)
|
||||
try:
|
||||
@@ -236,6 +339,9 @@ async def run_agent_stream(
|
||||
)
|
||||
logger.info(f"Received message: {message}")
|
||||
|
||||
if files and len(files) > 0:
|
||||
logger.info(f"Received {len(files)} files with message")
|
||||
|
||||
get_root_agent = get_agent(db, agent_id)
|
||||
logger.info(
|
||||
f"Root agent found: {get_root_agent.name} (type: {get_root_agent.type})"
|
||||
@@ -256,7 +362,7 @@ async def run_agent_stream(
|
||||
artifact_service=artifacts_service,
|
||||
memory_service=memory_service,
|
||||
)
|
||||
adk_session_id = external_id + "_" + agent_id
|
||||
adk_session_id = f"{external_id}_{agent_id}"
|
||||
if session_id is None:
|
||||
session_id = adk_session_id
|
||||
|
||||
@@ -275,7 +381,72 @@ async def run_agent_stream(
|
||||
session_id=adk_session_id,
|
||||
)
|
||||
|
||||
content = Content(role="user", parts=[Part(text=message)])
|
||||
# Process the received files
|
||||
file_parts = []
|
||||
if files and len(files) > 0:
|
||||
for file_data in files:
|
||||
try:
|
||||
# Decode the base64 file
|
||||
file_bytes = base64.b64decode(file_data.data)
|
||||
|
||||
# Detailed debug
|
||||
logger.info(
|
||||
f"DEBUG - Processing file: {file_data.filename}"
|
||||
)
|
||||
logger.info(f"DEBUG - File size: {len(file_bytes)} bytes")
|
||||
logger.info(
|
||||
f"DEBUG - MIME type: '{file_data.content_type}'"
|
||||
)
|
||||
logger.info(f"DEBUG - First 20 bytes: {file_bytes[:20]}")
|
||||
|
||||
# Create a Part for the file using the default constructor
|
||||
try:
|
||||
file_part = Part(
|
||||
inline_data=Blob(
|
||||
mime_type=file_data.content_type,
|
||||
data=file_bytes,
|
||||
)
|
||||
)
|
||||
logger.info(f"DEBUG - Part created successfully")
|
||||
except Exception as part_error:
|
||||
logger.error(
|
||||
f"DEBUG - Error creating Part: {str(part_error)}"
|
||||
)
|
||||
logger.error(
|
||||
f"DEBUG - Error type: {type(part_error).__name__}"
|
||||
)
|
||||
import traceback
|
||||
|
||||
logger.error(
|
||||
f"DEBUG - Stack trace: {traceback.format_exc()}"
|
||||
)
|
||||
raise
|
||||
|
||||
# Save the file in the ArtifactService
|
||||
version = artifacts_service.save_artifact(
|
||||
app_name=agent_id,
|
||||
user_id=external_id,
|
||||
session_id=adk_session_id,
|
||||
filename=file_data.filename,
|
||||
artifact=file_part,
|
||||
)
|
||||
logger.info(
|
||||
f"Saved file {file_data.filename} as version {version}"
|
||||
)
|
||||
|
||||
# Add the Part to the list of parts for the message content
|
||||
file_parts.append(file_part)
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"Error processing file {file_data.filename}: {str(e)}"
|
||||
)
|
||||
|
||||
# Create the content with the text message and the files
|
||||
parts = [Part(text=message)]
|
||||
if file_parts:
|
||||
parts.extend(file_parts)
|
||||
|
||||
content = Content(role="user", parts=parts)
|
||||
logger.info("Starting agent streaming execution")
|
||||
|
||||
try:
|
||||
@@ -286,9 +457,51 @@ async def run_agent_stream(
|
||||
)
|
||||
|
||||
async for event in events_async:
|
||||
event_dict = event.dict()
|
||||
event_dict = convert_sets(event_dict)
|
||||
yield json.dumps(event_dict)
|
||||
try:
|
||||
event_dict = event.dict()
|
||||
event_dict = convert_sets(event_dict)
|
||||
|
||||
if "content" in event_dict and event_dict["content"]:
|
||||
content = event_dict["content"]
|
||||
|
||||
if "role" not in content or content["role"] not in [
|
||||
"user",
|
||||
"agent",
|
||||
]:
|
||||
content["role"] = "agent"
|
||||
|
||||
if "parts" in content and content["parts"]:
|
||||
valid_parts = []
|
||||
for part in content["parts"]:
|
||||
if isinstance(part, dict):
|
||||
if "type" not in part and "text" in part:
|
||||
part["type"] = "text"
|
||||
valid_parts.append(part)
|
||||
elif "type" in part:
|
||||
valid_parts.append(part)
|
||||
|
||||
if valid_parts:
|
||||
content["parts"] = valid_parts
|
||||
else:
|
||||
content["parts"] = [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "Content without valid format",
|
||||
}
|
||||
]
|
||||
else:
|
||||
content["parts"] = [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "Content without parts",
|
||||
}
|
||||
]
|
||||
|
||||
# Send the individual event
|
||||
yield json.dumps(event_dict)
|
||||
except Exception as e:
|
||||
logger.error(f"Error processing event: {e}")
|
||||
continue
|
||||
|
||||
completed_session = session_service.get_session(
|
||||
app_name=agent_id,
|
||||
@@ -299,7 +512,7 @@ async def run_agent_stream(
|
||||
memory_service.add_session_to_memory(completed_session)
|
||||
except Exception as e:
|
||||
logger.error(f"Error processing request: {str(e)}")
|
||||
raise e
|
||||
raise InternalServerError(str(e)) from e
|
||||
finally:
|
||||
# Clean up MCP connection
|
||||
if exit_stack:
|
||||
@@ -312,7 +525,7 @@ async def run_agent_stream(
|
||||
logger.info("Agent streaming execution completed successfully")
|
||||
except AgentNotFoundError as e:
|
||||
logger.error(f"Error processing request: {str(e)}")
|
||||
raise e
|
||||
raise InternalServerError(str(e)) from e
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"Internal error processing request: {str(e)}", exc_info=True
|
||||
|
||||
@@ -1,3 +1,32 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: agent_service.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from fastapi import HTTPException, status
|
||||
@@ -74,6 +103,14 @@ def get_agent(db: Session, agent_id: Union[uuid.UUID, str]) -> Optional[Agent]:
|
||||
logger.warning(f"Agent not found: {agent_id}")
|
||||
return None
|
||||
|
||||
# Sanitize agent name if it contains spaces or special characters
|
||||
if agent.name and any(c for c in agent.name if not (c.isalnum() or c == "_")):
|
||||
agent.name = "".join(
|
||||
c if c.isalnum() or c == "_" else "_" for c in agent.name
|
||||
)
|
||||
# Update in database
|
||||
db.commit()
|
||||
|
||||
return agent
|
||||
except SQLAlchemyError as e:
|
||||
logger.error(f"Error searching for agent {agent_id}: {str(e)}")
|
||||
@@ -115,6 +152,17 @@ def get_agents_by_client(
|
||||
|
||||
agents = query.offset(skip).limit(limit).all()
|
||||
|
||||
# Sanitize agent names if they contain spaces or special characters
|
||||
for agent in agents:
|
||||
if agent.name and any(
|
||||
c for c in agent.name if not (c.isalnum() or c == "_")
|
||||
):
|
||||
agent.name = "".join(
|
||||
c if c.isalnum() or c == "_" else "_" for c in agent.name
|
||||
)
|
||||
# Update in database
|
||||
db.commit()
|
||||
|
||||
return agents
|
||||
except SQLAlchemyError as e:
|
||||
logger.error(f"Error searching for client agents {client_id}: {str(e)}")
|
||||
@@ -147,7 +195,15 @@ async def create_agent(db: Session, agent: AgentCreate) -> Agent:
|
||||
agent_card = response.json()
|
||||
|
||||
# Update agent with information from agent card
|
||||
agent.name = agent_card.get("name", "Unknown Agent")
|
||||
# Only update name if not provided or empty, or sanitize it
|
||||
if not agent.name or agent.name.strip() == "":
|
||||
# Sanitize name: remove spaces and special characters
|
||||
card_name = agent_card.get("name", "Unknown Agent")
|
||||
sanitized_name = "".join(
|
||||
c if c.isalnum() or c == "_" else "_" for c in card_name
|
||||
)
|
||||
agent.name = sanitized_name
|
||||
|
||||
agent.description = agent_card.get("description", "")
|
||||
|
||||
if agent.config is None:
|
||||
@@ -173,6 +229,51 @@ async def create_agent(db: Session, agent: AgentCreate) -> Agent:
|
||||
if "api_key" not in agent.config or not agent.config["api_key"]:
|
||||
agent.config["api_key"] = generate_api_key()
|
||||
|
||||
elif agent.type == "task":
|
||||
if not isinstance(agent.config, dict):
|
||||
agent.config = {}
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Invalid configuration: must be an object with tasks",
|
||||
)
|
||||
|
||||
if "tasks" not in agent.config:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=f"Invalid configuration: tasks is required for {agent.type} agents",
|
||||
)
|
||||
|
||||
if not agent.config["tasks"]:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Invalid configuration: tasks cannot be empty",
|
||||
)
|
||||
|
||||
for task in agent.config["tasks"]:
|
||||
if "agent_id" not in task:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Each task must have an agent_id",
|
||||
)
|
||||
|
||||
agent_id = task["agent_id"]
|
||||
task_agent = get_agent(db, agent_id)
|
||||
if not task_agent:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=f"Agent not found for task: {agent_id}",
|
||||
)
|
||||
|
||||
if "sub_agents" in agent.config and agent.config["sub_agents"]:
|
||||
if not validate_sub_agents(db, agent.config["sub_agents"]):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="One or more sub-agents do not exist",
|
||||
)
|
||||
|
||||
if "api_key" not in agent.config or not agent.config["api_key"]:
|
||||
agent.config["api_key"] = generate_api_key()
|
||||
|
||||
# Additional sub-agent validation (for non-llm and non-a2a types)
|
||||
elif agent.type != "llm":
|
||||
if not isinstance(agent.config, dict):
|
||||
@@ -425,7 +526,14 @@ async def update_agent(
|
||||
)
|
||||
agent_card = response.json()
|
||||
|
||||
agent_data["name"] = agent_card.get("name", "Unknown Agent")
|
||||
# Only update name if the original update doesn't specify a name
|
||||
if "name" not in agent_data or not agent_data["name"].strip():
|
||||
# Sanitize name: remove spaces and special characters
|
||||
card_name = agent_card.get("name", "Unknown Agent")
|
||||
sanitized_name = "".join(
|
||||
c if c.isalnum() or c == "_" else "_" for c in card_name
|
||||
)
|
||||
agent_data["name"] = sanitized_name
|
||||
agent_data["description"] = agent_card.get("description", "")
|
||||
|
||||
if "config" not in agent_data or agent_data["config"] is None:
|
||||
@@ -463,7 +571,14 @@ async def update_agent(
|
||||
)
|
||||
agent_card = response.json()
|
||||
|
||||
agent_data["name"] = agent_card.get("name", "Unknown Agent")
|
||||
# Only update name if the original update doesn't specify a name
|
||||
if "name" not in agent_data or not agent_data["name"].strip():
|
||||
# Sanitize name: remove spaces and special characters
|
||||
card_name = agent_card.get("name", "Unknown Agent")
|
||||
sanitized_name = "".join(
|
||||
c if c.isalnum() or c == "_" else "_" for c in card_name
|
||||
)
|
||||
agent_data["name"] = sanitized_name
|
||||
agent_data["description"] = agent_card.get("description", "")
|
||||
|
||||
if "config" not in agent_data or agent_data["config"] is None:
|
||||
@@ -608,6 +723,45 @@ async def update_agent(
|
||||
if "config" not in agent_data:
|
||||
agent_data["config"] = agent_config
|
||||
|
||||
if ("type" in agent_data and agent_data["type"] in ["task"]) or (
|
||||
agent.type in ["task"] and "config" in agent_data
|
||||
):
|
||||
config = agent_data.get("config", {})
|
||||
if "tasks" not in config:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=f"Invalid configuration: tasks is required for {agent_data.get('type', agent.type)} agents",
|
||||
)
|
||||
|
||||
if not config["tasks"]:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Invalid configuration: tasks cannot be empty",
|
||||
)
|
||||
|
||||
for task in config["tasks"]:
|
||||
if "agent_id" not in task:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Each task must have an agent_id",
|
||||
)
|
||||
|
||||
agent_id = task["agent_id"]
|
||||
task_agent = get_agent(db, agent_id)
|
||||
if not task_agent:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=f"Agent not found for task: {agent_id}",
|
||||
)
|
||||
|
||||
# Validar sub_agents se existir
|
||||
if "sub_agents" in config and config["sub_agents"]:
|
||||
if not validate_sub_agents(db, config["sub_agents"]):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="One or more sub-agents do not exist",
|
||||
)
|
||||
|
||||
if not agent_config.get("api_key") and (
|
||||
"config" not in agent_data or not agent_data["config"].get("api_key")
|
||||
):
|
||||
|
||||
@@ -1,3 +1,32 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: apikey_service.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
from src.models.models import ApiKey
|
||||
from src.utils.crypto import encrypt_api_key, decrypt_api_key
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
@@ -1,3 +1,32 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: audit_service.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from src.models.models import AuditLog
|
||||
|
||||
@@ -1,3 +1,32 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: auth_service.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
from src.models.models import User
|
||||
from src.schemas.user import TokenData
|
||||
|
||||
@@ -1,3 +1,32 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: client_service.p │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from fastapi import HTTPException, status
|
||||
|
||||
0
src/services/custom_agents/__init__.py
Normal file
0
src/services/custom_agents/__init__.py
Normal file
412
src/services/custom_agents/a2a_agent.py
Normal file
412
src/services/custom_agents/a2a_agent.py
Normal file
@@ -0,0 +1,412 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: a2a_agent.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
from google.adk.agents import BaseAgent
|
||||
from google.adk.agents.invocation_context import InvocationContext
|
||||
from google.adk.events import Event
|
||||
from google.genai.types import Content, Part
|
||||
|
||||
from typing import AsyncGenerator, List, Dict, Any, Optional
|
||||
import json
|
||||
|
||||
import httpx
|
||||
from httpx_sse import connect_sse
|
||||
|
||||
from src.schemas.a2a_types import (
|
||||
AgentCard,
|
||||
Message,
|
||||
TextPart,
|
||||
TaskSendParams,
|
||||
SendTaskRequest,
|
||||
SendTaskStreamingRequest,
|
||||
TaskState,
|
||||
)
|
||||
|
||||
from uuid import uuid4
|
||||
|
||||
|
||||
class A2ACustomAgent(BaseAgent):
|
||||
"""
|
||||
Custom agent that implements the A2A protocol directly.
|
||||
|
||||
This agent implements the interaction with an external A2A service.
|
||||
"""
|
||||
|
||||
# Field declarations for Pydantic
|
||||
agent_card_url: str
|
||||
agent_card: Optional[AgentCard]
|
||||
timeout: int
|
||||
base_url: str
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
name: str,
|
||||
agent_card_url: str,
|
||||
timeout: int = 300,
|
||||
sub_agents: List[BaseAgent] = [],
|
||||
**kwargs,
|
||||
):
|
||||
"""
|
||||
Initialize the A2A agent.
|
||||
|
||||
Args:
|
||||
name: Agent name
|
||||
agent_card_url: A2A agent card URL
|
||||
timeout: Maximum execution time (seconds)
|
||||
sub_agents: List of sub-agents to be executed after the A2A agent
|
||||
"""
|
||||
# Create base_url from agent_card_url
|
||||
base_url = agent_card_url
|
||||
if "/.well-known/agent.json" in base_url:
|
||||
base_url = base_url.split("/.well-known/agent.json")[0]
|
||||
|
||||
print(f"A2A agent initialized for URL: {agent_card_url}")
|
||||
|
||||
# Initialize base class
|
||||
super().__init__(
|
||||
name=name,
|
||||
agent_card_url=agent_card_url,
|
||||
base_url=base_url, # Pass base_url here
|
||||
agent_card=None,
|
||||
timeout=timeout,
|
||||
sub_agents=sub_agents,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
async def fetch_agent_card(self) -> AgentCard:
|
||||
"""Fetch the agent card from the A2A service."""
|
||||
if self.agent_card:
|
||||
return self.agent_card
|
||||
|
||||
card_url = f"{self.base_url}/.well-known/agent.json"
|
||||
print(f"Fetching agent card from: {card_url}")
|
||||
|
||||
async with httpx.AsyncClient() as client:
|
||||
response = await client.get(card_url)
|
||||
response.raise_for_status()
|
||||
try:
|
||||
card_data = response.json()
|
||||
self.agent_card = AgentCard(**card_data)
|
||||
return self.agent_card
|
||||
except json.JSONDecodeError as e:
|
||||
raise ValueError(f"Failed to parse agent card: {str(e)}")
|
||||
|
||||
async def _run_async_impl(
|
||||
self, ctx: InvocationContext
|
||||
) -> AsyncGenerator[Event, None]:
|
||||
"""
|
||||
Implementation of the A2A protocol according to the Google ADK documentation.
|
||||
|
||||
This method follows the pattern of implementing custom agents,
|
||||
sending the user's message to the A2A service and monitoring the response.
|
||||
"""
|
||||
|
||||
try:
|
||||
# 1. First, fetch the agent card if we haven't already
|
||||
try:
|
||||
agent_card = await self.fetch_agent_card()
|
||||
print(f"Agent card fetched: {agent_card.name}")
|
||||
except Exception as e:
|
||||
error_msg = f"Failed to fetch agent card: {str(e)}"
|
||||
print(error_msg)
|
||||
yield Event(
|
||||
author=self.name,
|
||||
content=Content(role="agent", parts=[Part(text=error_msg)]),
|
||||
)
|
||||
return
|
||||
|
||||
# 2. Extract the user's message from the context
|
||||
user_message = None
|
||||
|
||||
# Search for the user's message in the session events
|
||||
if ctx.session and hasattr(ctx.session, "events") and ctx.session.events:
|
||||
for event in reversed(ctx.session.events):
|
||||
if event.author == "user" and event.content and event.content.parts:
|
||||
user_message = event.content.parts[0].text
|
||||
print("Message found in session events")
|
||||
break
|
||||
|
||||
# Check in the session state if the message was not found in the events
|
||||
if not user_message and ctx.session and ctx.session.state:
|
||||
if "user_message" in ctx.session.state:
|
||||
user_message = ctx.session.state["user_message"]
|
||||
elif "message" in ctx.session.state:
|
||||
user_message = ctx.session.state["message"]
|
||||
|
||||
if not user_message:
|
||||
error_msg = "No user message found"
|
||||
print(error_msg)
|
||||
yield Event(
|
||||
author=self.name,
|
||||
content=Content(role="agent", parts=[Part(text=error_msg)]),
|
||||
)
|
||||
return
|
||||
|
||||
# 3. Create and format the task to send to the A2A agent
|
||||
print(f"Sending task to A2A agent: {user_message[:100]}...")
|
||||
|
||||
# Use the session ID as a stable identifier
|
||||
session_id = (
|
||||
str(ctx.session.id)
|
||||
if ctx.session and hasattr(ctx.session, "id")
|
||||
else str(uuid4())
|
||||
)
|
||||
task_id = str(uuid4())
|
||||
|
||||
# Prepare the message for the A2A agent
|
||||
formatted_message = Message(
|
||||
role="user",
|
||||
parts=[TextPart(text=user_message)],
|
||||
)
|
||||
|
||||
# Prepare the task parameters
|
||||
task_params = TaskSendParams(
|
||||
id=task_id,
|
||||
sessionId=session_id,
|
||||
message=formatted_message,
|
||||
acceptedOutputModes=["text"],
|
||||
)
|
||||
|
||||
# 4. Check if the agent supports streaming
|
||||
supports_streaming = (
|
||||
agent_card.capabilities.streaming if agent_card.capabilities else False
|
||||
)
|
||||
|
||||
if supports_streaming:
|
||||
print("Agent supports streaming, using streaming API")
|
||||
# Process with streaming
|
||||
try:
|
||||
request = SendTaskStreamingRequest(
|
||||
method="tasks/sendSubscribe", params=task_params
|
||||
)
|
||||
|
||||
try:
|
||||
async with httpx.AsyncClient() as client:
|
||||
response = await client.post(
|
||||
self.base_url,
|
||||
json=request.model_dump(),
|
||||
headers={"Accept": "text/event-stream"},
|
||||
timeout=self.timeout,
|
||||
)
|
||||
response.raise_for_status()
|
||||
|
||||
async for line in response.aiter_lines():
|
||||
if line.startswith("data:"):
|
||||
data = line[5:].strip()
|
||||
if data:
|
||||
try:
|
||||
result = json.loads(data)
|
||||
print(f"Stream event received: {result}")
|
||||
|
||||
# Check if this is a status update with a message
|
||||
if (
|
||||
"result" in result
|
||||
and "status" in result["result"]
|
||||
and "message"
|
||||
in result["result"]["status"]
|
||||
and "parts"
|
||||
in result["result"]["status"]["message"]
|
||||
):
|
||||
message_parts = result["result"][
|
||||
"status"
|
||||
]["message"]["parts"]
|
||||
parts = [
|
||||
Part(text=part["text"])
|
||||
for part in message_parts
|
||||
if part.get("type") == "text"
|
||||
and "text" in part
|
||||
]
|
||||
|
||||
if parts:
|
||||
yield Event(
|
||||
author=self.name,
|
||||
content=Content(
|
||||
role="agent", parts=parts
|
||||
),
|
||||
)
|
||||
|
||||
# Check if this is a final message
|
||||
if (
|
||||
"result" in result
|
||||
and result.get("result", {}).get(
|
||||
"final", False
|
||||
)
|
||||
and "status" in result["result"]
|
||||
and result["result"]["status"].get(
|
||||
"state"
|
||||
)
|
||||
in [
|
||||
TaskState.COMPLETED,
|
||||
TaskState.CANCELED,
|
||||
TaskState.FAILED,
|
||||
]
|
||||
):
|
||||
print(
|
||||
"Received final message, stream complete"
|
||||
)
|
||||
break
|
||||
except json.JSONDecodeError as e:
|
||||
print(f"Error parsing SSE data: {str(e)}")
|
||||
except Exception as stream_error:
|
||||
print(
|
||||
f"Error in direct streaming: {str(stream_error)}, falling back to regular API"
|
||||
)
|
||||
fallback_request = SendTaskRequest(
|
||||
method="tasks/send", params=task_params
|
||||
)
|
||||
|
||||
async with httpx.AsyncClient() as client:
|
||||
response = await client.post(
|
||||
self.base_url,
|
||||
json=fallback_request.model_dump(),
|
||||
timeout=self.timeout,
|
||||
)
|
||||
response.raise_for_status()
|
||||
|
||||
result = response.json()
|
||||
print(f"Fallback response: {result}")
|
||||
|
||||
# Extract agent message parts
|
||||
if (
|
||||
"result" in result
|
||||
and "status" in result["result"]
|
||||
and "message" in result["result"]["status"]
|
||||
and "parts" in result["result"]["status"]["message"]
|
||||
):
|
||||
message_parts = result["result"]["status"]["message"][
|
||||
"parts"
|
||||
]
|
||||
parts = [
|
||||
Part(text=part["text"])
|
||||
for part in message_parts
|
||||
if part.get("type") == "text" and "text" in part
|
||||
]
|
||||
|
||||
if parts:
|
||||
yield Event(
|
||||
author=self.name,
|
||||
content=Content(role="agent", parts=parts),
|
||||
)
|
||||
else:
|
||||
yield Event(
|
||||
author=self.name,
|
||||
content=Content(
|
||||
role="agent",
|
||||
parts=[
|
||||
Part(
|
||||
text="Received response without message parts"
|
||||
)
|
||||
],
|
||||
),
|
||||
)
|
||||
except Exception as e:
|
||||
error_msg = f"Error in streaming: {str(e)}"
|
||||
print(error_msg)
|
||||
yield Event(
|
||||
author=self.name,
|
||||
content=Content(role="agent", parts=[Part(text=error_msg)]),
|
||||
)
|
||||
else:
|
||||
print("Agent does not support streaming, using regular API")
|
||||
# Process with regular request
|
||||
try:
|
||||
request = SendTaskRequest(method="tasks/send", params=task_params)
|
||||
|
||||
async with httpx.AsyncClient() as client:
|
||||
response = await client.post(
|
||||
self.base_url,
|
||||
json=request.model_dump(),
|
||||
timeout=self.timeout,
|
||||
)
|
||||
response.raise_for_status()
|
||||
|
||||
result = response.json()
|
||||
print(f"Task response: {result}")
|
||||
|
||||
# Extract agent message parts
|
||||
if (
|
||||
"result" in result
|
||||
and "status" in result["result"]
|
||||
and "message" in result["result"]["status"]
|
||||
and "parts" in result["result"]["status"]["message"]
|
||||
):
|
||||
message_parts = result["result"]["status"]["message"][
|
||||
"parts"
|
||||
]
|
||||
parts = [
|
||||
Part(text=part["text"])
|
||||
for part in message_parts
|
||||
if part.get("type") == "text" and "text" in part
|
||||
]
|
||||
|
||||
if parts:
|
||||
yield Event(
|
||||
author=self.name,
|
||||
content=Content(role="agent", parts=parts),
|
||||
)
|
||||
else:
|
||||
yield Event(
|
||||
author=self.name,
|
||||
content=Content(
|
||||
role="agent",
|
||||
parts=[
|
||||
Part(
|
||||
text="Received response without message parts"
|
||||
)
|
||||
],
|
||||
),
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
error_msg = f"Error sending request: {str(e)}"
|
||||
print(error_msg)
|
||||
print(f"Error type: {type(e).__name__}")
|
||||
print(f"Error details: {str(e)}")
|
||||
|
||||
yield Event(
|
||||
author=self.name,
|
||||
content=Content(role="agent", parts=[Part(text=error_msg)]),
|
||||
)
|
||||
|
||||
# Run sub-agents
|
||||
for sub_agent in self.sub_agents:
|
||||
async for event in sub_agent.run_async(ctx):
|
||||
yield event
|
||||
|
||||
except Exception as e:
|
||||
# Handle any uncaught error
|
||||
error_msg = f"Error executing A2A agent: {str(e)}"
|
||||
print(error_msg)
|
||||
yield Event(
|
||||
author=self.name,
|
||||
content=Content(
|
||||
role="agent",
|
||||
parts=[Part(text=error_msg)],
|
||||
),
|
||||
)
|
||||
233
src/services/custom_agents/task_agent.py
Normal file
233
src/services/custom_agents/task_agent.py
Normal file
@@ -0,0 +1,233 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: task_agent.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 14, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
from attr import Factory
|
||||
from google.adk.agents import BaseAgent
|
||||
from google.adk.agents.invocation_context import InvocationContext
|
||||
from google.adk.events import Event
|
||||
from google.genai.types import Content, Part
|
||||
from src.services.agent_service import get_agent
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from typing import AsyncGenerator, List
|
||||
|
||||
from src.schemas.agent_config import AgentTask
|
||||
|
||||
|
||||
class TaskAgent(BaseAgent):
|
||||
"""
|
||||
Custom agent that implements the Task function.
|
||||
|
||||
This agent implements the interaction with an external Task service.
|
||||
"""
|
||||
|
||||
# Field declarations for Pydantic
|
||||
tasks: List[AgentTask]
|
||||
db: Session
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
name: str,
|
||||
tasks: List[AgentTask],
|
||||
db: Session,
|
||||
sub_agents: List[BaseAgent] = [],
|
||||
**kwargs,
|
||||
):
|
||||
"""
|
||||
Initialize the Task agent.
|
||||
|
||||
Args:
|
||||
name: Agent name
|
||||
tasks: List of tasks to be executed
|
||||
db: Database session
|
||||
sub_agents: List of sub-agents to be executed after the Task agent
|
||||
"""
|
||||
# Initialize base class
|
||||
super().__init__(
|
||||
name=name,
|
||||
tasks=tasks,
|
||||
db=db,
|
||||
sub_agents=sub_agents,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
async def _run_async_impl(
|
||||
self, ctx: InvocationContext
|
||||
) -> AsyncGenerator[Event, None]:
|
||||
"""
|
||||
Implementation of the Task agent.
|
||||
|
||||
This method follows the pattern of implementing custom agents,
|
||||
sending the user's message to the Task service and monitoring the response.
|
||||
"""
|
||||
exit_stack = None
|
||||
|
||||
try:
|
||||
# Extract the user's message from the context
|
||||
user_message = None
|
||||
|
||||
# Search for the user's message in the session events
|
||||
if ctx.session and hasattr(ctx.session, "events") and ctx.session.events:
|
||||
for event in reversed(ctx.session.events):
|
||||
if event.author == "user" and event.content and event.content.parts:
|
||||
user_message = event.content.parts[0].text
|
||||
print("Message found in session events")
|
||||
break
|
||||
|
||||
# Check in the session state if the message was not found in the events
|
||||
if not user_message and ctx.session and ctx.session.state:
|
||||
if "user_message" in ctx.session.state:
|
||||
user_message = ctx.session.state["user_message"]
|
||||
elif "message" in ctx.session.state:
|
||||
user_message = ctx.session.state["message"]
|
||||
|
||||
if not user_message:
|
||||
yield Event(
|
||||
author=self.name,
|
||||
content=Content(
|
||||
role="agent",
|
||||
parts=[Part(text="User message not found")],
|
||||
),
|
||||
)
|
||||
return
|
||||
|
||||
# Start the agent status
|
||||
yield Event(
|
||||
author=self.name,
|
||||
content=Content(
|
||||
role="agent",
|
||||
parts=[Part(text=f"Starting {self.name} task processing...")],
|
||||
),
|
||||
)
|
||||
|
||||
try:
|
||||
# Replace any {content} in the task descriptions with the user's input
|
||||
task = self.tasks[0]
|
||||
task.description = task.description.replace("{content}", user_message)
|
||||
task.enabled_tools = task.enabled_tools or []
|
||||
|
||||
agent = get_agent(self.db, task.agent_id)
|
||||
|
||||
if not agent:
|
||||
yield Event(
|
||||
author=self.name,
|
||||
content=Content(parts=[Part(text="Agent not found")]),
|
||||
)
|
||||
return
|
||||
|
||||
# Prepare task instructions
|
||||
task_message_instructions = f"""
|
||||
<task>
|
||||
<instructions>
|
||||
Execute the following task:
|
||||
</instructions>
|
||||
<description>{task.description}</description>
|
||||
<expected_output>{task.expected_output}</expected_output>
|
||||
</task>
|
||||
"""
|
||||
|
||||
# Send task instructions as an event
|
||||
yield Event(
|
||||
author=f"{self.name} - Task executor",
|
||||
content=Content(
|
||||
role="agent",
|
||||
parts=[Part(text=task_message_instructions)],
|
||||
),
|
||||
)
|
||||
|
||||
from src.services.agent_builder import AgentBuilder
|
||||
|
||||
print(f"Building agent in Task agent: {agent.name}")
|
||||
agent_builder = AgentBuilder(self.db)
|
||||
root_agent, exit_stack = await agent_builder.build_agent(
|
||||
agent, task.enabled_tools
|
||||
)
|
||||
|
||||
# Store task instructions in context for reference by sub-agents
|
||||
ctx.session.state["task_instructions"] = task_message_instructions
|
||||
|
||||
# Process the agent responses
|
||||
try:
|
||||
async for event in root_agent.run_async(ctx):
|
||||
yield event
|
||||
except GeneratorExit:
|
||||
print("Generator was closed prematurely, handling cleanup...")
|
||||
# Allow the exception to propagate after cleanup
|
||||
raise
|
||||
except Exception as e:
|
||||
error_msg = f"Error during agent execution: {str(e)}"
|
||||
print(error_msg)
|
||||
yield Event(
|
||||
author=self.name,
|
||||
content=Content(
|
||||
role="agent",
|
||||
parts=[Part(text=error_msg)],
|
||||
),
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
error_msg = f"Error sending request: {str(e)}"
|
||||
print(error_msg)
|
||||
print(f"Error type: {type(e).__name__}")
|
||||
print(f"Error details: {str(e)}")
|
||||
|
||||
yield Event(
|
||||
author=self.name,
|
||||
content=Content(role="agent", parts=[Part(text=error_msg)]),
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
# Handle any uncaught error
|
||||
print(f"Error executing Task agent: {str(e)}")
|
||||
yield Event(
|
||||
author=self.name,
|
||||
content=Content(
|
||||
role="agent",
|
||||
parts=[Part(text=f"Error interacting with Task agent: {str(e)}")],
|
||||
),
|
||||
)
|
||||
finally:
|
||||
# Ensure we close the exit_stack in the same task context where it was created
|
||||
if exit_stack:
|
||||
try:
|
||||
await exit_stack.aclose()
|
||||
print("Exit stack closed successfully")
|
||||
except Exception as e:
|
||||
print(f"Error closing exit_stack: {str(e)}")
|
||||
|
||||
# Execute sub-agents only if no exception occurred
|
||||
try:
|
||||
if "e" not in locals():
|
||||
for sub_agent in self.sub_agents:
|
||||
async for event in sub_agent.run_async(ctx):
|
||||
yield event
|
||||
except Exception as sub_e:
|
||||
print(f"Error executing sub-agents: {str(sub_e)}")
|
||||
# We don't yield a new event here to avoid raising during cleanup
|
||||
@@ -1,3 +1,32 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: workflow_agent.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from google.adk.agents import BaseAgent
|
||||
from google.adk.agents.invocation_context import InvocationContext
|
||||
@@ -87,7 +116,7 @@ class WorkflowAgent(BaseAgent):
|
||||
if not content:
|
||||
content = [
|
||||
Event(
|
||||
author="agent",
|
||||
author="workflow_agent",
|
||||
content=Content(parts=[Part(text="Content not found")]),
|
||||
)
|
||||
]
|
||||
@@ -139,7 +168,7 @@ class WorkflowAgent(BaseAgent):
|
||||
yield {
|
||||
"content": [
|
||||
Event(
|
||||
author="agent",
|
||||
author="workflow_agent",
|
||||
content=Content(parts=[Part(text="Agent not found")]),
|
||||
)
|
||||
],
|
||||
@@ -162,7 +191,7 @@ class WorkflowAgent(BaseAgent):
|
||||
conversation_history.append(event)
|
||||
new_content.append(event)
|
||||
|
||||
print(f"New content: {str(new_content)}")
|
||||
print(f"New content: {new_content}")
|
||||
|
||||
node_outputs = state.get("node_outputs", {})
|
||||
node_outputs[node_id] = {
|
||||
@@ -252,7 +281,7 @@ class WorkflowAgent(BaseAgent):
|
||||
|
||||
condition_content = [
|
||||
Event(
|
||||
author="agent",
|
||||
author="workflow_agent",
|
||||
content=Content(parts=[Part(text="Cycle limit reached")]),
|
||||
)
|
||||
]
|
||||
@@ -283,7 +312,7 @@ class WorkflowAgent(BaseAgent):
|
||||
|
||||
condition_content = [
|
||||
Event(
|
||||
author="agent",
|
||||
author=label,
|
||||
content=Content(
|
||||
parts=[
|
||||
Part(
|
||||
@@ -317,8 +346,10 @@ class WorkflowAgent(BaseAgent):
|
||||
session_id = state.get("session_id", "")
|
||||
conversation_history = state.get("conversation_history", [])
|
||||
|
||||
label = node_data.get("label", "message_node")
|
||||
|
||||
new_event = Event(
|
||||
author="agent",
|
||||
author=label,
|
||||
content=Content(parts=[Part(text=message_content)]),
|
||||
)
|
||||
content = content + [new_event]
|
||||
@@ -351,139 +382,160 @@ class WorkflowAgent(BaseAgent):
|
||||
condition_data = condition.get("data", {})
|
||||
|
||||
if condition_type == "previous-output":
|
||||
field = condition_data.get("field")
|
||||
operator = condition_data.get("operator")
|
||||
expected_value = condition_data.get("value")
|
||||
field, operator, expected_value, actual_value = (
|
||||
self._extract_condition_values(condition_data, state)
|
||||
)
|
||||
|
||||
actual_value = state.get(field, "")
|
||||
|
||||
# Special treatment for when content is a list of Events
|
||||
if field == "content" and isinstance(actual_value, list) and actual_value:
|
||||
# Extract text from each event for comparison
|
||||
extracted_texts = []
|
||||
for event in actual_value:
|
||||
if hasattr(event, "content") and hasattr(event.content, "parts"):
|
||||
for part in event.content.parts:
|
||||
if hasattr(part, "text") and part.text:
|
||||
extracted_texts.append(part.text)
|
||||
actual_value = self._extract_text_from_events(actual_value)
|
||||
|
||||
if extracted_texts:
|
||||
actual_value = " ".join(extracted_texts)
|
||||
print(f" Extracted text from events: '{actual_value[:100]}...'")
|
||||
result = self._process_condition(operator, actual_value, expected_value)
|
||||
|
||||
# Convert values to string for easier comparisons
|
||||
if actual_value is not None:
|
||||
actual_str = str(actual_value)
|
||||
else:
|
||||
actual_str = ""
|
||||
print(f" Check '{operator}': {result}")
|
||||
return result
|
||||
|
||||
if expected_value is not None:
|
||||
expected_str = str(expected_value)
|
||||
else:
|
||||
expected_str = ""
|
||||
return False
|
||||
|
||||
# Checks for definition
|
||||
if operator == "is_defined":
|
||||
result = actual_value is not None and actual_value != ""
|
||||
print(f" Check '{operator}': {result}")
|
||||
return result
|
||||
elif operator == "is_not_defined":
|
||||
result = actual_value is None or actual_value == ""
|
||||
print(f" Check '{operator}': {result}")
|
||||
return result
|
||||
def _process_condition(self, operator, actual_value, expected_value):
|
||||
"""Converts values to strings and processes the condition using the appropriate operator."""
|
||||
actual_str = str(actual_value) if actual_value is not None else ""
|
||||
expected_str = str(expected_value) if expected_value is not None else ""
|
||||
|
||||
# Checks for equality
|
||||
elif operator == "equals":
|
||||
result = actual_str == expected_str
|
||||
print(f" Check '{operator}': {result}")
|
||||
return result
|
||||
elif operator == "not_equals":
|
||||
result = actual_str != expected_str
|
||||
print(f" Check '{operator}': {result}")
|
||||
return result
|
||||
return self._process_operator(operator, actual_value, actual_str, expected_str)
|
||||
|
||||
# Checks for content
|
||||
elif operator == "contains":
|
||||
# Convert both to lowercase for case-insensitive comparison
|
||||
expected_lower = expected_str.lower()
|
||||
actual_lower = actual_str.lower()
|
||||
print(
|
||||
f" Comparison 'contains' without case distinction: '{expected_lower}' in '{actual_lower[:100]}...'"
|
||||
def _extract_condition_values(self, condition_data, state):
|
||||
"""Extracts field, operator, expected value and actual value from condition data."""
|
||||
field = condition_data.get("field")
|
||||
operator = condition_data.get("operator")
|
||||
expected_value = condition_data.get("value")
|
||||
actual_value = state.get(field, "")
|
||||
|
||||
return field, operator, expected_value, actual_value
|
||||
|
||||
def _extract_text_from_events(self, events):
|
||||
"""Extracts text content from a list of events for comparison."""
|
||||
extracted_texts = []
|
||||
for event in events:
|
||||
if hasattr(event, "content") and hasattr(event.content, "parts"):
|
||||
extracted_texts.extend(
|
||||
[
|
||||
part.text
|
||||
for part in event.content.parts
|
||||
if hasattr(part, "text") and part.text
|
||||
]
|
||||
)
|
||||
result = expected_lower in actual_lower
|
||||
print(f" Check '{operator}': {result}")
|
||||
return result
|
||||
elif operator == "not_contains":
|
||||
expected_lower = expected_str.lower()
|
||||
actual_lower = actual_str.lower()
|
||||
print(
|
||||
f" Comparison 'not_contains' without case distinction: '{expected_lower}' in '{actual_lower[:100]}...'"
|
||||
)
|
||||
result = expected_lower not in actual_lower
|
||||
print(f" Check '{operator}': {result}")
|
||||
return result
|
||||
|
||||
# Checks for start and end
|
||||
elif operator == "starts_with":
|
||||
result = actual_str.lower().startswith(expected_str.lower())
|
||||
print(f" Check '{operator}': {result}")
|
||||
return result
|
||||
elif operator == "ends_with":
|
||||
result = actual_str.lower().endswith(expected_str.lower())
|
||||
print(f" Check '{operator}': {result}")
|
||||
return result
|
||||
if extracted_texts:
|
||||
joined_text = " ".join(extracted_texts)
|
||||
print(f" Extracted text from events: '{joined_text[:100]}...'")
|
||||
return joined_text
|
||||
|
||||
# Numeric checks (attempting to convert to number)
|
||||
elif operator in [
|
||||
"greater_than",
|
||||
"greater_than_or_equal",
|
||||
"less_than",
|
||||
"less_than_or_equal",
|
||||
]:
|
||||
try:
|
||||
actual_num = float(actual_str) if actual_str else 0
|
||||
expected_num = float(expected_str) if expected_str else 0
|
||||
return ""
|
||||
|
||||
if operator == "greater_than":
|
||||
result = actual_num > expected_num
|
||||
elif operator == "greater_than_or_equal":
|
||||
result = actual_num >= expected_num
|
||||
elif operator == "less_than":
|
||||
result = actual_num < expected_num
|
||||
elif operator == "less_than_or_equal":
|
||||
result = actual_num <= expected_num
|
||||
print(f" Numeric check '{operator}': {result}")
|
||||
return result
|
||||
except (ValueError, TypeError):
|
||||
# If it's not possible to convert to number, return false
|
||||
print(
|
||||
f" Error converting values for numeric comparison: '{actual_str[:100]}...' and '{expected_str}'"
|
||||
)
|
||||
return False
|
||||
def _process_operator(self, operator, actual_value, actual_str, expected_str):
|
||||
"""Process the operator and return the result of the comparison."""
|
||||
# Definition checks
|
||||
if operator in ["is_defined", "is_not_defined"]:
|
||||
return self._check_definition(operator, actual_value)
|
||||
|
||||
# Checks with regular expressions
|
||||
elif operator == "matches":
|
||||
import re
|
||||
# Equality checks
|
||||
elif operator in ["equals", "not_equals"]:
|
||||
return self._check_equality(operator, actual_str, expected_str)
|
||||
|
||||
try:
|
||||
pattern = re.compile(expected_str, re.IGNORECASE)
|
||||
result = bool(pattern.search(actual_str))
|
||||
print(f" Check '{operator}': {result}")
|
||||
return result
|
||||
except re.error:
|
||||
print(f" Error in regular expression: '{expected_str}'")
|
||||
return False
|
||||
elif operator == "not_matches":
|
||||
import re
|
||||
# Content checks
|
||||
elif operator in ["contains", "not_contains"]:
|
||||
return self._case_insensitive_comparison(expected_str, actual_str, operator)
|
||||
|
||||
try:
|
||||
pattern = re.compile(expected_str, re.IGNORECASE)
|
||||
result = not bool(pattern.search(actual_str))
|
||||
print(f" Check '{operator}': {result}")
|
||||
return result
|
||||
except re.error:
|
||||
print(f" Error in regular expression: '{expected_str}'")
|
||||
return True # If the regex is invalid, we consider that there was no match
|
||||
# String pattern checks
|
||||
elif operator in ["starts_with", "ends_with"]:
|
||||
return self._check_string_pattern(operator, actual_str, expected_str)
|
||||
|
||||
# Numeric checks
|
||||
elif operator in [
|
||||
"greater_than",
|
||||
"greater_than_or_equal",
|
||||
"less_than",
|
||||
"less_than_or_equal",
|
||||
]:
|
||||
return self._check_numeric(operator, actual_str, expected_str)
|
||||
|
||||
# Regex checks
|
||||
elif operator in ["matches", "not_matches"]:
|
||||
return self._check_regex(operator, actual_str, expected_str)
|
||||
|
||||
return False
|
||||
|
||||
def _check_definition(self, operator, actual_value):
|
||||
"""Check if a value is defined or not."""
|
||||
if operator == "is_defined":
|
||||
return actual_value is not None and actual_value != ""
|
||||
else: # is_not_defined
|
||||
return actual_value is None or actual_value == ""
|
||||
|
||||
def _check_equality(self, operator, actual_str, expected_str):
|
||||
"""Check if two strings are equal or not."""
|
||||
return (
|
||||
(actual_str == expected_str)
|
||||
if operator == "equals"
|
||||
else (actual_str != expected_str)
|
||||
)
|
||||
|
||||
def _check_string_pattern(self, operator, actual_str, expected_str):
|
||||
"""Check if a string starts or ends with another string."""
|
||||
if operator == "starts_with":
|
||||
return actual_str.lower().startswith(expected_str.lower())
|
||||
else: # ends_with
|
||||
return actual_str.lower().endswith(expected_str.lower())
|
||||
|
||||
def _check_numeric(self, operator, actual_str, expected_str):
|
||||
"""Compare numeric values."""
|
||||
try:
|
||||
actual_num = float(actual_str) if actual_str else 0
|
||||
expected_num = float(expected_str) if expected_str else 0
|
||||
|
||||
if operator == "greater_than":
|
||||
return actual_num > expected_num
|
||||
elif operator == "greater_than_or_equal":
|
||||
return actual_num >= expected_num
|
||||
elif operator == "less_than":
|
||||
return actual_num < expected_num
|
||||
else: # less_than_or_equal
|
||||
return actual_num <= expected_num
|
||||
except (ValueError, TypeError):
|
||||
print(
|
||||
f" Error converting values for numeric comparison: '{actual_str[:100]}...' and '{expected_str}'"
|
||||
)
|
||||
return False
|
||||
|
||||
def _check_regex(self, operator, actual_str, expected_str):
|
||||
"""Check if a string matches a regex pattern."""
|
||||
import re
|
||||
|
||||
try:
|
||||
pattern = re.compile(expected_str, re.IGNORECASE)
|
||||
if operator == "matches":
|
||||
return bool(pattern.search(actual_str))
|
||||
else: # not_matches
|
||||
return not bool(pattern.search(actual_str))
|
||||
except re.error:
|
||||
print(f" Error in regular expression: '{expected_str}'")
|
||||
return (
|
||||
operator == "not_matches"
|
||||
) # Return True for not_matches, False for matches
|
||||
|
||||
def _case_insensitive_comparison(self, expected_str, actual_str, operator):
|
||||
"""Performs case-insensitive string comparison based on the specified operator."""
|
||||
expected_lower = expected_str.lower()
|
||||
actual_lower = actual_str.lower()
|
||||
|
||||
print(
|
||||
f" Comparison '{operator}' without case distinction: '{expected_lower}' in '{actual_lower[:100]}...'"
|
||||
)
|
||||
|
||||
if operator == "contains":
|
||||
return expected_lower in actual_lower
|
||||
elif operator == "not_contains":
|
||||
return expected_lower not in actual_lower
|
||||
|
||||
return False
|
||||
|
||||
@@ -529,38 +581,15 @@ class WorkflowAgent(BaseAgent):
|
||||
conditions = condition_nodes[node_id]
|
||||
any_condition_met = False
|
||||
|
||||
for condition in conditions:
|
||||
condition_id = condition.get("id")
|
||||
|
||||
# Get latest event for evaluation, ignoring condition node informational events
|
||||
content = state.get("content", [])
|
||||
latest_event = None
|
||||
for event in reversed(content):
|
||||
# Skip events generated by condition nodes
|
||||
if (
|
||||
event.author != "agent"
|
||||
or not hasattr(event.content, "parts")
|
||||
or not event.content.parts
|
||||
):
|
||||
latest_event = event
|
||||
break
|
||||
|
||||
evaluation_state = state.copy()
|
||||
if latest_event:
|
||||
evaluation_state["content"] = [latest_event]
|
||||
|
||||
# Check if the condition is met
|
||||
is_condition_met = self._evaluate_condition(
|
||||
condition, evaluation_state
|
||||
)
|
||||
|
||||
if is_condition_met:
|
||||
node_outputs = state.get("node_outputs", {})
|
||||
if node_id in node_outputs:
|
||||
conditions_met = node_outputs[node_id].get("conditions_met", [])
|
||||
if conditions_met:
|
||||
any_condition_met = True
|
||||
condition_id = conditions_met[0]
|
||||
print(
|
||||
f"Condition {condition_id} met. Moving to the next node."
|
||||
f"Using stored condition evaluation result: Condition {condition_id} met."
|
||||
)
|
||||
|
||||
# Find the connection that uses this condition_id as a handle
|
||||
if (
|
||||
node_id in edges_map
|
||||
and condition_id in edges_map[node_id]
|
||||
@@ -568,8 +597,49 @@ class WorkflowAgent(BaseAgent):
|
||||
return edges_map[node_id][condition_id]
|
||||
else:
|
||||
print(
|
||||
f"Condition {condition_id} not met. Continuing evaluation or using default path."
|
||||
"Using stored condition evaluation result: No conditions met."
|
||||
)
|
||||
else:
|
||||
for condition in conditions:
|
||||
condition_id = condition.get("id")
|
||||
|
||||
# Get latest event for evaluation, ignoring condition node informational events
|
||||
content = state.get("content", [])
|
||||
|
||||
# Filter out events generated by condition nodes or informational messages
|
||||
filtered_content = []
|
||||
for event in content:
|
||||
# Ignore events from condition nodes or that contain evaluation results
|
||||
if not hasattr(event, "author") or not (
|
||||
event.author.startswith("Condition")
|
||||
or "Condition evaluated:" in str(event)
|
||||
):
|
||||
filtered_content.append(event)
|
||||
|
||||
evaluation_state = state.copy()
|
||||
evaluation_state["content"] = filtered_content
|
||||
|
||||
# Check if the condition is met
|
||||
is_condition_met = self._evaluate_condition(
|
||||
condition, evaluation_state
|
||||
)
|
||||
|
||||
if is_condition_met:
|
||||
any_condition_met = True
|
||||
print(
|
||||
f"Condition {condition_id} met. Moving to the next node."
|
||||
)
|
||||
|
||||
# Find the connection that uses this condition_id as a handle
|
||||
if (
|
||||
node_id in edges_map
|
||||
and condition_id in edges_map[node_id]
|
||||
):
|
||||
return edges_map[node_id][condition_id]
|
||||
else:
|
||||
print(
|
||||
f"Condition {condition_id} not met. Continuing evaluation or using default path."
|
||||
)
|
||||
|
||||
# If no condition is met, use the bottom-handle if available
|
||||
if not any_condition_met:
|
||||
@@ -706,91 +776,96 @@ class WorkflowAgent(BaseAgent):
|
||||
async def _run_async_impl(
|
||||
self, ctx: InvocationContext
|
||||
) -> AsyncGenerator[Event, None]:
|
||||
"""
|
||||
Implementation of the workflow agent.
|
||||
|
||||
This method follows the pattern of custom agent implementation,
|
||||
executing the defined workflow and returning the results.
|
||||
"""
|
||||
|
||||
"""Implementation of the workflow agent executing the defined workflow and returning results."""
|
||||
try:
|
||||
# 1. Extract the user message from the context
|
||||
user_message = None
|
||||
|
||||
# Search for the user message in the session events
|
||||
if ctx.session and hasattr(ctx.session, "events") and ctx.session.events:
|
||||
for event in reversed(ctx.session.events):
|
||||
if event.author == "user" and event.content and event.content.parts:
|
||||
user_message = event.content.parts[0].text
|
||||
print("Message found in session events")
|
||||
break
|
||||
|
||||
# Check in the session state if the message was not found in the events
|
||||
if not user_message and ctx.session and ctx.session.state:
|
||||
if "user_message" in ctx.session.state:
|
||||
user_message = ctx.session.state["user_message"]
|
||||
elif "message" in ctx.session.state:
|
||||
user_message = ctx.session.state["message"]
|
||||
|
||||
# 2. Use the session ID as a stable identifier
|
||||
session_id = (
|
||||
str(ctx.session.id)
|
||||
if ctx.session and hasattr(ctx.session, "id")
|
||||
else str(uuid.uuid4())
|
||||
)
|
||||
|
||||
# 3. Create the workflow graph from the provided JSON
|
||||
user_message = await self._extract_user_message(ctx)
|
||||
session_id = self._get_session_id(ctx)
|
||||
graph = await self._create_graph(ctx, self.flow_json)
|
||||
|
||||
# 4. Prepare the initial state
|
||||
user_event = Event(
|
||||
author="user",
|
||||
content=Content(parts=[Part(text=user_message)]),
|
||||
initial_state = await self._prepare_initial_state(
|
||||
ctx, user_message, session_id
|
||||
)
|
||||
|
||||
# If the conversation history is empty, add the user message
|
||||
conversation_history = ctx.session.events or []
|
||||
if not conversation_history or (len(conversation_history) == 0):
|
||||
conversation_history = [user_event]
|
||||
|
||||
initial_state = State(
|
||||
content=[user_event],
|
||||
status="started",
|
||||
session_id=session_id,
|
||||
cycle_count=0,
|
||||
node_outputs={},
|
||||
conversation_history=conversation_history,
|
||||
)
|
||||
|
||||
# 5. Execute the graph
|
||||
print("\n🚀 Starting workflow execution:")
|
||||
print(f"Initial content: {user_message[:100]}...")
|
||||
|
||||
sent_events = 0 # Count of events already sent
|
||||
|
||||
async for state in graph.astream(initial_state, {"recursion_limit": 20}):
|
||||
# The state can be a dict with the node name as a key
|
||||
for node_state in state.values():
|
||||
content = node_state.get("content", [])
|
||||
# Only send new events
|
||||
for event in content[sent_events:]:
|
||||
if event.author != "user":
|
||||
yield event
|
||||
sent_events = len(content)
|
||||
|
||||
# Execute sub-agents
|
||||
for sub_agent in self.sub_agents:
|
||||
async for event in sub_agent.run_async(ctx):
|
||||
yield event
|
||||
# Iterar sobre o AsyncGenerator em vez de usar await
|
||||
async for event in self._execute_workflow(ctx, graph, initial_state):
|
||||
yield event
|
||||
|
||||
except Exception as e:
|
||||
# Handle any uncaught errors
|
||||
error_msg = f"Error executing the workflow agent: {str(e)}"
|
||||
print(error_msg)
|
||||
yield Event(
|
||||
author=self.name,
|
||||
content=Content(
|
||||
role="agent",
|
||||
parts=[Part(text=error_msg)],
|
||||
),
|
||||
)
|
||||
yield await self._handle_workflow_error(e)
|
||||
|
||||
async def _extract_user_message(self, ctx: InvocationContext) -> str:
|
||||
"""Extracts the user message from context session events or state."""
|
||||
# Try to find message in session events
|
||||
if ctx.session and hasattr(ctx.session, "events") and ctx.session.events:
|
||||
for event in reversed(ctx.session.events):
|
||||
if event.author == "user" and event.content and event.content.parts:
|
||||
print("Message found in session events")
|
||||
return event.content.parts[0].text
|
||||
|
||||
# Try to find message in session state
|
||||
if ctx.session and ctx.session.state:
|
||||
if "user_message" in ctx.session.state:
|
||||
return ctx.session.state["user_message"]
|
||||
elif "message" in ctx.session.state:
|
||||
return ctx.session.state["message"]
|
||||
|
||||
return ""
|
||||
|
||||
def _get_session_id(self, ctx: InvocationContext) -> str:
|
||||
"""Gets or generates a session ID."""
|
||||
if ctx.session and hasattr(ctx.session, "id"):
|
||||
return str(ctx.session.id)
|
||||
return str(uuid.uuid4())
|
||||
|
||||
async def _prepare_initial_state(
|
||||
self, ctx: InvocationContext, user_message: str, session_id: str
|
||||
) -> State:
|
||||
"""Prepares the initial state for workflow execution."""
|
||||
user_event = Event(
|
||||
author="user",
|
||||
content=Content(parts=[Part(text=user_message)]),
|
||||
)
|
||||
|
||||
conversation_history = ctx.session.events or [user_event]
|
||||
|
||||
return State(
|
||||
content=[user_event],
|
||||
status="started",
|
||||
session_id=session_id,
|
||||
cycle_count=0,
|
||||
node_outputs={},
|
||||
conversation_history=conversation_history,
|
||||
)
|
||||
|
||||
async def _execute_workflow(
|
||||
self, ctx: InvocationContext, graph: StateGraph, initial_state: State
|
||||
) -> AsyncGenerator[Event, None]:
|
||||
"""Executes the workflow graph and yields events."""
|
||||
sent_events = 0
|
||||
|
||||
async for state in graph.astream(initial_state, {"recursion_limit": 100}):
|
||||
for node_state in state.values():
|
||||
content = node_state.get("content", [])
|
||||
for event in content[sent_events:]:
|
||||
if event.author != "user":
|
||||
yield event
|
||||
sent_events = len(content)
|
||||
|
||||
# Execute sub-agents if any
|
||||
for sub_agent in self.sub_agents:
|
||||
async for event in sub_agent.run_async(ctx):
|
||||
yield event
|
||||
|
||||
async def _handle_workflow_error(self, error: Exception) -> Event:
|
||||
"""Creates an error event for workflow execution errors."""
|
||||
error_msg = f"Error executing the workflow agent: {str(error)}"
|
||||
print(error_msg)
|
||||
return Event(
|
||||
author=self.name,
|
||||
content=Content(
|
||||
role="agent",
|
||||
parts=[Part(text=error_msg)],
|
||||
),
|
||||
)
|
||||
@@ -1,3 +1,32 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: custom_tools.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
from typing import Any, Dict, List
|
||||
from google.adk.tools import FunctionTool
|
||||
import requests
|
||||
|
||||
@@ -1,11 +1,43 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: email_service.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
import sendgrid
|
||||
from sendgrid.helpers.mail import Mail, Email, To, Content
|
||||
from src.config.settings import settings
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from jinja2 import Environment, FileSystemLoader, select_autoescape
|
||||
import os
|
||||
import smtplib
|
||||
from email.mime.text import MIMEText
|
||||
from email.mime.multipart import MIMEMultipart
|
||||
from pathlib import Path
|
||||
from config.settings import settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -39,6 +71,110 @@ def _render_template(template_name: str, context: dict) -> str:
|
||||
return f"<p>Could not display email content. Please access {context.get('verification_link', '') or context.get('reset_link', '')}</p>"
|
||||
|
||||
|
||||
def _send_email_sendgrid(to_email: str, subject: str, html_content: str) -> bool:
|
||||
"""
|
||||
Send an email using SendGrid provider
|
||||
|
||||
Args:
|
||||
to_email: Recipient's email
|
||||
subject: Email subject
|
||||
html_content: HTML content of the email
|
||||
|
||||
Returns:
|
||||
bool: True if the email was sent successfully, False otherwise
|
||||
"""
|
||||
try:
|
||||
sg = sendgrid.SendGridAPIClient(api_key=settings.SENDGRID_API_KEY)
|
||||
from_email = Email(settings.EMAIL_FROM)
|
||||
to_email = To(to_email)
|
||||
content = Content("text/html", html_content)
|
||||
|
||||
mail = Mail(from_email, to_email, subject, content)
|
||||
response = sg.client.mail.send.post(request_body=mail.get())
|
||||
|
||||
if response.status_code >= 200 and response.status_code < 300:
|
||||
logger.info(f"Email sent via SendGrid to {to_email}")
|
||||
return True
|
||||
else:
|
||||
logger.error(
|
||||
f"Failed to send email via SendGrid to {to_email}. Status: {response.status_code}"
|
||||
)
|
||||
return False
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error sending email via SendGrid to {to_email}: {str(e)}")
|
||||
return False
|
||||
|
||||
|
||||
def _send_email_smtp(to_email: str, subject: str, html_content: str) -> bool:
|
||||
"""
|
||||
Send an email using SMTP provider
|
||||
|
||||
Args:
|
||||
to_email: Recipient's email
|
||||
subject: Email subject
|
||||
html_content: HTML content of the email
|
||||
|
||||
Returns:
|
||||
bool: True if the email was sent successfully, False otherwise
|
||||
"""
|
||||
try:
|
||||
# Create message container
|
||||
msg = MIMEMultipart('alternative')
|
||||
msg['Subject'] = subject
|
||||
msg['From'] = settings.SMTP_FROM or settings.EMAIL_FROM
|
||||
msg['To'] = to_email
|
||||
|
||||
# Attach HTML content
|
||||
part = MIMEText(html_content, 'html')
|
||||
msg.attach(part)
|
||||
|
||||
# Setup SMTP server
|
||||
if settings.SMTP_USE_SSL:
|
||||
server = smtplib.SMTP_SSL(settings.SMTP_HOST, settings.SMTP_PORT)
|
||||
else:
|
||||
server = smtplib.SMTP(settings.SMTP_HOST, settings.SMTP_PORT)
|
||||
if settings.SMTP_USE_TLS:
|
||||
server.starttls()
|
||||
|
||||
# Login if credentials are provided
|
||||
if settings.SMTP_USER and settings.SMTP_PASSWORD:
|
||||
server.login(settings.SMTP_USER, settings.SMTP_PASSWORD)
|
||||
|
||||
# Send email
|
||||
server.sendmail(
|
||||
settings.SMTP_FROM or settings.EMAIL_FROM,
|
||||
to_email,
|
||||
msg.as_string()
|
||||
)
|
||||
server.quit()
|
||||
|
||||
logger.info(f"Email sent via SMTP to {to_email}")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error sending email via SMTP to {to_email}: {str(e)}")
|
||||
return False
|
||||
|
||||
|
||||
def send_email(to_email: str, subject: str, html_content: str) -> bool:
|
||||
"""
|
||||
Send an email using the configured provider
|
||||
|
||||
Args:
|
||||
to_email: Recipient's email
|
||||
subject: Email subject
|
||||
html_content: HTML content of the email
|
||||
|
||||
Returns:
|
||||
bool: True if the email was sent successfully, False otherwise
|
||||
"""
|
||||
if settings.EMAIL_PROVIDER.lower() == "smtp":
|
||||
return _send_email_smtp(to_email, subject, html_content)
|
||||
else: # Default to SendGrid
|
||||
return _send_email_sendgrid(to_email, subject, html_content)
|
||||
|
||||
|
||||
def send_verification_email(email: str, token: str) -> bool:
|
||||
"""
|
||||
Send a verification email to the user
|
||||
@@ -51,40 +187,22 @@ def send_verification_email(email: str, token: str) -> bool:
|
||||
bool: True if the email was sent successfully, False otherwise
|
||||
"""
|
||||
try:
|
||||
sg = sendgrid.SendGridAPIClient(api_key=settings.SENDGRID_API_KEY)
|
||||
from_email = Email(settings.EMAIL_FROM)
|
||||
to_email = To(email)
|
||||
subject = "Email Verification - Evo AI"
|
||||
|
||||
verification_link = f"{settings.APP_URL}/api/v1/auth/verify-email/{token}"
|
||||
verification_link = f"{settings.APP_URL}/security/verify-email?code={token}"
|
||||
|
||||
html_content = _render_template(
|
||||
"verification_email",
|
||||
{
|
||||
"verification_link": verification_link,
|
||||
"user_name": email.split("@")[
|
||||
0
|
||||
], # Use part of the email as temporary name
|
||||
"user_name": email.split("@")[0], # Use part of the email as temporary name
|
||||
"current_year": datetime.now().year,
|
||||
},
|
||||
)
|
||||
|
||||
content = Content("text/html", html_content)
|
||||
|
||||
mail = Mail(from_email, to_email, subject, content)
|
||||
response = sg.client.mail.send.post(request_body=mail.get())
|
||||
|
||||
if response.status_code >= 200 and response.status_code < 300:
|
||||
logger.info(f"Verification email sent to {email}")
|
||||
return True
|
||||
else:
|
||||
logger.error(
|
||||
f"Failed to send verification email to {email}. Status: {response.status_code}"
|
||||
)
|
||||
return False
|
||||
return send_email(email, subject, html_content)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error sending verification email to {email}: {str(e)}")
|
||||
logger.error(f"Error preparing verification email to {email}: {str(e)}")
|
||||
return False
|
||||
|
||||
|
||||
@@ -100,40 +218,22 @@ def send_password_reset_email(email: str, token: str) -> bool:
|
||||
bool: True if the email was sent successfully, False otherwise
|
||||
"""
|
||||
try:
|
||||
sg = sendgrid.SendGridAPIClient(api_key=settings.SENDGRID_API_KEY)
|
||||
from_email = Email(settings.EMAIL_FROM)
|
||||
to_email = To(email)
|
||||
subject = "Password Reset - Evo AI"
|
||||
|
||||
reset_link = f"{settings.APP_URL}/reset-password?token={token}"
|
||||
reset_link = f"{settings.APP_URL}/security/reset-password?token={token}"
|
||||
|
||||
html_content = _render_template(
|
||||
"password_reset",
|
||||
{
|
||||
"reset_link": reset_link,
|
||||
"user_name": email.split("@")[
|
||||
0
|
||||
], # Use part of the email as temporary name
|
||||
"user_name": email.split("@")[0], # Use part of the email as temporary name
|
||||
"current_year": datetime.now().year,
|
||||
},
|
||||
)
|
||||
|
||||
content = Content("text/html", html_content)
|
||||
|
||||
mail = Mail(from_email, to_email, subject, content)
|
||||
response = sg.client.mail.send.post(request_body=mail.get())
|
||||
|
||||
if response.status_code >= 200 and response.status_code < 300:
|
||||
logger.info(f"Password reset email sent to {email}")
|
||||
return True
|
||||
else:
|
||||
logger.error(
|
||||
f"Failed to send password reset email to {email}. Status: {response.status_code}"
|
||||
)
|
||||
return False
|
||||
return send_email(email, subject, html_content)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error sending password reset email to {email}: {str(e)}")
|
||||
logger.error(f"Error preparing password reset email to {email}: {str(e)}")
|
||||
return False
|
||||
|
||||
|
||||
@@ -149,11 +249,7 @@ def send_welcome_email(email: str, user_name: str = None) -> bool:
|
||||
bool: True if the email was sent successfully, False otherwise
|
||||
"""
|
||||
try:
|
||||
sg = sendgrid.SendGridAPIClient(api_key=settings.SENDGRID_API_KEY)
|
||||
from_email = Email(settings.EMAIL_FROM)
|
||||
to_email = To(email)
|
||||
subject = "Welcome to Evo AI"
|
||||
|
||||
dashboard_link = f"{settings.APP_URL}/dashboard"
|
||||
|
||||
html_content = _render_template(
|
||||
@@ -165,22 +261,10 @@ def send_welcome_email(email: str, user_name: str = None) -> bool:
|
||||
},
|
||||
)
|
||||
|
||||
content = Content("text/html", html_content)
|
||||
|
||||
mail = Mail(from_email, to_email, subject, content)
|
||||
response = sg.client.mail.send.post(request_body=mail.get())
|
||||
|
||||
if response.status_code >= 200 and response.status_code < 300:
|
||||
logger.info(f"Welcome email sent to {email}")
|
||||
return True
|
||||
else:
|
||||
logger.error(
|
||||
f"Failed to send welcome email to {email}. Status: {response.status_code}"
|
||||
)
|
||||
return False
|
||||
return send_email(email, subject, html_content)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error sending welcome email to {email}: {str(e)}")
|
||||
logger.error(f"Error preparing welcome email to {email}: {str(e)}")
|
||||
return False
|
||||
|
||||
|
||||
@@ -200,12 +284,8 @@ def send_account_locked_email(
|
||||
bool: True if the email was sent successfully, False otherwise
|
||||
"""
|
||||
try:
|
||||
sg = sendgrid.SendGridAPIClient(api_key=settings.SENDGRID_API_KEY)
|
||||
from_email = Email(settings.EMAIL_FROM)
|
||||
to_email = To(email)
|
||||
subject = "Security Alert - Account Locked"
|
||||
|
||||
reset_link = f"{settings.APP_URL}/reset-password?token={reset_token}"
|
||||
reset_link = f"{settings.APP_URL}/security/reset-password?token={reset_token}"
|
||||
|
||||
html_content = _render_template(
|
||||
"account_locked",
|
||||
@@ -218,20 +298,8 @@ def send_account_locked_email(
|
||||
},
|
||||
)
|
||||
|
||||
content = Content("text/html", html_content)
|
||||
|
||||
mail = Mail(from_email, to_email, subject, content)
|
||||
response = sg.client.mail.send.post(request_body=mail.get())
|
||||
|
||||
if response.status_code >= 200 and response.status_code < 300:
|
||||
logger.info(f"Account locked email sent to {email}")
|
||||
return True
|
||||
else:
|
||||
logger.error(
|
||||
f"Failed to send account locked email to {email}. Status: {response.status_code}"
|
||||
)
|
||||
return False
|
||||
return send_email(email, subject, html_content)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error sending account locked email to {email}: {str(e)}")
|
||||
logger.error(f"Error preparing account locked email to {email}: {str(e)}")
|
||||
return False
|
||||
|
||||
@@ -1,3 +1,32 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: run_seeders.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from fastapi import HTTPException, status
|
||||
|
||||
@@ -1,3 +1,32 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: mcp_service.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
from google.adk.tools.mcp_tool.mcp_toolset import (
|
||||
MCPToolset,
|
||||
|
||||
@@ -1,3 +1,32 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: service_providers.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
from src.config.settings import settings
|
||||
from google.adk.artifacts.in_memory_artifact_service import InMemoryArtifactService
|
||||
from google.adk.sessions import DatabaseSessionService
|
||||
|
||||
@@ -1,3 +1,32 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: session_service.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
from google.adk.sessions import DatabaseSessionService
|
||||
from sqlalchemy.orm import Session
|
||||
from src.models.models import Session as SessionModel
|
||||
|
||||
@@ -1,3 +1,32 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: tool_service.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from fastapi import HTTPException, status
|
||||
|
||||
@@ -1,3 +1,32 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: user_service.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from src.models.models import User, Client
|
||||
@@ -7,7 +36,7 @@ from src.services.email_service import (
|
||||
send_verification_email,
|
||||
send_password_reset_email,
|
||||
)
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import uuid
|
||||
import logging
|
||||
from typing import Optional, Tuple
|
||||
@@ -295,7 +324,11 @@ def reset_password(db: Session, token: str, new_password: str) -> Tuple[bool, st
|
||||
return False, "Invalid password reset token"
|
||||
|
||||
# Check if the token has expired
|
||||
if user.password_reset_expiry < datetime.utcnow():
|
||||
now = datetime.now(timezone.utc)
|
||||
expiry = user.password_reset_expiry
|
||||
if expiry is not None and expiry.tzinfo is None:
|
||||
expiry = expiry.replace(tzinfo=timezone.utc)
|
||||
if expiry is None or expiry < now:
|
||||
logger.warning(
|
||||
f"Attempt to reset password with expired token for user: {user.email}"
|
||||
)
|
||||
@@ -341,7 +374,9 @@ def get_user_by_email(db: Session, email: str) -> Optional[User]:
|
||||
return None
|
||||
|
||||
|
||||
def authenticate_user(db: Session, email: str, password: str) -> Optional[User]:
|
||||
def authenticate_user(
|
||||
db: Session, email: str, password: str
|
||||
) -> Tuple[Optional[User], str]:
|
||||
"""
|
||||
Authenticates a user with email and password
|
||||
|
||||
@@ -351,16 +386,18 @@ def authenticate_user(db: Session, email: str, password: str) -> Optional[User]:
|
||||
password: User password
|
||||
|
||||
Returns:
|
||||
Optional[User]: Authenticated user or None
|
||||
Tuple[Optional[User], str]: Authenticated user and reason (or None and reason)
|
||||
"""
|
||||
user = get_user_by_email(db, email)
|
||||
if not user:
|
||||
return None
|
||||
return None, "user_not_found"
|
||||
if not verify_password(password, user.password_hash):
|
||||
return None
|
||||
return None, "invalid_password"
|
||||
if not user.email_verified:
|
||||
return None, "email_not_verified"
|
||||
if not user.is_active:
|
||||
return None
|
||||
return user
|
||||
return None, "inactive_user"
|
||||
return user, "success"
|
||||
|
||||
|
||||
def get_admin_users(db: Session, skip: int = 0, limit: int = 100):
|
||||
|
||||
@@ -1,83 +1,103 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>{% block title %}Evo AI{% endblock %}</title>
|
||||
<style>
|
||||
body {
|
||||
font-family: Arial, sans-serif;
|
||||
line-height: 1.6;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background-color: #f7f7f7;
|
||||
body {
|
||||
font-family: "Segoe UI", Arial, sans-serif;
|
||||
background-color: #f7f7f7;
|
||||
color: #222;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
.container {
|
||||
max-width: 480px;
|
||||
margin: 32px auto;
|
||||
background: #fff;
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 4px 24px rgba(0, 0, 0, 0.08);
|
||||
padding: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
.header {
|
||||
background: #f7f7f7;
|
||||
border-bottom: 1px solid #e5e5e5;
|
||||
padding: 32px 0 16px 0;
|
||||
text-align: center;
|
||||
}
|
||||
.header h1 {
|
||||
color: #155a2c;
|
||||
font-size: 2rem;
|
||||
margin: 0;
|
||||
letter-spacing: 1px;
|
||||
}
|
||||
.content {
|
||||
padding: 32px 24px 24px 24px;
|
||||
}
|
||||
.button {
|
||||
background: linear-gradient(90deg, #155a2c 0%, #1f7a3dff 100%);
|
||||
color: #fff !important;
|
||||
padding: 14px 0;
|
||||
border-radius: 6px;
|
||||
text-decoration: none;
|
||||
display: block;
|
||||
font-weight: bold;
|
||||
text-align: center;
|
||||
font-size: 1.1rem;
|
||||
margin: 32px 0 0 0;
|
||||
transition: filter 0.2s;
|
||||
box-shadow: 0 2px 8px rgba(37, 99, 235, 0.08);
|
||||
}
|
||||
.button:hover {
|
||||
filter: brightness(1.08);
|
||||
}
|
||||
.footer {
|
||||
font-size: 12px;
|
||||
text-align: center;
|
||||
color: #888;
|
||||
background: #f7f7f7;
|
||||
border-top: 1px solid #e5e5e5;
|
||||
padding: 20px 0 10px 0;
|
||||
}
|
||||
.link {
|
||||
color: #155a2c;
|
||||
text-decoration: underline;
|
||||
word-break: break-all;
|
||||
}
|
||||
.warning {
|
||||
color: #b91c1c;
|
||||
background: #fee2e2;
|
||||
border-radius: 4px;
|
||||
padding: 12px;
|
||||
margin-top: 20px;
|
||||
}
|
||||
@media (max-width: 600px) {
|
||||
.container {
|
||||
max-width: 98vw;
|
||||
margin: 8px;
|
||||
}
|
||||
.container {
|
||||
max-width: 600px;
|
||||
margin: 0 auto;
|
||||
padding: 20px;
|
||||
background-color: #ffffff;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
||||
}
|
||||
.header {
|
||||
background-color: #4A90E2;
|
||||
color: white;
|
||||
padding: 15px;
|
||||
text-align: center;
|
||||
border-radius: 6px 6px 0 0;
|
||||
}
|
||||
.content {
|
||||
padding: 20px;
|
||||
}
|
||||
.button {
|
||||
background-color: #4A90E2;
|
||||
color: white !important;
|
||||
padding: 12px 24px;
|
||||
text-decoration: none;
|
||||
border-radius: 4px;
|
||||
display: inline-block;
|
||||
font-weight: bold;
|
||||
text-align: center;
|
||||
transition: background-color 0.3s;
|
||||
}
|
||||
.button:hover {
|
||||
background-color: #3a7bc8;
|
||||
}
|
||||
.footer {
|
||||
font-size: 12px;
|
||||
text-align: center;
|
||||
margin-top: 30px;
|
||||
color: #888;
|
||||
border-top: 1px solid #eee;
|
||||
padding-top: 20px;
|
||||
}
|
||||
.link {
|
||||
word-break: break-all;
|
||||
color: #4A90E2;
|
||||
}
|
||||
.warning {
|
||||
color: #E74C3C;
|
||||
padding: 10px;
|
||||
background-color: #FADBD8;
|
||||
border-radius: 4px;
|
||||
margin-top: 20px;
|
||||
.content {
|
||||
padding: 18px 8px 16px 8px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
{% block additional_styles %}{% endblock %}
|
||||
</head>
|
||||
<body>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
<h1>{% block header %}Evo AI{% endblock %}</h1>
|
||||
</div>
|
||||
<div class="content">
|
||||
{% block content %}{% endblock %}
|
||||
</div>
|
||||
<div class="footer">
|
||||
<p>{% block footer_message %}This is an automated email, please do not reply.{% endblock %}</p>
|
||||
<p>© {{ current_year }} Evo AI. All rights reserved.</p>
|
||||
</div>
|
||||
<div class="header">
|
||||
<h1>{% block header %}Evo AI{% endblock %}</h1>
|
||||
</div>
|
||||
<div class="content">{% block content %}{% endblock %}</div>
|
||||
<div class="footer">
|
||||
<p>
|
||||
{% block footer_message %}This is an automated email, please do not
|
||||
reply.{% endblock %}
|
||||
</p>
|
||||
<p>© {{ current_year }} Evo AI. All rights reserved.</p>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -1,7 +1,42 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: a2a_utils.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
import base64
|
||||
import uuid
|
||||
from typing import Dict, List, Any, Optional
|
||||
from google.genai.types import Part, Blob
|
||||
|
||||
from src.schemas.a2a_types import (
|
||||
ContentTypeNotSupportedError,
|
||||
JSONRPCResponse,
|
||||
UnsupportedOperationError,
|
||||
Message,
|
||||
)
|
||||
|
||||
|
||||
@@ -26,3 +61,130 @@ def new_incompatible_types_error(request_id):
|
||||
|
||||
def new_not_implemented_error(request_id):
|
||||
return JSONRPCResponse(id=request_id, error=UnsupportedOperationError())
|
||||
|
||||
|
||||
def extract_files_from_message(message: Message) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
Extract file parts from an A2A message.
|
||||
|
||||
Args:
|
||||
message: An A2A Message object
|
||||
|
||||
Returns:
|
||||
List of file parts extracted from the message
|
||||
"""
|
||||
if not message or not message.parts:
|
||||
return []
|
||||
|
||||
files = []
|
||||
for part in message.parts:
|
||||
if hasattr(part, "type") and part.type == "file" and hasattr(part, "file"):
|
||||
files.append(part)
|
||||
|
||||
return files
|
||||
|
||||
|
||||
def a2a_part_to_adk_part(a2a_part: Dict[str, Any]) -> Optional[Part]:
|
||||
"""
|
||||
Convert an A2A protocol part to an ADK Part object.
|
||||
|
||||
Args:
|
||||
a2a_part: An A2A part dictionary
|
||||
|
||||
Returns:
|
||||
Converted ADK Part object or None if conversion not possible
|
||||
"""
|
||||
part_type = a2a_part.get("type")
|
||||
if part_type == "file" and "file" in a2a_part:
|
||||
file_data = a2a_part["file"]
|
||||
if "bytes" in file_data:
|
||||
try:
|
||||
# Convert base64 to bytes
|
||||
file_bytes = base64.b64decode(file_data["bytes"])
|
||||
mime_type = file_data.get("mimeType", "application/octet-stream")
|
||||
|
||||
# Create ADK Part
|
||||
return Part(inline_data=Blob(mime_type=mime_type, data=file_bytes))
|
||||
except Exception:
|
||||
return None
|
||||
elif part_type == "text" and "text" in a2a_part:
|
||||
# For text parts, we could create a text blob if needed
|
||||
return None
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def adk_part_to_a2a_part(
|
||||
adk_part: Part, filename: Optional[str] = None
|
||||
) -> Optional[Dict[str, Any]]:
|
||||
"""
|
||||
Convert an ADK Part object to an A2A protocol part.
|
||||
|
||||
Args:
|
||||
adk_part: An ADK Part object
|
||||
filename: Optional filename to use
|
||||
|
||||
Returns:
|
||||
Converted A2A Part dictionary or None if conversion not possible
|
||||
"""
|
||||
if hasattr(adk_part, "inline_data") and adk_part.inline_data:
|
||||
if adk_part.inline_data.data and adk_part.inline_data.mime_type:
|
||||
# Convert binary data to base64
|
||||
file_bytes = adk_part.inline_data.data
|
||||
mime_type = adk_part.inline_data.mime_type
|
||||
|
||||
# Generate filename if not provided
|
||||
if not filename:
|
||||
ext = get_extension_from_mime(mime_type)
|
||||
filename = f"file_{uuid.uuid4().hex}{ext}"
|
||||
|
||||
# Convert to A2A FilePart dict
|
||||
return {
|
||||
"type": "file",
|
||||
"file": {
|
||||
"name": filename,
|
||||
"mimeType": mime_type,
|
||||
"bytes": (
|
||||
base64.b64encode(file_bytes).decode("utf-8")
|
||||
if isinstance(file_bytes, bytes)
|
||||
else str(file_bytes)
|
||||
),
|
||||
},
|
||||
}
|
||||
elif hasattr(adk_part, "text") and adk_part.text:
|
||||
# Convert text part
|
||||
return {"type": "text", "text": adk_part.text}
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def get_extension_from_mime(mime_type: str) -> str:
|
||||
"""
|
||||
Get a file extension from MIME type.
|
||||
|
||||
Args:
|
||||
mime_type: MIME type string
|
||||
|
||||
Returns:
|
||||
Appropriate file extension with leading dot
|
||||
"""
|
||||
if not mime_type:
|
||||
return ""
|
||||
|
||||
mime_map = {
|
||||
"image/jpeg": ".jpg",
|
||||
"image/png": ".png",
|
||||
"image/gif": ".gif",
|
||||
"application/pdf": ".pdf",
|
||||
"text/plain": ".txt",
|
||||
"text/html": ".html",
|
||||
"text/csv": ".csv",
|
||||
"application/json": ".json",
|
||||
"application/xml": ".xml",
|
||||
"application/msword": ".doc",
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.document": ".docx",
|
||||
"application/vnd.ms-excel": ".xls",
|
||||
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": ".xlsx",
|
||||
}
|
||||
|
||||
return mime_map.get(mime_type, "")
|
||||
|
||||
@@ -1,3 +1,32 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: crypto.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
from cryptography.fernet import Fernet
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
|
||||
@@ -1,3 +1,32 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: logger.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
|
||||
@@ -1,3 +1,32 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: otel.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
import os
|
||||
import base64
|
||||
from src.config.settings import settings
|
||||
|
||||
@@ -1,3 +1,32 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: security.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
from passlib.context import CryptContext
|
||||
from datetime import datetime, timedelta
|
||||
import secrets
|
||||
|
||||
@@ -1,3 +1,32 @@
|
||||
"""
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ @author: Davidson Gomes │
|
||||
│ @file: streaming.py │
|
||||
│ Developed by: Davidson Gomes │
|
||||
│ Creation date: May 13, 2025 │
|
||||
│ Contact: contato@evolution-api.com │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @copyright © Evolution API 2025. All rights reserved. │
|
||||
│ Licensed under the Apache License, Version 2.0 │
|
||||
│ │
|
||||
│ You may not use this file except in compliance with the License. │
|
||||
│ You may obtain a copy of the License at │
|
||||
│ │
|
||||
│ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
│ │
|
||||
│ Unless required by applicable law or agreed to in writing, software │
|
||||
│ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
│ See the License for the specific language governing permissions and │
|
||||
│ limitations under the License. │
|
||||
├──────────────────────────────────────────────────────────────────────────────┤
|
||||
│ @important │
|
||||
│ For any future changes to the code in this file, it is recommended to │
|
||||
│ include, together with the modification, the information of the developer │
|
||||
│ who changed it and the date of modification. │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
from typing import AsyncGenerator
|
||||
from fastapi import HTTPException
|
||||
|
||||
Reference in New Issue
Block a user