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

# Report API

> Report failed or problematic completions to improve Morph model quality

## Overview

Report failed or problematic completions to help improve Morph's quality. This endpoint allows you to flag completions that produced incorrect, malformed, or problematic code so our team can investigate and improve the models.

**When to use this endpoint:**

* Generated code has syntax errors
* Applied changes broke existing functionality
* Model output doesn't match the intended instruction
* Generated code produces runtime errors or exceptions
* Code quality issues (security vulnerabilities, bad practices)

The completion ID can be found in the response headers (`x-completion-id`) or server logs from your original apply request.

## Request Body

<ParamField body="completion_id" type="string" required>
  The completion ID from the original request (found in response headers or logs)
</ParamField>

<ParamField body="failure_reason" type="string" required>
  Description of what went wrong (Error message, traceback, etc.)
</ParamField>

<ParamField body="user_query" type="string" optional>
  The original user instruction that led to the problematic completion. This helps provide context for debugging and improving the model. Maximum 2000 characters.
</ParamField>

## Response

<ResponseField name="success" type="boolean">
  Whether the report was successfully recorded
</ResponseField>

<ResponseField name="message" type="string">
  Confirmation message
</ResponseField>

<ResponseField name="data" type="object">
  <Expandable title="data">
    <ResponseField name="request_log_id" type="string">
      Internal ID of the reported request
    </ResponseField>

    <ResponseField name="reported_at" type="string">
      ISO timestamp when the report was recorded
    </ResponseField>
  </Expandable>
</ResponseField>

## Error Codes

| Status | Description                  |
| ------ | ---------------------------- |
| `200`  | Report successfully recorded |
| `400`  | Invalid request parameters   |
| `401`  | Invalid or missing API key   |
| `404`  | Completion ID not found      |
| `409`  | Request already reported     |

## Examples

### cURL

```bash theme={null}
curl -X POST "https://morphllm.com/api/report" \
  -H "Authorization: Bearer your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "completion_id": "chatcmpl-9d9e2fc21c094f4eacbcee0009f2f12d",
    "failure_reason": "Generated code had syntax errors: SyntaxError: Unexpected token in JSON",
    "user_query": "Add error handling to the user login function"
  }'
```

### JavaScript (fetch)

```javascript theme={null}
const reportFailure = async (completionId, failureReason, userQuery = null) => {
  const payload = {
    completion_id: completionId,
    failure_reason: failureReason,
  };
  
  // Include user_query only if provided
  if (userQuery) {
    payload.user_query = userQuery;
  }
  
  const response = await fetch('https://morphllm.com/api/report', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer your-api-key',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(payload),
  });

  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }

  return await response.json();
};

// Usage with user query
try {
  const result = await reportFailure(
    'chatcmpl-9d9e2fc21c094f4eacbcee0009f2f12d',
    'Generated code produces runtime error: TypeError: Cannot read property',
    'Add validation to user input fields'
  );
  console.log('Report submitted:', result);
} catch (error) {
  console.error('Failed to submit report:', error);
}

// Usage without user query
try {
  const result = await reportFailure(
    'chatcmpl-9d9e2fc21c094f4eacbcee0009f2f12d',
    'Generated code produces runtime error: TypeError: Cannot read property'
  );
  console.log('Report submitted:', result);
} catch (error) {
  console.error('Failed to submit report:', error);
}
```

### Python (requests)

```python theme={null}
import requests
import json

def report_failure(completion_id, failure_reason, api_key, user_query=None):
    url = "https://morphllm.com/api/report"
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }
    payload = {
        "completion_id": completion_id,
        "failure_reason": failure_reason
    }
    
    # Include user_query only if provided
    if user_query:
        payload["user_query"] = user_query
    
    try:
        response = requests.post(url, headers=headers, json=payload)
        response.raise_for_status()  # Raises an HTTPError for bad responses
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f"Error submitting report: {e}")
        return None

# Usage with user query
api_key = "your-api-key"
completion_id = "chatcmpl-9d9e2fc21c094f4eacbcee0009f2f12d"
failure_reason = """
Traceback (most recent call last):
  File "generated_code.py", line 10, in <module>
    result = process_data(invalid_input)
  File "generated_code.py", line 5, in process_data
    return data.split('.')
AttributeError: 'NoneType' object has no attribute 'split'
"""
user_query = "Refactor the data processing function to handle null values"

result = report_failure(completion_id, failure_reason, api_key, user_query)
if result:
    print(f"Report submitted successfully: {result}")

# Usage without user query  
result = report_failure(completion_id, failure_reason, api_key)
if result:
    print(f"Report submitted successfully: {result}")
```

