К основному содержанию
скилл CX Codex

llm-context — скилл для Claude Code: что делает и как установить

Извлекает готовый контекст веб-страниц через API Brave Search для заземления ответов ИИ. Пригодится при настройке RAG и автономных агентов.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add brave/brave-search-skills --skill llm-context -a claude-code
Открыть на GitHub

Что делает llm-context

Скилл обращается к конечной точке /res/v1/llm/context поисковой системы Brave. Вместо стандартного списка ссылок и коротких сниппетов запрос возвращает текстовые блоки, таблицы и фрагменты исходного кода со страниц, отсортированные по релевантности.

Для отправки запросов обязателен токен X-Subscription-Token из тарифа Search на платформе Brave Search API. В параметрах настраиваются объём токенов от 1024 до 32768 через maximum_number_of_tokens, число ссылок, фильтрация через Goggles и координаты заголовками X-Loc-Lat и X-Loc-Long.

Без ключа поиска сервис работать не будет, поэтому запускать скилл вслепую бессмысленно. В отличие от генеративного эндпоинта answers, здесь модель выполняет всего один поисковый запрос за вызов и не делает многошаговых рассуждений сама.

Какие задачи решает

  • получить очищенный текст и таблицы с сайтов для RAG без парсинга страниц
  • ограничить объём контекста веб-поиска точным числом токенов от 1024 до 32768
  • переранжировать выдачу под доверенные домены с помощью правил Goggles
  • добавить локальную привязку выдачи по координатам широты и долготы

Примеры запросов агенту

  • Найди через llm-context документацию по rust-lang.org с лимитом контекста 4096 токенов
  • Сделай запрос к Brave LLM Context по теме сравнения фреймворков и оставь таблицы
  • Запроси контекст из веба по запросу 'высочайшие горы' с параметром freshness pd

Как установить llm-context

1Через Skills CLI (Vercel)

npx skills add brave/brave-search-skills --skill llm-context -a claude-code

2Вручную: положить файлы

~/.claude/skills/llm-context/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/llm-context/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о llm-context

Как установить llm-context в Claude Code?

Выполните в терминале команду npx skills add brave/brave-search-skills --skill llm-context -a claude-code. Также можно поместить файл навыка по пути ~/.claude/skills/llm-context/SKILL.md.

Чем llm-context отличается от эндпоинта answers?

Он отдаёт сырые извлечённые фрагменты сайтов вашей собственной модели меньше чем за секунду. Эндпоинт answers сам формулирует готовый ответ со ссылками через многошаговый поиск.

Что нужно для работы скилла?

Потребуется токен Brave Search API с активным планом Search. Ключ передаётся в заголовке X-Subscription-Token при каждом обращении к API.

Исходный текст

SKILL.md · MIT
---
name: llm-context
description: USE FOR RAG/LLM grounding. Returns pre-extracted web content (text, tables, code) optimized for LLMs. GET + POST. Adjust max_tokens/count based on complexity. Supports Goggles, local/POI. For AI answers use answers. Recommended for anyone building AI/agentic applications.
---

# LLM Context

> **Requires API Key**: Get one at https://api.search.brave.com
>
> **Plan**: Included in the **Search** plan. See https://api-dashboard.search.brave.com/app/subscriptions/subscribe

Brave LLM Context API delivers pre-extracted, relevance-ranked web content optimized for grounding LLM responses in real-time search results. Unlike traditional web search APIs that return links and snippets, LLM Context extracts the actual page content—text chunks, tables, code blocks, and structured data—so your LLM or AI agent can reason over it directly.

## LLM Context vs AI Grounding

| Feature | LLM Context (this) | AI Grounding (`answers`) |
|--|--|--|
| Output | Raw extracted content for YOUR LLM | End-to-end AI answers with citations |
| Interface | REST API (GET/POST) | OpenAI-compatible `/chat/completions` |
| Searches | Single search per request | Multi-search (iterative research) |
| Speed | Fast (<1s) | Slower |
| Plan | Search | Answers |
| Endpoint | `/res/v1/llm/context` | `/res/v1/chat/completions` |
| Best for | AI agents, RAG pipelines, tool calls | Chat interfaces, research mode |

## Endpoint

```http
GET  https://api.search.brave.com/res/v1/llm/context
POST https://api.search.brave.com/res/v1/llm/context
```

**Authentication**: `X-Subscription-Token: <API_KEY>` header

**Optional Headers**:
- `Accept-Encoding: gzip` — Enable gzip compression

## Quick Start

### GET Request
```bash
curl -s "https://api.search.brave.com/res/v1/llm/context?q=tallest+mountains+in+the+world" \
  -H "Accept: application/json" \
  -H "X-Subscription-Token: ${BRAVE_SEARCH_API_KEY}"
```

