Logo de Chain Llm Pattern

Chain Llm Pattern

Comunidade
masteranime
chain-llm-pattern

Build multi-step LLM reasoning chains in n8n using Groq, OpenAI, or Claude for structured data extraction, categorization, scoring, and analysis. Use this skill whenever the user wants to chain multiple LLM calls together in an n8n workflow — phrases like "extract entities then categorize", "multi-step LLM prompt", "chain_llm", "LLM pipeline", "classify and score", "entity extraction then enrichment". Also use when processing call transcripts, customer messages, or any unstructured text through multiple analysis passes in n8n. Prefer this pattern over single-shot prompts whenever the output requires both extraction AND reasoning, since single-shot hallucinates categories while chains let each step verify the previous.

Visão geral

Publicado pormasteranime
Repositórion8n-claude-skills
Nome da habilidadechain-llm-pattern
Estrelas
34
Forks
8
Arquivos incluídos
1
LicençaMIT
Links
  • Instruções em Markdown

    Um arquivo SKILL.md que o modelo carrega sob demanda, consumindo tokens apenas quando uma solicitação é realmente relevante para a habilidade.

  • Funciona com qualquer LLM

    Habilidades de IA são Markdown simples, não código específico de um provedor, por isso funcionam com GPT, Claude, Gemini, Grok ou um modelo local.

  • 1 arquivos incluídos

    Scripts, modelos de documentos e referências que o modelo pode ler enquanto trabalha. Os arquivos são somente leitura e nunca são executados.

  • Código aberto

    Publicada por masteranime no GitHub. Leia o conteúdo-fonte antes de instalar.

Instalação

Instale a habilidade de IA Chain Llm Pattern no TypingMind para usá-la com qualquer LLM ou adicione-a a outro agente que leia SKILL.md.

1

Instalar no TypingMind

O TypingMind instala uma habilidade diretamente da pasta dela no GitHub — lê o arquivo SKILL.md, reúne os arquivos de recursos em um pacote e armazena o resultado localmente.

  1. Abra o app e vá para Plugins → Habilidades.
  2. Escolha "Instalar do GitHub".
  3. Cole a URL da pasta da habilidade exibida abaixo e confirme.
    https://github.com/masteranime/n8n-claude-skills/tree/main/skills/chain-llm-pattern
  4. Ative a habilidade em cada chat em que quiser disponibilizá-la.
Plugins → Habilidades → Nova habilidade → Via URL GitHub, depois cole a URL da pasta e pressione Continuar.
2

Instalar em outro agente

Qualquer agente que leia o formato Agent Skills pode usar esta habilidade — copie a pasta para o diretório de habilidades desse agente.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/masteranime/n8n-claude-skills.git /tmp/n8n-claude-skills
mkdir -p .claude/skills
cp -r /tmp/n8n-claude-skills/skills/chain-llm-pattern .claude/skills/chain-llm-pattern
Reinicie Claude Code após copiar para que a nova habilidade seja reconhecida.

Use no TypingMind

Ative Chain Llm Pattern em qualquer chat do TypingMind e o modelo cuida do resto. O nome e a descrição da habilidade ficam no prompt do sistema e, assim que uma solicitação relevante aparece, o modelo carrega as instruções completas automaticamente — sem precisar de acionamento manual e sem consumir tokens até que ela seja realmente usada.

O modelo carrega Chain Llm Pattern automaticamente assim que uma solicitação é relevante para essa habilidade.

Funciona com qualquer modelo de IA

Habilidades de IA são instruções em Markdown simples, não código específico de um provedor. Por isso, Chain Llm Pattern não fica vinculada ao modelo para o qual foi criada. Instale-a uma vez no TypingMind e use-a com GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama ou um modelo local executado por conta própria — tudo com suas próprias chaves de API.

  • Carregada apenas quando necessário

    O prompt do sistema contém apenas o nome e a descrição. As instruções são buscadas na primeira solicitação relevante, então uma habilidade sem uso não gera custo.

  • Troque de modelo durante a conversa

    Como a habilidade é composta de instruções, não de código, trocar de modelo não afeta seu funcionamento — o próximo modelo lê o mesmo arquivo SKILL.md.

Instruções da habilidade

