Agents API

Настраивайте AI-агентов: системный промпт, набор разрешённых коннекторов и доступ к учётным записям организации. Те же эндпоинты используются разделом «Агенты» в самом приложении.

Что такое агент

Агент — это профиль (имя, описание, системный промпт, аватар) плюс список разрешённых коннекторов и выданных учётных записей. Когда вы стартуете сессию с agent_id, ассистент работает под этим профилем и ограничен только теми коннекторами и учётками, которые вы выдали явно.

Создать агента

POST с профилем агента. Обязательное поле — только name, остальные опциональны.

curl -X POST "$BASE/organizations/$ORG_ID/agents" \ -H "Authorization: Bearer $SAMRESHUUU_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "Marketplace Manager", "description": "Watches WB and Ozon stock, replies to reviews", "system_prompt": "You are a senior marketplace operator. Be concise, cite SKU codes.", "avatar_url": "https://cdn.example.com/avatars/mp.png" }'
{ "id": "8a4b9c12-...-...", "org_id": "...", "name": "Marketplace Manager", "description": "Watches WB and Ozon stock, replies to reviews", "system_prompt": "You are a senior marketplace operator...", "avatar_url": "https://cdn.example.com/avatars/mp.png", "is_enabled": true, "created_by": "...", "created_at": "2026-04-29T10:00:00Z", "connectors": [], "kind": "custom" }

Список и получение агента

В списке системный агент идёт первым, затем ваши пользовательские агенты (с пагинацией).

curl "$BASE/organizations/$ORG_ID/agents?limit=20&offset=0" \ -H "Authorization: Bearer $SAMRESHUUU_API_KEY" curl "$BASE/organizations/$ORG_ID/agents/$AGENT_ID" \ -H "Authorization: Bearer $SAMRESHUUU_API_KEY"

Обновить или удалить

PATCH принимает частичный профиль. DELETE — мягкое удаление. Системный агент только для чтения и на любые мутации возвращает HTTP 400.

curl -X PATCH "$BASE/organizations/$ORG_ID/agents/$AGENT_ID" \ -H "Authorization: Bearer $SAMRESHUUU_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "description": "WB + Ozon + Yandex Market", "is_enabled": true }' curl -X DELETE "$BASE/organizations/$ORG_ID/agents/$AGENT_ID" \ -H "Authorization: Bearer $SAMRESHUUU_API_KEY"

Разрешённые коннекторы

PUT .../connectors задаёт полный список ключей коннекторов, которые агент может вызывать (wildberries, ozon, telegram, …). Пустой массив очищает список. Коннекторы — это какими инструментами агенту разрешено пользоваться; учётки — под какими аккаунтами.

curl -X PUT "$BASE/organizations/$ORG_ID/agents/$AGENT_ID/connectors" \ -H "Authorization: Bearer $SAMRESHUUU_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "connector_keys": ["wildberries", "ozon", "telegram"] }'

Доступные учётные записи

Возвращает все учётные записи организации под разрешённые агенту коннекторы плюс флаг granted — есть ли уже у агента доступ к ним.

curl "$BASE/organizations/$ORG_ID/agents/$AGENT_ID/available-credentials" \ -H "Authorization: Bearer $SAMRESHUUU_API_KEY"
[ { "credential_id": "c1...", "service_name": "wildberries", "instance_id": "wb_main", "account_label": "WB Seller — main", "last_used_at": "2026-04-28T18:21:00Z", "granted": false, "grant_id": null }, { "credential_id": "c2...", "service_name": "ozon", "instance_id": "ozon_main", "account_label": "Ozon Seller", "last_used_at": null, "granted": true, "grant_id": "g1..." } ]

Выдать учётную запись

Берёте credential_id из /available-credentials и выдаёте его агенту. Опциональные scopes сужают, какие части учётки агент может использовать. Отзыв — DELETE /grants/{grant_id}.

curl -X POST "$BASE/organizations/$ORG_ID/agents/$AGENT_ID/grants" \ -H "Authorization: Bearer $SAMRESHUUU_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "credential_id": "c1...", "scopes": { "read": true, "write": false } }' curl -X DELETE "$BASE/organizations/$ORG_ID/agents/$AGENT_ID/grants/$GRANT_ID" \ -H "Authorization: Bearer $SAMRESHUUU_API_KEY"

