Anthropic ChatCompletion

Anthropic ChatCompletion

Certified

Send chat messages with Claude

Calls the Anthropic Messages API with rendered inputs, optional system prompt, and sampling controls; defaults to maxTokens 1024 while emitting token usage counters. Refer to the Anthropic Console Settings to create an API key and the Anthropic API documentation for more information.

yaml
type: io.kestra.plugin.anthropic.ChatCompletion

Chat completion using Claude.

yaml
id: anthropic_chat_completion
namespace: company.team

tasks:
  - id: chat_completion
    type: io.kestra.plugin.anthropic.ChatCompletion
    apiKey: "{{ secret('ANTHROPIC_API_KEY') }}"
    model: "claude-sonnet-4-6"
    maxTokens: 1024
    messages:
      - type: USER
        content: "What is the capital of Japan? Answer with a unique word and without any punctuation."

Code generation using Claude

yaml
id: anthropic_code_generation
namespace: company.team

tasks:
  - id: code_generation
    type: io.kestra.plugin.anthropic.ChatCompletion
    apiKey: "{{ secret('ANTHROPIC_API_KEY') }}"
    model: "claude-sonnet-4-6"
    maxTokens: 1500
    temperature: 0.3
    messages:
      - type: USER
        content: |
          Write a Python function that:
          1. Takes a list of numbers as input
          2. Filters out negative numbers
          3. Calculates the average of remaining positive numbers
          4. Returns the result rounded to 2 decimal places
          5. Include error handling for empty lists
          Also provide 3 test cases with expected outputs.

Conversation with follow-up context

yaml
id: anthropic_context_conversation
namespace: company.team

tasks:
  - id: code_generation
    type: io.kestra.plugin.anthropic.ChatCompletion
    apiKey: "{{ secret('ANTHROPIC_API_KEY') }}"
    model: "claude-sonnet-4-6"
    maxTokens: 800
    temperature: 0.5
    messages:
      - type: USER
        content: "Explain quantum computing in simple terms."
      - type: ASSISTANT
        content: "Quantum computing uses quantum mechanical phenomena like superposition and entanglement to process information differently than classical computers. Instead of bits that are either 0 or 1, quantum computers use quantum bits (qubits) that can exist in multiple states simultaneously."
      - type: USER
        content: "That is helpful! Can you give me a practical example of how this could be used in everyday life in the next 10 years?"

Chat completion with prompt caching

yaml
id: anthropic_cached_chat
namespace: company.team

tasks:
  - id: cached_chat
    type: io.kestra.plugin.anthropic.ChatCompletion
    apiKey: "{{ secret('ANTHROPIC_API_KEY') }}"
    model: "claude-sonnet-4-6"
    maxTokens: 1024
    promptCaching: true
    system: "You are a helpful assistant with extensive knowledge about Kestra, the open-source orchestration platform."
    messages:
      - type: USER
        content: "What are the key features of Kestra?"

Tool-assisted structured extraction

yaml
id: anthropic_structured_output
namespace: company.team

tasks:
  - id: extract_data
    type: io.kestra.plugin.anthropic.ChatCompletion
    apiKey: "{{ secret('ANTHROPIC_API_KEY') }}"
    model: "claude-sonnet-4-6"
    maxTokens: 1024
    messages:
      - type: USER
        content: |
          Extract the following information from this text:
          "John Doe is 30 years old and works as a Software Engineer in San Francisco."
    tools:
      - name: extract_person_info
        description: "Extract structured information about a person"
        inputSchema:
          type: object
          properties:
            name:
              type: string
              description: "The person's full name"
            age:
              type: integer
              description: "The person's age"
            occupation:
              type: string
              description: "The person's job title"
            location:
              type: string
              description: "The person's location"
          required:
            - name
            - age

Chat completion with Anthropic web search

yaml
id: anthropic_web_search
namespace: company.team