Este é o conteúdo de SKILL.md que o modelo carrega. Leia antes de instalar — uma habilidade é um conjunto de instruções que seu modelo seguirá.

Chain LLM Pattern for n8n

Multi-step LLM chains outperform single-shot prompts on any task that combines extraction + reasoning. This skill encodes the production pattern.

When to use a chain vs a single prompt

Single prompt worksChain is better
"Summarize this email""Extract entities, then categorize by urgency, then decide routing"
"Translate this to English""Detect language, translate, then extract structured fields"
"Is this spam? yes/no""Score spam probability from email, phone, IP, content separately, then combine"

Rule of thumb: if the task has ≥2 distinct reasoning steps OR the final decision depends on intermediate structured data, use a chain.

The pattern (3-stage default)

Input → [Extract] → [Analyze/Classify] → [Score/Decide] → Output

Each stage is its own LLM node with its own prompt. Between stages, use Set or Code nodes to transform and validate.

Stage 1: Extract (schema-bound)

Use Information Extractor node (LangChain). NOT a generic AI Agent or raw HTTP call.

Why: Information Extractor binds output to a JSON schema. It parses, retries on invalid JSON, and fails loudly — instead of silently returning prose you then regex.

Define schema explicitly:

json
{
  "type": "object",
  "properties": {
    "customer_name": { "type": "string" },
    "product_mentioned": { "type": "string" },
    "sentiment": { "enum": ["positive", "neutral", "negative"] },
    "urgency_score": { "type": "number", "minimum": 0, "maximum": 10 }
  },
  "required": ["customer_name", "sentiment"]
}

System prompt for this stage: short, one job. "Extract the fields defined in the schema from the transcript. If a field is absent, omit it. Do not infer or guess."

Stage 2: Analyze (reason over extracted data)

Use Basic LLM Chain with the extracted JSON from Stage 1 as input.

This stage reasons: categorize, cluster, identify patterns, detect issues. The input is structured (from Stage 1) so the model isn't juggling parsing + reasoning simultaneously.

Example system prompt:

Given the extracted customer data below, classify into one of: [technical_issue, billing_question, cancellation_risk, upsell_opportunity]. Then identify the single most important next action. Return JSON with category and next_action.

Stage 3: Score / decide (deterministic where possible)

If the final step is arithmetic (e.g., composite scoring: 0.4 × email_score + 0.3 × phone_score + 0.3 × content_score), use a Code node, NOT an LLM.

LLMs are bad at arithmetic. They fail silently. Use Code (JavaScript) for any math involving weights, thresholds, or aggregation.

Model selection

StageRecommended modelWhy
ExtractGroq llama-3.3-70b-versatile or openai/gpt-4o-miniFast, cheap, good at schema adherence
AnalyzeClaude Sonnet 4 or GPT-4oReasoning quality matters more
Score (if LLM)gpt-4o-miniArithmetic weakness, keep cheap

Groq is the fastest provider for extract stages — 500+ tokens/sec. Use it unless you need Claude/OpenAI specifically.

Production rules

  1. Pin example data at each stage during development. Right-click node → "Pin Data". Without pinning, changing Stage 1 invalidates all downstream test data and you waste API calls.

  2. Budget tokens explicitly. Set maxTokens on every LLM node. Stage 1 extract rarely needs >500. Stage 2 analyze rarely >1000.

  3. Validate between stages. Insert a Code node between LLM stages that checks required fields exist. Fail fast with a clear error — don't let a missing field propagate and produce a confusing Stage 3 failure.

  4. Log stage outputs. Add a MySQL or Google Sheets insert after Stage 1 and Stage 2 that records the raw output (truncated to 1000 chars). You WILL need this for debugging.

  5. Temperature: 0 for extract, 0.2–0.4 for analyze, 0 for scoring. Extract must be deterministic. Analysis benefits from slight variance. Scoring must be deterministic.

Common multi-language variant (EN/ES/PT)

For transcripts in mixed languages, add a Stage 0:

Stage 0 (Groq): Detect language → route to language-specific prompts
Stage 1 (language-specific): Extract in source language
Stage 2: Translate structured output to English (cheap, short)
Stage 3: Analyze in English

