Логотип Query

Query

ОрганизацияПопулярный
GetStream
query

How list endpoints take filters and sorts, modelled on Stream's query syntax. Read before adding a filter, a sort, or a query endpoint.

Обзор

ИздательGetStream
РепозиторийAgents
Название навыкаquery
Звёзды
8.2K
Форки
709
Файлы в комплекте
Только инструкции
ЛицензияApache-2.0
Ссылки
  • Инструкции в формате Markdown

    Модель загружает файл SKILL.md по мере необходимости, поэтому токены расходуются только при подходящем запросе.

  • Работает с любой большой языковой моделью

    Навыки ИИ — это обычный Markdown, а не код для конкретного поставщика, поэтому они работают с GPT, Claude, Gemini, Grok и локальными моделями.

  • Всё необходимое — в инструкциях

    Всё необходимое для модели содержится в инструкциях — никаких дополнительных файлов для синхронизации.

  • Открытый исходный код

    Издатель навыка на GitHub — GetStream. Перед установкой изучите исходные материалы.

Установка

Установите навык ИИ Query в TypingMind, чтобы использовать его с любой LLM, или добавьте его в другой агент, который умеет читать SKILL.md.

1

Установка в TypingMind

TypingMind устанавливает навык прямо из его папки на GitHub: читает SKILL.md, собирает файлы ресурсов и сохраняет результат локально.

  1. Откройте приложение и перейдите в раздел «Плагины → Навыки».
  2. Выберите «Установить из GitHub».
  3. Вставьте указанную ниже ссылку на папку навыка и подтвердите установку.
    https://github.com/GetStream/Agents/tree/main/.claude/skills/query
  4. Включите навык в каждом чате, где хотите его использовать.
Плагины → Навыки → Добавить навык → По ссылке GitHub, затем вставьте ссылку на папку и нажмите «Продолжить».
2

Установка в другом агенте

Любой агент с поддержкой формата Agent Skills может использовать этот навык — скопируйте папку в каталог навыков этого агента.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/GetStream/Agents.git /tmp/Agents
mkdir -p .claude/skills
cp -r /tmp/Agents/.claude/skills/query .claude/skills/query
После копирования перезапустите Claude Code, чтобы загрузить новый навык.

Использование в TypingMind

Включите навык Query в любом чате TypingMind, и дальше модель всё сделает сама. Его название и описание хранятся в системном промпте, а при появлении подходящего запроса модель сама загружает полные инструкции. Вам не нужно вызывать навык вручную, и до фактического использования он не расходует токены.

Модель сама загружает навык Query, как только появляется подходящий для него запрос.

Работает с любой моделью ИИ

Навыки ИИ — это обычные инструкции в Markdown, а не код для конкретного поставщика, поэтому навык Query не привязан к модели, для которой он был создан. Установите его один раз в TypingMind и используйте с GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama или локальной моделью, которую запускаете самостоятельно, — со своими ключами API.

  • Загружается только при необходимости

    Системный промпт содержит только название и описание. Инструкции загружаются при первом подходящем запросе, поэтому неиспользуемый навык не расходует токены.

  • Меняйте модели прямо в чате

    Навык состоит из инструкций, а не кода, поэтому смена модели не нарушает его работу: новая модель читает тот же файл SKILL.md.

Инструкции навыка

Это содержимое файла SKILL.md, которое загружает модель. Прочитайте его перед установкой: навык — это инструкции, которым будет следовать ваша модель.

Query

One filter language for every list, the one getstream.io uses for users, channels, messages and calls. A caller who has written one Stream query can write ours.

Paging is the pagination skill (.claude/skills/pagination/SKILL.md). Read it first: this skill decides which rows, that one decides where the page starts.

Shape

A resource that needs more than a couple of equality filters gets POST /v1/<resource>/query, operationId query<Resources>:

json
{
  "filter": {"state": "closed", "created_at": {"$gte": "2026-09-01T00:00:00Z"}},
  "sort": [{"field": "created_at", "direction": -1}],
  "limit": 25,
  "cursor": "…"
}

