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

# Create Chat Completion

> Creates a model response for a chat conversation with the Pet Adoption Advisor AI. Supports streaming responses using Server-Sent Events (SSE).

## Pet Adoption Advisor

Our AI assistant helps users:
- Get personalized pet recommendations
- Learn about pet care and adoption process
- Answer questions about specific pets
- Provide breed information and compatibility advice

## Streaming Mode

When `stream: true`, the response is sent as Server-Sent Events (SSE), with each token delivered incrementally. This provides a better user experience for longer responses.

### Stream Format

Each chunk is sent as:
```
data: {"id":"chatcmpl_abc","object":"chat.completion.chunk","choices":[{"delta":{"content":"Hello"},"index":0}]}

```

The stream ends with:
```
data: [DONE]

```

## Non-Streaming Mode

When `stream: false` or omitted, returns a complete response object.



## OpenAPI

````yaml api-reference/modern-petstore-3.1.openapi.json post /chat/completions
openapi: 3.1.0
info:
  title: Modern Petstore API
  summary: A modern, realistic pet store API demonstrating current best practices
  description: >-
    This is a modern Pet Store API based on the OpenAPI 3.2 specification. It
    demonstrates contemporary API design patterns and best practices including
    RESTful compliance, proper HTTP methods, structured error responses (RFC
    9457), and modern authentication flows.


    Key features include pet catalog browsing, adoption workflow, order
    management, user accounts, AI-powered chat advisor, and real-time event
    notifications via webhooks. The API showcases OpenAPI 3.2 capabilities like
    hierarchical tags, QUERY HTTP method, OAuth device flow, and server-sent
    events.


    Some useful links:

    - [API Documentation](https://docs.petstoreapi.com)

    - [Source Code Repository](https://github.com/petstoreapi/PetstoreAPI)

    - [OpenAPI
    Specification](https://petstoreapi.com/v1/specs/modern-petstore-3.2.openapi.yaml)
  version: 1.0.0
  contact:
    name: Petstore API Support
    url: https://petstoreapi.com/support
    email: support@petstoreapi.com
  license:
    name: MIT
    identifier: MIT
servers:
  - url: https://api.petstoreapi.com/v1
    description: Production server
security:
  - bearerAuth: []
  - oauth2: []
tags:
  - name: Store
    description: Store operations including orders and inventory
  - name: Pet
    description: Pet catalog and management operations
  - name: Payments
    description: Payment processing with polymorphic payment sources
  - name: User
    description: User account management
  - name: Chat
    description: >-
      AI-powered chat completions with streaming support using Server-Sent
      Events (SSE)
    externalDocs:
      description: Learn more about Chat API
      url: https://petstoreapi.com/docs/chat
  - name: Webhooks
    description: Event-driven webhook notifications (OpenAPI 3.2)
    externalDocs:
      description: Learn more about webhooks
      url: https://petstoreapi.com/docs/webhooks
paths:
  /chat/completions:
    post:
      tags:
        - Chat
      summary: Create Chat Completion
      description: >-
        Creates a model response for a chat conversation with the Pet Adoption
        Advisor AI. Supports streaming responses using Server-Sent Events (SSE).


        ## Pet Adoption Advisor


        Our AI assistant helps users:

        - Get personalized pet recommendations

        - Learn about pet care and adoption process

        - Answer questions about specific pets

        - Provide breed information and compatibility advice


        ## Streaming Mode


        When `stream: true`, the response is sent as Server-Sent Events (SSE),
        with each token delivered incrementally. This provides a better user
        experience for longer responses.


        ### Stream Format


        Each chunk is sent as:

        ```

        data:
        {"id":"chatcmpl_abc","object":"chat.completion.chunk","choices":[{"delta":{"content":"Hello"},"index":0}]}


        ```


        The stream ends with:

        ```

        data: [DONE]


        ```


        ## Non-Streaming Mode


        When `stream: false` or omitted, returns a complete response object.
      operationId: createChatCompletion
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - messages
              properties:
                messages:
                  type: array
                  description: A list of messages comprising the conversation so far
                  items:
                    type: object
                    required:
                      - role
                      - content
                    properties:
                      role:
                        type: string
                        enum:
                          - SYSTEM
                          - USER
                          - ASSISTANT
                        description: The role of the message author
                      content:
                        type: string
                        description: The contents of the message
                  minItems: 1
                model:
                  type: string
                  description: ID of the model to use
                  enum:
                    - PET_ADVISOR_1
                    - PET_ADVISOR_TURBO
                  default: PET_ADVISOR_1
                stream:
                  type: boolean
                  description: >-
                    If true, partial message deltas will be sent via Server-Sent
                    Events
                  default: true
                maxTokens:
                  type: integer
                  description: Maximum number of tokens to generate
                  minimum: 1
                  maximum: 4096
                  default: 1024
                temperature:
                  type: number
                  description: Sampling temperature between 0 and 2
                  minimum: 0
                  maximum: 2
                  default: 1
              unevaluatedProperties: false
            examples:
              simple-question:
                summary: Simple pet question
                value:
                  messages:
                    - role: user
                      content: What should I know before adopting a cat?
                  model: pet-advisor-1
                  stream: false
              streaming-conversation:
                summary: Streaming multi-turn conversation
                value:
                  messages:
                    - role: system
                      content: You are a helpful pet adoption advisor.
                    - role: user
                      content: I'm looking for a pet that's good with kids
                    - role: assistant
                      content: >-
                        Great! Dogs like Labrador Retrievers and Golden
                        Retrievers are excellent with children.
                    - role: user
                      content: Tell me more about Golden Retrievers
                  model: pet-advisor-turbo
                  stream: true
                  temperature: 0.7
      responses:
        '201':
          description: Successful response. Format depends on the `stream` parameter.
          headers:
            Content-Type:
              description: Response content type
              schema:
                type: string
                enum:
                  - text/event-stream
                  - application/json
          content:
            text/event-stream:
              schema:
                type: string
                description: >-
                  Streaming response (when stream=true). Each line contains a
                  JSON chunk prefixed with 'data: '
                format: binary
              examples:
                streaming-response:
                  summary: Streaming chat completion
                  value: >+
                    data:
                    {"id":"chatcmpl_abc123","object":"chat.completion.chunk","created":1702648800,"model":"pet-advisor-1","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}]}


                    data:
                    {"id":"chatcmpl_abc123","object":"chat.completion.chunk","created":1702648800,"model":"pet-advisor-1","choices":[{"index":0,"delta":{"content":"Before"},"finish_reason":null}]}


                    data:
                    {"id":"chatcmpl_abc123","object":"chat.completion.chunk","created":1702648800,"model":"pet-advisor-1","choices":[{"index":0,"delta":{"content":"
                    adopting"},"finish_reason":null}]}


                    data:
                    {"id":"chatcmpl_abc123","object":"chat.completion.chunk","created":1702648800,"model":"pet-advisor-1","choices":[{"index":0,"delta":{"content":"
                    a"},"finish_reason":null}]}


                    data:
                    {"id":"chatcmpl_abc123","object":"chat.completion.chunk","created":1702648800,"model":"pet-advisor-1","choices":[{"index":0,"delta":{"content":"
                    cat"},"finish_reason":null}]}


                    data:
                    {"id":"chatcmpl_abc123","object":"chat.completion.chunk","created":1702648800,"model":"pet-advisor-1","choices":[{"index":0,"delta":{"content":"..."},"finish_reason":null}]}


                    data:
                    {"id":"chatcmpl_abc123","object":"chat.completion.chunk","created":1702648800,"model":"pet-advisor-1","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}


                    data: [DONE]

            application/json:
              schema:
                type: object
                description: Non-streaming response (when stream=false)
                properties:
                  id:
                    type: string
                    description: Unique identifier for the completion
                    pattern: ^chatcmpl_[a-z0-9]+$
                  object:
                    type: string
                    const: chat.completion
                  created:
                    type: integer
                    description: Unix timestamp of when the completion was created
                  model:
                    type: string
                    description: Model used for completion
                  choices:
                    type: array
                    items:
                      type: object
                      properties:
                        index:
                          type: integer
                        message:
                          type: object
                          properties:
                            role:
                              type: string
                              const: assistant
                            content:
                              type: string
                        finishReason:
                          type: string
                          enum:
                            - STOP
                            - LENGTH
                            - CONTENT_FILTER
                  usage:
                    type: object
                    properties:
                      promptTokens:
                        type: integer
                      completionTokens:
                        type: integer
                      totalTokens:
                        type: integer
              examples:
                complete-response:
                  summary: Complete chat response
                  value:
                    id: chatcmpl_abc123
                    object: chat.completion
                    created: 1702648800
                    model: pet-advisor-1
                    choices:
                      - index: 0
                        message:
                          role: assistant
                          content: >-
                            Before adopting a cat, consider these important
                            factors:


                            1. **Time Commitment**: Cats can live 15-20 years

                            2. **Space**: Ensure you have adequate living space

                            3. **Allergies**: Check if anyone in your household
                            has cat allergies

                            4. **Costs**: Budget for food, litter, vet care, and
                            supplies

                            5. **Lifestyle**: Consider if your schedule allows
                            for proper care


                            Would you like recommendations for cats currently
                            available for adoption?
                        finishReason: stop
                    usage:
                      promptTokens: 15
                      completionTokens: 89
                      totalTokens: 104
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '422':
          $ref: '#/components/responses/UnprocessableEntity'
        '429':
          $ref: '#/components/responses/TooManyRequests'
      deprecated: false
      security:
        - bearerAuth: []
        - oauth2:
            - chat:write
      externalDocs:
        description: Complete Chat API Guide with Streaming Examples
        url: https://petstoreapi.com/docs/chat/streaming-guide
      x-codeSamples:
        - lang: TypeScript
          label: TypeScript SDK (Non-Streaming)
          source: |-
            import { PetStoreAPI } from '@petstoreapi/sdk';

            const client = new PetStoreAPI({
              accessToken: process.env.OAUTH_ACCESS_TOKEN
            });

            const completion = await client.chat.completions.create({
              messages: [
                { role: 'user', content: 'What should I know before adopting a cat?' }
              ],
              model: 'pet-advisor-1',
              stream: false
            });

            console.log(completion.choices[0].message.content);
        - lang: TypeScript
          label: TypeScript SDK (Streaming)
          source: |-
            import { PetStoreAPI } from '@petstoreapi/sdk';

            const client = new PetStoreAPI({
              accessToken: process.env.OAUTH_ACCESS_TOKEN
            });

            const stream = await client.chat.completions.create({
              messages: [
                { role: 'user', content: 'What should I know before adopting a cat?' }
              ],
              model: 'pet-advisor-1',
              stream: true
            });

            for await (const chunk of stream) {
              const content = chunk.choices[0]?.delta?.content;
              if (content) {
                process.stdout.write(content);
              }
            }
        - lang: Python
          label: Python (Streaming)
          source: |-
            from petstore import PetStoreAPI

            client = PetStoreAPI(access_token=os.environ['OAUTH_ACCESS_TOKEN'])

            stream = client.chat.completions.create(
                messages=[
                    {"role": "user", "content": "What should I know before adopting a cat?"}
                ],
                model="pet-advisor-1",
                stream=True
            )

            for chunk in stream:
                if chunk.choices[0].delta.content:
                    print(chunk.choices[0].delta.content, end="")
        - lang: JavaScript
          label: JavaScript (Fetch with SSE)
          source: |-
            const response = await fetch(
              'https://api.petstoreapi.com/v1/chat/completions',
              {
                method: 'POST',
                headers: {
                  'Authorization': `Bearer ${accessToken}`,
                  'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                  messages: [
                    { role: 'user', content: 'What should I know before adopting a cat?' }
                  ],
                  model: 'pet-advisor-1',
                  stream: true
                })
              }
            );

            const reader = response.body.getReader();
            const decoder = new TextDecoder();

            while (true) {
              const { value, done } = await reader.read();
              if (done) break;
              
              const chunk = decoder.decode(value);
              const lines = chunk.split('\n').filter(line => line.startsWith('data: '));
              
              for (const line of lines) {
                const data = line.replace('data: ', '');
                if (data === '[DONE]') break;
                const parsed = JSON.parse(data);
                process.stdout.write(parsed.choices[0]?.delta?.content || '');
              }
            }
        - lang: Shell
          label: cURL (Non-Streaming)
          source: |-
            curl -X POST 'https://api.petstoreapi.com/v1/chat/completions' \
              -H 'Authorization: Bearer YOUR_ACCESS_TOKEN' \
              -H 'Content-Type: application/json' \
              -d '{
                "messages": [
                  {
                    "role": "user",
                    "content": "What should I know before adopting a cat?"
                  }
                ],
                "model": "pet-advisor-1",
                "stream": false
              }'
components:
  responses:
    BadRequest:
      description: Bad request - Invalid parameters
      headers:
        RateLimit-Limit:
          $ref: '#/components/headers/RateLimit-Limit'
        RateLimit-Remaining:
          $ref: '#/components/headers/RateLimit-Remaining'
        RateLimit-Reset:
          $ref: '#/components/headers/RateLimit-Reset'
      content:
        application/problem+json:
          schema:
            $ref: '#/components/schemas/Error'
          examples:
            invalid-parameter:
              summary: Invalid query parameter
              value:
                type: https://petstoreapi.com/errors/bad-request
                title: Bad Request
                status: 400
                detail: >-
                  Invalid value for parameter 'status'. Must be one of:
                  available, pending, sold.
                instance: /pets
    Unauthorized:
      description: Unauthorized - Authentication required
      content:
        application/problem+json:
          schema:
            $ref: '#/components/schemas/Error'
          examples:
            missing-token:
              summary: Missing authentication token
              value:
                type: https://petstoreapi.com/errors/unauthorized
                title: Unauthorized
                status: 401
                detail: >-
                  Authentication is required to access this resource. Please
                  provide a valid OAuth 2.0 token.
    UnprocessableEntity:
      description: Unprocessable entity - Validation errors
      content:
        application/problem+json:
          schema:
            $ref: '#/components/schemas/Error'
          examples:
            validation-errors:
              summary: Validation errors
              value:
                type: https://petstoreapi.com/errors/validation-error
                title: Validation Error
                status: 422
                detail: The request body contains validation errors.
                instance: /pets
                errors:
                  - field: name
                    message: Pet name is required
                    code: required_field
                  - field: status
                    message: Invalid status value
                    code: invalid_format
    TooManyRequests:
      description: Too many requests - Rate limit exceeded
      headers:
        RateLimit-Limit:
          $ref: '#/components/headers/RateLimit-Limit'
        RateLimit-Remaining:
          schema:
            type: integer
          example: 0
        RateLimit-Reset:
          $ref: '#/components/headers/RateLimit-Reset'
        Retry-After:
          description: Number of seconds to wait before retrying
          schema:
            type: integer
          example: 60
      content:
        application/problem+json:
          schema:
            $ref: '#/components/schemas/Error'
          examples:
            rate-limit-exceeded:
              summary: Rate limit exceeded
              value:
                type: https://petstoreapi.com/errors/rate-limit-exceeded
                title: Too Many Requests
                status: 429
                detail: >-
                  Rate limit exceeded. Please wait 60 seconds before making
                  another request.
  headers:
    RateLimit-Limit:
      description: The maximum number of requests allowed in the current time window
      schema:
        type: integer
      example: 100
    RateLimit-Remaining:
      description: The number of requests remaining in the current time window
      schema:
        type: integer
      example: 95
    RateLimit-Reset:
      description: The time at which the current rate limit window resets (Unix timestamp)
      schema:
        type: integer
      example: 1702648800
  schemas:
    Error:
      type: object
      description: RFC 9457 Problem Details for HTTP APIs
      required:
        - type
        - title
        - status
      properties:
        type:
          type: string
          format: uri
          description: A URI reference that identifies the problem type
          examples:
            - https://petstoreapi.com/errors/not-found
            - https://petstoreapi.com/errors/validation-error
        title:
          type: string
          description: A short, human-readable summary of the problem
          examples:
            - Resource Not Found
            - Validation Error
        status:
          type: integer
          description: The HTTP status code
          examples:
            - 404
            - 400
            - 422
        detail:
          type: string
          description: A human-readable explanation specific to this occurrence
          examples:
            - The requested pet with ID '123' was not found
        instance:
          type: string
          format: uri
          description: A URI reference that identifies the specific occurrence
          examples:
            - /v1/pets/123
        errors:
          type: array
          description: Detailed validation errors (for 422 responses)
          items:
            type: object
            required:
              - field
              - message
            properties:
              field:
                type: string
                description: The field that failed validation
              message:
                type: string
                description: Description of the validation error
              code:
                type: string
                description: Machine-readable error code
            unevaluatedProperties: false
      unevaluatedProperties: false
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
      description: >-
        Bearer token authentication using JWT (JSON Web Token). Include the
        token in the Authorization header as: `Authorization: Bearer <token>`
    oauth2:
      type: oauth2
      description: >-
        OAuth 2.0 authorization with multiple flows including device
        authorization for IoT devices and smart TVs
      flows:
        authorizationCode:
          authorizationUrl: https://auth.petstoreapi.com/authorize
          tokenUrl: https://auth.petstoreapi.com/token
          refreshUrl: https://auth.petstoreapi.com/refresh
          scopes:
            read:pets: Read pet information
            write:pets: Create and update pets
            read:orders: Read order information
            write:orders: Create and manage orders
            read:user: Read user profile
            write:user: Update user profile
            chat:write: Access AI chat completions

````