Запустить сессию под агентом

Передайте agent_id в теле POST /sessions/stream. Вызов запускает ход и возвращает 202 с его id — читайте ответ через SSE, как описано в разделе Стриминг (SSE). Ассистент возьмёт системный промпт агента и ограничится его коннекторами и учётками.

curl -X POST "$BASE/sessions/stream" \ -H "Authorization: Bearer $SAMRESHUUU_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "message": "Какие SKU за неделю упали по продажам сильнее всего?", "agent_id": "8a4b9c12-...-..." }'

Доступные инструменты

Полный набор инструментов, которые ассистент может вызывать внутри сессии агента. Набор фиксирован и одинаков для всех агентов — различаются только системный промпт и выданные коннекторы / учётные записи. Имена инструментов — это идентификаторы функций в tool_call.

Поиск в интернете3

ИнструментНазваниеОписание
web_searchПоиск в интернетеWeb search; returns titles, snippets, URLs. Plain query — no operators, no site:.
web_fetchЗагрузка страницыFetch readable text from a URL. Light alternative to a real browser; large pages are staged to /tmp/input.
yandex_image_searchПоиск картинокYandex/Pinterest image search; returns artifact UUIDs + source URLs for downstream tools.

Память пользователя2

ИнструментНазваниеОписание
read_memoryЧтение памятиRead user long-term memory: list / read / read_many over markdown files.
manage_memoryУправление памятьюWrite / delete / move user memory files. Content must include a YAML frontmatter (title, source).

Данные и документы6

ИнструментНазваниеОписание
documentsДокументыCatalog and attach the user's knowledge-base documents to the current task: list all previously uploaded docs (with filters), or attach specific ones for retrieval.
list_datasetsСклад · каталог датасетовCatalog of settled Bronze datasets in the org's warehouse — only what actually landed in warehouse_raw (real coverage, not the manifest wishlist).
describe_datasetСклад · схема датасетаSchema of one Bronze dataset (not the data): the freshest settled payload for (connector, dataset_key), flattened into columns {path, type, sample}.
manage_datasetСклад · Онбординг датасетаOnboard a dataset into the warehouse as data, without a deploy: a global descriptor (how to pull the endpoint) plus a per-org registry (sync cadence).
manage_silverСклад · Silver-маппингSilver layer as data: a registry of parse-mappings over Bronze, read by one generic extractor — no CREATE VIEW per dataset.
manage_goldСклад · Gold-витринаGold layer as data: a data-mart = a frozen author SELECT over the Bronze manifest, materialized by a deterministic runner.

Навыки3

ИнструментНазваниеОписание
skill_searchПоиск навыковSearch the skill catalog by task description; returns skill_id for read_skill.
read_skillЧтение навыкаLoad a skill's prompt, scripts, templates and checklists into context.
manage_skillУправление навыкамиList / create / update / delete / toggle / copy skills (custom and system).

Коннекторы и сервисы5

ИнструментНазваниеОписание
list_servicesКаталог сервисовList connected services; returns canonical service ids.
describe_serviceПаспорт сервисаService spec: modules, recipes, rate_limits, pagination_hints, response_examples.
connector_executeВызов сервисаSingle executor for any registered service: REST or RPC, validated against the service schema.
query_eventsЖурнал входящих событийLocal journal of inbound webhook events (read-only).
sign_documentПодписание документа КЭПSign a document with a qualified e-signature (CryptoPro) via Diadoc / SBIS.

Задачи и автоматизации3

ИнструментНазваниеОписание
query_tasksПросмотр задачRead-only queries: list tasks, get config, list_executions, execution_summary.
manage_taskУправление задачамиCreate / run / toggle / update / delete a saved task: create, create_subtask, run, toggle, update, delete.
task_runtimeСостояние и пауза задачиDurable state and suspend (only inside task execution): save_state, load_state, suspend.

Выполнение кода6

ИнструментНазваниеОписание
sandbox_bashВыполнение кода и командRun shell / Python in an isolated sandbox; returns stdout, stderr, exit_code, files.
repl_executeКод и данныеPersistent Jupyter-like Python REPL with helpers (peek, grep, chunk_indices, llm_query, FINAL).
edit_fileРедактирование файлаSearch-and-replace edits in sandbox files with fuzzy matching fallback.
exec_commandТерминалRun a command in a PTY session on the local machine; finished commands return stdout + exit_code, long-lived processes keep a session_id for write_stdin.
write_stdinТерминал: вводSend characters to the stdin of a live exec_command session (by session_id) and read fresh output; append \n to submit a line.
bsl_checkПроверка BSLStatic analysis of 1C (BSL) code via bsl-language-server on the local machine; point it at a .bsl/.os file or a configuration export folder.