The answer is a page, {items, has_more, next_cursor}, as in pagination.

  • POST because a filter is a tree, and a tree in a query string is unreadable. It still reads and nothing changes.
  • A simple GET list with a couple of query parameters stays as it is. Add query<Resources> beside it when it outgrows them; don't add a tenth query parameter.
  • filter is optional. An empty filter is every row the caller may see.

Stream calls the field filter_conditions. We call it filter; the grammar is the same.

Filter grammar

A filter is a JSON object. Keys are field names or logical operators, and all keys at one level are ANDed.

OperatorMeaningExample
$eqequal; a bare value is shorthand{"state": "closed"}
$inequal to any of a list{"agent": {"$in": ["a", "b"]}}
$gt $gte $lt $lterange, on numbers and RFC3339 times{"created_at": {"$lt": "…"}}
$existsthe field is set or not{"ended_at": {"$exists": false}}
$containsarray holds the value; object holds every key and value{"custom": {"$contains": {"team": "x"}}}
$autocompleteprefix match on a name{"title": {"$autocomplete": "sup"}}
$qfull-text match{"title": {"$q": "billing refund"}}
$and $ora list of filters{"$or": [{"state": "running"}, {"agent": "x"}]}

custom.<key> is shorthand for $contains on the custom object: {"custom.team": "x"} is {"custom": {"$contains": {"team": "x"}}}.

Not supported, and a 400: $ne, $nin, $nor, $not, regexes. Negative filters walk every row that does not match instead of seeking to the ones that do. Rewrite them as a positive $in. Stream allows $ne only on id and booleans; we allow $ne only on booleans, where it is just $eq with the other value.

Rules

  • Each endpoint declares an allow-list: field → operators, and the column each field reads. Anything else is a 400 that names the field and the operator. Never pass a caller's field name into SQL; it is looked up in the allow-list and the column comes from there.
  • Only allow what an index serves. If (customer_id, agent, created_at, id) exists, agent gets $eq and $in; a field with no index gets nothing until it has one. Custom fields get $eq/$contains only, as containment (@>), which a jsonb_path_ops GIN index on the JSONB column answers. Never $exists on a custom key: key-exists (?, ?|, ?&) needs the default jsonb_ops index, which is several times larger.
  • $and/$or nest one level deep at most, and $in takes at most 100 values. Deeper trees are a 400; they are how a list becomes a table scan.
  • Scope is not a filter. The handler ANDs the customer, and for end users the user, onto whatever arrived, as SessionFilter.UserID does. A caller cannot widen it by writing $or.
  • Values are typed by the field: a time must parse as RFC3339, a number as a number, an enum as one of its values. A wrong type is a 400, not an empty page.

Sort

sort is a list of {"field", "direction"}, direction 1 ascending or -1 descending, as Stream does it. Fields come from a sort allow-list, usually two or three indexed columns.

  • Omitted, the endpoint's default applies, e.g. created_at descending.
  • The server appends id in the direction of the last key, so the order is total.
  • The cursor holds every sort key and a fingerprint of the sort. A cursor sent with a different sort is a 400. See pagination for why the keys are in the cursor.
  • One index per allowed sort, behind the filters it is used with.

Paging

As in pagination: limit + cursor, never offset. Stream Chat's queries page by offset with a 1,000 row ceiling; Stream Video's queryCalls hands back a next pointer. We do what Video does.

  • filter and sort are resent with every page. The cursor is only a position.
  • The next page is the filter ANDed with (sort keys, id) < (cursor values), flipped to > for ascending keys.
  • Fetch limit + 1 for has_more. No counts.

Go