tasks:
  - id: search
    type: io.kestra.plugin.anthropic.ChatCompletion
    apiKey: "{{ secret('ANTHROPIC_API_KEY') }}"
    model: "claude-sonnet-4-6"
    maxTokens: 2048
    messages:
      - type: USER
        content: "Summarize recent news about open-source orchestration tools."
    tools:
      - type: WEB_SEARCH
        maxUses: 3

Stream a response with extended thinking and cost attribution

yaml
id: anthropic_thinking_stream
namespace: company.team

tasks:
  - id: reason
    type: io.kestra.plugin.anthropic.ChatCompletion
    apiKey: "{{ secret('ANTHROPIC_API_KEY') }}"
    model: claude-sonnet-4-6
    maxTokens: 4096
    thinking: true
    budgetTokens: 1024
    stream: true
    stopSequences: ["END"]
    metadata:
      userId: workflow-analysis
    serviceTier: STANDARD_ONLY
    connectTimeout: PT30S
    readTimeout: PT5M
    maxRetries: 2
    messages:
      - type: USER
        content: "Explain why the sum of two odd integers is even."

Analyze images and PDFs with citations and explicit cache breakpoints

yaml
id: anthropic_multimodal
namespace: company.team

tasks:
  - id: analyze
    type: io.kestra.plugin.anthropic.ChatCompletion
    apiKey: "{{ secret('ANTHROPIC_API_KEY') }}"
    model: claude-sonnet-4-6
    maxTokens: 2048
    systemPromptBlocks:
      - text: "Analyze the supplied sources and cite evidence."
        cacheControl: EPHEMERAL
    messages:
      - type: USER
        cacheControl: EPHEMERAL
        content:
          - type: TEXT
            text: "Compare the image with the report."
          - type: IMAGE
            source:
              type: URL
              url: https://upload.wikimedia.org/wikipedia/commons/a/a9/Example.jpg
          - type: DOCUMENT
            source:
              type: URL
              url: https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf
            title: Report
            citations:
              enabled: true

Use uploaded files and base64 content with beta API features

yaml
id: anthropic_file_content
namespace: company.team

inputs:
  - id: image_base64
    type: STRING
  - id: pdf_base64
    type: STRING
  - id: image_file_id
    type: STRING
  - id: pdf_file_id
    type: STRING

tasks:
  - id: analyze
    type: io.kestra.plugin.anthropic.ChatCompletion
    apiKey: "{{ secret('ANTHROPIC_API_KEY') }}"
    model: claude-sonnet-4-6
    betas: [files-api-2025-04-14]
    messages:
      - type: USER
        content:
          - type: TEXT
            text: "Summarize these sources. File IDs come from UploadFile."
          - type: IMAGE
            source:
              type: BASE64
              mediaType: image/png
              data: "{{ inputs.image_base64 }}"
          - type: DOCUMENT
            source:
              type: BASE64
              mediaType: application/pdf
              data: "{{ inputs.pdf_base64 }}"
          - type: IMAGE
            source:
              type: FILE
              fileId: "{{ inputs.image_file_id }}"
          - type: DOCUMENT
            source:
              type: FILE
              fileId: "{{ inputs.pdf_file_id }}"

Select a tool, cache its definition and tune the client

yaml
id: anthropic_tool_choice
namespace: company.team

tasks:
  - id: extract
    type: io.kestra.plugin.anthropic.ChatCompletion
    apiKey: "{{ secret('ANTHROPIC_API_KEY') }}"
    baseUrl: https://api.anthropic.com
    model: claude-sonnet-4-6
    toolChoice: TOOL
    toolChoiceName: extract_name
    tools:
      - name: extract_name
        description: Extract a person's name
        cacheControl: EPHEMERAL
        inputSchema:
          type: object
          properties:
            name:
              type: string
          required: [name]
    messages:
      - type: USER
        content: "My name is Ada."
Installation

Our standard Docker images already include this plugin. If you use a -slim image or another setup, install it with the following command:

kestractl plugins get io.kestra.plugin:plugin-anthropic --compatible-for $KESTRA_VERSION

