Agent Profiles

Агент — это DB-сущность, описывающая роль, инструменты, модели и методы исполнения. Python не содержит бизнес-логики агентов — только routing и execution.

Концепция

В clowbot агент = DB-сущность, а не Python-класс. Это ключевое отличие от традиционных agent-фреймворков.

Агент определяет:

  • goal — цель, добавляется в system prompt
  • allowed_tools — инструменты, которые можно вызывать
  • forbidden_tools — инструменты под запретом
  • preferred_models — модели для исполнения
  • default_temperature — температура по умолчанию
  • response_contract — формат ответа (JSON/markdown/code)

Поведенческие поля:

  • chat_mode — both / interactive / background
  • max_delegation_depth — глубина делегирования sub-агентам
  • can_create_methods — может ли создавать новые методы
  • sprint_config — параметры спринта для планирования

Структура agent_profile

Файл: db/init/359_agent_profiles.sql

CREATE TABLE clowbot.agent_profile (
  agent_code        text PRIMARY KEY,           -- Уникальный код агента
  goal              text NOT NULL DEFAULT '',   -- Цель, идёт в system prompt
  description       text NOT NULL DEFAULT '',   -- Человеческое описание
  allowed_tools     text[] NOT NULL DEFAULT '{}',   -- Разрешённые инструменты
  forbidden_tools   text[] NOT NULL DEFAULT '{}',   -- Запрещённые инструменты
  preferred_models  text[] NOT NULL DEFAULT '{}',   -- Предпочитаемые модели
  default_temperature numeric NOT NULL DEFAULT 0.7, -- Температура LLM
  response_contract jsonb NOT NULL DEFAULT '{}',    -- Формат ответа
  chat_mode         text DEFAULT 'both',           -- both/interactive/background
  can_create_methods boolean DEFAULT false,        -- Может создавать методы
  max_delegation_depth integer DEFAULT 0,          -- Глубина делегирования
  sprint_config     jsonb,                         -- Параметры спринта
  is_active         boolean NOT NULL DEFAULT true,
  created_at        timestamptz NOT NULL DEFAULT now(),
  updated_at        timestamptz NOT NULL DEFAULT now()
);

Пример INSERT

Файл: db/init/360_seed_agent_profiles.sql

INSERT INTO clowbot.agent_profile (
  agent_code, goal, description,
  allowed_tools, forbidden_tools, preferred_models,
  default_temperature, response_contract
) VALUES (
  'web_researcher',
  'Search the web and synthesize factual, sourced answers',
  'Runs multi-query web research with source attribution',
  ARRAY['web_search', 'rag_search'],  -- allowed
  ARRAY['db_query'],                   -- forbidden
  ARRAY['gemma3:4b', 'phi4-mini'],     -- models
  0.4,                                 -- temperature (низкая для точности)
  '{"format": "markdown", "max_tokens": 4096, "language": "auto"}'::jsonb
);

9 базовых агентов

Seed-данные из db/init/360_seed_agent_profiles.sql + UPDATE из 376_seed_agent_methods.sql

core_orchestrator

Main router agent, always included as base layer in prompt assembly

bothdepth:3

"Route user intent to the right execution path and compose final response"

Allowed tools:
web_searchdb_queryrag_search
Forbidden:
phi4-minigemma3:4b
temp: 0.7

task_decomposer

Decomposes multi-step goals into actionable subtask trees

bothdepth:2

"Break complex user tasks into ordered subtasks with dependency graph"

Allowed tools:
db_query
Forbidden:
gemma3:4bphi4-mini
temp: 0.5

web_researcher

Runs multi-query web research with source attribution

bothdepth:1

"Search the web and synthesize factual, sourced answers"

Allowed tools:
web_searchrag_search
Forbidden:
db_query
gemma3:4bphi4-mini
temp: 0.4

coder_executor

Structured code/SQL generation with strict output format

bothdepth:1

"Generate, review, and fix code and SQL queries"

Allowed tools:
db_query
Forbidden:
web_search
qwen2.5-coder:3bqwen2.5-coder:0.5b
temp: 0.3

sql_analyst

Runs SELECT queries, interprets results, and formats reports

bothdepth:1

