> ## Documentation Index
> Fetch the complete documentation index at: https://docs.dumplingai.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Generate Agent Completion

> Generate a completion from a DumplingAI agent with streaming or sync support.

## Description

This endpoint processes messages for a specific agent, generating a response using one of your AI agents. It can optionally maintain conversation history through threads.

## Endpoint

```
POST https://app.dumplingai.com/api/v1/agents/generate-completion
```

## Headers

* **Content-Type:** `application/json`
* **Authorization:** Bearer `<API_KEY>` (required)

## Request Body

```json theme={null}
{
  "messages": [
    {
      "role": "string",
      "content": "string"
    }
  ],
  "agentId": "string",
  "parseJson": "boolean",
  "threadId": "string"
}
```

* `messages`: An array of message objects, each containing:
  * `role`: Either "user" or "assistant"
  * `content`: The content of the message
* `agentId`: The unique identifier of the agent to use for processing
* `parseJson`: Whether to try and parse the JSON in the response into a JSON object
* `threadId`: (Optional) The ID of an existing thread to continue the conversation

## Responses

### Success (200 OK)

Returns the generated response, usage information, and thread details.

```json theme={null}
{
  "parsedJson": "object",
  "text": "string",
  "stepsTaken": "number",
  "steps": [
    {
      "text": "string",
      "toolCalls": "array",
      "toolResults": "array",
      "finishReason": "string",
      "usage": "object"
    }
  ],
  "tokenUsage": {
    "promptTokens": "number",
    "completionTokens": "number",
    "totalTokens": "number"
  },
  "creditUsage": "number",
  "threadId": "string"
}
```

### Error Responses

* **400 Bad Request**: If the request is invalid
* **401 Unauthorized**: If the API key is invalid or the user doesn't have access to the specified agent
* **403 Forbidden**: If the user doesn't have enough credits
* **404 Not Found**: If the specified agent or thread is not found

## Notes

* This endpoint uses 10 credits per 1000 total tokens used.
* The agent must belong to the project owned by the authenticated user.
* If no threadId is provided, a new thread will be created automatically.
* Messages are stored in the thread for conversation history.

## Rate Limiting

Rate limiting is applied based on the user's subscription.

## Example Request

```bash theme={null}
curl -X POST https://app.dumplingai.com/api/v1/agents/generate-completion \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
  "messages": [
    {
      "role": "user",
      "content": "Hello, can you help me with a task?"
    }
  ],
  "agentId": "agent_123456",
  "parseJson": false,
  "threadId": "optional_thread_id"
}'
```

## Example Response

```json theme={null}
{
  "parsedJson": null,
  "text": "Certainly! I'd be happy to help you with a task. What kind of task do you need assistance with?",
  "stepsTaken": 1,
  "steps": [
    {
      "text": "Certainly! I'd be happy to help you with a task. What kind of task do you need assistance with?",
      "toolCalls": [],
      "toolResults": [],
      "finishReason": "stop",
      "usage": {
        "promptTokens": 20,
        "completionTokens": 15,
        "totalTokens": 35
      }
    }
  ],
  "tokenUsage": {
    "promptTokens": 20,
    "completionTokens": 15,
    "totalTokens": 35
  },
  "creditUsage": 1,
  "threadId": "thread_123456"
}
```


## OpenAPI

````yaml POST /api/v1/agents/generate-completion
openapi: 3.0.3
info:
  title: DumplingAI API
  version: 1.0.0
  description: >
    REST API for DumplingAI's content intelligence and automation platform.

    All endpoints are grouped under `/api/v1`; most are secured via Bearer API
    keys unless an operation explicitly sets `security: []`.
servers:
  - url: https://app.dumplingai.com
    description: Production
security:
  - bearerAuth: []
tags:
  - name: YouTube
    description: Access metadata, search results, and transcripts from YouTube.
  - name: TikTok
    description: Retrieve TikTok profile, video, follower, and transcript data.
  - name: LinkedIn
    description: Programmatically fetch LinkedIn company and profile data.
  - name: Search
    description: Search-orientated endpoints spanning web, news, maps, and autocomplete.
  - name: Google
    description: Integrations with Google business listings and location data.
  - name: Scraping
    description: Webpage capture, crawling, and structured content extraction utilities.
  - name: Documents
    description: Document processing, conversion, and metadata utilities.
  - name: AI
    description: DumplingAI agent and knowledge base endpoints.
  - name: Developer Tools
    description: Utilities for executing sandboxed code via API.