### POST Request (JSON body)
```bash
curl -s --compressed -X POST "https://api.search.brave.com/res/v1/llm/context" \
  -H "Accept: application/json" \
  -H "Accept-Encoding: gzip" \
  -H "X-Subscription-Token: ${BRAVE_SEARCH_API_KEY}" \
  -H "Content-Type: application/json" \
  -d '{"q": "tallest mountains in the world"}'
```

### With Goggles (Inline)
```bash
curl -s "https://api.search.brave.com/res/v1/llm/context" \
  -H "Accept: application/json" \
  -H "X-Subscription-Token: ${BRAVE_SEARCH_API_KEY}" \
  -G \
  --data-urlencode "q=rust programming" \
  --data-urlencode 'goggles=$discard
$site=docs.rs
$site=rust-lang.org'
```

## Parameters

### Query Parameters

| Parameter | Type | Required | Default | Description |
|--|--|--|--|--|
| `q` | string | **Yes** | - | Search query (1-400 chars, max 50 words) |
| `country` | string | No | `US` | Search country (2-letter country code or `ALL`) |
| `search_lang` | string | No | `en` | Language preference (2+ char language code) |
| `count` | int | No | `20` | Max search results to consider (1-50) |
| `spellcheck` | bool | No | `true` | Whether to spellcheck the query before searching |
| `freshness` | string | No | `""` | Filters search results by page age. The age of a page is determined by the most relevant date reported by the content, such as its published or last modified date. Supported values: `pd` (24h or less), `pw` (7 days or less), `pm` (31 days or less), `py` (365 days or less), or a custom date range `YYYY-MM-DDtoYYYY-MM-DD` (e.g. `2022-04-01to2022-07-30`). |

### Context Size Parameters

| Parameter | Type | Required | Default | Description |
|--|--|--|--|--|
| `maximum_number_of_urls` | int | No | `20` | Max URLs in response (1-50) |
| `maximum_number_of_tokens` | int | No | `8192` | Approximate max tokens in context (1024-32768) |
| `maximum_number_of_snippets` | int | No | `50` | Max snippets across all URLs (1-256) |
| `maximum_number_of_tokens_per_url` | int | No | `4096` | Max tokens per individual URL (512-8192) |
| `maximum_number_of_snippets_per_url` | int | No | `50` | Max snippets per individual URL (1-100) |


### Filtering & Local Parameters

| Parameter | Type | Required | Default | Description |
|--|--|--|--|--|
| `context_threshold_mode` | string | No | `null` | Relevance threshold for including content (`strict`/`balanced`/`lenient`/`disabled`) |
| `safesearch` | string | No | `null` | Adult content filter (`off`/`moderate`/`strict`); not set means no filtering, except local recall which stays `strict` |
| `enable_local` | bool | No | `null` | Local recall control (`true`/`false`/`null`, see below) |
| `goggles` | string/list | No | `null` | Goggle URL or inline definition for custom re-ranking |
| `enable_source_metadata` | bool | No | `false` | Adds `site_name`, `favicon`, `thumbnail` and `description` to each `sources[url]` entry |

## Context Size Guidelines

| Task Type | count | max_tokens | Example |
|--|--|--|--|
| Simple factual | 5 | 2048 | "What year was Python created?" |
| Standard queries | 20 | 8192 | "Best practices for React hooks" |
| Complex research | 50 | 16384 | "Compare AI frameworks for production" |

Larger context windows provide more information but increase latency and cost (of your inference). Start with defaults and adjust.

## Threshold Modes

| Mode | Behavior |
|--|--|
| `null` (not set) | **Default** — resolves to `lenient` on the current API version |
| `strict` | Higher threshold — fewer but more relevant results |
| `balanced` | Good balance between coverage and relevance |
| `lenient` | Lower threshold — more results, may include less relevant content |
| `disabled` | No threshold filtering — return all extracted content |

## Local Recall

The `enable_local` parameter controls location-aware recall:

| Value | Behavior |
|--|--|
| `null` (not set) | **Auto-detect** — local recall enabled when any location header is provided |
| `true` | **Force local** — always use local recall, even without location headers |
| `false` | **Force standard** — always use standard web ranking, even with location headers |

For most use cases, omit `enable_local` and let the API auto-detect from location headers.

## Location Headers

| Header | Type | Description |
|--|--|--|
| `X-Loc-Lat` | float | Latitude (-90.0 to 90.0) |
| `X-Loc-Long` | float | Longitude (-180.0 to 180.0) |
| `X-Loc-City` | string | City name |
| `X-Loc-State` | string | State/region code (ISO 3166-2) |
| `X-Loc-State-Name` | string | State/region name |
| `X-Loc-Country` | string | 2-letter country code |
| `X-Loc-Postal-Code` | string | Postal code |