For kestractl, use your Kestra version with --compatible-for, or specify an exact plugin version.

For Kestra CLI, replace LATEST with a specific version or version range to pin the plugin version.

Properties

Anthropic API Key

Messages

Ordered chat turns. Include at least one USER message. Content accepts a string or a list of TEXT, IMAGE, and DOCUMENT blocks. Image/PDF sources support URL, BASE64, and FILE (fileId), and FILE sources require the Files API beta in betas.

Definitions
cacheControlstring

Cache control

Optional ephemeral breakpoint applied to the final block of this message.

contentstringarray

Message content

Plain text or a list of ContentBlock objects.

typestring
Possible Values
ASSISTANTUSER

Message role

Model

Claude model name to invoke (e.g., claude-sonnet-4-6); must match an Anthropic model available to your API key.

Assets this task consumes as inputs or produces as outputs, for lineage tracking and the asset graph (Enterprise Edition). A flow declaring this property on a task is rejected in the open-source edition.

Definitions
assetFailureBehaviorstring
Possible Values
IGNOREFAILWARN

Asset failure behavior

Behavior applied to the task state when a declared asset fails to render, emit, or be persisted (e.g. a lock conflict): FAIL escalates it to FAILED, WARN (default) warns it if it would otherwise succeed, IGNORE leaves the state untouched.

enableAutobooleanstring

Whether to auto-register assets referenced dynamically at runtime that are not statically declared in inputs or outputs.

inputsarray

The assets consumed as inputs.

id*string
Min length1
typestring
outputs

The assets produced as outputs.

id*string
Min length1
Max length150
type*object
descriptionstring
displayNamestring
metadataobject
Default{}
namespacestring
Min length1
Max length150
id*string
Min length1
Max length150
type*object
descriptionstring
displayNamestring
metadataobject
Default{}
namespacestring
Min length1
Max length150
id*string
Min length1
Max length150
type*object
descriptionstring
displayNamestring
metadataobject
Default{}
namespacestring
Min length1
Max length150
id*string
Min length1
Max length150
type*object
descriptionstring
displayNamestring
metadataobject
Default{}
namespacestring
Min length1
Max length150
id*string
Min length1
Max length150
type*object
descriptionstring
displayNamestring
metadataobject
Default{}
namespacestring
Min length1
Max length150
id*string
Min length1
Max length150
type*string
Min length1

Custom asset type

descriptionstring
displayNamestring
metadataobject
Default{}
namespacestring
Min length1
Max length150

Base URL

Optional Anthropic-compatible endpoint. Defaults to the SDK endpoint. Requests, including the API key, are sent to this host, so set it with forced: true in plugin defaults when the API key comes from there.

SubTypestring

Beta features

Optional Anthropic beta identifiers sent in the anthropic-beta header, for example files-api-2025-04-14 for file_id sources.

Thinking token budget

Required when thinking is enabled. At least 1024 and strictly less than maxTokens.

Connect timeout

Connection timeout as an ISO-8601 duration. Defaults to PT1M, and zero disables it.

Default2

Maximum retries

SDK retries for transient errors, between 0 and 10. Defaults to 2, and 0 disables them.

Default1024

Max Tokens

Maximum tokens Anthropic can generate; defaults to 1024 if unset.

Metadata

Optional attribution metadata containing userId. Do not include personal information.

Definitions
userIdstring

User ID

Opaque attribution identifier. Do not include personal information.

Defaultfalse

Prompt caching

Enable prompt caching to reduce costs and latency for repetitive prompts. When enabled, the API automatically caches the longest cacheable prefix of the request. Cached tokens are billed at a reduced rate. See the Anthropic prompt caching documentation for details.

Read timeout

Maximum time for a response as an ISO-8601 duration, both between packets and for the whole call. Defaults to the SDK timeout (PT10M), and zero disables it.

Possible Values
AUTOSTANDARD_ONLY

Service tier

