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

# Rate Message

> Rate an AI-generated message with a score and optional feedback

# Rate Message

Rate an AI-generated message to provide feedback on the quality of the response. This helps improve the AI agent's performance and track user satisfaction.

## Endpoint

```
PUT https://api.nexusgpt.io/api/public/messages/{messageId}/rate
```

## Authentication

<ParamField header="api-key" type="string" required>
  Your Nexus API key for authentication
</ParamField>

## Path Parameters

<ParamField path="messageId" type="string" required>
  The ID of the AI message to rate. This must be a message generated by the AI assistant, not a user message.
</ParamField>

## Request Body

<ParamField body="score" type="number" required>
  The rating score from 1 to 5, where:

  * 1 = Very Poor
  * 2 = Poor
  * 3 = Average
  * 4 = Good
  * 5 = Excellent
</ParamField>

<ParamField body="feedback" type="string" optional>
  Optional text feedback providing additional context about the rating. Maximum length: 1000 characters.
</ParamField>

<ResponseExample>
  ```json Success Response theme={null}
  {
    "id": "rating-550e8400-e29b-41d4",
    "messageId": "msg-123456789",
    "score": 5,
    "feedback": "Very helpful and accurate response!",
    "createdAt": "2024-01-15T10:30:00Z",
    "updatedAt": "2024-01-15T10:30:00Z"
  }
  ```
</ResponseExample>

## Response Fields

<ResponseField name="id" type="string" required>
  Unique identifier for the rating
</ResponseField>

<ResponseField name="messageId" type="string" required>
  The ID of the message that was rated
</ResponseField>

<ResponseField name="score" type="number" required>
  The rating score provided (1-5)
</ResponseField>

<ResponseField name="feedback" type="string" optional>
  The optional feedback text if provided
</ResponseField>

<ResponseField name="createdAt" type="string" required>
  ISO 8601 timestamp of when the rating was created
</ResponseField>

<ResponseField name="updatedAt" type="string" required>
  ISO 8601 timestamp of when the rating was last updated
</ResponseField>

## Example Usage