> **Priority**: `X-Loc-Lat` + `X-Loc-Long` take precedence. When provided, text-based headers (City, State, Country, Postal-Code) are not used for location resolution. Provide text-based headers **only** when you don't have coordinates.

### Example: With Coordinates
```bash
curl -s "https://api.search.brave.com/res/v1/llm/context" \
  -H "Accept: application/json" \
  -H "X-Subscription-Token: ${BRAVE_SEARCH_API_KEY}" \
  -H "X-Loc-Lat: 37.7749" \
  -H "X-Loc-Long: -122.4194" \
  -G \
  --data-urlencode "q=best coffee shops near me"
```

### Example: With Place Name
```bash
curl -s "https://api.search.brave.com/res/v1/llm/context" \
  -H "Accept: application/json" \
  -H "X-Subscription-Token: ${BRAVE_SEARCH_API_KEY}" \
  -H "X-Loc-City: San Francisco" \
  -H "X-Loc-State: CA" \
  -H "X-Loc-Country: US" \
  -G \
  --data-urlencode "q=best coffee shops near me"
```

## Goggles (Custom Ranking) — Unique to Brave

Goggles let you **control which sources ground your LLM** — essential for RAG quality.

| Use Case | Goggle Rules |
|--|--|
| Official docs only | `$discard\n$site=docs.python.org` |
| Exclude user content | `$discard,site=reddit.com\n$discard,site=stackoverflow.com` |
| Academic sources | `$discard\n$site=arxiv.org\n$site=scholar.google.com` |
| No paywalls | `$discard,site=medium.com` |

| Method | Example |
|--|--|
| **Hosted** | `--data-urlencode "goggles=https://raw.githubusercontent.com/brave/goggles-quickstart/main/goggles/1k_short.goggle"` |
| **Inline** | `--data-urlencode 'goggles=$discard\n$site=example.com'` |

> **Hosted** goggles must be on GitHub/GitLab, include `! name:`, `! description:`, `! author:` headers, and be registered at https://search.brave.com/goggles/create. **Inline** rules need no registration.

**Syntax**: Rules start with `$` + comma-separated options. **Actions** (pick one): `discard`, `boost[=N]`, `downrank[=N]` — N is an integer 1–10. **Site filter**: `site=DOMAIN`. Example: `$site=example.com,boost=3`. Separate rules with `\n` (`%0A`).

**Allow list**: `$discard\n$site=docs.python.org\n$site=developer.mozilla.org` — **Block list**: `$discard,site=pinterest.com\n$discard,site=quora.com`