Language-specific prompts extract better than a single multilingual prompt because entity names (cities, products) follow different patterns per language.

Anti-patterns

  • Don't use AI Agent for extraction. Agents are for tool use, not structured output. Use Information Extractor.
  • Don't concatenate all steps into one mega-prompt. Each hallucination compounds. Separate stages let you evaluate each independently.
  • Don't loop an LLM on retry without a counter. Infinite loops cost money. Cap retries at 3 via a counter in a Set node.

Reference

  • references/groq-chain-example.json — a working 4-node chain ready to import into n8n

Arquivos incluídos

O modelo lê esses arquivos sob demanda enquanto a habilidade está carregada. Eles são disponibilizados para leitura e nunca são executados.

Perguntas frequentes

O que a habilidade de IA Chain Llm Pattern faz?

Build multi-step LLM reasoning chains in n8n using Groq, OpenAI, or Claude for structured data extraction, categorization, scoring, and analysis. Use this skill whenever the user wants to chain multiple LLM calls together in an n8n workflow — phrases like "extract entities then categorize", "multi-step LLM prompt", "chain_llm", "LLM pipeline", "classify and score", "entity extraction then enrichment". Also use when processing call transcripts, customer messages, or any unstructured text through multiple analysis passes in n8n. Prefer this pattern over single-shot prompts whenever the output...

Por que usar Chain Llm Pattern no TypingMind?

Porque basta instalar uma vez para usar com qualquer modelo. Chain Llm Pattern é escrito em Markdown simples, e não em código específico de um provedor, então a mesma habilidade funciona com GPT-5, Claude, Gemini, Grok ou um modelo local — e é possível trocar de modelo no meio do chat sem que ela deixe de funcionar. O TypingMind usa suas próprias chaves de API, então o pagamento é feito diretamente aos provedores, em vez de uma assinatura por licença de usuário, e suas habilidades e chats permanecem no seu próprio armazenamento.

Como instalar Chain Llm Pattern no TypingMind?

Abra Plugins → Habilidades → Instalar do GitHub no TypingMind e cole https://github.com/masteranime/n8n-claude-skills/tree/main/skills/chain-llm-pattern. O TypingMind lê o arquivo SKILL.md, reúne os arquivos da habilidade e a instala para que possa ser ativada em cada chat.

Quais modelos de IA podem usar Chain Llm Pattern?

Qualquer modelo conectado no TypingMind. As habilidades de IA são instruções em Markdown simples, e não código específico de um provedor. Assim, GPT, Claude, Gemini, Grok e modelos locais podem carregar esta habilidade quando uma solicitação corresponder a ela.

Quantos modelos de IA posso usar com Chain Llm Pattern?

Quantos quiser. Desde que o modelo ofereça suporte a habilidades, é possível usar Chain Llm Pattern com ele — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama e outros — tudo no TypingMind com suas próprias chaves de API.

A habilidade de IA Chain Llm Pattern é gratuita?

Sim. A habilidade é publicada no GitHub por masteranime sob a licença MIT. O pagamento é feito apenas ao seu provedor de IA pelos tokens usados.

O que são habilidades de IA?

Uma habilidade de IA é um conjunto reutilizável de instruções que ensina um modelo de IA a realizar uma tarefa específica. Ela segue o formato aberto Agent Skills: um arquivo SKILL.md com nome e descrição, além de scripts, modelos de documento ou arquivos de referência de que o modelo possa precisar. O modelo lê as instruções apenas quando sua solicitação corresponde à habilidade, então uma habilidade instalada não gera custos até ser usada.

Qual é a diferença entre habilidades de IA e plugins ou servidores MCP?

Um plugin ou servidor MCP oferece ao modelo novas ferramentas para chamar — código que é executado em algum lugar e retorna um resultado. Já uma habilidade de IA fornece conhecimento e um processo ao modelo: como abordar uma tarefa, quais etapas seguir e como deve ser um bom resultado. As habilidades são escritas em Markdown simples, por isso não precisam de servidor, chave de API nem ambiente de execução, e funcionam com qualquer modelo.

Ver todos

Crie seu próprio espaço de IA agora

Inscreva-se na nossa newsletter para receber novidades sobre recursos e futuros sorteios 👇