<CodeGroup>
  ```bash cURL theme={null}
  curl -X PUT https://api.nexusgpt.io/api/public/messages/msg-123456789/rate \
    -H "Content-Type: application/json" \
    -H "api-key: YOUR_API_KEY" \
    -d '{
      "score": 5,
      "feedback": "Very helpful and accurate response!"
    }'
  ```

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

  async function rateMessage(messageId, score, feedback = null) {
    try {
      const response = await axios.put(
        `https://api.nexusgpt.io/api/public/messages/${messageId}/rate`,
        { 
          score: score,
          feedback: feedback 
        },
        {
          headers: {
            'Content-Type': 'application/json',
            'api-key': process.env.NEXUS_API_KEY
          }
        }
      );
      
      console.log('Rating submitted successfully:', response.data);
      return response.data;
      
    } catch (error) {
      console.error('Error submitting rating:', error.response?.data);
      throw error;
    }
  }

  // Rate a message with score only
  await rateMessage('msg-123456789', 5);

  // Rate a message with score and feedback
  await rateMessage('msg-123456789', 4, 'Good response but could be more detailed');
  ```

  ```python Python theme={null}
  import os
  import requests

  def rate_message(message_id, score, feedback=None):
      """Rate an AI message with a score and optional feedback"""
      url = f"https://api.nexusgpt.io/api/public/messages/{message_id}/rate"
      
      headers = {
          "Content-Type": "application/json",
          "api-key": os.environ.get("NEXUS_API_KEY")
      }
      
      data = {
          "score": score
      }
      
      if feedback:
          data["feedback"] = feedback
      
      try:
          response = requests.put(url, json=data, headers=headers)
          response.raise_for_status()
          
          print("Rating submitted successfully:", response.json())
          return response.json()
          
      except requests.exceptions.RequestException as e:
          print(f"Error submitting rating: {e}")
          if hasattr(e, 'response'):
              print(f"Response: {e.response.text}")
          raise

  # Rate a message with score only
  rate_message('msg-123456789', 5)

  # Rate a message with score and feedback
  rate_message('msg-123456789', 4, 'Good response but could be more detailed')
  ```

  ```go Go theme={null}
  package main

  import (
      "bytes"
      "encoding/json"
      "fmt"
      "io"
      "net/http"
      "os"
  )

  type RateMessageRequest struct {
      Score    int    `json:"score"`
      Feedback string `json:"feedback,omitempty"`
  }

  type RateMessageResponse struct {
      ID        string `json:"id"`
      MessageID string `json:"messageId"`
      Score     int    `json:"score"`
      Feedback  string `json:"feedback,omitempty"`
      CreatedAt string `json:"createdAt"`
      UpdatedAt string `json:"updatedAt"`
  }

  func rateMessage(messageID string, score int, feedback string) (*RateMessageResponse, error) {
      url := fmt.Sprintf("https://api.nexusgpt.io/api/public/messages/%s/rate", messageID)
      
      requestBody := RateMessageRequest{
          Score:    score,
          Feedback: feedback,
      }
      
      jsonData, err := json.Marshal(requestBody)
      if err != nil {
          return nil, err
      }
      
      req, err := http.NewRequest("PUT", url, bytes.NewBuffer(jsonData))
      if err != nil {
          return nil, err
      }
      
      req.Header.Set("Content-Type", "application/json")
      req.Header.Set("api-key", os.Getenv("NEXUS_API_KEY"))
      
      client := &http.Client{}
      resp, err := client.Do(req)
      if err != nil {
          return nil, err
      }
      defer resp.Body.Close()
      
      body, err := io.ReadAll(resp.Body)
      if err != nil {
          return nil, err
      }
      
      if resp.StatusCode != http.StatusOK {
          return nil, fmt.Errorf("API error: %s", string(body))
      }
      
      var result RateMessageResponse
      if err := json.Unmarshal(body, &result); err != nil {
          return nil, err
      }
      
      fmt.Printf("Rating submitted successfully: %+v\n", result)
      return &result, nil
  }
  ```
</CodeGroup>

## Rating Guidelines

### When to Rate Messages

* **After receiving a response**: Rate immediately after receiving an AI response while the context is fresh
* **Quality feedback**: Provide ratings that reflect the actual helpfulness of the response
* **Update ratings**: You can update a previous rating by calling the endpoint again with the same message ID

### Score Guidelines

| Score | Description | When to Use                                                       |
| ----- | ----------- | ----------------------------------------------------------------- |
| 5     | Excellent   | Perfect response, fully addresses the query, accurate and helpful |
| 4     | Good        | Mostly accurate and helpful with minor room for improvement       |
| 3     | Average     | Adequate response but missing some details or partially helpful   |
| 2     | Poor        | Response has significant issues or is mostly unhelpful            |
| 1     | Very Poor   | Completely wrong, irrelevant, or unhelpful response               |

## Common Patterns

### 1. Rate After Response Pattern

```javascript theme={null}
async function interactAndRate(sessionId, userMessage) {
  // Send message
  await sendMessage(sessionId, userMessage);
  
  // Get response
  const messages = await getMessages(sessionId, { limit: 2, order: 'desc' });
  const aiResponse = messages.find(m => m.type === 'assistant');
  
  // Rate the response based on quality
  if (aiResponse) {
    const score = evaluateResponse(aiResponse.content);
    await rateMessage(aiResponse.id, score);
  }
}
```

### 2. Feedback Collection Pattern

```javascript theme={null}
async function collectUserFeedback(messageId) {
  // Show rating UI to user
  const { score, feedback } = await showRatingDialog();
  
  // Submit rating with optional feedback
  try {
    const rating = await rateMessage(messageId, score, feedback);
    console.log('Thank you for your feedback!');
    return rating;
  } catch (error) {
    console.error('Failed to submit rating:', error);
  }
}
```

### 3. Batch Rating Pattern

```javascript theme={null}
async function rateMultipleMessages(ratings) {
  const results = [];
  
  for (const { messageId, score, feedback } of ratings) {
    try {
      const result = await rateMessage(messageId, score, feedback);
      results.push({ success: true, rating: result });
    } catch (error) {
      results.push({ success: false, messageId, error: error.message });
    }
  }
  
  return results;
}
```

## Error Responses

<ResponseExample>
  ```json 401 Unauthorized theme={null}
  {
    "statusCode": 401,
    "message": "Invalid API key",
    "error": "Unauthorized"
  }
  ```

  ```json 404 Not Found theme={null}
  {
    "statusCode": 404,
    "message": "Message not found",
    "error": "Not Found"
  }
  ```

  ```json 400 Bad Request - Invalid Score theme={null}
  {
    "statusCode": 400,
    "message": "Score must be between 1 and 5",
    "error": "Bad Request"
  }
  ```

  ```json 400 Bad Request - User Message theme={null}
  {
    "statusCode": 400,
    "message": "Only AI messages can be rated",
    "error": "Bad Request"
  }
  ```

  ```json 403 Forbidden theme={null}
  {
    "statusCode": 403,
    "message": "Message does not belong to your integration",
    "error": "Forbidden"
  }
  ```

  ```json 429 Too Many Requests theme={null}
  {
    "statusCode": 429,
    "message": "Rate limit exceeded",
    "error": "Too Many Requests"
  }
  ```
</ResponseExample>

## Best Practices

<AccordionGroup>
  <Accordion title="Rating Quality">
    * Provide honest and accurate ratings
    * Include specific feedback when possible
    * Rate based on the actual helpfulness of the response
    * Consider the context of the conversation
  </Accordion>

  <Accordion title="Feedback Content">
    * Keep feedback constructive and specific
    * Mention what was good or what could be improved
    * Avoid personal information in feedback
    * Use clear and concise language
  </Accordion>

  <Accordion title="Implementation">
    * Store message IDs for later rating
    * Implement rating UI in your application
    * Handle rating errors gracefully
    * Consider implementing a rating reminder system
  </Accordion>

  <Accordion title="Analytics">
    * Track rating patterns over time
    * Monitor average scores by conversation type
    * Use feedback to identify improvement areas
    * Correlate ratings with user engagement
  </Accordion>
</AccordionGroup>

## Limitations

* **Message Type**: Only AI-generated messages can be rated (not user messages)
* **Score Range**: Score must be an integer between 1 and 5
* **Feedback Length**: Maximum 1000 characters for feedback text
* **Update Behavior**: Rating the same message again will update the existing rating
* **Integration Scope**: You can only rate messages from your own integration

## Related Endpoints

* [Send Message](/api-reference/nexus-endpoints/send-message) - Send messages to get AI responses
* [List Messages](/api-reference/nexus-endpoints/list-messages) - Retrieve messages to find ones to rate
* [Get Session](/api-reference/nexus-endpoints/get-session) - Check session details and message history