Браузер и формы2

ИнструментНазваниеОписание
browser_interactБраузерHeadless browser actions: navigate, snapshot, click, fill, type, select, upload_file, screenshot.
request_formФорма пользователюInteractive pause: clarify question or integration connect.

Git2

ИнструментНазваниеОписание
git_cloneКлонирование репозиторияClone a Git repo into the sandbox with auto-auth (GitHub, GitLab; public or via integration token).
open_pull_requestОткрыть PR/MRPush the working branch and open a Pull Request (GitHub) or Merge Request (GitLab).

Генерация и обработка медиа5

ИнструментНазваниеОписание
generate_mediaГенерация медиаGenerate image, video, or audio (TTS, music, SFX) from a prompt; image-to-image, platform presets, and count for N variants per call.
edit_imageОбработка изображенийEdit an existing image: remove/blur background, crop, add text/border, marketplace resize. Batches the same operation over up to 20 sources.
render_visualВизуализацияInline visual in the message bubble: exactly one number-driven object — a chart, diagram, timeline, scheme, or KPI card. Ephemeral, not a saved document.
render_mapКартаInline map in the bubble: business geo-points on an interactive OpenStreetMap. Ephemeral artifact, not a saved document.
message_composeЧерновик сообщенияInline message draft in the bubble: 2–4 editable variants of one text the user edits, copies, and sends themselves. Ephemeral.

Анализ (зрение, OCR, аудио)4

ИнструментНазваниеОписание
analyze_imageАнализ изображенияVLM visual analysis: describe, compare, audit UI screenshots; up to 5 images per call.
ocrРаспознавание текста (OCR)OCR for images and scanned PDFs; batch up to 10 documents per call.
transcribeТранскрибация аудиоSpeech-to-text for mp3 / wav / ogg / m4a; batch up to 10, idempotent (cached).
analyze_videoАнализ видеоMultimodal video analysis via Gemini 2.5 Flash + Files API; accepts .mp4, .mov, .webm.

Планирование и управление3

ИнструментНазваниеОписание
run_subagentДелегирование подзадачиDelegate to an explore / execute / verify sub-agent with its own sandbox; up to 5 parallel tasks.
publish_appПубликация лендингаPublish a landing page built in the sandbox to <slug>.apps.samreshuuu.ru and return the public URL. Outward-facing and near-irreversible.
exitЗавершениеFinish the task: deliver the answer text and any output filepaths to the user.

Структура описания инструмента

Каждое описание инструмента самодостаточно — отдельного слоя гайдов нет. Модель читает описание дословно, поэтому все они следуют одной пятиблочной структуре:

  1. Назначение — одно-два предложения: что инструмент делает и что возвращает.
  2. Когда использовать — конкретные сценарии, где этот инструмент — правильный выбор.
  3. Когда НЕ использовать — границы применимости с указанием конкретного альтернативного инструмента.
  4. Ключевые ограничения — предусловия, форматы, лимиты, порядок вызовов и контракт ошибок.
  5. Интерпретация результата — как читать ответ, когда повторять, когда остановиться.

Дескрипторы инструментов лежат в config/prompts/tools.yaml и имеют такую форму:

my_tool: display_name: "Display Name" description: >- One-paragraph purpose of the tool — what it does and what it returns. Когда использовать: concrete scenarios where this tool is the right choice. Когда НЕ использовать: cases where another tool fits better — name the alternative. Key constraints: prerequisites, formats, limits, ordering, error contract. Result interpretation: how to read the response, when to retry, when to stop. category: external # read | write | external | llm | code_execution result_type: contextual # authoritative | contextual | action | metadata | status timeout_ms: 30000 is_mutating: false is_idempotent: true is_query_tool: false synthesis: prefix: "[MY_TOOL]" examples: - param: "value" schema_overrides: require_fields: ["param"] strip_null_fields: ["optional_field"]
Была ли страница полезна?