1 Commits
Author SHA1 Message Date
martin legrand 89f5736f6b feat : self run script 2025-05-05 15:55:35 +02:00
82 changed files with 8014 additions and 11435 deletions
-18
View File
@@ -1,18 +0,0 @@
# Python cache files
__pycache__/
*.py[cod]
# Virtual environments
agentic_seek_env/
.agentic_seek_env/
.env
# Git metadata
.git/
# macOS Finder files
.DS_Store
# Log files
*.log
+2 -12
View File
@@ -1,13 +1,3 @@
SEARXNG_BASE_URL="http://searxng:8080" SEARXNG_BASE_URL="http://127.0.0.1:8080"
REDIS_BASE_URL="redis://redis:6379/0"
WORK_DIR="/Users/username/Documents/workspace_with_my_files"
OLLAMA_PORT="11434"
LM_STUDIO_PORT="1234"
BACKEND_PORT="7777"
CUSTOM_ADDITIONAL_LLM_PORT="11435"
OPENAI_API_KEY='xxxxx' OPENAI_API_KEY='xxxxx'
DEEPSEEK_API_KEY='xxxxx' DEEPSEEK_API_KEY='xxxxx'
OPENROUTER_API_KEY='xxxxx'
TOGETHER_API_KEY='xxxxx'
GOOGLE_API_KEY='xxxxx'
ANTHROPIC_API_KEY='xxxxx'
+6 -3
View File
@@ -23,13 +23,16 @@ A clear and concise description of what you expected to happen.
**Screenshots** **Screenshots**
If applicable, add screenshots to help explain your problem. If applicable, add screenshots to help explain your problem.
**LLM Model used**
The model you used, for example deepseek-r1:14b
**Desktop (please complete the following information):** **Desktop (please complete the following information):**
- OS: [e.g. iOS] - OS: [e.g. iOS]
- Browser [e.g. chrome, safari] - Browser [e.g. chrome, safari]
- Version [e.g. 22] - Version [e.g. 22]
**Smartphone (please complete the following information):**
- Device: [e.g. iPhone6]
- OS: [e.g. iOS8.1]
- Browser [e.g. stock browser, safari]
- Version [e.g. 22]
**Additional context** **Additional context**
Add any other context about the problem here. Add any other context about the problem here.
-4
View File
@@ -6,12 +6,9 @@
*.egg-info *.egg-info
cookies.json cookies.json
test_agent.py test_agent.py
searxng/uwsgi.ini.new
searxng/settings.yml.new
config.ini config.ini
.voices/ .voices/
experimental/ experimental/
chrome_bundle/
.logs/ .logs/
.screenshots/*.png .screenshots/*.png
.screenshots/*.jpg .screenshots/*.jpg
@@ -21,7 +18,6 @@ agentic_seek_env/*
.env .env
*/.env */.env
dsk/ dsk/
chrome136/
### react ### ### react ###
.DS_* .DS_*
-1
View File
@@ -1 +0,0 @@
3.10
+27 -83
View File
@@ -1,102 +1,46 @@
FROM ubuntu:22.04
FROM --platform=linux/amd64 python:3.11-slim # Warning: doesn't work yet, backend is run on host machine for now
ENV DEBIAN_FRONTEND=noninteractive
# Install essential packages and Chrome dependencies
RUN apt-get update -y && apt-get install -y \
wget \
gnupg2 \
ca-certificates \
unzip \
xvfb \
libxss1 \
#libappindicator1 \
fonts-liberation \
libnss3 \
libatk1.0-0 \
libatk-bridge2.0-0 \
libcups2 \
libdrm2 \
libxcomposite1 \
libxdamage1 \
libxrandr2 \
xdg-utils \
dbus \
&& rm -rf /var/lib/apt/lists/*
RUN apt-get update -y && \
apt-get install -y \
gcc \
g++ \
gfortran \
libportaudio2 \
portaudio19-dev \
ffmpeg \
libavcodec-dev \
libavformat-dev \
libavutil-dev \
gnupg2 \
wget \
unzip \
python3 \
python3-pip \
libasound2 \
libatk-bridge2.0-0 \
libgtk-4-1 \
libnss3 \
xdg-utils \
wget \
&& rm -rf /var/lib/apt/lists/*
RUN apt-get update -y && \
apt-get install -y \
alsa-utils \
&& rm -rf /var/lib/apt/lists/*
ENV CHROME_TESTING_VERSION=134.0.6998.88
ENV DISPLAY=:99
WORKDIR /app WORKDIR /app
RUN set -eux; \ RUN apt-get update -qq -y && \
wget -qO /tmp/chrome.zip \ apt-get install -y \
"https://storage.googleapis.com/chrome-for-testing-public/${CHROME_TESTING_VERSION}/linux64/chrome-linux64.zip"; \ gcc \
unzip -q /tmp/chrome.zip -d /opt; \ g++ \
rm /tmp/chrome.zip; \ gfortran \
ln -s /opt/chrome-linux64/chrome /usr/local/bin/google-chrome; \ libportaudio2 \
ln -s /opt/chrome-linux64/chrome /usr/local/bin/chrome; \ portaudio19-dev \
mkdir -p /opt/chrome; \ ffmpeg \
ln -s /opt/chrome-linux64/chrome /opt/chrome/chrome; \ libavcodec-dev \
google-chrome --version libavformat-dev \
libavutil-dev \
RUN set -eux; \ gnupg2 \
wget -qO /tmp/chromedriver.zip \ wget \
"https://storage.googleapis.com/chrome-for-testing-public/${CHROME_TESTING_VERSION}/linux64/chromedriver-linux64.zip"; \ unzip \
unzip -q /tmp/chromedriver.zip -d /tmp; \ python3 \
mv /tmp/chromedriver-linux64/chromedriver /usr/local/bin; \ python3-pip \
rm /tmp/chromedriver.zip; \ libasound2 \
chmod +x /usr/local/bin/chromedriver; \ libatk-bridge2.0-0 \
chromedriver --version libgtk-4-1 \
libnss3 \
xdg-utils \
wget && \
RUN chmod +x /opt/chrome/chrome RUN chmod +x /opt/chrome/chrome
# Install dependencies
RUN pip3 install --upgrade pip setuptools wheel
COPY requirements.txt . COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt RUN pip install --no-cache-dir -r requirements.txt
RUN mkdir -p /opt/workspace
RUN mkdir -p /tmp && chmod 1777 /tmp
# Copy application code # Copy application code
COPY api.py . COPY api.py .
COPY sources/ ./sources/ COPY sources/ ./sources/
COPY prompts/ ./prompts/ COPY prompts/ ./prompts/
COPY crx/ crx/ COPY crx/ crx/
COPY llm_router/ llm_router/ COPY llm_router/ llm_router/
COPY .env .
COPY config.ini . COPY config.ini .
# Expose port
EXPOSE 8000 EXPOSE 8000
# Run the application # Run the application
+185 -332
View File
@@ -4,7 +4,7 @@
<img align="center" src="./media/agentic_seek_logo.png" width="300" height="300" alt="Agentic Seek Logo"> <img align="center" src="./media/agentic_seek_logo.png" width="300" height="300" alt="Agentic Seek Logo">
<p> <p>
English | [中文](./README_CHS.md) | [繁體中文](./README_CHT.md) | [Français](./README_FR.md) | [日本語](./README_JP.md) | [Português (Brasil)](./README_PTBR.md) | [Español](./README_ES.md) English | [中文](./README_CHS.md) | [繁體中文](./README_CHT.md) | [Français](./README_FR.md) | [日本語](./README_JP.md)
*A **100% local alternative to Manus AI**, this voice-enabled AI assistant autonomously browses the web, writes code, and plans tasks while keeping all data on your device. Tailored for local reasoning models, it runs entirely on your hardware, ensuring complete privacy and zero cloud dependency.* *A **100% local alternative to Manus AI**, this voice-enabled AI assistant autonomously browses the web, writes code, and plans tasks while keeping all data on your device. Tailored for local reasoning models, it runs entirely on your hardware, ensuring complete privacy and zero cloud dependency.*
@@ -22,7 +22,7 @@
* 📋 Plans & Executes Complex Tasks - From trip planning to complex projects — it can split big tasks into steps and get things done using multiple AI agents. * 📋 Plans & Executes Complex Tasks - From trip planning to complex projects — it can split big tasks into steps and get things done using multiple AI agents.
* 🎙️ Voice-Enabled - Clean, fast, futuristic voice and speech to text allowing you to talk to it like it's your personal AI from a sci-fi movie. (In progress) * 🎙️ Voice-Enabled - Clean, fast, futuristic voice and speech to text allowing you to talk to it like it's your personal AI from a sci-fi movie
### **Demo** ### **Demo**
@@ -32,21 +32,15 @@ https://github.com/user-attachments/assets/b8ca60e9-7b3b-4533-840e-08f9ac426316
Disclaimer: This demo, including all the files that appear (e.g: CV_candidates.zip), are entirely fictional. We are not a corporation, we seek open-source contributors not candidates. Disclaimer: This demo, including all the files that appear (e.g: CV_candidates.zip), are entirely fictional. We are not a corporation, we seek open-source contributors not candidates.
> 🛠⚠️ **Active Work in Progress** > 🛠️ **Work in Progress** Looking for contributors!
> 🙏 This project started as a side-project and has zero roadmap and zero funding. It's grown way beyond what I expected by ending in GitHub Trending. Contributions, feedback, and patience are deeply appreciated. ## Installation
## Prerequisites Make sure you have chrome driver, docker and python3.10 (or newer) installed.
Before you begin, ensure you have the following software installed: For issues related to chrome driver, see the **Chromedriver** section.
* **Git:** For cloning the repository. [Download Git](https://git-scm.com/downloads) ### 1️⃣ **Clone the repository and setup**
* **Python 3.10.x:** We strongly recommend using Python version 3.10.x. Using other versions might lead to dependency errors. [Download Python 3.10](https://www.python.org/downloads/release/python-3100/) (pick a 3.10.x version).
* **Docker Engine & Docker Compose:** For running bundled services like SearxNG.
* Install Docker Desktop (which includes Docker Compose V2): [Windows](https://docs.docker.com/desktop/install/windows-install/) | [Mac](https://docs.docker.com/desktop/install/mac-install/) | [Linux](https://docs.docker.com/desktop/install/linux-install/)
* Alternatively, install Docker Engine and Docker Compose separately on Linux: [Docker Engine](https://docs.docker.com/engine/install/) | [Docker Compose](https://docs.docker.com/compose/install/) (ensure you install Compose V2, e.g., `sudo apt-get install docker-compose-plugin`).
### 1. **Clone the repository and setup**
```sh ```sh
git clone https://github.com/Fosowl/agenticSeek.git git clone https://github.com/Fosowl/agenticSeek.git
@@ -54,82 +48,84 @@ cd agenticSeek
mv .env.example .env mv .env.example .env
``` ```
### 2. Change the .env file content ### 2 **Create a virtual env**
```sh ```sh
SEARXNG_BASE_URL="http://searxng:8080" # http://127.0.0.1:8080 if running on host python3 -m venv agentic_seek_env
REDIS_BASE_URL="redis://redis:6379/0" source agentic_seek_env/bin/activate
WORK_DIR="/Users/mlg/Documents/workspace_for_ai" # On Windows: agentic_seek_env\Scripts\activate
OLLAMA_PORT="11434"
LM_STUDIO_PORT="1234"
CUSTOM_ADDITIONAL_LLM_PORT="11435"
OPENAI_API_KEY='optional'
DEEPSEEK_API_KEY='optional'
OPENROUTER_API_KEY='optional'
TOGETHER_API_KEY='optional'
GOOGLE_API_KEY='optional'
ANTHROPIC_API_KEY='optional'
``` ```
### 3️⃣ **Install package**
Update the `.env` file with your own values as needed: Ensure Python, Docker and docker compose, and Google chrome are installed.
- **SEARXNG_BASE_URL**: Leave unchanged unless running on host with CLI mode. We recommand Python 3.10.0.
- **REDIS_BASE_URL**: Leave unchanged
- **WORK_DIR**: Path to your working directory on your local machine. AgenticSeek will be able to read and interact with these files.
- **OLLAMA_PORT**: Port number for the Ollama service.
- **LM_STUDIO_PORT**: Port number for the LM Studio service.
- **CUSTOM_ADDITIONAL_LLM_PORT**: Port for any additional custom LLM service.
**API Key are totally optional for user who choose to run LLM locally. Which is the primary purpose of this project. Leave empty if you have sufficient hardware** **Automatic Installation (Recommanded):**
### 3. **Start Docker** For Linux/Macos:
Make sure Docker is installed and running on your system. You can start Docker using the following commands:
- **On Linux/macOS:**
Open a terminal and run:
```sh
sudo systemctl start docker
```
Or launch Docker Desktop from your applications menu if installed.
- **On Windows:**
Start Docker Desktop from the Start menu.
You can verify Docker is running by executing:
```sh ```sh
docker info ./install.sh
``` ```
If you see information about your Docker installation, it is running correctly.
See the table of [Local Providers](#list-of-local-providers) below for a summary. For windows:
Next step: [Run AgenticSeek locally](#start-services-and-run) ```sh
./install.bat
```
*See the [Troubleshooting](#troubleshooting) section if you are having issues.* **Manually:**
*If your hardware can't run LLMs locally, see [Setup to run with an API](#setup-to-run-with-an-api).*
*For detailed `config.ini` explanations, see [Config Section](#config).* **Note: For any OS, ensure the ChromeDriver you install matches your installed Chrome version. Run `google-chrome --version`. See known issues if you have chrome >135**
- *Linux*:
Update Package List: `sudo apt update`
Install Dependencies: `sudo apt install -y alsa-utils portaudio19-dev python3-pyaudio libgtk-3-dev libnotify-dev libgconf-2-4 libnss3 libxss1`
Install ChromeDriver matching your Chrome browser version:
`sudo apt install -y chromium-chromedriver`
Install requirements: `pip3 install -r requirements.txt`
- *Macos*:
Update brew : `brew update`
Install chromedriver : `brew install --cask chromedriver`
Install portaudio: `brew install portaudio`
Upgrade pip : `python3 -m pip install --upgrade pip`
Upgrade wheel : : `pip3 install --upgrade setuptools wheel`
Install requirements: `pip3 install -r requirements.txt`
- *Windows*:
Install pyreadline3 `pip install pyreadline3`
Install portaudio manually (e.g., via vcpkg or prebuilt binaries) and then run: `pip install pyaudio`
Download and install chromedriver manually from: https://sites.google.com/chromium.org/driver/getting-started
Place chromedriver in a directory included in your PATH.
Install requirements: `pip3 install -r requirements.txt`
--- ---
## Setup for running LLM locally on your machine ## Setup for running LLM locally on your machine
**Hardware Requirements:** **We recommend using at the very least Deepseek 14B, smaller models will struggle with tasks especially for web browsing.**
To run LLMs locally, you'll need sufficient hardware. At a minimum, a GPU capable of running Magistral, Qwen or Deepseek 14B is required. See the FAQ for detailed model/performance recommendations.
**Setup your local provider** **Setup your local provider**
Start your local provider (for example with ollama): Start your local provider, for example with ollama:
Unless you wish to to run AgenticSeek on host (CLI mode), export or set the provider listen address:
```sh
export OLLAMA_HOST=0.0.0.0:11434
```
Then, start you provider:
```sh ```sh
ollama serve ollama serve
@@ -139,7 +135,7 @@ See below for a list of local supported provider.
**Update the config.ini** **Update the config.ini**
Change the config.ini file to set the provider_name to a supported provider and provider_model to a LLM supported by your provider. We recommend reasoning model such as *Magistral* or *Deepseek*. Change the config.ini file to set the provider_name to a supported provider and provider_model to a LLM supported by your provider. We recommand reasoning model such as *Qwen* or *Deepseek*.
See the **FAQ** at the end of the README for required hardware. See the **FAQ** at the end of the README for required hardware.
@@ -152,23 +148,17 @@ provider_server_address = 127.0.0.1:11434
agent_name = Jarvis # name of your AI agent_name = Jarvis # name of your AI
recover_last_session = True # whenever to recover the previous session recover_last_session = True # whenever to recover the previous session
save_session = True # whenever to remember the current session save_session = True # whenever to remember the current session
speak = False # text to speech speak = True # text to speech
listen = False # Speech to text, only for CLI, experimental listen = False # Speech to text, only for CLI
work_dir = /Users/mlg/Documents/workspace # The workspace for AgenticSeek.
jarvis_personality = False # Whenever to use a more "Jarvis" like personality (experimental) jarvis_personality = False # Whenever to use a more "Jarvis" like personality (experimental)
languages = en zh # The list of languages, Text to speech will default to the first language on the list languages = en zh # The list of languages, Text to speech will default to the first language on the list
[BROWSER] [BROWSER]
headless_browser = True # leave unchanged unless using CLI on host. headless_browser = True # Whenever to use headless browser, recommanded only if you use web interface.
stealth_mode = True # Use undetected selenium to reduce browser detection stealth_mode = True # Use undetected selenium to reduce browser detection
``` ```
**Warning**: Note: Some provider (eg: lm-studio) require you to have `http://` in front of the IP. For example `http://127.0.0.1:1234`
- The `config.ini` file format does not support comments.
Do not copy and paste the example configuration directly, as comments will cause errors. Instead, manually modify the `config.ini` file with your desired settings, excluding any comments.
- Do *NOT* set provider_name to `openai` if using LM-studio for running LLMs. Set it to `lm-studio`.
- Some provider (eg: lm-studio) require you to have `http://` in front of the IP. For example `http://127.0.0.1:1234`
**List of local providers** **List of local providers**
@@ -180,138 +170,93 @@ Do not copy and paste the example configuration directly, as comments will cause
Next step: [Start services and run AgenticSeek](#Start-services-and-Run) Next step: [Start services and run AgenticSeek](#Start-services-and-Run)
*See the [Troubleshooting](#troubleshooting) section if you are having issues.* *See the **Known issues** section if you are having issues*
*If your hardware can't run LLMs locally, see [Setup to run with an API](#setup-to-run-with-an-api).*
*For detailed `config.ini` explanations, see [Config Section](#config).* *See the **Run with an API** section if your hardware can't run deepseek locally*
*See the **Config** section for detailled config file explanation.*
---
## Setup to run with an API ## Setup to run with an API
This setup uses external, cloud-based LLM providers. You'll need an API key from your chosen service. Set the desired provider in the `config.ini`. See below for a list of API providers.
**1. Choose an API Provider and Get an API Key:** ```sh
Refer to the [List of API Providers](#list-of-api-providers) below. Visit their websites to sign up and obtain an API key.
**2. Set Your API Key as an Environment Variable:**
* **Linux/macOS:**
Open your terminal and use the `export` command. It's best to add this to your shell's profile file (e.g., `~/.bashrc`, `~/.zshrc`) for persistence.
```sh
export PROVIDER_API_KEY="your_api_key_here"
# Replace PROVIDER_API_KEY with the specific variable name, e.g., OPENAI_API_KEY, GOOGLE_API_KEY
```
Example for TogetherAI:
```sh
export TOGETHER_API_KEY="xxxxxxxxxxxxxxxxxxxxxx"
```
* **Windows:**
* **Command Prompt (Temporary for current session):**
```cmd
set PROVIDER_API_KEY=your_api_key_here
```
* **PowerShell (Temporary for current session):**
```powershell
$env:PROVIDER_API_KEY="your_api_key_here"
```
* **Permanently:** Search for "environment variables" in the Windows search bar, click "Edit the system environment variables," then click the "Environment Variables..." button. Add a new User variable with the appropriate name (e.g., `OPENAI_API_KEY`) and your key as the value.
*(See FAQ: [How do I set API keys?](#how-do-i-set-api-keys) for more details).*
**3. Update `config.ini`:**
```ini
[MAIN] [MAIN]
is_local = False is_local = False
provider_name = openai # Or google, deepseek, togetherAI, huggingface provider_name = google
provider_model = gpt-3.5-turbo # Or gemini-1.5-flash, deepseek-chat, mistralai/Mixtral-8x7B-Instruct-v0.1 etc. provider_model = gemini-2.0-flash
provider_server_address = # Typically ignored or can be left blank when is_local = False for most APIs provider_server_address = 127.0.0.1:5000 # doesn't matter
# ... other settings ...
``` ```
*Warning:* Make sure there are no trailing spaces in the `config.ini` values. Warning: Make sure there is not trailing space in the config.
**List of API Providers** Export your API key: `export <<PROVIDER>>_API_KEY="xxx"`
| Provider | `provider_name` | Local? | Description | API Key Link (Examples) | Example: export `TOGETHER_API_KEY="xxxxx"`
|--------------|-----------------|--------|---------------------------------------------------|---------------------------------------------|
| OpenAI | `openai` | No | Use ChatGPT models via OpenAI's API. | [platform.openai.com/signup](https://platform.openai.com/signup) |
| Google Gemini| `google` | No | Use Google Gemini models via Google AI Studio. | [aistudio.google.com/keys](https://aistudio.google.com/keys) |
| Deepseek | `deepseek` | No | Use Deepseek models via their API. | [platform.deepseek.com](https://platform.deepseek.com) |
| Hugging Face | `huggingface` | No | Use models from Hugging Face Inference API. | [huggingface.co/settings/tokens](https://huggingface.co/settings/tokens) |
| TogetherAI | `togetherAI` | No | Use various open-source models via TogetherAI API.| [api.together.ai/settings/api-keys](https://api.together.ai/settings/api-keys) |
| OpenRouter | `openrouter` | No | Use OpenRouter Models| [https://openrouter.ai/](https://openrouter.ai/) |
*Note:* **List of API providers**
* We advise against using `gpt-4o` or other OpenAI models for complex web browsing and task planning as current prompt optimizations are geared towards models like Deepseek.
* Coding/bash tasks might encounter issues with Gemini, as it may not strictly follow formatting prompts optimized for Deepseek. | Provider | Local? | Description |
* The `provider_server_address` in `config.ini` is generally not used when `is_local = False` as the API endpoint is usually hardcoded in the respective provider's library. |-----------|--------|-----------------------------------------------------------|
| openai | Depends | Use ChatGPT API |
| deepseek-api | No | Deepseek API (non-private) |
| huggingface| No | Hugging-Face API (non-private) |
| togetherAI | No | Use together AI API (non-private) |
| google | No | Use google gemini API (non-private) |
*We advice against using gpt-4o or other closedAI models*, performance are poor for web browsing and task planning.
Please also note that coding/bash might fail with gemini, it seem to ignore our prompt for format to respect, which are optimized for deepseek r1.
Next step: [Start services and run AgenticSeek](#Start-services-and-Run) Next step: [Start services and run AgenticSeek](#Start-services-and-Run)
*See the **Known issues** section if you are having issues* *See the **Known issues** section if you are having issues*
*See the **Config** section for detailed config file explanation.* *See the **Config** section for detailled config file explanation.*
--- ---
## Start services and Run ## Start services and Run
By default AgenticSeek is run fully in docker. Activate your python env if needed.
```sh
**Option 1:** Run in Docker, use web interface: source agentic_seek_env/bin/activate
```
Start required services. This will start all services from the docker-compose.yml, including: Start required services. This will start all services from the docker-compose.yml, including:
- searxng - searxng
- redis (required by searxng) - redis (required by searxng)
- frontend - frontend
- backend (if using `full` when using the web interface)
```sh ```sh
./start_services.sh full # MacOS sudo ./start_services.sh # MacOS
start start_services.cmd full # Window start ./start_services.cmd # Window
``` ```
**Warning:** This step will download and load all Docker images, which may take up to 30 minutes. After starting the services, please wait until the backend service is fully running (you should see **backend: "GET /health HTTP/1.1" 200 OK** in the log) before sending any messages. The backend services might take 5 minute to start on first run. **Options 1:** Run with the CLI interface.
```sh
python3 cli.py
```
We advice you set `headless_browser` to False in the config.ini for CLI mode.
**Options 2:** Run with the Web interface.
Start the backend.
```sh
python3 api.py
```
Go to `http://localhost:3000/` and you should see the web interface. Go to `http://localhost:3000/` and you should see the web interface.
*Troubleshooting service start:* If these scripts fail, ensure Docker Engine is running and Docker Compose (V2, `docker compose`) is correctly installed. Check the output in the terminal for error messages. See [FAQ: Help! I get an error when running AgenticSeek or its scripts.](#faq-troubleshooting)
**Option 2:** CLI mode:
To run with CLI interface you would have to install package on host:
```sh
./install.sh
./install.bat # windows
```
Then you must change the SEARXNG_BASE_URL in `config.ini` to:
```sh
SEARXNG_BASE_URL="http://localhost:8080"
```
Start required services. This will start some services from the docker-compose.yml, including:
- searxng
- redis (required by searxng)
- frontend
```sh
./start_services.sh # MacOS
start start_services.cmd # Window
```
Run: uv run: `uv run python -m ensurepip` to ensure uv has pip enabled.
Use the CLI: `uv run cli.py`
--- ---
## Usage ## Usage
Make sure the services are up and running with `./start_services.sh full` and go to `localhost:3000` for web interface. Make sure the services are up and running with `./start_services.sh` and run the AgenticSeek with `python3 cli.py` for CLI mode or `python3 api.py` then go to `localhost:3000` for web interface.
You can also use speech to text by setting `listen = True` in the config. Only for CLI mode. You can also use speech to text by setting `listen = True` in the config. Only for CLI mode.
@@ -369,7 +314,7 @@ Clone the repository and enter the `server/`folder.
```sh ```sh
git clone --depth 1 https://github.com/Fosowl/agenticSeek.git git clone --depth 1 https://github.com/Fosowl/agenticSeek.git
cd agenticSeek/llm_server/ cd agenticSeek/server/
``` ```
Install server specific requirements: Install server specific requirements:
@@ -397,7 +342,7 @@ Set the `provider_server_address` to the ip address of the machine that will run
is_local = False is_local = False
provider_name = server provider_name = server
provider_model = deepseek-r1:70b provider_model = deepseek-r1:70b
provider_server_address = http://x.x.x.x:3333 provider_server_address = x.x.x.x:3333
``` ```
@@ -407,8 +352,6 @@ Next step: [Start services and run AgenticSeek](#Start-services-and-Run)
## Speech to Text ## Speech to Text
Warning: speech to text only work in CLI mode at the moment.
Please note that currently speech to text only work in english. Please note that currently speech to text only work in english.
The speech-to-text functionality is disabled by default. To enable it, set the listen option to True in the config.ini file: The speech-to-text functionality is disabled by default. To enable it, set the listen option to True in the config.ini file:
@@ -442,158 +385,88 @@ Example config:
is_local = True is_local = True
provider_name = ollama provider_name = ollama
provider_model = deepseek-r1:32b provider_model = deepseek-r1:32b
provider_server_address = http://127.0.0.1:11434 # Example for Ollama; use http://127.0.0.1:1234 for LM-Studio provider_server_address = 127.0.0.1:11434
agent_name = Friday agent_name = Friday
recover_last_session = False recover_last_session = False
save_session = False save_session = False
speak = False speak = False
listen = False listen = False
work_dir = /Users/mlg/Documents/ai_folder
jarvis_personality = False jarvis_personality = False
languages = en zh # List of languages for TTS and potentially routing. languages = en zh
[BROWSER] [BROWSER]
headless_browser = False headless_browser = False
stealth_mode = False stealth_mode = False
``` ```
**Explanation of `config.ini` Settings**: **Explanation**:
* **`[MAIN]` Section:** - is_local -> Runs the agent locally (True) or on a remote server (False).
* `is_local`: `True` if using a local LLM provider (Ollama, LM-Studio, local OpenAI-compatible server) or the self-hosted server option. `False` if using a cloud-based API (OpenAI, Google, etc.).
* `provider_name`: Specifies the LLM provider.
* Local options: `ollama`, `lm-studio`, `openai` (for local OpenAI-compatible servers), `server` (for the self-hosted server setup).
* API options: `openai`, `google`, `deepseek`, `huggingface`, `togetherAI`.
* `provider_model`: The specific model name or ID for the chosen provider (e.g., `deepseekcoder:6.7b` for Ollama, `gpt-3.5-turbo` for OpenAI API, `mistralai/Mixtral-8x7B-Instruct-v0.1` for TogetherAI).
* `provider_server_address`: The address of your LLM provider.
* For local providers: e.g., `http://127.0.0.1:11434` for Ollama, `http://127.0.0.1:1234` for LM-Studio.
* For the `server` provider type: The address of your self-hosted LLM server (e.g., `http://your_server_ip:3333`).
* For cloud APIs (`is_local = False`): This is often ignored or can be left blank, as the API endpoint is usually handled by the client library.
* `agent_name`: Name of the AI assistant (e.g., Friday). Used as a trigger word for speech-to-text if enabled.
* `recover_last_session`: `True` to attempt to restore the previous session's state, `False` to start fresh.
* `save_session`: `True` to save the current session's state for potential recovery, `False` otherwise.
* `speak`: `True` to enable text-to-speech voice output, `False` to disable.
* `listen`: `True` to enable speech-to-text voice input (CLI mode only), `False` to disable.
* `work_dir`: **Crucial:** The directory where AgenticSeek will read/write files. **Ensure this path is valid and accessible on your system.**
* `jarvis_personality`: `True` to use a more "Jarvis-like" system prompt (experimental), `False` for the standard prompt.
* `languages`: A comma-separated list of languages (e.g., `en, zh, fr`). Used for TTS voice selection (defaults to the first) and can assist the LLM router. Avoid too many or very similar languages for router efficiency.
* **`[BROWSER]` Section:**
* `headless_browser`: `True` to run the automated browser without a visible window (recommended for web interface or non-interactive use). `False` to show the browser window (useful for CLI mode or debugging).
* `stealth_mode`: `True` to enable measures to make browser automation harder to detect. May require manual installation of browser extensions like anticaptcha.
- provider_name -> The provider to use (one of: `ollama`, `server`, `lm-studio`, `deepseek-api`)
This section summarizes the supported LLM provider types. Configure them in `config.ini`. - provider_model -> The model used, e.g., deepseek-r1:32b.
**Local Providers (Run on Your Own Hardware):** - provider_server_address -> Server address, e.g., 127.0.0.1:11434 for local. Set to anything for non-local API.
| Provider Name in `config.ini` | `is_local` | Description | Setup Section | - agent_name -> Name of the agent, e.g., Friday. Used as a trigger word for TTS.
|-------------------------------|------------|-----------------------------------------------------------------------------|------------------------------------------------------------------|
| `ollama` | `True` | Use Ollama to serve local LLMs. | [Setup for running LLM locally](#setup-for-running-llm-locally-on-your-machine) |
| `lm-studio` | `True` | Use LM-Studio to serve local LLMs. | [Setup for running LLM locally](#setup-for-running-llm-locally-on-your-machine) |
| `openai` (for local server) | `True` | Connect to a local server that exposes an OpenAI-compatible API (e.g., llama.cpp). | [Setup for running LLM locally](#setup-for-running-llm-locally-on-your-machine) |
| `server` | `False` | Connect to the AgenticSeek self-hosted LLM server running on another machine. | [Setup to run the LLM on your own server](#setup-to-run-the-llm-on-your-own-server) |
**API Providers (Cloud-Based):** - recover_last_session -> Restarts from last session (True) or not (False).
| Provider Name in `config.ini` | `is_local` | Description | Setup Section | - save_session -> Saves session data (True) or not (False).
|-------------------------------|------------|--------------------------------------------------|-----------------------------------------------------|
| `openai` | `False` | Use OpenAI's official API (e.g., GPT-3.5, GPT-4). | [Setup to run with an API](#setup-to-run-with-an-api) |
| `google` | `False` | Use Google's Gemini models via API. | [Setup to run with an API](#setup-to-run-with-an-api) |
| `deepseek` | `False` | Use Deepseek's official API. | [Setup to run with an API](#setup-to-run-with-an-api) |
| `huggingface` | `False` | Use Hugging Face Inference API. | [Setup to run with an API](#setup-to-run-with-an-api) |
| `togetherAI` | `False` | Use TogetherAI's API for various open models. | [Setup to run with an API](#setup-to-run-with-an-api) |
--- - speak -> Enables voice output (True) or not (False).
## Troubleshooting
If you encounter issues, this section provides guidance. - listen -> listen to voice input (True) or not (False).
# Known Issues - work_dir -> Folder the AI will have access to. eg: /Users/user/Documents/.
## ChromeDriver Issues - jarvis_personality -> Uses a JARVIS-like personality (True) or not (False). This simply change the prompt file.
**Error Example:** `SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version XXX` - languages -> The list of supported language, needed for the llm router to work properly, avoid putting too many or too similar languages.
### Root Cause - headless_browser -> Runs browser without a visible window (True) or not (False).
ChromeDriver version incompatibility occurs when:
1. Your installed ChromeDriver version doesn't match your Chrome browser version
2. In Docker environments, `undetected_chromedriver` may download its own ChromeDriver version, bypassing the mounted binary
### Solution Steps - stealth_mode -> Make bot detector time harder. Only downside is you have to manually install the anticaptcha extension.
#### 1. Check Your Chrome Version - languages -> List of supported languages. Required for agent routing system. The longer the languages list the more model will be downloaded.
Open Google Chrome → `Settings > About Chrome` to find your version (e.g., "Version 134.0.6998.88")
#### 2. Download Matching ChromeDriver ## Providers
**For Chrome 115 and newer:** Use the [Chrome for Testing API](https://googlechromelabs.github.io/chrome-for-testing/) The table below show the available providers:
- Visit the Chrome for Testing availability dashboard
- Find your Chrome version or the closest available match
- Download the ChromeDriver for your OS (Linux64 for Docker environments)
**For older Chrome versions:** Use the [legacy ChromeDriver downloads](https://chromedriver.chromium.org/downloads) | Provider | Local? | Description |
|-----------|--------|-----------------------------------------------------------|
| ollama | Yes | Run LLMs locally with ease using ollama as a LLM provider |
| server | Yes | Host the model on another machine, run your local machine |
| lm-studio | Yes | Run LLM locally with LM studio (`lm-studio`) |
| openai | Depends | Use ChatGPT API (non-private) or openai compatible API |
| deepseek-api | No | Deepseek API (non-private) |
| huggingface| No | Hugging-Face API (non-private) |
| togetherAI | No | Use together AI API (non-private) |
| google | No | Use google gemini API (non-private) |
![Download ChromeDriver from Chrome for Testing](./media/chromedriver_readme.png) To select a provider change the config.ini:
#### 3. Install ChromeDriver (Choose One Method)
**Method A: Project Root Directory (Recommended for Docker)**
```bash
# Place the downloaded chromedriver binary in your project root
cp path/to/downloaded/chromedriver ./chromedriver
chmod +x ./chromedriver # Make executable on Linux/macOS
``` ```
is_local = True
**Method B: System PATH** provider_name = ollama
```bash provider_model = deepseek-r1:32b
# Linux/macOS provider_server_address = 127.0.0.1:5000
sudo mv chromedriver /usr/local/bin/
sudo chmod +x /usr/local/bin/chromedriver
# Windows: Place chromedriver.exe in a folder that's in your PATH
``` ```
`is_local`: should be True for any locally running LLM, otherwise False.
#### 4. Verify Installation `provider_name`: Select the provider to use by it's name, see the provider list above.
```bash
# Test the ChromeDriver version
./chromedriver --version
# OR if in PATH:
chromedriver --version
```
### Docker-Specific Notes `provider_model`: Set the model to use by the agent.
⚠️ **Important for Docker Users:** `provider_server_address`: can be set to anything if you are not using the server provider.
- The Docker volume mount approach may not work with stealth mode (`undetected_chromedriver`)
- **Solution**: Place ChromeDriver in the project root directory as `./chromedriver`
- The application will automatically detect and use this binary
- You should see: `"Using ChromeDriver from project root: ./chromedriver"` in the logs
### Troubleshooting Tips # Known issues
1. **Still getting version mismatch?** ## Chromedriver Issues
- Verify the ChromeDriver is executable: `ls -la ./chromedriver`
- Check the ChromeDriver version: `./chromedriver --version`
- Ensure it matches your Chrome browser version
2. **Docker container issues?** **Known error #1:** *chromedriver mismatch*
- Check backend logs: `docker logs backend`
- Look for the message: `"Using ChromeDriver from project root"`
- If not found, verify the file exists and is executable
3. **Chrome for Testing versions**
- Use the exact version match when possible
- For version 134.0.6998.88, use ChromeDriver 134.0.6998.165 (closest available)
- Major version numbers must match (134 = 134)
### Version Compatibility Matrix
| Chrome Version | ChromeDriver Version | Status |
|----------------|---------------------|---------|
| 134.0.6998.x | 134.0.6998.165 | ✅ Works |
| 133.0.6943.x | 133.0.6943.141 | ✅ Works |
| 132.0.6834.x | 132.0.6834.159 | ✅ Works |
*For the latest compatibility, check the [Chrome for Testing dashboard](https://googlechromelabs.github.io/chrome-for-testing/)*
`Exception: Failed to initialize browser: Message: session not created: This version of ChromeDriver only supports Chrome version 113 `Exception: Failed to initialize browser: Message: session not created: This version of ChromeDriver only supports Chrome version 113
Current browser version is 134.0.6998.89 with binary path` Current browser version is 134.0.6998.89 with binary path`
@@ -617,28 +490,23 @@ If this section is incomplete please raise an issue.
## connection adapters Issues ## connection adapters Issues
``` ```
Exception: Provider lm-studio failed: HTTP request failed: No connection adapters were found for '127.0.0.1:1234/v1/chat/completions'` (Note: port may vary) Exception: Provider lm-studio failed: HTTP request failed: No connection adapters were found for '127.0.0.1:11434/v1/chat/completions'
``` ```
* **Cause:** The `provider_server_address` in `config.ini` for `lm-studio` (or other similar local OpenAI-compatible servers) is missing the `http://` prefix or is pointing to the wrong port. Make sure you have `http://` in front of the provider IP address :
* **Solution:**
* Ensure the address includes `http://`. LM-Studio typically defaults to `http://127.0.0.1:1234`.
* Correct `config.ini`: `provider_server_address = http://127.0.0.1:1234` (or your actual LM-Studio server port).
## SearxNG Base URL Not Provided `provider_server_address = http://127.0.0.1:11434`
## SearxNG base URL must be provided
``` ```
raise ValueError("SearxNG base URL must be provided either as an argument or via the SEARXNG_BASE_URL environment variable.") raise ValueError("SearxNG base URL must be provided either as an argument or via the SEARXNG_BASE_URL environment variable.")
ValueError: SearxNG base URL must be provided either as an argument or via the SEARXNG_BASE_URL environment variable.` ValueError: SearxNG base URL must be provided either as an argument or via the SEARXNG_BASE_URL environment variable.
``` ```
This might arise if you are running the CLI mode with the wrong base url for searxng. Maybe you didn't move `.env.example` as `.env` ? You can also export SEARXNG_BASE_URL:
The SEARXNG_BASE_URL should be depending on whenever you run in docker or on host: `export SEARXNG_BASE_URL="http://127.0.0.1:8080"`
**Run on host**: `SEARXNG_BASE_URL="http://localhost:8080"`
**Run fully in docker (web interface)**: `SEARXNG_BASE_URL="http://searxng:8080"`
## FAQ ## FAQ
@@ -649,9 +517,13 @@ The SEARXNG_BASE_URL should be depending on whenever you run in docker or on hos
| 7B | 8GB Vram | ⚠️ Not recommended. Performance is poor, frequent hallucinations, and planner agents will likely fail. | | 7B | 8GB Vram | ⚠️ Not recommended. Performance is poor, frequent hallucinations, and planner agents will likely fail. |
| 14B | 12 GB VRAM (e.g. RTX 3060) | ✅ Usable for simple tasks. May struggle with web browsing and planning tasks. | | 14B | 12 GB VRAM (e.g. RTX 3060) | ✅ Usable for simple tasks. May struggle with web browsing and planning tasks. |
| 32B | 24+ GB VRAM (e.g. RTX 4090) | 🚀 Success with most tasks, might still struggle with task planning | | 32B | 24+ GB VRAM (e.g. RTX 4090) | 🚀 Success with most tasks, might still struggle with task planning |
| 70B+ | 48+ GB Vram | 💪 Excellent. Recommended for advanced use cases. | | 70B+ | 48+ GB Vram (eg. mac studio) | 💪 Excellent. Recommended for advanced use cases. |
**Q: I get an error what do I do?** **Q: Why Deepseek R1 over other models?**
Deepseek R1 excels at reasoning and tool use for its size. We think its a solid fit for our needs other models work fine, but Deepseek is our primary pick.
**Q: I get an error running `cli.py`. What do I do?**
Ensure local is running (`ollama serve`), your `config.ini` matches your provider, and dependencies are installed. If none work feel free to raise an issue. Ensure local is running (`ollama serve`), your `config.ini` matches your provider, and dependencies are installed. If none work feel free to raise an issue.
@@ -661,41 +533,22 @@ Yes with Ollama, lm-studio or server providers, all speech to text, LLM and text
**Q: Why should I use AgenticSeek when I have Manus?** **Q: Why should I use AgenticSeek when I have Manus?**
This started as Side-Project we did out of interest about AI agents. Whats special about it is that we want to use local model and avoid APIs.
We draw inspiration from Jarvis and Friday (Iron man movies) to make it "cool" but for functionnality we take more inspiration from Manus, because that's what people want in the first place: a local manus alternative.
Unlike Manus, AgenticSeek prioritizes independence from external systems, giving you more control, privacy and avoid api cost. Unlike Manus, AgenticSeek prioritizes independence from external systems, giving you more control, privacy and avoid api cost.
**Q: Who is behind the project ?**
The project was created by me, along with two friends who serve as maintainers and contributors from the open-source community on GitHub. Were just a group of passionate individuals, not a startup or affiliated with any organization.
Any AgenticSeek account on X other than my personal account (https://x.com/Martin993886460) is an impersonation.
## Contribute ## Contribute
Were looking for developers to improve AgenticSeek! Check out open issues or discussion. Were looking for developers to improve AgenticSeek! Check out open issues or discussion.
[Contribution guide](./docs/CONTRIBUTING.md) [Contribution guide](./docs/CONTRIBUTING.md)
[![Star History Chart](https://api.star-history.com/svg?repos=Fosowl/agenticSeek&type=Date)](https://www.star-history.com/#Fosowl/agenticSeek&Date)
## Sponsors:
Want to level up AgenticSeek capabilities with features like flight search, trip planning, or snagging the best shopping deals? Consider crafting a custom tool with SerpApi to unlock more Jarvis-like capabilities. With SerpApi, you can turbocharge your agent for specialized tasks while staying in full control.
<a href="https://serpapi.com/"><img src="./media/banners/sponsor_banner_serpapi.png" height="350" alt="SerpApi Banner" ></a>
See [Contributing.md](./docs/CONTRIBUTING.md) to learn how to integrate custom tools!
### **Patron sponsor**:
- [tatra-labs](https://github.com/tatra-labs)
## Maintainers: ## Maintainers:
> [Fosowl](https://github.com/Fosowl) | Paris Time > [Fosowl](https://github.com/Fosowl) | Paris Time | (Sometime busy)
> [antoineVIVIES](https://github.com/antoineVIVIES) | Taipei Time > [https://github.com/antoineVIVIES](antoineVIVIES) | Taipei Time | (Often busy)
## Special Thanks: > [steveh8758](https://github.com/steveh8758) | Taipei Time | (Always busy)
> [tcsenpai](https://github.com/tcsenpai) and [plitc](https://github.com/plitc) For helping with backend dockerization
[![Star History Chart](https://api.star-history.com/svg?repos=Fosowl/agenticSeek&type=Date)](https://www.star-history.com/#Fosowl/agenticSeek&Date)
+335 -451
View File
File diff suppressed because it is too large Load Diff
+320 -453
View File
File diff suppressed because it is too large Load Diff
-682
View File
@@ -1,682 +0,0 @@
# AgenticSeek: Una Alternativa Privada y Local a Manus
<p align="center">
<img align="center" src="./media/agentic_seek_logo.png" width="300" height="300" alt="Agentic Seek Logo">
<p>
English | [中文](./README_CHS.md) | [繁體中文](./README_CHT.md) | [Français](./README_FR.md) | [日本語](./README_JP.md) | [Português (Brasil)](./README_PTBR.md) | [Español](./README_ES.md)
*Un asistente de IA con capacidad de voz que es una **alternativa 100% local a Manus AI**, navega autónomamente por la web, escribe código y planifica tareas manteniendo todos los datos en tu dispositivo. Diseñado para modelos de razonamiento local, funciona completamente en tu hardware, garantizando privacidad total y cero dependencia de la nube.*
[![Visitar AgenticSeek](https://img.shields.io/static/v1?label=Website&message=AgenticSeek&color=blue&style=flat-square)](https://fosowl.github.io/agenticSeek.html) ![License](https://img.shields.io/badge/license-GPL--3.0-green) [![Discord](https://img.shields.io/badge/Discord-Join%20Us-7289DA?logo=discord&logoColor=white)](https://discord.gg/8hGDaME3TC) [![Twitter](https://img.shields.io/twitter/url/https/twitter.com/fosowl.svg?style=social&label=Update%20%40Fosowl)](https://x.com/Martin993886460) [![GitHub stars](https://img.shields.io/github/stars/Fosowl/agenticSeek?style=social)](https://github.com/Fosowl/agenticSeek/stargazers)
### ¿Por qué AgenticSeek?
* 🔒 Totalmente Local & Privado - Todo funciona en tu máquina, sin nube, sin compartir datos. Tus archivos, conversaciones y búsquedas permanecen privados.
* 🌐 Navegación Web Inteligente - AgenticSeek puede navegar por Internet de forma autónoma: buscar, leer, extraer información, completar formularios web, todo sin manos.
* 💻 Asistente de Programación Autónomo - ¿Necesitas código? Puede escribir, depurar y ejecutar programas en Python, C, Go, Java y más, sin supervisión.
* 🧠 Selección Inteligente de Agentes - Tú pides, él elige automáticamente el mejor agente para la tarea. Como tener un equipo de expertos siempre disponible.
* 📋 Planifica y Ejecuta Tareas Complejas - Desde planificación de viajes hasta proyectos complejos, puede dividir grandes tareas en pasos y completarlos utilizando múltiples agentes de IA.
* 🎙️ Compatibilidad con Voz - Voz limpia, rápida y futurista con reconocimiento de voz, permitiéndote conversar como si fuera tu IA personal de una película de ciencia ficción. (En desarrollo)
### **Demo**
> *¿Puedes buscar el proyecto agenticSeek, aprender qué habilidades se necesitan, luego abrir CV_candidates.zip y decirme cuáles coinciden mejor con el proyecto?*
https://github.com/user-attachments/assets/b8ca60e9-7b3b-4533-840e-08f9ac426316
Descargo de responsabilidad: Esta demostración y todos los archivos que aparecen (ej: CV_candidates.zip) son completamente ficticios. No somos una corporación, buscamos colaboradores de código abierto, no candidatos.
> 🛠⚠️ **Trabajo Activo en Progreso**
> 🙏 Este proyecto comenzó como un proyecto paralelo y no tiene hoja de ruta ni financiación. Creció mucho más allá de lo esperado al aparecer en GitHub Trending. Las contribuciones, comentarios y paciencia son profundamente apreciados.
## Prerrequisitos
Antes de comenzar, asegúrate de tener instalado:
* **Git:** Para clonar el repositorio. [Descargar Git](https://git-scm.com/downloads)
* **Python 3.10.x:** Se recomienda encarecidamente Python 3.10.x. Otras versiones pueden causar errores de dependencia. [Descargar Python 3.10](https://www.python.org/downloads/release/python-3100/) (selecciona la versión 3.10.x).
* **Docker Engine & Docker Compose:** Para ejecutar servicios empaquetados como SearxNG.
* Instalar Docker Desktop (incluye Docker Compose V2): [Windows](https://docs.docker.com/desktop/install/windows-install/) | [Mac](https://docs.docker.com/desktop/install/mac-install/) | [Linux](https://docs.docker.com/desktop/install/linux-install/)
* O instalar Docker Engine y Docker Compose por separado en Linux: [Docker Engine](https://docs.docker.com/engine/install/) | [Docker Compose](https://docs.docker.com/compose/install/) (asegúrate de instalar Compose V2, por ejemplo `sudo apt-get install docker-compose-plugin`).
### 1. **Clonar el repositorio y configurar**
```sh
git clone https://github.com/Fosowl/agenticSeek.git
cd agenticSeek
mv .env.example .env
```
### 2. Modificar el contenido del archivo .env
```sh
SEARXNG_BASE_URL="http://searxng:8080" # Si ejecutas en modo CLI en el host, usa http://127.0.0.1:8080
REDIS_BASE_URL="redis://redis:6379/0"
WORK_DIR="/Users/mlg/Documents/workspace_for_ai"
OLLAMA_PORT="11434"
LM_STUDIO_PORT="1234"
CUSTOM_ADDITIONAL_LLM_PORT="11435"
OPENAI_API_KEY='optional'
DEEPSEEK_API_KEY='optional'
OPENROUTER_API_KEY='optional'
TOGETHER_API_KEY='optional'
GOOGLE_API_KEY='optional'
ANTHROPIC_API_KEY='optional'
```
Actualiza el archivo `.env` según sea necesario:
- **SEARXNG_BASE_URL**: Mantener sin cambios a menos que ejecutes en modo CLI en el host.
- **REDIS_BASE_URL**: Mantener sin cambios
- **WORK_DIR**: Ruta al directorio de trabajo local. AgenticSeek podrá leer e interactuar con estos archivos.
- **OLLAMA_PORT**: Número de puerto para el servicio Ollama.
- **LM_STUDIO_PORT**: Número de puerto para el servicio LM Studio.
- **CUSTOM_ADDITIONAL_LLM_PORT**: Puerto para cualquier servicio LLM adicional personalizado.
**Las claves API son completamente opcionales para quienes optan por ejecutar LLM localmente, que es el objetivo principal de este proyecto. Déjalas en blanco si tienes hardware suficiente.**
### 3. **Iniciar Docker**
Asegúrate de que Docker esté instalado y ejecutándose en tu sistema. Puedes iniciar Docker con los siguientes comandos:
- **Linux/macOS:**
Abre una terminal y ejecuta:
```sh
sudo systemctl start docker
```
O inicia Docker Desktop desde el menú de aplicaciones, si está instalado.
- **Windows:**
Inicia Docker Desktop desde el menú Inicio.
Puedes verificar si Docker se está ejecutando ejecutando:
```sh
docker info
```
Si ves información sobre tu instalación de Docker, está funcionando correctamente.
Consulta la [Lista de proveedores locales](#lista-de-proveedores-locales) a continuación para obtener un resumen.
Siguiente paso: [Ejecutar AgenticSeek localmente](#iniciar-servicios-y-ejecutar)
*Si tienes problemas, consulta la sección [Solución de problemas](#solución-de-problemas).*
*Si tu hardware no puede ejecutar LLM localmente, consulta [Configuración para ejecutar con una API](#configuración-para-ejecutar-con-una-api).*
*Para explicaciones detalladas de `config.ini`, consulta la [sección Configuración](#configuración).*
---
## Configuración para ejecutar LLM localmente en tu máquina
**Requisitos de hardware:**
Para ejecutar LLM localmente, necesitarás hardware suficiente. Como mínimo, se requiere una GPU capaz de ejecutar Magistral, Qwen o Deepseek 14B. Consulta el FAQ para recomendaciones detalladas de modelo/rendimiento.
**Configura tu proveedor local**
Inicia tu proveedor local, por ejemplo con ollama:
```sh
ollama serve
```
Consulta la lista de proveedores locales admitidos a continuación.
**Actualizar config.ini**
Cambia el archivo config.ini para establecer provider_name en un proveedor admitido y provider_model en un LLM admitido por tu proveedor. Recomendamos modelos de razonamiento como *Magistral* o *Deepseek*.
Consulta el **FAQ** al final del README para el hardware necesario.
```sh
[MAIN]
is_local = True # Ya sea que ejecutes localmente o con un proveedor remoto.
provider_name = ollama # o lm-studio, openai, etc.
provider_model = deepseek-r1:14b # elige un modelo compatible con tu hardware
provider_server_address = 127.0.0.1:11434
agent_name = Jarvis # el nombre de tu IA
recover_last_session = True # recuperar sesión anterior
save_session = True # recordar sesión actual
speak = False # texto a voz
listen = False # voz a texto, solo para CLI, experimental
jarvis_personality = False # usar personalidad más "Jarvis" (experimental)
languages = en zh # Lista de idiomas, TTS usará el primero de la lista por defecto
[BROWSER]
headless_browser = True # mantener sin cambios a menos que uses CLI en el host.
stealth_mode = True # Usa selenium indetectable para reducir la detección del navegador
```
**Advertencia**:
- El formato del archivo `config.ini` no admite comentarios.
No copies y pegues la configuración de ejemplo directamente, ya que los comentarios causarán errores. En su lugar, modifica manualmente el archivo `config.ini` con tu configuración deseada, sin comentarios.
- *NO* establezcas provider_name como `openai` si estás usando LM-studio para ejecutar LLM. Úsalo como `lm-studio`.
- Algunos proveedores (ej: lm-studio) requieren `http://` antes de la IP. Ejemplo: `http://127.0.0.1:1234`
**Lista de proveedores locales**
| Proveedor | ¿Local? | Descripción |
|-----------|--------|-----------------------------------------------------------|
| ollama | Sí | Ejecuta LLM localmente fácilmente usando ollama |
| lm-studio | Sí | Ejecuta LLM localmente con LM studio (establecer `provider_name` = `lm-studio`)|
| openai | Sí | Usa API compatible con openai (ej: servidor llama.cpp) |
Siguiente paso: [Iniciar servicios y ejecutar AgenticSeek](#iniciar-servicios-y-ejecutar)
*Si tienes problemas, consulta la sección [Solución de problemas](#solución-de-problemas).*
*Si tu hardware no puede ejecutar LLM localmente, consulta [Configuración para ejecutar con una API](#configuración-para-ejecutar-con-una-api).*
*Para explicaciones detalladas de `config.ini`, consulta la [sección Configuración](#configuración).*
## Configuración para ejecutar con una API
Esta configuración utiliza proveedores de LLM externos basados en la nube. Necesitarás obtener claves API del servicio elegido.
**1. Elige un proveedor de API y obtén una clave API:**
Consulta la [Lista de proveedores de API](#lista-de-proveedores-de-api) a continuación. Visita sus sitios web para registrarte y obtener claves API.
**2. Establece tu clave API como variable de entorno:**
* **Linux/macOS:**
Abre una terminal y usa el comando `export`. Es mejor agregarlo al archivo de configuración de tu shell (ej: `~/.bashrc`, `~/.zshrc`) para que sea persistente.
```sh
export PROVIDER_API_KEY="your_api_key_here"
# Reemplaza PROVIDER_API_KEY con el nombre de variable específico, ej: OPENAI_API_KEY, GOOGLE_API_KEY
```
Ejemplo de TogetherAI:
```sh
export TOGETHER_API_KEY="xxxxxxxxxxxxxxxxxxxxxx"
```
* **Windows:**
* **Símbolo del sistema (temporal para la sesión actual):**
```cmd
set PROVIDER_API_KEY=your_api_key_here
```
* **PowerShell (temporal para la sesión actual):**
```powershell
$env:PROVIDER_API_KEY="your_api_key_here"
```
* **Permanente:** Busca "variables de entorno" en la barra de búsqueda de Windows, haz clic en "Editar las variables de entorno del sistema", luego en el botón "Variables de entorno...". Agrega una nueva variable de usuario con el nombre apropiado (ej: `OPENAI_API_KEY`) y tu clave como valor.
*(Para más detalles, consulta el FAQ: [¿Cómo configuro una clave API?](#cómo-configuro-una-clave-api)).*
**3. Actualiza `config.ini`:**
```ini
[MAIN]
is_local = False
provider_name = openai # o google, deepseek, togetherAI, huggingface
provider_model = gpt-3.5-turbo # o gemini-1.5-flash, deepseek-chat, mistralai/Mixtral-8x7B-Instruct-v0.1, etc.
provider_server_address = # Cuando is_local = False, generalmente se ignora o puede dejarse en blanco para la mayoría de las API
# ... otras configuraciones ...
```
*Advertencia:* Asegúrate de que no haya espacios al final de los valores en config.
**Lista de proveedores de API**
| Proveedor | `provider_name` | ¿Local? | Descripción | Enlace de clave API (ejemplo) |
|--------------|-----------------|--------|---------------------------------------------------|---------------------------------------------|
| OpenAI | `openai` | No | Usa modelos ChatGPT a través de la API de OpenAI. | [platform.openai.com/signup](https://platform.openai.com/signup) |
| Google Gemini| `google` | No | Usa modelos Google Gemini a través de Google AI Studio. | [aistudio.google.com/keys](https://aistudio.google.com/keys) |
| Deepseek | `deepseek` | No | Usa modelos Deepseek a través de su API. | [platform.deepseek.com](https://platform.deepseek.com) |
| Hugging Face | `huggingface` | No | Usa modelos del Hugging Face Inference API. | [huggingface.co/settings/tokens](https://huggingface.co/settings/tokens) |
| TogetherAI | `togetherAI` | No | Usa varios modelos de código abierto a través de la API de TogetherAI.| [api.together.ai/settings/api-keys](https://api.together.ai/settings/api-keys) |
*Nota:*
* No recomendamos usar `gpt-4o` u otros modelos OpenAI para navegación web compleja y planificación de tareas, ya que la optimización actual de prompts está dirigida a modelos como Deepseek.
* Las tareas de codificación/bash pueden fallar con Gemini, ya que tiende a ignorar nuestro formato de prompt optimizado para Deepseek r1.
* Cuando `is_local = False`, `provider_server_address` en `config.ini` generalmente no se usa, ya que los endpoints de API suelen estar codificados en las bibliotecas del proveedor correspondiente.
Siguiente paso: [Iniciar servicios y ejecutar AgenticSeek](#iniciar-servicios-y-ejecutar)
*Si tienes problemas, consulta la sección **Problemas conocidos***
*Para explicaciones detalladas del archivo de configuración, consulta la **sección Configuración**.*
---
## Iniciar servicios y ejecutar
Por defecto, AgenticSeek se ejecuta completamente en Docker.
**Opción 1:** Ejecutar en Docker con interfaz web:
Inicia los servicios necesarios. Esto iniciará todos los servicios del docker-compose.yml, incluyendo:
- searxng
- redis (requerido para searxng)
- frontend
- backend (si usas `full` para la interfaz web)
```sh
./start_services.sh full # MacOS
start start_services.cmd full # Windows
```
**Advertencia:** Este paso descargará y cargará todas las imágenes de Docker, lo que puede tardar hasta 30 minutos. Después de iniciar los servicios, espera hasta que el servicio backend esté completamente ejecutándose (deberías ver **backend: "GET /health HTTP/1.1" 200 OK** en el registro) antes de enviar cualquier mensaje. En la primera ejecución, el servicio backend puede tardar 5 minutos en iniciarse.
Ve a `http://localhost:3000/` y deberías ver la interfaz web.
*Solución de problemas de inicio de servicios:* Si estos scripts fallan, asegúrate de que Docker Engine esté ejecutándose y que Docker Compose (V2, `docker compose`) esté correctamente instalado. Revisa los mensajes de error en la salida de la terminal. Consulta [FAQ: ¡Ayuda! Obtengo errores al ejecutar AgenticSeek o sus scripts.](#faq-solución-de-problemas)
**Opción 2:** Modo CLI:
Para ejecutar con la interfaz CLI, debes instalar los paquetes en el host:
```sh
./install.sh
./install.bat # windows
```
Luego debes cambiar SEARXNG_BASE_URL en `config.ini` a:
```sh
SEARXNG_BASE_URL="http://localhost:8080"
```
Inicia los servicios necesarios. Esto iniciará algunos servicios del docker-compose.yml, incluyendo:
- searxng
- redis (requerido para searxng)
- frontend
```sh
./start_services.sh # MacOS
start start_services.cmd # Windows
```
Ejecuta: uv run: `uv run python -m ensurepip` para asegurarte de que uv tenga pip habilitado.
Usa CLI: `uv run cli.py`
---
## Uso
Asegúrate de que los servicios estén ejecutándose con `./start_services.sh full` y luego ve a `localhost:3000` para la interfaz web.
También puedes usar voz a texto configurando `listen = True`. Solo para modo CLI.
Para salir, simplemente di/escribe `goodbye`.
Algunos ejemplos de uso:
> *¡Haz un juego de la serpiente en python!*
> *Busca en la web los mejores cafés en Rennes, Francia, y guarda una lista de tres con sus direcciones en rennes_cafes.txt.*
> *Escribe un programa Go para calcular el factorial de un número, guárdalo como factorial.go en tu workspace*
> *Busca en la carpeta summer_pictures todos los archivos JPG, renómbralos con la fecha de hoy y guarda la lista de archivos renombrados en photos_list.txt*
> *Busca en línea películas de ciencia ficción populares de 2024 y elige tres para ver esta noche. Guarda la lista en movie_night.txt.*
> *Busca en la web los últimos artículos de noticias de IA de 2025, selecciona tres y escribe un script Python para extraer títulos y resúmenes. Guarda el script como news_scraper.py y los resúmenes en ai_news.txt en /home/projects*
> *Viernes, busca en la web una API gratuita de precios de acciones, regístrate con supersuper7434567@gmail.com y escribe un script Python para obtener los precios diarios de Tesla usando la API, guardando los resultados en stock_prices.csv*
*Ten en cuenta que el llenado de formularios sigue siendo experimental y puede fallar.*
Después de ingresar tu consulta, AgenticSeek asignará el mejor agente para la tarea.
Como este es un prototipo inicial, el sistema de enrutamiento de agentes puede no asignar siempre el agente correcto a tu consulta.
Por lo tanto, sé muy explícito sobre lo que quieres y cómo la IA podría proceder, por ejemplo, si quieres que realice una búsqueda web, no digas:
`¿Conoces algunos buenos países para viajar solo?`
En su lugar, di:
`Realiza una búsqueda web y descubre cuáles son los mejores países para viajar solo`
---
## **Configuración para ejecutar LLM en tu propio servidor**
Si tienes una computadora potente o un servidor al que puedes acceder, pero quieres usarlo desde tu laptop, puedes optar por ejecutar el LLM en un servidor remoto usando nuestro servidor llm personalizado.
En tu "servidor" que ejecutará el modelo de IA, obtén la dirección IP
```sh
ip a | grep "inet " | grep -v 127.0.0.1 | awk '{print $2}' | cut -d/ -f1 # IP local
curl https://ipinfo.io/ip # IP pública
```
Nota: Para Windows o macOS, usa ipconfig o ifconfig para encontrar la dirección IP.
Clona el repositorio y entra en la carpeta `server/`.
```sh
git clone --depth 1 https://github.com/Fosowl/agenticSeek.git
cd agenticSeek/llm_server/
```
Instala los requisitos específicos del servidor:
```sh
pip3 install -r requirements.txt
```
Ejecuta el script del servidor.
```sh
python3 app.py --provider ollama --port 3333
```
Puedes elegir entre usar `ollama` y `llamacpp` como servicio LLM.
Ahora en tu computadora personal:
Cambia el archivo `config.ini` para establecer `provider_name` como `server` y `provider_model` como `deepseek-r1:xxb`.
Establece `provider_server_address` a la dirección IP de la máquina que ejecutará el modelo.
```sh
[MAIN]
is_local = False
provider_name = server
provider_model = deepseek-r1:70b
provider_server_address = http://x.x.x.x:3333
```
Siguiente paso: [Iniciar servicios y ejecutar AgenticSeek](#iniciar-servicios-y-ejecutar)
---
## Voz a Texto
Advertencia: La voz a texto solo funciona en modo CLI en este momento.
Ten en cuenta que la voz a texto solo funciona en inglés en este momento.
La funcionalidad de voz a texto está deshabilitada por defecto. Para habilitarla, establece listen en True en el archivo config.ini:
```
listen = True
```
Cuando está habilitado, la función de voz a texto escucha una palabra clave de activación, que es el nombre del agente, antes de procesar tu entrada. Puedes personalizar el nombre del agente actualizando el valor `agent_name` en *config.ini*:
```
agent_name = Friday
```
Para un mejor reconocimiento, recomendamos usar un nombre común en inglés como "John" o "Emma" como nombre de agente.
Una vez que veas que comienza a aparecer la transcripción, di el nombre del agente en voz alta para activarlo (ej: "Friday").
Di tu consulta claramente.
Termina tu solicitud con una frase de confirmación para indicar al sistema que proceda. Ejemplos de frases de confirmación incluyen:
```
"do it", "go ahead", "execute", "run", "start", "thanks", "would ya", "please", "okay?", "proceed", "continue", "go on", "do that", "go it", "do you understand?"
```
## Configuración
Ejemplo de configuración:
```
[MAIN]
is_local = True
provider_name = ollama
provider_model = deepseek-r1:32b
provider_server_address = http://127.0.0.1:11434 # Ejemplo de Ollama; LM-Studio usa http://127.0.0.1:1234
agent_name = Friday
recover_last_session = False
save_session = False
speak = False
listen = False
jarvis_personality = False
languages = en zh # Lista de idiomas para TTS y enrutamiento potencial.
[BROWSER]
headless_browser = False
stealth_mode = False
```
**Explicación de la configuración de `config.ini`**:
* **Sección `[MAIN]`:**
* `is_local`: `True` si usas proveedores de LLM locales (Ollama, LM-Studio, servidor local compatible con OpenAI) o la opción de servidor autoalojado. `False` si usas API basadas en la nube (OpenAI, Google, etc.).
* `provider_name`: Especifica el proveedor de LLM.
* Opciones locales: `ollama`, `lm-studio`, `openai` (para servidor local compatible con OpenAI), `server` (para configuración de servidor autoalojado).
* Opciones de API: `openai`, `google`, `deepseek`, `huggingface`, `togetherAI`.
* `provider_model`: Nombre o ID específico del modelo del proveedor seleccionado (ej: `deepseekcoder:6.7b` para Ollama, `gpt-3.5-turbo` para API de OpenAI, `mistralai/Mixtral-8x7B-Instruct-v0.1` para TogetherAI).
* `provider_server_address`: La dirección de tu proveedor de LLM.
* Para proveedores locales: ej: `http://127.0.0.1:11434` para Ollama, `http://127.0.0.1:1234` para LM-Studio.
* Para el tipo de proveedor `server`: La dirección de tu servidor LLM autoalojado (ej: `http://your_server_ip:3333`).
* Para API en la nube (`is_local = False`): Esto generalmente se ignora o puede dejarse en blanco, ya que los endpoints de API suelen ser manejados por las bibliotecas del cliente.
* `agent_name`: El nombre del asistente de IA (ej: Friday). Si está habilitado, se utiliza como palabra de activación para voz a texto.
* `recover_last_session`: `True` para intentar recuperar el estado de la sesión anterior, `False` para comenzar de nuevo.
* `save_session`: `True` para guardar el estado de la sesión actual para una posible recuperación, `False` en caso contrario.
* `speak`: `True` para habilitar la salida de voz de texto a voz, `False` para deshabilitar.
* `listen`: `True` para habilitar la entrada de voz de voz a texto (solo modo CLI), `False` para deshabilitar.
* `work_dir`: **Crítico:** El directorio donde AgenticSeek leerá/escribirá archivos. **Asegúrate de que esta ruta sea válida y accesible en tu sistema.**
* `jarvis_personality`: `True` para usar prompts del sistema más al estilo "Jarvis" (experimental), `False` para usar prompts estándar.
* `languages`: Lista de idiomas separados por comas (ej: `en, zh, fr`). Se utiliza para la selección de voz TTS (predeterminado el primero) y puede ayudar al enrutador LLM. Para evitar ineficiencias del enrutador, evita usar demasiados idiomas o idiomas muy similares.
* **Sección `[BROWSER]`:**
* `headless_browser`: `True` para ejecutar el navegador automatizado sin una ventana visible (recomendado para interfaz web o uso no interactivo). `False` para mostrar la ventana del navegador (útil para modo CLI o depuración).
* `stealth_mode`: `True` para habilitar medidas que dificultan la detección de la automatización del navegador. Puede requerir la instalación manual de extensiones del navegador como anticaptcha.
Esta sección resume los tipos de proveedores de LLM admitidos. Configúralos en `config.ini`.
**Proveedores locales (ejecutándose en tu propio hardware):**
| Nombre del proveedor en config.ini | `is_local` | Descripción | Sección de configuración |
|-------------------------------|------------|-----------------------------------------------------------------------------|------------------------------------------------------------------|
| `ollama` | `True` | Proporciona LLM localmente fácilmente usando Ollama. | [Configuración para ejecutar LLM localmente en tu máquina](#configuración-para-ejecutar-llm-localmente-en-tu-máquina) |
| `lm-studio` | `True` | Proporciona LLM localmente con LM-Studio. | [Configuración para ejecutar LLM localmente en tu máquina](#configuración-para-ejecutar-llm-localmente-en-tu-máquina) |
| `openai` (para servidor local) | `True` | Conéctate a un servidor local que exponga una API compatible con OpenAI (ej: llama.cpp). | [Configuración para ejecutar LLM localmente en tu máquina](#configuración-para-ejecutar-llm-localmente-en-tu-máquina) |
| `server` | `False` | Conéctate al servidor LLM autoalojado de AgenticSeek que se ejecuta en otra máquina. | [Configuración para ejecutar LLM en tu propio servidor](#configuración-para-ejecutar-llm-en-tu-propio-servidor) |
**Proveedores de API (basados en la nube):**
| Nombre del proveedor en config.ini | `is_local` | Descripción | Sección de configuración |
|-------------------------------|------------|--------------------------------------------------|-----------------------------------------------------|
| `openai` | `False` | Usa la API oficial de OpenAI (ej: GPT-3.5, GPT-4). | [Configuración para ejecutar con una API](#configuración-para-ejecutar-con-una-api) |
| `google` | `False` | Usa modelos Google Gemini a través de API. | [Configuración para ejecutar con una API](#configuración-para-ejecutar-con-una-api) |
| `deepseek` | `False` | Usa la API oficial de Deepseek. | [Configuración para ejecutar con una API](#configuración-para-ejecutar-con-una-api) |
| `huggingface` | `False` | Usa Hugging Face Inference API. | [Configuración para ejecutar con una API](#configuración-para-ejecutar-con-una-api) |
| `togetherAI` | `False` | Usa varios modelos abiertos a través de la API de TogetherAI. | [Configuración para ejecutar con una API](#configuración-para-ejecutar-con-una-api) |
---
## Solución de problemas
Si encuentras problemas, esta sección proporciona orientación.
# Problemas conocidos
## Problemas de ChromeDriver
**Ejemplo de error:** `SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version XXX`
### Causa principal
La incompatibilidad de versión de ChromeDriver ocurre cuando:
1. La versión de ChromeDriver que instalaste no coincide con la versión del navegador Chrome
2. En entornos Docker, `undetected_chromedriver` puede descargar su propia versión de ChromeDriver, evitando los binarios montados
### Pasos de solución
#### 1. Verifica tu versión de Chrome
Abre Google Chrome → `Configuración > Acerca de Chrome` para encontrar tu versión (ej: "Versión 134.0.6998.88")
#### 2. Descarga ChromeDriver coincidente
**Para Chrome 115 y versiones más recientes:** Usa [Chrome for Testing API](https://googlechromelabs.github.io/chrome-for-testing/)
- Visita el panel de disponibilidad de Chrome for Testing
- Encuentra tu versión de Chrome o la coincidencia disponible más cercana
- Descarga ChromeDriver para tu sistema operativo (usa Linux64 para entornos Docker)
**Para versiones antiguas de Chrome:** Usa [Descargas heredadas de ChromeDriver](https://chromedriver.chromium.org/downloads)
![Descargar ChromeDriver desde Chrome for Testing](./media/chromedriver_readme.png)
#### 3. Instala ChromeDriver (elige un método)
**Método A: Directorio raíz del proyecto (recomendado para Docker)**
```bash
# Coloca el binario de chromedriver descargado en el directorio raíz del proyecto
cp path/to/downloaded/chromedriver ./chromedriver
chmod +x ./chromedriver # Hazlo ejecutable en Linux/macOS
```
**Método B: PATH del sistema**
```bash
# Linux/macOS
sudo mv chromedriver /usr/local/bin/
sudo chmod +x /usr/local/bin/chromedriver
# Windows: Coloca chromedriver.exe en una carpeta en PATH
```
#### 4. Verifica la instalación
```bash
# Prueba la versión de ChromeDriver
./chromedriver --version
# O si está en PATH:
chromedriver --version
```
### Instrucciones específicas de Docker
⚠️ **Importante para usuarios de Docker:**
- El método de montaje de volúmenes de Docker puede no funcionar con el modo sigiloso (`undetected_chromedriver`)
- **Solución:** Coloca ChromeDriver en el directorio raíz del proyecto como `./chromedriver`
- La aplicación lo detectará automáticamente y usará este binario
- Deberías ver en los registros: `"Using ChromeDriver from project root: ./chromedriver"`
### Consejos para solución de problemas
1. **¿Sigues teniendo incompatibilidad de versión?**
- Verifica que ChromeDriver sea ejecutable: `ls -la ./chromedriver`
- Comprueba la versión de ChromeDriver: `./chromedriver --version`
- Asegúrate de que coincida con tu versión del navegador Chrome
2. **¿Problemas con el contenedor Docker?**
- Revisa los registros del backend: `docker logs backend`
- Busca el mensaje: `"Using ChromeDriver from project root"`
- Si no se encuentra, verifica que el archivo exista y sea ejecutable
3. **Versiones de Chrome for Testing**
- Usa una coincidencia exacta cuando sea posible
- Para la versión 134.0.6998.88, usa ChromeDriver 134.0.6998.165 (la versión disponible más cercana)
- El número de versión principal debe coincidir (134 = 134)
### Matriz de compatibilidad de versiones
| Versión de Chrome | Versión de ChromeDriver | Estado |
|----------------|---------------------|---------|
| 134.0.6998.x | 134.0.6998.165 | ✅ Disponible |
| 133.0.6943.x | 133.0.6943.141 | ✅ Disponible |
| 132.0.6834.x | 132.0.6834.159 | ✅ Disponible |
*Para la compatibilidad más reciente, consulta el [Panel de Chrome for Testing](https://googlechromelabs.github.io/chrome-for-testing/)*
`Exception: Failed to initialize browser: Message: session not created: This version of ChromeDriver only supports Chrome version 113
Current browser version is 134.0.6998.89 with binary path`
Esto sucede si tu navegador y la versión de chromedriver no coinciden.
Necesitas navegar para descargar la versión más reciente:
https://developer.chrome.com/docs/chromedriver/downloads
Si usas Chrome versión 115 o superior, ve a:
https://googlechromelabs.github.io/chrome-for-testing/
y descarga la versión de chromedriver que coincida con tu sistema operativo.
![alt text](./media/chromedriver_readme.png)
Si esta sección está incompleta, abre un issue.
## Problemas de adaptadores de conexión
```
Exception: Provider lm-studio failed: HTTP request failed: No connection adapters were found for '127.0.0.1:1234/v1/chat/completions'` (nota: el puerto puede variar)
```
* **Causa:** Falta el prefijo `http://` en `provider_server_address` para `lm-studio` (u otro servidor local compatible con OpenAI similar) en `config.ini`, o apunta al puerto incorrecto.
* **Solución:**
* Asegúrate de que la dirección incluya `http://`. LM-Studio normalmente usa `http://127.0.0.1:1234` por defecto.
* `config.ini` correcto: `provider_server_address = http://127.0.0.1:1234` (o tu puerto real del servidor LM-Studio).
## URL base de SearxNG no proporcionada
```
raise ValueError("SearxNG base URL must be provided either as an argument or via the SEARXNG_BASE_URL environment variable.")
ValueError: SearxNG base URL must be provided either as an argument or via the SEARXNG_BASE_URL environment variable.`
```
Esto puede ocurrir si ejecutas el modo CLI con la URL base de searxng incorrecta.
SEARXNG_BASE_URL debe diferir según si ejecutas en Docker o en el host:
**Ejecutando en el host:** `SEARXNG_BASE_URL="http://localhost:8080"`
**Ejecutando completamente en Docker (interfaz web):** `SEARXNG_BASE_URL="http://searxng:8080"`
## FAQ
**P: ¿Qué hardware necesito?**
| Tamaño del modelo | GPU | Comentarios |
|-----------|--------|-----------------------------------------------------------|
| 7B | 8GB VRAM | ⚠️ No recomendado. Rendimiento pobre, alucinaciones frecuentes, los agentes de planificación pueden fallar. |
| 14B | 12 GB VRAM (ej: RTX 3060) | ✅ Utilizable para tareas simples. Puede tener dificultades con la navegación web y la planificación de tareas. |
| 32B | 24+ GB VRAM (ej: RTX 4090) | 🚀 Éxito en la mayoría de las tareas, aún puede tener dificultades con la planificación de tareas |
| 70B+ | 48+ GB VRAM | 💪 Excelente. Recomendado para casos de uso avanzados. |
**P: ¿Qué hago si encuentro errores?**
Asegúrate de que lo local esté ejecutándose (`ollama serve`), que tu `config.ini` coincida con tu proveedor y que las dependencias estén instaladas. Si nada funciona, no dudes en abrir un issue.
**P: ¿Realmente puede ejecutarse 100% localmente?**
Sí, con proveedores Ollama, lm-studio o server, todos los modelos de voz a texto, LLM y texto a voz se ejecutan localmente. Las opciones no locales (OpenAI u otras API) son opcionales.
**P: ¿Por qué debería usar AgenticSeek cuando tengo Manus?**
A diferencia de Manus, AgenticSeek prioriza la independencia de los sistemas externos, dándote más control, privacidad y evitando costos de API.
**P: ¿Quién está detrás de este proyecto?**
Este proyecto fue creado por mí, con dos amigos como mantenedores y contribuyentes de la comunidad de código abierto en GitHub. Solo somos individuos apasionados, no una startup, ni estamos afiliados a ninguna organización.
Cualquier cuenta de AgenticSeek en X además de mi cuenta personal (https://x.com/Martin993886460) es impostora.
## Contribuir
¡Buscamos desarrolladores para mejorar AgenticSeek! Revisa los issues abiertos o discusiones.
[Guía de contribución](./docs/CONTRIBUTING.md)
## Patrocinadores:
¿Quieres mejorar las capacidades de AgenticSeek con funciones como búsqueda de vuelos, planificación de viajes o obtención de las mejores ofertas de compras? Considera usar SerpApi para crear herramientas personalizadas que desbloqueen más funcionalidades al estilo Jarvis. Con SerpApi, puedes acelerar tu agente para tareas profesionales mientras mantienes el control total.
<a href="https://serpapi.com/"><img src="./media/banners/sponsor_banner_serpapi.png" height="350" alt="SerpApi Banner" ></a>
¡Consulta [Contributing.md](./docs/CONTRIBUTING.md) para aprender cómo integrar herramientas personalizadas!
### **Patrocinadores**:
- [tatra-labs](https://github.com/tatra-labs)
## Mantenedores:
> [Fosowl](https://github.com/Fosowl) | Hora de París
> [antoineVIVIES](https://github.com/antoineVIVIES) | Hora de Taipei
## Agradecimientos especiales:
> [tcsenpai](https://github.com/tcsenpai) y [plitc](https://github.com/plitc) por ayudar con la dockerización del backend
[![Star History Chart](https://api.star-history.com/svg?repos=Fosowl/agenticSeek&type=Date)](https://www.star-history.com/#Fosowl/agenticSeek&Date)
+289 -474
View File
@@ -1,52 +1,54 @@
# AgenticSeek : Une Alternative Privée et Locale à Manus
<p align="center"> <p align="center">
<img align="center" src="./media/agentic_seek_logo.png" width="300" height="300" alt="Agentic Seek Logo"> <img align="center" src="./media/whale_readme.jpg">
<p> <p>
English | [中文](./README_CHS.md) | [繁體中文](./README_CHT.md) | [Français](./README_FR.md) | [日本語](./README_JP.md) | [Português (Brasil)](./README_PTBR.md) | [Español](./README_ES.md) --------------------------------------------------------------------------------
[English](./README.md) | [繁體中文](./README_CHT.md) | [日本語](./README_JP.md) | Français
*Un assistant IA avec reconnaissance vocale qui est une **alternative 100% locale à Manus AI**, navigue de manière autonome sur le web, écrit du code et planifie des tâches tout en gardant toutes les données sur votre appareil. Conçu pour des modèles de raisonnement locaux, il fonctionne entièrement sur votre matériel, garantissant une confidentialité totale et zéro dépendance au cloud.* # AgenticSeek: Une IA comme Manus mais à base d'agents DeepSeek R1 fonctionnant en local.
[![Visiter AgenticSeek](https://img.shields.io/static/v1?label=Website&message=AgenticSeek&color=blue&style=flat-square)](https://fosowl.github.io/agenticSeek.html) ![License](https://img.shields.io/badge/license-GPL--3.0-green) [![Discord](https://img.shields.io/badge/Discord-Join%20Us-7289DA?logo=discord&logoColor=white)](https://discord.gg/8hGDaME3TC) [![Twitter](https://img.shields.io/twitter/url/https/twitter.com/fosowl.svg?style=social&label=Update%20%40Fosowl)](https://x.com/Martin993886460) [![GitHub stars](https://img.shields.io/github/stars/Fosowl/agenticSeek?style=social)](https://github.com/Fosowl/agenticSeek/stargazers) Une alternative **entièrement locale** à Manus AI, un assistant IA qui code, explore votre système de fichiers, navigue sur le web et corrige ses erreurs, tout cela sans envoyer la moindre donnée dans le cloud. Cet agent autonome fonctionne entièrement sur votre hardware, garantissant la confidentialité de vos données.
### Pourquoi choisir AgenticSeek ? [![Visit AgenticSeek](https://img.shields.io/static/v1?label=Website&message=AgenticSeek&color=blue&style=flat-square)](https://fosowl.github.io/agenticSeek.html) ![License](https://img.shields.io/badge/license-GPL--3.0-green) [![Discord](https://img.shields.io/badge/Discord-Join%20Us-7289DA?logo=discord&logoColor=white)](https://discord.gg/8hGDaME3TC) [![Twitter](https://img.shields.io/twitter/url/https/twitter.com/fosowl.svg?style=social&label=Update%20%40Fosowl)](https://x.com/Martin993886460)
* 🔒 Totalement Local & Privé - Tout fonctionne sur votre machine, sans cloud, sans partage de données. Vos fichiers, conversations et recherches restent privés. > 🛠️ **En cours de développement** On cherche activement des contributeurs!
* 🌐 Navigation Web Intelligente - AgenticSeek peut naviguer sur Internet de manière autonome : rechercher, lire, extraire des informations, remplir des formulaires web, le tout sans intervention manuelle. https://github.com/user-attachments/assets/4bd5faf6-459f-4f94-bd1d-238c4b331469
* 💻 Assistant de Programmation Autonome - Besoin de code ? Il peut écrire, déboguer et exécuter des programmes en Python, C, Go, Java et plus encore, sans supervision. > *Recherche sur le web des activités à faire à Paris*
* 🧠 Sélection Intelligente d'Agents - Vous demandez, il choisit automatiquement le meilleur agent pour la tâche. Comme avoir une équipe d'experts toujours disponible. > *Code le jeu snake en python*
* 📋 Planifie et Exécute des Tâches Complexes - De la planification de voyage aux projets complexes, il peut décomposer de grandes tâches en étapes et les compléter en utilisant plusieurs agents IA. > *J'aimerais que tu trouve une api météo et que tu me code une application qui affiche la météo à Toulouse*
* 🎙️ Prise en Charge Vocale - Voix claire, rapide et futuriste avec reconnaissance vocale, vous permettant de converser comme avec votre IA personnelle de film de science-fiction. (En développement)
### **Démo**
> *Peux-tu rechercher le projet agenticSeek, apprendre quelles compétences sont nécessaires, puis ouvrir CV_candidates.zip et me dire lesquels correspondent le mieux au projet ?*
https://github.com/user-attachments/assets/b8ca60e9-7b3b-4533-840e-08f9ac426316 ## Fonctionnalités:
Avertissement : Cette démonstration et tous les fichiers qui apparaissent (ex: CV_candidates.zip) sont entièrement fictifs. Nous ne sommes pas une entreprise, nous recherchons des contributeurs open source, pas des candidats. - **100% Local**: Fonctionne en local sur votre PC. Vos données restent les vôtres.
> 🛠⚠️ **Travail Actif en Cours** - **Accès à vos Fichiers**: Utilise bash pour naviguer et manipuler vos fichiers.
> 🙏 Ce projet a commencé comme un projet parallèle et n'a ni feuille de route ni financement. Il a grandi bien au-delà des attentes en apparaissant dans GitHub Trending. Les contributions, commentaires et de la patience sont profondément appréciés. - **Codage semi-autonome**: Peut écrire, déboguer et exécuter du code en Python, C, Golang et d'autres langages à venir.
## Prérequis - **Routage d'Agent**: Sélectionne automatiquement lagent approprié pour la tâche.
Avant de commencer, assurez-vous d'avoir installé : - **Planification**: Pour les taches complexe utilise plusieurs agents.
* **Git:** Pour cloner le dépôt. [Télécharger Git](https://git-scm.com/downloads) - **Navigation Web Autonome**: Navigation web autonome.
* **Python 3.10.x:** Python 3.10.x est fortement recommandé. D'autres versions peuvent causer des erreurs de dépendance. [Télécharger Python 3.10](https://www.python.org/downloads/release/python-3100/) (sélectionnez la version 3.10.x).
* **Docker Engine & Docker Compose:** Pour exécuter des services empaquetés comme SearxNG.
* Installer Docker Desktop (inclut Docker Compose V2): [Windows](https://docs.docker.com/desktop/install/windows-install/) | [Mac](https://docs.docker.com/desktop/install/mac-install/) | [Linux](https://docs.docker.com/desktop/install/linux-install/)
* Ou installer Docker Engine et Docker Compose séparément sur Linux: [Docker Engine](https://docs.docker.com/engine/install/) | [Docker Compose](https://docs.docker.com/compose/install/) (assurez-vous d'installer Compose V2, par exemple `sudo apt-get install docker-compose-plugin`).
### 1. **Cloner le dépôt et configurer** - **Memoire efficace**: Gestion efficace de la mémoire et des sessions.
---
## **Installation**
Assurez-vous davoir installé le pilote Chrome, Docker et Python 3.10 (ou une version plus récente).
Pour les problèmes liés au pilote Chrome, consultez la section Chromedriver.
### 1️⃣ Cloner le repo et configurer
```sh ```sh
git clone https://github.com/Fosowl/agenticSeek.git git clone https://github.com/Fosowl/agenticSeek.git
@@ -54,310 +56,245 @@ cd agenticSeek
mv .env.example .env mv .env.example .env
``` ```
### 2. Modifier le contenu du fichier .env ### 2 **Créer un environnement virtuel**
```sh ```sh
SEARXNG_BASE_URL="http://searxng:8080" # Si vous exécutez en mode CLI sur l'hôte, utilisez http://127.0.0.1:8080 python3 -m venv agentic_seek_env
REDIS_BASE_URL="redis://redis:6379/0" source agentic_seek_env/bin/activate
WORK_DIR="/Users/mlg/Documents/workspace_for_ai" # Sur Windows: agentic_seek_env\Scripts\activate
OLLAMA_PORT="11434"
LM_STUDIO_PORT="1234"
CUSTOM_ADDITIONAL_LLM_PORT="11435"
OPENAI_API_KEY='optional'
DEEPSEEK_API_KEY='optional'
OPENROUTER_API_KEY='optional'
TOGETHER_API_KEY='optional'
GOOGLE_API_KEY='optional'
ANTHROPIC_API_KEY='optional'
``` ```
Mettez à jour le fichier `.env` selon vos besoins : ### 3️⃣ **Installation**
- **SEARXNG_BASE_URL**: Gardez inchangé sauf si vous exécutez en mode CLI sur l'hôte. **Automatique:**
- **REDIS_BASE_URL**: Gardez inchangé
- **WORK_DIR**: Chemin vers le répertoire de travail local. AgenticSeek pourra lire et interagir avec ces fichiers.
- **OLLAMA_PORT**: Numéro de port pour le service Ollama.
- **LM_STUDIO_PORT**: Numéro de port pour le service LM Studio.
- **CUSTOM_ADDITIONAL_LLM_PORT**: Port pour tout service LLM personnalisé supplémentaire.
**Les clés API sont complètement optionnelles pour ceux qui choisissent d'exécuter LLM localement, ce qui est l'objectif principal de ce projet. Laissez-les vides si vous avez du matériel suffisant.**
### 3. **Démarrer Docker**
Assurez-vous que Docker est installé et fonctionne sur votre système. Vous pouvez démarrer Docker avec les commandes suivantes :
- **Linux/macOS:**
Ouvrez un terminal et exécutez :
```sh
sudo systemctl start docker
```
Ou démarrez Docker Desktop depuis le menu des applications, s'il est installé.
- **Windows:**
Démarrez Docker Desktop depuis le menu Démarrer.
Vous pouvez vérifier si Docker fonctionne en exécutant :
```sh ```sh
docker info ./install.sh
``` ```
Si vous voyez des informations sur votre installation Docker, cela fonctionne correctement.
Consultez la [Liste des fournisseurs locaux](#liste-des-fournisseurs-locaux) ci-dessous pour un résumé. **Manuel:**
Prochaine étape: [Exécuter AgenticSeek localement](#démarrer-les-services-et-exécuter) **Note : Pour tous les systèmes d'exploitation, assurez-vous que le ChromeDriver que vous installez correspond à la version de Chrome installée. Exécutez `google-chrome --version`. Consultez les problèmes connus si vous avez Chrome >135**
*Si vous rencontrez des problèmes, consultez la section [Dépannage](#dépannage).* - *Linux*:
*Si votre matériel ne peut pas exécuter LLM localement, consultez [Configuration pour exécuter avec une API](#configuration-pour-exécuter-avec-une-api).*
*Pour des explications détaillées de `config.ini`, consultez la [section Configuration](#configuration).*
--- Mettre à jour la liste des paquets : `sudo apt update`
## Configuration pour exécuter LLM localement sur votre machine Installer les dépendances : `sudo apt install -y alsa-utils portaudio19-dev python3-pyaudio libgtk-3-dev libnotify-dev libgconf-2-4 libnss3 libxss1`
**Exigences matérielles:** Installer ChromeDriver correspondant à la version de votre navigateur Chrome :
`sudo apt install -y chromium-chromedriver`
Pour exécuter LLM localement, vous aurez besoin de matériel suffisant. Au minimum, une GPU capable d'exécuter Magistral, Qwen ou Deepseek 14B est requise. Consultez la FAQ pour des recommandations détaillées de modèle/performance. Installer les prérequis : `pip3 install -r requirements.txt`
**Configurez votre fournisseur local** - *macOS*:
Démarrez votre fournisseur local, par exemple avec ollama: Mettre à jour brew : `brew update`
Installer chromedriver : `brew install --cask chromedriver`
Installer portaudio : `brew install portaudio`
Mettre à jour pip : `python3 -m pip install --upgrade pip`
Mettre à jour wheel : `pip3 install --upgrade setuptools wheel`
Installer les prérequis : `pip3 install -r requirements.txt`
- *Windows*:
Installer pyreadline3 : `pip install pyreadline3`
Installer portaudio manuellement (par exemple, via vcpkg ou des binaires précompilés) puis exécutez : `pip install pyaudio`
Télécharger et installer chromedriver manuellement depuis : https://sites.google.com/chromium.org/driver/getting-started
Placez chromedriver dans un répertoire inclus dans votre PATH.
Installer les prérequis : `pip3 install -r requirements.txt`
## Faire fonctionner sur votre machine
**Nous recommandons dutiliser au minimum DeepSeek 14B, les modèles plus petits ont du mal avec lutilisation des outils et oublient rapidement le contexte.**
Lancer votre provider local, par exemple avec ollama:
```sh ```sh
ollama serve ollama serve
``` ```
Consultez la liste des fournisseurs locaux pris en charge ci-dessous. **Configurer le config.ini**
**Mettre à jour config.ini** Modifiez le fichier config.ini pour définir provider_name sur un fournisseur supporté et provider_model sur un LLM compatible avec votre fournisseur. Nous recommandons des modèles de raisonnement comme *Qwen* ou *Deepseek*.
Changez le fichier config.ini pour définir provider_name sur un fournisseur pris en charge et provider_model sur un LLM pris en charge par votre fournisseur. Nous recommandons des modèles de raisonnement comme *Magistral* ou *Deepseek*. Consultez la section **FAQ** à la fin du README pour connaître le matériel requis.
Consultez la **FAQ** à la fin du README pour le matériel nécessaire.
```sh ```sh
[MAIN] [MAIN]
is_local = True # Que vous exécutiez localement ou avec un fournisseur distant. is_local = True # Si vous exécutez localement ou avec un fournisseur distant.
provider_name = ollama # ou lm-studio, openai, etc. provider_name = ollama # ou lm-studio, openai, etc..
provider_model = deepseek-r1:14b # choisissez un modèle compatible avec votre matériel provider_model = deepseek-r1:14b # choisissez un modèle adapté à votre matériel
provider_server_address = 127.0.0.1:11434 provider_server_address = 127.0.0.1:11434
agent_name = Jarvis # le nom de votre IA agent_name = Jarvis # nom de votre IA
recover_last_session = True # récupérer la session précédente recover_last_session = True # récupérer ou non la session précédente
save_session = True # mémoriser la session actuelle save_session = True # mémoriser ou non la session actuelle
speak = False # texte vers parole speak = True # synthèse vocale
listen = False # parole vers texte, uniquement pour CLI, expérimental listen = False # reconnaissance vocale, uniquement pour CLI
jarvis_personality = False # utiliser une personnalité plus "Jarvis" (expérimental) work_dir = /Users/mlg/Documents/workspace # L'espace de travail pour AgenticSeek.
languages = en zh # Liste des langues, TTS utilisera la première de la liste par défaut jarvis_personality = False # Utiliser une personnalité plus "Jarvis", non recommandé avec des petits modèles
languages = en fr # Liste des langages, la synthèse vocale utilisera par défaut la première langue de la liste
[BROWSER] [BROWSER]
headless_browser = True # garder inchangé sauf si vous utilisez CLI sur l'hôte. headless_browser = True # Utiliser ou non le navigateur sans interface graphique, recommandé uniquement avec l'interface web.
stealth_mode = True # Utilise selenium indétectable pour réduire la détection du navigateur stealth_mode = True # Utiliser selenium non détectable pour réduire la détection du navigateur
``` ```
**Avertissement**: Remarque : Certains fournisseurs (ex : lm-studio) nécessitent `http://` devant l'adresse IP. Par exemple `http://127.0.0.1:1234`
- Le format du fichier `config.ini` ne prend pas en charge les commentaires.
Ne copiez et collez pas directement la configuration d'exemple, car les commentaires causeront des erreurs. Modifiez plutôt manuellement le fichier `config.ini` avec votre configuration souhaitée, sans commentaires.
- *NE* définissez PAS provider_name sur `openai` si vous utilisez LM-studio pour exécuter LLM. Utilisez `lm-studio`.
- Certains fournisseurs (ex: lm-studio) nécessitent `http://` avant l'IP. Exemple: `http://127.0.0.1:1234`
**Liste des fournisseurs locaux**
| Fournisseur | Local ? | Description |
|-----------|--------|-----------------------------------------------------------|
| ollama | Oui | Exécute LLM localement facilement en utilisant ollama |
| lm-studio | Oui | Exécute LLM localement avec LM studio (définir `provider_name` = `lm-studio`)|
| openai | Oui | Utilise une API compatible avec openai (ex: serveur llama.cpp) |
Prochaine étape: [Démarrer les services et exécuter AgenticSeek](#démarrer-les-services-et-exécuter)
*Si vous rencontrez des problèmes, consultez la section [Dépannage](#dépannage).*
*Si votre matériel ne peut pas exécuter LLM localement, consultez [Configuration pour exécuter avec une API](#configuration-pour-exécuter-avec-une-api).*
*Pour des explications détaillées de `config.ini`, consultez la [section Configuration](#configuration).*
## Configuration pour exécuter avec une API
Cette configuration utilise des fournisseurs de LLM externes basés sur le cloud. Vous devrez obtenir des clés API du service choisi.
**1. Choisissez un fournisseur d'API et obtenez une clé API:**
Consultez la [Liste des fournisseurs d'API](#liste-des-fournisseurs-dapi) ci-dessous. Visitez leurs sites web pour vous inscrire et obtenir des clés API.
**2. Définissez votre clé API comme variable d'environnement:**
* **Linux/macOS:**
Ouvrez un terminal et utilisez la commande `export`. Il est préférable de l'ajouter au fichier de configuration de votre shell (ex: `~/.bashrc`, `~/.zshrc`) pour qu'elle soit persistante.
```sh
export PROVIDER_API_KEY="your_api_key_here"
# Remplacez PROVIDER_API_KEY par le nom de variable spécifique, ex: OPENAI_API_KEY, GOOGLE_API_KEY
```
Exemple TogetherAI:
```sh
export TOGETHER_API_KEY="xxxxxxxxxxxxxxxxxxxxxx"
```
* **Windows:**
* **Invite de commandes (temporaire pour la session actuelle):**
```cmd
set PROVIDER_API_KEY=your_api_key_here
```
* **PowerShell (temporaire pour la session actuelle):**
```powershell
$env:PROVIDER_API_KEY="your_api_key_here"
```
* **Permanent:** Recherchez "variables d'environnement" dans la barre de recherche Windows, cliquez sur "Modifier les variables d'environnement système", puis sur le bouton "Variables d'environnement...". Ajoutez une nouvelle variable utilisateur avec le nom approprié (ex: `OPENAI_API_KEY`) et votre clé comme valeur.
*(Pour plus de détails, consultez la FAQ: [Comment configurer une clé API ?](#comment-configurer-une-clé-api)).*
**3. Mettez à jour `config.ini`:**
```ini **Liste des provideurs locaux**
[MAIN]
is_local = False | Fournisseur | Local ? | Description |
provider_name = openai # ou google, deepseek, togetherAI, huggingface |-------------|---------|-----------------------------------------------------------|
provider_model = gpt-3.5-turbo # ou gemini-1.5-flash, deepseek-chat, mistralai/Mixtral-8x7B-Instruct-v0.1, etc. | ollama | Oui | Exécutez des LLM localement avec facilité en utilisant ollama comme fournisseur LLM |
provider_server_address = # Lorsque is_local = False, généralement ignoré ou peut être laissé vide pour la plupart des API | lm-studio | Oui | Exécutez un LLM localement avec LM studio (définissez `provider_name` sur `lm-studio`) |
# ... autres configurations ... | openai | Oui | Utilisez une API local compatible avec openai |
### **Démarrer les services & Exécuter**
Activez votre environnement Python si nécessaire.
```sh
source agentic_seek_env/bin/activate
``` ```
*Avertissement:* Assurez-vous qu'il n'y a pas d'espaces à la fin des valeurs dans config.
**Liste des fournisseurs d'API** Démarrez les services requis. Cela lancera tous les services définis dans le fichier docker-compose.yml, y compris :
| Fournisseur | `provider_name` | Local ? | Description | Lien de clé API (exemple) |
|--------------|-----------------|--------|---------------------------------------------------|---------------------------------------------|
| OpenAI | `openai` | Non | Utilise les modèles ChatGPT via l'API OpenAI. | [platform.openai.com/signup](https://platform.openai.com/signup) |
| Google Gemini| `google` | Non | Utilise les modèles Google Gemini via Google AI Studio. | [aistudio.google.com/keys](https://aistudio.google.com/keys) |
| Deepseek | `deepseek` | Non | Utilise les modèles Deepseek via leur API. | [platform.deepseek.com](https://platform.deepseek.com) |
| Hugging Face | `huggingface` | Non | Utilise les modèles du Hugging Face Inference API. | [huggingface.co/settings/tokens](https://huggingface.co/settings/tokens) |
| TogetherAI | `togetherAI` | Non | Utilise divers modèles open source via l'API TogetherAI.| [api.together.ai/settings/api-keys](https://api.together.ai/settings/api-keys) |
*Note:*
* Nous ne recommandons pas d'utiliser `gpt-4o` ou d'autres modèles OpenAI pour la navigation web complexe et la planification de tâches, car l'optimisation actuelle des prompts cible des modèles comme Deepseek.
* Les tâches de codage/bash peuvent échouer avec Gemini, car il a tendance à ignorer notre format de prompt optimisé pour Deepseek r1.
* Lorsque `is_local = False`, `provider_server_address` dans `config.ini` n'est généralement pas utilisé, car les endpoints d'API sont généralement gérés par les bibliothèques du fournisseur correspondant.
Prochaine étape: [Démarrer les services et exécuter AgenticSeek](#démarrer-les-services-et-exécuter)
*Si vous rencontrez des problèmes, consultez la section **Problèmes connus***
*Pour des explications détaillées du fichier de configuration, consultez la **section Configuration**.*
---
## Démarrer les services et exécuter
Par défaut, AgenticSeek s'exécute entièrement dans Docker.
**Option 1:** Exécuter dans Docker avec interface web:
Démarrez les services nécessaires. Cela démarrera tous les services du docker-compose.yml, y compris:
- searxng - searxng
- redis (requis pour searxng) - redis (nécessaire pour searxng)
- frontend
- backend (si vous utilisez `full` pour l'interface web)
```sh
./start_services.sh full # MacOS
start start_services.cmd full # Windows
```
**Avertissement:** Cette étape téléchargera et chargera toutes les images Docker, ce qui peut prendre jusqu'à 30 minutes. Après avoir démarré les services, attendez que le service backend soit complètement opérationnel (vous devriez voir **backend: "GET /health HTTP/1.1" 200 OK** dans les logs) avant d'envoyer des messages. Lors du premier démarrage, le service backend peut prendre 5 minutes pour démarrer.
Allez à `http://localhost:3000/` et vous devriez voir l'interface web.
*Dépannage du démarrage des services:* Si ces scripts échouent, assurez-vous que Docker Engine fonctionne et que Docker Compose (V2, `docker compose`) est correctement installé. Vérifiez les messages d'erreur dans la sortie du terminal. Consultez [FAQ: Aide ! J'obtiens des erreurs lors de l'exécution d'AgenticSeek ou de ses scripts.](#faq-dépannage)
**Option 2:** Mode CLI:
Pour exécuter avec l'interface CLI, vous devez installer les packages sur l'hôte:
```sh
./install.sh
./install.bat # windows
```
Ensuite, vous devez changer SEARXNG_BASE_URL dans `config.ini` en:
```sh
SEARXNG_BASE_URL="http://localhost:8080"
```
Démarrez les services nécessaires. Cela démarrera certains services du docker-compose.yml, y compris:
- searxng
- redis (requis pour searxng)
- frontend - frontend
```sh ```sh
./start_services.sh # MacOS sudo ./start_services.sh # MacOS
start start_services.cmd # Windows start ./start_services.cmd # Windows
``` ```
Exécutez: uv run: `uv run python -m ensurepip` pour vous assurer que uv a pip activé. **Option 1 :** Exécuter avec l'interface CLI.
Utilisez CLI: `uv run cli.py` ```sh
python3 cli.py
```
**Option 2 :** Exécuter avec l'interface Web.
Démarrez le backend.
```sh
python3 api.py
```
Allez sur `http://localhost:3000/` et vous devriez voir l'interface web.
Veuillez noter que l'interface web ne diffuse pas les messages en continu pour le moment.
Voyez la section **Utilisation** si vous ne comprenez pas comment lutiliser
Voyez la section **Problèmes** connus si vous rencontrez des problèmes
Voyez la section **Exécuter avec une API** si votre matériel ne peut pas exécuter DeepSeek localement
Voyez la section **Configuration** pour une explication détaillée du fichier de configuration.
--- ---
## Utilisation ## Utilisation
Assurez-vous que les services fonctionnent avec `./start_services.sh full` puis allez à `localhost:3000` pour l'interface web. Assurez-vous que les services sont en cours dexécution avec ./start_services.sh et lancez AgenticSeek avec le CLI ou l'interface Web.
Vous pouvez également utiliser la parole vers texte en définissant `listen = True`. Uniquement pour le mode CLI. **CLI:**
Vous verrez un prompt : ">>> "
Cela indique quAgenticSeek attend que vous saisissiez des instructions.
Vous pouvez également utiliser la reconnaissance vocale en définissant `listen = True` dans la configuration.
Pour quitter, dites simplement `goodbye`.
Pour quitter, dites/tapez simplement `goodbye`. **Interface:**
Quelques exemples d'utilisation: Assurez-vous d'avoir bien démarré le backend avec `python3 api.py`.
Allez sur `localhost:3000` où vous verrez une interface web.
Tapez simplement votre message et patientez.
Si vous n'avez pas d'interface sur `localhost:3000`, c'est que vous n'avez pas démarré les services avec `start_services.sh`.
> *Fais un jeu de serpent en python !* Voici quelques exemples dutilisation :
> *Recherche sur le web les meilleurs cafés à Rennes, France, et sauvegarde une liste de trois avec leurs adresses dans rennes_cafes.txt.* ### Programmation
> *Écris un programme Go pour calculer la factorielle d'un nombre, sauvegarde-le comme factorial.go dans ton workspace* > *Aide-moi avec la multiplication de matrices en Golang*
> *Recherche dans le dossier summer_pictures tous les fichiers JPG, renomme-les avec la date d'aujourd'hui et sauvegarde la liste des fichiers renommés dans photos_list.txt* > *Initalize un nouveau project python, setup le readme, gitignore etc.. et fait un premier commit*
> *Recherche en ligne les films de science-fiction populaires de 2024 et choisis-en trois à regarder ce soir. Sauvegarde la liste dans movie_night.txt.* > *Fais un jeu snake en Python*
> *Recherche sur le web les derniers articles d'actualité sur l'IA de 2025, sélectionne-en trois et écris un script Python pour extraire les titres et résumés. Sauvegarde le script comme news_scraper.py et les résumés dans ai_news.txt dans /home/projects* ### Recherche web
> *Vendredi, recherche sur le web une API gratuite de prix d'actions, inscris-toi avec supersuper7434567@gmail.com et écris un script Python pour obtenir les prix quotidiens de Tesla en utilisant l'API, en sauvegardant les résultats dans stock_prices.csv* > *Fais une recherche sur le web pour trouver des startups technologiques au Japon qui travaillent sur des recherches avancées en IA*
*Notez que le remplissage de formulaires est toujours expérimental et peut échouer.* > *Peux-tu trouver sur internet qui a créé agenticSeek ?*
> *Peux-tu trouver sur quel site je peux acheter une RTX 4090 à bas prix ?*
### Fichier
> *Hé, peux-tu trouver où est contrat.pdf ? Je lai perdu*
> *Montre-moi combien despace il me reste sur mon disque*
> *Trouve et lis le fichier README.md et suis les instructions dinstallation*
### Conversation
> *Parle-moi de la France*
> *Quel est le sens de la vie ?*
> *Donne moi une recette simple pour ce midi j'ai pas d'inspi*
Après avoir saisi votre requête, AgenticSeek attribuera le meilleur agent pour la tâche. Après avoir saisi votre requête, AgenticSeek attribuera le meilleur agent pour la tâche.
Comme il s'agit d'un prototype initial, le système de routage des agents peut ne pas toujours attribuer l'agent correct à votre requête. Le système de routage des agents peut parfois ne pas toujours attribuer le bon agent en fonction de votre requête.
Par conséquent, soyez très explicite sur ce que vous voulez et comment l'IA pourrait procéder, par exemple si vous voulez qu'elle effectue une recherche web, ne dites pas: Par conséquent, vous devez être assez explicite sur ce que vous voulez et sur la manière dont lIA doit procéder. Par exemple, si vous voulez quelle effectue une recherche sur le web, ne dites pas :
`Connais-tu de bons pays pour voyager seul ?` Connait-tu de bons pays pour voyager seul ?
Dites plutôt: Dites plutôt :
`Effectue une recherche web et découvre quels sont les meilleurs pays pour voyager seul` Fait une recherche sur le web, quels sont les meilleurs pays pour voyager seul?
--- ---
## **Configuration pour exécuter LLM sur votre propre serveur** ## **Exécuter le LLM sur votre propre serveur**
Si vous avez un ordinateur puissant ou un serveur auquel vous pouvez accéder, mais que vous voulez l'utiliser depuis votre ordinateur portable, vous pouvez choisir d'exécuter le LLM sur un serveur distant en utilisant notre serveur llm personnalisé. Si vous disposez dun ordinateur puissant ou dun serveur que vous voulez utiliser, mais que vous souhaitez y accéder depuis votre ordinateur portable, vous avez la possibilité dexécuter le LLM sur un serveur distant.
Sur votre "serveur" qui exécutera le modèle d'IA, obtenez l'adresse IP ### 1️⃣ **Configurer et démarrer les scripts du serveur**
Sur votre "serveur" qui exécutera le modèle IA, obtenez ladresse IP
```sh ```sh
ip a | grep "inet " | grep -v 127.0.0.1 | awk '{print $2}' | cut -d/ -f1 # IP locale ip a | grep "inet " | grep -v 127.0.0.1 | awk '{print $2}' | cut -d/ -f1
curl https://ipinfo.io/ip # IP publique
``` ```
Note: Pour Windows ou macOS, utilisez ipconfig ou ifconfig pour trouver l'adresse IP. Remarque : Pour Windows ou macOS, utilisez respectivement ipconfig ou ifconfig pour trouver ladresse IP.
Clonez le dépôt et entrez dans le dossier server/.
Clonez le dépôt et entrez dans le dossier `server/`.
```sh ```sh
git clone --depth 1 https://github.com/Fosowl/agenticSeek.git git clone --depth 1 https://github.com/Fosowl/agenticSeek.git
cd agenticSeek/llm_server/ cd agenticSeek/server/
``` ```
Installez les exigences spécifiques au serveur: Installez les dépendances spécifiques au serveur :
```sh ```sh
pip3 install -r requirements.txt pip3 install -r requirements.txt
@@ -369,314 +306,192 @@ Exécutez le script du serveur.
python3 app.py --provider ollama --port 3333 python3 app.py --provider ollama --port 3333
``` ```
Vous pouvez choisir d'utiliser `ollama` et `llamacpp` comme service LLM. Vous avez le choix entre utiliser ollama et llamacpp comme service LLM.
Maintenant sur votre ordinateur personnel: ### 2️⃣ **Lancer**
Changez le fichier `config.ini` pour définir `provider_name` sur `server` et `provider_model` sur `deepseek-r1:xxb`. Maintenant, sur votre ordinateur personnel :
Définissez `provider_server_address` sur l'adresse IP de la machine qui exécutera le modèle.
Modifiez le fichier config.ini pour définir provider_name sur server et provider_model sur deepseek-r1:14b.
Définissez provider_server_address sur ladresse IP de la machine qui exécutera le modèle.
```sh ```sh
[MAIN] [MAIN]
is_local = False is_local = False
provider_name = server provider_name = server
provider_model = deepseek-r1:70b provider_model = deepseek-r1:14b
provider_server_address = http://x.x.x.x:3333 provider_server_address = x.x.x.x:3333
``` ```
Prochaine étape: [Démarrer les services et exécuter AgenticSeek](#démarrer-les-services-et-exécuter) Ensuite, exécutez avec le CLI ou l'interface graphique comme expliqué dans la section pour les fournisseurs locaux.
--- ## **Exécuter avec une API externe**
## Parole vers Texte AVERTISSEMENT : Assurez-vous quil ny a pas despace en fin de ligne dans la configuration.
Avertissement: La speech-to-text ne fonctionne qu'en mode CLI pour le moment. ```sh
[MAIN]
Notez que la parole vers texte ne fonctionne qu'en anglais pour le moment. is_local = False
provider_name = openai
La fonctionnalité de parole vers texte est désactivée par défaut. Pour l'activer, définissez listen sur True dans le fichier config.ini: provider_model = gpt-4o
provider_server_address = 127.0.0.1:5000 # n'importe pas
```
listen = True
``` ```
Lorsqu'elle est activée, la fonction de parole vers texte écoute un mot-clé de déclenchement, qui est le nom de l'agent, avant de traiter votre entrée. Vous pouvez personnaliser le nom de l'agent en mettant à jour la valeur `agent_name` dans *config.ini*: **Liste de provideurs API**
| Fournisseur | Local ? | Description |
|--------------|---------|-----------------------------------------------------------|
| openai | Non | Utilise l'API ChatGPT |
| deepseek-api | Non | API Deepseek (non privé) |
| huggingface | Non | API Hugging-Face (non privé) |
| togetherAI | Non | Utilise l'API Together AI (non privé) |
| google | Non | Utilise l'API Google Gemini (non privé) |
``` Ensuite, exécutez avec le CLI ou l'interface graphique comme expliqué dans la section pour les fournisseurs locaux.
agent_name = Friday
```
Pour une meilleure reconnaissance, nous recommandons d'utiliser un nom commun en anglais comme "John" ou "Emma" comme nom d'agent. ## Config
Une fois que vous voyez la transcription commencer à apparaître, dites le nom de l'agent à haute voix pour le réveiller (ex: "Friday"). Exemple de configuration :
Dites votre requête clairement.
Terminez votre demande par une phrase de confirmation pour indiquer au système de continuer. Les exemples de phrases de confirmation incluent:
```
"do it", "go ahead", "execute", "run", "start", "thanks", "would ya", "please", "okay?", "proceed", "continue", "go on", "do that", "go it", "do you understand?"
```
## Configuration
Exemple de configuration:
``` ```
[MAIN] [MAIN]
is_local = True is_local = True
provider_name = ollama provider_name = ollama
provider_model = deepseek-r1:32b provider_model = deepseek-r1:1.5b
provider_server_address = http://127.0.0.1:11434 # Exemple Ollama; LM-Studio utilise http://127.0.0.1:1234 provider_server_address = 127.0.0.1:11434
agent_name = Friday agent_name = Friday
recover_last_session = False recover_last_session = False
save_session = False save_session = False
speak = False speak = False
listen = False listen = False
work_dir = /Users/mlg/Documents/ai_folder
jarvis_personality = False jarvis_personality = False
languages = en zh # Liste des langues pour TTS et routage potentiel. languages = en fr
[BROWSER] [BROWSER]
headless_browser = False headless_browser = False
stealth_mode = False stealth_mode = False
``` ```
**Explication des paramètres de `config.ini`**: **Explication du fichier config.ini**:
* **Section `[MAIN]`:** `is_local` -> Exécute lagent localement (True) ou sur un serveur distant (False).
* `is_local`: `True` si vous utilisez des fournisseurs de LLM locaux (Ollama, LM-Studio, serveur local compatible OpenAI) ou l'option de serveur auto-hébergé. `False` si vous utilisez des API basées sur le cloud (OpenAI, Google, etc.).
* `provider_name`: Spécifie le fournisseur de LLM.
* Options locales: `ollama`, `lm-studio`, `openai` (pour serveur local compatible OpenAI), `server` (pour configuration de serveur auto-hébergé).
* Options d'API: `openai`, `google`, `deepseek`, `huggingface`, `togetherAI`.
* `provider_model`: Nom ou ID spécifique du modèle du fournisseur sélectionné (ex: `deepseekcoder:6.7b` pour Ollama, `gpt-3.5-turbo` pour API OpenAI, `mistralai/Mixtral-8x7B-Instruct-v0.1` pour TogetherAI).
* `provider_server_address`: L'adresse de votre fournisseur de LLM.
* Pour les fournisseurs locaux: ex: `http://127.0.0.1:11434` pour Ollama, `http://127.0.0.1:1234` pour LM-Studio.
* Pour le type de fournisseur `server`: L'adresse de votre serveur LLM auto-hébergé (ex: `http://your_server_ip:3333`).
* Pour les API cloud (`is_local = False`): Ceci est généralement ignoré ou peut être laissé vide, car les endpoints d'API sont généralement gérés par les bibliothèques clientes.
* `agent_name`: Le nom de l'assistant IA (ex: Friday). Si activé, utilisé comme mot de déclenchement pour la parole vers texte.
* `recover_last_session`: `True` pour tenter de récupérer l'état de la session précédente, `False` pour recommencer.
* `save_session`: `True` pour sauvegarder l'état de la session actuelle pour une récupération potentielle, `False` sinon.
* `speak`: `True` pour activer la sortie vocale de texte vers parole, `False` pour désactiver.
* `listen`: `True` pour activer l'entrée vocale de parole vers texte (uniquement mode CLI), `False` pour désactiver.
* `work_dir`: **Critique:** Le répertoire où AgenticSeek lira/écrira des fichiers. **Assurez-vous que ce chemin est valide et accessible sur votre système.**
* `jarvis_personality`: `True` pour utiliser des invites système plus "Jarvis-like" (expérimental), `False` pour utiliser des invites standard.
* `languages`: Liste de langues séparées par des virgules (ex: `en, zh, fr`). Utilisé pour la sélection de voix TTS (première par défaut) et peut aider le routeur LLM. Pour éviter les inefficacités du routeur, évitez d'utiliser trop de langues ou des langues très similaires.
* **Section `[BROWSER]`:**
* `headless_browser`: `True` pour exécuter le navigateur automatisé sans fenêtre visible (recommandé pour l'interface web ou l'utilisation non interactive). `False` pour afficher la fenêtre du navigateur (utile pour le mode CLI ou le débogage).
* `stealth_mode`: `True` pour activer des mesures qui rendent plus difficile la détection de l'automatisation du navigateur. Peut nécessiter l'installation manuelle d'extensions de navigateur comme anticaptcha.
Cette section résume les types de fournisseurs de LLM pris en charge. Configurez-les dans `config.ini`. `provider_name` -> Le fournisseur à utiliser (parmi : ollama, server, lm-studio, deepseek-api).
**Fournisseurs locaux (fonctionnant sur votre propre matériel):** `provider_model` -> Le modèle utilisé, par exemple, deepseek-r1:1.5b.
| Nom du fournisseur dans config.ini | `is_local` | Description | Section de configuration | `provider_server_address` -> Adresse du serveur, par exemple, 127.0.0.1:11434 pour local. Définissez nimporte quoi pour une API non locale.
|-------------------------------|------------|-----------------------------------------------------------------------------|------------------------------------------------------------------|
| `ollama` | `True` | Fournit LLM localement facilement en utilisant Ollama. | [Configuration pour exécuter LLM localement sur votre machine](#configuration-pour-exécuter-llm-localement-sur-votre-machine) |
| `lm-studio` | `True` | Fournit LLM localement avec LM-Studio. | [Configuration pour exécuter LLM localement sur votre machine](#configuration-pour-exécuter-llm-localement-sur-votre-machine) |
| `openai` (pour serveur local) | `True` | Connectez-vous à un serveur local exposant une API compatible OpenAI (ex: llama.cpp). | [Configuration pour exécuter LLM localement sur votre machine](#configuration-pour-exécuter-llm-localement-sur-votre-machine) |
| `server` | `False` | Connectez-vous au serveur LLM auto-hébergé d'AgenticSeek fonctionnant sur une autre machine. | [Configuration pour exécuter LLM sur votre propre serveur](#configuration-pour-exécuter-llm-sur-votre-propre-serveur) |
**Fournisseurs d'API (basés sur le cloud):** `agent_name` -> Nom de lagent, par exemple, Friday. Utilisé comme mot déclencheur pour la reconnaissance vocale.
| Nom du fournisseur dans config.ini | `is_local` | Description | Section de configuration | `recover_last_session` -> Reprend la dernière session (True) ou non (False).
|-------------------------------|------------|--------------------------------------------------|-----------------------------------------------------|
| `openai` | `False` | Utilise l'API officielle d'OpenAI (ex: GPT-3.5, GPT-4). | [Configuration pour exécuter avec une API](#configuration-pour-exécuter-avec-une-api) |
| `google` | `False` | Utilise les modèles Google Gemini via API. | [Configuration pour exécuter avec une API](#configuration-pour-exécuter-avec-une-api) |
| `deepseek` | `False` | Utilise l'API officielle de Deepseek. | [Configuration pour exécuter avec une API](#configuration-pour-exécuter-avec-une-api) |
| `huggingface` | `False` | Utilise Hugging Face Inference API. | [Configuration pour exécuter avec une API](#configuration-pour-exécuter-avec-une-api) |
| `togetherAI` | `False` | Utilise divers modèles ouverts via l'API TogetherAI. | [Configuration pour exécuter avec une API](#configuration-pour-exécuter-avec-une-api) |
--- `save_session` -> Sauvegarde les données de la session (True) ou non (False).
## Dépannage
Si vous rencontrez des problèmes, cette section fournit des conseils. `speak` -> Active la sortie vocale (True) ou non (False).
# Problèmes connus `listen` -> Écoute les entrées vocales (True) ou non (False).
## Problèmes de ChromeDriver `work_dir` -> Dossier auquel lIA aura accès, par exemple : /Users/user/Documents/.
**Exemple d'erreur:** `SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version XXX` `jarvis_personality` -> Utilise une personnalité inspiré de Jarvis (True) ou non (False). Cela utilise simplement une prompt alternative. Marche moins bien en français.
### Cause racine `headless_browser` -> Exécute le navigateur sans fenêtre visible (True) ou non (False).
L'incompatibilité de version de ChromeDriver se produit lorsque:
1. La version de ChromeDriver que vous avez installée ne correspond pas à la version du navigateur Chrome
2. Dans les environnements Docker, `undetected_chromedriver` peut télécharger sa propre version de ChromeDriver, contournant les binaires montés
### Étapes de résolution `stealth_mode` -> Rend la détection des bots plus difficile. Le seul inconvénient est que vous devez installer manuellement lextension anticaptcha.
#### 1. Vérifiez votre version de Chrome `languages` -> La liste de languages supportés (nécessaire pour le routage d'agents). Plus la liste est longue. Plus un nombre important de modèles sera téléchargés.
Ouvrez Google Chrome → `Paramètres > À propos de Chrome` pour trouver votre version (ex: "Version 134.0.6998.88")
#### 2. Téléchargez ChromeDriver correspondant ## Providers
**Pour Chrome 115 et versions ultérieures:** Utilisez [Chrome for Testing API](https://googlechromelabs.github.io/chrome-for-testing/) Le tableau ci-dessous montre les LLM providers disponibles :
- Visitez le tableau de disponibilité de Chrome for Testing
- Trouvez votre version de Chrome ou la correspondance disponible la plus proche
- Téléchargez ChromeDriver pour votre système d'exploitation (utilisez Linux64 pour les environnements Docker)
**Pour les anciennes versions de Chrome:** Utilisez [Téléchargements hérités de ChromeDriver](https://chromedriver.chromium.org/downloads) | Provider | Local? | Description |
|-----------|--------|-----------------------------------------------------------|
| ollama | Yes | Exécutez des LLM localement avec facilité en utilisant Ollama comme fournisseur LLM
| server | Yes | Hébergez le modèle sur une autre machine, exécutez sur votre machine locale
| lm-studio | Yes | Exécutez un LLM localement avec LM Studio (définissez provider_name sur lm-studio)
| openai | No | Utilise l'API ChatGPT (pas privé) |
| deepseek-api | No | Utilise l'API Deepseek (pas privé) |
| huggingface| No | Utilise Hugging-Face (pas privé) |
| together| No | Utilise l'api Together AI |
![Télécharger ChromeDriver depuis Chrome for Testing](./media/chromedriver_readme.png) Pour sélectionner un provider LLM, modifiez le config.ini :
#### 3. Installez ChromeDriver (choisissez une méthode) ```
is_local = False
**Méthode A: Répertoire racine du projet (recommandé pour Docker)** provider_name = openai
```bash provider_model = gpt-4o
# Placez le binaire chromedriver téléchargé dans le répertoire racine du projet provider_server_address = 127.0.0.1:5000
cp path/to/downloaded/chromedriver ./chromedriver
chmod +x ./chromedriver # Rendez-le exécutable sur Linux/macOS
``` ```
**Méthode B: PATH système** `is_local` : doit être True pour tout LLM exécuté localement, sinon False.
```bash
# Linux/macOS
sudo mv chromedriver /usr/local/bin/
sudo chmod +x /usr/local/bin/chromedriver
# Windows: Placez chromedriver.exe dans un dossier du PATH `provider_name` : Sélectionnez le fournisseur à utiliser par son nom, voir la liste des fournisseurs ci-dessus.
```
#### 4. Vérifiez l'installation `provider_model` : Définissez le modèle à utiliser par lagent.
```bash
# Testez la version de ChromeDriver
./chromedriver --version
# Ou s'il est dans PATH:
chromedriver --version
```
### Instructions spécifiques à Docker `provider_server_address` : peut être défini sur nimporte quoi si vous nutilisez pas le fournisseur server.
⚠️ **Important pour les utilisateurs de Docker:** # Problèmes connus
- La méthode de montage de volumes Docker peut ne pas fonctionner avec le mode furtif (`undetected_chromedriver`)
- **Solution:** Placez ChromeDriver dans le répertoire racine du projet en tant que `./chromedriver`
- L'application le détectera automatiquement et utilisera ce binaire
- Vous devriez voir dans les logs: `"Using ChromeDriver from project root: ./chromedriver"`
### Conseils de dépannage ## Problèmes avec Chromedriver
1. **Toujours une incompatibilité de version ?** Erreur #1:**incompatibilité**
- Vérifiez que ChromeDriver est exécutable: `ls -la ./chromedriver`
- Vérifiez la version de ChromeDriver: `./chromedriver --version`
- Assurez-vous qu'elle correspond à votre version du navigateur Chrome
2. **Problèmes avec le conteneur Docker ?**
- Vérifiez les logs du backend: `docker logs backend`
- Recherchez le message: `"Using ChromeDriver from project root"`
- S'il n'est pas trouvé, vérifiez que le fichier existe et est exécutable
3. **Versions de Chrome for Testing**
- Utilisez une correspondance exacte lorsque possible
- Pour la version 134.0.6998.88, utilisez ChromeDriver 134.0.6998.165 (la version disponible la plus proche)
- Le numéro de version principal doit correspondre (134 = 134)
### Matrice de compatibilité des versions
| Version de Chrome | Version de ChromeDriver | Statut |
|----------------|---------------------|---------|
| 134.0.6998.x | 134.0.6998.165 | ✅ Disponible |
| 133.0.6943.x | 133.0.6943.141 | ✅ Disponible |
| 132.0.6834.x | 132.0.6834.159 | ✅ Disponible |
*Pour la compatibilité la plus récente, consultez le [Tableau de Chrome for Testing](https://googlechromelabs.github.io/chrome-for-testing/)*
`Exception: Failed to initialize browser: Message: session not created: This version of ChromeDriver only supports Chrome version 113 `Exception: Failed to initialize browser: Message: session not created: This version of ChromeDriver only supports Chrome version 113
Current browser version is 134.0.6998.89 with binary path` Current browser version is 134.0.6998.89 with binary path`
Cela se produit si votre navigateur et la version de chromedriver ne correspondent pas. Cela se produit sil y a une incompatibilité entre votre navigateur et la version de chromedriver.
Vous devez naviguer pour télécharger la dernière version: Vous devez naviguer pour télécharger la dernière version :
https://developer.chrome.com/docs/chromedriver/downloads https://developer.chrome.com/docs/chromedriver/downloads
Si vous utilisez Chrome version 115 ou supérieure, allez à: Si vous utilisez Chrome version 115 ou plus récent, allez sur :
https://googlechromelabs.github.io/chrome-for-testing/ https://googlechromelabs.github.io/chrome-for-testing/
et téléchargez la version de chromedriver correspondant à votre système d'exploitation. Et téléchargez la version de chromedriver correspondant à votre système dexploitation.
![alt text](./media/chromedriver_readme.png) ![alt text](./media/chromedriver_readme.png)
Si cette section est incomplète, ouvrez un issue. Si cette section est incomplète, merci de faire une nouvelle issue sur github.
## Problèmes d'adaptateurs de connexion
```
Exception: Provider lm-studio failed: HTTP request failed: No connection adapters were found for '127.0.0.1:1234/v1/chat/completions'` (note: le port peut varier)
```
* **Cause:** Il manque le préfixe `http://` dans `provider_server_address` pour `lm-studio` (ou un autre serveur local compatible OpenAI similaire) dans `config.ini`, ou il pointe vers le mauvais port.
* **Solution:**
* Assurez-vous que l'adresse inclut `http://`. LM-Studio utilise généralement `http://127.0.0.1:1234` par défaut.
* `config.ini` correct: `provider_server_address = http://127.0.0.1:1234` (ou votre port réel du serveur LM-Studio).
## URL de base de SearxNG non fournie
```
raise ValueError("SearxNG base URL must be provided either as an argument or via the SEARXNG_BASE_URL environment variable.")
ValueError: SearxNG base URL must be provided either as an argument or via the SEARXNG_BASE_URL environment variable.`
```
Cela peut se produire si vous exécutez le mode CLI avec une URL de base de searxng incorrecte.
SEARXNG_BASE_URL doit différer selon que vous exécutez dans Docker ou sur l'hôte:
**Exécution sur l'hôte:** `SEARXNG_BASE_URL="http://localhost:8080"`
**Exécution complètement dans Docker (interface web):** `SEARXNG_BASE_URL="http://searxng:8080"`
## FAQ ## FAQ
**Q: Quel matériel est nécessaire ?**
**Q: De quel matériel ai-je besoin ?** | Taille du Modèle | GPU | Commentaire |
|--------------------|------|----------------------------------------------------------|
| 7B | 8 Go VRAM | ⚠️ Non recommandé. Performances médiocres, hallucinations fréquentes, et l'agent planificateur échouera probablement. |
| 14B | 12 Go VRAM (par ex. RTX 3060) | ✅ Utilisable pour des tâches simples. Peut rencontrer des difficultés avec la navigation web et les tâches de planification. |
| 32B | 24+ Go VRAM (par ex. RTX 4090) | 🚀 Réussite avec la plupart des tâches, peut encore avoir des difficultés avec la planification des tâches. |
| 70B+ | 48+ Go VRAM (par ex. Mac Studio) | 💪 Excellent. Recommandé pour des cas d'utilisation avancés. |
| Taille du modèle | GPU | Commentaires | **Q: Pourquoi deepseek et pas un autre modèle**
|-----------|--------|-----------------------------------------------------------|
| 7B | 8GB VRAM | ⚠️ Non recommandé. Performances médiocres, hallucinations fréquentes, les agents de planification peuvent échouer. |
| 14B | 12 GB VRAM (ex: RTX 3060) | ✅ Utilisable pour des tâches simples. Peut avoir des difficultés avec la navigation web et la planification de tâches. |
| 32B | 24+ GB VRAM (ex: RTX 4090) | 🚀 Réussit la plupart des tâches, peut encore avoir des difficultés avec la planification de tâches |
| 70B+ | 48+ GB VRAM | 💪 Excellent. Recommandé pour les cas d'utilisation avancés. |
**Q: Que faire si je rencontre des erreurs ?** DeepSeek R1 excelle dans le raisonnement et lutilisation doutils pour sa taille. Nous pensons que cest un choix solide pour nos besoins, bien que dautres modèles fonctionnent également (bien que moins bien pour un nombre équivalent de paramètres).
Assurez-vous que le local fonctionne (`ollama serve`), que votre `config.ini` correspond à votre fournisseur et que les dépendances sont installées. Si rien ne fonctionne, n'hésitez pas à ouvrir un issue. **Q: J'ai une erreur quand je lance le programme, je fait quoi?**
**Q: Peut-il vraiment fonctionner à 100% localement ?** Assurez-vous quOllama est en cours dexécution (ollama serve), que votre config.ini correspond à votre fournisseur, et que les dépendances sont installées. Si cela ne fonctionne pas, nhésitez pas à signaler un problème.
Oui, avec les fournisseurs Ollama, lm-studio ou server, tous les modèles de parole vers texte, LLM et texte vers parole fonctionnent localement. Les options non locales (OpenAI ou autres API) sont optionnelles. **Q: C'est vraiment 100% local?**
**Q: Pourquoi devrais-je utiliser AgenticSeek quand j'ai Manus ?** Oui, avec les fournisseurs Ollama, lm-studio ou Server, toute la reconnaissance vocale, le LLM et la synthèse vocale fonctionnent localement. Les options non locales (OpenAI ou autres API) sont facultatives.
Contrairement à Manus, AgenticSeek privilégie l'indépendance des systèmes externes, vous donnant plus de contrôle, de confidentialité et évitant les coûts d'API. **Q: En quoi c'est supérieur à Manus**
**Q: Qui est derrière ce projet ?** Il ne l'est certainement pas, mais nous privilégions lexécution locale et la confidentialité par rapport à une approche basée sur le cloud. Cest une alternative plus accessible et surtout moins cher !
Ce projet a été créé par moi, avec deux amis comme mainteneurs et des contributeurs de la communauté open source sur GitHub. Nous sommes juste des individus passionnés, pas une startup, ni affiliés à aucune organisation. ## Contribution
Tout compte AgenticSeek sur X autre que mon compte personnel (https://x.com/Martin993886460) est un imposteur. Nous recherchons des développeurs pour améliorer AgenticSeek ! Consultez la section "issues" github ou les discussions.
## Contribuer
Nous recherchons des développeurs pour améliorer AgenticSeek ! Consultez les problèmes ouverts ou les discussions.
[Guide de contribution](./docs/CONTRIBUTING.md)
## Sponsors:
Vous voulez améliorer les capacités d'AgenticSeek avec des fonctionnalités comme la recherche de vols, la planification de voyages ou l'obtention des meilleures offres d'achat ? Envisagez d'utiliser SerpApi pour créer des outils personnalisés qui débloquent plus de fonctionnalités de type Jarvis. Avec SerpApi, vous pouvez accélérer votre agent pour des tâches professionnelles tout en gardant le contrôle total.
<a href="https://serpapi.com/"><img src="./media/banners/sponsor_banner_serpapi.png" height="350" alt="SerpApi Banner" ></a>
Consultez [Contributing.md](./docs/CONTRIBUTING.md) pour apprendre comment intégrer des outils personnalisés !
### **Sponsors**:
- [tatra-labs](https://github.com/tatra-labs)
## Mainteneurs:
> [Fosowl](https://github.com/Fosowl) | Heure de Paris
> [antoineVIVIES](https://github.com/antoineVIVIES) | Heure de Taipei
## Remerciements spéciaux:
> [tcsenpai](https://github.com/tcsenpai) et [plitc](https://github.com/plitc) pour avoir aidé à la dockerisation du backend
[![Star History Chart](https://api.star-history.com/svg?repos=Fosowl/agenticSeek&type=Date)](https://www.star-history.com/#Fosowl/agenticSeek&Date) [![Star History Chart](https://api.star-history.com/svg?repos=Fosowl/agenticSeek&type=Date)](https://www.star-history.com/#Fosowl/agenticSeek&Date)
[Guide du contributeur](./docs/CONTRIBUTING.md)
## Mainteneurs:
> [Fosowl](https://github.com/Fosowl)
> [steveh8758](https://github.com/steveh8758)
> [https://github.com/antoineVIVIES](https://github.com/antoineVIVIES)
+267 -462
View File
@@ -1,52 +1,61 @@
# AgenticSeek: Manusのプライベートでローカルな代替品
<p align="center"> <p align="center">
<img align="center" src="./media/agentic_seek_logo.png" width="300" height="300" alt="Agentic Seek Logo"> <img align="center" src="./media/whale_readme.jpg">
<p> <p>
English | [中文](./README_CHS.md) | [繁體中文](./README_CHT.md) | [Français](./README_FR.md) | [日本語](./README_JP.md) | [Português (Brasil)](./README_PTBR.md) | [Español](./README_ES.md) --------------------------------------------------------------------------------
[English](./README.md) | [中文](./README_CHS.md) | [繁體中文](./README_CHT.md) | [Français](./README_FR.md) | 日本語
*音声対応のAIアシスタントで、**100%ローカルで動作するManus AIの代替品**です。自律的にウェブを閲覧し、コードを書き、タスクを計画し、すべてのデータをデバイス上に保持します。ローカル推論モデル向けに設計されており、完全にあなたのハードウェア上で動作し、プライバシーを保証し、クラウドへの依存をゼロにします。* # AgenticSeek: Deepseek R1エージェントによって動作するManusのようなAI。
[![AgenticSeekを訪問](https://img.shields.io/static/v1?label=Website&message=AgenticSeek&color=blue&style=flat-square)](https://fosowl.github.io/agenticSeek.html) ![License](https://img.shields.io/badge/license-GPL--3.0-green) [![Discord](https://img.shields.io/badge/Discord-Join%20Us-7289DA?logo=discord&logoColor=white)](https://discord.gg/8hGDaME3TC) [![Twitter](https://img.shields.io/twitter/url/https/twitter.com/fosowl.svg?style=social&label=Update%20%40Fosowl)](https://x.com/Martin993886460) [![GitHub stars](https://img.shields.io/github/stars/Fosowl/agenticSeek?style=social)](https://github.com/Fosowl/agenticSeek/stargazers)
### なぜAgenticSeekを選ぶのか? **Manus AIの完全なローカル代替品**、音声対応のAIアシスタントで、コードを書き、ファイルシステムを探索し、ウェブを閲覧し、ミスを修正し、データをクラウドに送信することなくすべてを行います。DeepSeek R1のような推論モデルを使用して構築されており、この自律エージェントは完全にハードウェア上で動作し、データのプライバシーを保護します。
* 🔒 完全にローカル&プライベート - すべてがあなたのマシン上で動作し、クラウドなし、データ共有なし。あなたのファイル、会話、検索はプライベートのままです。 [![Visit AgenticSeek](https://img.shields.io/static/v1?label=Website&message=AgenticSeek&color=blue&style=flat-square)](https://fosowl.github.io/agenticSeek.html) ![License](https://img.shields.io/badge/license-GPL--3.0-green) [![Discord](https://img.shields.io/badge/Discord-Join%20Us-7289DA?logo=discord&logoColor=white)](https://discord.gg/8hGDaME3TC) [![Twitter](https://img.shields.io/twitter/url/https/twitter.com/fosowl.svg?style=social&label=Update%20%40Fosowl)](https://x.com/Martin993886460)
* 🌐 インテリジェントなウェブブラウジング - AgenticSeekは自律的にインターネットを閲覧できます:検索、読み取り、情報抽出、ウェブフォーム入力、すべて手動操作なしで。 > 🛠️ **進行中の作業** – 貢献者を探しています!
* 💻 自律的なプログラミングアシスタント - コードが必要ですか?Python、C、Go、Javaなどのプログラムを監督なしで書き、デバッグし、実行できます。
* 🧠 インテリジェントなエージェント選択 - あなたが要求すると、自動的に最適なエージェントがタスクに割り当てられます。常に利用可能な専門家チームを持っているようなものです。
* 📋 複雑なタスクの計画と実行 - 旅行計画から複雑なプロジェクトまで、大きなタスクをステップに分解し、複数のAIエージェントを使用して完了できます。
* 🎙️ 音声サポート - クリーンで高速で未来的な音声と音声認識機能により、SF映画のようなパーソナルAIと会話できます。(開発中) https://github.com/user-attachments/assets/fe9e8006-0462-4793-8b31-25bd42c6d1eb
### **デモ**
> *agenticSeekプロジェクトを検索して必要なスキルを学び、CV_candidates.zipを開いて、どの候補がプロジェクトに最も適しているか教えてくれますか?*
https://github.com/user-attachments/assets/b8ca60e9-7b3b-4533-840e-08f9ac426316
免責事項:このデモと表示されるすべてのファイル(例:CV_candidates.zip)は完全に架空のものです。私たちは企業ではなく、候補者ではなくオープンソースの貢献者を求めています。 *そしてもっと多くのことができます!*
> 🛠⚠️ **アクティブな開発中** > *大阪と東京のAIスタートアップを深く調査し、少なくとも5つ見つけて、research_japan.txtファイルに保存してください*
> 🙏 このプロジェクトはサイドプロジェクトとして始まり、ロードマップも資金もありませんでした。GitHub Trendingに登場して予想以上に成長しました。貢献、フィードバック、忍耐に深く感謝します。 > *C言語でテトリスゲームを作れますか?*
## 前提条件 > *新しいプロジェクトファイルインデックスをmark2として設定したいです。*
始める前に、以下がインストールされていることを確認してください:
* **Git:** リポジトリをクローンするため。[Gitをダウンロード](https://git-scm.com/downloads) ## 特徴:
* **Python 3.10.x:** Python 3.10.xを強く推奨します。他のバージョンでは依存関係エラーが発生する可能性があります。[Python 3.10をダウンロード](https://www.python.org/downloads/release/python-3100/)3.10.xバージョンを選択)。
* **Docker Engine & Docker Compose:** SearxNGなどのパッケージ化されたサービスを実行するため。
* Docker Desktopをインストール(Docker Compose V2を含む):[Windows](https://docs.docker.com/desktop/install/windows-install/) | [Mac](https://docs.docker.com/desktop/install/mac-install/) | [Linux](https://docs.docker.com/desktop/install/linux-install/)
* またはLinuxでDocker EngineとDocker Composeを別々にインストール:[Docker Engine](https://docs.docker.com/engine/install/) | [Docker Compose](https://docs.docker.com/compose/install/)(Compose V2をインストールしていることを確認、例:`sudo apt-get install docker-compose-plugin`)。
### 1. **リポジトリをクローンして設定** - **100%ローカル**: クラウドなし、ハードウェア上で動作。データはあなたのものです。
- **ファイルシステムの操作**: bashを使用してファイルを簡単にナビゲートおよび操作します。
- **自律的なコーディング**: Python、C、Golangなどのコードを書き、デバッグし、実行できます。
- **エージェントルーティング**: タスクに最適なエージェントを自動的に選択します。
- **計画**: 複雑なタスクの場合、複数のエージェントを起動して計画および実行します。
- **自律的なウェブブラウジング**: 自律的なウェブナビゲーション。
- **メモリ**: 効率的なメモリとセッション管理。
---
## **インストール**
chrome driver、docker、およびpython3.10(またはそれ以降)がインストールされていることを確認してください。
chrome driverに関連する問題については、**Chromedriver**セクションを参照してください。
### 1️⃣ **リポジトリをクローンしてセットアップ**
```sh ```sh
git clone https://github.com/Fosowl/agenticSeek.git git clone https://github.com/Fosowl/agenticSeek.git
@@ -54,311 +63,238 @@ cd agenticSeek
mv .env.example .env mv .env.example .env
``` ```
### 2. .envファイルの内容を変更 ### 2 **仮想環境を作成**
```sh ```sh
SEARXNG_BASE_URL="http://searxng:8080" # ホストでCLIモードを実行する場合はhttp://127.0.0.1:8080を使用 python3 -m venv agentic_seek_env
REDIS_BASE_URL="redis://redis:6379/0" source agentic_seek_env/bin/activate
WORK_DIR="/Users/mlg/Documents/workspace_for_ai" # Windowsの場合: agentic_seek_env\Scripts\activate
OLLAMA_PORT="11434"
LM_STUDIO_PORT="1234"
CUSTOM_ADDITIONAL_LLM_PORT="11435"
OPENAI_API_KEY='optional'
DEEPSEEK_API_KEY='optional'
OPENROUTER_API_KEY='optional'
TOGETHER_API_KEY='optional'
GOOGLE_API_KEY='optional'
ANTHROPIC_API_KEY='optional'
``` ```
必要に応じて`.env`ファイルを更新してください: ### 3️⃣ **パッケージをインストール**
- **SEARXNG_BASE_URL**: ホストでCLIモードを実行する場合を除き、変更しないでください。 **自動インストール:**
- **REDIS_BASE_URL**: 変更しないでください
- **WORK_DIR**: ローカル作業ディレクトリへのパス。AgenticSeekはこれらのファイルを読み取り、操作できます。
- **OLLAMA_PORT**: Ollamaサービスのポート番号。
- **LM_STUDIO_PORT**: LM Studioサービスのポート番号。
- **CUSTOM_ADDITIONAL_LLM_PORT**: 追加のカスタムLLMサービスのポート。
**APIキーは、ローカルでLLMを実行することを選択するユーザーには完全にオプションであり、これがこのプロジェクトの主な目的です。ハードウェアが十分にある場合は空のままにしてください。**
### 3. **Dockerを起動**
Dockerがインストールされ、システム上で実行されていることを確認してください。以下のコマンドでDockerを起動できます:
- **Linux/macOS:**
ターミナルを開いて実行:
```sh
sudo systemctl start docker
```
または、インストールされている場合はアプリケーションメニューからDocker Desktopを起動。
- **Windows:**
スタートメニューからDocker Desktopを起動。
Dockerが実行されているかは以下で確認できます:
```sh ```sh
docker info ./install.sh
``` ```
Dockerインストール情報が表示されれば正常に動作しています。
要約については以下の[ローカルプロバイダーリスト](#ローカルプロバイダーリスト)を参照してください。 ** テキスト読み上げ(TTS)機能で日本語をサポートするには、fugashi(日本語分かち書きライブラリ)をインストールする必要があります:**
次のステップ:[ローカルでAgenticSeekを実行](#サービスを起動して実行) ```
pip3 install --upgrade pyopenjtalk jaconv mojimoji unidic fugashi
pip install unidic-lite
python -m unidic download
```
*問題が発生した場合は、[トラブルシューティング](#トラブルシューティング)セクションを参照してください。* **手動で:**
*ハードウェアがローカルでLLMを実行できない場合は、[APIを使用した実行設定](#apiを使用した実行設定)を参照してください。*
*詳細な`config.ini`の説明については、[設定セクション](#設定)を参照してください。* ```sh
pip3 install -r requirements.txt
# または
python3 setup.py install
```
--- ---
## マシン上でローカルにLLMを実行する設定 ## ローカルマシンでLLMを実行するためのセットアップ
**ハードウェア要件:** **少なくともDeepseek 14Bを使用することをお勧めします。小さいモデルでは、特にウェブブラウジングのタスクで苦労する可能性があります。**
LLMをローカルで実行するには、十分なハードウェアが必要です。少なくともMagistral、Qwen、またはDeepseek 14Bを実行できるGPUが必要です。詳細なモデル/パフォーマンスの推奨事項についてはFAQを参照してください。 **ローカルプロバイダーをセットアップする**
**ローカルプロバイダーを設定** たとえば、ollamaを使用してローカルプロバイダーを開始します:
例えばollamaを使用してローカルプロバイダーを起動:
```sh ```sh
ollama serve ollama serve
``` ```
サポートされているローカルプロバイダーのリストは以下を参照してください 以下に、サポートされているローカルプロバイダーのリストを示します
**config.iniを更新** **config.iniを更新する**
config.iniファイルを変更して、provider_nameをサポートされているプロバイダーにprovider_modelをプロバイダーがサポートするLLMに設定します。*Magistral*や*Deepseek*などの推論モデルをお勧めします。 config.iniファイルを変更して、`provider_name`をサポートされているプロバイダーに設定し、`provider_model``deepseek-r1:14b`に設定します。
必要なハードウェアについては、READMEの最後にある**FAQ**を参照してください。 注意: `deepseek-r1:14b`は例です。ハードウェアが許可する場合は、より大きなモデルを使用してください。
```sh ```sh
[MAIN] [MAIN]
is_local = True # ローカルで実行するかリモートプロバイダーを使用するか is_local = True
provider_name = ollama # またはlm-studio、openaiなど provider_name = ollama # または lm-studio、openai など
provider_model = deepseek-r1:14b # ハードウェアに互換性のあるモデルを選択 provider_model = deepseek-r1:14b
provider_server_address = 127.0.0.1:11434 provider_server_address = 127.0.0.1:11434
agent_name = Jarvis # AIの名前
recover_last_session = True # 前のセッションを復元
save_session = True # 現在のセッションを記憶
speak = False # テキスト読み上げ
listen = False # 音声認識、CLIのみ、実験的
jarvis_personality = False # より「Jarvis」的な性格を使用(実験的)
languages = en zh # 言語リスト、TTSはデフォルトでリストの最初を使用
[BROWSER]
headless_browser = True # ホストでCLIを使用する場合を除き変更しない
stealth_mode = True # 検出されにくいseleniumを使用してブラウザ検出を減らす
``` ```
**警告**: **ローカルプロバイダーのリスト**
- `config.ini`ファイル形式はコメントをサポートしていません。 | プロバイダー | ローカル? | 説明 |
コメントがエラーを引き起こすため、サンプル設定を直接コピー&ペーストしないでください。代わりに、コメントなしで希望の設定で`config.ini`ファイルを手動で変更してください。
- LM-studioを使用してLLMを実行する場合、provider_nameを`openai`に設定*しない*でください。`lm-studio`として使用してください。
- 一部のプロバイダー(例:lm-studio)では、IPの前に`http://`が必要です。例:`http://127.0.0.1:1234`
**ローカルプロバイダーリスト**
| プロバイダー | ローカル? | 説明 |
|-----------|--------|-----------------------------------------------------------| |-----------|--------|-----------------------------------------------------------|
| ollama | はい | ollamaを使用して簡単にローカルでLLMを実行 | | ollama | はい | ollamaをLLMプロバイダーとして使用してローカルでLLMを簡単に実行 |
| lm-studio | はい | LM studioローカルLLMを実行(`provider_name` = `lm-studio`に設定)| | lm-studio | はい | LM studioを使用してローカルLLMを実行(`provider_name``lm-studio`に設定)|
| openai | はい | OpenAI互換API(例:llama.cppサーバー)を使用 | | openai | はい | OpenAI互換APIを使用 |
次のステップ[サービスを起動してAgenticSeekを実行](#サービスを起動して実行) 次のステップ: [サービスを開始してAgenticSeekを実行する](#Start-services-and-Run)
*問題が発生し場合は、[トラブルシューティング](#トラブルシューティング)セクションを参照してください。* *問題が発生している場合は、**既知の問題**セクションを参照してください。*
*ハードウェアがローカルでLLMを実行できない場合は、[APIを使用した実行設定](#apiを使用した実行設定)を参照してください。*
*詳細な`config.ini`の説明については、[設定セクション](#設定)を参照してください。*
## APIを使用した実行設定 *ハードウェアがDeepseekをローカルで実行できない場合は、**APIを使用した実行**セクションを参照してください。*
この設定では、外部のクラウドベースのLLMプロバイダーを使用します。選択したサービスからAPIキーを取得する必要があります。 *詳細な設定ファイルの説明については、**設定**セクションを参照してください。*
**1. APIプロバイダーを選択し、APIキーを取得:**
以下の[APIプロバイダーリスト](#apiプロバイダーリスト)を参照してください。ウェブサイトにアクセスして登録し、APIキーを取得してください。
**2. APIキーを環境変数として設定:**
* **Linux/macOS:**
ターミナルを開き、`export`コマンドを使用します。永続的にするにはシェルの設定ファイル(例:`~/.bashrc`、`~/.zshrc`)に追加するのがベストです。
```sh
export PROVIDER_API_KEY="your_api_key_here"
# PROVIDER_API_KEYを特定の変数名に置き換えてください、例:OPENAI_API_KEY、GOOGLE_API_KEY
```
TogetherAIの例:
```sh
export TOGETHER_API_KEY="xxxxxxxxxxxxxxxxxxxxxx"
```
* **Windows:**
* **コマンドプロンプト(現在のセッション限定):**
```cmd
set PROVIDER_API_KEY=your_api_key_here
```
* **PowerShell(現在のセッション限定):**
```powershell
$env:PROVIDER_API_KEY="your_api_key_here"
```
* **永続的:** Windowsの検索バーで「環境変数」を検索し、「システムの環境変数を編集」をクリックしてから「環境変数...」ボタンをクリックします。適切な名前(例:`OPENAI_API_KEY`)とキーを値として新しいユーザー変数を追加します。
*(詳細については、FAQを参照してください:[APIキーを設定する方法?](#apiキーを設定する方法))。*
**3. `config.ini`を更新:**
```ini
[MAIN]
is_local = False
provider_name = openai # またはgoogle、deepseek、togetherAI、huggingface
provider_model = gpt-3.5-turbo # またはgemini-1.5-flash、deepseek-chat、mistralai/Mixtral-8x7B-Instruct-v0.1など
provider_server_address = # is_local = Falseの場合、ほとんどのAPIでは無視されるか空にできる
# ... その他の設定 ...
```
*警告:* configの値に末尾のスペースがないことを確認してください。
**APIプロバイダーリスト**
| プロバイダー | `provider_name` | ローカル? | 説明 | APIキーリンク(例) |
|--------------|-----------------|--------|---------------------------------------------------|---------------------------------------------|
| OpenAI | `openai` | いいえ | OpenAIのAPIを通じてChatGPTモデルを使用。 | [platform.openai.com/signup](https://platform.openai.com/signup) |
| Google Gemini| `google` | いいえ | Google AI Studioを通じてGoogle Geminiモデルを使用。 | [aistudio.google.com/keys](https://aistudio.google.com/keys) |
| Deepseek | `deepseek` | いいえ | 彼らのAPIを通じてDeepseekモデルを使用。 | [platform.deepseek.com](https://platform.deepseek.com) |
| Hugging Face | `huggingface` | いいえ | Hugging Face Inference APIのモデルを使用。 | [huggingface.co/settings/tokens](https://huggingface.co/settings/tokens) |
| TogetherAI | `togetherAI` | いいえ | TogetherAI APIを通じて様々なオープンソースモデルを使用。| [api.together.ai/settings/api-keys](https://api.together.ai/settings/api-keys) |
| OpenRouter | `openrouter` | いいえ | OpenRouter APIを通じて様々なオープンソースモデルを使用。| [openrouter.api](https://openrouter.ai/) |
*注:*
* 複雑なウェブブラウジングとタスクプランニングには`gpt-4o`や他のOpenAIモデルの使用は推奨しません。現在のプロンプト最適化はDeepseekなどのモデルを対象としているためです。
* コーディング/bashタスクはGeminiで失敗する可能性があります。Deepseek r1用に最適化されたプロンプト形式を無視する傾向があるためです。
* `is_local = False`の場合、`config.ini`の`provider_server_address`は通常使用されません。APIエンドポイントは通常、対応するプロバイダーのライブラリで処理されるためです。
次のステップ:[サービスを起動してAgenticSeekを実行](#サービスを起動して実行)
*問題が発生した場合は、**既知の問題**セクションを参照してください*
*詳細な設定ファイルの説明については、**設定セクション**を参照してください。*
--- ---
## サービスを起動して実行 ## APIを使用したセットアップ
デフォルトでは、AgenticSeekは完全にDocker内で実行されます `config.ini`で希望するプロバイダーを設定してください
**オプション1:** DockerでWebインターフェースを使用して実行:
必要なサービスを起動します。これにより、docker-compose.ymlのすべてのサービスが起動します:
- searxng
- redissearxngに必要)
- frontend
- backendWebインターフェースに`full`を使用する場合)
```sh ```sh
./start_services.sh full # MacOS [MAIN]
start start_services.cmd full # Windows is_local = False
provider_name = openai
provider_model = gpt-4o
provider_server_address = 127.0.0.1:5000
``` ```
**警告:** このステップではすべてのDockerイメージがダウンロードされロードされます。最大30分かかる場合があります。サービスを起動した後、メッセージを送信する前にバックエンドサービスが完全に実行されていることを確認してください(ログに**backend: "GET /health HTTP/1.1" 200 OK**が表示されるはずです)。初回実行時、バックエンドサービスは起動に5分かかる場合があります 警告: `config.ini`に末尾のスペースがないことを確認してください
ローカルのOpenAIベースのAPIを使用する場合は、`is_local`をTrueに設定してください。
OpenAIベースのAPIが独自のサーバーで実行されている場合は、IPアドレスを変更してください。
次のステップ: [サービスを開始してAgenticSeekを実行する](#Start-services-and-Run)
*問題が発生している場合は、**既知の問題**セクションを参照してください。*
*詳細な設定ファイルの説明については、**設定**セクションを参照してください。*
---
## サービスの開始と実行
必要に応じてPython環境をアクティブにしてください。
```sh
source agentic_seek_env/bin/activate
```
必要なサービスを開始します。これにより、docker-compose.ymlから以下のサービスがすべて開始されます:
- searxng
- redis (searxngに必要)
- フロントエンド
```sh
sudo ./start_services.sh # MacOS
start ./start_services.cmd # Windows
```
**オプション1:** CLIインターフェースで実行。
```sh
python3 cli.py
```
**オプション2:** Webインターフェースで実行。
注意: 現在、CLIの使用を推奨しています。Webインターフェースは開発中です。
バックエンドを開始します。
```sh
python3 api.py
```
`http://localhost:3000/`にアクセスすると、Webインターフェースが表示されます。 `http://localhost:3000/`にアクセスすると、Webインターフェースが表示されます。
*サービス起動のトラブルシューティング:* これらのスクリプトが失敗する場合は、Docker Engineが実行中でDocker ComposeV2、`docker compose`)が正しくインストールされていることを確認してください。ターミナル出力のエラーメッセージを確認してください。[FAQ: ヘルプ!AgenticSeekまたはそのスクリプトを実行するとエラーが発生します](#faq-トラブルシューティング)を参照してください。 現在、Webインターフェースではメッセージのストリーミングがサポートされていないことに注意してください。
**オプション2:** CLIモード:
CLIインターフェースで実行するには、ホストにパッケージをインストールする必要があります:
```sh
./install.sh
./install.bat # windows
```
次に、`config.ini`のSEARXNG_BASE_URLを以下に変更する必要があります:
```sh
SEARXNG_BASE_URL="http://localhost:8080"
```
必要なサービスを起動します。これにより、docker-compose.ymlの一部のサービスが起動します:
- searxng
- redissearxngに必要)
- frontend
```sh
./start_services.sh # MacOS
start start_services.cmd # Windows
```
実行:uv run: `uv run python -m ensurepip` でuvがpipを有効にしていることを確認します。
CLIを使用:`uv run cli.py`
--- ---
## 使用方法 ## 使い方
サービスが`./start_services.sh full`で実行されていることを確認し、`localhost:3000`にアクセスしてWebインターフェースを使用します。 警告: 現在、サポートされている言語は英語、中国語、フランス語のみです。他の言語でのプロンプトは機能しますが、適切なエージェントにルーティングされない場合があります。
`listen = True`を設定することで音声認識も使用できます。CLIモードのみ。 サービスが`./start_services.sh`で起動していることを確認し、`python3 cli.py`でagenticSeekを実行します。
終了するには、単に`goodbye`と言う/入力します。 ```sh
sudo ./start_services.sh
python3 cli.py
```
使用例: `>>> `と表示されます
これは、agenticSeekが指示を待っていることを示します。
configで`listen = True`を設定することで、音声認識を使用することもできます。
> *Pythonでスネークゲームを作って!* 終了するには、単に`goodbye`と言います。
> *ウェブでフランスのレンヌの最高のカフェを検索し、3つとその住所をrennes_cafes.txtに保存して* 以下は使用例です:
> *階乗を計算するGoプログラムを書き、factorial.goとしてワークスペースに保存して* ### コーディング/バッシュ
> *summer_picturesフォルダ内のすべてのJPGファイルを検索し、今日の日付で名前を変更し、名前変更されたファイルのリストをphotos_list.txtに保存して* > *Pythonでスネークゲームを作成*
> *オンラインで2024年の人気SF映画を検索し、今夜見るために3つ選び、movie_night.txtに保存して* > *C言語で行列の掛け算を教えて*
> *ウェブで2025年の最新AIニュース記事を検索し、3つ選び、タイトルと要約を抽出するPythonスクリプトを書き、スクリプトをnews_scraper.pyとして保存し、要約をai_news.txtに保存(/home/projects* > *Golangでブラックジャックを作成*
> *金曜日、無料の株価APIをウェブ検索し、supersuper7434567@gmail.comで登録し、APIを使用してテスラの日次株価を取得するPythonスクリプトを書き、結果をstock_prices.csvに保存して* ### ウェブ検索
*フォーム入力はまだ実験的であり、失敗する可能性があることに注意してください。* > *日本の最先端のAI研究を行っているクールなテックスタートアップを見つけるためにウェブ検索を行う*
クエリを入力すると、AgenticSeekが最適なエージェントをタスクに割り当てます。 > *agenticSeekを作成したのは誰かをインターネットで見つけることができますか?*
これは初期プロトタイプであるため、エージェントルーティングシステムは常にクエリに正しいエージェントを割り当てられるとは限りません。 > *オンラインの燃料計算機を使用して、ニースからミラノまでの旅行の費用を見積もることができますか?*
したがって、あなたが何を望んでいるか、そしてAIがどのように進めるかを非常に明確に表現する必要があります。例えば、ウェブ検索をしてほしい場合は、次のように言わないでください: ### ファイルシステム
`一人旅に適した国を知っていますか?` > *契約書.pdfがどこにあるか見つけてくれませんか?*
代わりに、次のように言ってください: > *ディスクにどれだけの空き容量があるか教えて*
`ウェブ検索を実行し、一人旅に最適な国を見つけてください` > *READMEを読んでプロジェクトを/home/path/projectにインストールしてください*
### カジュアル
> *フランスのレンヌについて教えて*
> *博士号を追求すべきですか?*
> *最高のワークアウトルーチンは何ですか?*
クエリを入力すると、agenticSeekはタスクに最適なエージェントを割り当てます。
これは初期のプロトタイプであるため、エージェントルーティングシステムはクエリに基づいて常に適切なエージェントを割り当てるとは限りません。
したがって、何を望んでいるか、AIがどのように進行するかについて非常に明確にする必要があります。たとえば、ウェブ検索を行いたい場合は、次のように言わないでください:
`一人旅に良い国を知っていますか?`
代わりに、次のように尋ねてください:
`ウェブ検索を行い、一人旅に最適な国を見つけてください`
--- ---
## **独自のサーバーでLLMを実行する設定** ## **ボーナス: 自分のサーバーでLLMを実行するためのセットアップ**
強力なコンピューターやアクセス可能なサーバーを持っているが、ラップトップから使用したい場合は、カスタムllmサーバーを使用してリモートサーバーでLLMを実行することを選択できます。 強力なコンピュータサーバーを持っていて、それをラップトップから使用したい場合リモートサーバーでLLMを実行するオプションがあります。
AIモデルを実行する「サーバー」で、IPアドレスを取得します AIモデルを実行する「サーバー」で、IPアドレスを取得します
```sh ```sh
ip a | grep "inet " | grep -v 127.0.0.1 | awk '{print $2}' | cut -d/ -f1 # ローカルIP ip a | grep "inet " | grep -v 127.0.0.1 | awk '{print $2}' | cut -d/ -f1 # ローカルIP
curl https://ipinfo.io/ip # パブリックIP curl https://ipinfo.io/ip # 公開IP
``` ```
注:WindowsまたはmacOSでは、IPアドレスを見つけるためにipconfigまたはifconfigを使用してください。 注意: WindowsまたはmacOSの場合、IPアドレスを見つけるには、それぞれ`ipconfig`または`ifconfig`を使用してください。
リポジトリをクローンし、`server/`フォルダに移動します。 リポジトリをクローンし、`server/`フォルダに移動します。
```sh ```sh
git clone --depth 1 https://github.com/Fosowl/agenticSeek.git git clone --depth 1 https://github.com/Fosowl/agenticSeek.git
cd agenticSeek/llm_server/ cd agenticSeek/server/
``` ```
サーバー固有の要件をインストールします サーバー固有の依存関係をインストールします:
```sh ```sh
pip3 install -r requirements.txt pip3 install -r requirements.txt
@@ -370,11 +306,11 @@ pip3 install -r requirements.txt
python3 app.py --provider ollama --port 3333 python3 app.py --provider ollama --port 3333
``` ```
LLMサービスとして`ollama`と`llamacpp`のどちらを使用するか選択できます。 `ollama``llamacpp`のどちらかをLLMサービスとして選択できます。
次に、あなたのパーソナルコンピューターで: 次に、個人用コンピュータで以下を行います:
`config.ini`ファイルを変更して、`provider_name`を`server`に、`provider_model`を`deepseek-r1:xxb`に設定します。 `config.ini`ファイルを変更し`provider_name``server`に、`provider_model``deepseek-r1:xxb`に設定します。
`provider_server_address`をモデルを実行するマシンのIPアドレスに設定します。 `provider_server_address`をモデルを実行するマシンのIPアドレスに設定します。
```sh ```sh
@@ -382,246 +318,135 @@ LLMサービスとして`ollama`と`llamacpp`のどちらを使用するか選
is_local = False is_local = False
provider_name = server provider_name = server
provider_model = deepseek-r1:70b provider_model = deepseek-r1:70b
provider_server_address = http://x.x.x.x:3333 provider_server_address = x.x.x.x:3333
``` ```
次のステップ[サービスを起動してAgenticSeekを実行](#サービスを起動して実行) 次のステップ: [サービスを開始してAgenticSeekを実行する](#Start-services-and-Run)
--- ---
## 音声認識 ## 音声認識
警告:現在、音声認識はCLIモードでのみ機能します 現在、音声認識は英語でのみ動作することに注意してください
現在、音声認識は英語でのみ機能することに注意してください。 音声認識機能はデフォルトで無効になっています。有効にするには、config.iniファイルでlistenオプションをTrueに設定します:
音声認識機能はデフォルトで無効になっています。有効にするには、config.iniファイルでlistenオプションをTrueに設定します:
``` ```
listen = True listen = True
``` ```
有効にすると、音声認識機能はトリガーワード、つまりエージェントの名前をリッスンし、その後入力を処理し始めます。*config.ini*ファイルの`agent_name`値を更新することでエージェントの名前をカスタマイズできます 有効にすると、音声認識機能はトリガーキーワードエージェントの名前)を待ちます。その後入力を処理します。エージェントの名前は*config.ini*ファイルの`agent_name`値を更新することでカスタマイズできます:
``` ```
agent_name = Friday agent_name = Friday
``` ```
最高の認識のためには、エージェント名として「John」や「Emma」などの一般的な英語名を使用することをお勧めします。 最適な認識のために、"John"や"Emma"のような一般的な英語の名前をエージェント名として使用することをお勧めします。
文字起こしが表示され始めたら、エージェントの名前を大声で言って起動します(例:Friday)。 トランスクリプトが表示され始めたら、エージェントの名前を大声で言って起動します(例:"Friday")。
クエリを明確に言います。 クエリを明確に話します。
確認フレーズでリクエストを終了してシステムに続行するように指示します。確認フレーズの例 リクエストを終了する際に確認フレーズを使用してシステムに進行を通知します。確認フレーズの例には次のようなものがあります:
``` ```
"do it", "go ahead", "execute", "run", "start", "thanks", "would ya", "please", "okay?", "proceed", "continue", "go on", "do that", "go it", "do you understand?" "do it", "go ahead", "execute", "run", "start", "thanks", "would ya", "please", "okay?", "proceed", "continue", "go on", "do that", "go it", "do you understand?"
``` ```
## 設定 ## 設定
設定例 設定例:
``` ```
[MAIN] [MAIN]
is_local = True is_local = True
provider_name = ollama provider_name = ollama
provider_model = deepseek-r1:32b provider_model = deepseek-r1:1.5b
provider_server_address = http://127.0.0.1:11434 # Ollama例;LM-Studioはhttp://127.0.0.1:1234を使用 provider_server_address = 127.0.0.1:11434
agent_name = Friday agent_name = Friday
recover_last_session = False recover_last_session = False
save_session = False save_session = False
speak = False speak = False
listen = False listen = False
work_dir = /Users/mlg/Documents/ai_folder
jarvis_personality = False jarvis_personality = False
languages = en zh # TTSおよび潜在的なルーティングの言語リスト。 languages = en ja
[BROWSER] [BROWSER]
headless_browser = False headless_browser = False
stealth_mode = False stealth_mode = False
``` ```
**`config.ini`設定の説明** **説明**:
* **`[MAIN]`セクション:** - is_local -> エージェントをローカルで実行する(True)か、リモートサーバーで実行する(False)。
* `is_local`: ローカルLLMプロバイダー(Ollama、LM-Studio、ローカルOpenAI互換サーバー)またはセルフホストサーバーオプションを使用する場合は`True`。クラウドベースのAPI(OpenAI、Googleなど)を使用する場合は`False` - provider_name -> 使用するプロバイダー(`ollama``server``lm-studio``deepseek-api`のいずれか)
* `provider_name`: LLMプロバイダーを指定します - provider_model -> 使用するモデル、例: deepseek-r1:1.5b
* ローカルオプション:`ollama`、`lm-studio`、`openai`(ローカルOpenAI互換サーバー用)、`server`(セルフホストサーバー設定用) - provider_server_address -> サーバーアドレス、例: 127.0.0.1:11434(ローカルの場合)。非ローカルAPIの場合は何でも設定できます
* APIオプション:`openai`、`google`、`deepseek`、`huggingface`、`togetherAI` - agent_name -> エージェントの名前、例: Friday。TTSのトリガーワードとして使用されます
* `provider_model`: 選択したプロバイダーの特定のモデル名またはID(例:Ollamaの`deepseekcoder:6.7b`、OpenAI APIの`gpt-3.5-turbo`、TogetherAIの`mistralai/Mixtral-8x7B-Instruct-v0.1`)。 - recover_last_session -> 最後のセッションから再開する(True)か、しない(False)。
* `provider_server_address`: あなたのLLMプロバイダーのアドレス - save_session -> セッションデータを保存する(True)か、しない(False)
* ローカルプロバイダー用:例:Ollamaの`http://127.0.0.1:11434`、LM-Studioの`http://127.0.0.1:1234` - speak -> 音声出力を有効にする(True)か、しない(False)
* `server`プロバイダータイプ用:あなたのセルフホストLLMサーバーのアドレス(例:`http://your_server_ip:3333`)。 - listen -> 音声入力を有効にする(True)か、しない(False)。
* クラウドAPI用(`is_local = False`):これは通常無視されるか空にできます。APIエンドポイントは通常クライアントライブラリで処理されるためです - work_dir -> AIがアクセスするフォルダー。例: /Users/user/Documents/
* `agent_name`: AIアシスタントの名前(例:Friday)。有効な場合、音声認識のトリガーワードとして使用されます。 - jarvis_personality -> JARVISのようなパーソナリティを使用する(True)か、しない(False)。これは単にプロンプトファイルを変更するだけです。
* `recover_last_session`: `True`は前のセッションの状態を復元しようとし、`False`は最初から開始します - headless_browser -> ウィンドウを表示せずにブラウザを実行する(True)か、しない(False)
* `save_session`: `True`は現在のセッションの状態を潜在的な復元用に保存し、`False`はしません - stealth_mode -> ボット検出を難しくします。唯一の欠点は、anticaptcha拡張機能を手動でインストールする必要があることです
* `speak`: `True`はテキスト読み上げ音声出力を有効にし、`False`は無効にします。 - languages -> List of supported languages. Required for agent routing system. The longer the languages list the more model will be downloaded.
* `listen`: `True`は音声認識音声入力を有効にし(CLIモードのみ)、`False`は無効にします。
* `work_dir`: **重要:** AgenticSeekがファイルを読み書きするディレクトリ。**このパスがシステムで有効かつアクセス可能であることを確認してください。**
* `jarvis_personality`: `True`はより「Jarvis-like」なシステムプロンプトを使用(実験的)、`False`は標準プロンプトを使用。
* `languages`: カンマ区切りの言語リスト(例:`en, zh, fr`)。TTS音声選択(デフォルトは最初)に使用され、LLMルーターを支援できます。ルーターの非効率性を避けるため、多すぎる言語や非常に類似した言語の使用は避けてください。
* **`[BROWSER]`セクション:**
* `headless_browser`: `True`は可視ウィンドウなしで自動化ブラウザを実行(Webインターフェースまたは非対話的使用に推奨)。`False`はブラウザウィンドウを表示(CLIモードまたはデバッグに有用)。
* `stealth_mode`: `True`はブラウザ自動化の検出を困難にする措置を有効にします。anticaptchaなどのブラウザ拡張機能の手動インストールが必要な場合があります。
このセクションはサポートされているLLMプロバイダータイプをまとめています。`config.ini`で設定します。 ## プロバイダー
**ローカルプロバイダー(独自のハードウェアで実行):** 以下の表は利用可能なプロバイダーを示しています:
| config.iniのプロバイダー | `is_local` | 説明 | 設定セクション | | プロバイダー | ローカル? | 説明 |
|-------------------------------|------------|-----------------------------------------------------------------------------|------------------------------------------------------------------| |-----------|--------|-----------------------------------------------------------|
| `ollama` | `True` | Ollamaを使用してローカルでLLMを簡単に提供。 | [マシン上でローカルにLLMを実行する設定](#マシン上でローカルにllmを実行する設定) | | ollama | はい | ollamaをLLMプロバイダーとして使用してローカルでLLMを簡単に実行 |
| `lm-studio` | `True` | LM-StudioでローカルにLLMを提供。 | [マシン上でローカルにLLMを実行する設定](#マシン上でローカルにllmを実行する設定) | | server | はい | モデルを別のマシンでホストし、ローカルマシンで実行 |
| `openai`(ローカルサーバー用) | `True` | OpenAI互換APIを公開するローカルサーバー(例:llama.cpp)に接続。 | [マシン上でローカルLLMを実行する設定](#マシン上でローカルにllmを実行する設定) | | lm-studio | はい | LM studio`lm-studio`)を使用してローカルLLMを実行 |
| `server` | `False` | 別のマシンで実行されているAgenticSeekセルフホストLLMサーバーに接続。 | [独自のサーバーでLLMを実行する設定](#独自のサーバーでllmを実行する設定) | | openai | 場合による | ChatGPT API(非プライベート)またはopenai互換APIを使用 |
| deepseek-api | いいえ | Deepseek API(非プライベート) |
| huggingface| いいえ | Hugging-Face API(非プライベート) |
| togetherAI | いいえ | together AI API(非プライベート)を使用
**APIプロバイダー(クラウドベース):**
| config.iniのプロバイダー名 | `is_local` | 説明 | 設定セクション | プロバイダーを選択するには、config.iniを変更します:
|-------------------------------|------------|--------------------------------------------------|-----------------------------------------------------|
| `openai` | `False` | OpenAIの公式API(例:GPT-3.5、GPT-4)を使用。 | [APIを使用した実行設定](#apiを使用した実行設定) |
| `google` | `False` | APIを通じてGoogleのGeminiモデルを使用。 | [APIを使用した実行設定](#apiを使用した実行設定) |
| `deepseek` | `False` | Deepseekの公式APIを使用。 | [APIを使用した実行設定](#apiを使用した実行設定) |
| `huggingface` | `False` | Hugging Face Inference APIを使用。 | [APIを使用した実行設定](#apiを使用した実行設定) |
| `togetherAI` | `False` | TogetherAIのAPIを通じて様々なオープンモデルを使用。 | [APIを使用した実行設定](#apiを使用した実行設定) |
--- ```
## トラブルシューティング is_local = False
provider_name = openai
provider_model = gpt-4o
provider_server_address = 127.0.0.1:5000
```
`is_local`: ローカルで実行されるLLMの場合はTrue、それ以外の場合はFalse。
問題が発生した場合、このセクションはガイダンスを提供します `provider_name`: 使用するプロバイダーを名前で選択します。上記のプロバイダーリストを参照してください
`provider_model`: エージェントが使用するモデルを設定します。
`provider_server_address`: サーバープロバイダーを使用しない場合は何でも設定できます。
# 既知の問題 # 既知の問題
## ChromeDriverの問題 ## Chromedriverの問題
**エラー例:** `SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version XXX` **既知のエラー#1:** *chromedriverの不一致*
### 根本原因
ChromeDriverのバージョン非互換性は以下で発生します:
1. インストールしたChromeDriverのバージョンがChromeブラウザのバージョンと一致しない
2. Docker環境では、`undetected_chromedriver`が独自のChromeDriverバージョンをダウンロードし、マウントされたバイナリを回避する可能性がある
### 解決手順
#### 1. Chromeのバージョンを確認
Google Chromeを開く → `設定 > Chromeについて`でバージョンを確認(例:「バージョン 134.0.6998.88」)
#### 2. 一致するChromeDriverをダウンロード
**Chrome 115以降の場合:** [Chrome for Testing API](https://googlechromelabs.github.io/chrome-for-testing/)を使用
- Chrome for Testingの可用性ダッシュボードにアクセス
- あなたのChromeバージョンまたは最も近い利用可能な一致を見つける
- オペレーティングシステム用のChromeDriverをダウンロード(Docker環境ではLinux64を使用)
**古いChromeバージョンの場合:** [レガシーChromeDriverダウンロード](https://chromedriver.chromium.org/downloads)を使用
![Chrome for TestingからChromeDriverをダウンロード](./media/chromedriver_readme.png)
#### 3. ChromeDriverをインストール(方法を選択)
**方法A:プロジェクトルートディレクトリ(Docker推奨)**
```bash
# ダウンロードしたchromedriverバイナリをプロジェクトルートディレクトリに配置
cp path/to/downloaded/chromedriver ./chromedriver
chmod +x ./chromedriver # Linux/macOSで実行可能にする
```
**方法B:システムPATH**
```bash
# Linux/macOS
sudo mv chromedriver /usr/local/bin/
sudo chmod +x /usr/local/bin/chromedriver
# Windows: chromedriver.exeをPATH内のフォルダに配置
```
#### 4. インストールを確認
```bash
# ChromeDriverのバージョンをテスト
./chromedriver --version
# またはPATHにある場合:
chromedriver --version
```
### Docker固有の指示
⚠️ **Dockerユーザーへの重要:**
- Dockerボリュームマウント方法はステルスモード(`undetected_chromedriver`)では機能しない可能性があります
- **解決策:** ChromeDriverをプロジェクトルートディレクトリに`./chromedriver`として配置
- アプリケーションが自動的に検出し、このバイナリを使用します
- ログに次のメッセージが表示されるはずです:`"Using ChromeDriver from project root: ./chromedriver"`
### トラブルシューティングのヒント
1. **まだバージョンの不一致が発生しますか?**
- ChromeDriverが実行可能か確認:`ls -la ./chromedriver`
- ChromeDriverのバージョンを確認:`./chromedriver --version`
- Chromeブラウザのバージョンと一致することを確認
2. **Dockerコンテナの問題ですか?**
- バックエンドログを確認:`docker logs backend`
- メッセージを探す:`"Using ChromeDriver from project root"`
- 見つからない場合は、ファイルが存在し実行可能であることを確認
3. **Chrome for Testingのバージョン**
- 可能な限り完全一致を使用
- バージョン134.0.6998.88の場合、ChromeDriver 134.0.6998.165を使用(最も近い利用可能バージョン)
- メジャーバージョン番号は一致する必要があります(134 = 134)
### バージョン互換性マトリックス
| Chromeバージョン | ChromeDriverバージョン | ステータス |
|----------------|---------------------|---------|
| 134.0.6998.x | 134.0.6998.165 | ✅ 利用可能 |
| 133.0.6943.x | 133.0.6943.141 | ✅ 利用可能 |
| 132.0.6834.x | 132.0.6834.159 | ✅ 利用可能 |
*最新の互換性については、[Chrome for Testingダッシュボード](https://googlechromelabs.github.io/chrome-for-testing/)を確認*
`Exception: Failed to initialize browser: Message: session not created: This version of ChromeDriver only supports Chrome version 113 `Exception: Failed to initialize browser: Message: session not created: This version of ChromeDriver only supports Chrome version 113
Current browser version is 134.0.6998.89 with binary path` Current browser version is 134.0.6998.89 with binary path`
ブラウザとchromedriverのバージョンが一致しない場合に発生します。 これは、ブラウザとchromedriverのバージョンが一致しない場合に発生します。
最新バージョンをダウンロードする必要があります: 最新バージョンをダウンロードするには、次のリンクにアクセスしてください:
https://developer.chrome.com/docs/chromedriver/downloads https://developer.chrome.com/docs/chromedriver/downloads
Chromeバージョン115以降を使用している場合は、以下にアクセス: Chromeバージョン115以降を使用している場合は、次のリンクにアクセスしてください:
https://googlechromelabs.github.io/chrome-for-testing/ https://googlechromelabs.github.io/chrome-for-testing/
オペレーティングシステムに一致するchromedriverバージョンをダウンロードします。 お使いのOSに対応するchromedriverバージョンをダウンロードします。
![alt text](./media/chromedriver_readme.png) ![alt text](./media/chromedriver_readme.png)
このセクションが不完全な場合は、issueを開いてください。 このセクションが不完全な場合は、問題を報告してください。
## 接続アダプターの問題
```
Exception: Provider lm-studio failed: HTTP request failed: No connection adapters were found for '127.0.0.1:1234/v1/chat/completions'`(注:ポートは異なる場合があります)
```
* **原因:** `config.ini`の`lm-studio`(または他の類似のローカルOpenAI互換サーバー)の`provider_server_address`に`http://`プレフィックスが欠けているか、間違ったポートを指している。
* **解決策:**
* アドレスに`http://`が含まれていることを確認。LM-Studioは通常デフォルトで`http://127.0.0.1:1234`を使用。
* 正しい`config.ini``provider_server_address = http://127.0.0.1:1234`(または実際のLM-Studioサーバーポート)。
## SearxNGベースURLが提供されていない
```
raise ValueError("SearxNG base URL must be provided either as an argument or via the SEARXNG_BASE_URL environment variable.")
ValueError: SearxNG base URL must be provided either as an argument or via the SEARXNG_BASE_URL environment variable.`
```
間違ったsearxngベースURLでCLIモードを実行すると発生する可能性があります。
SEARXNG_BASE_URLは、Dockerで実行するかホストで実行するかによって異なります:
**ホストで実行:** `SEARXNG_BASE_URL="http://localhost:8080"`
**完全にDocker内で実行(Webインターフェース):** `SEARXNG_BASE_URL="http://searxng:8080"`
## FAQ ## FAQ
@@ -629,55 +454,35 @@ SEARXNG_BASE_URLは、Dockerで実行するかホストで実行するかによ
| モデルサイズ | GPU | コメント | | モデルサイズ | GPU | コメント |
|-----------|--------|-----------------------------------------------------------| |-----------|--------|-----------------------------------------------------------|
| 7B | 8GB VRAM | ⚠️ 推奨。パフォーマンスが低く、頻繁幻覚、計画エージェントが失敗する可能性があります。 | | 7B | 8GB VRAM | ⚠️ 推奨されません。パフォーマンスが低く、頻繁幻覚を起こし、プランナーエージェントが失敗する可能性が高いです。 |
| 14B | 12 GB VRAM(例:RTX 3060 | ✅ 単なタスクに使用可能。ウェブブラウジングとタスク計画に困難がある可能性があります。 | | 14B | 12GB VRAM (例: RTX 3060) | ✅ 単なタスクに使用可能です。ウェブブラウジングや計画タスクには苦労する可能性があります。 |
| 32B | 24+ GB VRAM(例:RTX 4090 | 🚀 ほとんどのタスクで成功、タスク計画にまだ困難がある可能性があります | | 32B | 24GB以上のVRAM (例: RTX 4090) | 🚀 ほとんどのタスクで成功しますが、タスク計画にまだ苦労する可能性があります |
| 70B+ | 48+ GB VRAM | 💪 優れています。高度な使用例に推奨。 | | 70B+ | 48GB以上のVRAM (例: Mac Studio) | 💪 優れた性能。高度なユースケースに推奨されます。 |
**Q: エラーが発生したらどうすればよいですか?** **Q: なぜ他のモデルではなくDeepseek R1を選ぶのですか?**
ローカルが実行されていること(`ollama serve`)、`config.ini`がプロバイダーと一致していること、依存関係がインストールされていることを確認してください。どれも機能しない場合は、遠慮なくissueを開いてください Deepseek R1は、そのサイズに対して推論とツールの使用に優れています。私たちのニーズに最適だと考えています。他のモデルも問題なく動作しますが、Deepseekが私たちの主な選択です
**Q: `cli.py`を実行するとエラーが発生します。どうすればよいですか?**
Ollamaが実行中であることを確認してください(`ollama serve`)、`config.ini`がプロバイダーに一致していること、および依存関係がインストールされていることを確認してください。それでも解決しない場合は、問題を報告してください。
**Q: 本当に100%ローカルで実行できますか?** **Q: 本当に100%ローカルで実行できますか?**
はい、Ollama、lm-studio、またはserverプロバイダーを使用すると、すべての音声認識、LLM、テキスト読み上げモデルがローカルで実行されます。非ローカルオプション(OpenAI或其他API)はオプションです。 はい、OllamaまたはServerプロバイダーを使用すると、すべての音声認識、LLM、および音声合成モデルがローカルで実行されます。非ローカルオプション(OpenAIまたは他のAPI)はオプションです。
**Q: Manusがあるのに、なぜAgenticSeekを使用する必要がありますか?** **Q: Manusを持っているのに、なぜAgenticSeekを使用する必要があるのですか?**
Manusとは異なり、AgenticSeekは外部システムからの独立性を優先し、より多くの制御、プライバシー、APIコストの回避を提供します。 これは、AIエージェントに関する興味から始まったサイドプロジェクトです。特別な点は、ローカルモデルを使用し、APIを避けることです。
私たちは、JarvisやFriday(アイアンマン映画)からインスピレーションを得て、「クール」にしようとしましたが、機能性に関してはManusから多くのインスピレーションを得ています。なぜなら、人々が最初に求めているのはローカルのManusの代替品だからです。
**Q: このプロジェクトの背後には誰がいますか?** Manusとは異なり、AgenticSeekは外部システムからの独立性を優先し、より多くの制御、プライバシーを提供し、APIのコストを回避します。
このプロジェクトは私によって作成され、2人の友人がメンテナーとして、GitHub上のオープンソースコミュニティの貢献者と共に運営されています。私たちは単なる情熱的な個人であり、スタートアップではなく、どの組織にも所属していません。
私の個人アカウント(https://x.com/Martin993886460)以外のX上のAgenticSeekアカウントはすべて偽物です。
## 貢献 ## 貢献
AgenticSeekを改善する開発者を探しています!オープンなissueやディスカッションを確認してください。 AgenticSeekを改善するための開発者を探しています!オープンな問題やディスカッションを確認してください。
[貢献ガイド](./docs/CONTRIBUTING.md)
## スポンサー:
フライト検索、旅行計画、または最高の買い物のお得な情報の取得などの機能でAgenticSeekの能力を向上させたいですか?SerpApiを使用してカスタムツールを作成し、より多くのJarvisのような機能を解放することを検討してください。SerpApiを使用すると、プロフェッショナルなタスクのためにエージェントを加速させながら、完全な制御を維持できます。
<a href="https://serpapi.com/"><img src="./media/banners/sponsor_banner_serpapi.png" height="350" alt="SerpApi Banner" ></a>
[Contributing.md](./docs/CONTRIBUTING.md)をチェックして、カスタムツールを統合する方法を学びましょう!
### **スポンサー**
- [tatra-labs](https://github.com/tatra-labs)
## メンテナー:
> [Fosowl](https://github.com/Fosowl) | パリ時間
> [antoineVIVIES](https://github.com/antoineVIVIES) | 台北時間
## 特別な感謝:
> [tcsenpai](https://github.com/tcsenpai) と [plitc](https://github.com/plitc) がバックエンドのDocker化を支援
[![Star History Chart](https://api.star-history.com/svg?repos=Fosowl/agenticSeek&type=Date)](https://www.star-history.com/#Fosowl/agenticSeek&Date) [![Star History Chart](https://api.star-history.com/svg?repos=Fosowl/agenticSeek&type=Date)](https://www.star-history.com/#Fosowl/agenticSeek&Date)
## 著者:
> [Fosowl](https://github.com/Fosowl)
> [steveh8758](https://github.com/steveh8758)
-682
View File
@@ -1,682 +0,0 @@
# AgenticSeek: Uma Alternativa Privada e Local ao Manus
<p align="center">
<img align="center" src="./media/agentic_seek_logo.png" width="300" height="300" alt="Agentic Seek Logo">
<p>
English | [中文](./README_CHS.md) | [繁體中文](./README_CHT.md) | [Français](./README_FR.md) | [日本語](./README_JP.md) | [Português (Brasil)](./README_PTBR.md) | [Español](./README_ES.md)
*Um assistente de IA com reconhecimento de voz que é uma **alternativa 100% local ao Manus AI**, navega autonomamente na web, escreve código e planeja tarefas enquanto mantém todos os dados no seu dispositivo. Projetado para modelos de raciocínio local, funciona inteiramente no seu hardware, garantindo total privacidade e zero dependência de nuvem.*
[![Visitar AgenticSeek](https://img.shields.io/static/v1?label=Website&message=AgenticSeek&color=blue&style=flat-square)](https://fosowl.github.io/agenticSeek.html) ![License](https://img.shields.io/badge/license-GPL--3.0-green) [![Discord](https://img.shields.io/badge/Discord-Join%20Us-7289DA?logo=discord&logoColor=white)](https://discord.gg/8hGDaME3TC) [![Twitter](https://img.shields.io/twitter/url/https/twitter.com/fosowl.svg?style=social&label=Update%20%40Fosowl)](https://x.com/Martin993886460) [![GitHub stars](https://img.shields.io/github/stars/Fosowl/agenticSeek?style=social)](https://github.com/Fosowl/agenticSeek/stargazers)
### Por que escolher o AgenticSeek?
* 🔒 Totalmente Local & Privado - Tudo funciona na sua máquina, sem nuvem, sem compartilhamento de dados. Seus arquivos, conversas e pesquisas permanecem privados.
* 🌐 Navegação Web Inteligente - O AgenticSeek pode navegar na Internet autonomamente: pesquisar, ler, extrair informações, preencher formulários web, tudo sem intervenção manual.
* 💻 Assistente de Programação Autônomo - Precisa de código? Ele pode escrever, depurar e executar programas em Python, C, Go, Java e muito mais, sem supervisão.
* 🧠 Seleção Inteligente de Agentes - Você pergunta, ele escolhe automaticamente o melhor agente para a tarefa. Como ter uma equipe de especialistas sempre disponível.
* 📋 Planeja e Executa Tarefas Complexas - Desde o planejamento de viagens até projetos complexos, ele pode decompor grandes tarefas em etapas e completá-las usando múltiplos agentes de IA.
* 🎙️ Suporte de Voz - Voz clara, rápida e futurista com reconhecimento de voz, permitindo que você converse como com sua IA pessoal de filme de ficção científica. (Em desenvolvimento)
### **Demo**
> *Você pode pesquisar o projeto agenticSeek, aprender quais habilidades são necessárias e, em seguida, abrir CV_candidates.zip e me dizer quais correspondem melhor ao projeto?*
https://github.com/user-attachments/assets/b8ca60e9-7b3b-4533-840e-08f9ac426316
Aviso: Esta demonstração e todos os arquivos que aparecem (ex: CV_candidates.zip) são totalmente fictícios. Não somos uma empresa, estamos procurando contribuidores de código aberto, não candidatos.
> 🛠⚠️ **Trabalho Ativo em Andamento**
> 🙏 Este projeto começou como um projeto paralelo e não tem roadmap nem financiamento. Cresceu muito além das expectativas ao aparecer no GitHub Trending. Contribuições, comentários e paciência são profundamente apreciados.
## Pré-requisitos
Antes de começar, certifique-se de ter instalado:
* **Git:** Para clonar o repositório. [Baixar Git](https://git-scm.com/downloads)
* **Python 3.10.x:** Python 3.10.x é altamente recomendado. Outras versões podem causar erros de dependência. [Baixar Python 3.10](https://www.python.org/downloads/release/python-3100/) (selecione a versão 3.10.x).
* **Docker Engine & Docker Compose:** Para executar serviços empacotados como SearxNG.
* Instalar Docker Desktop (inclui Docker Compose V2): [Windows](https://docs.docker.com/desktop/install/windows-install/) | [Mac](https://docs.docker.com/desktop/install/mac-install/) | [Linux](https://docs.docker.com/desktop/install/linux-install/)
* Ou instalar Docker Engine e Docker Compose separadamente no Linux: [Docker Engine](https://docs.docker.com/engine/install/) | [Docker Compose](https://docs.docker.com/compose/install/) (certifique-se de instalar Compose V2, por exemplo `sudo apt-get install docker-compose-plugin`).
### 1. **Clonar o repositório e configurar**
```sh
git clone https://github.com/Fosowl/agenticSeek.git
cd agenticSeek
mv .env.example .env
```
### 2. Modificar o conteúdo do arquivo .env
```sh
SEARXNG_BASE_URL="http://searxng:8080" # Se você executar no modo CLI no host, use http://127.0.0.1:8080
REDIS_BASE_URL="redis://redis:6379/0"
WORK_DIR="/Users/mlg/Documents/workspace_for_ai"
OLLAMA_PORT="11434"
LM_STUDIO_PORT="1234"
CUSTOM_ADDITIONAL_LLM_PORT="11435"
OPENAI_API_KEY='optional'
DEEPSEEK_API_KEY='optional'
OPENROUTER_API_KEY='optional'
TOGETHER_API_KEY='optional'
GOOGLE_API_KEY='optional'
ANTHROPIC_API_KEY='optional'
```
Atualize o arquivo `.env` conforme necessário:
- **SEARXNG_BASE_URL**: Mantenha inalterado, a menos que você execute no modo CLI no host.
- **REDIS_BASE_URL**: Mantenha inalterado
- **WORK_DIR**: Caminho para o diretório de trabalho local. O AgenticSeek poderá ler e interagir com esses arquivos.
- **OLLAMA_PORT**: Número da porta para o serviço Ollama.
- **LM_STUDIO_PORT**: Número da porta para o serviço LM Studio.
- **CUSTOM_ADDITIONAL_LLM_PORT**: Porta para qualquer serviço LLM personalizado adicional.
**As chaves de API são completamente opcionais para aqueles que optam por executar LLM localmente, que é o objetivo principal deste projeto. Deixe-as vazias se você tiver hardware suficiente.**
### 3. **Iniciar o Docker**
Certifique-se de que o Docker está instalado e funcionando no seu sistema. Você pode iniciar o Docker com os seguintes comandos:
- **Linux/macOS:**
Abra um terminal e execute:
```sh
sudo systemctl start docker
```
Ou inicie o Docker Desktop a partir do menu de aplicativos, se instalado.
- **Windows:**
Inicie o Docker Desktop a partir do menu Iniciar.
Você pode verificar se o Docker está funcionando executando:
```sh
docker info
```
Se você vir informações sobre sua instalação do Docker, ele está funcionando corretamente.
Consulte a [Lista de provedores locais](#lista-de-provedores-locais) abaixo para um resumo.
Próxima etapa: [Executar o AgenticSeek localmente](#iniciar-os-serviços-e-executar)
*Se você encontrar problemas, consulte a seção [Solução de problemas](#solução-de-problemas).*
*Se seu hardware não puder executar LLM localmente, consulte [Configuração para executar com uma API](#configuração-para-executar-com-uma-api).*
*Para explicações detalhadas do `config.ini`, consulte a [seção Configuração](#configuração).*
---
## Configuração para executar LLM localmente na sua máquina
**Requisitos de hardware:**
Para executar LLM localmente, você precisará de hardware suficiente. No mínimo, uma GPU capaz de executar Magistral, Qwen ou Deepseek 14B é necessária. Consulte o FAQ para recomendações detalhadas de modelo/desempenho.
**Configure seu provedor local**
Inicie seu provedor local, por exemplo com ollama:
```sh
ollama serve
```
Consulte a lista de provedores locais suportados abaixo.
**Atualizar config.ini**
Altere o arquivo config.ini para definir provider_name como um provedor suportado e provider_model como um LLM suportado pelo seu provedor. Recomendamos modelos de raciocínio como *Magistral* ou *Deepseek*.
Consulte o **FAQ** no final do README para o hardware necessário.
```sh
[MAIN]
is_local = True # Se você está executando localmente ou com um provedor remoto.
provider_name = ollama # ou lm-studio, openai, etc.
provider_model = deepseek-r1:14b # escolha um modelo compatível com seu hardware
provider_server_address = 127.0.0.1:11434
agent_name = Jarvis # o nome da sua IA
recover_last_session = True # recuperar a sessão anterior
save_session = True # memorizar a sessão atual
speak = False # texto para fala
listen = False # fala para texto, apenas para CLI, experimental
jarvis_personality = False # usar uma personalidade mais "Jarvis" (experimental)
languages = en zh # Lista de idiomas, TTS usará o primeiro da lista por padrão
[BROWSER]
headless_browser = True # mantenha inalterado, a menos que use CLI no host.
stealth_mode = True # Use selenium indetectável para reduzir a detecção do navegador
```
**Aviso**:
- O formato do arquivo `config.ini` não suporta comentários.
Não copie e cole diretamente a configuração de exemplo, pois os comentários causarão erros. Em vez disso, modifique manualmente o arquivo `config.ini` com sua configuração desejada, sem comentários.
- *NÃO* defina provider_name como `openai` se você estiver usando LM-studio para executar LLM. Use-o como `lm-studio`.
- Alguns provedores (ex: lm-studio) exigem `http://` antes do IP. Exemplo: `http://127.0.0.1:1234`
**Lista de provedores locais**
| Provedor | Local ? | Descrição |
|-----------|--------|-----------------------------------------------------------|
| ollama | Sim | Executa LLM localmente facilmente usando ollama |
| lm-studio | Sim | Executa LLM localmente com LM studio (defina `provider_name` = `lm-studio`)|
| openai | Sim | Use uma API compatível com openai (ex: servidor llama.cpp) |
Próxima etapa: [Iniciar os serviços e executar o AgenticSeek](#iniciar-os-serviços-e-executar)
*Se você encontrar problemas, consulte a seção [Solução de problemas](#solução-de-problemas).*
*Se seu hardware não puder executar LLM localmente, consulte [Configuração para executar com uma API](#configuração-para-executar-com-uma-api).*
*Para explicações detalhadas do `config.ini`, consulte a [seção Configuração](#configuração).*
## Configuração para executar com uma API
Esta configuração usa provedores de LLM externos baseados em nuvem. Você precisará obter chaves de API do serviço escolhido.
**1. Escolha um provedor de API e obtenha uma chave de API:**
Consulte a [Lista de provedores de API](#lista-de-provedores-de-api) abaixo. Visite seus sites para se inscrever e obter chaves de API.
**2. Defina sua chave de API como variável de ambiente:**
* **Linux/macOS:**
Abra um terminal e use o comando `export`. É melhor adicioná-lo ao arquivo de configuração do seu shell (ex: `~/.bashrc`, `~/.zshrc`) para que seja persistente.
```sh
export PROVIDER_API_KEY="your_api_key_here"
# Substitua PROVIDER_API_KEY pelo nome de variável específico, ex: OPENAI_API_KEY, GOOGLE_API_KEY
```
Exemplo TogetherAI:
```sh
export TOGETHER_API_KEY="xxxxxxxxxxxxxxxxxxxxxx"
```
* **Windows:**
* **Prompt de comando (temporário para a sessão atual):**
```cmd
set PROVIDER_API_KEY=your_api_key_here
```
* **PowerShell (temporário para a sessão atual):**
```powershell
$env:PROVIDER_API_KEY="your_api_key_here"
```
* **Permanente:** Pesquise "variáveis de ambiente" na barra de pesquisa do Windows, clique em "Editar variáveis de ambiente do sistema" e depois no botão "Variáveis de ambiente...". Adicione uma nova variável de usuário com o nome apropriado (ex: `OPENAI_API_KEY`) e sua chave como valor.
*(Para mais detalhes, consulte o FAQ: [Como configurar uma chave de API?](#como-configurar-uma-chave-de-api)).*
**3. Atualize `config.ini`:**
```ini
[MAIN]
is_local = False
provider_name = openai # ou google, deepseek, togetherAI, huggingface
provider_model = gpt-3.5-turbo # ou gemini-1.5-flash, deepseek-chat, mistralai/Mixtral-8x7B-Instruct-v0.1, etc.
provider_server_address = # Quando is_local = False, geralmente ignorado ou pode ser deixado vazio para a maioria das APIs
# ... outras configurações ...
```
*Aviso:* Certifique-se de que não há espaços no final dos valores no config.
**Lista de provedores de API**
| Provedor | `provider_name` | Local ? | Descrição | Link da chave de API (exemplo) |
|--------------|-----------------|--------|---------------------------------------------------|---------------------------------------------|
| OpenAI | `openai` | Não | Use os modelos ChatGPT via API OpenAI. | [platform.openai.com/signup](https://platform.openai.com/signup) |
| Google Gemini| `google` | Não | Use os modelos Google Gemini via Google AI Studio. | [aistudio.google.com/keys](https://aistudio.google.com/keys) |
| Deepseek | `deepseek` | Não | Use os modelos Deepseek via sua API. | [platform.deepseek.com](https://platform.deepseek.com) |
| Hugging Face | `huggingface` | Não | Use modelos do Hugging Face Inference API. | [huggingface.co/settings/tokens](https://huggingface.co/settings/tokens) |
| TogetherAI | `togetherAI` | Não | Use vários modelos open source via API TogetherAI.| [api.together.ai/settings/api-keys](https://api.together.ai/settings/api-keys) |
*Nota:*
* Não recomendamos usar `gpt-4o` ou outros modelos OpenAI para navegação web complexa e planejamento de tarefas, pois a otimização atual de prompts visa modelos como Deepseek.
* Tarefas de codificação/bash podem falhar com Gemini, pois tende a ignorar nosso formato de prompt otimizado para Deepseek r1.
* Quando `is_local = False`, `provider_server_address` no `config.ini` geralmente não é usado, pois os endpoints de API são geralmente gerenciados pelas bibliotecas do provedor correspondente.
Próxima etapa: [Iniciar os serviços e executar o AgenticSeek](#iniciar-os-serviços-e-executar)
*Se você encontrar problemas, consulte a seção **Problemas conhecidos***
*Para explicações detalhadas do arquivo de configuração, consulte a **seção Configuração**.*
---
## Iniciar os serviços e executar
Por padrão, o AgenticSeek é executado inteiramente no Docker.
**Opção 1:** Executar no Docker com interface web:
Inicie os serviços necessários. Isso iniciará todos os serviços do docker-compose.yml, incluindo:
- searxng
- redis (necessário para searxng)
- frontend
- backend (se você usar `full` para a interface web)
```sh
./start_services.sh full # MacOS
start start_services.cmd full # Windows
```
**Aviso:** Esta etapa baixará e carregará todas as imagens do Docker, o que pode levar até 30 minutos. Depois de iniciar os serviços, aguarde até que o serviço backend esteja totalmente operacional (você deve ver **backend: "GET /health HTTP/1.1" 200 OK** nos logs) antes de enviar mensagens. Na primeira inicialização, o serviço backend pode levar 5 minutos para iniciar.
Vá para `http://localhost:3000/` e você deve ver a interface web.
*Solução de problemas de inicialização de serviços:* Se esses scripts falharem, certifique-se de que o Docker Engine está funcionando e que o Docker Compose (V2, `docker compose`) está instalado corretamente. Verifique as mensagens de erro na saída do terminal. Consulte [FAQ: Ajuda! Estou recebendo erros ao executar o AgenticSeek ou seus scripts.](#faq-solução-de-problemas)
**Opção 2:** Modo CLI:
Para executar com a interface CLI, você precisa instalar os pacotes no host:
```sh
./install.sh
./install.bat # windows
```
Em seguida, você precisa alterar SEARXNG_BASE_URL no `config.ini` para:
```sh
SEARXNG_BASE_URL="http://localhost:8080"
```
Inicie os serviços necessários. Isso iniciará alguns serviços do docker-compose.yml, incluindo:
- searxng
- redis (necessário para searxng)
- frontend
```sh
./start_services.sh # MacOS
start start_services.cmd # Windows
```
Execute: uv run: `uv run python -m ensurepip` para garantir que o uv tenha o pip ativado.
Use CLI: `uv run cli.py`
---
## Uso
Certifique-se de que os serviços estão funcionando com `./start_services.sh full` e vá para `localhost:3000` para a interface web.
Você também pode usar fala para texto definindo `listen = True`. Apenas para o modo CLI.
Para sair, basta dizer/digitar `goodbye`.
Alguns exemplos de uso:
> *Faça um jogo da cobra em python!*
> *Pesquise na web os melhores cafés em Rennes, França, e salve uma lista de três com seus endereços em rennes_cafes.txt.*
> *Escreva um programa Go para calcular o fatorial de um número, salve-o como factorial.go em seu workspace*
> *Pesquise na pasta summer_pictures todos os arquivos JPG, renomeie-os com a data de hoje e salve a lista de arquivos renomeados em photos_list.txt*
> *Pesquise online os filmes de ficção científica populares de 2024 e escolha três para assistir esta noite. Salve a lista em movie_night.txt.*
> *Pesquise na web os últimos artigos de notícias sobre IA de 2025, selecione três e escreva um script Python para extrair os títulos e resumos. Salve o script como news_scraper.py e os resumos em ai_news.txt em /home/projects*
> *Sexta-feira, pesquise na web uma API gratuita de preços de ações, inscreva-se com supersuper7434567@gmail.com e escreva um script Python para obter os preços diários da Tesla usando a API, salvando os resultados em stock_prices.csv*
*Observe que o preenchimento de formulários ainda é experimental e pode falhar.*
Depois de inserir sua consulta, o AgenticSeek atribuirá o melhor agente para a tarefa.
Como este é um protótipo inicial, o sistema de roteamento de agentes pode nem sempre atribuir o agente correto à sua consulta.
Portanto, seja muito explícito sobre o que você quer e como a IA pode proceder, por exemplo, se você quiser que ela faça uma pesquisa na web, não diga:
`Você conhece bons países para viajar sozinho?`
Em vez disso, diga:
`Execute uma pesquisa na web e descubra quais são os melhores países para viajar sozinho`
---
## **Configuração para executar LLM em seu próprio servidor**
Se você tem um computador poderoso ou um servidor que pode acessar, mas quer usá-lo do seu laptop, você pode optar por executar o LLM em um servidor remoto usando nosso servidor llm personalizado.
No seu "servidor" que executará o modelo de IA, obtenha o endereço IP
```sh
ip a | grep "inet " | grep -v 127.0.0.1 | awk '{print $2}' | cut -d/ -f1 # IP local
curl https://ipinfo.io/ip # IP público
```
Nota: Para Windows ou macOS, use ipconfig ou ifconfig para encontrar o endereço IP.
Clone o repositório e entre na pasta `server/`.
```sh
git clone --depth 1 https://github.com/Fosowl/agenticSeek.git
cd agenticSeek/llm_server/
```
Instale os requisitos específicos do servidor:
```sh
pip3 install -r requirements.txt
```
Execute o script do servidor.
```sh
python3 app.py --provider ollama --port 3333
```
Você pode escolher usar `ollama` e `llamacpp` como serviço LLM.
Agora no seu computador pessoal:
Altere o arquivo `config.ini` para definir `provider_name` como `server` e `provider_model` como `deepseek-r1:xxb`.
Defina `provider_server_address` como o endereço IP da máquina que executará o modelo.
```sh
[MAIN]
is_local = False
provider_name = server
provider_model = deepseek-r1:70b
provider_server_address = http://x.x.x.x:3333
```
Próxima etapa: [Iniciar os serviços e executar o AgenticSeek](#iniciar-os-serviços-e-executar)
---
## Fala para Texto
Aviso: Fala para texto funciona apenas no modo CLI no momento.
Observe que a fala para texto funciona apenas em inglês no momento.
A funcionalidade de fala para texto está desativada por padrão. Para ativá-la, defina listen como True no arquivo config.ini:
```
listen = True
```
Quando ativada, a funcionalidade de fala para texto ouve uma palavra-chave de gatilho, que é o nome do agente, antes de processar sua entrada. Você pode personalizar o nome do agente atualizando o valor `agent_name` em *config.ini*:
```
agent_name = Friday
```
Para melhor reconhecimento, recomendamos usar um nome comum em inglês como "John" ou "Emma" como nome do agente.
Assim que você vir a transcrição começar a aparecer, diga o nome do agente em voz alta para acordá-lo (ex: "Friday").
Diga sua consulta claramente.
Termine sua solicitação com uma frase de confirmação para indicar ao sistema para continuar. Exemplos de frases de confirmação incluem:
```
"do it", "go ahead", "execute", "run", "start", "thanks", "would ya", "please", "okay?", "proceed", "continue", "go on", "do that", "go it", "do you understand?"
```
## Configuração
Exemplo de configuração:
```
[MAIN]
is_local = True
provider_name = ollama
provider_model = deepseek-r1:32b
provider_server_address = http://127.0.0.1:11434 # Exemplo Ollama; LM-Studio usa http://127.0.0.1:1234
agent_name = Friday
recover_last_session = False
save_session = False
speak = False
listen = False
jarvis_personality = False
languages = en zh # Lista de idiomas para TTS e roteamento potencial.
[BROWSER]
headless_browser = False
stealth_mode = False
```
**Explicação das configurações de `config.ini`**:
* **Seção `[MAIN]`:**
* `is_local`: `True` se você estiver usando provedores de LLM locais (Ollama, LM-Studio, servidor local compatível com OpenAI) ou a opção de servidor auto-hospedado. `False` se você estiver usando APIs baseadas em nuvem (OpenAI, Google, etc.).
* `provider_name`: Especifica o provedor de LLM.
* Opções locais: `ollama`, `lm-studio`, `openai` (para servidor local compatível com OpenAI), `server` (para configuração de servidor auto-hospedado).
* Opções de API: `openai`, `google`, `deepseek`, `huggingface`, `togetherAI`.
* `provider_model`: Nome ou ID específico do modelo do provedor selecionado (ex: `deepseekcoder:6.7b` para Ollama, `gpt-3.5-turbo` para API OpenAI, `mistralai/Mixtral-8x7B-Instruct-v0.1` para TogetherAI).
* `provider_server_address`: O endereço do seu provedor de LLM.
* Para provedores locais: ex: `http://127.0.0.1:11434` para Ollama, `http://127.0.0.1:1234` para LM-Studio.
* Para o tipo de provedor `server`: O endereço do seu servidor LLM auto-hospedado (ex: `http://your_server_ip:3333`).
* Para APIs em nuvem (`is_local = False`): Isso geralmente é ignorado ou pode ser deixado em branco, pois os endpoints da API são geralmente gerenciados pelas bibliotecas do provedor correspondente.
* `agent_name`: O nome do assistente de IA (ex: Friday). Se ativado, usado como palavra de gatilho para fala para texto.
* `recover_last_session`: `True` para tentar recuperar o estado da sessão anterior, `False` para começar do zero.
* `save_session`: `True` para salvar o estado da sessão atual para possível recuperação, `False` caso contrário.
* `speak`: `True` para ativar a saída de voz de texto para fala, `False` para desativar.
* `listen`: `True` para ativar a entrada de voz de fala para texto (apenas modo CLI), `False` para desativar.
* `work_dir`: **Crítico:** O diretório onde o AgenticSeek lerá/escreverá arquivos. **Certifique-se de que este caminho é válido e acessível no seu sistema.**
* `jarvis_personality`: `True` para usar prompts de sistema mais "Jarvis-like" (experimental), `False` para usar prompts padrão.
* `languages`: Lista de idiomas separados por vírgulas (ex: `en, zh, fr`). Usado para seleção de voz TTS (primeira por padrão) e pode ajudar o roteador LLM. Para evitar ineficiências do roteador, evite usar muitos idiomas ou idiomas muito semelhantes.
* **Seção `[BROWSER]`:**
* `headless_browser`: `True` para executar o navegador automatizado sem janela visível (recomendado para interface web ou uso não interativo). `False` para exibir a janela do navegador (útil para modo CLI ou depuração).
* `stealth_mode`: `True` para ativar medidas que tornam mais difícil a detecção da automação do navegador. Pode exigir instalação manual de extensões de navegador como anticaptcha.
Esta seção resume os tipos de provedores de LLM suportados. Configure-os em `config.ini`.
**Provedores locais (executando em seu próprio hardware):**
| Nome do provedor em config.ini | `is_local` | Descrição | Seção de configuração |
|-------------------------------|------------|-----------------------------------------------------------------------------|------------------------------------------------------------------|
| `ollama` | `True` | Fornece LLM localmente facilmente usando Ollama. | [Configuração para executar LLM localmente na sua máquina](#configuração-para-executar-llm-localmente-na-sua-máquina) |
| `lm-studio` | `True` | Fornece LLM localmente com LM-Studio. | [Configuração para executar LLM localmente na sua máquina](#configuração-para-executar-llm-localmente-na-sua-máquina) |
| `openai` (para servidor local) | `True` | Conecte-se a um servidor local expondo uma API compatível com OpenAI (ex: llama.cpp). | [Configuração para executar LLM localmente na sua máquina](#configuração-para-executar-llm-localmente-na-sua-máquina) |
| `server` | `False` | Conecte-se ao servidor LLM auto-hospedado do AgenticSeek em execução em outra máquina. | [Configuração para executar LLM em seu próprio servidor](#configuração-para-executar-llm-em-seu-próprio-servidor) |
**Provedores de API (baseados em nuvem):**
| Nome do provedor em config.ini | `is_local` | Descrição | Seção de configuração |
|-------------------------------|------------|--------------------------------------------------|-----------------------------------------------------|
| `openai` | `False` | Use a API oficial da OpenAI (ex: GPT-3.5, GPT-4). | [Configuração para executar com uma API](#configuração-para-executar-com-uma-api) |
| `google` | `False` | Use os modelos Google Gemini via API. | [Configuração para executar com uma API](#configuração-para-executar-com-uma-api) |
| `deepseek` | `False` | Use a API oficial da Deepseek. | [Configuração para executar com uma API](#configuração-para-executar-com-uma-api) |
| `huggingface` | `False` | Use Hugging Face Inference API. | [Configuração para executar com uma API](#configuração-para-executar-com-uma-api) |
| `togetherAI` | `False` | Use vários modelos abertos via API TogetherAI. | [Configuração para executar com uma API](#configuração-para-executar-com-uma-api) |
---
## Solução de problemas
Se você encontrar problemas, esta seção fornece orientações.
# Problemas conhecidos
## Problemas do ChromeDriver
**Exemplo de erro:** `SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version XXX`
### Causa raiz
A incompatibilidade de versão do ChromeDriver ocorre quando:
1. A versão do ChromeDriver que você instalou não corresponde à versão do navegador Chrome
2. Em ambientes Docker, `undetected_chromedriver` pode baixar sua própria versão do ChromeDriver, contornando os binários montados
### Etapas de solução
#### 1. Verifique sua versão do Chrome
Abra o Google Chrome → `Configurações > Sobre o Chrome` para encontrar sua versão (ex: "Versão 134.0.6998.88")
#### 2. Baixe o ChromeDriver correspondente
**Para Chrome 115 e superior:** Use [Chrome for Testing API](https://googlechromelabs.github.io/chrome-for-testing/)
- Visite o painel de disponibilidade do Chrome for Testing
- Encontre sua versão do Chrome ou a correspondência disponível mais próxima
- Baixe o ChromeDriver para seu sistema operacional (use Linux64 para ambientes Docker)
**Para versões mais antigas do Chrome:** Use [Downloads legados do ChromeDriver](https://chromedriver.chromium.org/downloads)
![Baixar ChromeDriver do Chrome for Testing](./media/chromedriver_readme.png)
#### 3. Instale o ChromeDriver (escolha um método)
**Método A: Diretório raiz do projeto (recomendado para Docker)**
```bash
# Coloque o binário chromedriver baixado no diretório raiz do projeto
cp path/to/downloaded/chromedriver ./chromedriver
chmod +x ./chromedriver # Torne-o executável no Linux/macOS
```
**Método B: PATH do sistema**
```bash
# Linux/macOS
sudo mv chromedriver /usr/local/bin/
sudo chmod +x /usr/local/bin/chromedriver
# Windows: Coloque chromedriver.exe em uma pasta do PATH
```
#### 4. Verifique a instalação
```bash
# Teste a versão do ChromeDriver
./chromedriver --version
# Ou se estiver no PATH:
chromedriver --version
```
### Instruções específicas do Docker
⚠️ **Importante para usuários do Docker:**
- O método de montagem de volumes do Docker pode não funcionar com o modo furtivo (`undetected_chromedriver`)
- **Solução:** Coloque o ChromeDriver no diretório raiz do projeto como `./chromedriver`
- O aplicativo o detectará automaticamente e usará este binário
- Você deve ver nos logs: `"Using ChromeDriver from project root: ./chromedriver"`
### Dicas de solução de problemas
1. **Ainda há incompatibilidade de versão?**
- Verifique se o ChromeDriver é executável: `ls -la ./chromedriver`
- Verifique a versão do ChromeDriver: `./chromedriver --version`
- Certifique-se de que corresponde à versão do seu navegador Chrome
2. **Problemas com o contêiner Docker?**
- Verifique os logs do backend: `docker logs backend`
- Procure a mensagem: `"Using ChromeDriver from project root"`
- Se não for encontrado, verifique se o arquivo existe e é executável
3. **Versões do Chrome for Testing**
- Use uma correspondência exata quando possível
- Para a versão 134.0.6998.88, use o ChromeDriver 134.0.6998.165 (a versão disponível mais próxima)
- O número da versão principal deve corresponder (134 = 134)
### Matriz de compatibilidade de versões
| Versão do Chrome | Versão do ChromeDriver | Status |
|----------------|---------------------|---------|
| 134.0.6998.x | 134.0.6998.165 | ✅ Disponível |
| 133.0.6943.x | 133.0.6943.141 | ✅ Disponível |
| 132.0.6834.x | 132.0.6834.159 | ✅ Disponível |
*Para a compatibilidade mais recente, consulte o [Painel do Chrome for Testing](https://googlechromelabs.github.io/chrome-for-testing/)*
`Exception: Failed to initialize browser: Message: session not created: This version of ChromeDriver only supports Chrome version 113
Current browser version is 134.0.6998.89 with binary path`
Isso acontece se seu navegador e a versão do chromedriver não corresponderem.
Você precisa navegar para baixar a versão mais recente:
https://developer.chrome.com/docs/chromedriver/downloads
Se você estiver usando o Chrome versão 115 ou superior, vá para:
https://googlechromelabs.github.io/chrome-for-testing/
e baixe a versão do chromedriver correspondente ao seu sistema operacional.
![alt text](./media/chromedriver_readme.png)
Se esta seção estiver incompleta, abra um issue.
## Problemas de adaptadores de conexão
```
Exception: Provider lm-studio failed: HTTP request failed: No connection adapters were found for '127.0.0.1:1234/v1/chat/completions'` (nota: a porta pode variar)
```
* **Causa:** Falta o prefixo `http://` em `provider_server_address` para `lm-studio` (ou outro servidor local compatível com OpenAI semelhante) no `config.ini`, ou ele aponta para a porta errada.
* **Solução:**
* Certifique-se de que o endereço inclui `http://`. O LM-Studio geralmente usa `http://127.0.0.1:1234` por padrão.
* `config.ini` correto: `provider_server_address = http://127.0.0.1:1234` (ou sua porta real do servidor LM-Studio).
## URL base do SearxNG não fornecida
```
raise ValueError("SearxNG base URL must be provided either as an argument or via the SEARXNG_BASE_URL environment variable.")
ValueError: SearxNG base URL must be provided either as an argument or via the SEARXNG_BASE_URL environment variable.`
```
Isso pode acontecer se você executar o modo CLI com uma URL base do searxng incorreta.
SEARXNG_BASE_URL deve diferir dependendo se você está executando no Docker ou no host:
**Execução no host:** `SEARXNG_BASE_URL="http://localhost:8080"`
**Execução completamente no Docker (interface web):** `SEARXNG_BASE_URL="http://searxng:8080"`
## FAQ
**P: De qual hardware eu preciso?**
| Tamanho do modelo | GPU | Comentários |
|-----------|--------|-----------------------------------------------------------|
| 7B | 8GB VRAM | ⚠️ Não recomendado. Desempenho ruim, alucinações frequentes, agentes de planejamento podem falhar. |
| 14B | 12 GB VRAM (ex: RTX 3060) | ✅ Utilizável para tarefas simples. Pode ter dificuldades com navegação web e planejamento de tarefas. |
| 32B | 24+ GB VRAM (ex: RTX 4090) | 🚀 Consegue a maioria das tarefas, ainda pode ter dificuldades com planejamento de tarefas |
| 70B+ | 48+ GB VRAM | 💪 Excelente. Recomendado para casos de uso avançados. |
**P: O que fazer se eu encontrar erros?**
Certifique-se de que o local está funcionando (`ollama serve`), que seu `config.ini` corresponde ao seu provedor e que as dependências estão instaladas. Se nada funcionar, sinta-se à vontade para abrir um issue.
**P: Ele pode realmente funcionar 100% localmente?**
Sim, com os provedores Ollama, lm-studio ou server, todos os modelos de fala para texto, LLM e texto para fala funcionam localmente. As opções não locais (OpenAI ou outras APIs) são opcionais.
**P: Por que eu deveria usar o AgenticSeek quando tenho o Manus?**
Ao contrário do Manus, o AgenticSeek prioriza a independência de sistemas externos, dando a você mais controle, privacidade e evitando custos de API.
**P: Quem está por trás deste projeto?**
Este projeto foi criado por mim, com dois amigos como mantenedores e contribuidores da comunidade de código aberto no GitHub. Somos apenas indivíduos apaixonados, não uma startup, nem afiliados a qualquer organização.
Qualquer conta AgenticSeek no X diferente da minha conta pessoal (https://x.com/Martin993886460) é um impostor.
## Contribuir
Estamos procurando desenvolvedores para melhorar o AgenticSeek! Verifique os problemas abertos ou discussões.
[Guia de contribuição](./docs/CONTRIBUTING.md)
## Patrocinadores:
Você quer melhorar as capacidades do AgenticSeek com recursos como pesquisa de voos, planejamento de viagens ou obtenção das melhores ofertas de compra? Considere usar o SerpApi para criar ferramentas personalizadas que desbloqueiem mais recursos do tipo Jarvis. Com o SerpApi, você pode acelerar seu agente para tarefas profissionais enquanto mantém o controle total.
<a href="https://serpapi.com/"><img src="./media/banners/sponsor_banner_serpapi.png" height="350" alt="SerpApi Banner" ></a>
Confira [Contributing.md](./docs/CONTRIBUTING.md) para aprender como integrar ferramentas personalizadas!
### **Patrocinadores**:
- [tatra-labs](https://github.com/tatra-labs)
## Mantenedores:
> [Fosowl](https://github.com/Fosowl) | Horário de Paris
> [antoineVIVIES](https://github.com/antoineVIVIES) | Horário de Taipei
## Agradecimentos especiais:
> [tcsenpai](https://github.com/tcsenpai) e [plitc](https://github.com/plitc) por ajudar na dockerização do backend
[![Star History Chart](https://api.star-history.com/svg?repos=Fosowl/agenticSeek&type=Date)](https://www.star-history.com/#Fosowl/agenticSeek&Date)
+5 -66
View File
@@ -22,26 +22,6 @@ from sources.utility import pretty_print
from sources.logger import Logger from sources.logger import Logger
from sources.schemas import QueryRequest, QueryResponse from sources.schemas import QueryRequest, QueryResponse
from dotenv import load_dotenv
load_dotenv()
def is_running_in_docker():
"""Detect if code is running inside a Docker container."""
# Method 1: Check for .dockerenv file
if os.path.exists('/.dockerenv'):
return True
# Method 2: Check cgroup
try:
with open('/proc/1/cgroup', 'r') as f:
return 'docker' in f.read()
except:
pass
return False
from celery import Celery from celery import Celery
@@ -68,25 +48,7 @@ def initialize_system():
stealth_mode = config.getboolean('BROWSER', 'stealth_mode') stealth_mode = config.getboolean('BROWSER', 'stealth_mode')
personality_folder = "jarvis" if config.getboolean('MAIN', 'jarvis_personality') else "base" personality_folder = "jarvis" if config.getboolean('MAIN', 'jarvis_personality') else "base"
languages = config["MAIN"]["languages"].split(' ') languages = config["MAIN"]["languages"].split(' ')
# Force headless mode in Docker containers
headless = config.getboolean('BROWSER', 'headless_browser')
if is_running_in_docker() and not headless:
# Print prominent warning to console (visible in docker-compose output)
print("\n" + "*" * 70)
print("*** WARNING: Detected Docker environment - forcing headless_browser=True ***")
print("*** INFO: To see the browser, run 'python cli.py' on your host machine ***")
print("*" * 70 + "\n")
# Flush to ensure it's displayed immediately
sys.stdout.flush()
# Also log to file
logger.warning("Detected Docker environment - forcing headless_browser=True")
logger.info("To see the browser, run 'python cli.py' on your host machine instead")
headless = True
provider = Provider( provider = Provider(
provider_name=config["MAIN"]["provider_name"], provider_name=config["MAIN"]["provider_name"],
model=config["MAIN"]["provider_model"], model=config["MAIN"]["provider_model"],
@@ -96,7 +58,7 @@ def initialize_system():
logger.info(f"Provider initialized: {provider.provider_name} ({provider.model})") logger.info(f"Provider initialized: {provider.provider_name} ({provider.model})")
browser = Browser( browser = Browser(
create_driver(headless=headless, stealth_mode=stealth_mode, lang=languages[0]), create_driver(headless=config.getboolean('BROWSER', 'headless_browser'), stealth_mode=stealth_mode),
anticaptcha_manual_install=stealth_mode anticaptcha_manual_install=stealth_mode
) )
logger.info("Browser initialized") logger.info("Browser initialized")
@@ -166,12 +128,6 @@ async def is_active():
logger.info("Is active endpoint called") logger.info("Is active endpoint called")
return {"is_active": interaction.is_active} return {"is_active": interaction.is_active}
@api.get("/stop")
async def stop():
logger.info("Stop endpoint called")
interaction.current_agent.request_stop()
return JSONResponse(status_code=200, content={"status": "stopped"})
@api.get("/latest_answer") @api.get("/latest_answer")
async def get_latest_answer(): async def get_latest_answer():
global query_resp_history global query_resp_history
@@ -182,7 +138,6 @@ async def get_latest_answer():
query_resp = { query_resp = {
"done": "false", "done": "false",
"answer": interaction.current_agent.last_answer, "answer": interaction.current_agent.last_answer,
"reasoning": interaction.current_agent.last_reasoning,
"agent_name": interaction.current_agent.agent_name if interaction.current_agent else "None", "agent_name": interaction.current_agent.agent_name if interaction.current_agent else "None",
"success": interaction.current_agent.success, "success": interaction.current_agent.success,
"blocks": {f'{i}': block.jsonify() for i, block in enumerate(interaction.get_last_blocks_result())} if interaction.current_agent else {}, "blocks": {f'{i}': block.jsonify() for i, block in enumerate(interaction.get_last_blocks_result())} if interaction.current_agent else {},
@@ -190,7 +145,6 @@ async def get_latest_answer():
"uid": uid "uid": uid
} }
interaction.current_agent.last_answer = "" interaction.current_agent.last_answer = ""
interaction.current_agent.last_reasoning = ""
query_resp_history.append(query_resp) query_resp_history.append(query_resp)
return JSONResponse(status_code=200, content=query_resp) return JSONResponse(status_code=200, content=query_resp)
if query_resp_history: if query_resp_history:
@@ -204,7 +158,6 @@ async def think_wrapper(interaction, query):
success = await interaction.think() success = await interaction.think()
if not success: if not success:
interaction.last_answer = "Error: No answer from agent" interaction.last_answer = "Error: No answer from agent"
interaction.last_reasoning = "Error: No reasoning from agent"
interaction.last_success = False interaction.last_success = False
else: else:
interaction.last_success = True interaction.last_success = True
@@ -213,8 +166,7 @@ async def think_wrapper(interaction, query):
return success return success
except Exception as e: except Exception as e:
logger.error(f"Error in think_wrapper: {str(e)}") logger.error(f"Error in think_wrapper: {str(e)}")
interaction.last_answer = f"" interaction.last_answer = f"Error: {str(e)}"
interaction.last_reasoning = f"Error: {str(e)}"
interaction.last_success = False interaction.last_success = False
raise e raise e
@@ -225,7 +177,6 @@ async def process_query(request: QueryRequest):
query_resp = QueryResponse( query_resp = QueryResponse(
done="false", done="false",
answer="", answer="",
reasoning="",
agent_name="Unknown", agent_name="Unknown",
success="false", success="false",
blocks={}, blocks={},
@@ -243,7 +194,6 @@ async def process_query(request: QueryRequest):
if not success: if not success:
query_resp.answer = interaction.last_answer query_resp.answer = interaction.last_answer
query_resp.reasoning = interaction.last_reasoning
return JSONResponse(status_code=400, content=query_resp.jsonify()) return JSONResponse(status_code=400, content=query_resp.jsonify())
if interaction.current_agent: if interaction.current_agent:
@@ -258,11 +208,11 @@ async def process_query(request: QueryRequest):
logger.info(f"Blocks: {blocks_json}") logger.info(f"Blocks: {blocks_json}")
query_resp.done = "true" query_resp.done = "true"
query_resp.answer = interaction.last_answer query_resp.answer = interaction.last_answer
query_resp.reasoning = interaction.last_reasoning
query_resp.agent_name = interaction.current_agent.agent_name query_resp.agent_name = interaction.current_agent.agent_name
query_resp.success = str(interaction.last_success) query_resp.success = str(interaction.last_success)
query_resp.blocks = blocks_json query_resp.blocks = blocks_json
# Store the raw dictionary representation
query_resp_dict = { query_resp_dict = {
"done": query_resp.done, "done": query_resp.done,
"answer": query_resp.answer, "answer": query_resp.answer,
@@ -285,15 +235,4 @@ async def process_query(request: QueryRequest):
interaction.save_session() interaction.save_session()
if __name__ == "__main__": if __name__ == "__main__":
# Print startup info uvicorn.run(api, host="0.0.0.0", port=8000)
if is_running_in_docker():
print("[AgenticSeek] Starting in Docker container...")
else:
print("[AgenticSeek] Starting on host machine...")
envport = os.getenv("BACKEND_PORT")
if envport:
port = int(envport)
else:
port = 7777
uvicorn.run(api, host="0.0.0.0", port=7777)
+4 -4
View File
@@ -29,7 +29,7 @@ async def main():
is_local=config.getboolean('MAIN', 'is_local')) is_local=config.getboolean('MAIN', 'is_local'))
browser = Browser( browser = Browser(
create_driver(headless=config.getboolean('BROWSER', 'headless_browser'), stealth_mode=stealth_mode, lang=languages[0]), create_driver(headless=config.getboolean('BROWSER', 'headless_browser'), stealth_mode=stealth_mode),
anticaptcha_manual_install=stealth_mode anticaptcha_manual_install=stealth_mode
) )
@@ -49,9 +49,9 @@ async def main():
PlannerAgent(name="Planner", PlannerAgent(name="Planner",
prompt_path=f"prompts/{personality_folder}/planner_agent.txt", prompt_path=f"prompts/{personality_folder}/planner_agent.txt",
provider=provider, verbose=False, browser=browser), provider=provider, verbose=False, browser=browser),
#McpAgent(name="MCP Agent", McpAgent(name="MCP Agent",
# prompt_path=f"prompts/{personality_folder}/mcp_agent.txt", prompt_path=f"prompts/{personality_folder}/mcp_agent.txt",
# provider=provider, verbose=False), # NOTE under development provider=provider, verbose=False),
] ]
interaction = Interaction(agents, interaction = Interaction(agents,
+2 -1
View File
@@ -3,11 +3,12 @@ is_local = True
provider_name = ollama provider_name = ollama
provider_model = deepseek-r1:14b provider_model = deepseek-r1:14b
provider_server_address = 127.0.0.1:11434 provider_server_address = 127.0.0.1:11434
agent_name = Jarvis agent_name = Name_of_your_AI
recover_last_session = False recover_last_session = False
save_session = False save_session = False
speak = False speak = False
listen = False listen = False
work_dir = /Users/mlg/Documents/workspace_for_agenticseek
jarvis_personality = False jarvis_personality = False
languages = en languages = en
[BROWSER] [BROWSER]
+36 -40
View File
@@ -1,9 +1,8 @@
version: '3.8' version: '3'
services: services:
redis: redis:
container_name: redis container_name: redis
profiles: ["core", "full"]
image: docker.io/valkey/valkey:8-alpine image: docker.io/valkey/valkey:8-alpine
command: valkey-server --save 30 1 --loglevel warning command: valkey-server --save 30 1 --loglevel warning
restart: unless-stopped restart: unless-stopped
@@ -25,16 +24,15 @@ services:
searxng: searxng:
container_name: searxng container_name: searxng
profiles: ["core", "full"]
image: docker.io/searxng/searxng:latest image: docker.io/searxng/searxng:latest
restart: unless-stopped restart: unless-stopped
ports: ports:
- "8080:8080" - "8080:8080"
volumes: volumes:
- ./searxng:/etc/searxng:rw,z - ./searxng:/etc/searxng:rw
environment: environment:
- SEARXNG_BASE_URL=${SEARXNG_BASE_URL:-http://localhost:8080/} - SEARXNG_BASE_URL=http://localhost:8080/
- SEARXNG_SECRET_KEY=${SEARXNG_SECRET_KEY} - SEARXNG_SECRET_KEY=$(openssl rand -hex 32)
- UWSGI_WORKERS=4 - UWSGI_WORKERS=4
- UWSGI_THREADS=4 - UWSGI_THREADS=4
cap_add: cap_add:
@@ -53,52 +51,50 @@ services:
frontend: frontend:
container_name: frontend container_name: frontend
profiles: ["core", "full"]
build: build:
context: ./frontend context: ./frontend
dockerfile: Dockerfile.frontend dockerfile: Dockerfile.frontend
ports: ports:
- "3000:3000" - "3000:3000"
volumes: volumes:
- ./frontend/agentic-seek-front/src:/app/src:rw,z - ./frontend/agentic-seek-front/src:/app/src
- ./screenshots:/app/screenshots - ./screenshots:/app/screenshots
environment: environment:
- NODE_ENV=development - NODE_ENV=development
- CHOKIDAR_USEPOLLING=true - CHOKIDAR_USEPOLLING=true
- REACT_APP_BACKEND_URL=http://localhost:7777 - BACKEND_URL=http://backend:8000
networks: networks:
- agentic-seek-net - agentic-seek-net
# NOTE: backend service is not working yet due to issue with chromedriver on docker.
# Therefore backend is run on host machine.
# Open to pull requests to fix this.
backend: #backend:
container_name: backend # container_name: backend
profiles: ["backend", "full"] # build:
build: # context: ./
context: . # dockerfile: Dockerfile.backend
dockerfile: Dockerfile.backend # stdin_open: true
ports: # tty: true
- ${BACKEND_PORT:-7777}:${BACKEND_PORT:-7777} # shm_size: 8g
volumes: # ports:
- ./:/app # - "8000:8000"
- ${WORK_DIR:-.}:/opt/workspace # volumes:
command: python3 api.py # - ./:/app
environment: # environment:
- SEARXNG_BASE_URL=${SEARXNG_BASE_URL:-http://searxng:8080} # - NODE_ENV=development
- REDIS_URL=${REDIS_BASE_URL:-redis://redis:6379/0} # - REDIS_URL=redis://redis:6379/0
- WORK_DIR=/opt/workspace # - SEARXNG_URL=http://searxng:8080
- BACKEND_PORT=${BACKEND_PORT} # - OLLAMA_URL=http://localhost:11434
- DOCKER_INTERNAL_URL=http://host.docker.internal # - LM_STUDIO_URL=http://localhost:1234
- OPENAI_API_KEY=${OPENAI_API_KEY} # extra_hosts:
- DEEPSEEK_API_KEY=${DEEPSEEK_API_KEY} # - "host.docker.internal:host-gateway"
- OPENROUTER_API_KEY=${OPENROUTER_API_KEY} # depends_on:
- TOGETHER_API_KEY=${TOGETHER_API_KEY} # - redis
- GOOGLE_API_KEY=${GOOGLE_API_KEY} # - searxng
- ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY} # networks:
- HUGGINGFACE_API_KEY=${HUGGINGFACE_API_KEY} # - agentic-seek-net
- DSK_DEEPSEEK_API_KEY=${DSK_DEEPSEEK_API_KEY}
networks:
- agentic-seek-net
extra_hosts:
- "host.docker.internal:host-gateway"
volumes: volumes:
redis-data: redis-data:
@@ -106,4 +102,4 @@ volumes:
networks: networks:
agentic-seek-net: agentic-seek-net:
driver: bridge driver: bridge
+8 -39
View File
@@ -92,13 +92,11 @@ Here are some tasks and areas where we need contributions:
Tools are extensions that enable agents to perform specific actions, such as running Python code, making API calls, or conducting web searches. All tools inherit from the Tools base class, which provides methods for parsing and executing tool instructions. Tools are extensions that enable agents to perform specific actions, such as running Python code, making API calls, or conducting web searches. All tools inherit from the Tools base class, which provides methods for parsing and executing tool instructions.
## Understand Tools parsing ## Tools parsing
Agents invoke tools using a standardized format called a block. A block consists of the tool name followed by the content (e.g., code, query, or parameters) to execute. When creating a prompt for an Agent, you must explicitly tell them to use this format. Agents invoke tools using a standardized format called a block. A block consists of the tool name followed by the content (e.g., code, query, or parameters) to execute. The format looks like this:
The format looks like this: BECAUSE WE USE MARKDOWN QUOTE FORMAT, READING WILL BE BROKEN ON GITHUB PLEASE START READING THE FILE AS RAW: https://raw.githubusercontent.com/Fosowl/agenticSeek/refs/heads/main/CONTRIBUTING.md
BECAUSE WE USE MARKDOWN QUOTE FORMAT, READING WILL BE BROKEN ON GITHUB PLEASE START READING THE FILE AS RAW: https://raw.githubusercontent.com/Fosowl/agenticSeek/refs/heads/dev/docs/CONTRIBUTING.md
```<tool name> ```<tool name>
@@ -119,9 +117,10 @@ How to handle multiple arguments then ?
Good question! Each tool is free to handle argument in it's own way within the block, but we provide a common parsing logic: Good question! Each tool is free to handle argument in it's own way within the block, but we provide a common parsing logic:
```trip_search ```flight_search
from=Paris from=Paris
to=Toulouse to=Taipei
date=30/04/2026
``` ```
To extract these parameters, use the `get_parameter_value` method provided by the Tools class. Each tool can define its own parameter-handling logic, but the Tools class ensures consistent parsing. To extract these parameters, use the `get_parameter_value` method provided by the Tools class. Each tool can define its own parameter-handling logic, but the Tools class ensures consistent parsing.
@@ -136,7 +135,7 @@ print("Hello world")
Will save the code in toto.py file within the work_folder defined in the config.ini Will save the code in toto.py file within the work_folder defined in the config.ini
## Tools Implementation ## Execution
When developing a tool, you must implement three abstract methods defined in the Tools class to handle execution, failure detection, and feedback to the agent. These methods ensure consistent behavior across tools and enable robust interaction with the LLM. When developing a tool, you must implement three abstract methods defined in the Tools class to handle execution, failure detection, and feedback to the agent. These methods ensure consistent behavior across tools and enable robust interaction with the LLM.
@@ -172,39 +171,9 @@ Recap:
- get_parameter_value: Retrieves parameter values from a block's content. - get_parameter_value: Retrieves parameter values from a block's content.
- File handling: Supports saving block content to files when a :path is specified. - File handling: Supports saving block content to files when a :path is specified.
## Prompting an Agent for Tools usage
Consider an example where you want to add a flight search tool to the casual agent, you will need to modify the prompt file for the CasualAgent (e.g., casual_agent.txt) to instruct the LLM to use the a simple flight_search tool. you could add to the prompt:
You can search for flights using the flight_search tool. Example:
```flight_search
RY7481
```
You simply need to enter the flight number, you will then various informations about the flight if it exist, such as : Airline, Status, Departure time, Arrival Time
## Add the tool to your agent
To add a tool to an agent you simply need to:
1. Import a tool.
2. Add the tool class to the **tools** dictionnary.
3. Update the agent prompt.
```python
from sources.tools.flightSearch import FlightSearch
class CasualAgent(Agent):
def __init__(self, name, prompt_path, provider, verbose=False):
super().__init__(name, prompt_path, provider, verbose, None)
self.tools = {
"flight_search": FlightSearch(),
}
self.role = "en"
self.type = "casual_agent"
```
# Implementing and using Agents # Implementing and using Agents
Agents are classes that define how an LLM interacts with users and processes inputs. They can use tools (e.g., for executing code or querying APIs) and maintain a memory of the conversation to provide context-aware responses. All agents inherit from the base Agent class, which provides core functionality like memory management and LLM communication. Agents are classes that define how an LLM interacts with users and processes inputs. They can use tools (e.g., for executing code or querying APIs) and maintain a memory of the conversation to provide context-aware responses. All agents inherit from the base Agent class, which provides core functionality like memory management and LLM communication.
The simplest agent example is the casual agent: The simplest agent example is the casual agent:
File diff suppressed because it is too large Load Diff
-1
View File
@@ -10,7 +10,6 @@
"axios": "^1.8.4", "axios": "^1.8.4",
"react": "^19.1.0", "react": "^19.1.0",
"react-dom": "^19.1.0", "react-dom": "^19.1.0",
"react-markdown": "^10.1.0",
"react-scripts": "5.0.1", "react-scripts": "5.0.1",
"web-vitals": "^2.1.4" "web-vitals": "^2.1.4"
}, },
Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.2 KiB

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 148 KiB

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

File diff suppressed because it is too large Load Diff
+257 -397
View File
@@ -1,417 +1,277 @@
import React, { useState, useEffect, useRef, useCallback } from "react"; import React, { useState, useEffect, useRef } from 'react';
import ReactMarkdown from "react-markdown"; import axios from 'axios';
import axios from "axios"; import './App.css';
import "./App.css"; import { colors } from './colors';
import { ThemeToggle } from "./components/ThemeToggle";
import { ResizableLayout } from "./components/ResizableLayout";
import faviconPng from "./logo.png";
const BACKEND_URL = process.env.REACT_APP_BACKEND_URL;
console.log("Using backend URL:", BACKEND_URL);
function App() { function App() {
const [query, setQuery] = useState(""); const [query, setQuery] = useState('');
const [messages, setMessages] = useState([]); const [messages, setMessages] = useState([]);
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null); const [error, setError] = useState(null);
const [currentView, setCurrentView] = useState("blocks"); const [currentView, setCurrentView] = useState('blocks');
const [responseData, setResponseData] = useState(null); const [responseData, setResponseData] = useState(null);
const [isOnline, setIsOnline] = useState(false); const [isOnline, setIsOnline] = useState(false);
const [status, setStatus] = useState("Agents ready"); const [status, setStatus] = useState('Agents ready');
const [expandedReasoning, setExpandedReasoning] = useState(new Set()); const messagesEndRef = useRef(null);
const messagesEndRef = useRef(null);
const fetchLatestAnswer = useCallback(async () => { useEffect(() => {
try { const intervalId = setInterval(() => {
const res = await axios.get(`${BACKEND_URL}/latest_answer`); checkHealth();
const data = res.data; fetchLatestAnswer();
fetchScreenshot();
}, 3000);
return () => clearInterval(intervalId);
}, [messages]);
updateData(data); const checkHealth = async () => {
if (!data.answer || data.answer.trim() === "") { try {
return; await axios.get('http://0.0.0.0:8000/health');
} setIsOnline(true);
const normalizedNewAnswer = normalizeAnswer(data.answer); console.log('System is online');
const answerExists = messages.some( } catch {
(msg) => normalizeAnswer(msg.content) === normalizedNewAnswer setIsOnline(false);
); console.log('System is offline');
if (!answerExists) { }
setMessages((prev) => [ };
...prev,
{ const fetchScreenshot = async () => {
type: "agent", try {
content: data.answer, const timestamp = new Date().getTime();
reasoning: data.reasoning, const res = await axios.get(`http://0.0.0.0:8000/screenshots/updated_screen.png?timestamp=${timestamp}`, {
agentName: data.agent_name, responseType: 'blob'
});
console.log('Screenshot fetched successfully');
const imageUrl = URL.createObjectURL(res.data);
setResponseData((prev) => {
if (prev?.screenshot && prev.screenshot !== 'placeholder.png') {
URL.revokeObjectURL(prev.screenshot);
}
return {
...prev,
screenshot: imageUrl,
screenshotTimestamp: new Date().getTime()
};
});
} catch (err) {
console.error('Error fetching screenshot:', err);
setResponseData((prev) => ({
...prev,
screenshot: 'placeholder.png',
screenshotTimestamp: new Date().getTime()
}));
}
};
const normalizeAnswer = (answer) => {
return answer
.trim()
.toLowerCase()
.replace(/\s+/g, ' ')
.replace(/[.,!?]/g, '')
};
const scrollToBottom = () => {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
};
const fetchLatestAnswer = async () => {
try {
const res = await axios.get('http://0.0.0.0:8000/latest_answer');
const data = res.data;
updateData(data);
if (!data.answer || data.answer.trim() === '') {
return;
}
const normalizedNewAnswer = normalizeAnswer(data.answer);
const answerExists = messages.some(
(msg) => normalizeAnswer(msg.content) === normalizedNewAnswer
);
if (!answerExists) {
setMessages((prev) => [
...prev,
{
type: 'agent',
content: data.answer,
agentName: data.agent_name,
status: data.status,
uid: data.uid,
},
]);
setStatus(data.status);
scrollToBottom();
} else {
console.log('Duplicate answer detected, skipping:', data.answer);
}
} catch (error) {
console.error('Error fetching latest answer:', error);
}
};
const updateData = (data) => {
setResponseData((prev) => ({
...prev,
blocks: data.blocks || prev.blocks || null,
done: data.done,
answer: data.answer,
agent_name: data.agent_name,
status: data.status, status: data.status,
uid: data.uid, uid: data.uid,
}, }));
]); };
setStatus(data.status);
scrollToBottom();
} else {
console.log("Duplicate answer detected, skipping:", data.answer);
}
} catch (error) {
console.error("Error fetching latest answer:", error);
}
}, [messages]);
useEffect(() => { const handleSubmit = async (e) => {
const intervalId = setInterval(() => { e.preventDefault();
checkHealth(); checkHealth();
fetchLatestAnswer(); if (!query.trim()) {
fetchScreenshot(); console.log('Empty query');
}, 3000); return;
return () => clearInterval(intervalId);
}, [fetchLatestAnswer]);
const checkHealth = async () => {
try {
await axios.get(`${BACKEND_URL}/health`);
setIsOnline(true);
console.log("System is online");
} catch {
setIsOnline(false);
console.log("System is offline");
}
};
const fetchScreenshot = async () => {
try {
const timestamp = new Date().getTime();
const res = await axios.get(
`${BACKEND_URL}/screenshots/updated_screen.png?timestamp=${timestamp}`,
{
responseType: "blob",
} }
); setMessages((prev) => [...prev, { type: 'user', content: query }]);
console.log("Screenshot fetched successfully"); setIsLoading(true);
const imageUrl = URL.createObjectURL(res.data); setError(null);
setResponseData((prev) => {
if (prev?.screenshot && prev.screenshot !== "placeholder.png") { try {
URL.revokeObjectURL(prev.screenshot); console.log('Sending query:', query);
setQuery('waiting for response...');
const res = await axios.post('http://0.0.0.0:8000/query', {
query,
tts_enabled: false
});
setQuery('Enter your query...');
console.log('Response:', res.data);
const data = res.data;
updateData(data);
} catch (err) {
console.error('Error:', err);
setError('Failed to process query.');
setMessages((prev) => [
...prev,
{ type: 'error', content: 'Error: Unable to get a response.' },
]);
} finally {
console.log('Query completed');
setIsLoading(false);
setQuery('');
} }
return { };
...prev,
screenshot: imageUrl,
screenshotTimestamp: new Date().getTime(),
};
});
} catch (err) {
console.error("Error fetching screenshot:", err);
setResponseData((prev) => ({
...prev,
screenshot: "placeholder.png",
screenshotTimestamp: new Date().getTime(),
}));
}
};
const normalizeAnswer = (answer) => { const handleGetScreenshot = async () => {
return answer try {
.trim() setCurrentView('screenshot');
.toLowerCase() } catch (err) {
.replace(/\s+/g, " ") setError('Browser not in use');
.replace(/[.,!?]/g, ""); }
}; };
const scrollToBottom = () => { return (
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" }); <div className="app">
}; <header className="header">
<h1>AgenticSeek</h1>
</header>
<main className="main">
<div className="app-sections">
const toggleReasoning = (messageIndex) => {
setExpandedReasoning((prev) => {
const newSet = new Set(prev);
if (newSet.has(messageIndex)) {
newSet.delete(messageIndex);
} else {
newSet.add(messageIndex);
}
return newSet;
});
};
const updateData = (data) => { <div className="chat-section">
setResponseData((prev) => ({ <h2>Chat Interface</h2>
...prev, <div className="messages">
blocks: data.blocks || prev.blocks || null, {messages.length === 0 ? (
done: data.done, <p className="placeholder">No messages yet. Type below to start!</p>
answer: data.answer, ) : (
agent_name: data.agent_name, messages.map((msg, index) => (
status: data.status, <div
uid: data.uid, key={index}
})); className={`message ${
}; msg.type === 'user'
? 'user-message'
const handleStop = async (e) => { : msg.type === 'agent'
e.preventDefault(); ? 'agent-message'
checkHealth(); : 'error-message'
setIsLoading(false); }`}
setError(null); >
try { {msg.type === 'agent' && (
await axios.get(`${BACKEND_URL}/stop`); <span className="agent-name">{msg.agentName}</span>
setStatus("Requesting stop..."); )}
} catch (err) { <p>{msg.content}</p>
console.error("Error stopping the agent:", err); </div>
} ))
}; )}
<div ref={messagesEndRef} />
const handleSubmit = async (e) => { </div>
e.preventDefault(); {isOnline && <div className="loading-animation">{status}</div>}
checkHealth(); {!isLoading && !isOnline && <p className="loading-animation">System offline. Deploy backend first.</p>}
if (!query.trim()) { <form onSubmit={handleSubmit} className="input-form">
console.log("Empty query"); <input
return; type="text"
} value={query}
setMessages((prev) => [...prev, { type: "user", content: query }]); onChange={(e) => setQuery(e.target.value)}
setIsLoading(true); placeholder="Type your query..."
setError(null); disabled={isLoading}
/>
try { <button type="submit" disabled={isLoading}>
console.log("Sending query:", query); Send
setQuery("waiting for response..."); </button>
const res = await axios.post(`${BACKEND_URL}/query`, { </form>
query,
tts_enabled: false,
});
setQuery("Enter your query...");
console.log("Response:", res.data);
const data = res.data;
updateData(data);
} catch (err) {
console.error("Error:", err);
setError("Failed to process query.");
setMessages((prev) => [
...prev,
{ type: "error", content: "Error: Unable to get a response." },
]);
} finally {
console.log("Query completed");
setIsLoading(false);
setQuery("");
}
};
const handleGetScreenshot = async () => {
try {
setCurrentView("screenshot");
} catch (err) {
setError("Browser not in use");
}
};
return (
<div className="app">
<header className="header">
<div className="header-brand">
<div className="logo-container">
<img src={faviconPng} alt="AgenticSeek" className="logo-icon" />
</div>
<div className="brand-text">
<h1>AgenticSeek</h1>
</div>
</div>
<div className="header-status">
<div
className={`status-indicator ${isOnline ? "online" : "offline"}`}
>
<div className="status-dot"></div>
<span className="status-text">
{isOnline ? "Online" : "Offline"}
</span>
</div>
</div>
<div className="header-actions">
<a
href="https://github.com/Fosowl/agenticSeek"
target="_blank"
rel="noopener noreferrer"
className="action-button github-link"
aria-label="View on GitHub"
>
<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
<path d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z" />
</svg>
<span className="action-text">GitHub</span>
</a>
<div>
<ThemeToggle />
</div>
</div>
</header>
<main className="main">
<ResizableLayout initialLeftWidth={50}>
<div className="chat-section">
<h2>Chat Interface</h2>
<div className="messages">
{messages.length === 0 ? (
<p className="placeholder">
No messages yet. Type below to start!
</p>
) : (
messages.map((msg, index) => (
<div
key={index}
className={`message ${
msg.type === "user"
? "user-message"
: msg.type === "agent"
? "agent-message"
: "error-message"
}`}
>
<div className="message-header">
{msg.type === "agent" && (
<span className="agent-name">{msg.agentName}</span>
)}
{msg.type === "agent" &&
msg.reasoning &&
expandedReasoning.has(index) && (
<div className="reasoning-content">
<ReactMarkdown>{msg.reasoning}</ReactMarkdown>
</div>
)}
{msg.type === "agent" && (
<button
className="reasoning-toggle"
onClick={() => toggleReasoning(index)}
title={
expandedReasoning.has(index)
? "Hide reasoning"
: "Show reasoning"
}
>
{expandedReasoning.has(index) ? "▼" : "▶"} Reasoning
</button>
)}
</div> </div>
<div className="message-content">
<ReactMarkdown>{msg.content}</ReactMarkdown>
</div>
</div>
))
)}
<div ref={messagesEndRef} />
</div>
{isOnline && <div className="loading-animation">{status}</div>}
{!isLoading && !isOnline && (
<p className="loading-animation">
System offline. Deploy backend first.
</p>
)}
<form onSubmit={handleSubmit} className="input-form">
<input
type="text"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Type your query..."
disabled={isLoading}
/>
<div className="action-buttons">
<button
type="submit"
disabled={isLoading}
className="icon-button"
aria-label="Send message"
>
<svg width="18" height="18" viewBox="0 0 24 24" fill="none">
<path
d="M22 2L11 13M22 2L15 22L11 13M22 2L2 9L11 13"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
</button>
<button
type="button"
onClick={handleStop}
className="icon-button stop-button"
aria-label="Stop processing"
>
<svg width="16" height="16" viewBox="0 0 24 24" fill="none">
<rect
x="6"
y="6"
width="12"
height="12"
fill="currentColor"
rx="2"
/>
</svg>
</button>
</div>
</form>
</div>
<div className="computer-section"> <div className="computer-section">
<h2>Computer View</h2> <h2>Computer View</h2>
<div className="view-selector"> <div className="view-selector">
<button <button
className={currentView === "blocks" ? "active" : ""} className={currentView === 'blocks' ? 'active' : ''}
onClick={() => setCurrentView("blocks")} onClick={() => setCurrentView('blocks')}
> >
Editor View Editor View
</button> </button>
<button <button
className={currentView === "screenshot" ? "active" : ""} className={currentView === 'screenshot' ? 'active' : ''}
onClick={ onClick={responseData?.screenshot ? () => setCurrentView('screenshot') : handleGetScreenshot}
responseData?.screenshot >
? () => setCurrentView("screenshot") Browser View
: handleGetScreenshot </button>
} </div>
> <div className="content">
Browser View {error && <p className="error">{error}</p>}
</button> {currentView === 'blocks' ? (
</div> <div className="blocks">
<div className="content"> {responseData && responseData.blocks && Object.values(responseData.blocks).length > 0 ? (
{error && <p className="error">{error}</p>} Object.values(responseData.blocks).map((block, index) => (
{currentView === "blocks" ? ( <div key={index} className="block">
<div className="blocks"> <p className="block-tool">Tool: {block.tool_type}</p>
{responseData && <pre>{block.block}</pre>
responseData.blocks && <p className="block-feedback">Feedback: {block.feedback}</p>
Object.values(responseData.blocks).length > 0 ? ( <p className="block-success">
Object.values(responseData.blocks).map((block, index) => ( Success: {block.success ? 'Yes' : 'No'}
<div key={index} className="block"> </p>
<p className="block-tool">Tool: {block.tool_type}</p> </div>
<pre>{block.block}</pre> ))
<p className="block-feedback"> ) : (
Feedback: {block.feedback} <div className="block">
</p> <p className="block-tool">Tool: No tool in use</p>
{block.success ? ( <pre>No file opened</pre>
<p className="block-success">Success</p> </div>
) : ( )}
<p className="block-failure">Failure</p> </div>
)} ) : (
</div> <div className="screenshot">
)) <img
) : ( src={responseData?.screenshot || 'placeholder.png'}
<div className="block"> alt="Screenshot"
<p className="block-tool">Tool: No tool in use</p> onError={(e) => {
<pre>No file opened</pre> e.target.src = 'placeholder.png';
console.error('Failed to load screenshot');
}}
key={responseData?.screenshotTimestamp || 'default'}
/>
</div>
)}
</div>
</div> </div>
)}
</div> </div>
) : ( </main>
<div className="screenshot"> </div>
<img );
src={responseData?.screenshot || "placeholder.png"}
alt="Screenshot"
onError={(e) => {
e.target.src = "placeholder.png";
console.error("Failed to load screenshot");
}}
key={responseData?.screenshotTimestamp || "default"}
/>
</div>
)}
</div>
</div>
</ResizableLayout>
</main>
</div>
);
} }
export default App; export default App;
+54 -55
View File
@@ -1,64 +1,63 @@
export const colors = { export const colors = {
// Primary colors - matching the dashboard theme // Primary colors
primary: "#2563eb", primary: '#0066cc',
primaryLight: "#dbeafe", primaryLight: '#e6f2ff',
primaryDark: "#1d4ed8", primaryDark: '#004c99',
// Secondary colors - modern grays // Secondary colors
secondary: "#64748b", secondary: '#6c757d',
secondaryLight: "#f1f5f9", secondaryLight: '#f8f9fa',
secondaryDark: "#1e293b", secondaryDark: '#343a40',
// Accent colors // Accent colors
accent: "#f59e0b", accent: '#ff9500',
accentLight: "#fef3c7", accentLight: '#fff4e6',
accentDark: "#d97706", accentDark: '#cc7a00',
// Status colors // Status colors
success: "#10b981", success: '#28a745',
successLight: "#d1fae5", successLight: '#e8f5e9',
warning: "#f59e0b", warning: '#ffc107',
warningLight: "#fef3c7", warningLight: '#fff9e6',
error: "#ef4444", error: '#dc3545',
errorLight: "#fee2e2", errorLight: '#ffebee',
info: "#06b6d4", info: '#17a2b8',
infoLight: "#cffafe", infoLight: '#e3f2fd',
// Neutral colors - modern palette // Neutral colors
white: "#ffffff", white: '#ffffff',
gray50: "#f8fafc", gray100: '#f8f9fa',
gray100: "#f1f5f9", gray200: '#e9ecef',
gray200: "#e2e8f0", gray300: '#dee2e6',
gray300: "#cbd5e1", gray400: '#ced4da',
gray400: "#94a3b8", gray500: '#adb5bd',
gray500: "#64748b", gray600: '#6c757d',
gray600: "#475569", gray700: '#495057',
gray700: "#334155", gray800: '#343a40',
gray800: "#1e293b", gray900: '#212529',
gray900: "#0f172a", black: '#000000',
black: "#000000",
// Text colors // Text colors
textPrimary: "#0f172a", textPrimary: '#212529',
textSecondary: "#64748b", textSecondary: '#6c757d',
textDisabled: "#94a3b8", textDisabled: '#adb5bd',
// Background colors // Background colors
background: "#f8fafc", background: '#f8f8f8',
card: "#ffffff", card: '#ffffff',
// Border colors // Border colors
border: "#e2e8f0", border: '#dee2e6',
divider: "#f1f5f9", divider: '#e9ecef',
// Transparent colors // Transparent colors
transparent: "transparent", transparent: 'transparent',
semiTransparent: "rgba(15, 23, 42, 0.6)", semiTransparent: 'rgba(0, 0, 0, 0.5)',
// Dark theme colors // Dark theme colors
darkBackground: "#0f172a", darkBackground: '#0f172a',
darkCard: "#1e293b", darkCard: '#1e293b',
darkBorder: "#334155", darkBorder: '#334155',
darkText: "#f8fafc", darkText: '#f8fafc',
darkTextSecondary: "#cbd5e1", darkTextSecondary: '#cbd5e1',
}; };
@@ -1,69 +0,0 @@
.resizable-container {
display: flex;
width: 100%;
height: 100%;
overflow: hidden;
}
.resizable-left,
.resizable-right {
height: 100%;
overflow: hidden;
min-width: 0;
}
.resize-handle {
width: 8px;
background-color: transparent;
cursor: col-resize;
display: flex;
align-items: center;
justify-content: center;
padding: 0 2px;
transition: background-color 0.2s ease;
position: relative;
flex-shrink: 0;
}
.resize-handle:hover {
background-color: var(--accent);
}
.resize-handle-line {
width: 2px;
height: 40px;
background-color: var(--border);
border-radius: 1px;
transition: all 0.2s ease;
}
.resize-handle:hover .resize-handle-line {
background-color: var(--accent-foreground);
height: 60px;
}
.resizable-container.dragging .resize-handle {
background-color: var(--accent);
}
.resizable-container.dragging .resize-handle-line {
background-color: var(--accent-foreground);
height: 100vh;
}
/* Mobile responsiveness */
@media (max-width: 768px) {
.resizable-container {
flex-direction: column;
}
.resizable-left,
.resizable-right {
width: 100% !important;
height: 50vh;
}
.resize-handle {
display: none;
}
}
@@ -1,70 +0,0 @@
import React, { useState, useRef, useCallback } from "react";
import "./ResizableLayout.css";
export const ResizableLayout = ({ children, initialLeftWidth = 50 }) => {
const [leftWidth, setLeftWidth] = useState(initialLeftWidth);
const [isDragging, setIsDragging] = useState(false);
const containerRef = useRef(null);
const handleMouseDown = useCallback((e) => {
e.preventDefault();
setIsDragging(true);
}, []);
const handleMouseMove = useCallback(
(e) => {
if (!isDragging || !containerRef.current) return;
const containerRect = containerRef.current.getBoundingClientRect();
const newLeftWidth =
((e.clientX - containerRect.left) / containerRect.width) * 100;
// Constrain between 20% and 80%
const constrainedWidth = Math.max(20, Math.min(80, newLeftWidth));
setLeftWidth(constrainedWidth);
},
[isDragging]
);
const handleMouseUp = useCallback(() => {
setIsDragging(false);
}, []);
React.useEffect(() => {
if (isDragging) {
document.addEventListener("mousemove", handleMouseMove);
document.addEventListener("mouseup", handleMouseUp);
document.body.style.cursor = "col-resize";
document.body.style.userSelect = "none";
} else {
document.removeEventListener("mousemove", handleMouseMove);
document.removeEventListener("mouseup", handleMouseUp);
document.body.style.cursor = "";
document.body.style.userSelect = "";
}
return () => {
document.removeEventListener("mousemove", handleMouseMove);
document.removeEventListener("mouseup", handleMouseUp);
document.body.style.cursor = "";
document.body.style.userSelect = "";
};
}, [isDragging, handleMouseMove, handleMouseUp]);
return (
<div
ref={containerRef}
className={`resizable-container ${isDragging ? "dragging" : ""}`}
>
<div className="resizable-left" style={{ width: `${leftWidth}%` }}>
{children[0]}
</div>
<div className="resize-handle" onMouseDown={handleMouseDown}>
<div className="resize-handle-line" />
</div>
<div className="resizable-right" style={{ width: `${100 - leftWidth}%` }}>
{children[1]}
</div>
</div>
);
};
@@ -1,34 +0,0 @@
import React from "react";
import { useTheme } from "../contexts/ThemeContext";
export const ThemeToggle = () => {
const { isDark, toggleTheme } = useTheme();
return (
<button
onClick={toggleTheme}
className="theme-toggle"
aria-label="Toggle theme"
>
{isDark ? (
<svg width="20" height="20" viewBox="0 0 24 24" fill="none">
<circle cx="12" cy="12" r="5" stroke="currentColor" strokeWidth="2" />
<path
d="M12 1v2M12 21v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M1 12h2M21 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42"
stroke="currentColor"
strokeWidth="2"
/>
</svg>
) : (
<svg width="20" height="20" viewBox="0 0 24 24" fill="none">
<path
d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"
stroke="currentColor"
strokeWidth="2"
fill="currentColor"
/>
</svg>
)}
</button>
);
};
@@ -1,34 +0,0 @@
import React, { createContext, useContext, useState, useEffect } from "react";
const ThemeContext = createContext();
export const ThemeProvider = ({ children }) => {
const [isDark, setIsDark] = useState(() => {
const saved = localStorage.getItem("theme");
return saved ? saved === "dark" : true; // Default to dark
});
useEffect(() => {
localStorage.setItem("theme", isDark ? "dark" : "light");
document.documentElement.setAttribute(
"data-theme",
isDark ? "dark" : "light"
);
}, [isDark]);
const toggleTheme = () => setIsDark(!isDark);
return (
<ThemeContext.Provider value={{ isDark, toggleTheme }}>
{children}
</ThemeContext.Provider>
);
};
export const useTheme = () => {
const context = useContext(ThemeContext);
if (!context) {
throw new Error("useTheme must be used within ThemeProvider");
}
return context;
};
+6 -10
View File
@@ -1,14 +1,10 @@
import React from "react"; import React from 'react';
import ReactDOM from "react-dom/client"; import ReactDOM from 'react-dom/client';
import App from "./App"; import App from './App';
import { ThemeProvider } from "./contexts/ThemeContext";
import "./styles/globals.css";
const root = ReactDOM.createRoot(document.getElementById("root")); const root = ReactDOM.createRoot(document.getElementById('root'));
root.render( root.render(
<React.StrictMode> <React.StrictMode>
<ThemeProvider> <App />
<App />
</ThemeProvider>
</React.StrictMode> </React.StrictMode>
); );
Binary file not shown.

Before

Width:  |  Height:  |  Size: 148 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 841.9 595.3"><g fill="#61DAFB"><path d="M666.3 296.5c0-32.5-40.7-63.3-103.1-82.4 14.4-63.6 8-114.2-20.2-130.4-6.5-3.8-14.1-5.6-22.4-5.6v22.3c4.6 0 8.3.9 11.4 2.6 13.6 7.8 19.5 37.5 14.9 75.7-1.1 9.4-2.9 19.3-5.1 29.4-19.6-4.8-41-8.5-63.5-10.9-13.5-18.5-27.5-35.3-41.6-50 32.6-30.3 63.2-46.9 84-46.9V78c-27.5 0-63.5 19.6-99.9 53.6-36.4-33.8-72.4-53.2-99.9-53.2v22.3c20.7 0 51.4 16.5 84 46.6-14 14.7-28 31.4-41.3 49.9-22.6 2.4-44 6.1-63.6 11-2.3-10-4-19.7-5.2-29-4.7-38.2 1.1-67.9 14.6-75.8 3-1.8 6.9-2.6 11.5-2.6V78.5c-8.4 0-16 1.8-22.6 5.6-28.1 16.2-34.4 66.7-19.9 130.1-62.2 19.2-102.7 49.9-102.7 82.3 0 32.5 40.7 63.3 103.1 82.4-14.4 63.6-8 114.2 20.2 130.4 6.5 3.8 14.1 5.6 22.5 5.6 27.5 0 63.5-19.6 99.9-53.6 36.4 33.8 72.4 53.2 99.9 53.2 8.4 0 16-1.8 22.6-5.6 28.1-16.2 34.4-66.7 19.9-130.1 62-19.1 102.5-49.9 102.5-82.3zm-130.2-66.7c-3.7 12.9-8.3 26.2-13.5 39.5-4.1-8-8.4-16-13.1-24-4.6-8-9.5-15.8-14.4-23.4 14.2 2.1 27.9 4.7 41 7.9zm-45.8 106.5c-7.8 13.5-15.8 26.3-24.1 38.2-14.9 1.3-30 2-45.2 2-15.1 0-30.2-.7-45-1.9-8.3-11.9-16.4-24.6-24.2-38-7.6-13.1-14.5-26.4-20.8-39.8 6.2-13.4 13.2-26.8 20.7-39.9 7.8-13.5 15.8-26.3 24.1-38.2 14.9-1.3 30-2 45.2-2 15.1 0 30.2.7 45 1.9 8.3 11.9 16.4 24.6 24.2 38 7.6 13.1 14.5 26.4 20.8 39.8-6.3 13.4-13.2 26.8-20.7 39.9zm32.3-13c5.4 13.4 10 26.8 13.8 39.8-13.1 3.2-26.9 5.9-41.2 8 4.9-7.7 9.8-15.6 14.4-23.7 4.6-8 8.9-16.1 13-24.1zM421.2 430c-9.3-9.6-18.6-20.3-27.8-32 9 .4 18.2.7 27.5.7 9.4 0 18.7-.2 27.8-.7-9 11.7-18.3 22.4-27.5 32zm-74.4-58.9c-14.2-2.1-27.9-4.7-41-7.9 3.7-12.9 8.3-26.2 13.5-39.5 4.1 8 8.4 16 13.1 24 4.7 8 9.5 15.8 14.4 23.4zM420.7 163c9.3 9.6 18.6 20.3 27.8 32-9-.4-18.2-.7-27.5-.7-9.4 0-18.7.2-27.8.7 9-11.7 18.3-22.4 27.5-32zm-74 58.9c-4.9 7.7-9.8 15.6-14.4 23.7-4.6 8-8.9 16-13 24-5.4-13.4-10-26.8-13.8-39.8 13.1-3.1 26.9-5.8 41.2-7.9zm-90.5 125.2c-35.4-15.1-58.3-34.9-58.3-50.6 0-15.7 22.9-35.6 58.3-50.6 8.6-3.7 18-7 27.7-10.1 5.7 19.6 13.2 40 22.5 60.9-9.2 20.8-16.6 41.1-22.2 60.6-9.9-3.1-19.3-6.5-28-10.2zM310 490c-13.6-7.8-19.5-37.5-14.9-75.7 1.1-9.4 2.9-19.3 5.1-29.4 19.6 4.8 41 8.5 63.5 10.9 13.5 18.5 27.5 35.3 41.6 50-32.6 30.3-63.2 46.9-84 46.9-4.5-.1-8.3-1-11.3-2.7zm237.2-76.2c4.7 38.2-1.1 67.9-14.6 75.8-3 1.8-6.9 2.6-11.5 2.6-20.7 0-51.4-16.5-84-46.6 14-14.7 28-31.4 41.3-49.9 22.6-2.4 44-6.1 63.6-11 2.3 10.1 4.1 19.8 5.2 29.1zm38.5-66.7c-8.6 3.7-18 7-27.7 10.1-5.7-19.6-13.2-40-22.5-60.9 9.2-20.8 16.6-41.1 22.2-60.6 9.9 3.1 19.3 6.5 28.1 10.2 35.4 15.1 58.3 34.9 58.3 50.6-.1 15.7-23 35.6-58.4 50.6zM320.8 78.4z"/><circle cx="420.9" cy="296.5" r="45.7"/><path d="M520.5 78.1z"/></g></svg>

After

Width:  |  Height:  |  Size: 2.6 KiB

@@ -1,217 +0,0 @@
:root {
--background: hsl(0 0% 100%);
--foreground: hsl(222.2 47.4% 11.2%);
--muted: hsl(210 40% 96.1%);
--muted-foreground: hsl(215.4 16.3% 46.9%);
--popover: hsl(0 0% 100%);
--popover-foreground: hsl(222.2 47.4% 11.2%);
--card: hsl(0 0% 100%);
--card-foreground: hsl(222.2 47.4% 11.2%);
--border: hsl(214.3 31.8% 91.4%);
--input: hsl(214.3 31.8% 91.4%);
--primary: hsl(222.2 47.4% 11.2%);
--primary-foreground: hsl(210 40% 98%);
--secondary: hsl(210 40% 96.1%);
--secondary-foreground: hsl(222.2 47.4% 11.2%);
--accent: hsl(210 40% 96.1%);
--accent-foreground: hsl(222.2 47.4% 11.2%);
--destructive: hsl(0 100% 50%);
--destructive-foreground: hsl(210 40% 98%);
--ring: hsl(215 20.2% 65.1%);
--radius: 0.5rem;
}
.dark {
--background: hsl(224 71% 4%);
--foreground: hsl(213 31% 91%);
--muted: hsl(223 47% 11%);
--muted-foreground: hsl(215.4 16.3% 56.9%);
--popover: hsl(224 71% 4%);
--popover-foreground: hsl(215 20.2% 65.1%);
--card: hsl(224 71% 4%);
--card-foreground: hsl(213 31% 91%);
--border: hsl(216 34% 17%);
--input: hsl(216 34% 17%);
--primary: hsl(210 40% 98%);
--primary-foreground: hsl(222.2 47.4% 1.2%);
--secondary: hsl(222.2 47.4% 11.2%);
--secondary-foreground: hsl(210 40% 98%);
--accent: hsl(216 34% 17%);
--accent-foreground: hsl(210 40% 98%);
--destructive: hsl(0 63% 31%);
--destructive-foreground: hsl(210 40% 98%);
--ring: hsl(216 34% 17%);
--radius: 0.5rem;
}
[data-theme="dark"] {
--background: #0a0a0a;
--foreground: #fafafa;
--card: #1a1a1a;
--card-foreground: #fafafa;
--popover: #1a1a1a;
--popover-foreground: #fafafa;
--primary: #fafafa;
--primary-foreground: #0a0a0a;
--secondary: #2a2a2a;
--secondary-foreground: #fafafa;
--muted: #1e1e1e;
--muted-foreground: #a1a1aa;
--accent: #6b7280;
--accent-foreground: #ffffff;
--destructive: #ef4444;
--destructive-foreground: #ffffff;
--border: #333333;
--input: #333333;
--ring: #6b7280;
}
[data-theme="light"] {
--background: #ffffff;
--foreground: #0a0a0a;
--card: #ffffff;
--card-foreground: #0a0a0a;
--popover: #ffffff;
--popover-foreground: #0a0a0a;
--primary: #0a0a0a;
--primary-foreground: #ffffff;
--secondary: #f5f5f5;
--secondary-foreground: #0a0a0a;
--muted: #f5f5f5;
--muted-foreground: #737373;
--accent: #6b7280;
--accent-foreground: #ffffff;
--destructive: #ef4444;
--destructive-foreground: #ffffff;
--border: #e5e5e5;
--input: #e5e5e5;
--ring: #6b7280;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
background-color: var(--background);
color: var(--foreground);
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto",
sans-serif;
transition: background-color 0.3s ease, color 0.3s ease;
margin: 0;
padding: 0;
height: 100vh;
overflow: hidden;
}
html,
body,
#root {
height: 100%;
overflow: hidden;
}
.theme-toggle {
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
min-width: 44px;
height: 44px;
padding: 0 12px;
border-radius: 12px;
border: 1px solid var(--border);
background: var(--card);
color: var(--foreground);
text-decoration: none;
font-size: 0.875rem;
font-weight: 500;
cursor: pointer;
transition: all 0.3s ease;
position: relative;
overflow: hidden;
}
.theme-toggle::before {
content: "";
position: absolute;
top: 0;
left: -100%;
width: 100%;
height: 100%;
background: linear-gradient(
90deg,
transparent,
rgba(255, 255, 255, 0.1),
transparent
);
transition: left 0.5s ease;
}
.theme-toggle:hover::before {
left: 100%;
}
.theme-toggle:hover {
background: #24292e;
border-color: #24292e;
color: white;
transform: translateY(-2px);
box-shadow: 0 8px 25px rgba(36, 41, 46, 0.3);
}
.github-link {
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
min-width: 44px;
height: 44px;
padding: 0 12px;
border-radius: 12px;
border: 1px solid var(--border);
background: var(--card);
color: var(--foreground);
text-decoration: none;
font-size: 0.875rem;
font-weight: 500;
transition: all 0.3s ease;
position: relative;
overflow: hidden;
}
.github-link::before {
content: "";
position: absolute;
top: 0;
left: -100%;
width: 100%;
height: 100%;
background: linear-gradient(
90deg,
transparent,
rgba(255, 255, 255, 0.1),
transparent
);
transition: left 0.5s ease;
}
.github-link:hover::before {
left: 100%;
}
.github-link:hover {
background: #24292e;
border-color: #24292e;
color: white;
transform: translateY(-2px);
box-shadow: 0 8px 25px rgba(36, 41, 46, 0.3);
}
.header-actions {
display: flex;
align-items: center;
gap: 12px;
}
+1
View File
@@ -5,6 +5,7 @@ set LLM_ROUTER_DIR=llm_router
if exist "%SCRIPTS_DIR%\windows_install.bat" ( if exist "%SCRIPTS_DIR%\windows_install.bat" (
echo Running Windows installation script... echo Running Windows installation script...
call "%SCRIPTS_DIR%\windows_install.bat" call "%SCRIPTS_DIR%\windows_install.bat"
cd "%LLM_ROUTER_DIR%" && call dl_safetensors.bat
) else ( ) else (
echo Error: %SCRIPTS_DIR%\windows_install.bat not found! echo Error: %SCRIPTS_DIR%\windows_install.bat not found!
exit /b 1 exit /b 1
+2 -2
View File
@@ -1,6 +1,6 @@
########## ##########
# Dummy script to download the model # Dummy script to download the model
# Because downloading with hugging face does not seem to work, maybe I am doing something wrong? # Because dowloading with hugging face does not seem to work, maybe I am doing something wrong?
# AdaptiveClassifier.from_pretrained("adaptive-classifier/llm-router") ----> result in config.json not found # AdaptiveClassifier.from_pretrained("adaptive-classifier/llm-router") ----> result in config.json not found
# Therefore, I put all the files in llm_router and download the model file with this script, If you know a better way please raise an issue # Therefore, I put all the files in llm_router and download the model file with this script, If you know a better way please raise an issue
######### #########
@@ -30,4 +30,4 @@ if [ ! -f "$FILENAME" ]; then
fi fi
else else
echo "File already exists, skipping download" echo "File already exists, skipping download"
fi fi
+2 -2
View File
@@ -6966,7 +6966,7 @@
0.010188529267907143 0.010188529267907143
], ],
"label": "LOW", "label": "LOW",
"text": "You are AoControl, a helpful and knowledgeable agent. To achieve your goal of answering complex questions correctly, you have access to the following tools:\n AoInnovus: An agent with knowledge of the Cadence Innovus User Guide and corresponding Tcl command usage\n AoTcl: An agent with knowledge of the Tcl language\nTo answer questions, you'll need to go through multiple steps involving step-by-step thinking and selecting appropriate tools and their inputs; tools will respond with observations.\nWhen you are ready for a final answer, respond with the `Final Answer:`\nUse the following format:\nQuestion: The question to be answered\nTHought: Reason if you have the final answer. If yes, answer the question. If not, find out the missing information needed to answer it.\nTool: Pick one of {AoInnovus, AoTcl}\nTool Input: The input for the tool\nObservation: The tool will respond with the result\n...\nFinal Answer: The final answer to the question, make it short (50-100 words)\nThought, Tool, Tool Input, and Observation steps can be repeated multiple times, but sometimes we can find an answer in the first pass.\n---\nQuestion: How do I identify the impact of metal fill on my timing violations?\nThought: Let's think step-by-step, I first need to" "text": "You are AoControl, a helpful and knowledgeable agent. To achieve your goal of answering complex questions correctly, you have access to the following tools:\n AoInnovus: An agent with knowledge of the Cadence Innovus User Guide and corresponding Tcl command usage\n AoTcl: An agent with knowledge of the Tcl language\nTo answer questions, you'll need to go through multiple steps involving step-by-step thinking and selecting appropriate tools and their inputs; tools will respond with observations.\nWhen you are ready for a final answer, respond with the `Final Answer:`\nUse the following format:\nQuestion: The question to be answered\nTHought: Reason if you have the final answer. If yes, anwer the question. If not, find out the missing information needed to answer it.\nTool: Pick one of {AoInnovus, AoTcl}\nTool Input: The input for the tool\nObservation: The tool will respond with the result\n...\nFinal Answer: The final answer to the question, make it short (50-100 words)\nThought, Tool, Tool Input, and Observation steps can be repeated multiple times, but sometimes we can find an answer in the first pass.\n---\nQuestion: How do I identify the impact of metal fill on my timing violations?\nThought: Let's think step-by-step, I first need to"
}, },
{ {
"embedding": [ "embedding": [
@@ -7743,4 +7743,4 @@
"text": "Generate service startup ideas based on experiences around data science and artificial intelligence for teenagers. For example, when I say \u201cI wish there was an exciting way to explore the worlds of data science and artificial intelligence this summer\u201d, you generate a business plan for the digital startup complete with idea name, a short one liner, target user persona, user\u2019s pain points to solve, main value propositions, sales & marketing channels, revenue stream sources, cost structures, key activities, key resources, key partners, idea validation steps, estimated 1st year cost of operation, and potential business challenges to look for. Write the result in a markdown table." "text": "Generate service startup ideas based on experiences around data science and artificial intelligence for teenagers. For example, when I say \u201cI wish there was an exciting way to explore the worlds of data science and artificial intelligence this summer\u201d, you generate a business plan for the digital startup complete with idea name, a short one liner, target user persona, user\u2019s pain points to solve, main value propositions, sales & marketing channels, revenue stream sources, cost structures, key activities, key resources, key partners, idea validation steps, estimated 1st year cost of operation, and potential business challenges to look for. Write the result in a markdown table."
} }
] ]
} }
Binary file not shown.

Before

Width:  |  Height:  |  Size: 118 KiB

+3 -3
View File
@@ -20,7 +20,7 @@ toto.py
You can execute bash command using the bash tag : You can execute bash command using the bash tag :
```bash ```bash
#!/bin/bash #!/bin/bash
ls -la # example ls -la # exemple
``` ```
You can execute python using the python tag You can execute python using the python tag
@@ -48,5 +48,5 @@ Some rules:
- You do not ever need to use bash to execute code. - You do not ever need to use bash to execute code.
- Do not ever tell user how to run it. user know it. - Do not ever tell user how to run it. user know it.
- If using gui, make sure echap or exit button close the program - If using gui, make sure echap or exit button close the program
- No laziness, write and rewrite full code every time - No lazyness, write and rewrite full code every time
- If query is unclear say REQUEST_CLARIFICATION - If query is unclear say REQUEST_CLARIFICATION
+3 -3
View File
@@ -29,7 +29,7 @@ You: Sure, here is the plan:
## Task 3: I will setup the project using the file agent ## Task 3: I will setup the project using the file agent
## Task 4: I assign the coding agent to make a weather app in python ## Task 4: I asign the coding agent to make a weather app in python
```json ```json
{ {
@@ -74,7 +74,7 @@ Rules:
- Put your plan in a json with the key "plan". - Put your plan in a json with the key "plan".
- specify work folder name to all coding or file agents. - specify work folder name to all coding or file agents.
- You might use a file agent before code agent to setup a project properly. specify folder name. - You might use a file agent before code agent to setup a project properly. specify folder name.
- Give clear, detailed order to each agent and how their task relate to the previous task (if any). - Give clear, detailled order to each agent and how their task relate to the previous task (if any).
- The file agent can only conduct one action at the time. successive file agent could be needed. - The file agent can only conduct one action at the time. successive file agent could be needed.
- Only use web agent for finding necessary informations. - Only use web agent for finding necessary informations.
- Always tell the coding agent where to save file. - Always tell the coding agent where to save file.
@@ -82,4 +82,4 @@ Rules:
- Make sure json is within ```json tag - Make sure json is within ```json tag
- Coding agent should write the whole code in a single file unless instructed otherwise. - Coding agent should write the whole code in a single file unless instructed otherwise.
- Do not use python for NLP analysis of a text, you can review a text with the casual agent - Do not use python for NLP analysis of a text, you can review a text with the casual agent
- One step, one agent. - One step, one agent.
-56
View File
@@ -1,56 +0,0 @@
[project]
name = "agenticseek"
version = "0.1.0"
description = "Add your description here"
readme = "README.md"
requires-python = ">=3.10"
dependencies = [
"adaptive-classifier>=0.0.10",
"aiofiles>=24.1.0",
"anyio>=3.5.0,<5",
"celery>=5.5.1",
"certifi==2025.4.26",
"chromedriver-autoinstaller>=0.6.4",
"colorama>=0.4.6",
"distro>=1.7.0,<2",
"fake-useragent>=2.1.0",
"fastapi>=0.115.12",
"flask>=3.1.0",
"httpx>=0.27,<0.29",
"ipython>=8.13.0",
"jiter>=0.4.0,<1",
"kokoro==0.9.4",
"langid>=1.1.6",
"librosa>=0.10.2.post1",
"markdownify>=1.1.0",
"numpy>=1.24.4",
"ollama>=0.4.7",
"openai>=1.84.0",
"ordered-set>=4.1.0",
"playsound3>=1.0.0",
"protobuf>=3.20.3",
"pyaudio>=0.2.14",
"pydantic>=2.10.6",
"pydantic-core>=2.27.2",
"pypdf>=5.4.0",
"pypinyin>=0.54.0",
"pyreadline3>=3.5.4",
"python-dotenv>=1.0.0",
"requests>=2.31.0",
"sacremoses>=0.0.53",
"scipy>=1.9.3",
"selenium>=4.27.1",
"selenium-stealth>=1.0.6",
"sentencepiece>=0.2.0",
"setuptools>=75.6.0",
"sniffio>=1.3.1",
"soundfile>=0.13.1",
"termcolor>=2.4.0",
"text2emotion>=0.0.5",
"together>=1.5.0",
"torch>=2.4.1",
"tqdm>4",
"transformers>=4.46.3",
"undetected-chromedriver>=3.5.5",
"uvicorn>=0.34.0",
]
+2 -2
View File
@@ -13,10 +13,11 @@ requests>=2.31.0
numpy>=1.24.4 numpy>=1.24.4
colorama>=0.4.6 colorama>=0.4.6
python-dotenv>=1.0.0 python-dotenv>=1.0.0
playsound3>=1.0.0 playsound>=1.3.0
soundfile>=0.13.1 soundfile>=0.13.1
transformers>=4.46.3 transformers>=4.46.3
torch>=2.4.1 torch>=2.4.1
python-dotenv>=1.0.0
ollama>=0.4.7 ollama>=0.4.7
scipy>=1.9.3 scipy>=1.9.3
soundfile>=0.13.1 soundfile>=0.13.1
@@ -40,7 +41,6 @@ fake_useragent>=2.1.0
selenium_stealth>=1.0.6 selenium_stealth>=1.0.6
undetected-chromedriver>=3.5.5 undetected-chromedriver>=3.5.5
sentencepiece>=0.2.0 sentencepiece>=0.2.0
together>=1.5.0
tqdm>4 tqdm>4
openai openai
sniffio sniffio
+12 -31
View File
@@ -3,19 +3,14 @@
echo "Starting installation for Linux..." echo "Starting installation for Linux..."
set -e set -e
# Check if uv is installed
if ! command -v uv &> /dev/null; then
echo "Error: uv is not installed. Please install uv first."
echo "You can install it using: curl -LsSf https://astral.sh/uv/install.sh | sh"
exit 1
fi
# Update package list # Update package list
sudo apt-get update || { echo "Failed to update package list"; exit 1; } sudo apt-get update || { echo "Failed to update package list"; exit 1; }
# make sure essential tool are installed # make sure essential tool are installed
# Install essential tools
sudo apt-get install -y \ sudo apt-get install -y \
python3-dev \ python3-dev \
python3-pip \
python3-wheel \
build-essential \ build-essential \
alsa-utils \ alsa-utils \
portaudio19-dev \ portaudio19-dev \
@@ -26,29 +21,15 @@ sudo apt-get install -y \
libnss3 \ libnss3 \
libxss1 || { echo "Failed to install packages"; exit 1; } libxss1 || { echo "Failed to install packages"; exit 1; }
# Initialize uv project if pyproject.toml doesn't exist # upgrade pip
if [ ! -f "pyproject.toml" ]; then pip install --upgrade pip
echo "Initializing uv project..." # install wheel
uv init --python 3.10 || { echo "Failed to initialize uv project"; exit 1; } pip install --upgrade pip setuptools wheel
fi
# Sync the project (creates venv and installs dependencies)
echo "Setting up Python environment with uv..."
uv sync --python 3.10 || { echo "Failed to sync uv project"; exit 1; }
# Add specific packages
echo "Adding Selenium..."
uv add selenium || { echo "Failed to add selenium"; exit 1; }
# Add dependencies from requirements.txt if it exists
if [ -f "requirements.txt" ]; then
echo "Adding dependencies from requirements.txt..."
uv add -r requirements.txt || { echo "Failed to add requirements from requirements.txt"; exit 1; }
fi
# install docker compose # install docker compose
sudo apt install -y docker-compose sudo apt install -y docker-compose
# Install Selenium for chromedriver
pip3 install selenium
# Install Python dependencies from requirements.txt
pip3 install -r requirements.txt --no-cache-dir
echo "Installation complete for Linux!" echo "Installation complete for Linux!"
echo "To activate the environment, run: source .venv/bin/activate"
echo "Or run commands with: uv run <command>"
+9 -30
View File
@@ -4,13 +4,6 @@ echo "Starting installation for macOS..."
set -e set -e
# Check if uv is installed
if ! command -v uv &> /dev/null; then
echo "Error: uv is not installed. Please install uv first."
echo "You can install it using: curl -LsSf https://astral.sh/uv/install.sh | sh"
exit 1
fi
# Check if homebrew is installed # Check if homebrew is installed
if ! command -v brew &> /dev/null; then if ! command -v brew &> /dev/null; then
echo "Homebrew not found. Installing Homebrew..." echo "Homebrew not found. Installing Homebrew..."
@@ -25,27 +18,13 @@ brew install wget
brew install --cask chromedriver brew install --cask chromedriver
# Install portaudio for pyAudio using Homebrew # Install portaudio for pyAudio using Homebrew
brew install portaudio brew install portaudio
# update pip
python3 -m pip install --upgrade pip
# upgrade setuptools and wheel
pip3 install --upgrade setuptools wheel
# Install Selenium
pip3 install selenium
# Install Python dependencies from requirements.txt
pip3 install -r requirements.txt --no-cache-dir
# Initialize uv project if pyproject.toml doesn't exist echo "Installation complete for macOS!"
if [ ! -f "pyproject.toml" ]; then
echo "Initializing uv project..."
uv init --python 3.10 || { echo "Failed to initialize uv project"; exit 1; }
fi
# Sync the project (creates venv and installs dependencies)
echo "Setting up Python environment with uv..."
uv sync --python 3.10 || { echo "Failed to sync uv project"; exit 1; }
# Add specific packages
echo "Adding Selenium..."
uv add selenium || { echo "Failed to add selenium"; exit 1; }
# Add dependencies from requirements.txt if it exists
if [ -f "requirements.txt" ]; then
echo "Adding dependencies from requirements.txt..."
uv add -r requirements.txt || { echo "Failed to add requirements from requirements.txt"; exit 1; }
fi
echo "Installation complete for macOS!"
echo "To activate the environment, run: source .venv/bin/activate"
echo "Or run commands with: uv run <command>"
+10 -60
View File
@@ -1,67 +1,17 @@
@echo off @echo off
echo Starting installation for Windows... echo Starting installation for Windows...
REM Check if uv is installed REM Install Python dependencies from requirements.txt
uv --version >nul 2>&1 pip install pyreadline3
if %errorlevel% neq 0 ( pip install -r requirements.txt
echo Error: uv is not installed. Please install uv first.
echo You can install it using: powershell -c "irm https://astral.sh/uv/install.ps1 | iex"
pause
exit /b 2
)
REM Initialize uv project if pyproject.toml doesn't exist REM Install Selenium
if not exist "pyproject.toml" ( pip install selenium
echo Initializing uv project...
uv init --python 3.10
if %errorlevel% neq 0 (
echo Failed to initialize uv project
pause
exit /b 1
)
)
REM Sync the project (creates venv and installs dependencies)
echo Setting up Python environment with uv...
uv sync --python 3.10
if %errorlevel% neq 0 (
echo Failed to sync uv project
pause
exit /b 1
)
REM Add specific packages
echo Adding pyreadline3...
uv add pyreadline3
if %errorlevel% neq 0 (
echo Failed to add pyreadline3
pause
exit /b 1
)
echo Adding Selenium...
uv add selenium
if %errorlevel% neq 0 (
echo Failed to add selenium
pause
exit /b 1
)
REM Add dependencies from requirements.txt if it exists
if exist "requirements.txt" (
echo Adding dependencies from requirements.txt...
uv add -r requirements.txt
if %errorlevel% neq 0 (
echo Warning: Some packages from requirements.txt failed to install.
)
)
echo Installation complete for Windows!
echo To activate the environment, run: .venv\Scripts\activate
echo Or run commands with: uv run ^<command^>
echo.
echo Note: pyAudio installation may require additional steps on Windows. echo Note: pyAudio installation may require additional steps on Windows.
echo If pyAudio fails to install, please install portaudio manually and try again. echo Please install portaudio manually (e.g., via vcpkg or prebuilt binaries) and then run: pip install pyaudio
echo Also, chromedriver-autoinstaller should handle chromedriver automatically. echo Also, download and install chromedriver manually from: https://sites.google.com/chromium.org/driver/getting-started
echo If needed, download chromedriver manually from: https://sites.google.com/chromium.org/driver/getting-started echo Place chromedriver in a directory included in your PATH.
echo Installation partially complete for Windows. Follow manual steps above.
pause pause
+1 -2
View File
@@ -31,7 +31,6 @@ services:
- SEARXNG_BASE_URL=http://localhost:8080/ - SEARXNG_BASE_URL=http://localhost:8080/
- UWSGI_WORKERS=1 - UWSGI_WORKERS=1
- UWSGI_THREADS=1 - UWSGI_THREADS=1
user: "1000:1000" # Run as current user to avoid permission issues
cap_add: cap_add:
- CHOWN - CHOWN
- SETGID - SETGID
@@ -43,4 +42,4 @@ services:
max-file: "1" max-file: "1"
volumes: volumes:
redis-data: redis-data:
-40
View File
@@ -1,40 +0,0 @@
[real_ip]
# Number of values to trust for X-Forwarded-For.
x_for = 1
# The prefix defines the number of leading bits in an address that are compared
# to determine whether or not an address is part of a (client) network.
ipv4_prefix = 32
ipv6_prefix = 48
[botdetection.ip_limit]
# To get unlimited access in a local network, by default link-local addresses
# (networks) are not monitored by the ip_limit
filter_link_local = false
# activate link_token method in the ip_limit method
link_token = false
[botdetection.ip_lists]
# In the limiter, the ip_lists method has priority over all other methods -> if
# an IP is in the pass_ip list, it has unrestricted access and it is also not
# checked if e.g. the "user agent" suggests a bot (e.g. curl).
block_ip = [
# '93.184.216.34', # IPv4 of example.org
# '257.1.1.1', # invalid IP --> will be ignored, logged in ERROR class
]
pass_ip = [
# '192.168.0.0/16', # IPv4 private network
# 'fe80::/10' # IPv6 linklocal / wins over botdetection.ip_limit.filter_link_local
]
# Activate passlist of (hardcoded) IPs from the SearXNG organization,
# e.g. `check.searx.space`.
pass_searxng_org = true
File diff suppressed because it is too large Load Diff
+52
View File
@@ -0,0 +1,52 @@
[uwsgi]
# Who will run the code
uid = searxng
gid = searxng
# Number of workers (usually CPU count)
# default value: %k (= number of CPU core, see Dockerfile)
workers = 4
# Number of threads per worker
# default value: 4 (see Dockerfile)
threads = 4
# The right granted on the created socket
chmod-socket = 666
# Plugin to use and interpreter config
single-interpreter = true
master = true
plugin = python3
lazy-apps = true
enable-threads = 4
# Module to import
module = searx.webapp
# Virtualenv and python path
pythonpath = /usr/local/searxng/
chdir = /usr/local/searxng/searx/
# automatically set processes name to something meaningful
auto-procname = true
# Disable request logging for privacy
disable-logging = true
log-5xx = true
# Set the max size of a request (request-body excluded)
buffer-size = 8192
# No keep alive
# See https://github.com/searx/searx-docker/issues/24
add-header = Connection: close
# Follow SIGTERM convention
# See https://github.com/searxng/searxng/issues/3427
die-on-term
# uwsgi serves the static files
static-map = /static=/usr/local/searxng/searx/static
static-gzip-all = True
offload-threads = 4
Executable → Regular
+92 -39
View File
@@ -444,11 +444,11 @@ engines:
disabled: true disabled: true
# Requires Tor # Requires Tor
#- name: ahmia - name: ahmia
# engine: ahmia engine: ahmia
# categories: onions categories: onions
# enable_http: true enable_http: true
# shortcut: ah shortcut: ah
- name: anaconda - name: anaconda
engine: xpath engine: xpath
@@ -641,6 +641,11 @@ engines:
# # get your API key from: https://core.ac.uk/api-keys/register/ # # get your API key from: https://core.ac.uk/api-keys/register/
# api_key: 'unset' # api_key: 'unset'
- name: cppreference
engine: cppreference
shortcut: cpp
paging: false
disabled: true
- name: crossref - name: crossref
engine: crossref engine: crossref
@@ -1496,12 +1501,31 @@ engines:
engine: pinterest engine: pinterest
shortcut: pin shortcut: pin
#- name: piped - name: piped
# engine: piped engine: piped
# shortcut: ppd shortcut: ppd
# categories: videos categories: videos
# piped_filter: videos piped_filter: videos
# timeout: 3.0 timeout: 3.0
# URL to use as link and for embeds
frontend_url: https://srv.piped.video
# Instance will be selected randomly, for more see https://piped-instances.kavin.rocks/
backend_url:
- https://pipedapi.adminforge.de
- https://pipedapi.nosebs.ru
- https://pipedapi.ducks.party
- https://pipedapi.reallyaweso.me
- https://api.piped.private.coffee
- https://pipedapi.darkness.services
- name: piped.music
engine: piped
network: piped
shortcut: ppdm
categories: music
piped_filter: music_songs
timeout: 3.0
- name: piratebay - name: piratebay
engine: piratebay engine: piratebay
@@ -1918,6 +1942,20 @@ engines:
shortcut: tm shortcut: tm
disabled: true disabled: true
# Requires Tor
- name: torch
engine: xpath
paging: true
search_url:
http://xmh57jrknzkhv6y3ls3ubitzfqnkrwxhopf5aygthi7d6rplyvk3noyd.onion/cgi-bin/omega/omega?P={query}&DEFAULTOP=and
results_xpath: //table//tr
url_xpath: ./td[2]/a
title_xpath: ./td[2]/b
content_xpath: ./td[2]/small
categories: onions
enable_http: true
shortcut: tch
# torznab engine lets you query any torznab compatible indexer. Using this # torznab engine lets you query any torznab compatible indexer. Using this
# engine in combination with Jackett opens the possibility to query a lot of # engine in combination with Jackett opens the possibility to query a lot of
# public and private indexers directly from SearXNG. More details at: # public and private indexers directly from SearXNG. More details at:
@@ -2117,33 +2155,33 @@ engines:
website: https://www.wikivoyage.org/ website: https://www.wikivoyage.org/
wikidata_id: Q373 wikidata_id: Q373
# - name: wikicommons.images - name: wikicommons.images
# engine: wikicommons engine: wikicommons
# shortcut: wc shortcut: wc
# categories: images categories: images
# search_type: images search_type: images
# number_of_results: 10 number_of_results: 10
#
# - name: wikicommons.videos - name: wikicommons.videos
# engine: wikicommons engine: wikicommons
# shortcut: wcv shortcut: wcv
# categories: videos categories: videos
# search_type: videos search_type: videos
# number_of_results: 10 number_of_results: 10
#
# - name: wikicommons.audio - name: wikicommons.audio
# engine: wikicommons engine: wikicommons
# shortcut: wca shortcut: wca
# categories: music categories: music
# search_type: audio search_type: audio
# number_of_results: 10 number_of_results: 10
#
# - name: wikicommons.files - name: wikicommons.files
# engine: wikicommons engine: wikicommons
# shortcut: wcf shortcut: wcf
# categories: files categories: files
# search_type: files search_type: files
# number_of_results: 10 number_of_results: 10
- name: wolframalpha - name: wolframalpha
shortcut: wa shortcut: wa
@@ -2320,6 +2358,16 @@ engines:
# timeout can be reduced in 'local' search mode # timeout can be reduced in 'local' search mode
timeout: 5.0 timeout: 5.0
- name: yacy images
engine: yacy
network: yacy
categories: images
search_type: image
shortcut: yai
disabled: true
# timeout can be reduced in 'local' search mode
timeout: 5.0
- name: rumble - name: rumble
engine: rumble engine: rumble
shortcut: ru shortcut: ru
@@ -2433,6 +2481,11 @@ engines:
shortcut: wttr shortcut: wttr
timeout: 9.0 timeout: 9.0
- name: yummly
engine: yummly
shortcut: yum
disabled: true
- name: brave - name: brave
engine: brave engine: brave
shortcut: br shortcut: br
@@ -2613,4 +2666,4 @@ doi_resolvers:
sci-hub.st: 'https://sci-hub.st/' sci-hub.st: 'https://sci-hub.st/'
sci-hub.ru: 'https://sci-hub.ru/' sci-hub.ru: 'https://sci-hub.ru/'
default_doi_resolver: 'oadoi.org' default_doi_resolver: 'oadoi.org'
File diff suppressed because it is too large Load Diff
+3 -3
View File
@@ -5,12 +5,12 @@ gid = searxng
# Number of workers (usually CPU count) # Number of workers (usually CPU count)
# default value: %k (= number of CPU core, see Dockerfile) # default value: %k (= number of CPU core, see Dockerfile)
workers = 4 workers = 1
# Number of threads per worker # Number of threads per worker
# default value: 4 (see Dockerfile) # default value: 4 (see Dockerfile)
enable-threads = 4 enable-threads = true
threads = 4 threads = 1
# The right granted on the created socket # The right granted on the created socket
chmod-socket = 666 chmod-socket = 666
+108
View File
@@ -0,0 +1,108 @@
#!/usr/bin python3
"""
self_run.py is a script for automatically creating prompts, and saving history as training data.
"""
import sys
import argparse
import configparser
import asyncio
from sources.llm_provider import Provider
from sources.interaction import Interaction
from sources.agents import Agent, CoderAgent, CasualAgent, FileAgent, PlannerAgent, BrowserAgent, McpAgent
from sources.browser import Browser, create_driver
import warnings
warnings.filterwarnings("ignore")
config = configparser.ConfigParser()
config.read('config.ini')
def copy_conversations_folder():
source_path = "conversations/"
destination_path = "training_data/"
if not os.path.exists(destination_path):
os.makedirs(destination_path)
for filename in os.listdir(source_path):
source_file = os.path.join(source_path, filename)
destination_file = os.path.join(destination_path, filename)
shutil.copy2(source_file, destination_file)
print(f"Copied {source_file} to {destination_file}")
def get_random_query(provider):
prompt = """
You are an expert in crafting queries for AgenticSeek, a AI assistant that autonomously browses the web, writes code, plans tasks, and manages files. It supports tasks like web searches, coding in Python/C/Go/Java, file operations, task planning.
Queries must be explicit, specifying actions like "search the web," "write code," or "save to a file," as AgenticSeek's agent routing may not infer vague intents.
Generate a single realistic user query for AgenticSeek. The query should:
Be concise and explicit about the desired action (e.g., web search, coding, file management).
Align with AgenticSeeks capabilities (web browsing, coding, task planning, file operations).
Include a specific output where relevant (e.g., save to a file with a clear name and path).
Reflect a practical use case (e.g., research, programming, personal tasks).
Be formatted as a single sentence.
Example Query:
Search the web for the best hiking trails in Colorado and save a list of three trails with their locations in hiking_trails.txt in /home/project
"""
history = [{"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": prompt}]
thought = provider.respond(history)
return thought
async def self_runner():
provider = Provider(provider_name=config["MAIN"]["provider_name"],
model=config["MAIN"]["provider_model"],
server_address=config["MAIN"]["provider_server_address"],
is_local=config.getboolean('MAIN', 'is_local'))
browser = Browser(
create_driver(headless=True, stealth_mode=False),
anticaptcha_manual_install=False
)
agents = [
CasualAgent(name=config["MAIN"]["agent_name"],
prompt_path=f"prompts/base/casual_agent.txt",
provider=provider, verbose=False),
CoderAgent(name="coder",
prompt_path=f"prompts/base/coder_agent.txt",
provider=provider, verbose=False),
FileAgent(name="File Agent",
prompt_path=f"prompts/base/file_agent.txt",
provider=provider, verbose=False),
BrowserAgent(name="Browser",
prompt_path=f"prompts/base/browser_agent.txt",
provider=provider, verbose=False, browser=browser),
PlannerAgent(name="Planner",
prompt_path=f"prompts/base/planner_agent.txt",
provider=provider, verbose=False, browser=browser)
]
interaction = Interaction(agents,
tts_enabled=False,
stt_enabled=False,
recover_last_session=False,
langs=['en']
)
print("Start self-running for training data generation...")
try:
while interaction.is_active:
query = get_random_query(provider)
print(f"Generated query: {query}")
interaction.set_query(query)
if await interaction.think():
interaction.show_answer()
except Exception as e:
if config.getboolean('MAIN', 'save_session'):
interaction.save_session()
copy_conversations_folder()
raise e
finally:
if config.getboolean('MAIN', 'save_session'):
interaction.save_session()
copy_conversations_folder()
if __name__ == "__main__":
asyncio.run(self_runner())
+2 -17
View File
@@ -44,9 +44,7 @@ class Agent():
self.blocks_result = [] self.blocks_result = []
self.success = True self.success = True
self.last_answer = "" self.last_answer = ""
self.last_reasoning = ""
self.status_message = "Haven't started yet" self.status_message = "Haven't started yet"
self.stop = False
self.verbose = verbose self.verbose = verbose
self.executor = ThreadPoolExecutor(max_workers=1) self.executor = ThreadPoolExecutor(max_workers=1)
@@ -66,10 +64,6 @@ class Agent():
def get_last_answer(self) -> str: def get_last_answer(self) -> str:
return self.last_answer return self.last_answer
@property
def get_last_reasoning(self) -> str:
return self.last_reasoning
@property @property
def get_blocks(self) -> list: def get_blocks(self) -> list:
return self.blocks_result return self.blocks_result
@@ -120,13 +114,6 @@ class Agent():
except Exception as e: except Exception as e:
raise e raise e
def request_stop(self) -> None:
"""
Request the agent to stop.
"""
self.stop = True
self.status_message = "Stopped"
@abstractmethod @abstractmethod
def process(self, prompt, speech_module) -> str: def process(self, prompt, speech_module) -> str:
""" """
@@ -140,10 +127,8 @@ class Agent():
Remove the reasoning block of reasoning model like deepseek. Remove the reasoning block of reasoning model like deepseek.
""" """
end_tag = "</think>" end_tag = "</think>"
end_idx = text.rfind(end_tag) end_idx = text.rfind(end_tag)+8
if end_idx == -1: return text[end_idx:]
return text
return text[end_idx+8:]
def extract_reasoning_text(self, text: str) -> None: def extract_reasoning_text(self, text: str) -> None:
""" """
+15 -25
View File
@@ -41,7 +41,7 @@ class BrowserAgent(Agent):
self.memory = Memory(self.load_prompt(prompt_path), self.memory = Memory(self.load_prompt(prompt_path),
recover_last_session=False, # session recovery in handled by the interaction class recover_last_session=False, # session recovery in handled by the interaction class
memory_compression=False, memory_compression=False,
model_provider=provider.get_model_name() if provider else None) model_provider=provider.get_model_name())
def get_today_date(self) -> str: def get_today_date(self) -> str:
"""Get the date""" """Get the date"""
@@ -77,14 +77,14 @@ class BrowserAgent(Agent):
def get_unvisited_links(self) -> List[str]: def get_unvisited_links(self) -> List[str]:
return "\n".join([f"[{i}] {link}" for i, link in enumerate(self.navigable_links) if link not in self.search_history]) return "\n".join([f"[{i}] {link}" for i, link in enumerate(self.navigable_links) if link not in self.search_history])
def make_newsearch_prompt(self, prompt: str, search_result: dict) -> str: def make_newsearch_prompt(self, user_prompt: str, search_result: dict) -> str:
search_choice = self.stringify_search_results(search_result) search_choice = self.stringify_search_results(search_result)
self.logger.info(f"Search results: {search_choice}") self.logger.info(f"Search results: {search_choice}")
return f""" return f"""
Based on the search result: Based on the search result:
{search_choice} {search_choice}
Your goal is to find accurate and complete information to satisfy the users request. Your goal is to find accurate and complete information to satisfy the users request.
User request: {prompt} User request: {user_prompt}
To proceed, choose a relevant link from the search results. Announce your choice by saying: "I will navigate to <link>" To proceed, choose a relevant link from the search results. Announce your choice by saying: "I will navigate to <link>"
Do not explain your choice. Do not explain your choice.
""" """
@@ -181,7 +181,6 @@ class BrowserAgent(Agent):
animate_thinking("Thinking...", color="status") animate_thinking("Thinking...", color="status")
self.memory.push('user', prompt) self.memory.push('user', prompt)
answer, reasoning = await self.llm_request() answer, reasoning = await self.llm_request()
self.last_reasoning = reasoning
if show_reasoning: if show_reasoning:
pretty_print(reasoning, color="failure") pretty_print(reasoning, color="failure")
pretty_print(answer, color="output") pretty_print(answer, color="output")
@@ -235,23 +234,19 @@ class BrowserAgent(Agent):
return links return links
def select_link(self, links: List[str]) -> str | None: def select_link(self, links: List[str]) -> str | None:
"""
Select the first unvisited link that is not the current page.
Preference is given to links not in search_history.
"""
for lk in links: for lk in links:
if lk == self.current_page or lk in self.search_history: if lk == self.current_page:
self.logger.info(f"Skipping already visited or current link: {lk}") self.logger.info(f"Already visited {lk}. Skipping.")
continue continue
self.logger.info(f"Selected link: {lk}") self.logger.info(f"Selected link: {lk}")
return lk return lk
self.logger.warning("No suitable link selected.") self.logger.warning("No link selected.")
return None return None
def get_page_text(self, limit_to_model_ctx = False) -> str: def get_page_text(self, compression = False) -> str:
"""Get the text content of the current page.""" """Get the text content of the current page."""
page_text = self.browser.get_text() page_text = self.browser.get_text()
if limit_to_model_ctx: if compression:
#page_text = self.memory.compress_text_to_max_ctx(page_text) #page_text = self.memory.compress_text_to_max_ctx(page_text)
page_text = self.memory.trim_text_to_max_ctx(page_text) page_text = self.memory.trim_text_to_max_ctx(page_text)
return page_text return page_text
@@ -354,13 +349,11 @@ class BrowserAgent(Agent):
self.show_search_results(search_result) self.show_search_results(search_result)
prompt = self.make_newsearch_prompt(user_prompt, search_result) prompt = self.make_newsearch_prompt(user_prompt, search_result)
unvisited = [None] unvisited = [None]
while not complete and len(unvisited) > 0 and not self.stop: while not complete and len(unvisited) > 0:
self.memory.clear() self.memory.clear()
unvisited = self.select_unvisited(search_result) unvisited = self.select_unvisited(search_result)
answer, reasoning = await self.llm_decide(prompt, show_reasoning = False) answer, reasoning = await self.llm_decide(prompt, show_reasoning = False)
if self.stop:
pretty_print(f"Requested stop.", color="failure")
break
if self.last_answer == answer: if self.last_answer == answer:
prompt = self.stuck_prompt(user_prompt, unvisited) prompt = self.stuck_prompt(user_prompt, unvisited)
continue continue
@@ -372,13 +365,13 @@ class BrowserAgent(Agent):
self.status_message = "Filling web form..." self.status_message = "Filling web form..."
pretty_print(f"Filling inputs form...", color="status") pretty_print(f"Filling inputs form...", color="status")
fill_success = self.browser.fill_form(extracted_form) fill_success = self.browser.fill_form(extracted_form)
page_text = self.get_page_text(limit_to_model_ctx=True) page_text = self.get_page_text()
answer = self.handle_update_prompt(user_prompt, page_text, fill_success) answer = self.handle_update_prompt(user_prompt, page_text, fill_success)
answer, reasoning = await self.llm_decide(prompt) answer, reasoning = await self.llm_decide(prompt)
if Action.FORM_FILLED.value in answer: if Action.FORM_FILLED.value in answer:
pretty_print(f"Filled form. Handling page update.", color="status") pretty_print(f"Filled form. Handling page update.", color="status")
page_text = self.get_page_text(limit_to_model_ctx=True) page_text = self.get_page_text()
self.navigable_links = self.browser.get_navigable() self.navigable_links = self.browser.get_navigable()
prompt = self.make_navigation_prompt(user_prompt, page_text) prompt = self.make_navigation_prompt(user_prompt, page_text)
continue continue
@@ -400,10 +393,7 @@ class BrowserAgent(Agent):
if (link == None and len(extracted_form) < 3) or Action.GO_BACK.value in answer or link in self.search_history: if (link == None and len(extracted_form) < 3) or Action.GO_BACK.value in answer or link in self.search_history:
pretty_print(f"Going back to results. Still {len(unvisited)}", color="status") pretty_print(f"Going back to results. Still {len(unvisited)}", color="status")
self.status_message = "Going back to search results..." self.status_message = "Going back to search results..."
request_prompt = user_prompt prompt = self.make_newsearch_prompt(user_prompt, unvisited)
if link is None:
request_prompt += f"\nYou previously choosen:\n{self.last_answer} but the website is unavailable. Consider other options."
prompt = self.make_newsearch_prompt(request_prompt, unvisited)
self.search_history.append(link) self.search_history.append(link)
self.current_page = link self.current_page = link
continue continue
@@ -417,7 +407,7 @@ class BrowserAgent(Agent):
prompt = self.make_newsearch_prompt(user_prompt, unvisited) prompt = self.make_newsearch_prompt(user_prompt, unvisited)
continue continue
self.current_page = link self.current_page = link
page_text = self.get_page_text(limit_to_model_ctx=True) page_text = self.get_page_text()
self.navigable_links = self.browser.get_navigable() self.navigable_links = self.browser.get_navigable()
prompt = self.make_navigation_prompt(user_prompt, page_text) prompt = self.make_navigation_prompt(user_prompt, page_text)
self.status_message = "Navigating..." self.status_message = "Navigating..."
@@ -434,4 +424,4 @@ class BrowserAgent(Agent):
return answer, reasoning return answer, reasoning
if __name__ == "__main__": if __name__ == "__main__":
pass pass
+1 -3
View File
@@ -51,12 +51,10 @@ class CoderAgent(Agent):
self.memory.push('user', prompt) self.memory.push('user', prompt)
clarify_trigger = "REQUEST_CLARIFICATION" clarify_trigger = "REQUEST_CLARIFICATION"
while attempt < max_attempts and not self.stop: while attempt < max_attempts:
print("Stopped?", self.stop)
animate_thinking("Thinking...", color="status") animate_thinking("Thinking...", color="status")
await self.wait_message(speech_module) await self.wait_message(speech_module)
answer, reasoning = await self.llm_request() answer, reasoning = await self.llm_request()
self.last_reasoning = reasoning
if clarify_trigger in answer: if clarify_trigger in answer:
self.last_answer = answer self.last_answer = answer
await asyncio.sleep(0) await asyncio.sleep(0)
+1 -2
View File
@@ -28,11 +28,10 @@ class FileAgent(Agent):
exec_success = False exec_success = False
prompt += f"\nYou must work in directory: {self.work_dir}" prompt += f"\nYou must work in directory: {self.work_dir}"
self.memory.push('user', prompt) self.memory.push('user', prompt)
while exec_success is False and not self.stop: while exec_success is False:
await self.wait_message(speech_module) await self.wait_message(speech_module)
animate_thinking("Thinking...", color="status") animate_thinking("Thinking...", color="status")
answer, reasoning = await self.llm_request() answer, reasoning = await self.llm_request()
self.last_reasoning = reasoning
exec_success, _ = self.execute_modules(answer) exec_success, _ = self.execute_modules(answer)
answer = self.remove_blocks(answer) answer = self.remove_blocks(answer)
self.last_answer = answer self.last_answer = answer
+2 -1
View File
@@ -35,7 +35,8 @@ class McpAgent(Agent):
""" """
api_key_mcp_finder = os.getenv("MCP_FINDER_API_KEY") api_key_mcp_finder = os.getenv("MCP_FINDER_API_KEY")
if not api_key_mcp_finder or api_key_mcp_finder == "": if not api_key_mcp_finder or api_key_mcp_finder == "":
pretty_print("MCP Finder disabled.", color="warning") pretty_print("MCP Finder API key not found. Please set the MCP_FINDER_API_KEY environment variable.", color="failure")
pretty_print("MCP Finder disabled.", color="failure")
self.enabled = False self.enabled = False
return { return {
"mcp_finder": api_key_mcp_finder "mcp_finder": api_key_mcp_finder
+10 -22
View File
@@ -83,15 +83,11 @@ class PlannerAgent(Agent):
self.logger.warning(f"Agent {task['agent']} does not exist.") self.logger.warning(f"Agent {task['agent']} does not exist.")
pretty_print(f"Agent {task['agent']} does not exist.", color="warning") pretty_print(f"Agent {task['agent']} does not exist.", color="warning")
return [] return []
try: agent = {
agent = { 'agent': task['agent'],
'agent': task['agent'], 'id': task['id'],
'id': task['id'], 'task': task['task']
'task': task['task'] }
}
except:
self.logger.warning("Missing field in json plan.")
return []
self.logger.info(f"Created agent {task['agent']} with task: {task['task']}") self.logger.info(f"Created agent {task['agent']} with task: {task['task']}")
if 'need' in task: if 'need' in task:
self.logger.info(f"Agent {task['agent']} was given info:\n {task['need']}") self.logger.info(f"Agent {task['agent']} was given info:\n {task['need']}")
@@ -160,7 +156,6 @@ class PlannerAgent(Agent):
return [] return []
agents_tasks = self.parse_agent_tasks(answer) agents_tasks = self.parse_agent_tasks(answer)
if agents_tasks == []: if agents_tasks == []:
self.show_plan(agents_tasks, answer)
prompt = f"Failed to parse the tasks. Please write down your task followed by a json plan within ```json. Do not ask for clarification.\n" prompt = f"Failed to parse the tasks. Please write down your task followed by a json plan within ```json. Do not ask for clarification.\n"
pretty_print("Failed to make plan. Retrying...", color="warning") pretty_print("Failed to make plan. Retrying...", color="warning")
continue continue
@@ -183,11 +178,7 @@ class PlannerAgent(Agent):
last_agent_work = agents_work_result[id] last_agent_work = agents_work_result[id]
tool_success_str = "success" if success else "failure" tool_success_str = "success" if success else "failure"
pretty_print(f"Agent {id} work {tool_success_str}.", color="success" if success else "failure") pretty_print(f"Agent {id} work {tool_success_str}.", color="success" if success else "failure")
try: if int(id) == len(agents_tasks):
id_int = int(id)
except Exception as e:
return agents_tasks
if id_int == len(agents_tasks):
next_task = "No task follow, this was the last step. If it failed add a task to recover." next_task = "No task follow, this was the last step. If it failed add a task to recover."
else: else:
next_task = f"Next task is: {agents_tasks[int(id)][0]}." next_task = f"Next task is: {agents_tasks[int(id)][0]}."
@@ -200,7 +191,7 @@ class PlannerAgent(Agent):
{last_agent_work} {last_agent_work}
Agent {id} work was a {tool_success_str} according to system interpreter. Agent {id} work was a {tool_success_str} according to system interpreter.
{next_task} {next_task}
Is the work done for task {id} leading to success or failure ? Did an agent fail with a task? Is the work done for task {id} leading to sucess or failure ? Did an agent fail with a task?
If agent work was good: answer "NO_UPDATE" If agent work was good: answer "NO_UPDATE"
If agent work is leading to failure: update the plan. If agent work is leading to failure: update the plan.
If a task failed add a task to try again or recover from failure. You might have near identical task twice. If a task failed add a task to try again or recover from failure. You might have near identical task twice.
@@ -230,9 +221,8 @@ class PlannerAgent(Agent):
agent_prompt = self.make_prompt(task['task'], required_infos) agent_prompt = self.make_prompt(task['task'], required_infos)
pretty_print(f"Agent {task['agent']} started working...", color="status") pretty_print(f"Agent {task['agent']} started working...", color="status")
self.logger.info(f"Agent {task['agent']} started working on {task['task']}.") self.logger.info(f"Agent {task['agent']} started working on {task['task']}.")
answer, reasoning = await self.agents[task['agent'].lower()].process(agent_prompt, None) answer, _ = await self.agents[task['agent'].lower()].process(agent_prompt, None)
self.last_answer = answer self.last_answer = answer
self.last_reasoning = reasoning
self.blocks_result = self.agents[task['agent'].lower()].blocks_result self.blocks_result = self.agents[task['agent'].lower()].blocks_result
agent_answer = self.agents[task['agent'].lower()].raw_answer_blocks(answer) agent_answer = self.agents[task['agent'].lower()].raw_answer_blocks(answer)
success = self.agents[task['agent'].lower()].get_success success = self.agents[task['agent'].lower()].get_success
@@ -267,7 +257,7 @@ class PlannerAgent(Agent):
return "Failed to parse the tasks.", "" return "Failed to parse the tasks.", ""
i = 0 i = 0
steps = len(agents_tasks) steps = len(agents_tasks)
while i < steps and not self.stop: while i < steps:
task_name, task = agents_tasks[i][0], agents_tasks[i][1] task_name, task = agents_tasks[i][0], agents_tasks[i][1]
self.status_message = "Starting agents..." self.status_message = "Starting agents..."
pretty_print(f"I will {task_name}.", color="info") pretty_print(f"I will {task_name}.", color="info")
@@ -281,11 +271,9 @@ class PlannerAgent(Agent):
answer, success = await self.start_agent_process(task, required_infos) answer, success = await self.start_agent_process(task, required_infos)
except Exception as e: except Exception as e:
raise e raise e
if self.stop:
pretty_print(f"Requested stop.", color="failure")
agents_work_result[task['id']] = answer agents_work_result[task['id']] = answer
agents_tasks = await self.update_plan(goal, agents_tasks, agents_work_result, task['id'], success) agents_tasks = await self.update_plan(goal, agents_tasks, agents_work_result, task['id'], success)
steps = len(agents_tasks) steps = len(agents_tasks)
i += 1 i += 1
return answer, "" return answer, ""
+66 -185
View File
@@ -19,7 +19,6 @@ import time
import random import random
import os import os
import shutil import shutil
import uuid
import tempfile import tempfile
import markdownify import markdownify
import sys import sys
@@ -43,17 +42,10 @@ def get_chrome_path() -> str:
paths = ["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", paths = ["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
"/Applications/Google Chrome Beta.app/Contents/MacOS/Google Chrome Beta"] "/Applications/Google Chrome Beta.app/Contents/MacOS/Google Chrome Beta"]
else: # Linux else: # Linux
paths = ["/usr/bin/google-chrome", paths = ["/usr/bin/google-chrome", "/usr/bin/chromium-browser", "/usr/bin/chromium", "/opt/chrome/chrome", "/usr/local/bin/chrome"]
"/opt/chrome/chrome",
"/usr/bin/chromium-browser",
"/usr/bin/chromium",
"/usr/local/bin/chrome",
"/opt/google/chrome/chrome-headless-shell",
#"/app/chrome_bundle/chrome136/chrome-linux64"
]
for path in paths: for path in paths:
if os.path.exists(path) and os.access(path, os.X_OK): if os.path.exists(path) and os.access(path, os.X_OK): # Check if executable
return path return path
print("Looking for Google Chrome in these locations failed:") print("Looking for Google Chrome in these locations failed:")
print('\n'.join(paths)) print('\n'.join(paths))
@@ -70,9 +62,9 @@ def get_chrome_path() -> str:
def get_random_user_agent() -> str: def get_random_user_agent() -> str:
"""Get a random user agent string with associated vendor.""" """Get a random user agent string with associated vendor."""
user_agents = [ user_agents = [
{"ua": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36", "vendor": "Google Inc."}, {"ua": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36", "vendor": "Google Inc."},
{"ua": "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_6_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36", "vendor": "Apple Inc."}, {"ua": "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_6_1) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Safari/605.1.15", "vendor": "Apple Inc."},
{"ua": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36", "vendor": "Google Inc."}, {"ua": "Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0", "vendor": ""},
] ]
return random.choice(user_agents) return random.choice(user_agents)
@@ -80,36 +72,17 @@ def install_chromedriver() -> str:
""" """
Install the ChromeDriver if not already installed. Return the path. Install the ChromeDriver if not already installed. Return the path.
""" """
# First try to use chromedriver in the project root directory (as per README)
project_root_chromedriver = "./chromedriver"
if os.path.exists(project_root_chromedriver) and os.access(project_root_chromedriver, os.X_OK):
print(f"Using ChromeDriver from project root: {project_root_chromedriver}")
return project_root_chromedriver
# Then try to use the system-installed chromedriver
chromedriver_path = shutil.which("chromedriver") chromedriver_path = shutil.which("chromedriver")
if chromedriver_path: if not chromedriver_path:
return chromedriver_path try:
chromedriver_path = chromedriver_autoinstaller.install()
# In Docker environment, try the fixed path except Exception as e:
if os.path.exists('/.dockerenv'): raise FileNotFoundError(
docker_chromedriver_path = "/usr/local/bin/chromedriver" "ChromeDriver not found and could not be installed automatically. "
if os.path.exists(docker_chromedriver_path) and os.access(docker_chromedriver_path, os.X_OK): "Please install it manually from https://chromedriver.chromium.org/downloads."
print(f"Using Docker ChromeDriver at {docker_chromedriver_path}") "and ensure it's in your PATH or specify the path directly."
return docker_chromedriver_path "See know issues in readme if your chrome version is above 115."
) from e
# Fallback to auto-installer only if no other option works
try:
print("ChromeDriver not found, attempting to install automatically...")
chromedriver_path = chromedriver_autoinstaller.install()
except Exception as e:
raise FileNotFoundError(
"ChromeDriver not found and could not be installed automatically. "
"Please install it manually from https://chromedriver.chromium.org/downloads."
"and ensure it's in your PATH or specify the path directly."
"See know issues in readme if your chrome version is above 115."
) from e
if not chromedriver_path: if not chromedriver_path:
raise FileNotFoundError("ChromeDriver not found. Please install it or add it to your PATH.") raise FileNotFoundError("ChromeDriver not found. Please install it or add it to your PATH.")
return chromedriver_path return chromedriver_path
@@ -118,11 +91,28 @@ def bypass_ssl() -> str:
""" """
This is a fallback for stealth mode to bypass SSL verification. Which can fail on some setup. This is a fallback for stealth mode to bypass SSL verification. Which can fail on some setup.
""" """
pretty_print("Bypassing SSL verification issues, we strongly advice you update your certifi SSL certificate.", color="warning") pretty_print("This is a workaround for SSL issues but upsafe we strongly advice you update your certifi SSL certificate.", color="warning")
ssl._create_default_https_context = ssl._create_unverified_context ssl._create_default_https_context = ssl._create_unverified_context
def create_chrome_options(headless=False, stealth_mode=True, crx_path="./crx/nopecha.crx", lang="en") -> Options: def create_undetected_chromedriver(service, chrome_options) -> webdriver.Chrome:
"""Create Chrome options - separated for reusability.""" """Create an undetected ChromeDriver instance."""
try:
driver = uc.Chrome(service=service, options=chrome_options)
except Exception as e:
pretty_print(f"Failed to create Chrome driver: {str(e)}. Trying to bypass SSL...", color="failure")
try:
bypass_ssl()
driver = uc.Chrome(service=service, options=chrome_options)
except Exception as e:
pretty_print(f"Failed to create Chrome driver, fallback failed:\n{str(e)}.", color="failure")
raise e
raise e
# hide webdriver flag
driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")
return driver
def create_driver(headless=False, stealth_mode=True, crx_path="./crx/nopecha.crx") -> webdriver.Chrome:
"""Create a Chrome WebDriver with specified options."""
chrome_options = Options() chrome_options = Options()
chrome_path = get_chrome_path() chrome_path = get_chrome_path()
@@ -131,117 +121,54 @@ def create_chrome_options(headless=False, stealth_mode=True, crx_path="./crx/nop
chrome_options.binary_location = chrome_path chrome_options.binary_location = chrome_path
if headless: if headless:
chrome_options.add_argument("--headless=new") chrome_options.add_argument("--headless")
chrome_options.add_argument("--disable-gpu") chrome_options.add_argument("--disable-gpu")
chrome_options.add_argument("--disable-webgl") chrome_options.add_argument("--disable-webgl")
user_data_dir = tempfile.mkdtemp()
user_agent = get_random_user_agent() user_agent = get_random_user_agent()
width, height = (1920, 1080) chrome_options.add_argument(f"--user-data-dir={user_data_dir}")
profile_dir = f"/tmp/chrome_profile_{uuid.uuid4().hex[:8]}"
# Core options
chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument('--disable-dev-shm-usage') chrome_options.add_argument("--disable-dev-shm-usage")
chrome_options.add_argument(f'--user-data-dir={profile_dir}')
chrome_options.add_argument(f"--accept-lang={lang}-{lang.upper()},{lang};q=0.9")
chrome_options.add_argument("--disable-extensions")
chrome_options.add_argument("--disable-background-timer-throttling")
chrome_options.add_argument("--timezone=Europe/Paris")
chrome_options.add_argument('--remote-debugging-port=9222')
chrome_options.add_argument('--disable-background-timer-throttling')
chrome_options.add_argument('--disable-backgrounding-occluded-windows')
chrome_options.add_argument('--disable-renderer-backgrounding')
chrome_options.add_argument('--disable-features=TranslateUI')
chrome_options.add_argument('--disable-ipc-flooding-protection')
chrome_options.add_argument("--mute-audio") chrome_options.add_argument("--mute-audio")
chrome_options.add_argument("--disable-notifications") chrome_options.add_argument("--disable-notifications")
chrome_options.add_argument("--autoplay-policy=user-gesture-required") chrome_options.add_argument("--autoplay-policy=user-gesture-required")
chrome_options.add_argument("--disable-features=SitePerProcess,IsolateOrigins")
chrome_options.add_argument("--enable-features=NetworkService,NetworkServiceInProcess")
chrome_options.add_argument("--disable-blink-features=AutomationControlled") chrome_options.add_argument("--disable-blink-features=AutomationControlled")
chrome_options.add_argument(f'user-agent={user_agent["ua"]}') chrome_options.add_argument(f'user-agent={user_agent["ua"]}')
resolutions = [(1920, 1080), (1366, 768), (1440, 900)]
width, height = random.choice(resolutions)
chrome_options.add_argument(f'--window-size={width},{height}') chrome_options.add_argument(f'--window-size={width},{height}')
if not stealth_mode: if not stealth_mode:
# crx file can't be installed in stealth mode
if not os.path.exists(crx_path): if not os.path.exists(crx_path):
pretty_print(f"Anti-captcha CRX not found at {crx_path}.", color="failure") pretty_print(f"Anti-captcha CRX not found at {crx_path}.", color="failure")
else: else:
chrome_options.add_extension(crx_path) chrome_options.add_extension(crx_path)
if not stealth_mode:
security_prefs = {
"profile.default_content_setting_values.geolocation": 0,
"profile.default_content_setting_values.notifications": 0,
"profile.default_content_setting_values.camera": 0,
"profile.default_content_setting_values.microphone": 0,
"profile.default_content_setting_values.midi_sysex": 0,
"profile.default_content_setting_values.clipboard": 0,
"profile.default_content_setting_values.media_stream": 0,
"profile.default_content_setting_values.background_sync": 0,
"profile.default_content_setting_values.sensors": 0,
"profile.default_content_setting_values.accessibility_events": 0,
"safebrowsing.enabled": True,
"credentials_enable_service": False,
"profile.password_manager_enabled": False,
"webkit.webprefs.accelerated_2d_canvas_enabled": True,
"webkit.webprefs.force_dark_mode_enabled": False,
"webkit.webprefs.accelerated_2d_canvas_msaa_sample_count": 4,
"enable_webgl": True,
"enable_webgl2_compute_context": True
}
chrome_options.add_experimental_option("prefs", security_prefs)
chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
chrome_options.add_experimental_option('useAutomationExtension', False)
return chrome_options
def create_undetected_chromedriver(service, chrome_options) -> webdriver.Chrome:
"""Create an undetected ChromeDriver instance with proper error handling."""
try:
driver = uc.Chrome(service=service, options=chrome_options)
except Exception as e:
pretty_print(f"Failed to create Chrome driver: {str(e)}. Trying to bypass SSL...", color="failure")
try:
bypass_ssl()
# Create NEW options object - this is the key fix
fresh_options = create_chrome_options(
headless=any("--headless" in arg for arg in chrome_options.arguments),
stealth_mode=True, # We're in stealth mode if we reach this point
crx_path="./crx/nopecha.crx" # Default path
)
driver = uc.Chrome(service=service, options=fresh_options)
except Exception as e:
pretty_print(f"Failed to create Chrome driver, fallback failed:\n{str(e)}.", color="failure")
raise e
driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")
return driver
def create_driver(headless=False, stealth_mode=True, crx_path="./crx/nopecha.crx", lang="en") -> webdriver.Chrome:
"""Create a Chrome WebDriver with specified options."""
# Warn if trying to run non-headless in Docker
if not headless and os.path.exists('/.dockerenv'):
print("[WARNING] Running non-headless browser in Docker may fail!")
print("[WARNING] Consider setting headless=True or headless_browser=True in config.ini")
chrome_options = create_chrome_options(headless, stealth_mode, crx_path, lang)
chromedriver_path = install_chromedriver() chromedriver_path = install_chromedriver()
service = Service(chromedriver_path) service = Service(chromedriver_path)
if stealth_mode: if stealth_mode:
chrome_options.add_argument("--disable-blink-features=AutomationControlled")
driver = create_undetected_chromedriver(service, chrome_options) driver = create_undetected_chromedriver(service, chrome_options)
user_agent = get_random_user_agent() chrome_version = driver.capabilities['browserVersion']
stealth(driver, stealth(driver,
languages=["en-US", "en"], languages=["en-US", "en"],
vendor=user_agent["vendor"], vendor=user_agent["vendor"],
platform="Win64" if "windows" in user_agent["ua"].lower() else "MacIntel" if "mac" in user_agent["ua"].lower() else "Linux x86_64", platform="Win64" if "Windows" in user_agent["ua"] else "MacIntel" if "Macintosh" in user_agent["ua"] else "Linux x86_64",
webgl_vendor="Intel Inc.", webgl_vendor="Intel Inc.",
renderer="Intel Iris OpenGL Engine", renderer="Intel Iris OpenGL Engine",
fix_hairline=True, fix_hairline=True,
) )
return driver return driver
else: security_prefs = {
return webdriver.Chrome(service=service, options=chrome_options) "profile.default_content_setting_values.media_stream": 2,
"profile.default_content_setting_values.geolocation": 2,
"safebrowsing.enabled": True,
}
chrome_options.add_experimental_option("prefs", security_prefs)
chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
chrome_options.add_experimental_option('useAutomationExtension', False)
return webdriver.Chrome(service=service, options=chrome_options)
class Browser: class Browser:
def __init__(self, driver, anticaptcha_manual_install=False): def __init__(self, driver, anticaptcha_manual_install=False):
@@ -257,17 +184,12 @@ class Browser:
except Exception as e: except Exception as e:
raise Exception(f"Failed to initialize browser: {str(e)}") raise Exception(f"Failed to initialize browser: {str(e)}")
self.setup_tabs() self.setup_tabs()
self.patch_browser_fingerprint()
if anticaptcha_manual_install: if anticaptcha_manual_install:
self.load_anticatpcha_manually() self.load_anticatpcha_manually()
def setup_tabs(self): def setup_tabs(self):
self.tabs = self.driver.window_handles self.tabs = self.driver.window_handles
try: self.driver.get("https://www.google.com")
self.driver.get("https://www.google.com")
except Exception as e:
self.logger.log(f"Failed to setup initial tab:" + str(e))
pass
self.screenshot() self.screenshot()
def switch_control_tab(self): def switch_control_tab(self):
@@ -276,40 +198,14 @@ class Browser:
def load_anticatpcha_manually(self): def load_anticatpcha_manually(self):
pretty_print("You might want to install the AntiCaptcha extension for captchas.", color="warning") pretty_print("You might want to install the AntiCaptcha extension for captchas.", color="warning")
try: self.driver.get(self.anticaptcha)
self.driver.get(self.anticaptcha)
except Exception as e:
self.logger.log(f"Failed to setup initial tab:" + str(e))
pass
def human_move(element):
actions = ActionChains(driver)
x_offset = random.randint(-5,5)
for _ in range(random.randint(2,5)):
actions.move_by_offset(x_offset, random.randint(-2,2))
actions.pause(random.uniform(0.1,0.3))
actions.click().perform()
def human_scroll(self):
for _ in range(random.randint(1, 3)):
scroll_pixels = random.randint(150, 1200)
self.driver.execute_script(f"window.scrollBy(0, {scroll_pixels});")
time.sleep(random.uniform(0.5, 2.0))
if random.random() < 0.4:
self.driver.execute_script(f"window.scrollBy(0, -{random.randint(50, 300)});")
time.sleep(random.uniform(0.3, 1.0))
def patch_browser_fingerprint(self) -> None:
script = self.load_js("spoofing.js")
self.driver.execute_script(script)
def go_to(self, url:str) -> bool: def go_to(self, url:str) -> bool:
"""Navigate to a specified URL.""" """Navigate to a specified URL."""
time.sleep(random.uniform(0.4, 2.5)) time.sleep(random.uniform(0.4, 2.5)) # more human behavior
try: try:
initial_handles = self.driver.window_handles initial_handles = self.driver.window_handles
self.driver.get(url) self.driver.get(url)
time.sleep(random.uniform(0.01, 0.3))
try: try:
wait = WebDriverWait(self.driver, timeout=10) wait = WebDriverWait(self.driver, timeout=10)
wait.until( wait.until(
@@ -321,8 +217,6 @@ class Browser:
except TimeoutException: except TimeoutException:
self.logger.warning("Timeout while waiting for page to bypass 'checking your browser'") self.logger.warning("Timeout while waiting for page to bypass 'checking your browser'")
self.apply_web_safety() self.apply_web_safety()
time.sleep(random.uniform(0.01, 0.2))
self.human_scroll()
self.logger.log(f"Navigated to: {url}") self.logger.log(f"Navigated to: {url}")
return True return True
except TimeoutException as e: except TimeoutException as e:
@@ -722,24 +616,19 @@ class Browser:
return self.screenshot_folder + "/updated_screen.png" return self.screenshot_folder + "/updated_screen.png"
def screenshot(self, filename:str = 'updated_screen.png') -> bool: def screenshot(self, filename:str = 'updated_screen.png') -> bool:
"""Take a screenshot of the current page, attempt to capture the full page by zooming out.""" """Take a screenshot of the current page."""
self.logger.info("Taking full page screenshot...") self.logger.info("Taking screenshot...")
time.sleep(0.1) time.sleep(0.1)
try: try:
original_zoom = self.driver.execute_script("return document.body.style.zoom || 1;")
self.driver.execute_script("document.body.style.zoom='75%'")
time.sleep(0.1)
path = os.path.join(self.screenshot_folder, filename) path = os.path.join(self.screenshot_folder, filename)
if not os.path.exists(self.screenshot_folder): if not os.path.exists(self.screenshot_folder):
os.makedirs(self.screenshot_folder) os.makedirs(self.screenshot_folder)
self.driver.save_screenshot(path) self.driver.save_screenshot(path)
self.logger.info(f"Full page screenshot saved as {filename}") self.logger.info(f"Screenshot saved as {filename}")
return True
except Exception as e: except Exception as e:
self.logger.error(f"Error taking full page screenshot: {str(e)}") self.logger.error(f"Error taking screenshot: {str(e)}")
return False return False
finally:
self.driver.execute_script(f"document.body.style.zoom='1'")
return True
def apply_web_safety(self): def apply_web_safety(self):
""" """
@@ -750,25 +639,17 @@ class Browser:
input_elements = self.driver.execute_script(script) input_elements = self.driver.execute_script(script)
if __name__ == "__main__": if __name__ == "__main__":
driver = create_driver(headless=False, stealth_mode=True, crx_path="../crx/nopecha.crx") driver = create_driver(headless=False, stealth_mode=True)
browser = Browser(driver, anticaptcha_manual_install=True) browser = Browser(driver, anticaptcha_manual_install=True)
input("press enter to continue") input("press enter to continue")
print("AntiCaptcha / Form Test") print("AntiCaptcha / Form Test")
browser.go_to("https://bot.sannysoft.com") #browser.go_to("https://www.browserscan.net/bot-detection")
time.sleep(5)
#txt = browser.get_text() #txt = browser.get_text()
#browser.go_to("https://www.google.com/recaptcha/api2/demo")
browser.go_to("https://home.openweathermap.org/users/sign_up") browser.go_to("https://home.openweathermap.org/users/sign_up")
inputs_visible = browser.get_form_inputs() inputs_visible = browser.get_form_inputs()
print("inputs:", inputs_visible) print("inputs:", inputs_visible)
#inputs_fill = ['[q](checked)', '[q](checked)', '[user[username]](mlg)', '[user[email]](mlg.fcu@gmail.com)', '[user[password]](placeholder_P@ssw0rd123)', '[user[password_confirmation]](placeholder_P@ssw0rd123)'] #inputs_fill = ['[q](checked)', '[q](checked)', '[user[username]](mlg)', '[user[email]](mlg.fcu@gmail.com)', '[user[password]](placeholder_P@ssw0rd123)', '[user[password_confirmation]](placeholder_P@ssw0rd123)']
#browser.fill_form(inputs_fill) #browser.fill_form(inputs_fill)
input("press enter to exit") input("press enter to exit")
# Test sites for browser fingerprinting and captcha
# https://nowsecure.nl/
# https://bot.sannysoft.com
# https://browserleaks.com/
# https://bot.incolumitas.com/
# https://fingerprintjs.github.io/fingerprintjs/
# https://antoinevastel.com/bots/
+1 -2
View File
@@ -22,7 +22,6 @@ class Interaction:
self.current_agent = None self.current_agent = None
self.last_query = None self.last_query = None
self.last_answer = None self.last_answer = None
self.last_reasoning = None
self.agents = agents self.agents = agents
self.tts_enabled = tts_enabled self.tts_enabled = tts_enabled
self.stt_enabled = stt_enabled self.stt_enabled = stt_enabled
@@ -159,7 +158,7 @@ class Interaction:
tmp = self.last_answer tmp = self.last_answer
self.current_agent = agent self.current_agent = agent
self.is_generating = True self.is_generating = True
self.last_answer, self.last_reasoning = await agent.process(self.last_query, self.speech) self.last_answer, _ = await agent.process(self.last_query, self.speech)
self.is_generating = False self.is_generating = False
if push_last_agent_memory: if push_last_agent_memory:
self.current_agent.memory.push('user', self.last_query) self.current_agent.memory.push('user', self.last_query)
+43 -3
View File
@@ -1,6 +1,8 @@
from typing import List, Tuple, Type, Dict from typing import List, Tuple, Type, Dict
import re import re
import langid import langid
import nltk
from nltk.sentiment.vader import SentimentIntensityAnalyzer
from transformers import MarianMTModel, MarianTokenizer from transformers import MarianMTModel, MarianTokenizer
from sources.utility import pretty_print, animate_thinking from sources.utility import pretty_print, animate_thinking
@@ -14,6 +16,7 @@ class LanguageUtility:
args: args:
supported_language: list of languages for translation, determine which Helsinki-NLP model to load supported_language: list of languages for translation, determine which Helsinki-NLP model to load
""" """
self.sid = None
self.translators_tokenizer = None self.translators_tokenizer = None
self.translators_model = None self.translators_model = None
self.logger = Logger("language.log") self.logger = Logger("language.log")
@@ -22,6 +25,11 @@ class LanguageUtility:
def load_model(self) -> None: def load_model(self) -> None:
animate_thinking("Loading language utility...", color="status") animate_thinking("Loading language utility...", color="status")
try:
nltk.data.find('vader_lexicon')
except LookupError:
nltk.download('vader_lexicon')
self.sid = SentimentIntensityAnalyzer()
self.translators_tokenizer = {lang: MarianTokenizer.from_pretrained(f"Helsinki-NLP/opus-mt-{lang}-en") for lang in self.supported_language if lang != "en"} self.translators_tokenizer = {lang: MarianTokenizer.from_pretrained(f"Helsinki-NLP/opus-mt-{lang}-en") for lang in self.supported_language if lang != "en"}
self.translators_model = {lang: MarianMTModel.from_pretrained(f"Helsinki-NLP/opus-mt-{lang}-en") for lang in self.supported_language if lang != "en"} self.translators_model = {lang: MarianMTModel.from_pretrained(f"Helsinki-NLP/opus-mt-{lang}-en") for lang in self.supported_language if lang != "en"}
@@ -57,17 +65,49 @@ class LanguageUtility:
translation = model.generate(**inputs) translation = model.generate(**inputs)
return tokenizer.decode(translation[0], skip_special_tokens=True) return tokenizer.decode(translation[0], skip_special_tokens=True)
def detect_emotion(self, text: str) -> str:
"""
Detect the dominant emotion in the given text
Args:
text: string to analyze
Returns: string of the dominant emotion
"""
try:
scores = self.sid.polarity_scores(text)
emotions = {
'Happy': max(scores['pos'], 0),
'Angry': 0,
'Sad': max(scores['neg'], 0),
'Fear': 0,
'Surprise': 0
}
if scores['compound'] < -0.5:
emotions['Angry'] = abs(scores['compound']) * 0.5
emotions['Fear'] = abs(scores['compound']) * 0.5
elif scores['compound'] > 0.5:
emotions['Happy'] = scores['compound']
emotions['Surprise'] = scores['compound'] * 0.5
dominant_emotion = max(emotions, key=emotions.get)
if emotions[dominant_emotion] == 0:
return 'Neutral'
self.logger.info(f"Emotion: {dominant_emotion} for text: {text}")
return dominant_emotion
except Exception as e:
raise e
def analyze(self, text): def analyze(self, text):
""" """
Combined analysis of language and emotion Combined analysis of language and emotion
Args: Args:
text: string to analyze text: string to analyze
Returns: dictionary with language related information Returns: dictionary with language and emotion results
""" """
try: try:
language = self.detect_language(text) language = self.detect_language(text)
emotions = self.detect_emotion(text)
return { return {
"language": language "language": language,
"emotions": emotions
} }
except Exception as e: except Exception as e:
raise e raise e
@@ -85,4 +125,4 @@ if __name__ == "__main__":
pretty_print(f"Language: {detector.detect_language(text)}", color="status") pretty_print(f"Language: {detector.detect_language(text)}", color="status")
result = detector.analyze(text) result = detector.analyze(text)
trans = detector.translate(text, result['language']) trans = detector.translate(text, result['language'])
pretty_print(f"Translation: {trans} - from: {result['language']}") pretty_print(f"Translation: {trans} - from: {result['language']} - Emotion: {result['emotions']}")
+50 -159
View File
@@ -1,26 +1,27 @@
import os import os
import platform
import socket
import subprocess
import time import time
from urllib.parse import urlparse import ollama
from ollama import chat
import httpx
import requests import requests
from dotenv import load_dotenv import subprocess
from ollama import Client as OllamaClient import ipaddress
import httpx
import socket
import platform
from urllib.parse import urlparse
from dotenv import load_dotenv, set_key
from openai import OpenAI from openai import OpenAI
from typing import List, Tuple, Type, Dict
from sources.logger import Logger
from sources.utility import pretty_print, animate_thinking from sources.utility import pretty_print, animate_thinking
from sources.logger import Logger
class Provider: class Provider:
def __init__(self, provider_name, model, server_address="127.0.0.1:5000", is_local=False): def __init__(self, provider_name, model, server_address = "127.0.0.1:5000", is_local=False):
self.provider_name = provider_name.lower() self.provider_name = provider_name.lower()
self.model = model self.model = model
self.is_local = is_local self.is_local = is_local
self.server_ip = server_address self.server_ip = server_address
self.server_address = server_address
self.available_providers = { self.available_providers = {
"ollama": self.ollama_fn, "ollama": self.ollama_fn,
"server": self.server_fn, "server": self.server_fn,
@@ -31,13 +32,11 @@ class Provider:
"deepseek": self.deepseek_fn, "deepseek": self.deepseek_fn,
"together": self.together_fn, "together": self.together_fn,
"dsk_deepseek": self.dsk_deepseek, "dsk_deepseek": self.dsk_deepseek,
"openrouter": self.openrouter_fn,
"test": self.test_fn "test": self.test_fn
} }
self.logger = Logger("provider.log") self.logger = Logger("provider.log")
self.api_key = None self.api_key = None
self.internal_url, self.in_docker = self.get_internal_url() self.unsafe_providers = ["openai", "deepseek", "dsk_deepseek", "together", "google"]
self.unsafe_providers = ["openai", "deepseek", "dsk_deepseek", "together", "google", "openrouter"]
if self.provider_name not in self.available_providers: if self.provider_name not in self.available_providers:
raise ValueError(f"Unknown provider: {provider_name}") raise ValueError(f"Unknown provider: {provider_name}")
if self.provider_name in self.unsafe_providers and self.is_local == False: if self.provider_name in self.unsafe_providers and self.is_local == False:
@@ -45,7 +44,7 @@ class Provider:
self.api_key = self.get_api_key(self.provider_name) self.api_key = self.get_api_key(self.provider_name)
elif self.provider_name != "ollama": elif self.provider_name != "ollama":
pretty_print(f"Provider: {provider_name} initialized at {self.server_ip}", color="success") pretty_print(f"Provider: {provider_name} initialized at {self.server_ip}", color="success")
def get_model_name(self) -> str: def get_model_name(self) -> str:
return self.model return self.model
@@ -57,15 +56,8 @@ class Provider:
pretty_print(f"API key {api_key_var} not found in .env file. Please add it", color="warning") pretty_print(f"API key {api_key_var} not found in .env file. Please add it", color="warning")
exit(1) exit(1)
return api_key return api_key
def get_internal_url(self):
load_dotenv()
url = os.getenv("DOCKER_INTERNAL_URL")
if not url: # running on host
return "http://localhost", False
return url, True
def respond(self, history, verbose=True): def respond(self, history, verbose = True):
""" """
Use the choosen provider to generate text. Use the choosen provider to generate text.
""" """
@@ -81,8 +73,7 @@ class Provider:
except AttributeError as e: except AttributeError as e:
raise NotImplementedError(f"{str(e)}\nIs {self.provider_name} implemented ?") raise NotImplementedError(f"{str(e)}\nIs {self.provider_name} implemented ?")
except ModuleNotFoundError as e: except ModuleNotFoundError as e:
raise ModuleNotFoundError( raise ModuleNotFoundError(f"{str(e)}\nA import related to provider {self.provider_name} was not found. Is it installed ?")
f"{str(e)}\nA import related to provider {self.provider_name} was not found. Is it installed ?")
except Exception as e: except Exception as e:
if "try again later" in str(e).lower(): if "try again later" in str(e).lower():
return f"{self.provider_name} server is overloaded. Please try again later." return f"{self.provider_name} server is overloaded. Please try again later."
@@ -115,7 +106,8 @@ class Provider:
except (subprocess.TimeoutExpired, subprocess.SubprocessError) as e: except (subprocess.TimeoutExpired, subprocess.SubprocessError) as e:
return False return False
def server_fn(self, history, verbose=False):
def server_fn(self, history, verbose = False):
""" """
Use a remote server with LLM to generate text. Use a remote server with LLM to generate text.
""" """
@@ -149,59 +141,50 @@ class Provider:
pretty_print(f"An error occurred: {str(e)}", color="failure") pretty_print(f"An error occurred: {str(e)}", color="failure")
break break
except KeyError as e: except KeyError as e:
raise Exception( raise Exception(f"{str(e)}\nError occured with server route. Are you using the correct address for the config.ini provider?") from e
f"{str(e)}\nError occured with server route. Are you using the correct address for the config.ini provider?") from e
except Exception as e: except Exception as e:
raise e raise e
return thought return thought
def ollama_fn(self, history, verbose=False): def ollama_fn(self, history, verbose = False):
""" """
Use local or remote Ollama server to generate text. Use local ollama server to generate text.
""" """
thought = "" thought = ""
host = f"{self.internal_url}:11434" if self.is_local else f"http://{self.server_address}"
client = OllamaClient(host=host)
try: try:
stream = client.chat( stream = chat(
model=self.model, model=self.model,
messages=history, messages=history,
stream=True, stream=True,
) )
for chunk in stream: for chunk in stream:
if verbose: if verbose:
print(chunk["message"]["content"], end="", flush=True) print(chunk['message']['content'], end='', flush=True)
thought += chunk["message"]["content"] thought += chunk['message']['content']
except httpx.ConnectError as e: except httpx.ConnectError as e:
raise Exception( raise Exception("\nOllama connection failed. provider should not be set to ollama if server address is not localhost") from e
f"\nOllama connection failed at {host}. Check if the server is running." except ollama.ResponseError as e:
) from e if e.status_code == 404:
except Exception as e:
if hasattr(e, 'status_code') and e.status_code == 404:
animate_thinking(f"Downloading {self.model}...") animate_thinking(f"Downloading {self.model}...")
client.pull(self.model) ollama.pull(self.model)
self.ollama_fn(history, verbose) self.ollama_fn(history, verbose)
if "refused" in str(e).lower(): if "refused" in str(e).lower():
raise Exception( raise Exception("Ollama connection failed. is the server running ?") from e
f"Ollama connection refused at {host}. Is the server running?"
) from e
raise e raise e
return thought return thought
def huggingface_fn(self, history, verbose=False): def huggingface_fn(self, history, verbose=False):
""" """
Use huggingface to generate text. Use huggingface to generate text.
""" """
from huggingface_hub import InferenceClient from huggingface_hub import InferenceClient
client = InferenceClient( client = InferenceClient(
api_key=self.get_api_key("huggingface") api_key=self.get_api_key("huggingface")
) )
completion = client.chat.completions.create( completion = client.chat.completions.create(
model=self.model, model=self.model,
messages=history, messages=history,
max_tokens=1024, max_tokens=1024,
) )
thought = completion.choices[0].message thought = completion.choices[0].message
return thought.content return thought.content
@@ -211,13 +194,7 @@ class Provider:
Use openai to generate text. Use openai to generate text.
""" """
base_url = self.server_ip base_url = self.server_ip
if self.is_local and self.in_docker: if self.is_local:
try:
host, port = base_url.split(':')
except Exception as e:
port = "8000"
client = OpenAI(api_key=self.api_key, base_url=f"{self.internal_url}:{port}")
elif self.is_local:
client = OpenAI(api_key=self.api_key, base_url=f"http://{base_url}") client = OpenAI(api_key=self.api_key, base_url=f"http://{base_url}")
else: else:
client = OpenAI(api_key=self.api_key) client = OpenAI(api_key=self.api_key)
@@ -235,39 +212,7 @@ class Provider:
return thought return thought
except Exception as e: except Exception as e:
raise Exception(f"OpenAI API error: {str(e)}") from e raise Exception(f"OpenAI API error: {str(e)}") from e
def anthropic_fn(self, history, verbose=False):
"""
Use Anthropic to generate text.
"""
from anthropic import Anthropic
client = Anthropic(api_key=self.api_key)
system_message = None
messages = []
for message in history:
clean_message = {'role': message['role'], 'content': message['content']}
if message['role'] == 'system':
system_message = message['content']
else:
messages.append(clean_message)
try:
response = client.messages.create(
model=self.model,
max_tokens=1024,
messages=messages,
system=system_message
)
if response is None:
raise Exception("Anthropic response is empty.")
thought = response.content[0].text
if verbose:
print(thought)
return thought
except Exception as e:
raise Exception(f"Anthropic API error: {str(e)}") from e
def google_fn(self, history, verbose=False): def google_fn(self, history, verbose=False):
""" """
Use google gemini to generate text. Use google gemini to generate text.
@@ -333,93 +278,40 @@ class Provider:
return thought return thought
except Exception as e: except Exception as e:
raise Exception(f"Deepseek API error: {str(e)}") from e raise Exception(f"Deepseek API error: {str(e)}") from e
def lm_studio_fn(self, history, verbose=False): def lm_studio_fn(self, history, verbose = False):
""" """
Use local lm-studio server to generate text. Use local lm-studio server to generate text.
lm studio use endpoint /v1/chat/completions not /chat/completions like openai
""" """
if self.in_docker: thought = ""
# Extract port from server_address if present route_start = f"{self.server_ip}/v1/chat/completions"
port = "1234" # default
if ":" in self.server_address:
port = self.server_address.split(":")[1]
url = f"{self.internal_url}:{port}"
else:
url = f"http://{self.server_ip}"
route_start = f"{url}/v1/chat/completions"
payload = { payload = {
"messages": history, "messages": history,
"temperature": 0.7, "temperature": 0.7,
"max_tokens": 4096, "max_tokens": 4096,
"model": self.model "model": self.model
} }
try: try:
response = requests.post(route_start, json=payload, timeout=30) response = requests.post(route_start, json=payload)
if response.status_code != 200: result = response.json()
raise Exception(f"LM Studio returned status {response.status_code}: {response.text}")
if not response.text.strip():
raise Exception("LM Studio returned empty response")
try:
result = response.json()
except ValueError as json_err:
raise Exception(f"Invalid JSON from LM Studio: {response.text[:200]}") from json_err
if verbose: if verbose:
print("Response from LM Studio:", result) print("Response from LM Studio:", result)
choices = result.get("choices", []) return result.get("choices", [{}])[0].get("message", {}).get("content", "")
if not choices:
raise Exception(f"No choices in LM Studio response: {result}")
message = choices[0].get("message", {})
content = message.get("content", "")
if not content:
raise Exception(f"Empty content in LM Studio response: {result}")
return content
except requests.exceptions.Timeout:
raise Exception("LM Studio request timed out - check if server is responsive")
except requests.exceptions.ConnectionError:
raise Exception(f"Cannot connect to LM Studio at {route_start} - check if server is running")
except requests.exceptions.RequestException as e: except requests.exceptions.RequestException as e:
raise Exception(f"HTTP request failed: {str(e)}") from e raise Exception(f"HTTP request failed: {str(e)}") from e
except Exception as e: except Exception as e:
if "LM Studio" in str(e): raise Exception(f"An error occurred: {str(e)}") from e
raise # Re-raise our custom exceptions
raise Exception(f"Unexpected error: {str(e)}") from e
return thought return thought
def openrouter_fn(self, history, verbose=False): def dsk_deepseek(self, history, verbose = False):
"""
Use OpenRouter API to generate text.
"""
client = OpenAI(api_key=self.api_key, base_url="https://openrouter.ai/api/v1")
if self.is_local:
# This case should ideally not be reached if unsafe_providers is set correctly
# and is_local is False in config for openrouter
raise Exception("OpenRouter is not available for local use. Change config.ini")
try:
response = client.chat.completions.create(
model=self.model,
messages=history,
)
if response is None:
raise Exception("OpenRouter response is empty.")
thought = response.choices[0].message.content
if verbose:
print(thought)
return thought
except Exception as e:
raise Exception(f"OpenRouter API error: {str(e)}") from e
def dsk_deepseek(self, history, verbose=False):
""" """
Use: xtekky/deepseek4free Use: xtekky/deepseek4free
For free api. Api key should be set to DSK_DEEPSEEK_API_KEY For free api. Api key should be set to DSK_DEEPSEEK_API_KEY
This is an unofficial provider, you'll have to find how to set it up yourself. This is an unofficial provider, you'll have to find how to set it up yourself.
""" """
from dsk.api import ( from dsk.api import (
DeepSeekAPI, DeepSeekAPI,
AuthenticationError, AuthenticationError,
RateLimitError, RateLimitError,
NetworkError, NetworkError,
@@ -448,7 +340,7 @@ class Provider:
raise APIError(f"API error occurred: {str(e)}") from e raise APIError(f"API error occurred: {str(e)}") from e
return None return None
def test_fn(self, history, verbose=True): def test_fn(self, history, verbose = True):
""" """
This function is used to conduct tests. This function is used to conduct tests.
""" """
@@ -457,7 +349,6 @@ class Provider:
""" """
return thought return thought
if __name__ == "__main__": if __name__ == "__main__":
provider = Provider("server", "deepseek-r1:32b", " x.x.x.x:8080") provider = Provider("server", "deepseek-r1:32b", " x.x.x.x:8080")
res = provider.respond(["user", "Hello, how are you?"]) res = provider.respond(["user", "Hello, how are you?"])
+5 -7
View File
@@ -17,13 +17,11 @@ class Logger:
def create_logging(self, log_filename): def create_logging(self, log_filename):
self.logger = logging.getLogger(log_filename) self.logger = logging.getLogger(log_filename)
self.logger.setLevel(logging.DEBUG) self.logger.setLevel(logging.DEBUG)
self.logger.handlers.clear() if not self.logger.handlers:
self.logger.propagate = False file_handler = logging.FileHandler(self.log_path)
file_handler = logging.FileHandler(self.log_path) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') file_handler.setFormatter(formatter)
file_handler.setFormatter(formatter) self.logger.addHandler(file_handler)
self.logger.addHandler(file_handler)
def create_folder(self, path): def create_folder(self, path):
"""Create log dir""" """Create log dir"""
+5 -12
View File
@@ -7,14 +7,10 @@ import json
from typing import List, Tuple, Type, Dict from typing import List, Tuple, Type, Dict
import torch import torch
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
import configparser
from sources.utility import timer_decorator, pretty_print, animate_thinking from sources.utility import timer_decorator, pretty_print, animate_thinking
from sources.logger import Logger from sources.logger import Logger
config = configparser.ConfigParser()
config.read('config.ini')
class Memory(): class Memory():
""" """
Memory is a class for managing the conversation memory Memory is a class for managing the conversation memory
@@ -122,13 +118,13 @@ class Memory():
json_memory = json.load(f) json_memory = json.load(f)
except FileNotFoundError: except FileNotFoundError:
self.logger.warning(f"File not found: {path}") self.logger.warning(f"File not found: {path}")
return {} return None
except json.JSONDecodeError: except json.JSONDecodeError:
self.logger.warning(f"Error decoding JSON from file: {path}") self.logger.warning(f"Error decoding JSON from file: {path}")
return {} return None
except Exception as e: except Exception as e:
self.logger.warning(f"Error loading file {path}: {e}") self.logger.warning(f"Error loading file {path}: {e}")
return {} return None
return json_memory return json_memory
def load_memory(self, agent_type: str = "casual_agent") -> None: def load_memory(self, agent_type: str = "casual_agent") -> None:
@@ -166,10 +162,7 @@ class Memory():
if self.memory[curr_idx-1]['content'] == content: if self.memory[curr_idx-1]['content'] == content:
pretty_print("Warning: same message have been pushed twice to memory", color="error") pretty_print("Warning: same message have been pushed twice to memory", color="error")
time_str = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") time_str = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
if config["MAIN"]["provider_name"] == "openrouter": self.memory.append({'role': role, 'content': content, 'time': time_str, 'model_used': self.model_provider})
self.memory.append({'role': role, 'content': content})
else:
self.memory.append({'role': role, 'content': content, 'time': time_str, 'model_used': self.model_provider})
return curr_idx-1 return curr_idx-1
def clear(self) -> None: def clear(self) -> None:
@@ -245,7 +238,7 @@ class Memory():
if len(self.memory[i]['content']) > 1024: if len(self.memory[i]['content']) > 1024:
self.memory[i]['content'] = self.summarize(self.memory[i]['content']) self.memory[i]['content'] = self.summarize(self.memory[i]['content'])
def trim_text_to_max_ctx(self, text: str) -> str: def trip_text_to_max_ctx(self, text: str) -> str:
""" """
Truncate a text to fit within the maximum context size of the model. Truncate a text to fit within the maximum context size of the model.
""" """
-2
View File
@@ -19,7 +19,6 @@ class QueryRequest(BaseModel):
class QueryResponse(BaseModel): class QueryResponse(BaseModel):
done: str done: str
answer: str answer: str
reasoning: str
agent_name: str agent_name: str
success: str success: str
blocks: dict blocks: dict
@@ -33,7 +32,6 @@ class QueryResponse(BaseModel):
return { return {
"done": self.done, "done": self.done,
"answer": self.answer, "answer": self.answer,
"reasoning": self.reasoning,
"agent_name": self.agent_name, "agent_name": self.agent_name,
"success": self.success, "success": self.success,
"blocks": self.blocks, "blocks": self.blocks,
+6 -38
View File
@@ -3,18 +3,11 @@ from typing import List, Tuple, Type, Dict
import queue import queue
import threading import threading
import numpy as np import numpy as np
import torch
import time import time
from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, pipeline
IMPORT_FOUND = True import librosa
import pyaudio
try:
import torch
import librosa
import pyaudio
from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, pipeline
except ImportError:
print(Fore.RED + "Speech To Text disabled." + Fore.RESET)
IMPORT_FOUND = False
audio_queue = queue.Queue() audio_queue = queue.Queue()
done = False done = False
@@ -30,18 +23,13 @@ class AudioRecorder:
self.chunk = chunk self.chunk = chunk
self.record_seconds = record_seconds self.record_seconds = record_seconds
self.verbose = verbose self.verbose = verbose
self.thread = None self.audio = pyaudio.PyAudio()
self.audio = None self.thread = threading.Thread(target=self._record, daemon=True)
if IMPORT_FOUND:
self.audio = pyaudio.PyAudio()
self.thread = threading.Thread(target=self._record, daemon=True)
def _record(self) -> None: def _record(self) -> None:
""" """
Record audio from the microphone and add it to the audio queue. Record audio from the microphone and add it to the audio queue.
""" """
if not IMPORT_FOUND:
return
stream = self.audio.open(format=self.format, channels=self.channels, rate=self.rate, stream = self.audio.open(format=self.format, channels=self.channels, rate=self.rate,
input=True, frames_per_buffer=self.chunk) input=True, frames_per_buffer=self.chunk)
if self.verbose: if self.verbose:
@@ -70,14 +58,10 @@ class AudioRecorder:
def start(self) -> None: def start(self) -> None:
"""Start the recording thread.""" """Start the recording thread."""
if not IMPORT_FOUND:
return
self.thread.start() self.thread.start()
def join(self) -> None: def join(self) -> None:
"""Wait for the recording thread to finish.""" """Wait for the recording thread to finish."""
if not IMPORT_FOUND:
return
self.thread.join() self.thread.join()
class Transcript: class Transcript:
@@ -85,9 +69,6 @@ class Transcript:
Transcript is a class that transcribes audio from the audio queue and adds it to the transcript. Transcript is a class that transcribes audio from the audio queue and adds it to the transcript.
""" """
def __init__(self): def __init__(self):
if not IMPORT_FOUND:
print(Fore.RED + "Transcript: Speech to Text is disabled." + Fore.RESET)
return
self.last_read = None self.last_read = None
device = self.get_device() device = self.get_device()
torch_dtype = torch.float16 if device == "cuda" else torch.float32 torch_dtype = torch.float16 if device == "cuda" else torch.float32
@@ -110,8 +91,6 @@ class Transcript:
) )
def get_device(self) -> str: def get_device(self) -> str:
if not IMPORT_FOUND:
return "cpu"
if torch.backends.mps.is_available(): if torch.backends.mps.is_available():
return "mps" return "mps"
if torch.cuda.is_available(): if torch.cuda.is_available():
@@ -129,8 +108,6 @@ class Transcript:
def transcript_job(self, audio_data: np.ndarray, sample_rate: int = 16000) -> str: def transcript_job(self, audio_data: np.ndarray, sample_rate: int = 16000) -> str:
"""Transcribe the audio data.""" """Transcribe the audio data."""
if not IMPORT_FOUND:
return ""
if audio_data.dtype != np.float32: if audio_data.dtype != np.float32:
audio_data = audio_data.astype(np.float32) / np.iinfo(audio_data.dtype).max audio_data = audio_data.astype(np.float32) / np.iinfo(audio_data.dtype).max
if len(audio_data.shape) > 1: if len(audio_data.shape) > 1:
@@ -145,9 +122,6 @@ class AudioTranscriber:
AudioTranscriber is a class that transcribes audio from the audio queue and adds it to the transcript. AudioTranscriber is a class that transcribes audio from the audio queue and adds it to the transcript.
""" """
def __init__(self, ai_name: str, verbose: bool = False): def __init__(self, ai_name: str, verbose: bool = False):
if not IMPORT_FOUND:
print(Fore.RED + "AudioTranscriber: Speech to Text is disabled." + Fore.RESET)
return
self.verbose = verbose self.verbose = verbose
self.ai_name = ai_name self.ai_name = ai_name
self.transcriptor = Transcript() self.transcriptor = Transcript()
@@ -178,8 +152,6 @@ class AudioTranscriber:
""" """
Transcribe the audio data using AI stt model. Transcribe the audio data using AI stt model.
""" """
if not IMPORT_FOUND:
return
global done global done
if self.verbose: if self.verbose:
print(Fore.BLUE + "AudioTranscriber: Started processing..." + Fore.RESET) print(Fore.BLUE + "AudioTranscriber: Started processing..." + Fore.RESET)
@@ -213,13 +185,9 @@ class AudioTranscriber:
def start(self): def start(self):
"""Start the transcription thread.""" """Start the transcription thread."""
if not IMPORT_FOUND:
return
self.thread.start() self.thread.start()
def join(self): def join(self):
if not IMPORT_FOUND:
return
"""Wait for the transcription thread to finish.""" """Wait for the transcription thread to finish."""
self.thread.join() self.thread.join()
+7 -14
View File
@@ -5,14 +5,9 @@ import subprocess
from sys import modules from sys import modules
from typing import List, Tuple, Type, Dict from typing import List, Tuple, Type, Dict
IMPORT_FOUND = True from kokoro import KPipeline
try: from IPython.display import display, Audio
from kokoro import KPipeline import soundfile as sf
from IPython.display import display, Audio
import soundfile as sf
except ImportError:
print("Speech synthesis disabled. Please install the kokoro package.")
IMPORT_FOUND = False
if __name__ == "__main__": if __name__ == "__main__":
from utility import pretty_print, animate_thinking from utility import pretty_print, animate_thinking
@@ -38,7 +33,7 @@ class Speech():
} }
self.pipeline = None self.pipeline = None
self.language = language self.language = language
if enable and IMPORT_FOUND: if enable:
self.pipeline = KPipeline(lang_code=self.lang_map[language]) self.pipeline = KPipeline(lang_code=self.lang_map[language])
self.voice = self.voice_map[language][voice_idx] self.voice = self.voice_map[language][voice_idx]
self.speed = 1.2 self.speed = 1.2
@@ -62,8 +57,7 @@ class Speech():
sentence (str): The text to convert to speech. Will be pre-processed. sentence (str): The text to convert to speech. Will be pre-processed.
voice_idx (int, optional): Index of the voice to use from the voice map. voice_idx (int, optional): Index of the voice to use from the voice map.
""" """
if not self.pipeline or not IMPORT_FOUND: if not self.pipeline:
print("Pipeline disabled.")
return return
if voice_idx >= len(self.voice_map[self.language]): if voice_idx >= len(self.voice_map[self.language]):
pretty_print("Invalid voice number, using default voice", color="error") pretty_print("Invalid voice number, using default voice", color="error")
@@ -115,7 +109,7 @@ class Speech():
def shorten_paragraph(self, sentence): def shorten_paragraph(self, sentence):
#TODO find a better way, we would like to have the TTS not be annoying, speak only useful informations #TODO find a better way, we would like to have the TTS not be annoying, speak only useful informations
""" """
Find long paragraph like **explanation**: <long text> by keeping only the first sentence. Find long paragraph like **explaination**: <long text> by keeping only the first sentence.
Args: Args:
sentence (str): The sentence to shorten sentence (str): The sentence to shorten
Returns: Returns:
@@ -165,7 +159,6 @@ class Speech():
if __name__ == "__main__": if __name__ == "__main__":
# TODO add info message for cn2an, jieba chinese related import # TODO add info message for cn2an, jieba chinese related import
IMPORT_FOUND = False
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
speech = Speech() speech = Speech()
tosay_en = """ tosay_en = """
@@ -187,4 +180,4 @@ if __name__ == "__main__":
spk = Speech(enable=True, language="en", voice_idx=2) spk = Speech(enable=True, language="en", voice_idx=2)
for i in range(0, 5): for i in range(0, 5):
print(f"Speaking english with voice {i}") print(f"Speaking english with voice {i}")
spk.speak(tosay_en, voice_idx=i) spk.speak(tosay_en, voice_idx=i)
+3 -4
View File
@@ -8,7 +8,7 @@ if __name__ == "__main__": # if running as a script for individual testing
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
from sources.tools.tools import Tools from sources.tools.tools import Tools
from sources.tools.safety import is_any_unsafe from sources.tools.safety import is_unsafe
class BashInterpreter(Tools): class BashInterpreter(Tools):
""" """
@@ -43,9 +43,9 @@ class BashInterpreter(Tools):
for command in commands: for command in commands:
command = f"cd {self.work_dir} && {command}" command = f"cd {self.work_dir} && {command}"
command = command.replace('\n', '') command = command.replace('\n', '')
if self.safe_mode and is_any_unsafe(commands): if self.safe_mode and is_unsafe(commands):
print(f"Unsafe command rejected: {command}") print(f"Unsafe command rejected: {command}")
return "\nUnsafe command: {command}. Execution aborted. This is beyond allowed capabilities report to user." return "Unsafe command detected, execution aborted."
if self.language_bash_attempt(command) and self.allow_language_exec_bash == False: if self.language_bash_attempt(command) and self.allow_language_exec_bash == False:
continue continue
try: try:
@@ -100,7 +100,6 @@ class BashInterpreter(Tools):
r"not permitted", r"not permitted",
r"not installed", r"not installed",
r"not found", r"not found",
r"aborted",
r"no such", r"no such",
r"too many", r"too many",
r"too few", r"too few",
+1 -1
View File
@@ -83,7 +83,7 @@ class FileFinder(Tools):
else: else:
return {"filename": file_path, "error": "File not found"} return {"filename": file_path, "error": "File not found"}
def recursive_search(self, directory_path: str, filename: str) -> str: def recursive_search(self, directory_path: str, filename: str) -> str | None:
""" """
Recursively searches for files in a directory and its subdirectories. Recursively searches for files in a directory and its subdirectories.
Args: Args:
+25 -29
View File
@@ -12,65 +12,61 @@ from sources.tools.tools import Tools
class FlightSearch(Tools): class FlightSearch(Tools):
def __init__(self, api_key: str = None): def __init__(self, api_key: str = None):
""" """
A tool to search for flight information using a flight number via SerpApi. A tool to search for flight information using a flight number via AviationStack API.
""" """
super().__init__() super().__init__()
self.tag = "flight_search" self.tag = "flight_search"
self.name = "Flight Search" self.name = "Flight Search"
self.description = "Search for flight information using a flight number via SerpApi." self.description = "Search for flight information using a flight number via AviationStack API."
self.api_key = api_key or os.getenv("SERPAPI_API_KEY") self.api_key = None
self.api_key = api_key or os.getenv("AVIATIONSTACK_API_KEY")
def execute(self, blocks: str, safety: bool = True) -> str: def execute(self, blocks: str, safety: bool = True) -> str:
if self.api_key is None: if self.api_key is None:
return "Error: No SerpApi key provided." return "Error: No AviationStack API key provided."
for block in blocks: for block in blocks:
flight_number = block.strip().upper().replace('\n', '') flight_number = block.strip().lower().replace('\n', '')
if not flight_number: if not flight_number:
return "Error: No flight number provided." return "Error: No flight number provided."
try: try:
url = "https://serpapi.com/search" url = "http://api.aviationstack.com/v1/flights"
params = { params = {
"engine": "google_flights", "access_key": self.api_key,
"api_key": self.api_key, "flight_iata": flight_number,
"q": flight_number, "limit": 1
"type": "2" # Flight status search
} }
response = requests.get(url, params=params) response = requests.get(url, params=params)
response.raise_for_status() response.raise_for_status()
data = response.json() data = response.json()
if "data" in data and len(data["data"]) > 0:
if "flights" in data and len(data["flights"]) > 0: flight = data["data"][0]
flight = data["flights"][0] # Extract key flight information
flight_status = flight.get("flight_status", "Unknown")
departure = flight.get("departure", {})
arrival = flight.get("arrival", {})
airline = flight.get("airline", {}).get("name", "Unknown")
# Extract key information departure_airport = departure.get("airport", "Unknown")
departure = flight.get("departure_airport", {}) departure_time = departure.get("scheduled", "Unknown")
arrival = flight.get("arrival_airport", {}) arrival_airport = arrival.get("airport", "Unknown")
arrival_time = arrival.get("scheduled", "Unknown")
departure_code = departure.get("id", "Unknown")
departure_time = flight.get("departure_time", "Unknown")
arrival_code = arrival.get("id", "Unknown")
arrival_time = flight.get("arrival_time", "Unknown")
airline = flight.get("airline", "Unknown")
status = flight.get("flight_status", "Unknown")
return ( return (
f"Flight: {flight_number}\n" f"Flight: {flight_number}\n"
f"Airline: {airline}\n" f"Airline: {airline}\n"
f"Status: {status}\n" f"Status: {flight_status}\n"
f"Departure: {departure_code} at {departure_time}\n" f"Departure: {departure_airport} at {departure_time}\n"
f"Arrival: {arrival_code} at {arrival_time}" f"Arrival: {arrival_airport} at {arrival_time}"
) )
else: else:
return f"No flight information found for {flight_number}" return f"No flight information found for {flight_number}"
except requests.RequestException as e: except requests.RequestException as e:
return f"Error during flight search: {str(e)}" return f"Error during flight search: {str(e)}"
except Exception as e: except Exception as e:
return f"Unexpected error: {str(e)}" return f"Unexpected error: {str(e)}"
return "No flight search performed" return "No flight search performed"
def execution_failure_check(self, output: str) -> bool: def execution_failure_check(self, output: str) -> bool:
+2 -2
View File
@@ -76,7 +76,7 @@ class MCP_finder(Tools):
try: try:
matching_mcp_infos = self.find_mcp_servers(block_clean) matching_mcp_infos = self.find_mcp_servers(block_clean)
except requests.exceptions.RequestException as e: except requests.exceptions.RequestException as e:
output += "Connection failed. Is the API key in environment?\n" output += "Connection failed. Is the API key in environement?\n"
continue continue
except Exception as e: except Exception as e:
output += f"Error: {str(e)}\n" output += f"Error: {str(e)}\n"
@@ -118,4 +118,4 @@ if __name__ == "__main__":
result = tool.execute([""" result = tool.execute(["""
stock stock
"""], False) """], False)
print(result) print(result)
+1 -10
View File
@@ -31,7 +31,7 @@ unsafe_commands_unix = [
"route" # Routing table management "route" # Routing table management
"--force", # Force flag for many commands "--force", # Force flag for many commands
"rebase", # Rebase git repository "rebase", # Rebase git repository
"git" # Git commands "git ." # Git commands
] ]
unsafe_commands_windows = [ unsafe_commands_windows = [
@@ -66,15 +66,6 @@ unsafe_commands_windows = [
"bootcfg" "bootcfg"
] ]
def is_any_unsafe(cmds):
"""
check if any bash command is unsafe.
"""
for cmd in cmds:
if is_unsafe(cmd):
return True
return False
def is_unsafe(cmd): def is_unsafe(cmd):
""" """
check if a bash command is unsafe. check if a bash command is unsafe.
+1 -1
View File
@@ -16,7 +16,7 @@ class searxSearch(Tools):
self.tag = "web_search" self.tag = "web_search"
self.name = "searxSearch" self.name = "searxSearch"
self.description = "A tool for searching a SearxNG for web search" self.description = "A tool for searching a SearxNG for web search"
self.base_url = os.getenv("SEARXNG_BASE_URL") # Requires a SearxNG base URL self.base_url = base_url or os.getenv("SEARXNG_BASE_URL") # Requires a SearxNG base URL
self.user_agent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36" self.user_agent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36"
self.paywall_keywords = [ self.paywall_keywords = [
"Member-only", "access denied", "restricted content", "404", "this page is not working" "Member-only", "access denied", "restricted content", "404", "this page is not working"
+22 -16
View File
@@ -41,23 +41,28 @@ class Tools():
self.config = configparser.ConfigParser() self.config = configparser.ConfigParser()
self.work_dir = self.create_work_dir() self.work_dir = self.create_work_dir()
self.excutable_blocks_found = False self.excutable_blocks_found = False
self.safe_mode = False self.safe_mode = True
self.allow_language_exec_bash = False self.allow_language_exec_bash = False
def get_work_dir(self): def get_work_dir(self):
return self.work_dir return self.work_dir
def set_allow_language_exec_bash(self, value: bool) -> None: def set_allow_language_exec_bash(value: bool) -> None:
self.allow_language_exec_bash = value self.allow_language_exec_bash = value
def safe_get_work_dir_path(self): def check_config_dir_validity(self):
path = None """Check if the config directory is valid."""
path = os.getenv('WORK_DIR', path) path = self.config['MAIN']['work_dir']
if path is None or path == "": if path == "":
path = self.config['MAIN']['work_dir'] if 'MAIN' in self.config and 'work_dir' in self.config['MAIN'] else None print("WARNING: Work directory not set in config.ini")
if path is None or path == "": return False
raise Exception("No work dir specified, please specify a work dir in .env file.") if path.lower() == "none":
return path print("WARNING: Work directory set to none in config.ini")
return False
if not os.path.exists(path):
print(f"WARNING: Work directory {path} does not exist")
return False
return True
def config_exists(self): def config_exists(self):
"""Check if the config file exists.""" """Check if the config file exists."""
@@ -68,10 +73,11 @@ class Tools():
default_path = os.path.dirname(os.getcwd()) default_path = os.path.dirname(os.getcwd())
if self.config_exists(): if self.config_exists():
self.config.read('./config.ini') self.config.read('./config.ini')
workdir_path = self.safe_get_work_dir_path() config_path = self.config['MAIN']['work_dir']
dir_path = default_path if not self.check_config_dir_validity() else config_path
else: else:
workdir_path = default_path dir_path = default_path
return workdir_path return dir_path
@abstractmethod @abstractmethod
def execute(self, blocks:[str], safety:bool) -> str: def execute(self, blocks:[str], safety:bool) -> str:
@@ -151,7 +157,7 @@ class Tools():
self.excutable_blocks_found = False self.excutable_blocks_found = False
return tmp return tmp
def load_exec_block(self, llm_text: str): def load_exec_block(self, llm_text: str) -> tuple[list[str], str | None]:
""" """
Extract code/query blocks from LLM-generated text and process them for execution. Extract code/query blocks from LLM-generated text and process them for execution.
This method parses the text looking for code blocks marked with the tool's tag (e.g. ```python). This method parses the text looking for code blocks marked with the tool's tag (e.g. ```python).
@@ -215,4 +221,4 @@ for file in os.listdir():
``` ```
goodbye! goodbye!
""") """)
print(rt) print(rt)
+3 -1
View File
@@ -21,5 +21,7 @@ window.fetch = function() {
console.log('Blocked fetch request'); console.log('Blocked fetch request');
return Promise.reject('Blocked'); return Promise.reject('Blocked');
}; };
// Block annoying dialogs
window.alert = function() {};
window.confirm = function() { return false; };
window.prompt = function() { return null; }; window.prompt = function() { return null; };
-126
View File
@@ -1,126 +0,0 @@
// Core automation masking
delete window.cdc_adoQpoasnfa76pfcZLmcfl_Array;
delete window.cdc_adoQpoasnfa76pfcZLmcfl_Promise;
delete window.cdc_adoQpoasnfa76pfcZLmcfl_Symbol;
window.RTCPeerConnection = undefined;
window.webkitRTCPeerConnection = undefined;
window.mozRTCPeerConnection = undefined;
window.Notification = class Notification {
constructor(title, options = {}) {
this.title = title;
this.options = options;
}
static permission = 'granted';
static requestPermission = () => Promise.resolve('granted');
close() {}
onclick = null;
onerror = null;
onclose = null;
onshow = null;
};
Object.keys(window).forEach((key) => {
if (key.includes("webdriver") || key.includes("selenium") || key.includes("driver")) {
delete window[key];
}
});
// Randomize plugins
const pluginsList = [
{type: 'application/x-google-chrome-pdf', description: 'Portable Document Format', filename: 'internal-pdf-viewer', name: 'Chrome PDF Plugin'},
{type: 'application/x-nacl', description: 'Native Client Executable', filename: 'internal-nacl-plugin', name: 'Native Client'},
{type: 'application/x-ppapi-widevine-cdm', description: 'Widevine Content Decryption Module', filename: 'widevinecdm', name: 'Widevine CDM'}
];
Object.defineProperty(navigator, 'plugins', {
get: () => pluginsList.slice(0, Math.floor(Math.random() * pluginsList.length) + 1)
});
// Font spoofing
const fontList = ['Arial', 'Helvetica', 'Times New Roman', 'Courier New', 'Verdana'];
Object.defineProperty(document, 'fonts', {
value: {
add: function() {},
check: function(font) { return fontList.includes(font.split(' ').slice(-1)[0]); },
delete: function() {},
forEach: function(cb) { fontList.forEach(f => cb(f)); },
has: function(font) { return fontList.includes(font.split(' ').slice(-1)[0]); },
keys: function() { return fontList; },
size: fontList.length
}
});
// Canvas fingerprint spoofing
HTMLCanvasElement.prototype.toDataURL = function() {
const ctx = this.getContext('2d');
// Add varied noise to avoid consistent fingerprints
for (let i = 0; i < 10; i++) {
ctx.fillStyle = `rgba(${Math.random() * 5}, ${Math.random() * 5}, ${Math.random() * 5}, 0.005)`;
ctx.fillRect(Math.random() * this.width, Math.random() * this.height, 1, 1);
}
return originalToDataURL.apply(this, arguments);
};
const [w, h] = [1920, 1080];
Object.defineProperty(window, 'screen', {
value: {
width: w,
height: h,
availWidth: w - 20,
availHeight: h - 100,
colorDepth: 24,
pixelDepth: 24
}
});
// ===== WebGL Consistency =====
const os = navigator.userAgent.includes('Windows') ? 'Windows' : 'Mac';
const webGLParams = {
'Windows': {
37445: 'Google Inc. (NVIDIA)', // VENDOR
37446: 'ANGLE (NVIDIA, NVIDIA GeForce RTX 3060)', // RENDERER
36349: 'NVIDIA Corporation', // UNMASKED_VENDOR_WEBGL
37444: 'NVIDIA GeForce RTX 3060', // UNMASKED_RENDERER_WEBGL
35661: 'WebGL 2.0' // VERSION
},
'Mac': {
37445: 'Apple Inc.',
37446: 'Apple M1 Pro',
36349: 'Apple',
37444: 'Apple M1 Pro',
35661: 'WebGL 2.0 (Metal)'
}
};
// replace WebGL parameters
WebGLRenderingContext.prototype.getParameter = function(parameter) {
return webGLParams[os][parameter] || getParameter.call(this, parameter);
};
// Performance API spoofing
if ('performance' in window) {
Object.defineProperty(performance, 'memory', {
value: {
jsHeapSizeLimit: 4294705152,
totalJSHeapSize: 78365432,
usedJSHeapSize: 46543210
},
configurable: true
});
}
const originalCreate = window.AudioContext || window.webkitAudioContext;
window.AudioContext = window.webkitAudioContext = function() {
const context = new originalCreate();
const analyser = context.createAnalyser();
analyser.fake = true; // Mark as spoofed
// Spoof common methods
analyser.getFloatFrequencyData = () => new Float32Array(1024).fill(Math.random() * -100);
return context;
};
+9 -41
View File
@@ -1,45 +1,13 @@
@echo off @echo off
if "%1"=="full" ( REM Up the provider in windows
echo Starting full deployment... start ollama serve
) else (
set "msg=Starting partial deployment... (backend run on host), use "full" to run all services in containers" docker-compose up
echo !msg! if %ERRORLEVEL% neq 0 (
echo Error: Failed to start containers. Check Docker logs with 'docker compose logs'.
echo Possible fixes: Ensure Docker Desktop is running or check if port 8080 is free.
exit /b 1
) )
@echo off timeout /t 10 /nobreak >nul
openssl rand -hex 32 >nul 2>&1
if %ERRORLEVEL% == 0 (
for /f %%i in ('openssl rand -hex 32') do set SEARXNG_SECRET_KEY=%%i
goto :key_generated
)
python --version >nul 2>&1
if %ERRORLEVEL% == 0 (
for /f %%i in ('python -c "import secrets; print(secrets.token_hex(32))"') do set SEARXNG_SECRET_KEY=%%i
goto :key_generated
)
py --version >nul 2>&1
if %ERRORLEVEL% == 0 (
for /f %%i in ('py -c "import secrets; print(secrets.token_hex(32))"') do set SEARXNG_SECRET_KEY=%%i
goto :key_generated
)
echo Error: Neither openssl nor python is available to generate a secret key.
echo Please install Python from https://python.org or OpenSSL
exit /b 2
:key_generated
echo Secret key generated successfully
REM Generate secret key
for /f %%i in ('powershell -command "[System.Web.Security.Membership]::GeneratePassword(64,0)"') do set SEARXNG_SECRET_KEY=%%i
if "%1"=="full" (
docker compose up -d backend
timeout /t 5 /nobreak >nul
docker compose --profile full up
) else (
docker compose --profile core up
)
+22 -89
View File
@@ -1,35 +1,12 @@
#!/bin/bash #!/bin/bash
source .env
command_exists() { command_exists() {
command -v "$1" &> /dev/null command -v "$1" &> /dev/null
} }
if [ -z "$WORK_DIR" ]; then
echo "Error: WORK_DIR environment variable is not set. Please set it in your .env file."
exit 1
fi
if [[ "$OSTYPE" == "darwin"* ]]; then #
dir_size_bytes=$(du -s -b "$WORK_DIR" 2>/dev/null | awk '{print $1}') # Check if Docker is installed é running
else #
dir_size_bytes=$(du -s --bytes "$WORK_DIR" 2>/dev/null | awk '{print $1}')
fi
max_size_bytes=$((2 * 1024 * 1024 * 1024 * 10))
echo "Mounting $WORK_DIR ($dir_size_bytes bytes) to docker."
if [ "$dir_size_bytes" -gt "$max_size_bytes" ]; then
echo "Error: WORK_DIR ($WORK_DIR) contains more than 20GB of data ($(du -sh "$WORK_DIR" 2>/dev/null | awk '{print $1}'))."
exit 1
fi
if [ "$1" = "full" ]; then
echo "Starting full deployment with backend and all services..."
else
echo "Starting core deployment with frontend and search services only... use ./start_services.sh full to start backend as well"
fi
if ! command_exists docker; then if ! command_exists docker; then
echo "Error: Docker is not installed. Please install Docker first." echo "Error: Docker is not installed. Please install Docker first."
@@ -64,18 +41,17 @@ else
fi fi
# Check if Docker Compose is installed # Check if Docker Compose is installed
# Prefer the newer 'docker compose' command if available if ! command_exists docker-compose && ! docker compose version >/dev/null 2>&1; then
if docker compose version >/dev/null 2>&1; then echo "Error: Docker Compose is not installed. Please install it first."
echo "Using newer docker compose (v2)." echo "On Ubuntu: sudo apt install docker-compose"
COMPOSE_CMD="docker compose" echo "Or via pip: pip install docker-compose"
elif command_exists docker-compose; then exit 1
echo "Using old docker-compose." fi
if command_exists docker-compose; then
COMPOSE_CMD="docker-compose" COMPOSE_CMD="docker-compose"
else else
echo "Error: Docker Compose is not installed. Please install it first." COMPOSE_CMD="docker compose"
echo "On Ubuntu: sudo apt install docker-compose-plugin"
echo "Or install Docker Desktop which includes compose v2"
exit 1
fi fi
# Check if docker-compose.yml exists # Check if docker-compose.yml exists
@@ -84,58 +60,15 @@ if [ ! -f "docker-compose.yml" ]; then
exit 1 exit 1
fi fi
# Stop only the backend container if it's running to ensure a clean state # start docker compose for searxng, redis, frontend services
if docker ps --format '{{.Names}}' | grep -q '^backend$'; then echo "Warning: stopping all docker containers (t-4 seconds)..."
echo "New start: (re)starting backend container..." sleep 4
docker stop backend docker stop $(docker ps -a -q)
echo "Backend container stopped." echo "All containers stopped"
fi
# export searxng secret key (cross-platform) if ! $COMPOSE_CMD up; then
if command -v openssl &> /dev/null; then echo "Error: Failed to start containers. Check Docker logs with '$COMPOSE_CMD logs'."
export SEARXNG_SECRET_KEY=$(openssl rand -hex 32) echo "Possible fixes: Run with sudo or ensure port 8080 is free."
else exit 1
# Fallback: use Python if openssl is not available
if command -v python3 &> /dev/null; then
export SEARXNG_SECRET_KEY=$(python3 -c "import secrets; print(secrets.token_hex(32))")
else
echo "Error: Neither openssl nor python is available to generate a secret key."
exit 1
fi
fi fi
sleep 10
if [ "$1" = "full" ]; then
# First start backend and wait for it to be healthy
echo "Full docker deployment. Starting backend service..."
if ! $COMPOSE_CMD up -d backend; then
echo "Error: Failed to start backend container."
exit 1
fi
# Wait for backend to be healthy (check if it's running and not restarting)
echo "Waiting for backend to be ready..."
for i in {1..30}; do
if [ "$(docker inspect -f '{{.State.Running}}' backend)" = "true" ] && \
[ "$(docker inspect -f '{{.State.Restarting}}' backend)" = "false" ]; then
echo "backend is ready!"
break
fi
if [ $i -eq 30 ]; then
echo "Error: backend failed to start properly after 30 seconds"
$COMPOSE_CMD logs backend
exit 1
fi
sleep 1
done
if ! $COMPOSE_CMD --profile full up; then
echo "Error: Failed to start containers. Check Docker logs with '$COMPOSE_CMD logs'."
echo "Possible fixes: Run with sudo or ensure port 8080 is free."
exit 1
fi
else
if ! $COMPOSE_CMD --profile core up; then
echo "Error: Failed to start containers. Check Docker logs with '$COMPOSE_CMD logs'."
echo "Possible fixes: Run with sudo or ensure port 8080 is free."
exit 1
fi
fi
sleep 10
+1 -1
View File
@@ -23,7 +23,7 @@ class TestBrowserAgentParsing(unittest.TestCase):
"https://thriveonai.com/15-ai-startups-in-japan-to-take-note-of", "https://thriveonai.com/15-ai-startups-in-japan-to-take-note-of",
"www.google.com", "www.google.com",
"https://test.org/about?page=1", "https://test.org/about?page=1",
"https://weatherstack.com/documentation" "https://weatherstack.com/documentation",
] ]
result = self.agent.extract_links(test_text) result = self.agent.extract_links(test_text)
self.assertEqual(result, expected) self.assertEqual(result, expected)
-230
View File
@@ -1,230 +0,0 @@
import unittest
import os
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from sources.tools.tools import Tools
class TestToolsParsing(unittest.TestCase):
"""
Test suite for the Tools class parsing functionality, specifically the load_exec_block method.
This method is responsible for extracting code blocks from LLM-generated text.
"""
def setUp(self):
"""Set up test fixtures before each test method."""
class TestTool(Tools):
def execute(self, blocks, safety=False):
return "test execution"
def execution_failure_check(self, output):
return False
def interpreter_feedback(self, output):
return "test feedback"
self.tool = TestTool()
self.tool.tag = "python" # Set tag for testing
def test_load_exec_block_single_block(self):
"""Test parsing a single code block from LLM text."""
llm_text = """Here's some Python code:
```python
print("Hello, World!")
x = 42
```
That's the code."""
blocks, save_path = self.tool.load_exec_block(llm_text)
self.assertIsNotNone(blocks)
self.assertEqual(len(blocks), 1)
self.assertEqual(blocks[0], '\nprint("Hello, World!")\nx = 42\n')
self.assertIsNone(save_path)
def test_load_exec_block_multiple_blocks(self):
"""Test parsing multiple code blocks from LLM text."""
llm_text = """First block:
```python
import os
print("First block")
```
Second block:
```python
import sys
print("Second block")
```
Done."""
blocks, save_path = self.tool.load_exec_block(llm_text)
self.assertIsNotNone(blocks)
self.assertEqual(len(blocks), 2)
self.assertEqual(blocks[0], '\nimport os\nprint("First block")\n')
self.assertEqual(blocks[1], '\nimport sys\nprint("Second block")\n')
self.assertIsNone(save_path)
def test_load_exec_block_with_save_path(self):
"""Test parsing code block with save path specification."""
llm_text = """```python
save_path: test_file.py
import os
print("Hello with save path")
```"""
blocks, save_path = self.tool.load_exec_block(llm_text)
self.assertIsNotNone(blocks)
self.assertEqual(len(blocks), 1)
self.assertEqual(blocks[0], '\nsave_path: test_file.py\nimport os\nprint("Hello with save path")\n')
self.assertIsNone(save_path)
def test_load_exec_block_with_indentation(self):
"""Test parsing code blocks with leading whitespace/indentation."""
llm_text = """ Here's indented code:
```python
def hello():
print("Hello")
return True
```
End of code."""
blocks, save_path = self.tool.load_exec_block(llm_text)
self.assertIsNotNone(blocks)
self.assertEqual(len(blocks), 1)
expected_code = '\ndef hello():\n print("Hello")\n return True\n'
self.assertEqual(blocks[0], expected_code)
def test_load_exec_block_no_blocks(self):
"""Test parsing text with no code blocks."""
llm_text = """This is just regular text with no code blocks.
There are no python blocks here.
Just plain text."""
blocks, save_path = self.tool.load_exec_block(llm_text)
self.assertIsNone(blocks)
self.assertIsNone(save_path)
def test_load_exec_block_wrong_tag(self):
"""Test parsing text with code blocks but wrong language tag."""
llm_text = """```javascript
console.log("This is JavaScript, not Python");
```"""
blocks, save_path = self.tool.load_exec_block(llm_text)
self.assertIsNone(blocks)
self.assertIsNone(save_path)
def test_load_exec_block_incomplete_block(self):
"""Test parsing text with incomplete code block (missing closing tag)."""
llm_text = """```python
print("This block has no closing tag")
x = 42"""
blocks, save_path = self.tool.load_exec_block(llm_text)
self.assertEqual(blocks, [])
self.assertIsNone(save_path)
def test_load_exec_block_empty_block(self):
"""Test parsing empty code block."""
llm_text = """```python
```"""
blocks, save_path = self.tool.load_exec_block(llm_text)
self.assertIsNotNone(blocks)
self.assertEqual(len(blocks), 1)
self.assertEqual(blocks[0], '\n')
def test_load_exec_block_mixed_content(self):
"""Test parsing text with mixed content including code blocks."""
llm_text = """Let me help you with that task.
First, I'll import the necessary modules:
```python
import os
import sys
```
Then I'll define a function:
```python
def process_data(data):
return data.upper()
```
Finally, let's use it:
```python
result = process_data("hello world")
print(result)
```
That should work!"""
blocks, save_path = self.tool.load_exec_block(llm_text)
self.assertIsNotNone(blocks)
self.assertEqual(len(blocks), 3)
self.assertEqual(blocks[0], '\nimport os\nimport sys\n')
self.assertEqual(blocks[1], '\ndef process_data(data):\n return data.upper()\n')
self.assertEqual(blocks[2], '\nresult = process_data("hello world")\nprint(result)\n')
def test_load_exec_block_with_special_characters(self):
"""Test parsing code blocks containing special characters."""
llm_text = """```python
text = "Hello \"world\" with 'quotes'"
regex = r"^\\d+$"
path = "C:\\Users\\test\\file.txt"
```"""
blocks, save_path = self.tool.load_exec_block(llm_text)
self.assertIsNotNone(blocks)
self.assertEqual(len(blocks), 1)
expected = '\ntext = "Hello "world" with \'quotes\'"\nregex = r"^\\d+$"\npath = "C:\\Users\\test\\file.txt"\n'
self.assertEqual(blocks[0], expected)
def test_load_exec_block_tag_undefined(self):
"""Test that assertion error is raised when tag is undefined."""
self.tool.tag = "undefined"
llm_text = """```python
print("test")
```"""
with self.assertRaises(AssertionError):
self.tool.load_exec_block(llm_text)
def test_found_executable_blocks_flag(self):
"""Test that the executable blocks found flag is set correctly."""
self.assertFalse(self.tool.found_executable_blocks())
llm_text = """```python
print("test")
```"""
blocks, save_path = self.tool.load_exec_block(llm_text)
self.assertTrue(self.tool.found_executable_blocks())
self.assertFalse(self.tool.found_executable_blocks())
def test_get_parameter_value(self):
"""Test the get_parameter_value helper method."""
block = """param1 = value1
param2 = value2
some other text
param3 = value3"""
self.assertEqual(self.tool.get_parameter_value(block, "param1"), "value1")
self.assertEqual(self.tool.get_parameter_value(block, "param2"), "value2")
self.assertEqual(self.tool.get_parameter_value(block, "param3"), "value3")
self.assertIsNone(self.tool.get_parameter_value(block, "nonexistent"))
if __name__ == '__main__':
unittest.main()
Generated
-3649
View File
File diff suppressed because it is too large Load Diff