"Analyze data from database and produce actionable insights"

Allowed tools:
db_query
Forbidden:
web_search
qwen2.5-coder:3bphi4-mini
temp: 0.3

summarizer

Summarizes threads, documents, conversations, and search results

backgrounddepth:0

"Condense long content into concise structured summaries"

Allowed tools:
rag_search
Forbidden:
phi4-minigemma3:4b
temp: 0.4

critic_reviewer

Reviews LLM outputs for hallucination, relevance, and completeness

backgrounddepth:0

"Evaluate response quality and suggest improvements"

Allowed tools:
Forbidden:
web_searchdb_query
gemma3:4bdeepseek-r1:8b
temp: 0.5

memory_keeper

Tracks user preferences, history patterns, and cross-session context

backgrounddepth:1

"Manage persistent user context and session memory"

Allowed tools:
db_queryrag_search
Forbidden:
phi4-mini
temp: 0.3

n8n_composer

Creates n8n workflow definitions using HTTP Request nodes to internal API

interactivedepth:1

"Generate valid n8n workflow JSON from task descriptions"

Allowed tools:
db_query
Forbidden:
web_search
qwen2.5-coder:3b
temp: 0.2

Режимы работы (chat_mode)

both

Участвует в прямом чате и может быть вызван процессом

core_orchestrator, task_decomposer, web_researcher, coder_executor, sql_analyst

interactive

Только при явном вызове пользователя

n8n_composer (создание workflow — ответственный процесс)

background

Только через делегирование от других агентов

summarizer, critic_reviewer, memory_keeper

Глубина делегирования

max_delegation_depth определяет, сколько уровней sub-агентов может вызвать агент.

3core_orchestrator — может делегировать task_decomposer → web_researcher → summarizer
2task_decomposer — один уровень промежуточной делегации
1web_researcher, coder_executor, sql_analyst, memory_keeper, n8n_composer
0summarizer, critic_reviewer — конечные исполнители, не делегируют

Политика выбора (agent_selection_policy)

Таблица agent_selection_policy связывает intent/process_code с агентом.

CREATE TABLE clowbot.agent_selection_policy (
  policy_id          uuid PRIMARY KEY,
  agent_code         text REFERENCES agent_profile(agent_code),
  match_intent       text[] NOT NULL DEFAULT '{}',   -- Интенты для匹配
  match_process_code text[] NOT NULL DEFAULT '{}',   -- Коды процессов
  match_scope        text[] NOT NULL DEFAULT '{}',   -- direct / group
  match_team_id      uuid,                           -- Опционально: команда
  priority           integer NOT NULL DEFAULT 100,   -- Приоритет при конфликте
  is_active          boolean NOT NULL DEFAULT true
);

Примеры политик из seed:

agent_codematch_intentmatch_process_codepriority
core_orchestrator['direct', 'chat']['default_chat']10
web_researcher['web_search', 'web']['web_search', 'web_research_brief']80
coder_executor['code', 'sql'][]80
sql_analyst['db', 'data', 'analytics']['kpi_coach', 'deadline_report']80
task_decomposer['planning', 'plan', 'decompose'][]70
summarizer['summarize', 'summary', 'digest']['daily_digest', 'content_factory_digest']70

Связь с prompt_fragments

Таблица agent_profile_prompt_map связывает агента с prompt-фрагментами для сборки system prompt.

CREATE TABLE clowbot.agent_profile_prompt_map (
  map_id        uuid PRIMARY KEY,
  agent_code    text REFERENCES agent_profile(agent_code),
  fragment_id   uuid REFERENCES prompt_fragment(fragment_id),
  weight        numeric NOT NULL DEFAULT 1.0,   -- Вес при сборке
  ordinal       integer NOT NULL DEFAULT 0,     -- Порядок
  assembly_mode text NOT NULL DEFAULT 'append', -- append/prepend/replace
  is_required   boolean NOT NULL DEFAULT true,
  UNIQUE (agent_code, fragment_id)
);

Если для агента нет явно привязанных фрагментов, система автоматически подбирает топ-3 по agent_family и fragment_type. См. bot/app/services/agent_selection.py:_infer_agent_family() и _infer_fragment_type().

Связи с другими страницами