### Node.js (axios)

```javascript theme={null}
const axios = require('axios');

async function reportFailure(completionId, failureReason, apiKey, userQuery = null) {
  try {
    const payload = {
      completion_id: completionId,
      failure_reason: failureReason,
    };
    
    // Include user_query only if provided
    if (userQuery) {
      payload.user_query = userQuery;
    }

    const response = await axios.post('https://morphllm.com/api/report', payload, {
      headers: {
        'Authorization': `Bearer ${apiKey}`,
        'Content-Type': 'application/json',
      },
    });

    return response.data;
  } catch (error) {
    if (error.response) {
      // Server responded with error status
      console.error('Server error:', error.response.data);
      throw new Error(`Server error: ${error.response.status} - ${error.response.data.error?.message}`);
    } else if (error.request) {
      // Request was made but no response received
      console.error('Network error:', error.request);
      throw new Error('Network error: No response received');
    } else {
      // Something else happened
      console.error('Request error:', error.message);
      throw new Error(`Request error: ${error.message}`);
    }
  }
}

// Usage with user query
(async () => {
  try {
    const result = await reportFailure(
      'chatcmpl-9d9e2fc21c094f4eacbcee0009f2f12d',
      'Generated code fails unit tests: Expected 5 but got undefined',
      'your-api-key',
      'Add unit tests for the calculate function'
    );
    
    console.log('Success:', result.message);
    console.log('Report ID:', result.data?.request_log_id);
    console.log('Reported at:', result.data?.reported_at);
  } catch (error) {
    console.error('Failed to report:', error.message);
  }
})();

// Usage without user query
(async () => {
  try {
    const result = await reportFailure(
      'chatcmpl-9d9e2fc21c094f4eacbcee0009f2f12d',
      'Generated code fails unit tests: Expected 5 but got undefined',
      'your-api-key'
    );
    
    console.log('Success:', result.message);
    console.log('Report ID:', result.data?.request_log_id);
    console.log('Reported at:', result.data?.reported_at);
  } catch (error) {
    console.error('Failed to report:', error.message);
  }
})();
```

### Response Example

Successful response (200 OK):

```json theme={null}
{
  "success": true,
  "message": "Report successfully recorded",
  "data": {
    "request_log_id": "req_123456789",
    "reported_at": "2024-01-15T10:30:00Z"
  }
}
```

Error response (400 Bad Request):

```json theme={null}
{
  "error": {
    "message": "Missing required parameter: completion_id",
    "type": "invalid_request_error",
    "code": "missing_parameter"
  }
}
```


## OpenAPI

````yaml POST /api/report
openapi: 3.1.0
info:
  title: Morph API
  version: 1.1.0
  description: >-
    The Morph public API at api.morphllm.com: OpenAI- and Anthropic-compatible
    inference (chat completions, messages), Fast Apply code editing, Compact
    context compression, Reflex classification, and fine-tuning. Model ids,
    prices, and context windows are served live at
    https://www.morphllm.com/api/models/json.
  contact:
    name: Morph
    url: https://morphllm.com
    email: info@morphllm.com
  license:
    name: Proprietary
    url: https://morphllm.com/privacy/tos
servers:
  - url: https://api.morphllm.com
    description: Production