Put the grammar in one package and reuse it; an endpoint only supplies its allow-lists.

  • A short allow-list needs no parser. querySessions (internal/api/session_query.go) declares its filter as closed Huma structs, with one struct per operator (Equals, TextMatch), so the schema validates the request and documents it too. Combinations the schema cannot express, such as a text search with project_id, are refused in sessionQueryOf. The cursor carries the sort, so a cursor from one sort is refused by another. Start here, and move to a tree only when $and, $or or $in are needed.
  • Parse the body into a tree once, validating against the allow-list as you go. The handler gets a typed tree or an invalidRequest APIError.
  • Compile the tree to bun Where clauses with bound values. Field names never reach SQL as text.
  • Where a list merges rows held in memory with rows in Postgres, like live sessions in Manager.find, the same tree needs a Match(item) too, so both halves filter and sort alike.
  • Document the allowed fields, operators and sorts in the operation's description; that is what a caller reads.
  • Tests follow the go-testing skill: one per allowed operator, one for a rejected field and a rejected operator, one for a nested $or, and one that pages a filtered, sorted list to the end without repeating or skipping a row.

SDKs

Go first, as AGENTS.md says. The filter is a plain map in every SDK (map[string]any, a dict, an object), which is how Stream's SDKs take filter_conditions. Sort is a typed list. List methods follow the cursor the way Items.Unwind does.

Часто задаваемые вопросы

Что делает навык ИИ Query?

How list endpoints take filters and sorts, modelled on Stream's query syntax. Read before adding a filter, a sort, or a query endpoint.

Зачем использовать Query в TypingMind?

Потому что вы устанавливаете навык один раз и используете его с любой моделью. Query — это обычный текст в формате Markdown, а не код для конкретного поставщика, поэтому один и тот же навык работает с GPT-5, Claude, Gemini, Grok или локальной моделью. Вы можете менять модель прямо во время чата, и навык продолжит работать. TypingMind использует ваши собственные ключи API, поэтому вы платите поставщикам напрямую, а не оформляете подписку с оплатой за каждое место. Ваши навыки и чаты остаются в вашем собственном хранилище.

Как установить Query в TypingMind?

В TypingMind откройте «Плагины → Навыки → Установить из GitHub» и вставьте https://github.com/GetStream/Agents/tree/main/.claude/skills/query. TypingMind прочитает файл SKILL.md и установит навык, который можно включать отдельно для каждого чата.

Какие модели ИИ могут использовать Query?

Любая модель, которую вы подключите в TypingMind. Навыки ИИ — это обычные инструкции в формате Markdown, а не код для конкретного поставщика, поэтому GPT, Claude, Gemini, Grok и локальные модели могут загружать этот навык, когда запрос ему соответствует.

Со сколькими моделями ИИ можно использовать Query?

С любым количеством. В TypingMind вы можете использовать Query с любой моделью, которая поддерживает навыки, в том числе с GPT, Claude, Gemini, Grok, DeepSeek, Mistral и Llama. Для этого вы используете собственные ключи API.

Бесплатен ли навык ИИ Query?

Да. Навык опубликован на GitHub по лицензии Apache-2.0. Издатель — GetStream. Вы платите только своему поставщику ИИ за использованные токены.

Что такое навыки ИИ?

Навык ИИ — это набор инструкций, которыми модель ИИ может пользоваться каждый раз, когда ей нужно выполнить конкретную задачу. Он соответствует открытому формату Agent Skills: файл SKILL.md с названием и описанием, а также любые скрипты, шаблоны или справочные файлы, которые могут понадобиться модели. Модель читает инструкции, только когда ваш запрос соответствует навыку, поэтому установленный навык ничего не стоит, пока не используется.

Чем навыки ИИ отличаются от плагинов и серверов MCP?

Плагин или сервер MCP даёт модели новые инструменты, которые она может вызывать: при вызове где-то выполняется код и возвращает результат. Навык ИИ, напротив, даёт модели знания и описывает порядок действий: как подойти к задаче, какие шаги выполнить и каким должен быть хороший результат. Навыки — это обычный текст в формате Markdown, поэтому им не нужны сервер, ключ API или среда выполнения, и они работают с любой моделью.

Все

Создайте своё рабочее пространство с ИИ прямо сейчас

Подпишитесь на нашу рассылку, чтобы узнавать о новых функциях и предстоящих розыгрышах 👇