AUTO (Anthropic chooses the tier) or STANDARD_ONLY (standard capacity only). Unset uses the API default.

SubTypestring

Stop sequences

Optional strings that stop generation. The matched string is returned in stopSequence.

Defaultfalse

Stream response

Log complete text lines as they arrive, flush the final partial line, and return the complete response and usage at the end. Defaults to false.

System prompt

Optional system instructions applied to the whole conversation. Use systemPromptBlocks instead for per-block cache control.

System prompt blocks

Optional system blocks with text and cacheControl: EPHEMERAL. Mutually exclusive with system.

Definitions
cacheControlstring

Cache control

Optional ephemeral cache breakpoint on this system block.

textstring

System instructions

Temperature

Sampling randomness; range 0.0-1.0. Unset by default and only sent to Anthropic when explicitly provided. Lower for deterministic replies.

Defaultfalse

Extended thinking

Enable Claude's extended thinking. Requires budgetTokens and sets temperature to 1, warning when a different temperature is provided. Defaults to false.

Possible Values
AUTOANYTOOLNONE

Tool choice

AUTO lets Claude decide, ANY requires a tool, TOOL requires toolChoiceName and NONE disables tools. Forced tool use is incompatible with thinking. Unset uses the API default (AUTO when tools are provided).

Tool choice name

Name of the tool to call when toolChoice is TOOL.

Tools

Tools Claude can use. Each entry is either a user-defined tool (name, optional description, inputSchema JSON Schema) or an Anthropic built-in tool selected with type (currently WEB_SEARCH, with optional maxUses, allowedDomains and blockedDomains). With built-in tools, Anthropic can end a long-running turn with stopReason pause_turn; the task does not resume it, so outputText may then be partial.

Definitions
cacheControlstring

Cache control

Optional ephemeral cache breakpoint on this tool.

descriptionstring

Tool description

Optional description of what the tool does.

inputSchemaobject

Input schema

JSON Schema object defining the expected parameters for the tool.

namestring

Tool name

Unique identifier for the tool (1-128 characters).

allowedDomainsarray
SubTypestring

Allowed domains

Only return results from these domains. Cannot be combined with blockedDomains.

blockedDomainsarray
SubTypestring

Blocked domains

Never return results from these domains. Cannot be combined with allowedDomains.

maxUsesinteger

Max uses

Maximum searches per request (WEB_SEARCH only).

typestring

Tool type

The Anthropic-provided tool to enable.

Top K

Samples only from the top K tokens for each step; leave unset to let the model choose.

Top P

Nucleus sampling cap; 0.1 keeps only tokens in top 10% probability mass.

Cache creation input tokens

Number of tokens written to the cache.

Cache read input tokens

Number of tokens read from the cache.

Citations

Source references attached to response text blocks, in response order.

Definitions
citedTextstring

Cited text

documentIndexinteger

Document index

documentTitlestring

Document title

endBlockIndexinteger

End block index

endCharIndexinteger

End character index

endPageNumberinteger

End page number

fileIdstring

File ID

startBlockIndexinteger

Start block index

startCharIndexinteger

Start character index

startPageNumberinteger

Start page number

titlestring

Source title

typestring

Citation type

urlstring

Source URL

Assistant text extracted from the response

The full response from Claude

Stop reason

The reason the model stopped generating (e.g., end_turn, tool_use, max_tokens).

Stop sequence

The stop string matched by the model, if any.

Thinking

Extended thinking text, when returned by Claude. Redacted thinking is available only in rawResponse.

Tool uses

List of tools that Claude requested to use, if any.

Definitions
idstring

Tool use ID

Unique identifier for this tool use.

inputobject

Tool input

Parameters passed to the tool as a map.

namestring

Tool name

Name of the tool being called.

Unittoken

Number of tokens written to the prompt cache.

Unittoken

Number of tokens read from the prompt cache.

Unittoken

Number of input tokens processed by the model.

Unittoken

Number of output tokens generated by the model.