security: []
tags:
  - name: chat
    description: >-
      OpenAI- and Anthropic-compatible chat inference, including Fast Apply and
      WarpGrep models.
  - name: compact
    description: Context compression for long agent conversations.
  - name: reflex
    description: 'Per-turn classifiers: realtime prediction and batches.'
  - name: fine-tuning
    description: Reflex fine-tuning job lifecycle.
  - name: models
    description: Model listing and management.
  - name: telemetry
    description: Usage reporting hooks.
paths:
  /api/report:
    post:
      tags:
        - telemetry
      summary: Report a failed completion
      description: >-
        Report failed or problematic completions to help improve Morph's
        quality. Reference the completion by the id returned with the original
        response and describe the failure; the original request and response are
        already on file.
      operationId: createReport
      requestBody:
        description: Report request for failed completion
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ReportRequest'
      responses:
        '200':
          description: Report successfully recorded
          content:
            application/json:
              example:
                success: true
                message: Report successfully recorded
                data:
                  request_log_id: req_123456789
                  reported_at: '2024-01-15T10:30:00Z'
              schema:
                $ref: '#/components/schemas/ReportResponse'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/InternalError'
      security:
        - bearerAuth: []
components:
  schemas:
    ReportRequest:
      type: object
      properties:
        completion_id:
          type: string
          description: >-
            The completion ID from the original request (found in response
            headers or logs)
          example: chatcmpl-9d9e2fc21c094f4eacbcee0009f2f12d
        failure_reason:
          type: string
          description: Description of what went wrong (Error message, traceback, etc.)
          example: 'Traceback: ... Generated code had syntax errors'
        user_query:
          type: string
          maxLength: 2000
          description: >-
            Optional: The original user instruction that led to the problematic
            completion
          example: Add error handling to the login function
      required:
        - completion_id
        - failure_reason
      description: >-
        A single problematic completion, identified by id and described by its
        failure.
      example:
        completion_id: chatcmpl-9d9e2fc21c094f4eacbcee0009f2f12d
        failure_reason: 'Traceback: ... Generated code had syntax errors'
        user_query: Add error handling to the login function
    ReportResponse:
      type: object
      properties:
        success:
          type: boolean
          description: Whether the report was successfully recorded
          example: true
        message:
          type: string
          description: Confirmation message
          example: Report successfully recorded
        data:
          type: object
          properties:
            request_log_id:
              type: string
              description: Internal ID of the reported request
              example: req_123456789
            reported_at:
              type: string
              format: date-time
              description: ISO timestamp when the report was recorded
              example: '2024-01-15T10:30:00Z'
          description: Additional response data
          example:
            request_log_id: req_123456789
            reported_at: '2024-01-15T10:30:00Z'
      required:
        - success
        - message
      description: Acknowledgement that the report was stored, with the internal record id.
      example:
        success: true
        message: Report successfully recorded
        data:
          request_log_id: req_123456789
          reported_at: '2024-01-15T10:30:00Z'
    Error:
      type: object
      properties:
        error:
          type: object
          properties:
            code:
              type: string
              example: invalid_request_error
              description: Machine-readable error code.
            message:
              type: string
              example: The request body is missing the `model` field.
              description: Human-readable explanation of the failure.
          required:
            - code
            - message
      required:
        - error
      description: Standard error envelope returned by every non-2xx response.
      example:
        error:
          code: invalid_request_error
          message: The request body is missing the `model` field.
  responses:
    BadRequest:
      description: Malformed request — missing or invalid fields.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error:
              code: invalid_request_error
              message: The request body is missing the `model` field.
    Unauthorized:
      description: Missing or invalid API key.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error:
              code: unauthorized
              message: Invalid API key provided.
    RateLimited:
      description: Rate limited — retry after the interval in the Retry-After header.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error:
              code: rate_limited
              message: Too many requests. Retry in 12 seconds.
    InternalError:
      description: Internal error — safe to retry with backoff.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error:
              code: internal_error
              message: Something went wrong on our side.
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: opaque
      description: >-
        Morph API key, passed as `Authorization: Bearer sk-...`. Create keys at
        https://www.morphllm.com/dashboard/api-keys.

````