paths:
  /api/v1/agents/generate-completion:
    post:
      tags:
        - AI
      summary: Generate agent completion
      description: >-
        Generate a completion from a DumplingAI agent with streaming or sync
        support.
      operationId: generateAgentCompletion
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/AgentCompletionRequest'
            examples:
              default:
                value:
                  agentId: agnt_123
                  messages:
                    - role: user
                      content: Summarize this article
      responses:
        '200':
          description: Agent completion returned.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/AgentCompletionResponse'
        '400':
          description: Invalid request payload.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '401':
          description: Missing or invalid API key.
        '500':
          description: Unexpected server error.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
components:
  schemas:
    AgentCompletionRequest:
      type: object
      description: Parameters required to request an agent completion.
      required:
        - agentId
        - messages
      properties:
        agentId:
          type: string
          description: Identifier of the agent to run.
        threadId:
          type: string
          description: Optional thread identifier for continuing a previous conversation.
        messages:
          type: array
          description: Ordered conversation history sent to the agent.
          items:
            $ref: '#/components/schemas/ModelMessage'
        parseJson:
          type: boolean
          description: When true, attempt to parse the final response as JSON.
        requestSource:
          $ref: '#/components/schemas/RequestSource'
      additionalProperties: false
    AgentCompletionResponse:
      type: object
      required:
        - text
        - stepsTaken
        - steps
        - tokenUsage
        - creditUsage
        - threadId
      properties:
        text:
          type: string
        stepsTaken:
          type: integer
        steps:
          type: array
          items:
            $ref: '#/components/schemas/AgentCompletionStep'
        tokenUsage:
          $ref: '#/components/schemas/AgentCompletionUsage'
        creditUsage:
          type: integer
        threadId:
          type: string
        parsedJson:
          description: >-
            Parsed JSON extracted from the final assistant text when `parseJson`
            is true.
          oneOf:
            - type: object
              additionalProperties: true
            - type: array
              items: {}
      additionalProperties: false
    ErrorResponse:
      type: object
      properties:
        error:
          type: string
          description: Human-readable description of what went wrong.
      required:
        - error
    ModelMessage:
      type: object
      description: Message exchanged with an agent or language model.
      required:
        - role
        - content
      properties:
        role:
          type: string
          description: Role of the message author.
          enum:
            - system
            - user
            - assistant
            - tool
        content:
          description: Message content. Accepts simple strings or structured message parts.
          oneOf:
            - type: string
            - type: array
              items:
                $ref: '#/components/schemas/MessageContentPart'
            - type: object
              additionalProperties: true
        providerOptions:
          type: object
          additionalProperties: true
          description: >-
            Provider-specific metadata passed through to the underlying language
            model.
      additionalProperties: false
    RequestSource:
      type: string
      description: Optional identifier describing where the API request originated.
      enum:
        - API
        - WEB
        - MAKE_DOT_COM
        - ZAPIER
        - N8N
        - PLAYGROUND
        - DEFAULT_AUTOMATION
        - AGENT_PREVIEW
        - AGENT_LIVE
        - AUTOPILOT
        - STUDIO
    AgentCompletionStep:
      type: object
      required:
        - finishReason
        - usage
      properties:
        text:
          type: string
          nullable: true
        toolCalls:
          type: array
          nullable: true
          items:
            $ref: '#/components/schemas/AgentCompletionToolCall'
        toolResults:
          type: array
          nullable: true
          items:
            $ref: '#/components/schemas/AgentCompletionToolResult'
        finishReason:
          type: string
        usage:
          $ref: '#/components/schemas/AgentCompletionUsage'
      additionalProperties: false
    AgentCompletionUsage:
      type: object
      required:
        - promptTokens
        - completionTokens
        - totalTokens
      properties:
        promptTokens:
          type: integer
        completionTokens:
          type: integer
        totalTokens:
          type: integer
      additionalProperties: false
    MessageContentPart:
      type: object
      required:
        - type
      properties:
        type:
          type: string
          description: Type of message part such as `text`, `image`, or `tool-call`.
        text:
          type: string
          description: Text content for `text` message parts.
        data:
          type: object
          additionalProperties: true
          description: Additional structured data associated with the part.
      additionalProperties: true
    AgentCompletionToolCall:
      type: object
      required:
        - type
        - toolCallId
        - toolName
      properties:
        type:
          type: string
          enum:
            - tool-call
        toolCallId:
          type: string
        toolName:
          type: string
        args:
          type: object
          additionalProperties: true
      additionalProperties: false
    AgentCompletionToolResult:
      type: object
      required:
        - toolCallId
        - toolName
      properties:
        toolCallId:
          type: string
        toolName:
          type: string
        result:
          type: object
          additionalProperties: true
      additionalProperties: false
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: API Key

````