**Resources**: [Discover](https://search.brave.com/goggles/discover) · [Syntax](https://search.brave.com/help/goggles) · [Quickstart](https://github.com/brave/goggles-quickstart)

## Response Format

### Standard Response

```json
{
  "grounding": {
    "generic": [
      {
        "url": "https://example.com/page",
        "title": "Page Title",
        "snippets": [
          "Relevant text chunk extracted from the page...",
          "Another relevant passage from the same page..."
        ]
      }
    ],
    "map": []
  },
  "sources": {
    "https://example.com/page": {
      "title": "Page Title",
      "hostname": "example.com",
      "age": ["Wednesday, January 15, 2025", "2025-01-15", "392 days ago", "2025-01-15T13:45:02Z"]
    }
  }
}
```

### Local Response (with `enable_local`)

```json
{
  "grounding": {
    "generic": [...],
    "poi": {
      "name": "Business Name",
      "url": "https://business.com",
      "title": "Title of business.com website",
      "snippets": ["Business details and information..."]
    },
    "map": [
      {
        "name": "Place Name",
        "url": "https://place.com",
        "title": "Title of place.com website",
        "snippets": ["Place information and details..."]
      }
    ]
  },
  "sources": {
    "https://business.com": {
      "title": "Business Name",
      "hostname": "business.com",
      "age": []
    }
  }
}
```

### Response Fields

| Field | Type | Description |
|--|--|--|
| `grounding` | object | Container for all grounding content by type |
| `grounding.generic` | array | Array of URL objects with extracted content (main grounding data) |
| `grounding.generic[].url` | string | Source URL |
| `grounding.generic[].title` | string | Page title |
| `grounding.generic[].snippets` | array | Extracted smart chunks relevant to the query |
| `grounding.poi` | object/null | Point of interest data (only with local recall) |
| `grounding.poi.name` | string/null | Point of interest name |
| `grounding.poi.url` | string/null | POI source URL |
| `grounding.poi.title` | string/null | POI page title |
| `grounding.poi.snippets` | array/null | POI text snippets |
| `grounding.map` | array | Map/place results (only with local recall) |
| `grounding.map[].name` | string/null | Place name |
| `grounding.map[].url` | string/null | Place source URL |
| `grounding.map[].title` | string/null | Place page title |
| `grounding.map[].snippets` | array/null | Place text snippets |
| `sources` | object | Metadata for all referenced URLs, keyed by URL |
| `sources[url].title` | string | Page title |
| `sources[url].hostname` | string | Source hostname |
| `sources[url].age` | array | The page's date in four fixed positions: full date, `YYYY-MM-DD`, relative age, ISO 8601 timestamp. Empty when the page has no known date |
| `sources[url].description` | string | The page's own description, independent of the query. Requires `enable_source_metadata` |
| `sources[url].site_name` | string | Site name. Requires `enable_source_metadata` |
| `sources[url].favicon` | string | Favicon URL. Requires `enable_source_metadata` |
| `sources[url].thumbnail` | object/null | Page thumbnail (`src`, `original`). Requires `enable_source_metadata` |
| `sources[url].snippet` | string? | Best snippet for the page |

**Note**: Snippets may contain plain text OR JSON-serialized structured data (tables, schemas, code blocks). LLMs handle this mixed format well.

## Use Cases

- **AI Agents**: Give your agent a web search tool that returns ready-to-use content in a single call
- **RAG Pipelines**: Ground LLM responses in fresh, relevant web content
- **AI Assistants & Chatbots**: Provide factual answers backed by real sources
- **Question Answering**: Retrieve focused context for specific queries
- **Fact Checking**: Verify claims against current web content
- **Content Research**: Gather source material on any topic with one API call

## Best Practices

- **Token budget**: Start with defaults (`maximum_number_of_tokens=8192`, `count=20`). Reduce for simple lookups, increase for complex research.
- **Source quality**: Use Goggles to restrict to trusted sources. Set `context_threshold_mode=strict` when precision > recall.
- **Performance**: Use smallest `count` and `maximum_number_of_tokens` that meet your needs. For local queries, provide location headers.

© brave · MIT · brave/brave-search-skills

Похожие скиллы

Все скиллы по теме «Настройка агента: память, контекст, субагенты» →
prompt-engineering NeoLabHQ Скилл содержит паттерны составления промптов для агентов, сабагентов и LLM. Пригодится при сборке промпт-шаблонов, цепочек рассуждений и хуков. CX Codex +1 1 400установок llm-application-dev MoizIbnYousaf Скилл для разработки приложений на больших языковых моделях: промпты, RAG-конвейер, вызовы API и обработка ошибок. CX Codex +1 462установок llm-architect VoltAgent Community Проектирует архитектуру LLM-систем для продакшена: от RAG и файнтюнинга до оптимизации инференса в vLLM. Пригодится при высоких нагрузках и оптимизации расходов на токены. 649установок context-engineering-collection muratcankoylan Набор техник для проектирования продакшн-агентов: управление контекстом, многоагентные системы, долгоживущие петли. Нужен, если вы строите автономные системы, которые должны работать надёжно. CX Codex +1 4 200установок context-compression sickn33 Скилл управляет сжатием контекста в длинных сессиях агента, когда разговор превышает лимит токенов. Вместо наивного удаления текста сохраняет структурированные резюме с файлами, решениями и состоянием. CX Codex +1 1 400установок omni-context-rtk cheaper-inference Настраивает RTK-фильтры, правила работы с контекстом и его передачу между этапами. Нужен для проверки сжатия на реальных запросах. CX Codex +1 984установок

Из того же набора7

images-search Скилл находит картинки через API поиска Brave с миниатюрами и прямыми ссылками. Пригодится агенту для подбора иллюстраций и фактчекинга визуала. CX Codex +1 1 700установок news-search Ищет свежие статьи через новостной индекс Brave с фильтрацией по датам и правилам Goggles. Помогает следить за событиями за последние 24 часа. CX Codex +1 1 600установок videos-search Ищет видео через Brave Search API с метаданными о длительности, просмотрах и авторах. Пригодится для мониторинга свежих роликов и сбора обучающих материалов. CX Codex +1 1 200установок suggest Скилл для автодополнения поисковых запросов через Brave Search API с исправлением опечаток и быстрым ответом до 100 мс. CX Codex +1 1 100установок local-pois Получает подробные сведения об организациях по их идентификаторам через Brave Search API. Помогает извлечь контакты, рейтинги и часы работы. CX Codex +1 1 100установок local-place-search Скилл ищет заведения, адреса и улицы через Brave Search API и отдаёт координаты, рейтинг, часы работы и телефон. CX Codex +1 395установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой