# paths

## /assistants

### get

#### operationId

listAssistants

#### tags

- Assistants

#### summary

List assistants

#### parameters

##### name

limit

##### in

query

##### description

A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20.


##### required

false

##### schema

###### type

integer

###### default

20

##### name

order

##### in

query

##### description

Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order.


##### schema

###### type

string

###### default

desc

###### enum

- asc
- desc

##### name

after

##### in

query

##### description

A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list.


##### schema

###### type

string

##### name

before

##### in

query

##### description

A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list.


##### schema

###### type

string


#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ListAssistantsResponse

#### x-oaiMeta

##### name

List assistants

##### group

assistants

##### beta

true

##### returns

A list of [assistant](https://platform.openai.com/docs/api-reference/assistants/object) objects.

##### examples

###### response

{
  "object": "list",
  "data": [
    {
      "id": "asst_abc123",
      "object": "assistant",
      "created_at": 1698982736,
      "name": "Coding Tutor",
      "description": null,
      "model": "gpt-4o",
      "instructions": "You are a helpful assistant designed to make me better at coding!",
      "tools": [],
      "tool_resources": {},
      "metadata": {},
      "top_p": 1.0,
      "temperature": 1.0,
      "response_format": "auto"
    },
    {
      "id": "asst_abc456",
      "object": "assistant",
      "created_at": 1698982718,
      "name": "My Assistant",
      "description": null,
      "model": "gpt-4o",
      "instructions": "You are a helpful assistant designed to make me better at coding!",
      "tools": [],
      "tool_resources": {},
      "metadata": {},
      "top_p": 1.0,
      "temperature": 1.0,
      "response_format": "auto"
    },
    {
      "id": "asst_abc789",
      "object": "assistant",
      "created_at": 1698982643,
      "name": null,
      "description": null,
      "model": "gpt-4o",
      "instructions": null,
      "tools": [],
      "tool_resources": {},
      "metadata": {},
      "top_p": 1.0,
      "temperature": 1.0,
      "response_format": "auto"
    }
  ],
  "first_id": "asst_abc123",
  "last_id": "asst_abc789",
  "has_more": false
}


###### request

####### curl

curl "https://api.openai.com/v1/assistants?order=desc&limit=20" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "OpenAI-Beta: assistants=v2"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
page = client.beta.assistants.list()
page = page.data[0]
print(page.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

// Automatically fetches more pages as needed.
for await (const assistant of client.beta.assistants.list()) {
  console.log(assistant.id);
}

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  page, err := client.Beta.Assistants.List(context.TODO(), openai.BetaAssistantListParams{

  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", page)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.beta.assistants.AssistantListPage;
import com.openai.models.beta.assistants.AssistantListParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        AssistantListPage page = client.beta().assistants().list();
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

page = openai.beta.assistants.list

puts(page)

#### description

Returns a list of assistants.

### post

#### operationId

createAssistant

#### tags

- Assistants

#### summary

Create assistant

#### requestBody

##### required

true

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/CreateAssistantRequest

#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/AssistantObject

#### x-oaiMeta

##### name

Create assistant

##### group

assistants

##### beta

true

##### returns

An [assistant](https://platform.openai.com/docs/api-reference/assistants/object) object.

##### examples

###### title

Code Interpreter

###### request

####### curl

curl "https://api.openai.com/v1/assistants" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "OpenAI-Beta: assistants=v2" \
  -d '{
    "instructions": "You are a personal math tutor. When asked a question, write and run Python code to answer the question.",
    "name": "Math Tutor",
    "tools": [{"type": "code_interpreter"}],
    "model": "gpt-4o"
  }'


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
assistant = client.beta.assistants.create(
    model="gpt-4o",
)
print(assistant.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const assistant = await client.beta.assistants.create({ model: 'gpt-4o' });

console.log(assistant.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
  "github.com/openai/openai-go/shared"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  assistant, err := client.Beta.Assistants.New(context.TODO(), openai.BetaAssistantNewParams{
    Model: shared.ChatModelGPT5,
  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", assistant.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.ChatModel;
import com.openai.models.beta.assistants.Assistant;
import com.openai.models.beta.assistants.AssistantCreateParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        AssistantCreateParams params = AssistantCreateParams.builder()
            .model(ChatModel.GPT_5)
            .build();
        Assistant assistant = client.beta().assistants().create(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

assistant = openai.beta.assistants.create(model: :"gpt-5")

puts(assistant)

###### response

{
  "id": "asst_abc123",
  "object": "assistant",
  "created_at": 1698984975,
  "name": "Math Tutor",
  "description": null,
  "model": "gpt-4o",
  "instructions": "You are a personal math tutor. When asked a question, write and run Python code to answer the question.",
  "tools": [
    {
      "type": "code_interpreter"
    }
  ],
  "metadata": {},
  "top_p": 1.0,
  "temperature": 1.0,
  "response_format": "auto"
}


###### title

Files

###### request

####### curl

curl https://api.openai.com/v1/assistants \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "OpenAI-Beta: assistants=v2" \
  -d '{
    "instructions": "You are an HR bot, and you have access to files to answer employee questions about company policies.",
    "tools": [{"type": "file_search"}],
    "tool_resources": {"file_search": {"vector_store_ids": ["vs_123"]}},
    "model": "gpt-4o"
  }'


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
assistant = client.beta.assistants.create(
    model="gpt-4o",
)
print(assistant.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const assistant = await client.beta.assistants.create({ model: 'gpt-4o' });

console.log(assistant.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
  "github.com/openai/openai-go/shared"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  assistant, err := client.Beta.Assistants.New(context.TODO(), openai.BetaAssistantNewParams{
    Model: shared.ChatModelGPT5,
  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", assistant.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.ChatModel;
import com.openai.models.beta.assistants.Assistant;
import com.openai.models.beta.assistants.AssistantCreateParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        AssistantCreateParams params = AssistantCreateParams.builder()
            .model(ChatModel.GPT_5)
            .build();
        Assistant assistant = client.beta().assistants().create(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

assistant = openai.beta.assistants.create(model: :"gpt-5")

puts(assistant)

###### response

{
  "id": "asst_abc123",
  "object": "assistant",
  "created_at": 1699009403,
  "name": "HR Helper",
  "description": null,
  "model": "gpt-4o",
  "instructions": "You are an HR bot, and you have access to files to answer employee questions about company policies.",
  "tools": [
    {
      "type": "file_search"
    }
  ],
  "tool_resources": {
    "file_search": {
      "vector_store_ids": ["vs_123"]
    }
  },
  "metadata": {},
  "top_p": 1.0,
  "temperature": 1.0,
  "response_format": "auto"
}



#### description

Create an assistant with a model and instructions.

## /assistants/{assistant_id}

### get

#### operationId

getAssistant

#### tags

- Assistants

#### summary

Retrieve assistant

#### parameters

##### in

path

##### name

assistant_id

##### required

true

##### schema

###### type

string

##### description

The ID of the assistant to retrieve.


#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/AssistantObject

#### x-oaiMeta

##### name

Retrieve assistant

##### group

assistants

##### beta

true

##### returns

The [assistant](https://platform.openai.com/docs/api-reference/assistants/object) object matching the specified ID.

##### examples

###### response

{
  "id": "asst_abc123",
  "object": "assistant",
  "created_at": 1699009709,
  "name": "HR Helper",
  "description": null,
  "model": "gpt-4o",
  "instructions": "You are an HR bot, and you have access to files to answer employee questions about company policies.",
  "tools": [
    {
      "type": "file_search"
    }
  ],
  "metadata": {},
  "top_p": 1.0,
  "temperature": 1.0,
  "response_format": "auto"
}


###### request

####### curl

curl https://api.openai.com/v1/assistants/asst_abc123 \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "OpenAI-Beta: assistants=v2"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
assistant = client.beta.assistants.retrieve(
    "assistant_id",
)
print(assistant.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const assistant = await client.beta.assistants.retrieve('assistant_id');

console.log(assistant.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  assistant, err := client.Beta.Assistants.Get(context.TODO(), "assistant_id")
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", assistant.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.beta.assistants.Assistant;
import com.openai.models.beta.assistants.AssistantRetrieveParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        Assistant assistant = client.beta().assistants().retrieve("assistant_id");
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

assistant = openai.beta.assistants.retrieve("assistant_id")

puts(assistant)

#### description

Retrieves an assistant.

### post

#### operationId

modifyAssistant

#### tags

- Assistants

#### summary

Modify assistant

#### parameters

##### in

path

##### name

assistant_id

##### required

true

##### schema

###### type

string

##### description

The ID of the assistant to modify.


#### requestBody

##### required

true

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/ModifyAssistantRequest

#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/AssistantObject

#### x-oaiMeta

##### name

Modify assistant

##### group

assistants

##### beta

true

##### returns

The modified [assistant](https://platform.openai.com/docs/api-reference/assistants/object) object.

##### examples

###### response

{
  "id": "asst_123",
  "object": "assistant",
  "created_at": 1699009709,
  "name": "HR Helper",
  "description": null,
  "model": "gpt-4o",
  "instructions": "You are an HR bot, and you have access to files to answer employee questions about company policies. Always response with info from either of the files.",
  "tools": [
    {
      "type": "file_search"
    }
  ],
  "tool_resources": {
    "file_search": {
      "vector_store_ids": []
    }
  },
  "metadata": {},
  "top_p": 1.0,
  "temperature": 1.0,
  "response_format": "auto"
}


###### request

####### curl

curl https://api.openai.com/v1/assistants/asst_abc123 \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "OpenAI-Beta: assistants=v2" \
  -d '{
      "instructions": "You are an HR bot, and you have access to files to answer employee questions about company policies. Always response with info from either of the files.",
      "tools": [{"type": "file_search"}],
      "model": "gpt-4o"
    }'


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
assistant = client.beta.assistants.update(
    assistant_id="assistant_id",
)
print(assistant.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const assistant = await client.beta.assistants.update('assistant_id');

console.log(assistant.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  assistant, err := client.Beta.Assistants.Update(
    context.TODO(),
    "assistant_id",
    openai.BetaAssistantUpdateParams{

    },
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", assistant.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.beta.assistants.Assistant;
import com.openai.models.beta.assistants.AssistantUpdateParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        Assistant assistant = client.beta().assistants().update("assistant_id");
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

assistant = openai.beta.assistants.update("assistant_id")

puts(assistant)

#### description

Modifies an assistant.

### delete

#### operationId

deleteAssistant

#### tags

- Assistants

#### summary

Delete assistant

#### parameters

##### in

path

##### name

assistant_id

##### required

true

##### schema

###### type

string

##### description

The ID of the assistant to delete.


#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/DeleteAssistantResponse

#### x-oaiMeta

##### name

Delete assistant

##### group

assistants

##### beta

true

##### returns

Deletion status

##### examples

###### response

{
  "id": "asst_abc123",
  "object": "assistant.deleted",
  "deleted": true
}


###### request

####### curl

curl https://api.openai.com/v1/assistants/asst_abc123 \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "OpenAI-Beta: assistants=v2" \
  -X DELETE


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
assistant_deleted = client.beta.assistants.delete(
    "assistant_id",
)
print(assistant_deleted.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const assistantDeleted = await client.beta.assistants.delete('assistant_id');

console.log(assistantDeleted.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  assistantDeleted, err := client.Beta.Assistants.Delete(context.TODO(), "assistant_id")
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", assistantDeleted.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.beta.assistants.AssistantDeleteParams;
import com.openai.models.beta.assistants.AssistantDeleted;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        AssistantDeleted assistantDeleted = client.beta().assistants().delete("assistant_id");
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

assistant_deleted = openai.beta.assistants.delete("assistant_id")

puts(assistant_deleted)

#### description

Delete an assistant.

## /audio/speech

### post

#### operationId

createSpeech

#### tags

- Audio

#### summary

Create speech

#### requestBody

##### required

true

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/CreateSpeechRequest

#### responses

##### 200

###### description

OK

###### headers

####### Transfer-Encoding

######## schema

######### type

string

######## description

chunked

###### content

####### application/octet-stream

######## schema

######### type

string

######### format

binary

####### text/event-stream

######## schema

######### $ref

#/components/schemas/CreateSpeechResponseStreamEvent

#### x-oaiMeta

##### name

Create speech

##### group

audio

##### returns

The audio file content or a [stream of audio events](https://platform.openai.com/docs/api-reference/audio/speech-audio-delta-event).

##### examples

###### title

Default

###### request

####### curl

curl https://api.openai.com/v1/audio/speech \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4o-mini-tts",
    "input": "The quick brown fox jumped over the lazy dog.",
    "voice": "alloy"
  }' \
  --output speech.mp3


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
speech = client.audio.speech.create(
    input="input",
    model="string",
    voice="ash",
)
print(speech)
content = speech.read()
print(content)

####### javascript

import fs from "fs";
import path from "path";
import OpenAI from "openai";

const openai = new OpenAI();

const speechFile = path.resolve("./speech.mp3");

async function main() {
  const mp3 = await openai.audio.speech.create({
    model: "gpt-4o-mini-tts",
    voice: "alloy",
    input: "Today is a wonderful day to build something people love!",
  });
  console.log(speechFile);
  const buffer = Buffer.from(await mp3.arrayBuffer());
  await fs.promises.writeFile(speechFile, buffer);
}
main();


####### csharp

using System;
using System.IO;

using OpenAI.Audio;

AudioClient client = new(
    model: "gpt-4o-mini-tts",
    apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY")
);

BinaryData speech = client.GenerateSpeech(
    text: "The quick brown fox jumped over the lazy dog.",
    voice: GeneratedSpeechVoice.Alloy
);

using FileStream stream = File.OpenWrite("speech.mp3");
speech.ToStream().CopyTo(stream);


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const speech = await client.audio.speech.create({ input: 'input', model: 'string', voice: 'ash' });

console.log(speech);

const content = await speech.blob();
console.log(content);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  speech, err := client.Audio.Speech.New(context.TODO(), openai.AudioSpeechNewParams{
    Input: "input",
    Model: openai.SpeechModelTTS1,
    Voice: openai.AudioSpeechNewParamsVoiceAlloy,
  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", speech)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.http.HttpResponse;
import com.openai.models.audio.speech.SpeechCreateParams;
import com.openai.models.audio.speech.SpeechModel;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        SpeechCreateParams params = SpeechCreateParams.builder()
            .input("input")
            .model(SpeechModel.TTS_1)
            .voice(SpeechCreateParams.Voice.ALLOY)
            .build();
        HttpResponse speech = client.audio().speech().create(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

speech = openai.audio.speech.create(input: "input", model: :"tts-1", voice: :alloy)

puts(speech)

###### title

SSE Stream Format

###### request

####### curl

curl https://api.openai.com/v1/audio/speech \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4o-mini-tts",
    "input": "The quick brown fox jumped over the lazy dog.",
    "voice": "alloy",
    "stream_format": "sse"
  }'


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const speech = await client.audio.speech.create({ input: 'input', model: 'string', voice: 'ash' });

console.log(speech);

const content = await speech.blob();
console.log(content);

####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
speech = client.audio.speech.create(
    input="input",
    model="string",
    voice="ash",
)
print(speech)
content = speech.read()
print(content)

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  speech, err := client.Audio.Speech.New(context.TODO(), openai.AudioSpeechNewParams{
    Input: "input",
    Model: openai.SpeechModelTTS1,
    Voice: openai.AudioSpeechNewParamsVoiceAlloy,
  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", speech)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.http.HttpResponse;
import com.openai.models.audio.speech.SpeechCreateParams;
import com.openai.models.audio.speech.SpeechModel;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        SpeechCreateParams params = SpeechCreateParams.builder()
            .input("input")
            .model(SpeechModel.TTS_1)
            .voice(SpeechCreateParams.Voice.ALLOY)
            .build();
        HttpResponse speech = client.audio().speech().create(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

speech = openai.audio.speech.create(input: "input", model: :"tts-1", voice: :alloy)

puts(speech)


#### description

Generates audio from the input text.

## /audio/transcriptions

### post

#### operationId

createTranscription

#### tags

- Audio

#### summary

Create transcription

#### requestBody

##### required

true

##### content

###### multipart/form-data

####### schema

######## $ref

#/components/schemas/CreateTranscriptionRequest

#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### anyOf

########## $ref

#/components/schemas/CreateTranscriptionResponseJson

########## $ref

#/components/schemas/CreateTranscriptionResponseVerboseJson

########## x-stainless-skip

- go


####### text/event-stream

######## schema

######### $ref

#/components/schemas/CreateTranscriptionResponseStreamEvent

#### x-oaiMeta

##### name

Create transcription

##### group

audio

##### returns

The [transcription object](https://platform.openai.com/docs/api-reference/audio/json-object), a [verbose transcription object](https://platform.openai.com/docs/api-reference/audio/verbose-json-object) or a [stream of transcript events](https://platform.openai.com/docs/api-reference/audio/transcript-text-delta-event).

##### examples

###### title

Default

###### request

####### curl

curl https://api.openai.com/v1/audio/transcriptions \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: multipart/form-data" \
  -F file="@/path/to/file/audio.mp3" \
  -F model="gpt-4o-transcribe"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
transcription = client.audio.transcriptions.create(
    file=b"raw file contents",
    model="gpt-4o-transcribe",
)
print(transcription)

####### javascript

import fs from "fs";
import OpenAI from "openai";

const openai = new OpenAI();

async function main() {
  const transcription = await openai.audio.transcriptions.create({
    file: fs.createReadStream("audio.mp3"),
    model: "gpt-4o-transcribe",
  });

  console.log(transcription.text);
}
main();


####### csharp

using System;

using OpenAI.Audio;
string audioFilePath = "audio.mp3";

AudioClient client = new(
    model: "gpt-4o-transcribe",
    apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY")
);

AudioTranscription transcription = client.TranscribeAudio(audioFilePath);

Console.WriteLine($"{transcription.Text}");


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const transcription = await client.audio.transcriptions.create({
  file: fs.createReadStream('speech.mp3'),
  model: 'gpt-4o-transcribe',
});

console.log(transcription);

####### go

package main

import (
  "bytes"
  "context"
  "fmt"
  "io"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  transcription, err := client.Audio.Transcriptions.New(context.TODO(), openai.AudioTranscriptionNewParams{
    File: io.Reader(bytes.NewBuffer([]byte("some file contents"))),
    Model: openai.AudioModelWhisper1,
  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", transcription)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.audio.AudioModel;
import com.openai.models.audio.transcriptions.TranscriptionCreateParams;
import com.openai.models.audio.transcriptions.TranscriptionCreateResponse;
import java.io.ByteArrayInputStream;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        TranscriptionCreateParams params = TranscriptionCreateParams.builder()
            .file(ByteArrayInputStream("some content".getBytes()))
            .model(AudioModel.WHISPER_1)
            .build();
        TranscriptionCreateResponse transcription = client.audio().transcriptions().create(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

transcription = openai.audio.transcriptions.create(file: Pathname(__FILE__), model: :"whisper-1")

puts(transcription)

###### response

{
  "text": "Imagine the wildest idea that you've ever had, and you're curious about how it might scale to something that's a 100, a 1,000 times bigger. This is a place where you can get to do that.",
  "usage": {
    "type": "tokens",
    "input_tokens": 14,
    "input_token_details": {
      "text_tokens": 0,
      "audio_tokens": 14
    },
    "output_tokens": 45,
    "total_tokens": 59
  }
}


###### title

Streaming

###### request

####### curl

curl https://api.openai.com/v1/audio/transcriptions \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: multipart/form-data" \
  -F file="@/path/to/file/audio.mp3" \
  -F model="gpt-4o-mini-transcribe" \
  -F stream=true


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
transcription = client.audio.transcriptions.create(
    file=b"raw file contents",
    model="gpt-4o-transcribe",
)
print(transcription)

####### javascript

import fs from "fs";
import OpenAI from "openai";

const openai = new OpenAI();

const stream = await openai.audio.transcriptions.create({
  file: fs.createReadStream("audio.mp3"),
  model: "gpt-4o-mini-transcribe",
  stream: true,
});

for await (const event of stream) {
  console.log(event);
}


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const transcription = await client.audio.transcriptions.create({
  file: fs.createReadStream('speech.mp3'),
  model: 'gpt-4o-transcribe',
});

console.log(transcription);

####### go

package main

import (
  "bytes"
  "context"
  "fmt"
  "io"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  transcription, err := client.Audio.Transcriptions.New(context.TODO(), openai.AudioTranscriptionNewParams{
    File: io.Reader(bytes.NewBuffer([]byte("some file contents"))),
    Model: openai.AudioModelWhisper1,
  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", transcription)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.audio.AudioModel;
import com.openai.models.audio.transcriptions.TranscriptionCreateParams;
import com.openai.models.audio.transcriptions.TranscriptionCreateResponse;
import java.io.ByteArrayInputStream;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        TranscriptionCreateParams params = TranscriptionCreateParams.builder()
            .file(ByteArrayInputStream("some content".getBytes()))
            .model(AudioModel.WHISPER_1)
            .build();
        TranscriptionCreateResponse transcription = client.audio().transcriptions().create(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

transcription = openai.audio.transcriptions.create(file: Pathname(__FILE__), model: :"whisper-1")

puts(transcription)

###### response

data: {"type":"transcript.text.delta","delta":"I","logprobs":[{"token":"I","logprob":-0.00007588794,"bytes":[73]}]}

data: {"type":"transcript.text.delta","delta":" see","logprobs":[{"token":" see","logprob":-3.1281633e-7,"bytes":[32,115,101,101]}]}

data: {"type":"transcript.text.delta","delta":" skies","logprobs":[{"token":" skies","logprob":-2.3392786e-6,"bytes":[32,115,107,105,101,115]}]}

data: {"type":"transcript.text.delta","delta":" of","logprobs":[{"token":" of","logprob":-3.1281633e-7,"bytes":[32,111,102]}]}

data: {"type":"transcript.text.delta","delta":" blue","logprobs":[{"token":" blue","logprob":-1.0280384e-6,"bytes":[32,98,108,117,101]}]}

data: {"type":"transcript.text.delta","delta":" and","logprobs":[{"token":" and","logprob":-0.0005108566,"bytes":[32,97,110,100]}]}

data: {"type":"transcript.text.delta","delta":" clouds","logprobs":[{"token":" clouds","logprob":-1.9361265e-7,"bytes":[32,99,108,111,117,100,115]}]}

data: {"type":"transcript.text.delta","delta":" of","logprobs":[{"token":" of","logprob":-1.9361265e-7,"bytes":[32,111,102]}]}

data: {"type":"transcript.text.delta","delta":" white","logprobs":[{"token":" white","logprob":-7.89631e-7,"bytes":[32,119,104,105,116,101]}]}

data: {"type":"transcript.text.delta","delta":",","logprobs":[{"token":",","logprob":-0.0014890312,"bytes":[44]}]}

data: {"type":"transcript.text.delta","delta":" the","logprobs":[{"token":" the","logprob":-0.0110956915,"bytes":[32,116,104,101]}]}

data: {"type":"transcript.text.delta","delta":" bright","logprobs":[{"token":" bright","logprob":0.0,"bytes":[32,98,114,105,103,104,116]}]}

data: {"type":"transcript.text.delta","delta":" blessed","logprobs":[{"token":" blessed","logprob":-0.000045848617,"bytes":[32,98,108,101,115,115,101,100]}]}

data: {"type":"transcript.text.delta","delta":" days","logprobs":[{"token":" days","logprob":-0.000010802739,"bytes":[32,100,97,121,115]}]}

data: {"type":"transcript.text.delta","delta":",","logprobs":[{"token":",","logprob":-0.00001700133,"bytes":[44]}]}

data: {"type":"transcript.text.delta","delta":" the","logprobs":[{"token":" the","logprob":-0.0000118755715,"bytes":[32,116,104,101]}]}

data: {"type":"transcript.text.delta","delta":" dark","logprobs":[{"token":" dark","logprob":-5.5122365e-7,"bytes":[32,100,97,114,107]}]}

data: {"type":"transcript.text.delta","delta":" sacred","logprobs":[{"token":" sacred","logprob":-5.4385737e-6,"bytes":[32,115,97,99,114,101,100]}]}

data: {"type":"transcript.text.delta","delta":" nights","logprobs":[{"token":" nights","logprob":-4.00813e-6,"bytes":[32,110,105,103,104,116,115]}]}

data: {"type":"transcript.text.delta","delta":",","logprobs":[{"token":",","logprob":-0.0036910512,"bytes":[44]}]}

data: {"type":"transcript.text.delta","delta":" and","logprobs":[{"token":" and","logprob":-0.0031903093,"bytes":[32,97,110,100]}]}

data: {"type":"transcript.text.delta","delta":" I","logprobs":[{"token":" I","logprob":-1.504853e-6,"bytes":[32,73]}]}

data: {"type":"transcript.text.delta","delta":" think","logprobs":[{"token":" think","logprob":-4.3202e-7,"bytes":[32,116,104,105,110,107]}]}

data: {"type":"transcript.text.delta","delta":" to","logprobs":[{"token":" to","logprob":-1.9361265e-7,"bytes":[32,116,111]}]}

data: {"type":"transcript.text.delta","delta":" myself","logprobs":[{"token":" myself","logprob":-1.7432603e-6,"bytes":[32,109,121,115,101,108,102]}]}

data: {"type":"transcript.text.delta","delta":",","logprobs":[{"token":",","logprob":-0.29254505,"bytes":[44]}]}

data: {"type":"transcript.text.delta","delta":" what","logprobs":[{"token":" what","logprob":-0.016815351,"bytes":[32,119,104,97,116]}]}

data: {"type":"transcript.text.delta","delta":" a","logprobs":[{"token":" a","logprob":-3.1281633e-7,"bytes":[32,97]}]}

data: {"type":"transcript.text.delta","delta":" wonderful","logprobs":[{"token":" wonderful","logprob":-2.1008714e-6,"bytes":[32,119,111,110,100,101,114,102,117,108]}]}

data: {"type":"transcript.text.delta","delta":" world","logprobs":[{"token":" world","logprob":-8.180258e-6,"bytes":[32,119,111,114,108,100]}]}

data: {"type":"transcript.text.delta","delta":".","logprobs":[{"token":".","logprob":-0.014231676,"bytes":[46]}]}

data: {"type":"transcript.text.done","text":"I see skies of blue and clouds of white, the bright blessed days, the dark sacred nights, and I think to myself, what a wonderful world.","logprobs":[{"token":"I","logprob":-0.00007588794,"bytes":[73]},{"token":" see","logprob":-3.1281633e-7,"bytes":[32,115,101,101]},{"token":" skies","logprob":-2.3392786e-6,"bytes":[32,115,107,105,101,115]},{"token":" of","logprob":-3.1281633e-7,"bytes":[32,111,102]},{"token":" blue","logprob":-1.0280384e-6,"bytes":[32,98,108,117,101]},{"token":" and","logprob":-0.0005108566,"bytes":[32,97,110,100]},{"token":" clouds","logprob":-1.9361265e-7,"bytes":[32,99,108,111,117,100,115]},{"token":" of","logprob":-1.9361265e-7,"bytes":[32,111,102]},{"token":" white","logprob":-7.89631e-7,"bytes":[32,119,104,105,116,101]},{"token":",","logprob":-0.0014890312,"bytes":[44]},{"token":" the","logprob":-0.0110956915,"bytes":[32,116,104,101]},{"token":" bright","logprob":0.0,"bytes":[32,98,114,105,103,104,116]},{"token":" blessed","logprob":-0.000045848617,"bytes":[32,98,108,101,115,115,101,100]},{"token":" days","logprob":-0.000010802739,"bytes":[32,100,97,121,115]},{"token":",","logprob":-0.00001700133,"bytes":[44]},{"token":" the","logprob":-0.0000118755715,"bytes":[32,116,104,101]},{"token":" dark","logprob":-5.5122365e-7,"bytes":[32,100,97,114,107]},{"token":" sacred","logprob":-5.4385737e-6,"bytes":[32,115,97,99,114,101,100]},{"token":" nights","logprob":-4.00813e-6,"bytes":[32,110,105,103,104,116,115]},{"token":",","logprob":-0.0036910512,"bytes":[44]},{"token":" and","logprob":-0.0031903093,"bytes":[32,97,110,100]},{"token":" I","logprob":-1.504853e-6,"bytes":[32,73]},{"token":" think","logprob":-4.3202e-7,"bytes":[32,116,104,105,110,107]},{"token":" to","logprob":-1.9361265e-7,"bytes":[32,116,111]},{"token":" myself","logprob":-1.7432603e-6,"bytes":[32,109,121,115,101,108,102]},{"token":",","logprob":-0.29254505,"bytes":[44]},{"token":" what","logprob":-0.016815351,"bytes":[32,119,104,97,116]},{"token":" a","logprob":-3.1281633e-7,"bytes":[32,97]},{"token":" wonderful","logprob":-2.1008714e-6,"bytes":[32,119,111,110,100,101,114,102,117,108]},{"token":" world","logprob":-8.180258e-6,"bytes":[32,119,111,114,108,100]},{"token":".","logprob":-0.014231676,"bytes":[46]}],"usage":{"input_tokens":14,"input_token_details":{"text_tokens":0,"audio_tokens":14},"output_tokens":45,"total_tokens":59}}


###### title

Logprobs

###### request

####### curl

curl https://api.openai.com/v1/audio/transcriptions \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: multipart/form-data" \
  -F file="@/path/to/file/audio.mp3" \
  -F "include[]=logprobs" \
  -F model="gpt-4o-transcribe" \
  -F response_format="json"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
transcription = client.audio.transcriptions.create(
    file=b"raw file contents",
    model="gpt-4o-transcribe",
)
print(transcription)

####### javascript

import fs from "fs";
import OpenAI from "openai";

const openai = new OpenAI();

async function main() {
  const transcription = await openai.audio.transcriptions.create({
    file: fs.createReadStream("audio.mp3"),
    model: "gpt-4o-transcribe",
    response_format: "json",
    include: ["logprobs"]
  });

  console.log(transcription);
}
main();


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const transcription = await client.audio.transcriptions.create({
  file: fs.createReadStream('speech.mp3'),
  model: 'gpt-4o-transcribe',
});

console.log(transcription);

####### go

package main

import (
  "bytes"
  "context"
  "fmt"
  "io"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  transcription, err := client.Audio.Transcriptions.New(context.TODO(), openai.AudioTranscriptionNewParams{
    File: io.Reader(bytes.NewBuffer([]byte("some file contents"))),
    Model: openai.AudioModelWhisper1,
  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", transcription)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.audio.AudioModel;
import com.openai.models.audio.transcriptions.TranscriptionCreateParams;
import com.openai.models.audio.transcriptions.TranscriptionCreateResponse;
import java.io.ByteArrayInputStream;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        TranscriptionCreateParams params = TranscriptionCreateParams.builder()
            .file(ByteArrayInputStream("some content".getBytes()))
            .model(AudioModel.WHISPER_1)
            .build();
        TranscriptionCreateResponse transcription = client.audio().transcriptions().create(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

transcription = openai.audio.transcriptions.create(file: Pathname(__FILE__), model: :"whisper-1")

puts(transcription)

###### response

{
  "text": "Hey, my knee is hurting and I want to see the doctor tomorrow ideally.",
  "logprobs": [
    { "token": "Hey", "logprob": -1.0415299, "bytes": [72, 101, 121] },
    { "token": ",", "logprob": -9.805982e-5, "bytes": [44] },
    { "token": " my", "logprob": -0.00229799, "bytes": [32, 109, 121] },
    {
      "token": " knee",
      "logprob": -4.7159858e-5,
      "bytes": [32, 107, 110, 101, 101]
    },
    { "token": " is", "logprob": -0.043909557, "bytes": [32, 105, 115] },
    {
      "token": " hurting",
      "logprob": -1.1041146e-5,
      "bytes": [32, 104, 117, 114, 116, 105, 110, 103]
    },
    { "token": " and", "logprob": -0.011076359, "bytes": [32, 97, 110, 100] },
    { "token": " I", "logprob": -5.3193703e-6, "bytes": [32, 73] },
    {
      "token": " want",
      "logprob": -0.0017156356,
      "bytes": [32, 119, 97, 110, 116]
    },
    { "token": " to", "logprob": -7.89631e-7, "bytes": [32, 116, 111] },
    { "token": " see", "logprob": -5.5122365e-7, "bytes": [32, 115, 101, 101] },
    { "token": " the", "logprob": -0.0040786397, "bytes": [32, 116, 104, 101] },
    {
      "token": " doctor",
      "logprob": -2.3392786e-6,
      "bytes": [32, 100, 111, 99, 116, 111, 114]
    },
    {
      "token": " tomorrow",
      "logprob": -7.89631e-7,
      "bytes": [32, 116, 111, 109, 111, 114, 114, 111, 119]
    },
    {
      "token": " ideally",
      "logprob": -0.5800861,
      "bytes": [32, 105, 100, 101, 97, 108, 108, 121]
    },
    { "token": ".", "logprob": -0.00011093382, "bytes": [46] }
  ],
  "usage": {
    "type": "tokens",
    "input_tokens": 14,
    "input_token_details": {
      "text_tokens": 0,
      "audio_tokens": 14
    },
    "output_tokens": 45,
    "total_tokens": 59
  }
}


###### title

Word timestamps

###### request

####### curl

curl https://api.openai.com/v1/audio/transcriptions \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: multipart/form-data" \
  -F file="@/path/to/file/audio.mp3" \
  -F "timestamp_granularities[]=word" \
  -F model="whisper-1" \
  -F response_format="verbose_json"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
transcription = client.audio.transcriptions.create(
    file=b"raw file contents",
    model="gpt-4o-transcribe",
)
print(transcription)

####### javascript

import fs from "fs";
import OpenAI from "openai";

const openai = new OpenAI();

async function main() {
  const transcription = await openai.audio.transcriptions.create({
    file: fs.createReadStream("audio.mp3"),
    model: "whisper-1",
    response_format: "verbose_json",
    timestamp_granularities: ["word"]
  });

  console.log(transcription.text);
}
main();


####### csharp

using System;

using OpenAI.Audio;

string audioFilePath = "audio.mp3";

AudioClient client = new(
    model: "whisper-1",
    apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY")
);

AudioTranscriptionOptions options = new()
{
    ResponseFormat = AudioTranscriptionFormat.Verbose,
    TimestampGranularities = AudioTimestampGranularities.Word,
};

AudioTranscription transcription = client.TranscribeAudio(audioFilePath, options);

Console.WriteLine($"{transcription.Text}");


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const transcription = await client.audio.transcriptions.create({
  file: fs.createReadStream('speech.mp3'),
  model: 'gpt-4o-transcribe',
});

console.log(transcription);

####### go

package main

import (
  "bytes"
  "context"
  "fmt"
  "io"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  transcription, err := client.Audio.Transcriptions.New(context.TODO(), openai.AudioTranscriptionNewParams{
    File: io.Reader(bytes.NewBuffer([]byte("some file contents"))),
    Model: openai.AudioModelWhisper1,
  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", transcription)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.audio.AudioModel;
import com.openai.models.audio.transcriptions.TranscriptionCreateParams;
import com.openai.models.audio.transcriptions.TranscriptionCreateResponse;
import java.io.ByteArrayInputStream;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        TranscriptionCreateParams params = TranscriptionCreateParams.builder()
            .file(ByteArrayInputStream("some content".getBytes()))
            .model(AudioModel.WHISPER_1)
            .build();
        TranscriptionCreateResponse transcription = client.audio().transcriptions().create(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

transcription = openai.audio.transcriptions.create(file: Pathname(__FILE__), model: :"whisper-1")

puts(transcription)

###### response

{
  "task": "transcribe",
  "language": "english",
  "duration": 8.470000267028809,
  "text": "The beach was a popular spot on a hot summer day. People were swimming in the ocean, building sandcastles, and playing beach volleyball.",
  "words": [
    {
      "word": "The",
      "start": 0.0,
      "end": 0.23999999463558197
    },
    ...
    {
      "word": "volleyball",
      "start": 7.400000095367432,
      "end": 7.900000095367432
    }
  ],
  "usage": {
    "type": "duration",
    "seconds": 9
  }
}


###### title

Segment timestamps

###### request

####### curl

curl https://api.openai.com/v1/audio/transcriptions \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: multipart/form-data" \
  -F file="@/path/to/file/audio.mp3" \
  -F "timestamp_granularities[]=segment" \
  -F model="whisper-1" \
  -F response_format="verbose_json"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
transcription = client.audio.transcriptions.create(
    file=b"raw file contents",
    model="gpt-4o-transcribe",
)
print(transcription)

####### javascript

import fs from "fs";
import OpenAI from "openai";

const openai = new OpenAI();

async function main() {
  const transcription = await openai.audio.transcriptions.create({
    file: fs.createReadStream("audio.mp3"),
    model: "whisper-1",
    response_format: "verbose_json",
    timestamp_granularities: ["segment"]
  });

  console.log(transcription.text);
}
main();


####### csharp

using System;

using OpenAI.Audio;

string audioFilePath = "audio.mp3";

AudioClient client = new(
    model: "whisper-1",
    apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY")
);

AudioTranscriptionOptions options = new()
{
    ResponseFormat = AudioTranscriptionFormat.Verbose,
    TimestampGranularities = AudioTimestampGranularities.Segment,
};

AudioTranscription transcription = client.TranscribeAudio(audioFilePath, options);

Console.WriteLine($"{transcription.Text}");


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const transcription = await client.audio.transcriptions.create({
  file: fs.createReadStream('speech.mp3'),
  model: 'gpt-4o-transcribe',
});

console.log(transcription);

####### go

package main

import (
  "bytes"
  "context"
  "fmt"
  "io"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  transcription, err := client.Audio.Transcriptions.New(context.TODO(), openai.AudioTranscriptionNewParams{
    File: io.Reader(bytes.NewBuffer([]byte("some file contents"))),
    Model: openai.AudioModelWhisper1,
  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", transcription)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.audio.AudioModel;
import com.openai.models.audio.transcriptions.TranscriptionCreateParams;
import com.openai.models.audio.transcriptions.TranscriptionCreateResponse;
import java.io.ByteArrayInputStream;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        TranscriptionCreateParams params = TranscriptionCreateParams.builder()
            .file(ByteArrayInputStream("some content".getBytes()))
            .model(AudioModel.WHISPER_1)
            .build();
        TranscriptionCreateResponse transcription = client.audio().transcriptions().create(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

transcription = openai.audio.transcriptions.create(file: Pathname(__FILE__), model: :"whisper-1")

puts(transcription)

###### response

{
  "task": "transcribe",
  "language": "english",
  "duration": 8.470000267028809,
  "text": "The beach was a popular spot on a hot summer day. People were swimming in the ocean, building sandcastles, and playing beach volleyball.",
  "segments": [
    {
      "id": 0,
      "seek": 0,
      "start": 0.0,
      "end": 3.319999933242798,
      "text": " The beach was a popular spot on a hot summer day.",
      "tokens": [
        50364, 440, 7534, 390, 257, 3743, 4008, 322, 257, 2368, 4266, 786, 13, 50530
      ],
      "temperature": 0.0,
      "avg_logprob": -0.2860786020755768,
      "compression_ratio": 1.2363636493682861,
      "no_speech_prob": 0.00985979475080967
    },
    ...
  ],
  "usage": {
    "type": "duration",
    "seconds": 9
  }
}



#### description

Transcribes audio into the input language.

## /audio/translations

### post

#### operationId

createTranslation

#### tags

- Audio

#### summary

Create translation

#### requestBody

##### required

true

##### content

###### multipart/form-data

####### schema

######## $ref

#/components/schemas/CreateTranslationRequest

#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### anyOf

########## $ref

#/components/schemas/CreateTranslationResponseJson

########## $ref

#/components/schemas/CreateTranslationResponseVerboseJson

########## x-stainless-skip

- go


#### x-oaiMeta

##### name

Create translation

##### group

audio

##### returns

The translated text.

##### examples

###### response

{
  "text": "Hello, my name is Wolfgang and I come from Germany. Where are you heading today?"
}


###### request

####### curl

curl https://api.openai.com/v1/audio/translations \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: multipart/form-data" \
  -F file="@/path/to/file/german.m4a" \
  -F model="whisper-1"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
translation = client.audio.translations.create(
    file=b"raw file contents",
    model="whisper-1",
)
print(translation)

####### javascript

import fs from "fs";
import OpenAI from "openai";

const openai = new OpenAI();

async function main() {
    const translation = await openai.audio.translations.create({
        file: fs.createReadStream("speech.mp3"),
        model: "whisper-1",
    });

    console.log(translation.text);
}
main();


####### csharp

using System;

using OpenAI.Audio;

string audioFilePath = "audio.mp3";

AudioClient client = new(
    model: "whisper-1",
    apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY")
);

AudioTranscription transcription = client.TranscribeAudio(audioFilePath);

Console.WriteLine($"{transcription.Text}");


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const translation = await client.audio.translations.create({
  file: fs.createReadStream('speech.mp3'),
  model: 'whisper-1',
});

console.log(translation);

####### go

package main

import (
  "bytes"
  "context"
  "fmt"
  "io"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  translation, err := client.Audio.Translations.New(context.TODO(), openai.AudioTranslationNewParams{
    File: io.Reader(bytes.NewBuffer([]byte("some file contents"))),
    Model: openai.AudioModelWhisper1,
  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", translation)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.audio.AudioModel;
import com.openai.models.audio.translations.TranslationCreateParams;
import com.openai.models.audio.translations.TranslationCreateResponse;
import java.io.ByteArrayInputStream;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        TranslationCreateParams params = TranslationCreateParams.builder()
            .file(ByteArrayInputStream("some content".getBytes()))
            .model(AudioModel.WHISPER_1)
            .build();
        TranslationCreateResponse translation = client.audio().translations().create(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

translation = openai.audio.translations.create(file: Pathname(__FILE__), model: :"whisper-1")

puts(translation)

#### description

Translates audio into English.

## /batches

### post

#### summary

Create batch

#### operationId

createBatch

#### tags

- Batch

#### requestBody

##### required

true

##### content

###### application/json

####### schema

######## type

object

######## required

- input_file_id
- endpoint
- completion_window

######## properties

######### input_file_id

########## type

string

########## description

The ID of an uploaded file that contains requests for the new batch.

See [upload file](https://platform.openai.com/docs/api-reference/files/create) for how to upload a file.

Your input file must be formatted as a [JSONL file](https://platform.openai.com/docs/api-reference/batch/request-input), and must be uploaded with the purpose `batch`. The file can contain up to 50,000 requests, and can be up to 200 MB in size.


######### endpoint

########## type

string

########## enum

- /v1/responses
- /v1/chat/completions
- /v1/embeddings
- /v1/completions

########## description

The endpoint to be used for all requests in the batch. Currently `/v1/responses`, `/v1/chat/completions`, `/v1/embeddings`, and `/v1/completions` are supported. Note that `/v1/embeddings` batches are also restricted to a maximum of 50,000 embedding inputs across all requests in the batch.

######### completion_window

########## type

string

########## enum

- 24h

########## description

The time frame within which the batch should be processed. Currently only `24h` is supported.

######### metadata

########## $ref

#/components/schemas/Metadata

######### output_expires_after

########## $ref

#/components/schemas/BatchFileExpirationAfter

#### responses

##### 200

###### description

Batch created successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/Batch

#### x-oaiMeta

##### name

Create batch

##### group

batch

##### returns

The created [Batch](https://platform.openai.com/docs/api-reference/batch/object) object.

##### examples

###### response

{
  "id": "batch_abc123",
  "object": "batch",
  "endpoint": "/v1/chat/completions",
  "errors": null,
  "input_file_id": "file-abc123",
  "completion_window": "24h",
  "status": "validating",
  "output_file_id": null,
  "error_file_id": null,
  "created_at": 1711471533,
  "in_progress_at": null,
  "expires_at": null,
  "finalizing_at": null,
  "completed_at": null,
  "failed_at": null,
  "expired_at": null,
  "cancelling_at": null,
  "cancelled_at": null,
  "request_counts": {
    "total": 0,
    "completed": 0,
    "failed": 0
  },
  "metadata": {
    "customer_id": "user_123456789",
    "batch_description": "Nightly eval job",
  }
}


###### request

####### curl

curl https://api.openai.com/v1/batches \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "input_file_id": "file-abc123",
    "endpoint": "/v1/chat/completions",
    "completion_window": "24h"
  }'


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
batch = client.batches.create(
    completion_window="24h",
    endpoint="/v1/responses",
    input_file_id="input_file_id",
)
print(batch.id)

####### node

import OpenAI from "openai";

const openai = new OpenAI();

async function main() {
  const batch = await openai.batches.create({
    input_file_id: "file-abc123",
    endpoint: "/v1/chat/completions",
    completion_window: "24h"
  });

  console.log(batch);
}

main();


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const batch = await client.batches.create({
  completion_window: '24h',
  endpoint: '/v1/responses',
  input_file_id: 'input_file_id',
});

console.log(batch.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  batch, err := client.Batches.New(context.TODO(), openai.BatchNewParams{
    CompletionWindow: openai.BatchNewParamsCompletionWindow24h,
    Endpoint: openai.BatchNewParamsEndpointV1Responses,
    InputFileID: "input_file_id",
  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", batch.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.batches.Batch;
import com.openai.models.batches.BatchCreateParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        BatchCreateParams params = BatchCreateParams.builder()
            .completionWindow(BatchCreateParams.CompletionWindow._24H)
            .endpoint(BatchCreateParams.Endpoint.V1_RESPONSES)
            .inputFileId("input_file_id")
            .build();
        Batch batch = client.batches().create(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

batch = openai.batches.create(
  completion_window: :"24h",
  endpoint: :"/v1/responses",
  input_file_id: "input_file_id"
)

puts(batch)

#### description

Creates and executes a batch from an uploaded file of requests

### get

#### operationId

listBatches

#### tags

- Batch

#### summary

List batch

#### parameters

##### in

query

##### name

after

##### required

false

##### schema

###### type

string

##### description

A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list.


##### name

limit

##### in

query

##### description

A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20.


##### required

false

##### schema

###### type

integer

###### default

20


#### responses

##### 200

###### description

Batch listed successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ListBatchesResponse

#### x-oaiMeta

##### name

List batch

##### group

batch

##### returns

A list of paginated [Batch](https://platform.openai.com/docs/api-reference/batch/object) objects.

##### examples

###### response

{
  "object": "list",
  "data": [
    {
      "id": "batch_abc123",
      "object": "batch",
      "endpoint": "/v1/chat/completions",
      "errors": null,
      "input_file_id": "file-abc123",
      "completion_window": "24h",
      "status": "completed",
      "output_file_id": "file-cvaTdG",
      "error_file_id": "file-HOWS94",
      "created_at": 1711471533,
      "in_progress_at": 1711471538,
      "expires_at": 1711557933,
      "finalizing_at": 1711493133,
      "completed_at": 1711493163,
      "failed_at": null,
      "expired_at": null,
      "cancelling_at": null,
      "cancelled_at": null,
      "request_counts": {
        "total": 100,
        "completed": 95,
        "failed": 5
      },
      "metadata": {
        "customer_id": "user_123456789",
        "batch_description": "Nightly job",
      }
    },
    { ... },
  ],
  "first_id": "batch_abc123",
  "last_id": "batch_abc456",
  "has_more": true
}


###### request

####### curl

curl https://api.openai.com/v1/batches?limit=2 \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
page = client.batches.list()
page = page.data[0]
print(page.id)

####### node

import OpenAI from "openai";

const openai = new OpenAI();

async function main() {
  const list = await openai.batches.list();

  for await (const batch of list) {
    console.log(batch);
  }
}

main();


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

// Automatically fetches more pages as needed.
for await (const batch of client.batches.list()) {
  console.log(batch.id);
}

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  page, err := client.Batches.List(context.TODO(), openai.BatchListParams{

  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", page)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.batches.BatchListPage;
import com.openai.models.batches.BatchListParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        BatchListPage page = client.batches().list();
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

page = openai.batches.list

puts(page)

#### description

List your organization's batches.

## /batches/{batch_id}

### get

#### operationId

retrieveBatch

#### tags

- Batch

#### summary

Retrieve batch

#### parameters

##### in

path

##### name

batch_id

##### required

true

##### schema

###### type

string

##### description

The ID of the batch to retrieve.


#### responses

##### 200

###### description

Batch retrieved successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/Batch

#### x-oaiMeta

##### name

Retrieve batch

##### group

batch

##### returns

The [Batch](https://platform.openai.com/docs/api-reference/batch/object) object matching the specified ID.

##### examples

###### response

{
  "id": "batch_abc123",
  "object": "batch",
  "endpoint": "/v1/completions",
  "errors": null,
  "input_file_id": "file-abc123",
  "completion_window": "24h",
  "status": "completed",
  "output_file_id": "file-cvaTdG",
  "error_file_id": "file-HOWS94",
  "created_at": 1711471533,
  "in_progress_at": 1711471538,
  "expires_at": 1711557933,
  "finalizing_at": 1711493133,
  "completed_at": 1711493163,
  "failed_at": null,
  "expired_at": null,
  "cancelling_at": null,
  "cancelled_at": null,
  "request_counts": {
    "total": 100,
    "completed": 95,
    "failed": 5
  },
  "metadata": {
    "customer_id": "user_123456789",
    "batch_description": "Nightly eval job",
  }
}


###### request

####### curl

curl https://api.openai.com/v1/batches/batch_abc123 \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
batch = client.batches.retrieve(
    "batch_id",
)
print(batch.id)

####### node

import OpenAI from "openai";

const openai = new OpenAI();

async function main() {
  const batch = await openai.batches.retrieve("batch_abc123");

  console.log(batch);
}

main();


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const batch = await client.batches.retrieve('batch_id');

console.log(batch.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  batch, err := client.Batches.Get(context.TODO(), "batch_id")
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", batch.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.batches.Batch;
import com.openai.models.batches.BatchRetrieveParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        Batch batch = client.batches().retrieve("batch_id");
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

batch = openai.batches.retrieve("batch_id")

puts(batch)

#### description

Retrieves a batch.

## /batches/{batch_id}/cancel

### post

#### operationId

cancelBatch

#### tags

- Batch

#### summary

Cancel batch

#### parameters

##### in

path

##### name

batch_id

##### required

true

##### schema

###### type

string

##### description

The ID of the batch to cancel.


#### responses

##### 200

###### description

Batch is cancelling. Returns the cancelling batch's details.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/Batch

#### x-oaiMeta

##### name

Cancel batch

##### group

batch

##### returns

The [Batch](https://platform.openai.com/docs/api-reference/batch/object) object matching the specified ID.

##### examples

###### response

{
  "id": "batch_abc123",
  "object": "batch",
  "endpoint": "/v1/chat/completions",
  "errors": null,
  "input_file_id": "file-abc123",
  "completion_window": "24h",
  "status": "cancelling",
  "output_file_id": null,
  "error_file_id": null,
  "created_at": 1711471533,
  "in_progress_at": 1711471538,
  "expires_at": 1711557933,
  "finalizing_at": null,
  "completed_at": null,
  "failed_at": null,
  "expired_at": null,
  "cancelling_at": 1711475133,
  "cancelled_at": null,
  "request_counts": {
    "total": 100,
    "completed": 23,
    "failed": 1
  },
  "metadata": {
    "customer_id": "user_123456789",
    "batch_description": "Nightly eval job",
  }
}


###### request

####### curl

curl https://api.openai.com/v1/batches/batch_abc123/cancel \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -X POST


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
batch = client.batches.cancel(
    "batch_id",
)
print(batch.id)

####### node

import OpenAI from "openai";

const openai = new OpenAI();

async function main() {
  const batch = await openai.batches.cancel("batch_abc123");

  console.log(batch);
}

main();


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const batch = await client.batches.cancel('batch_id');

console.log(batch.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  batch, err := client.Batches.Cancel(context.TODO(), "batch_id")
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", batch.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.batches.Batch;
import com.openai.models.batches.BatchCancelParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        Batch batch = client.batches().cancel("batch_id");
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

batch = openai.batches.cancel("batch_id")

puts(batch)

#### description

Cancels an in-progress batch. The batch will be in status `cancelling` for up to 10 minutes, before changing to `cancelled`, where it will have partial results (if any) available in the output file.

## /chat/completions

### get

#### operationId

listChatCompletions

#### tags

- Chat

#### summary

List Chat Completions

#### parameters

##### name

model

##### in

query

##### description

The model used to generate the Chat Completions.

##### required

false

##### schema

###### type

string

##### name

metadata

##### in

query

##### description

A list of metadata keys to filter the Chat Completions by. Example:

`metadata[key1]=value1&metadata[key2]=value2`


##### required

false

##### schema

###### $ref

#/components/schemas/Metadata

##### name

after

##### in

query

##### description

Identifier for the last chat completion from the previous pagination request.

##### required

false

##### schema

###### type

string

##### name

limit

##### in

query

##### description

Number of Chat Completions to retrieve.

##### required

false

##### schema

###### type

integer

###### default

20

##### name

order

##### in

query

##### description

Sort order for Chat Completions by timestamp. Use `asc` for ascending order or `desc` for descending order. Defaults to `asc`.

##### required

false

##### schema

###### type

string

###### enum

- asc
- desc

###### default

asc


#### responses

##### 200

###### description

A list of Chat Completions

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ChatCompletionList

#### x-oaiMeta

##### name

List Chat Completions

##### group

chat

##### returns

A list of [Chat Completions](https://platform.openai.com/docs/api-reference/chat/list-object) matching the specified filters.

##### path

list

##### examples

###### response

{
  "object": "list",
  "data": [
    {
      "object": "chat.completion",
      "id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2",
      "model": "gpt-4.1-2025-04-14",
      "created": 1738960610,
      "request_id": "req_ded8ab984ec4bf840f37566c1011c417",
      "tool_choice": null,
      "usage": {
        "total_tokens": 31,
        "completion_tokens": 18,
        "prompt_tokens": 13
      },
      "seed": 4944116822809979520,
      "top_p": 1.0,
      "temperature": 1.0,
      "presence_penalty": 0.0,
      "frequency_penalty": 0.0,
      "system_fingerprint": "fp_50cad350e4",
      "input_user": null,
      "service_tier": "default",
      "tools": null,
      "metadata": {},
      "choices": [
        {
          "index": 0,
          "message": {
            "content": "Mind of circuits hum,  \nLearning patterns in silenceâ  \nFuture's quiet spark.",
            "role": "assistant",
            "tool_calls": null,
            "function_call": null
          },
          "finish_reason": "stop",
          "logprobs": null
        }
      ],
      "response_format": null
    }
  ],
  "first_id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2",
  "last_id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2",
  "has_more": false
}


###### request

####### curl

curl https://api.openai.com/v1/chat/completions \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
page = client.chat.completions.list()
page = page.data[0]
print(page.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

// Automatically fetches more pages as needed.
for await (const chatCompletion of client.chat.completions.list()) {
  console.log(chatCompletion.id);
}

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  page, err := client.Chat.Completions.List(context.TODO(), openai.ChatCompletionListParams{

  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", page)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.chat.completions.ChatCompletionListPage;
import com.openai.models.chat.completions.ChatCompletionListParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        ChatCompletionListPage page = client.chat().completions().list();
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

page = openai.chat.completions.list

puts(page)

#### description

List stored Chat Completions. Only Chat Completions that have been stored
with the `store` parameter set to `true` will be returned.


### post

#### operationId

createChatCompletion

#### tags

- Chat

#### summary

Create chat completion

#### requestBody

##### required

true

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/CreateChatCompletionRequest

#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/CreateChatCompletionResponse

####### text/event-stream

######## schema

######### $ref

#/components/schemas/CreateChatCompletionStreamResponse

#### x-oaiMeta

##### name

Create chat completion

##### group

chat

##### returns

Returns a [chat completion](https://platform.openai.com/docs/api-reference/chat/object) object, or a streamed sequence of [chat completion chunk](https://platform.openai.com/docs/api-reference/chat/streaming) objects if the request is streamed.


##### path

create

##### examples

###### title

Default

###### request

####### curl

curl https://api.openai.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "VAR_chat_model_id",
    "messages": [
      {
        "role": "developer",
        "content": "You are a helpful assistant."
      },
      {
        "role": "user",
        "content": "Hello!"
      }
    ]
  }'


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
chat_completion = client.chat.completions.create(
    messages=[{
        "content": "string",
        "role": "developer",
    }],
    model="gpt-4o",
)
print(chat_completion)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const chatCompletion = await client.chat.completions.create({
  messages: [{ content: 'string', role: 'developer' }],
  model: 'gpt-4o',
});

console.log(chatCompletion);

####### csharp

using System;
using System.Collections.Generic;

using OpenAI.Chat;

ChatClient client = new(
    model: "gpt-4.1",
    apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY")
);

List<ChatMessage> messages =
[
    new SystemChatMessage("You are a helpful assistant."),
    new UserChatMessage("Hello!")
];

ChatCompletion completion = client.CompleteChat(messages);

Console.WriteLine(completion.Content[0].Text);


####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
  "github.com/openai/openai-go/shared"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  chatCompletion, err := client.Chat.Completions.New(context.TODO(), openai.ChatCompletionNewParams{
    Messages: []openai.ChatCompletionMessageParamUnion{openai.ChatCompletionMessageParamUnion{
      OfDeveloper: &openai.ChatCompletionDeveloperMessageParam{
        Content: openai.ChatCompletionDeveloperMessageParamContentUnion{
          OfString: openai.String("string"),
        },
      },
    }},
    Model: shared.ChatModelGPT5,
  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", chatCompletion)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.ChatModel;
import com.openai.models.chat.completions.ChatCompletion;
import com.openai.models.chat.completions.ChatCompletionCreateParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
            .addDeveloperMessage("string")
            .model(ChatModel.GPT_5)
            .build();
        ChatCompletion chatCompletion = client.chat().completions().create(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

chat_completion = openai.chat.completions.create(messages: [{content: "string", role: :developer}], model: :"gpt-5")

puts(chat_completion)

###### response

{
  "id": "chatcmpl-B9MBs8CjcvOU2jLn4n570S5qMJKcT",
  "object": "chat.completion",
  "created": 1741569952,
  "model": "gpt-4.1-2025-04-14",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Hello! How can I assist you today?",
        "refusal": null,
        "annotations": []
      },
      "logprobs": null,
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 19,
    "completion_tokens": 10,
    "total_tokens": 29,
    "prompt_tokens_details": {
      "cached_tokens": 0,
      "audio_tokens": 0
    },
    "completion_tokens_details": {
      "reasoning_tokens": 0,
      "audio_tokens": 0,
      "accepted_prediction_tokens": 0,
      "rejected_prediction_tokens": 0
    }
  },
  "service_tier": "default"
}


###### title

Image input

###### request

####### curl

curl https://api.openai.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "gpt-4.1",
    "messages": [
      {
        "role": "user",
        "content": [
          {
            "type": "text",
            "text": "What is in this image?"
          },
          {
            "type": "image_url",
            "image_url": {
              "url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg"
            }
          }
        ]
      }
    ],
    "max_tokens": 300
  }'


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
chat_completion = client.chat.completions.create(
    messages=[{
        "content": "string",
        "role": "developer",
    }],
    model="gpt-4o",
)
print(chat_completion)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const chatCompletion = await client.chat.completions.create({
  messages: [{ content: 'string', role: 'developer' }],
  model: 'gpt-4o',
});

console.log(chatCompletion);

####### csharp

using System;
using System.Collections.Generic;

using OpenAI.Chat;

ChatClient client = new(
    model: "gpt-4.1",
    apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY")
);

List<ChatMessage> messages =
[
    new UserChatMessage(
    [
        ChatMessageContentPart.CreateTextPart("What's in this image?"),
        ChatMessageContentPart.CreateImagePart(new Uri("https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg"))
    ])
];

ChatCompletion completion = client.CompleteChat(messages);

Console.WriteLine(completion.Content[0].Text);


####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
  "github.com/openai/openai-go/shared"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  chatCompletion, err := client.Chat.Completions.New(context.TODO(), openai.ChatCompletionNewParams{
    Messages: []openai.ChatCompletionMessageParamUnion{openai.ChatCompletionMessageParamUnion{
      OfDeveloper: &openai.ChatCompletionDeveloperMessageParam{
        Content: openai.ChatCompletionDeveloperMessageParamContentUnion{
          OfString: openai.String("string"),
        },
      },
    }},
    Model: shared.ChatModelGPT5,
  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", chatCompletion)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.ChatModel;
import com.openai.models.chat.completions.ChatCompletion;
import com.openai.models.chat.completions.ChatCompletionCreateParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
            .addDeveloperMessage("string")
            .model(ChatModel.GPT_5)
            .build();
        ChatCompletion chatCompletion = client.chat().completions().create(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

chat_completion = openai.chat.completions.create(messages: [{content: "string", role: :developer}], model: :"gpt-5")

puts(chat_completion)

###### response

{
  "id": "chatcmpl-B9MHDbslfkBeAs8l4bebGdFOJ6PeG",
  "object": "chat.completion",
  "created": 1741570283,
  "model": "gpt-4.1-2025-04-14",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "The image shows a wooden boardwalk path running through a lush green field or meadow. The sky is bright blue with some scattered clouds, giving the scene a serene and peaceful atmosphere. Trees and shrubs are visible in the background.",
        "refusal": null,
        "annotations": []
      },
      "logprobs": null,
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 1117,
    "completion_tokens": 46,
    "total_tokens": 1163,
    "prompt_tokens_details": {
      "cached_tokens": 0,
      "audio_tokens": 0
    },
    "completion_tokens_details": {
      "reasoning_tokens": 0,
      "audio_tokens": 0,
      "accepted_prediction_tokens": 0,
      "rejected_prediction_tokens": 0
    }
  },
  "service_tier": "default"
}


###### title

Streaming

###### request

####### curl

curl https://api.openai.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "VAR_chat_model_id",
    "messages": [
      {
        "role": "developer",
        "content": "You are a helpful assistant."
      },
      {
        "role": "user",
        "content": "Hello!"
      }
    ],
    "stream": true
  }'


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
chat_completion = client.chat.completions.create(
    messages=[{
        "content": "string",
        "role": "developer",
    }],
    model="gpt-4o",
)
print(chat_completion)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const chatCompletion = await client.chat.completions.create({
  messages: [{ content: 'string', role: 'developer' }],
  model: 'gpt-4o',
});

console.log(chatCompletion);

####### csharp

using System;
using System.ClientModel;
using System.Collections.Generic;
using System.Threading.Tasks;

using OpenAI.Chat;

ChatClient client = new(
    model: "gpt-4.1",
    apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY")
);

List<ChatMessage> messages =
[
    new SystemChatMessage("You are a helpful assistant."),
    new UserChatMessage("Hello!")
];

AsyncCollectionResult<StreamingChatCompletionUpdate> completionUpdates = client.CompleteChatStreamingAsync(messages);

await foreach (StreamingChatCompletionUpdate completionUpdate in completionUpdates)
{
    if (completionUpdate.ContentUpdate.Count > 0)
    {
        Console.Write(completionUpdate.ContentUpdate[0].Text);
    }
}


####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
  "github.com/openai/openai-go/shared"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  chatCompletion, err := client.Chat.Completions.New(context.TODO(), openai.ChatCompletionNewParams{
    Messages: []openai.ChatCompletionMessageParamUnion{openai.ChatCompletionMessageParamUnion{
      OfDeveloper: &openai.ChatCompletionDeveloperMessageParam{
        Content: openai.ChatCompletionDeveloperMessageParamContentUnion{
          OfString: openai.String("string"),
        },
      },
    }},
    Model: shared.ChatModelGPT5,
  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", chatCompletion)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.ChatModel;
import com.openai.models.chat.completions.ChatCompletion;
import com.openai.models.chat.completions.ChatCompletionCreateParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
            .addDeveloperMessage("string")
            .model(ChatModel.GPT_5)
            .build();
        ChatCompletion chatCompletion = client.chat().completions().create(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

chat_completion = openai.chat.completions.create(messages: [{content: "string", role: :developer}], model: :"gpt-5")

puts(chat_completion)

###### response

{"id":"chatcmpl-123","object":"chat.completion.chunk","created":1694268190,"model":"gpt-4o-mini", "system_fingerprint": "fp_44709d6fcb", "choices":[{"index":0,"delta":{"role":"assistant","content":""},"logprobs":null,"finish_reason":null}]}

{"id":"chatcmpl-123","object":"chat.completion.chunk","created":1694268190,"model":"gpt-4o-mini", "system_fingerprint": "fp_44709d6fcb", "choices":[{"index":0,"delta":{"content":"Hello"},"logprobs":null,"finish_reason":null}]}

....

{"id":"chatcmpl-123","object":"chat.completion.chunk","created":1694268190,"model":"gpt-4o-mini", "system_fingerprint": "fp_44709d6fcb", "choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]}


###### title

Functions

###### request

####### curl

curl https://api.openai.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d '{
  "model": "gpt-4.1",
  "messages": [
    {
      "role": "user",
      "content": "What is the weather like in Boston today?"
    }
  ],
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "get_current_weather",
        "description": "Get the current weather in a given location",
        "parameters": {
          "type": "object",
          "properties": {
            "location": {
              "type": "string",
              "description": "The city and state, e.g. San Francisco, CA"
            },
            "unit": {
              "type": "string",
              "enum": ["celsius", "fahrenheit"]
            }
          },
          "required": ["location"]
        }
      }
    }
  ],
  "tool_choice": "auto"
}'


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
chat_completion = client.chat.completions.create(
    messages=[{
        "content": "string",
        "role": "developer",
    }],
    model="gpt-4o",
)
print(chat_completion)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const chatCompletion = await client.chat.completions.create({
  messages: [{ content: 'string', role: 'developer' }],
  model: 'gpt-4o',
});

console.log(chatCompletion);

####### csharp

using System;
using System.Collections.Generic;

using OpenAI.Chat;

ChatClient client = new(
    model: "gpt-4.1",
    apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY")
);

ChatTool getCurrentWeatherTool = ChatTool.CreateFunctionTool(
    functionName: "get_current_weather",
    functionDescription: "Get the current weather in a given location",
    functionParameters: BinaryData.FromString("""
        {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "The city and state, e.g. San Francisco, CA"
                },
                "unit": {
                    "type": "string",
                    "enum": [ "celsius", "fahrenheit" ]
                }
            },
            "required": [ "location" ]
        }
    """)
);

List<ChatMessage> messages =
[
    new UserChatMessage("What's the weather like in Boston today?"),
];

ChatCompletionOptions options = new()
{
    Tools =
    {
        getCurrentWeatherTool
    },
    ToolChoice = ChatToolChoice.CreateAutoChoice(),
};

ChatCompletion completion = client.CompleteChat(messages, options);


####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
  "github.com/openai/openai-go/shared"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  chatCompletion, err := client.Chat.Completions.New(context.TODO(), openai.ChatCompletionNewParams{
    Messages: []openai.ChatCompletionMessageParamUnion{openai.ChatCompletionMessageParamUnion{
      OfDeveloper: &openai.ChatCompletionDeveloperMessageParam{
        Content: openai.ChatCompletionDeveloperMessageParamContentUnion{
          OfString: openai.String("string"),
        },
      },
    }},
    Model: shared.ChatModelGPT5,
  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", chatCompletion)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.ChatModel;
import com.openai.models.chat.completions.ChatCompletion;
import com.openai.models.chat.completions.ChatCompletionCreateParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
            .addDeveloperMessage("string")
            .model(ChatModel.GPT_5)
            .build();
        ChatCompletion chatCompletion = client.chat().completions().create(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

chat_completion = openai.chat.completions.create(messages: [{content: "string", role: :developer}], model: :"gpt-5")

puts(chat_completion)

###### response

{
  "id": "chatcmpl-abc123",
  "object": "chat.completion",
  "created": 1699896916,
  "model": "gpt-4o-mini",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": null,
        "tool_calls": [
          {
            "id": "call_abc123",
            "type": "function",
            "function": {
              "name": "get_current_weather",
              "arguments": "{\n\"location\": \"Boston, MA\"\n}"
            }
          }
        ]
      },
      "logprobs": null,
      "finish_reason": "tool_calls"
    }
  ],
  "usage": {
    "prompt_tokens": 82,
    "completion_tokens": 17,
    "total_tokens": 99,
    "completion_tokens_details": {
      "reasoning_tokens": 0,
      "accepted_prediction_tokens": 0,
      "rejected_prediction_tokens": 0
    }
  }
}


###### title

Logprobs

###### request

####### curl

curl https://api.openai.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "VAR_chat_model_id",
    "messages": [
      {
        "role": "user",
        "content": "Hello!"
      }
    ],
    "logprobs": true,
    "top_logprobs": 2
  }'


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
chat_completion = client.chat.completions.create(
    messages=[{
        "content": "string",
        "role": "developer",
    }],
    model="gpt-4o",
)
print(chat_completion)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const chatCompletion = await client.chat.completions.create({
  messages: [{ content: 'string', role: 'developer' }],
  model: 'gpt-4o',
});

console.log(chatCompletion);

####### csharp

using System;
using System.Collections.Generic;

using OpenAI.Chat;

ChatClient client = new(
    model: "gpt-4.1",
    apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY")
);

List<ChatMessage> messages =
[
    new UserChatMessage("Hello!")
];

ChatCompletionOptions options = new()
{
    IncludeLogProbabilities = true,
    TopLogProbabilityCount = 2
};

ChatCompletion completion = client.CompleteChat(messages, options);

Console.WriteLine(completion.Content[0].Text);


####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
  "github.com/openai/openai-go/shared"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  chatCompletion, err := client.Chat.Completions.New(context.TODO(), openai.ChatCompletionNewParams{
    Messages: []openai.ChatCompletionMessageParamUnion{openai.ChatCompletionMessageParamUnion{
      OfDeveloper: &openai.ChatCompletionDeveloperMessageParam{
        Content: openai.ChatCompletionDeveloperMessageParamContentUnion{
          OfString: openai.String("string"),
        },
      },
    }},
    Model: shared.ChatModelGPT5,
  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", chatCompletion)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.ChatModel;
import com.openai.models.chat.completions.ChatCompletion;
import com.openai.models.chat.completions.ChatCompletionCreateParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
            .addDeveloperMessage("string")
            .model(ChatModel.GPT_5)
            .build();
        ChatCompletion chatCompletion = client.chat().completions().create(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

chat_completion = openai.chat.completions.create(messages: [{content: "string", role: :developer}], model: :"gpt-5")

puts(chat_completion)

###### response

{
  "id": "chatcmpl-123",
  "object": "chat.completion",
  "created": 1702685778,
  "model": "gpt-4o-mini",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Hello! How can I assist you today?"
      },
      "logprobs": {
        "content": [
          {
            "token": "Hello",
            "logprob": -0.31725305,
            "bytes": [72, 101, 108, 108, 111],
            "top_logprobs": [
              {
                "token": "Hello",
                "logprob": -0.31725305,
                "bytes": [72, 101, 108, 108, 111]
              },
              {
                "token": "Hi",
                "logprob": -1.3190403,
                "bytes": [72, 105]
              }
            ]
          },
          {
            "token": "!",
            "logprob": -0.02380986,
            "bytes": [
              33
            ],
            "top_logprobs": [
              {
                "token": "!",
                "logprob": -0.02380986,
                "bytes": [33]
              },
              {
                "token": " there",
                "logprob": -3.787621,
                "bytes": [32, 116, 104, 101, 114, 101]
              }
            ]
          },
          {
            "token": " How",
            "logprob": -0.000054669687,
            "bytes": [32, 72, 111, 119],
            "top_logprobs": [
              {
                "token": " How",
                "logprob": -0.000054669687,
                "bytes": [32, 72, 111, 119]
              },
              {
                "token": "<|end|>",
                "logprob": -10.953937,
                "bytes": null
              }
            ]
          },
          {
            "token": " can",
            "logprob": -0.015801601,
            "bytes": [32, 99, 97, 110],
            "top_logprobs": [
              {
                "token": " can",
                "logprob": -0.015801601,
                "bytes": [32, 99, 97, 110]
              },
              {
                "token": " may",
                "logprob": -4.161023,
                "bytes": [32, 109, 97, 121]
              }
            ]
          },
          {
            "token": " I",
            "logprob": -3.7697225e-6,
            "bytes": [
              32,
              73
            ],
            "top_logprobs": [
              {
                "token": " I",
                "logprob": -3.7697225e-6,
                "bytes": [32, 73]
              },
              {
                "token": " assist",
                "logprob": -13.596657,
                "bytes": [32, 97, 115, 115, 105, 115, 116]
              }
            ]
          },
          {
            "token": " assist",
            "logprob": -0.04571125,
            "bytes": [32, 97, 115, 115, 105, 115, 116],
            "top_logprobs": [
              {
                "token": " assist",
                "logprob": -0.04571125,
                "bytes": [32, 97, 115, 115, 105, 115, 116]
              },
              {
                "token": " help",
                "logprob": -3.1089056,
                "bytes": [32, 104, 101, 108, 112]
              }
            ]
          },
          {
            "token": " you",
            "logprob": -5.4385737e-6,
            "bytes": [32, 121, 111, 117],
            "top_logprobs": [
              {
                "token": " you",
                "logprob": -5.4385737e-6,
                "bytes": [32, 121, 111, 117]
              },
              {
                "token": " today",
                "logprob": -12.807695,
                "bytes": [32, 116, 111, 100, 97, 121]
              }
            ]
          },
          {
            "token": " today",
            "logprob": -0.0040071653,
            "bytes": [32, 116, 111, 100, 97, 121],
            "top_logprobs": [
              {
                "token": " today",
                "logprob": -0.0040071653,
                "bytes": [32, 116, 111, 100, 97, 121]
              },
              {
                "token": "?",
                "logprob": -5.5247097,
                "bytes": [63]
              }
            ]
          },
          {
            "token": "?",
            "logprob": -0.0008108172,
            "bytes": [63],
            "top_logprobs": [
              {
                "token": "?",
                "logprob": -0.0008108172,
                "bytes": [63]
              },
              {
                "token": "?\n",
                "logprob": -7.184561,
                "bytes": [63, 10]
              }
            ]
          }
        ]
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 9,
    "completion_tokens": 9,
    "total_tokens": 18,
    "completion_tokens_details": {
      "reasoning_tokens": 0,
      "accepted_prediction_tokens": 0,
      "rejected_prediction_tokens": 0
    }
  },
  "system_fingerprint": null
}



#### description

**Starting a new project?** We recommend trying [Responses](https://platform.openai.com/docs/api-reference/responses) 
to take advantage of the latest OpenAI platform features. Compare
[Chat Completions with Responses](https://platform.openai.com/docs/guides/responses-vs-chat-completions?api-mode=responses).

---

Creates a model response for the given chat conversation. Learn more in the
[text generation](https://platform.openai.com/docs/guides/text-generation), [vision](https://platform.openai.com/docs/guides/vision),
and [audio](https://platform.openai.com/docs/guides/audio) guides.

Parameter support can differ depending on the model used to generate the
response, particularly for newer reasoning models. Parameters that are only
supported for reasoning models are noted below. For the current state of 
unsupported parameters in reasoning models, 
[refer to the reasoning guide](https://platform.openai.com/docs/guides/reasoning).


## /chat/completions/{completion_id}

### get

#### operationId

getChatCompletion

#### tags

- Chat

#### summary

Get chat completion

#### parameters

##### in

path

##### name

completion_id

##### required

true

##### schema

###### type

string

##### description

The ID of the chat completion to retrieve.


#### responses

##### 200

###### description

A chat completion

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/CreateChatCompletionResponse

#### x-oaiMeta

##### name

Get chat completion

##### group

chat

##### returns

The [ChatCompletion](https://platform.openai.com/docs/api-reference/chat/object) object matching the specified ID.

##### examples

###### response

{
  "object": "chat.completion",
  "id": "chatcmpl-abc123",
  "model": "gpt-4o-2024-08-06",
  "created": 1738960610,
  "request_id": "req_ded8ab984ec4bf840f37566c1011c417",
  "tool_choice": null,
  "usage": {
    "total_tokens": 31,
    "completion_tokens": 18,
    "prompt_tokens": 13
  },
  "seed": 4944116822809979520,
  "top_p": 1.0,
  "temperature": 1.0,
  "presence_penalty": 0.0,
  "frequency_penalty": 0.0,
  "system_fingerprint": "fp_50cad350e4",
  "input_user": null,
  "service_tier": "default",
  "tools": null,
  "metadata": {},
  "choices": [
    {
      "index": 0,
      "message": {
        "content": "Mind of circuits hum,  \nLearning patterns in silenceâ  \nFuture's quiet spark.",
        "role": "assistant",
        "tool_calls": null,
        "function_call": null
      },
      "finish_reason": "stop",
      "logprobs": null
    }
  ],
  "response_format": null
}


###### request

####### curl

curl https://api.openai.com/v1/chat/completions/chatcmpl-abc123 \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
chat_completion = client.chat.completions.retrieve(
    "completion_id",
)
print(chat_completion.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const chatCompletion = await client.chat.completions.retrieve('completion_id');

console.log(chatCompletion.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  chatCompletion, err := client.Chat.Completions.Get(context.TODO(), "completion_id")
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", chatCompletion.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.chat.completions.ChatCompletion;
import com.openai.models.chat.completions.ChatCompletionRetrieveParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        ChatCompletion chatCompletion = client.chat().completions().retrieve("completion_id");
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

chat_completion = openai.chat.completions.retrieve("completion_id")

puts(chat_completion)

#### description

Get a stored chat completion. Only Chat Completions that have been created
with the `store` parameter set to `true` will be returned.


### post

#### operationId

updateChatCompletion

#### tags

- Chat

#### summary

Update chat completion

#### parameters

##### in

path

##### name

completion_id

##### required

true

##### schema

###### type

string

##### description

The ID of the chat completion to update.


#### requestBody

##### required

true

##### content

###### application/json

####### schema

######## type

object

######## required

- metadata

######## properties

######### metadata

########## $ref

#/components/schemas/Metadata

#### responses

##### 200

###### description

A chat completion

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/CreateChatCompletionResponse

#### x-oaiMeta

##### name

Update chat completion

##### group

chat

##### returns

The [ChatCompletion](https://platform.openai.com/docs/api-reference/chat/object) object matching the specified ID.

##### examples

###### response

{
  "object": "chat.completion",
  "id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2",
  "model": "gpt-4o-2024-08-06",
  "created": 1738960610,
  "request_id": "req_ded8ab984ec4bf840f37566c1011c417",
  "tool_choice": null,
  "usage": {
    "total_tokens": 31,
    "completion_tokens": 18,
    "prompt_tokens": 13
  },
  "seed": 4944116822809979520,
  "top_p": 1.0,
  "temperature": 1.0,
  "presence_penalty": 0.0,
  "frequency_penalty": 0.0,
  "system_fingerprint": "fp_50cad350e4",
  "input_user": null,
  "service_tier": "default",
  "tools": null,
  "metadata": {
    "foo": "bar"
  },
  "choices": [
    {
      "index": 0,
      "message": {
        "content": "Mind of circuits hum,  \nLearning patterns in silenceâ  \nFuture's quiet spark.",
        "role": "assistant",
        "tool_calls": null,
        "function_call": null
      },
      "finish_reason": "stop",
      "logprobs": null
    }
  ],
  "response_format": null
}


###### request

####### curl

curl -X POST https://api.openai.com/v1/chat/completions/chat_abc123 \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"metadata": {"foo": "bar"}}'


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
chat_completion = client.chat.completions.update(
    completion_id="completion_id",
    metadata={
        "foo": "string"
    },
)
print(chat_completion.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const chatCompletion = await client.chat.completions.update('completion_id', { metadata: { foo: 'string' } });

console.log(chatCompletion.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
  "github.com/openai/openai-go/shared"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  chatCompletion, err := client.Chat.Completions.Update(
    context.TODO(),
    "completion_id",
    openai.ChatCompletionUpdateParams{
      Metadata: shared.Metadata{
      "foo": "string",
      },
    },
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", chatCompletion.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.JsonValue;
import com.openai.models.chat.completions.ChatCompletion;
import com.openai.models.chat.completions.ChatCompletionUpdateParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        ChatCompletionUpdateParams params = ChatCompletionUpdateParams.builder()
            .completionId("completion_id")
            .metadata(ChatCompletionUpdateParams.Metadata.builder()
                .putAdditionalProperty("foo", JsonValue.from("string"))
                .build())
            .build();
        ChatCompletion chatCompletion = client.chat().completions().update(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

chat_completion = openai.chat.completions.update("completion_id", metadata: {foo: "string"})

puts(chat_completion)

#### description

Modify a stored chat completion. Only Chat Completions that have been
created with the `store` parameter set to `true` can be modified. Currently,
the only supported modification is to update the `metadata` field.


### delete

#### operationId

deleteChatCompletion

#### tags

- Chat

#### summary

Delete chat completion

#### parameters

##### in

path

##### name

completion_id

##### required

true

##### schema

###### type

string

##### description

The ID of the chat completion to delete.


#### responses

##### 200

###### description

The chat completion was deleted successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ChatCompletionDeleted

#### x-oaiMeta

##### name

Delete chat completion

##### group

chat

##### returns

A deletion confirmation object.

##### examples

###### response

{
  "object": "chat.completion.deleted",
  "id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2",
  "deleted": true
}


###### request

####### curl

curl -X DELETE https://api.openai.com/v1/chat/completions/chat_abc123 \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
chat_completion_deleted = client.chat.completions.delete(
    "completion_id",
)
print(chat_completion_deleted.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const chatCompletionDeleted = await client.chat.completions.delete('completion_id');

console.log(chatCompletionDeleted.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  chatCompletionDeleted, err := client.Chat.Completions.Delete(context.TODO(), "completion_id")
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", chatCompletionDeleted.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.chat.completions.ChatCompletionDeleteParams;
import com.openai.models.chat.completions.ChatCompletionDeleted;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        ChatCompletionDeleted chatCompletionDeleted = client.chat().completions().delete("completion_id");
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

chat_completion_deleted = openai.chat.completions.delete("completion_id")

puts(chat_completion_deleted)

#### description

Delete a stored chat completion. Only Chat Completions that have been
created with the `store` parameter set to `true` can be deleted.


## /chat/completions/{completion_id}/messages

### get

#### operationId

getChatCompletionMessages

#### tags

- Chat

#### summary

Get chat messages

#### parameters

##### in

path

##### name

completion_id

##### required

true

##### schema

###### type

string

##### description

The ID of the chat completion to retrieve messages from.

##### name

after

##### in

query

##### description

Identifier for the last message from the previous pagination request.

##### required

false

##### schema

###### type

string

##### name

limit

##### in

query

##### description

Number of messages to retrieve.

##### required

false

##### schema

###### type

integer

###### default

20

##### name

order

##### in

query

##### description

Sort order for messages by timestamp. Use `asc` for ascending order or `desc` for descending order. Defaults to `asc`.

##### required

false

##### schema

###### type

string

###### enum

- asc
- desc

###### default

asc


#### responses

##### 200

###### description

A list of messages

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ChatCompletionMessageList

#### x-oaiMeta

##### name

Get chat messages

##### group

chat

##### returns

A list of [messages](https://platform.openai.com/docs/api-reference/chat/message-list) for the specified chat completion.

##### examples

###### response

{
  "object": "list",
  "data": [
    {
      "id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2-0",
      "role": "user",
      "content": "write a haiku about ai",
      "name": null,
      "content_parts": null
    }
  ],
  "first_id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2-0",
  "last_id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2-0",
  "has_more": false
}


###### request

####### curl

curl https://api.openai.com/v1/chat/completions/chat_abc123/messages \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
page = client.chat.completions.messages.list(
    completion_id="completion_id",
)
page = page.data[0]
print(page)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

// Automatically fetches more pages as needed.
for await (const chatCompletionStoreMessage of client.chat.completions.messages.list('completion_id')) {
  console.log(chatCompletionStoreMessage);
}

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  page, err := client.Chat.Completions.Messages.List(
    context.TODO(),
    "completion_id",
    openai.ChatCompletionMessageListParams{

    },
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", page)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.chat.completions.messages.MessageListPage;
import com.openai.models.chat.completions.messages.MessageListParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        MessageListPage page = client.chat().completions().messages().list("completion_id");
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

page = openai.chat.completions.messages.list("completion_id")

puts(page)

#### description

Get the messages in a stored chat completion. Only Chat Completions that
have been created with the `store` parameter set to `true` will be
returned.


## /completions

### post

#### operationId

createCompletion

#### tags

- Completions

#### summary

Create completion

#### requestBody

##### required

true

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/CreateCompletionRequest

#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/CreateCompletionResponse

#### x-oaiMeta

##### name

Create completion

##### group

completions

##### returns

Returns a [completion](https://platform.openai.com/docs/api-reference/completions/object) object, or a sequence of completion objects if the request is streamed.


##### legacy

true

##### examples

###### title

No streaming

###### request

####### curl

curl https://api.openai.com/v1/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "VAR_completion_model_id",
    "prompt": "Say this is a test",
    "max_tokens": 7,
    "temperature": 0
  }'


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
completion = client.completions.create(
    model="string",
    prompt="This is a test.",
)
print(completion)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const completion = await client.completions.create({ model: 'string', prompt: 'This is a test.' });

console.log(completion);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  completion, err := client.Completions.New(context.TODO(), openai.CompletionNewParams{
    Model: openai.CompletionNewParamsModelGPT3_5TurboInstruct,
    Prompt: openai.CompletionNewParamsPromptUnion{
      OfString: openai.String("This is a test."),
    },
  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", completion)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.completions.Completion;
import com.openai.models.completions.CompletionCreateParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        CompletionCreateParams params = CompletionCreateParams.builder()
            .model(CompletionCreateParams.Model.GPT_3_5_TURBO_INSTRUCT)
            .prompt("This is a test.")
            .build();
        Completion completion = client.completions().create(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

completion = openai.completions.create(model: :"gpt-3.5-turbo-instruct", prompt: "This is a test.")

puts(completion)

###### response

{
  "id": "cmpl-uqkvlQyYK7bGYrRHQ0eXlWi7",
  "object": "text_completion",
  "created": 1589478378,
  "model": "VAR_completion_model_id",
  "system_fingerprint": "fp_44709d6fcb",
  "choices": [
    {
      "text": "\n\nThis is indeed a test",
      "index": 0,
      "logprobs": null,
      "finish_reason": "length"
    }
  ],
  "usage": {
    "prompt_tokens": 5,
    "completion_tokens": 7,
    "total_tokens": 12
  }
}


###### title

Streaming

###### request

####### curl

curl https://api.openai.com/v1/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "VAR_completion_model_id",
    "prompt": "Say this is a test",
    "max_tokens": 7,
    "temperature": 0,
    "stream": true
  }'


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
completion = client.completions.create(
    model="string",
    prompt="This is a test.",
)
print(completion)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const completion = await client.completions.create({ model: 'string', prompt: 'This is a test.' });

console.log(completion);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  completion, err := client.Completions.New(context.TODO(), openai.CompletionNewParams{
    Model: openai.CompletionNewParamsModelGPT3_5TurboInstruct,
    Prompt: openai.CompletionNewParamsPromptUnion{
      OfString: openai.String("This is a test."),
    },
  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", completion)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.completions.Completion;
import com.openai.models.completions.CompletionCreateParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        CompletionCreateParams params = CompletionCreateParams.builder()
            .model(CompletionCreateParams.Model.GPT_3_5_TURBO_INSTRUCT)
            .prompt("This is a test.")
            .build();
        Completion completion = client.completions().create(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

completion = openai.completions.create(model: :"gpt-3.5-turbo-instruct", prompt: "This is a test.")

puts(completion)

###### response

{
  "id": "cmpl-7iA7iJjj8V2zOkCGvWF2hAkDWBQZe",
  "object": "text_completion",
  "created": 1690759702,
  "choices": [
    {
      "text": "This",
      "index": 0,
      "logprobs": null,
      "finish_reason": null
    }
  ],
  "model": "gpt-3.5-turbo-instruct"
  "system_fingerprint": "fp_44709d6fcb",
}



#### description

Creates a completion for the provided prompt and parameters.

## /containers

### get

#### summary

List containers

#### description

List Containers

#### operationId

ListContainers

#### parameters

##### name

limit

##### in

query

##### description

A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20.


##### required

false

##### schema

###### type

integer

###### default

20

##### name

order

##### in

query

##### description

Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order.


##### schema

###### type

string

###### default

desc

###### enum

- asc
- desc

##### name

after

##### in

query

##### description

A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list.


##### schema

###### type

string


#### responses

##### 200

###### description

Success

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ContainerListResource

#### x-oaiMeta

##### name

List containers

##### group

containers

##### returns

a list of [container](https://platform.openai.com/docs/api-reference/containers/object) objects.

##### path

get

##### examples

###### response

{
  "object": "list",
  "data": [
    {
        "id": "cntr_682dfebaacac8198bbfe9c2474fb6f4a085685cbe3cb5863",
        "object": "container",
        "created_at": 1747844794,
        "status": "running",
        "expires_after": {
            "anchor": "last_active_at",
            "minutes": 20
        },
        "last_active_at": 1747844794,
        "name": "My Container"
    }
  ],
  "first_id": "container_123",
  "last_id": "container_123",
  "has_more": false
}


###### request

####### curl

curl https://api.openai.com/v1/containers \
  -H "Authorization: Bearer $OPENAI_API_KEY"


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

// Automatically fetches more pages as needed.
for await (const containerListResponse of client.containers.list()) {
  console.log(containerListResponse.id);
}

####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
page = client.containers.list()
page = page.data[0]
print(page.id)

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  page, err := client.Containers.List(context.TODO(), openai.ContainerListParams{

  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", page)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.containers.ContainerListPage;
import com.openai.models.containers.ContainerListParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        ContainerListPage page = client.containers().list();
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

page = openai.containers.list

puts(page)

### post

#### summary

Create container

#### description

Create Container

#### operationId

CreateContainer

#### parameters


#### requestBody

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/CreateContainerBody

#### responses

##### 200

###### description

Success

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ContainerResource

#### x-oaiMeta

##### name

Create container

##### group

containers

##### returns

The created [container](https://platform.openai.com/docs/api-reference/containers/object) object.

##### path

post

##### examples

###### response

{
    "id": "cntr_682e30645a488191b6363a0cbefc0f0a025ec61b66250591",
    "object": "container",
    "created_at": 1747857508,
    "status": "running",
    "expires_after": {
        "anchor": "last_active_at",
        "minutes": 20
    },
    "last_active_at": 1747857508,
    "name": "My Container"
}


###### request

####### curl

curl https://api.openai.com/v1/containers \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
        "name": "My Container"
      }'


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const container = await client.containers.create({ name: 'name' });

console.log(container.id);

####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
container = client.containers.create(
    name="name",
)
print(container.id)

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  container, err := client.Containers.New(context.TODO(), openai.ContainerNewParams{
    Name: "name",
  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", container.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.containers.ContainerCreateParams;
import com.openai.models.containers.ContainerCreateResponse;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        ContainerCreateParams params = ContainerCreateParams.builder()
            .name("name")
            .build();
        ContainerCreateResponse container = client.containers().create(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

container = openai.containers.create(name: "name")

puts(container)

## /containers/{container_id}

### get

#### summary

Retrieve container

#### description

Retrieve Container

#### operationId

RetrieveContainer

#### parameters

##### name

container_id

##### in

path

##### required

true

##### schema

###### type

string


#### responses

##### 200

###### description

Success

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ContainerResource

#### x-oaiMeta

##### name

Retrieve container

##### group

containers

##### returns

The [container](https://platform.openai.com/docs/api-reference/containers/object) object.

##### path

get

##### examples

###### response

{
    "id": "cntr_682dfebaacac8198bbfe9c2474fb6f4a085685cbe3cb5863",
    "object": "container",
    "created_at": 1747844794,
    "status": "running",
    "expires_after": {
        "anchor": "last_active_at",
        "minutes": 20
    },
    "last_active_at": 1747844794,
    "name": "My Container"
}


###### request

####### curl

curl https://api.openai.com/v1/containers/cntr_682dfebaacac8198bbfe9c2474fb6f4a085685cbe3cb5863 \
  -H "Authorization: Bearer $OPENAI_API_KEY"


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const container = await client.containers.retrieve('container_id');

console.log(container.id);

####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
container = client.containers.retrieve(
    "container_id",
)
print(container.id)

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  container, err := client.Containers.Get(context.TODO(), "container_id")
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", container.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.containers.ContainerRetrieveParams;
import com.openai.models.containers.ContainerRetrieveResponse;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        ContainerRetrieveResponse container = client.containers().retrieve("container_id");
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

container = openai.containers.retrieve("container_id")

puts(container)

### delete

#### operationId

DeleteContainer

#### summary

Delete a container

#### description

Delete Container

#### parameters

##### name

container_id

##### in

path

##### description

The ID of the container to delete.

##### required

true

##### schema

###### type

string


#### responses

##### 200

###### description

OK

#### x-oaiMeta

##### name

Delete a container

##### group

containers

##### returns

Deletion Status

##### path

delete

##### examples

###### response

{
    "id": "cntr_682dfebaacac8198bbfe9c2474fb6f4a085685cbe3cb5863",
    "object": "container.deleted",
    "deleted": true
}


###### request

####### curl

curl -X DELETE https://api.openai.com/v1/containers/cntr_682dfebaacac8198bbfe9c2474fb6f4a085685cbe3cb5863 \
  -H "Authorization: Bearer $OPENAI_API_KEY"


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

await client.containers.delete('container_id');

####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
client.containers.delete(
    "container_id",
)

####### go

package main

import (
  "context"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  err := client.Containers.Delete(context.TODO(), "container_id")
  if err != nil {
    panic(err.Error())
  }
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.containers.ContainerDeleteParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        client.containers().delete("container_id");
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

result = openai.containers.delete("container_id")

puts(result)

## /containers/{container_id}/files

### post

#### summary

Create container file

#### description

Create a Container File

You can send either a multipart/form-data request with the raw file content, or a JSON request with a file ID.


#### operationId

CreateContainerFile

#### parameters

##### name

container_id

##### in

path

##### required

true

##### schema

###### type

string


#### requestBody

##### required

true

##### content

###### multipart/form-data

####### schema

######## $ref

#/components/schemas/CreateContainerFileBody

#### responses

##### 200

###### description

Success

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ContainerFileResource

#### x-oaiMeta

##### name

Create container file

##### group

containers

##### returns

The created [container file](https://platform.openai.com/docs/api-reference/container-files/object) object.

##### path

post

##### examples

###### response

{
  "id": "cfile_682e0e8a43c88191a7978f477a09bdf5",
  "object": "container.file",
  "created_at": 1747848842,
  "bytes": 880,
  "container_id": "cntr_682e0e7318108198aa783fd921ff305e08e78805b9fdbb04",
  "path": "/mnt/data/88e12fa445d32636f190a0b33daed6cb-tsconfig.json",
  "source": "user"
}


###### request

####### curl

curl https://api.openai.com/v1/containers/cntr_682e0e7318108198aa783fd921ff305e08e78805b9fdbb04/files \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -F file="@example.txt"


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const file = await client.containers.files.create('container_id');

console.log(file.id);

####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
file = client.containers.files.create(
    container_id="container_id",
)
print(file.id)

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  file, err := client.Containers.Files.New(
    context.TODO(),
    "container_id",
    openai.ContainerFileNewParams{

    },
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", file.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.containers.files.FileCreateParams;
import com.openai.models.containers.files.FileCreateResponse;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        FileCreateResponse file = client.containers().files().create("container_id");
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

file = openai.containers.files.create("container_id")

puts(file)

### get

#### summary

List container files

#### description

List Container files

#### operationId

ListContainerFiles

#### parameters

##### name

container_id

##### in

path

##### required

true

##### schema

###### type

string

##### name

limit

##### in

query

##### description

A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20.


##### required

false

##### schema

###### type

integer

###### default

20

##### name

order

##### in

query

##### description

Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order.


##### schema

###### type

string

###### default

desc

###### enum

- asc
- desc

##### name

after

##### in

query

##### description

A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list.


##### schema

###### type

string


#### responses

##### 200

###### description

Success

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ContainerFileListResource

#### x-oaiMeta

##### name

List container files

##### group

containers

##### returns

a list of [container file](https://platform.openai.com/docs/api-reference/container-files/object) objects.

##### path

get

##### examples

###### response

{
    "object": "list",
    "data": [
        {
            "id": "cfile_682e0e8a43c88191a7978f477a09bdf5",
            "object": "container.file",
            "created_at": 1747848842,
            "bytes": 880,
            "container_id": "cntr_682e0e7318108198aa783fd921ff305e08e78805b9fdbb04",
            "path": "/mnt/data/88e12fa445d32636f190a0b33daed6cb-tsconfig.json",
            "source": "user"
        }
    ],
    "first_id": "cfile_682e0e8a43c88191a7978f477a09bdf5",
    "has_more": false,
    "last_id": "cfile_682e0e8a43c88191a7978f477a09bdf5"
}


###### request

####### curl

curl https://api.openai.com/v1/containers/cntr_682e0e7318108198aa783fd921ff305e08e78805b9fdbb04/files \
  -H "Authorization: Bearer $OPENAI_API_KEY"


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

// Automatically fetches more pages as needed.
for await (const fileListResponse of client.containers.files.list('container_id')) {
  console.log(fileListResponse.id);
}

####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
page = client.containers.files.list(
    container_id="container_id",
)
page = page.data[0]
print(page.id)

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  page, err := client.Containers.Files.List(
    context.TODO(),
    "container_id",
    openai.ContainerFileListParams{

    },
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", page)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.containers.files.FileListPage;
import com.openai.models.containers.files.FileListParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        FileListPage page = client.containers().files().list("container_id");
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

page = openai.containers.files.list("container_id")

puts(page)

## /containers/{container_id}/files/{file_id}

### get

#### summary

Retrieve container file

#### description

Retrieve Container File

#### operationId

RetrieveContainerFile

#### parameters

##### name

container_id

##### in

path

##### required

true

##### schema

###### type

string

##### name

file_id

##### in

path

##### required

true

##### schema

###### type

string


#### responses

##### 200

###### description

Success

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ContainerFileResource

#### x-oaiMeta

##### name

Retrieve container file

##### group

containers

##### returns

The [container file](https://platform.openai.com/docs/api-reference/container-files/object) object.

##### path

get

##### examples

###### response

{
    "id": "cfile_682e0e8a43c88191a7978f477a09bdf5",
    "object": "container.file",
    "created_at": 1747848842,
    "bytes": 880,
    "container_id": "cntr_682e0e7318108198aa783fd921ff305e08e78805b9fdbb04",
    "path": "/mnt/data/88e12fa445d32636f190a0b33daed6cb-tsconfig.json",
    "source": "user"
}


###### request

####### curl

curl https://api.openai.com/v1/containers/container_123/files/file_456 \
  -H "Authorization: Bearer $OPENAI_API_KEY"


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const file = await client.containers.files.retrieve('file_id', { container_id: 'container_id' });

console.log(file.id);

####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
file = client.containers.files.retrieve(
    file_id="file_id",
    container_id="container_id",
)
print(file.id)

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  file, err := client.Containers.Files.Get(
    context.TODO(),
    "container_id",
    "file_id",
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", file.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.containers.files.FileRetrieveParams;
import com.openai.models.containers.files.FileRetrieveResponse;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        FileRetrieveParams params = FileRetrieveParams.builder()
            .containerId("container_id")
            .fileId("file_id")
            .build();
        FileRetrieveResponse file = client.containers().files().retrieve(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

file = openai.containers.files.retrieve("file_id", container_id: "container_id")

puts(file)

### delete

#### operationId

DeleteContainerFile

#### summary

Delete a container file

#### description

Delete Container File

#### parameters

##### name

container_id

##### in

path

##### required

true

##### schema

###### type

string

##### name

file_id

##### in

path

##### required

true

##### schema

###### type

string


#### responses

##### 200

###### description

OK

#### x-oaiMeta

##### name

Delete a container file

##### group

containers

##### returns

Deletion Status

##### path

delete

##### examples

###### response

{
    "id": "cfile_682e0e8a43c88191a7978f477a09bdf5",
    "object": "container.file.deleted",
    "deleted": true
}


###### request

####### curl

curl -X DELETE https://api.openai.com/v1/containers/cntr_682dfebaacac8198bbfe9c2474fb6f4a085685cbe3cb5863/files/cfile_682e0e8a43c88191a7978f477a09bdf5 \
  -H "Authorization: Bearer $OPENAI_API_KEY"


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

await client.containers.files.delete('file_id', { container_id: 'container_id' });

####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
client.containers.files.delete(
    file_id="file_id",
    container_id="container_id",
)

####### go

package main

import (
  "context"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  err := client.Containers.Files.Delete(
    context.TODO(),
    "container_id",
    "file_id",
  )
  if err != nil {
    panic(err.Error())
  }
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.containers.files.FileDeleteParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        FileDeleteParams params = FileDeleteParams.builder()
            .containerId("container_id")
            .fileId("file_id")
            .build();
        client.containers().files().delete(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

result = openai.containers.files.delete("file_id", container_id: "container_id")

puts(result)

## /containers/{container_id}/files/{file_id}/content

### get

#### summary

Retrieve container file content

#### description

Retrieve Container File Content

#### operationId

RetrieveContainerFileContent

#### parameters

##### name

container_id

##### in

path

##### required

true

##### schema

###### type

string

##### name

file_id

##### in

path

##### required

true

##### schema

###### type

string


#### responses

##### 200

###### description

Success

#### x-oaiMeta

##### name

Retrieve container file content

##### group

containers

##### returns

The contents of the container file.

##### path

get

##### examples

###### response

<binary content of the file>


###### request

####### curl

curl https://api.openai.com/v1/containers/container_123/files/cfile_456/content \
  -H "Authorization: Bearer $OPENAI_API_KEY"


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const content = await client.containers.files.content.retrieve('file_id', { container_id: 'container_id' });

console.log(content);

const data = await content.blob();
console.log(data);

####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
content = client.containers.files.content.retrieve(
    file_id="file_id",
    container_id="container_id",
)
print(content)
data = content.read()
print(data)

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  content, err := client.Containers.Files.Content.Get(
    context.TODO(),
    "container_id",
    "file_id",
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", content)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.http.HttpResponse;
import com.openai.models.containers.files.content.ContentRetrieveParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        ContentRetrieveParams params = ContentRetrieveParams.builder()
            .containerId("container_id")
            .fileId("file_id")
            .build();
        HttpResponse content = client.containers().files().content().retrieve(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

content = openai.containers.files.content.retrieve("file_id", container_id: "container_id")

puts(content)

## /conversations

### post

#### operationId

createConversation

#### tags

- Conversations

#### summary

Create a conversation

#### requestBody

##### required

true

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/CreateConversationRequest

#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ConversationResource

#### x-oaiMeta

##### name

Create a conversation

##### group

conversations

##### returns

Returns a [Conversation](https://platform.openai.com/docs/api-reference/conversations/object) object.


##### path

create

##### examples

###### title

Create a conversation.

###### request

####### curl

curl https://api.openai.com/v1/conversations \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "metadata": {"topic": "demo"},
    "items": [
      {
        "type": "message",
        "role": "user",
        "content": "Hello!"
      }
    ]
  }'


####### javascript

import OpenAI from "openai";
const client = new OpenAI();

const conversation = await client.conversations.create({
  metadata: { topic: "demo" },
  items: [
    { type: "message", role: "user", content: "Hello!" }
  ],
});
console.log(conversation);


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
conversation = client.conversations.create()
print(conversation.id)

####### csharp

using System;
using System.Collections.Generic;
using OpenAI.Conversations;

OpenAIConversationClient client = new(
    apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY")
);

Conversation conversation = client.CreateConversation(
    new CreateConversationOptions
    {
        Metadata = new Dictionary<string, string>
        {
            { "topic", "demo" }
        },
        Items =
        {
            new ConversationMessageInput
            {
                Role = "user",
                Content = "Hello!"
            }
        }
    }
);
Console.WriteLine(conversation.Id);


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const conversation = await client.conversations.create();

console.log(conversation.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/conversations"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  conversation, err := client.Conversations.New(context.TODO(), conversations.ConversationNewParams{

  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", conversation.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.conversations.Conversation;
import com.openai.models.conversations.ConversationCreateParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        Conversation conversation = client.conversations().create();
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

conversation = openai.conversations.create

puts(conversation)

###### response

{
  "id": "conv_123",
  "object": "conversation",
  "created_at": 1741900000,
  "metadata": {"topic": "demo"}
}



#### description

Create a conversation.

## /conversations/{conversation_id}

### get

#### operationId

getConversation

#### tags

- Conversations

#### summary

Retrieve a conversation

#### parameters

##### in

path

##### name

conversation_id

##### required

true

##### schema

###### type

string

###### example

conv_123

##### description

The ID of the conversation to retrieve.


#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ConversationResource

#### x-oaiMeta

##### name

Retrieve a conversation

##### group

conversations

##### returns

Returns a [Conversation](https://platform.openai.com/docs/api-reference/conversations/object) object.


##### path

retrieve

##### examples

###### title

Retrieve a conversation

###### request

####### curl

curl https://api.openai.com/v1/conversations/conv_123 \
  -H "Authorization: Bearer $OPENAI_API_KEY"


####### javascript

import OpenAI from "openai";
const client = new OpenAI();

const conversation = await client.conversations.retrieve("conv_123");
console.log(conversation);


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
conversation = client.conversations.retrieve(
    "conv_123",
)
print(conversation.id)

####### csharp

using System;
using OpenAI.Conversations;

OpenAIConversationClient client = new(
    apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY")
);

Conversation conversation = client.GetConversation("conv_123");
Console.WriteLine(conversation.Id);


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const conversation = await client.conversations.retrieve('conv_123');

console.log(conversation.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  conversation, err := client.Conversations.Get(context.TODO(), "conv_123")
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", conversation.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.conversations.Conversation;
import com.openai.models.conversations.ConversationRetrieveParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        Conversation conversation = client.conversations().retrieve("conv_123");
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

conversation = openai.conversations.retrieve("conv_123")

puts(conversation)

###### response

{
  "id": "conv_123",
  "object": "conversation",
  "created_at": 1741900000,
  "metadata": {"topic": "demo"}
}



#### description

Get a conversation with the given ID.

### post

#### operationId

updateConversation

#### tags

- Conversations

#### summary

Update a conversation

#### parameters

##### in

path

##### name

conversation_id

##### required

true

##### schema

###### type

string

###### example

conv_123

##### description

The ID of the conversation to update.


#### requestBody

##### required

true

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/UpdateConversationBody

#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ConversationResource

#### x-oaiMeta

##### name

Update a conversation

##### group

conversations

##### returns

Returns the updated [Conversation](https://platform.openai.com/docs/api-reference/conversations/object) object.


##### path

update

##### examples

###### title

Update conversation metadata

###### request

####### curl

curl https://api.openai.com/v1/conversations/conv_123 \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "metadata": {"topic": "project-x"}
  }'


####### javascript

import OpenAI from "openai";
const client = new OpenAI();

const updated = await client.conversations.update(
  "conv_123",
  { metadata: { topic: "project-x" } }
);
console.log(updated);


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
conversation = client.conversations.update(
    conversation_id="conv_123",
    metadata={
        "foo": "string"
    },
)
print(conversation.id)

####### csharp

using System;
using System.Collections.Generic;
using OpenAI.Conversations;

OpenAIConversationClient client = new(
    apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY")
);

Conversation updated = client.UpdateConversation(
    conversationId: "conv_123",
    new UpdateConversationOptions
    {
        Metadata = new Dictionary<string, string>
        {
            { "topic", "project-x" }
        }
    }
);
Console.WriteLine(updated.Id);


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const conversation = await client.conversations.update('conv_123', { metadata: { foo: 'string' } });

console.log(conversation.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/conversations"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  conversation, err := client.Conversations.Update(
    context.TODO(),
    "conv_123",
    conversations.ConversationUpdateParams{
      Metadata: map[string]string{
      "foo": "string",
      },
    },
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", conversation.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.JsonValue;
import com.openai.models.conversations.Conversation;
import com.openai.models.conversations.ConversationUpdateParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        ConversationUpdateParams params = ConversationUpdateParams.builder()
            .conversationId("conv_123")
            .metadata(ConversationUpdateParams.Metadata.builder()
                .putAdditionalProperty("foo", JsonValue.from("string"))
                .build())
            .build();
        Conversation conversation = client.conversations().update(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

conversation = openai.conversations.update("conv_123", metadata: {foo: "string"})

puts(conversation)

###### response

{
  "id": "conv_123",
  "object": "conversation",
  "created_at": 1741900000,
  "metadata": {"topic": "project-x"}
}



#### description

Update a conversation's metadata with the given ID.

### delete

#### operationId

deleteConversation

#### tags

- Conversations

#### summary

Delete a conversation

#### parameters

##### in

path

##### name

conversation_id

##### required

true

##### schema

###### type

string

###### example

conv_123

##### description

The ID of the conversation to delete.


#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/DeletedConversationResource

#### x-oaiMeta

##### name

Delete a conversation

##### group

conversations

##### returns

A success message.


##### path

delete

##### examples

###### title

Delete a conversation

###### request

####### curl

curl -X DELETE https://api.openai.com/v1/conversations/conv_123 \
  -H "Authorization: Bearer $OPENAI_API_KEY"


####### javascript

import OpenAI from "openai";
const client = new OpenAI();

const deleted = await client.conversations.delete("conv_123");
console.log(deleted);


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
conversation_deleted_resource = client.conversations.delete(
    "conv_123",
)
print(conversation_deleted_resource.id)

####### csharp

using System;
using OpenAI.Conversations;

OpenAIConversationClient client = new(
    apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY")
);

DeletedConversation deleted = client.DeleteConversation("conv_123");
Console.WriteLine(deleted.Id);


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const conversationDeletedResource = await client.conversations.delete('conv_123');

console.log(conversationDeletedResource.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  conversationDeletedResource, err := client.Conversations.Delete(context.TODO(), "conv_123")
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", conversationDeletedResource.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.conversations.ConversationDeleteParams;
import com.openai.models.conversations.ConversationDeletedResource;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        ConversationDeletedResource conversationDeletedResource = client.conversations().delete("conv_123");
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

conversation_deleted_resource = openai.conversations.delete("conv_123")

puts(conversation_deleted_resource)

###### response

{
  "id": "conv_123",
  "object": "conversation.deleted",
  "deleted": true
}



#### description

Delete a conversation with the given ID.

## /conversations/{conversation_id}/items

### post

#### operationId

createConversationItems

#### tags

- Conversations

#### summary

Create items

#### parameters

##### in

path

##### name

conversation_id

##### required

true

##### schema

###### type

string

###### example

conv_123

##### description

The ID of the conversation to add the item to.

##### name

include

##### in

query

##### required

false

##### schema

###### type

array

###### items

####### $ref

#/components/schemas/Includable

##### description

Additional fields to include in the response. See the `include`
parameter for [listing Conversation items above](https://platform.openai.com/docs/api-reference/conversations/list-items#conversations_list_items-include) for more information.



#### requestBody

##### required

true

##### content

###### application/json

####### schema

######## properties

######### items

########## type

array

########## description

The items to add to the conversation. You may add up to 20 items at a time.


########## items

########### $ref

#/components/schemas/InputItem

########## maxItems

20

######## required

- items

#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ConversationItemList

#### x-oaiMeta

##### name

Create items

##### group

conversations

##### returns

Returns the list of added [items](https://platform.openai.com/docs/api-reference/conversations/list-items-object).


##### path

create-item

##### examples

###### title

Add a user message to a conversation

###### request

####### curl

curl https://api.openai.com/v1/conversations/conv_123/items \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "items": [
      {
        "type": "message",
        "role": "user",
        "content": [
          {"type": "input_text", "text": "Hello!"}
        ]
      },
      {
        "type": "message",
        "role": "user",
        "content": [
          {"type": "input_text", "text": "How are you?"}
        ]
      }
    ]
  }'


####### javascript

import OpenAI from "openai";
const client = new OpenAI();

const items = await client.conversations.items.create(
  "conv_123",
  {
    items: [
      {
        type: "message",
        role: "user",
        content: [{ type: "input_text", text: "Hello!" }],
      },
      {
        type: "message",
        role: "user",
        content: [{ type: "input_text", text: "How are you?" }],
      },
    ],
  }
);
console.log(items.data);


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
conversation_item_list = client.conversations.items.create(
    conversation_id="conv_123",
    items=[{
        "content": "string",
        "role": "user",
    }],
)
print(conversation_item_list.first_id)

####### csharp

using System;
using System.Collections.Generic;
using OpenAI.Conversations;

OpenAIConversationClient client = new(
    apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY")
);

ConversationItemList created = client.ConversationItems.Create(
    conversationId: "conv_123",
    new CreateConversationItemsOptions
    {
        Items = new List<ConversationItem>
        {
            new ConversationMessage
            {
                Role = "user",
                Content =
                {
                    new ConversationInputText { Text = "Hello!" }
                }
            },
            new ConversationMessage
            {
                Role = "user",
                Content =
                {
                    new ConversationInputText { Text = "How are you?" }
                }
            }
        }
    }
);
Console.WriteLine(created.Data.Count);


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const conversationItemList = await client.conversations.items.create('conv_123', {
  items: [{ content: 'string', role: 'user' }],
});

console.log(conversationItemList.first_id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/conversations"
  "github.com/openai/openai-go/option"
  "github.com/openai/openai-go/responses"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  conversationItemList, err := client.Conversations.Items.New(
    context.TODO(),
    "conv_123",
    conversations.ItemNewParams{
      Items: []responses.ResponseInputItemUnionParam{responses.ResponseInputItemUnionParam{
        OfMessage: &responses.EasyInputMessageParam{
          Content: responses.EasyInputMessageContentUnionParam{
            OfString: openai.String("string"),
          },
          Role: responses.EasyInputMessageRoleUser,
        },
      }},
    },
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", conversationItemList.FirstID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.conversations.items.ConversationItemList;
import com.openai.models.conversations.items.ItemCreateParams;
import com.openai.models.responses.EasyInputMessage;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        ItemCreateParams params = ItemCreateParams.builder()
            .conversationId("conv_123")
            .addItem(EasyInputMessage.builder()
                .content("string")
                .role(EasyInputMessage.Role.USER)
                .build())
            .build();
        ConversationItemList conversationItemList = client.conversations().items().create(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

conversation_item_list = openai.conversations.items.create("conv_123", items: [{content: "string", role: :user}])

puts(conversation_item_list)

###### response

{
  "object": "list",
  "data": [
    {
      "type": "message",
      "id": "msg_abc",
      "status": "completed",
      "role": "user",
      "content": [
        {"type": "input_text", "text": "Hello!"}
      ]
    },
    {
      "type": "message",
      "id": "msg_def",
      "status": "completed",
      "role": "user",
      "content": [
        {"type": "input_text", "text": "How are you?"}
      ]
    }
  ],
  "first_id": "msg_abc",
  "last_id": "msg_def",
  "has_more": false
}



#### description

Create items in a conversation with the given ID.

### get

#### operationId

listConversationItems

#### tags

- Conversations

#### summary

List items

#### parameters

##### in

path

##### name

conversation_id

##### required

true

##### schema

###### type

string

###### example

conv_123

##### description

The ID of the conversation to list items for.

##### name

limit

##### in

query

##### description

A limit on the number of objects to be returned. Limit can range between
1 and 100, and the default is 20.


##### required

false

##### schema

###### type

integer

###### default

20

##### in

query

##### name

order

##### schema

###### type

string

###### enum

- asc
- desc

##### description

The order to return the input items in. Default is `desc`.
- `asc`: Return the input items in ascending order.
- `desc`: Return the input items in descending order.


##### in

query

##### name

after

##### schema

###### type

string

##### description

An item ID to list items after, used in pagination.


##### name

include

##### in

query

##### required

false

##### schema

###### type

array

###### items

####### $ref

#/components/schemas/Includable

##### description

Specify additional output data to include in the model response. Currently
supported values are:
- `web_search_call.action.sources`: Include the sources of the web search tool call.
- `code_interpreter_call.outputs`: Includes the outputs of python code execution
  in code interpreter tool call items.
- `computer_call_output.output.image_url`: Include image urls from the computer call output.
- `file_search_call.results`: Include the search results of
  the file search tool call.
- `message.input_image.image_url`: Include image urls from the input message.
- `message.output_text.logprobs`: Include logprobs with assistant messages.
- `reasoning.encrypted_content`: Includes an encrypted version of reasoning
  tokens in reasoning item outputs. This enables reasoning items to be used in
  multi-turn conversations when using the Responses API statelessly (like
  when the `store` parameter is set to `false`, or when an organization is
  enrolled in the zero data retention program).



#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ConversationItemList

#### x-oaiMeta

##### name

List items

##### group

conversations

##### returns

Returns a [list object](https://platform.openai.com/docs/api-reference/conversations/list-items-object) containing Conversation items.


##### path

list-items

##### examples

###### title

List items in a conversation

###### request

####### curl

curl "https://api.openai.com/v1/conversations/conv_123/items?limit=10" \
  -H "Authorization: Bearer $OPENAI_API_KEY"


####### javascript

import OpenAI from "openai";
const client = new OpenAI();

const items = await client.conversations.items.list("conv_123", { limit: 10 });
console.log(items.data);


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
page = client.conversations.items.list(
    conversation_id="conv_123",
)
page = page.data[0]
print(page)

####### csharp

using System;
using OpenAI.Conversations;

OpenAIConversationClient client = new(
    apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY")
);

ConversationItemList items = client.ConversationItems.List(
    conversationId: "conv_123",
    new ListConversationItemsOptions { Limit = 10 }
);
Console.WriteLine(items.Data.Count);


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

// Automatically fetches more pages as needed.
for await (const conversationItem of client.conversations.items.list('conv_123')) {
  console.log(conversationItem);
}

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/conversations"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  page, err := client.Conversations.Items.List(
    context.TODO(),
    "conv_123",
    conversations.ItemListParams{

    },
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", page)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.conversations.items.ItemListPage;
import com.openai.models.conversations.items.ItemListParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        ItemListPage page = client.conversations().items().list("conv_123");
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

page = openai.conversations.items.list("conv_123")

puts(page)

###### response

{
  "object": "list",
  "data": [
    {
      "type": "message",
      "id": "msg_abc",
      "status": "completed",
      "role": "user",
      "content": [
        {"type": "input_text", "text": "Hello!"}
      ]
    }
  ],
  "first_id": "msg_abc",
  "last_id": "msg_abc",
  "has_more": false
}



#### description

List all items for a conversation with the given ID.

## /conversations/{conversation_id}/items/{item_id}

### get

#### operationId

getConversationItem

#### tags

- Conversations

#### summary

Retrieve an item

#### parameters

##### in

path

##### name

conversation_id

##### required

true

##### schema

###### type

string

###### example

conv_123

##### description

The ID of the conversation that contains the item.

##### in

path

##### name

item_id

##### required

true

##### schema

###### type

string

###### example

msg_abc

##### description

The ID of the item to retrieve.

##### name

include

##### in

query

##### required

false

##### schema

###### type

array

###### items

####### $ref

#/components/schemas/Includable

##### description

Additional fields to include in the response. See the `include`
parameter for [listing Conversation items above](https://platform.openai.com/docs/api-reference/conversations/list-items#conversations_list_items-include) for more information.



#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ConversationItem

#### x-oaiMeta

##### name

Retrieve an item

##### group

conversations

##### returns

Returns a [Conversation Item](https://platform.openai.com/docs/api-reference/conversations/item-object).


##### path

get-item

##### examples

###### title

Retrieve an item

###### request

####### curl

curl https://api.openai.com/v1/conversations/conv_123/items/msg_abc \
  -H "Authorization: Bearer $OPENAI_API_KEY"


####### javascript

import OpenAI from "openai";
const client = new OpenAI();

const item = await client.conversations.items.retrieve(
  "conv_123",
  "msg_abc"
);
console.log(item);


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
conversation_item = client.conversations.items.retrieve(
    item_id="msg_abc",
    conversation_id="conv_123",
)
print(conversation_item)

####### csharp

using System;
using OpenAI.Conversations;

OpenAIConversationClient client = new(
    apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY")
);

ConversationItem item = client.ConversationItems.Get(
    conversationId: "conv_123",
    itemId: "msg_abc"
);
Console.WriteLine(item.Id);


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const conversationItem = await client.conversations.items.retrieve('msg_abc', {
  conversation_id: 'conv_123',
});

console.log(conversationItem);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/conversations"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  conversationItem, err := client.Conversations.Items.Get(
    context.TODO(),
    "conv_123",
    "msg_abc",
    conversations.ItemGetParams{

    },
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", conversationItem)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.conversations.items.ConversationItem;
import com.openai.models.conversations.items.ItemRetrieveParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        ItemRetrieveParams params = ItemRetrieveParams.builder()
            .conversationId("conv_123")
            .itemId("msg_abc")
            .build();
        ConversationItem conversationItem = client.conversations().items().retrieve(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

conversation_item = openai.conversations.items.retrieve("msg_abc", conversation_id: "conv_123")

puts(conversation_item)

###### response

{
  "type": "message",
  "id": "msg_abc",
  "status": "completed",
  "role": "user",
  "content": [
    {"type": "input_text", "text": "Hello!"}
  ]
}



#### description

Get a single item from a conversation with the given IDs.

### delete

#### operationId

deleteConversationItem

#### tags

- Conversations

#### summary

Delete an item

#### parameters

##### in

path

##### name

conversation_id

##### required

true

##### schema

###### type

string

###### example

conv_123

##### description

The ID of the conversation that contains the item.

##### in

path

##### name

item_id

##### required

true

##### schema

###### type

string

###### example

msg_abc

##### description

The ID of the item to delete.


#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ConversationResource

#### x-oaiMeta

##### name

Delete an item

##### group

conversations

##### returns

Returns the updated [Conversation](https://platform.openai.com/docs/api-reference/conversations/object) object.


##### path

delete-item

##### examples

###### title

Delete an item

###### request

####### curl

curl -X DELETE https://api.openai.com/v1/conversations/conv_123/items/msg_abc \
  -H "Authorization: Bearer $OPENAI_API_KEY"


####### javascript

import OpenAI from "openai";
const client = new OpenAI();

const conversation = await client.conversations.items.delete(
  "conv_123",
  "msg_abc"
);
console.log(conversation);


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
conversation = client.conversations.items.delete(
    item_id="msg_abc",
    conversation_id="conv_123",
)
print(conversation.id)

####### csharp

using System;
using OpenAI.Conversations;

OpenAIConversationClient client = new(
    apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY")
);

Conversation conversation = client.ConversationItems.Delete(
    conversationId: "conv_123",
    itemId: "msg_abc"
);
Console.WriteLine(conversation.Id);


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const conversation = await client.conversations.items.delete('msg_abc', { conversation_id: 'conv_123' });

console.log(conversation.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  conversation, err := client.Conversations.Items.Delete(
    context.TODO(),
    "conv_123",
    "msg_abc",
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", conversation.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.conversations.Conversation;
import com.openai.models.conversations.items.ItemDeleteParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        ItemDeleteParams params = ItemDeleteParams.builder()
            .conversationId("conv_123")
            .itemId("msg_abc")
            .build();
        Conversation conversation = client.conversations().items().delete(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

conversation = openai.conversations.items.delete("msg_abc", conversation_id: "conv_123")

puts(conversation)

###### response

{
  "id": "conv_123",
  "object": "conversation",
  "created_at": 1741900000,
  "metadata": {"topic": "demo"}
}



#### description

Delete an item from a conversation with the given IDs.

## /embeddings

### post

#### operationId

createEmbedding

#### tags

- Embeddings

#### summary

Create embeddings

#### requestBody

##### required

true

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/CreateEmbeddingRequest

#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/CreateEmbeddingResponse

#### x-oaiMeta

##### name

Create embeddings

##### group

embeddings

##### returns

A list of [embedding](https://platform.openai.com/docs/api-reference/embeddings/object) objects.

##### examples

###### response

{
  "object": "list",
  "data": [
    {
      "object": "embedding",
      "embedding": [
        0.0023064255,
        -0.009327292,
        .... (1536 floats total for ada-002)
        -0.0028842222,
      ],
      "index": 0
    }
  ],
  "model": "text-embedding-ada-002",
  "usage": {
    "prompt_tokens": 8,
    "total_tokens": 8
  }
}


###### request

####### curl

curl https://api.openai.com/v1/embeddings \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "input": "The food was delicious and the waiter...",
    "model": "text-embedding-ada-002",
    "encoding_format": "float"
  }'


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
create_embedding_response = client.embeddings.create(
    input="The quick brown fox jumped over the lazy dog",
    model="text-embedding-3-small",
)
print(create_embedding_response.data)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const createEmbeddingResponse = await client.embeddings.create({
  input: 'The quick brown fox jumped over the lazy dog',
  model: 'text-embedding-3-small',
});

console.log(createEmbeddingResponse.data);

####### csharp

using System;

using OpenAI.Embeddings;

EmbeddingClient client = new(
    model: "text-embedding-3-small",
    apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY")
);

OpenAIEmbedding embedding = client.GenerateEmbedding(input: "The quick brown fox jumped over the lazy dog");
ReadOnlyMemory<float> vector = embedding.ToFloats();

for (int i = 0; i < vector.Length; i++)
{
    Console.WriteLine($"  [{i,4}] = {vector.Span[i]}");
}


####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  createEmbeddingResponse, err := client.Embeddings.New(context.TODO(), openai.EmbeddingNewParams{
    Input: openai.EmbeddingNewParamsInputUnion{
      OfString: openai.String("The quick brown fox jumped over the lazy dog"),
    },
    Model: openai.EmbeddingModelTextEmbeddingAda002,
  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", createEmbeddingResponse.Data)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.embeddings.CreateEmbeddingResponse;
import com.openai.models.embeddings.EmbeddingCreateParams;
import com.openai.models.embeddings.EmbeddingModel;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        EmbeddingCreateParams params = EmbeddingCreateParams.builder()
            .input("The quick brown fox jumped over the lazy dog")
            .model(EmbeddingModel.TEXT_EMBEDDING_ADA_002)
            .build();
        CreateEmbeddingResponse createEmbeddingResponse = client.embeddings().create(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

create_embedding_response = openai.embeddings.create(
  input: "The quick brown fox jumped over the lazy dog",
  model: :"text-embedding-ada-002"
)

puts(create_embedding_response)

#### description

Creates an embedding vector representing the input text.

## /evals

### get

#### operationId

listEvals

#### tags

- Evals

#### summary

List evals

#### parameters

##### name

after

##### in

query

##### description

Identifier for the last eval from the previous pagination request.

##### required

false

##### schema

###### type

string

##### name

limit

##### in

query

##### description

Number of evals to retrieve.

##### required

false

##### schema

###### type

integer

###### default

20

##### name

order

##### in

query

##### description

Sort order for evals by timestamp. Use `asc` for ascending order or `desc` for descending order.

##### required

false

##### schema

###### type

string

###### enum

- asc
- desc

###### default

asc

##### name

order_by

##### in

query

##### description

Evals can be ordered by creation time or last updated time. Use
`created_at` for creation time or `updated_at` for last updated time.


##### required

false

##### schema

###### type

string

###### enum

- created_at
- updated_at

###### default

created_at


#### responses

##### 200

###### description

A list of evals

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/EvalList

#### x-oaiMeta

##### name

List evals

##### group

evals

##### returns

A list of [evals](https://platform.openai.com/docs/api-reference/evals/object) matching the specified filters.

##### path

list

##### examples

###### response

{
  "object": "list",
  "data": [
    {
      "id": "eval_67abd54d9b0081909a86353f6fb9317a",
      "object": "eval",
      "data_source_config": {
        "type": "stored_completions",
        "metadata": {
          "usecase": "push_notifications_summarizer"
        },
        "schema": {
          "type": "object",
          "properties": {
            "item": {
              "type": "object"
            },
            "sample": {
              "type": "object"
            }
          },
          "required": [
            "item",
            "sample"
          ]
        }
      },
      "testing_criteria": [
        {
          "name": "Push Notification Summary Grader",
          "id": "Push Notification Summary Grader-9b876f24-4762-4be9-aff4-db7a9b31c673",
          "type": "label_model",
          "model": "o3-mini",
          "input": [
            {
              "type": "message",
              "role": "developer",
              "content": {
                "type": "input_text",
                "text": "\nLabel the following push notification summary as either correct or incorrect.\nThe push notification and the summary will be provided below.\nA good push notificiation summary is concise and snappy.\nIf it is good, then label it as correct, if not, then incorrect.\n"
              }
            },
            {
              "type": "message",
              "role": "user",
              "content": {
                "type": "input_text",
                "text": "\nPush notifications: {{item.input}}\nSummary: {{sample.output_text}}\n"
              }
            }
          ],
          "passing_labels": [
            "correct"
          ],
          "labels": [
            "correct",
            "incorrect"
          ],
          "sampling_params": null
        }
      ],
      "name": "Push Notification Summary Grader",
      "created_at": 1739314509,
      "metadata": {
        "description": "A stored completions eval for push notification summaries"
      }
    }
  ],
  "first_id": "eval_67abd54d9b0081909a86353f6fb9317a",
  "last_id": "eval_67aa884cf6688190b58f657d4441c8b7",
  "has_more": true
}


###### request

####### curl

curl https://api.openai.com/v1/evals?limit=1 \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
page = client.evals.list()
page = page.data[0]
print(page.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

// Automatically fetches more pages as needed.
for await (const evalListResponse of client.evals.list()) {
  console.log(evalListResponse.id);
}

####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.evals.EvalListPage;
import com.openai.models.evals.EvalListParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        EvalListPage page = client.evals().list();
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

page = openai.evals.list

puts(page)

#### description

List evaluations for a project.


### post

#### operationId

createEval

#### tags

- Evals

#### summary

Create eval

#### requestBody

##### required

true

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/CreateEvalRequest

#### responses

##### 201

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/Eval

#### x-oaiMeta

##### name

Create eval

##### group

evals

##### returns

The created [Eval](https://platform.openai.com/docs/api-reference/evals/object) object.

##### path

post

##### examples

###### response

{
  "object": "eval",
  "id": "eval_67b7fa9a81a88190ab4aa417e397ea21",
  "data_source_config": {
    "type": "stored_completions",
    "metadata": {
      "usecase": "chatbot"
    },
    "schema": {
      "type": "object",
      "properties": {
        "item": {
          "type": "object"
        },
        "sample": {
          "type": "object"
        }
      },
      "required": [
        "item",
        "sample"
      ]
  },
  "testing_criteria": [
    {
      "name": "Example label grader",
      "type": "label_model",
      "model": "o3-mini",
      "input": [
        {
          "type": "message",
          "role": "developer",
          "content": {
            "type": "input_text",
            "text": "Classify the sentiment of the following statement as one of positive, neutral, or negative"
          }
        },
        {
          "type": "message",
          "role": "user",
          "content": {
            "type": "input_text",
            "text": "Statement: {{item.input}}"
          }
        }
      ],
      "passing_labels": [
        "positive"
      ],
      "labels": [
        "positive",
        "neutral",
        "negative"
      ]
    }
  ],
  "name": "Sentiment",
  "created_at": 1740110490,
  "metadata": {
    "description": "An eval for sentiment analysis"
  }
}


###### request

####### curl

curl https://api.openai.com/v1/evals \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
        "name": "Sentiment",
        "data_source_config": {
          "type": "stored_completions",
          "metadata": {
              "usecase": "chatbot"
          }
        },
        "testing_criteria": [
          {
            "type": "label_model",
            "model": "o3-mini",
            "input": [
              {
                "role": "developer",
                "content": "Classify the sentiment of the following statement as one of 'positive', 'neutral', or 'negative'"
              },
              {
                "role": "user",
                "content": "Statement: {{item.input}}"
              }
            ],
            "passing_labels": [
              "positive"
            ],
            "labels": [
              "positive",
              "neutral",
              "negative"
            ],
            "name": "Example label grader"
          }
        ]
      }'


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
eval = client.evals.create(
    data_source_config={
        "item_schema": {
            "foo": "bar"
        },
        "type": "custom",
    },
    testing_criteria=[{
        "input": [{
            "content": "content",
            "role": "role",
        }],
        "labels": ["string"],
        "model": "model",
        "name": "name",
        "passing_labels": ["string"],
        "type": "label_model",
    }],
)
print(eval.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const _eval = await client.evals.create({
  data_source_config: { item_schema: { foo: 'bar' }, type: 'custom' },
  testing_criteria: [
    {
      input: [{ content: 'content', role: 'role' }],
      labels: ['string'],
      model: 'model',
      name: 'name',
      passing_labels: ['string'],
      type: 'label_model',
    },
  ],
});

console.log(_eval.id);

####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.JsonValue;
import com.openai.models.evals.EvalCreateParams;
import com.openai.models.evals.EvalCreateResponse;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        EvalCreateParams params = EvalCreateParams.builder()
            .customDataSourceConfig(EvalCreateParams.DataSourceConfig.Custom.ItemSchema.builder()
                .putAdditionalProperty("foo", JsonValue.from("bar"))
                .build())
            .addTestingCriterion(EvalCreateParams.TestingCriterion.LabelModel.builder()
                .addInput(EvalCreateParams.TestingCriterion.LabelModel.Input.SimpleInputMessage.builder()
                    .content("content")
                    .role("role")
                    .build())
                .addLabel("string")
                .model("model")
                .name("name")
                .addPassingLabel("string")
                .build())
            .build();
        EvalCreateResponse eval = client.evals().create(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

eval_ = openai.evals.create(
  data_source_config: {item_schema: {foo: "bar"}, type: :custom},
  testing_criteria: [
    {
      input: [{content: "content", role: "role"}],
      labels: ["string"],
      model: "model",
      name: "name",
      passing_labels: ["string"],
      type: :label_model
    }
  ]
)

puts(eval_)

#### description

Create the structure of an evaluation that can be used to test a model's performance.
An evaluation is a set of testing criteria and the config for a data source, which dictates the schema of the data used in the evaluation. After creating an evaluation, you can run it on different models and model parameters. We support several types of graders and datasources.
For more information, see the [Evals guide](https://platform.openai.com/docs/guides/evals).


## /evals/{eval_id}

### get

#### operationId

getEval

#### tags

- Evals

#### summary

Get an eval

#### parameters

##### name

eval_id

##### in

path

##### required

true

##### schema

###### type

string

##### description

The ID of the evaluation to retrieve.


#### responses

##### 200

###### description

The evaluation

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/Eval

#### x-oaiMeta

##### name

Get an eval

##### group

evals

##### returns

The [Eval](https://platform.openai.com/docs/api-reference/evals/object) object matching the specified ID.

##### path

get

##### examples

###### response

{
  "object": "eval",
  "id": "eval_67abd54d9b0081909a86353f6fb9317a",
  "data_source_config": {
    "type": "custom",
    "schema": {
      "type": "object",
      "properties": {
        "item": {
          "type": "object",
          "properties": {
            "input": {
              "type": "string"
            },
            "ground_truth": {
              "type": "string"
            }
          },
          "required": [
            "input",
            "ground_truth"
          ]
        }
      },
      "required": [
        "item"
      ]
    }
  },
  "testing_criteria": [
    {
      "name": "String check",
      "id": "String check-2eaf2d8d-d649-4335-8148-9535a7ca73c2",
      "type": "string_check",
      "input": "{{item.input}}",
      "reference": "{{item.ground_truth}}",
      "operation": "eq"
    }
  ],
  "name": "External Data Eval",
  "created_at": 1739314509,
  "metadata": {},
}


###### request

####### curl

curl https://api.openai.com/v1/evals/eval_67abd54d9b0081909a86353f6fb9317a \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
eval = client.evals.retrieve(
    "eval_id",
)
print(eval.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const _eval = await client.evals.retrieve('eval_id');

console.log(_eval.id);

####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.evals.EvalRetrieveParams;
import com.openai.models.evals.EvalRetrieveResponse;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        EvalRetrieveResponse eval = client.evals().retrieve("eval_id");
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

eval_ = openai.evals.retrieve("eval_id")

puts(eval_)

#### description

Get an evaluation by ID.


### post

#### operationId

updateEval

#### tags

- Evals

#### summary

Update an eval

#### parameters

##### name

eval_id

##### in

path

##### required

true

##### schema

###### type

string

##### description

The ID of the evaluation to update.


#### requestBody

##### description

Request to update an evaluation

##### required

true

##### content

###### application/json

####### schema

######## type

object

######## properties

######### name

########## type

string

########## description

Rename the evaluation.

######### metadata

########## $ref

#/components/schemas/Metadata

#### responses

##### 200

###### description

The updated evaluation

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/Eval

#### x-oaiMeta

##### name

Update an eval

##### group

evals

##### returns

The [Eval](https://platform.openai.com/docs/api-reference/evals/object) object matching the updated version.

##### path

update

##### examples

###### response

{
  "object": "eval",
  "id": "eval_67abd54d9b0081909a86353f6fb9317a",
  "data_source_config": {
    "type": "custom",
    "schema": {
      "type": "object",
      "properties": {
        "item": {
          "type": "object",
          "properties": {
            "input": {
              "type": "string"
            },
            "ground_truth": {
              "type": "string"
            }
          },
          "required": [
            "input",
            "ground_truth"
          ]
        }
      },
      "required": [
        "item"
      ]
    }
  },
  "testing_criteria": [
    {
      "name": "String check",
      "id": "String check-2eaf2d8d-d649-4335-8148-9535a7ca73c2",
      "type": "string_check",
      "input": "{{item.input}}",
      "reference": "{{item.ground_truth}}",
      "operation": "eq"
    }
  ],
  "name": "Updated Eval",
  "created_at": 1739314509,
  "metadata": {"description": "Updated description"},
}


###### request

####### curl

curl https://api.openai.com/v1/evals/eval_67abd54d9b0081909a86353f6fb9317a \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"name": "Updated Eval", "metadata": {"description": "Updated description"}}'


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
eval = client.evals.update(
    eval_id="eval_id",
)
print(eval.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const _eval = await client.evals.update('eval_id');

console.log(_eval.id);

####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.evals.EvalUpdateParams;
import com.openai.models.evals.EvalUpdateResponse;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        EvalUpdateResponse eval = client.evals().update("eval_id");
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

eval_ = openai.evals.update("eval_id")

puts(eval_)

#### description

Update certain properties of an evaluation.


### delete

#### operationId

deleteEval

#### tags

- Evals

#### summary

Delete an eval

#### parameters

##### name

eval_id

##### in

path

##### required

true

##### schema

###### type

string

##### description

The ID of the evaluation to delete.


#### responses

##### 200

###### description

Successfully deleted the evaluation.

###### content

####### application/json

######## schema

######### type

object

######### properties

########## object

########### type

string

########### example

eval.deleted

########## deleted

########### type

boolean

########### example

true

########## eval_id

########### type

string

########### example

eval_abc123

######### required

- object
- deleted
- eval_id

##### 404

###### description

Evaluation not found.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/Error

#### x-oaiMeta

##### name

Delete an eval

##### group

evals

##### returns

A deletion confirmation object.

##### examples

###### response

{
  "object": "eval.deleted",
  "deleted": true,
  "eval_id": "eval_abc123"
}


###### request

####### curl

curl https://api.openai.com/v1/evals/eval_abc123 \
  -X DELETE \
  -H "Authorization: Bearer $OPENAI_API_KEY"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
eval = client.evals.delete(
    "eval_id",
)
print(eval.eval_id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const _eval = await client.evals.delete('eval_id');

console.log(_eval.eval_id);

####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.evals.EvalDeleteParams;
import com.openai.models.evals.EvalDeleteResponse;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        EvalDeleteResponse eval = client.evals().delete("eval_id");
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

eval_ = openai.evals.delete("eval_id")

puts(eval_)

#### description

Delete an evaluation.


## /evals/{eval_id}/runs

### get

#### operationId

getEvalRuns

#### tags

- Evals

#### summary

Get eval runs

#### parameters

##### name

eval_id

##### in

path

##### required

true

##### schema

###### type

string

##### description

The ID of the evaluation to retrieve runs for.

##### name

after

##### in

query

##### description

Identifier for the last run from the previous pagination request.

##### required

false

##### schema

###### type

string

##### name

limit

##### in

query

##### description

Number of runs to retrieve.

##### required

false

##### schema

###### type

integer

###### default

20

##### name

order

##### in

query

##### description

Sort order for runs by timestamp. Use `asc` for ascending order or `desc` for descending order. Defaults to `asc`.

##### required

false

##### schema

###### type

string

###### enum

- asc
- desc

###### default

asc

##### name

status

##### in

query

##### description

Filter runs by status. One of `queued` | `in_progress` | `failed` | `completed` | `canceled`.

##### required

false

##### schema

###### type

string

###### enum

- queued
- in_progress
- completed
- canceled
- failed


#### responses

##### 200

###### description

A list of runs for the evaluation

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/EvalRunList

#### x-oaiMeta

##### name

Get eval runs

##### group

evals

##### returns

A list of [EvalRun](https://platform.openai.com/docs/api-reference/evals/run-object) objects matching the specified ID.

##### path

get-runs

##### examples

###### response

{
  "object": "list",
  "data": [
    {
      "object": "eval.run",
      "id": "evalrun_67e0c7d31560819090d60c0780591042",
      "eval_id": "eval_67e0c726d560819083f19a957c4c640b",
      "report_url": "https://platform.openai.com/evaluations/eval_67e0c726d560819083f19a957c4c640b",
      "status": "completed",
      "model": "o3-mini",
      "name": "bulk_with_negative_examples_o3-mini",
      "created_at": 1742784467,
      "result_counts": {
        "total": 1,
        "errored": 0,
        "failed": 0,
        "passed": 1
      },
      "per_model_usage": [
        {
          "model_name": "o3-mini",
          "invocation_count": 1,
          "prompt_tokens": 563,
          "completion_tokens": 874,
          "total_tokens": 1437,
          "cached_tokens": 0
        }
      ],
      "per_testing_criteria_results": [
        {
          "testing_criteria": "Push Notification Summary Grader-1808cd0b-eeec-4e0b-a519-337e79f4f5d1",
          "passed": 1,
          "failed": 0
        }
      ],
      "data_source": {
        "type": "completions",
        "source": {
          "type": "file_content",
          "content": [
            {
              "item": {
                "notifications": "\n- New message from Sarah: \"Can you call me later?\"\n- Your package has been delivered!\n- Flash sale: 20% off electronics for the next 2 hours!\n"
              }
            }
          ]
        },
        "input_messages": {
          "type": "template",
          "template": [
            {
              "type": "message",
              "role": "developer",
              "content": {
                "type": "input_text",
                "text": "\n\n\n\nYou are a helpful assistant that takes in an array of push notifications and returns a collapsed summary of them.\nThe push notification will be provided as follows:\n<push_notifications>\n...notificationlist...\n</push_notifications>\n\nYou should return just the summary and nothing else.\n\n\nYou should return a summary that is concise and snappy.\n\n\nHere is an example of a good summary:\n<push_notifications>\n- Traffic alert: Accident reported on Main Street.- Package out for delivery: Expected by 5 PM.- New friend suggestion: Connect with Emma.\n</push_notifications>\n<summary>\nTraffic alert, package expected by 5pm, suggestion for new friend (Emily).\n</summary>\n\n\nHere is an example of a bad summary:\n<push_notifications>\n- Traffic alert: Accident reported on Main Street.- Package out for delivery: Expected by 5 PM.- New friend suggestion: Connect with Emma.\n</push_notifications>\n<summary>\nTraffic alert reported on main street. You have a package that will arrive by 5pm, Emily is a new friend suggested for you.\n</summary>\n"
              }
            },
            {
              "type": "message",
              "role": "user",
              "content": {
                "type": "input_text",
                "text": "<push_notifications>{{item.notifications}}</push_notifications>"
              }
            }
          ]
        },
        "model": "o3-mini",
        "sampling_params": null
      },
      "error": null,
      "metadata": {}
    }
  ],
  "first_id": "evalrun_67e0c7d31560819090d60c0780591042",
  "last_id": "evalrun_67e0c7d31560819090d60c0780591042",
  "has_more": true
}


###### request

####### curl

curl https://api.openai.com/v1/evals/egroup_67abd54d9b0081909a86353f6fb9317a/runs \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
page = client.evals.runs.list(
    eval_id="eval_id",
)
page = page.data[0]
print(page.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

// Automatically fetches more pages as needed.
for await (const runListResponse of client.evals.runs.list('eval_id')) {
  console.log(runListResponse.id);
}

####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.evals.runs.RunListPage;
import com.openai.models.evals.runs.RunListParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        RunListPage page = client.evals().runs().list("eval_id");
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

page = openai.evals.runs.list("eval_id")

puts(page)

#### description

Get a list of runs for an evaluation.


### post

#### operationId

createEvalRun

#### tags

- Evals

#### summary

Create eval run

#### parameters

##### in

path

##### name

eval_id

##### required

true

##### schema

###### type

string

##### description

The ID of the evaluation to create a run for.


#### requestBody

##### required

true

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/CreateEvalRunRequest

#### responses

##### 201

###### description

Successfully created a run for the evaluation

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/EvalRun

##### 400

###### description

Bad request (for example, missing eval object)

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/Error

#### x-oaiMeta

##### name

Create eval run

##### group

evals

##### returns

The [EvalRun](https://platform.openai.com/docs/api-reference/evals/run-object) object matching the specified ID.

##### examples

###### response

{
  "object": "eval.run",
  "id": "evalrun_67e57965b480819094274e3a32235e4c",
  "eval_id": "eval_67e579652b548190aaa83ada4b125f47",
  "report_url": "https://platform.openai.com/evaluations/eval_67e579652b548190aaa83ada4b125f47&run_id=evalrun_67e57965b480819094274e3a32235e4c",
  "status": "queued",
  "model": "gpt-4o-mini",
  "name": "gpt-4o-mini",
  "created_at": 1743092069,
  "result_counts": {
    "total": 0,
    "errored": 0,
    "failed": 0,
    "passed": 0
  },
  "per_model_usage": null,
  "per_testing_criteria_results": null,
  "data_source": {
    "type": "completions",
    "source": {
      "type": "file_content",
      "content": [
        {
          "item": {
            "input": "Tech Company Launches Advanced Artificial Intelligence Platform",
            "ground_truth": "Technology"
          }
        }
      ]
    },
    "input_messages": {
      "type": "template",
      "template": [
        {
          "type": "message",
          "role": "developer",
          "content": {
            "type": "input_text",
            "text": "Categorize a given news headline into one of the following topics: Technology, Markets, World, Business, or Sports.\n\n# Steps\n\n1. Analyze the content of the news headline to understand its primary focus.\n2. Extract the subject matter, identifying any key indicators or keywords.\n3. Use the identified indicators to determine the most suitable category out of the five options: Technology, Markets, World, Business, or Sports.\n4. Ensure only one category is selected per headline.\n\n# Output Format\n\nRespond with the chosen category as a single word. For instance: \"Technology\", \"Markets\", \"World\", \"Business\", or \"Sports\".\n\n# Examples\n\n**Input**: \"Apple Unveils New iPhone Model, Featuring Advanced AI Features\"  \n**Output**: \"Technology\"\n\n**Input**: \"Global Stocks Mixed as Investors Await Central Bank Decisions\"  \n**Output**: \"Markets\"\n\n**Input**: \"War in Ukraine: Latest Updates on Negotiation Status\"  \n**Output**: \"World\"\n\n**Input**: \"Microsoft in Talks to Acquire Gaming Company for $2 Billion\"  \n**Output**: \"Business\"\n\n**Input**: \"Manchester United Secures Win in Premier League Football Match\"  \n**Output**: \"Sports\" \n\n# Notes\n\n- If the headline appears to fit into more than one category, choose the most dominant theme.\n- Keywords or phrases such as \"stocks\", \"company acquisition\", \"match\", or technological brands can be good indicators for classification.\n"
          }
        },
        {
          "type": "message",
          "role": "user",
          "content": {
            "type": "input_text",
            "text": "{{item.input}}"
          }
        }
      ]
    },
    "model": "gpt-4o-mini",
    "sampling_params": {
      "seed": 42,
      "temperature": 1.0,
      "top_p": 1.0,
      "max_completions_tokens": 2048
    }
  },
  "error": null,
  "metadata": {}
}


###### request

####### curl

curl https://api.openai.com/v1/evals/eval_67e579652b548190aaa83ada4b125f47/runs \
  -X POST \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"name":"gpt-4o-mini","data_source":{"type":"completions","input_messages":{"type":"template","template":[{"role":"developer","content":"Categorize a given news headline into one of the following topics: Technology, Markets, World, Business, or Sports.\n\n# Steps\n\n1. Analyze the content of the news headline to understand its primary focus.\n2. Extract the subject matter, identifying any key indicators or keywords.\n3. Use the identified indicators to determine the most suitable category out of the five options: Technology, Markets, World, Business, or Sports.\n4. Ensure only one category is selected per headline.\n\n# Output Format\n\nRespond with the chosen category as a single word. For instance: \"Technology\", \"Markets\", \"World\", \"Business\", or \"Sports\".\n\n# Examples\n\n**Input**: \"Apple Unveils New iPhone Model, Featuring Advanced AI Features\"  \n**Output**: \"Technology\"\n\n**Input**: \"Global Stocks Mixed as Investors Await Central Bank Decisions\"  \n**Output**: \"Markets\"\n\n**Input**: \"War in Ukraine: Latest Updates on Negotiation Status\"  \n**Output**: \"World\"\n\n**Input**: \"Microsoft in Talks to Acquire Gaming Company for $2 Billion\"  \n**Output**: \"Business\"\n\n**Input**: \"Manchester United Secures Win in Premier League Football Match\"  \n**Output**: \"Sports\" \n\n# Notes\n\n- If the headline appears to fit into more than one category, choose the most dominant theme.\n- Keywords or phrases such as \"stocks\", \"company acquisition\", \"match\", or technological brands can be good indicators for classification.\n"} , {"role":"user","content":"{{item.input}}"}]} ,"sampling_params":{"temperature":1,"max_completions_tokens":2048,"top_p":1,"seed":42},"model":"gpt-4o-mini","source":{"type":"file_content","content":[{"item":{"input":"Tech Company Launches Advanced Artificial Intelligence Platform","ground_truth":"Technology"}}]}}'


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
run = client.evals.runs.create(
    eval_id="eval_id",
    data_source={
        "source": {
            "content": [{
                "item": {
                    "foo": "bar"
                }
            }],
            "type": "file_content",
        },
        "type": "jsonl",
    },
)
print(run.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const run = await client.evals.runs.create('eval_id', {
  data_source: { source: { content: [{ item: { foo: 'bar' } }], type: 'file_content' }, type: 'jsonl' },
});

console.log(run.id);

####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.JsonValue;
import com.openai.models.evals.runs.CreateEvalJsonlRunDataSource;
import com.openai.models.evals.runs.RunCreateParams;
import com.openai.models.evals.runs.RunCreateResponse;
import java.util.List;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        RunCreateParams params = RunCreateParams.builder()
            .evalId("eval_id")
            .dataSource(CreateEvalJsonlRunDataSource.builder()
                .fileContentSource(List.of(CreateEvalJsonlRunDataSource.Source.FileContent.Content.builder()
                    .item(CreateEvalJsonlRunDataSource.Source.FileContent.Content.Item.builder()
                        .putAdditionalProperty("foo", JsonValue.from("bar"))
                        .build())
                    .build()))
                .build())
            .build();
        RunCreateResponse run = client.evals().runs().create(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

run = openai.evals.runs.create(
  "eval_id",
  data_source: {source: {content: [{item: {foo: "bar"}}], type: :file_content}, type: :jsonl}
)

puts(run)

#### description

Kicks off a new run for a given evaluation, specifying the data source, and what model configuration to use to test. The datasource will be validated against the schema specified in the config of the evaluation.


## /evals/{eval_id}/runs/{run_id}

### get

#### operationId

getEvalRun

#### tags

- Evals

#### summary

Get an eval run

#### parameters

##### name

eval_id

##### in

path

##### required

true

##### schema

###### type

string

##### description

The ID of the evaluation to retrieve runs for.

##### name

run_id

##### in

path

##### required

true

##### schema

###### type

string

##### description

The ID of the run to retrieve.


#### responses

##### 200

###### description

The evaluation run

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/EvalRun

#### x-oaiMeta

##### name

Get an eval run

##### group

evals

##### returns

The [EvalRun](https://platform.openai.com/docs/api-reference/evals/run-object) object matching the specified ID.

##### path

get

##### examples

###### response

{
  "object": "eval.run",
  "id": "evalrun_67abd54d60ec8190832b46859da808f7",
  "eval_id": "eval_67abd54d9b0081909a86353f6fb9317a",
  "report_url": "https://platform.openai.com/evaluations/eval_67abd54d9b0081909a86353f6fb9317a?run_id=evalrun_67abd54d60ec8190832b46859da808f7",
  "status": "queued",
  "model": "gpt-4o-mini",
  "name": "gpt-4o-mini",
  "created_at": 1743092069,
  "result_counts": {
    "total": 0,
    "errored": 0,
    "failed": 0,
    "passed": 0
  },
  "per_model_usage": null,
  "per_testing_criteria_results": null,
  "data_source": {
    "type": "completions",
    "source": {
      "type": "file_content",
      "content": [
        {
          "item": {
            "input": "Tech Company Launches Advanced Artificial Intelligence Platform",
            "ground_truth": "Technology"
          }
        },
        {
          "item": {
            "input": "Central Bank Increases Interest Rates Amid Inflation Concerns",
            "ground_truth": "Markets"
          }
        },
        {
          "item": {
            "input": "International Summit Addresses Climate Change Strategies",
            "ground_truth": "World"
          }
        },
        {
          "item": {
            "input": "Major Retailer Reports Record-Breaking Holiday Sales",
            "ground_truth": "Business"
          }
        },
        {
          "item": {
            "input": "National Team Qualifies for World Championship Finals",
            "ground_truth": "Sports"
          }
        },
        {
          "item": {
            "input": "Stock Markets Rally After Positive Economic Data Released",
            "ground_truth": "Markets"
          }
        },
        {
          "item": {
            "input": "Global Manufacturer Announces Merger with Competitor",
            "ground_truth": "Business"
          }
        },
        {
          "item": {
            "input": "Breakthrough in Renewable Energy Technology Unveiled",
            "ground_truth": "Technology"
          }
        },
        {
          "item": {
            "input": "World Leaders Sign Historic Climate Agreement",
            "ground_truth": "World"
          }
        },
        {
          "item": {
            "input": "Professional Athlete Sets New Record in Championship Event",
            "ground_truth": "Sports"
          }
        },
        {
          "item": {
            "input": "Financial Institutions Adapt to New Regulatory Requirements",
            "ground_truth": "Business"
          }
        },
        {
          "item": {
            "input": "Tech Conference Showcases Advances in Artificial Intelligence",
            "ground_truth": "Technology"
          }
        },
        {
          "item": {
            "input": "Global Markets Respond to Oil Price Fluctuations",
            "ground_truth": "Markets"
          }
        },
        {
          "item": {
            "input": "International Cooperation Strengthened Through New Treaty",
            "ground_truth": "World"
          }
        },
        {
          "item": {
            "input": "Sports League Announces Revised Schedule for Upcoming Season",
            "ground_truth": "Sports"
          }
        }
      ]
    },
    "input_messages": {
      "type": "template",
      "template": [
        {
          "type": "message",
          "role": "developer",
          "content": {
            "type": "input_text",
            "text": "Categorize a given news headline into one of the following topics: Technology, Markets, World, Business, or Sports.\n\n# Steps\n\n1. Analyze the content of the news headline to understand its primary focus.\n2. Extract the subject matter, identifying any key indicators or keywords.\n3. Use the identified indicators to determine the most suitable category out of the five options: Technology, Markets, World, Business, or Sports.\n4. Ensure only one category is selected per headline.\n\n# Output Format\n\nRespond with the chosen category as a single word. For instance: \"Technology\", \"Markets\", \"World\", \"Business\", or \"Sports\".\n\n# Examples\n\n**Input**: \"Apple Unveils New iPhone Model, Featuring Advanced AI Features\"  \n**Output**: \"Technology\"\n\n**Input**: \"Global Stocks Mixed as Investors Await Central Bank Decisions\"  \n**Output**: \"Markets\"\n\n**Input**: \"War in Ukraine: Latest Updates on Negotiation Status\"  \n**Output**: \"World\"\n\n**Input**: \"Microsoft in Talks to Acquire Gaming Company for $2 Billion\"  \n**Output**: \"Business\"\n\n**Input**: \"Manchester United Secures Win in Premier League Football Match\"  \n**Output**: \"Sports\" \n\n# Notes\n\n- If the headline appears to fit into more than one category, choose the most dominant theme.\n- Keywords or phrases such as \"stocks\", \"company acquisition\", \"match\", or technological brands can be good indicators for classification.\n"
          }
        },
        {
          "type": "message",
          "role": "user",
          "content": {
            "type": "input_text",
            "text": "{{item.input}}"
          }
        }
      ]
    },
    "model": "gpt-4o-mini",
    "sampling_params": {
      "seed": 42,
      "temperature": 1.0,
      "top_p": 1.0,
      "max_completions_tokens": 2048
    }
  },
  "error": null,
  "metadata": {}
}


###### request

####### curl

curl https://api.openai.com/v1/evals/eval_67abd54d9b0081909a86353f6fb9317a/runs/evalrun_67abd54d60ec8190832b46859da808f7 \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
run = client.evals.runs.retrieve(
    run_id="run_id",
    eval_id="eval_id",
)
print(run.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const run = await client.evals.runs.retrieve('run_id', { eval_id: 'eval_id' });

console.log(run.id);

####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.evals.runs.RunRetrieveParams;
import com.openai.models.evals.runs.RunRetrieveResponse;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        RunRetrieveParams params = RunRetrieveParams.builder()
            .evalId("eval_id")
            .runId("run_id")
            .build();
        RunRetrieveResponse run = client.evals().runs().retrieve(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

run = openai.evals.runs.retrieve("run_id", eval_id: "eval_id")

puts(run)

#### description

Get an evaluation run by ID.


### post

#### operationId

cancelEvalRun

#### tags

- Evals

#### summary

Cancel eval run

#### parameters

##### name

eval_id

##### in

path

##### required

true

##### schema

###### type

string

##### description

The ID of the evaluation whose run you want to cancel.

##### name

run_id

##### in

path

##### required

true

##### schema

###### type

string

##### description

The ID of the run to cancel.


#### responses

##### 200

###### description

The canceled eval run object

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/EvalRun

#### x-oaiMeta

##### name

Cancel eval run

##### group

evals

##### returns

The updated [EvalRun](https://platform.openai.com/docs/api-reference/evals/run-object) object reflecting that the run is canceled.

##### path

post

##### examples

###### response

{
  "object": "eval.run",
  "id": "evalrun_67abd54d60ec8190832b46859da808f7",
  "eval_id": "eval_67abd54d9b0081909a86353f6fb9317a",
  "report_url": "https://platform.openai.com/evaluations/eval_67abd54d9b0081909a86353f6fb9317a?run_id=evalrun_67abd54d60ec8190832b46859da808f7",
  "status": "canceled",
  "model": "gpt-4o-mini",
  "name": "gpt-4o-mini",
  "created_at": 1743092069,
  "result_counts": {
    "total": 0,
    "errored": 0,
    "failed": 0,
    "passed": 0
  },
  "per_model_usage": null,
  "per_testing_criteria_results": null,
  "data_source": {
    "type": "completions",
    "source": {
      "type": "file_content",
      "content": [
        {
          "item": {
            "input": "Tech Company Launches Advanced Artificial Intelligence Platform",
            "ground_truth": "Technology"
          }
        },
        {
          "item": {
            "input": "Central Bank Increases Interest Rates Amid Inflation Concerns",
            "ground_truth": "Markets"
          }
        },
        {
          "item": {
            "input": "International Summit Addresses Climate Change Strategies",
            "ground_truth": "World"
          }
        },
        {
          "item": {
            "input": "Major Retailer Reports Record-Breaking Holiday Sales",
            "ground_truth": "Business"
          }
        },
        {
          "item": {
            "input": "National Team Qualifies for World Championship Finals",
            "ground_truth": "Sports"
          }
        },
        {
          "item": {
            "input": "Stock Markets Rally After Positive Economic Data Released",
            "ground_truth": "Markets"
          }
        },
        {
          "item": {
            "input": "Global Manufacturer Announces Merger with Competitor",
            "ground_truth": "Business"
          }
        },
        {
          "item": {
            "input": "Breakthrough in Renewable Energy Technology Unveiled",
            "ground_truth": "Technology"
          }
        },
        {
          "item": {
            "input": "World Leaders Sign Historic Climate Agreement",
            "ground_truth": "World"
          }
        },
        {
          "item": {
            "input": "Professional Athlete Sets New Record in Championship Event",
            "ground_truth": "Sports"
          }
        },
        {
          "item": {
            "input": "Financial Institutions Adapt to New Regulatory Requirements",
            "ground_truth": "Business"
          }
        },
        {
          "item": {
            "input": "Tech Conference Showcases Advances in Artificial Intelligence",
            "ground_truth": "Technology"
          }
        },
        {
          "item": {
            "input": "Global Markets Respond to Oil Price Fluctuations",
            "ground_truth": "Markets"
          }
        },
        {
          "item": {
            "input": "International Cooperation Strengthened Through New Treaty",
            "ground_truth": "World"
          }
        },
        {
          "item": {
            "input": "Sports League Announces Revised Schedule for Upcoming Season",
            "ground_truth": "Sports"
          }
        }
      ]
    },
    "input_messages": {
      "type": "template",
      "template": [
        {
          "type": "message",
          "role": "developer",
          "content": {
            "type": "input_text",
            "text": "Categorize a given news headline into one of the following topics: Technology, Markets, World, Business, or Sports.\n\n# Steps\n\n1. Analyze the content of the news headline to understand its primary focus.\n2. Extract the subject matter, identifying any key indicators or keywords.\n3. Use the identified indicators to determine the most suitable category out of the five options: Technology, Markets, World, Business, or Sports.\n4. Ensure only one category is selected per headline.\n\n# Output Format\n\nRespond with the chosen category as a single word. For instance: \"Technology\", \"Markets\", \"World\", \"Business\", or \"Sports\".\n\n# Examples\n\n**Input**: \"Apple Unveils New iPhone Model, Featuring Advanced AI Features\"  \n**Output**: \"Technology\"\n\n**Input**: \"Global Stocks Mixed as Investors Await Central Bank Decisions\"  \n**Output**: \"Markets\"\n\n**Input**: \"War in Ukraine: Latest Updates on Negotiation Status\"  \n**Output**: \"World\"\n\n**Input**: \"Microsoft in Talks to Acquire Gaming Company for $2 Billion\"  \n**Output**: \"Business\"\n\n**Input**: \"Manchester United Secures Win in Premier League Football Match\"  \n**Output**: \"Sports\" \n\n# Notes\n\n- If the headline appears to fit into more than one category, choose the most dominant theme.\n- Keywords or phrases such as \"stocks\", \"company acquisition\", \"match\", or technological brands can be good indicators for classification.\n"
          }
        },
        {
          "type": "message",
          "role": "user",
          "content": {
            "type": "input_text",
            "text": "{{item.input}}"
          }
        }
      ]
    },
    "model": "gpt-4o-mini",
    "sampling_params": {
      "seed": 42,
      "temperature": 1.0,
      "top_p": 1.0,
      "max_completions_tokens": 2048
    }
  },
  "error": null,
  "metadata": {}
}


###### request

####### curl

curl https://api.openai.com/v1/evals/eval_67abd54d9b0081909a86353f6fb9317a/runs/evalrun_67abd54d60ec8190832b46859da808f7/cancel \
  -X POST \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
response = client.evals.runs.cancel(
    run_id="run_id",
    eval_id="eval_id",
)
print(response.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const response = await client.evals.runs.cancel('run_id', { eval_id: 'eval_id' });

console.log(response.id);

####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.evals.runs.RunCancelParams;
import com.openai.models.evals.runs.RunCancelResponse;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        RunCancelParams params = RunCancelParams.builder()
            .evalId("eval_id")
            .runId("run_id")
            .build();
        RunCancelResponse response = client.evals().runs().cancel(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

response = openai.evals.runs.cancel("run_id", eval_id: "eval_id")

puts(response)

#### description

Cancel an ongoing evaluation run.


### delete

#### operationId

deleteEvalRun

#### tags

- Evals

#### summary

Delete eval run

#### parameters

##### name

eval_id

##### in

path

##### required

true

##### schema

###### type

string

##### description

The ID of the evaluation to delete the run from.

##### name

run_id

##### in

path

##### required

true

##### schema

###### type

string

##### description

The ID of the run to delete.


#### responses

##### 200

###### description

Successfully deleted the eval run

###### content

####### application/json

######## schema

######### type

object

######### properties

########## object

########### type

string

########### example

eval.run.deleted

########## deleted

########### type

boolean

########### example

true

########## run_id

########### type

string

########### example

evalrun_677469f564d48190807532a852da3afb

##### 404

###### description

Run not found

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/Error

#### x-oaiMeta

##### name

Delete eval run

##### group

evals

##### returns

An object containing the status of the delete operation.

##### path

delete

##### examples

###### response

{
  "object": "eval.run.deleted",
  "deleted": true,
  "run_id": "evalrun_abc456"
}


###### request

####### curl

curl https://api.openai.com/v1/evals/eval_123abc/runs/evalrun_abc456 \
  -X DELETE \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
run = client.evals.runs.delete(
    run_id="run_id",
    eval_id="eval_id",
)
print(run.run_id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const run = await client.evals.runs.delete('run_id', { eval_id: 'eval_id' });

console.log(run.run_id);

####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.evals.runs.RunDeleteParams;
import com.openai.models.evals.runs.RunDeleteResponse;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        RunDeleteParams params = RunDeleteParams.builder()
            .evalId("eval_id")
            .runId("run_id")
            .build();
        RunDeleteResponse run = client.evals().runs().delete(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

run = openai.evals.runs.delete("run_id", eval_id: "eval_id")

puts(run)

#### description

Delete an eval run.


## /evals/{eval_id}/runs/{run_id}/output_items

### get

#### operationId

getEvalRunOutputItems

#### tags

- Evals

#### summary

Get eval run output items

#### parameters

##### name

eval_id

##### in

path

##### required

true

##### schema

###### type

string

##### description

The ID of the evaluation to retrieve runs for.

##### name

run_id

##### in

path

##### required

true

##### schema

###### type

string

##### description

The ID of the run to retrieve output items for.

##### name

after

##### in

query

##### description

Identifier for the last output item from the previous pagination request.

##### required

false

##### schema

###### type

string

##### name

limit

##### in

query

##### description

Number of output items to retrieve.

##### required

false

##### schema

###### type

integer

###### default

20

##### name

status

##### in

query

##### description

Filter output items by status. Use `failed` to filter by failed output
items or `pass` to filter by passed output items.


##### required

false

##### schema

###### type

string

###### enum

- fail
- pass

##### name

order

##### in

query

##### description

Sort order for output items by timestamp. Use `asc` for ascending order or `desc` for descending order. Defaults to `asc`.

##### required

false

##### schema

###### type

string

###### enum

- asc
- desc

###### default

asc


#### responses

##### 200

###### description

A list of output items for the evaluation run

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/EvalRunOutputItemList

#### x-oaiMeta

##### name

Get eval run output items

##### group

evals

##### returns

A list of [EvalRunOutputItem](https://platform.openai.com/docs/api-reference/evals/run-output-item-object) objects matching the specified ID.

##### path

get

##### examples

###### response

{
  "object": "list",
  "data": [
    {
      "object": "eval.run.output_item",
      "id": "outputitem_67e5796c28e081909917bf79f6e6214d",
      "created_at": 1743092076,
      "run_id": "evalrun_67abd54d60ec8190832b46859da808f7",
      "eval_id": "eval_67abd54d9b0081909a86353f6fb9317a",
      "status": "pass",
      "datasource_item_id": 5,
      "datasource_item": {
        "input": "Stock Markets Rally After Positive Economic Data Released",
        "ground_truth": "Markets"
      },
      "results": [
        {
          "name": "String check-a2486074-d803-4445-b431-ad2262e85d47",
          "sample": null,
          "passed": true,
          "score": 1.0
        }
      ],
      "sample": {
        "input": [
          {
            "role": "developer",
            "content": "Categorize a given news headline into one of the following topics: Technology, Markets, World, Business, or Sports.\n\n# Steps\n\n1. Analyze the content of the news headline to understand its primary focus.\n2. Extract the subject matter, identifying any key indicators or keywords.\n3. Use the identified indicators to determine the most suitable category out of the five options: Technology, Markets, World, Business, or Sports.\n4. Ensure only one category is selected per headline.\n\n# Output Format\n\nRespond with the chosen category as a single word. For instance: \"Technology\", \"Markets\", \"World\", \"Business\", or \"Sports\".\n\n# Examples\n\n**Input**: \"Apple Unveils New iPhone Model, Featuring Advanced AI Features\"  \n**Output**: \"Technology\"\n\n**Input**: \"Global Stocks Mixed as Investors Await Central Bank Decisions\"  \n**Output**: \"Markets\"\n\n**Input**: \"War in Ukraine: Latest Updates on Negotiation Status\"  \n**Output**: \"World\"\n\n**Input**: \"Microsoft in Talks to Acquire Gaming Company for $2 Billion\"  \n**Output**: \"Business\"\n\n**Input**: \"Manchester United Secures Win in Premier League Football Match\"  \n**Output**: \"Sports\" \n\n# Notes\n\n- If the headline appears to fit into more than one category, choose the most dominant theme.\n- Keywords or phrases such as \"stocks\", \"company acquisition\", \"match\", or technological brands can be good indicators for classification.\n",
            "tool_call_id": null,
            "tool_calls": null,
            "function_call": null
          },
          {
            "role": "user",
            "content": "Stock Markets Rally After Positive Economic Data Released",
            "tool_call_id": null,
            "tool_calls": null,
            "function_call": null
          }
        ],
        "output": [
          {
            "role": "assistant",
            "content": "Markets",
            "tool_call_id": null,
            "tool_calls": null,
            "function_call": null
          }
        ],
        "finish_reason": "stop",
        "model": "gpt-4o-mini-2024-07-18",
        "usage": {
          "total_tokens": 325,
          "completion_tokens": 2,
          "prompt_tokens": 323,
          "cached_tokens": 0
        },
        "error": null,
        "temperature": 1.0,
        "max_completion_tokens": 2048,
        "top_p": 1.0,
        "seed": 42
      }
    }
  ],
  "first_id": "outputitem_67e5796c28e081909917bf79f6e6214d",
  "last_id": "outputitem_67e5796c28e081909917bf79f6e6214d",
  "has_more": true
}


###### request

####### curl

curl https://api.openai.com/v1/evals/egroup_67abd54d9b0081909a86353f6fb9317a/runs/erun_67abd54d60ec8190832b46859da808f7/output_items \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
page = client.evals.runs.output_items.list(
    run_id="run_id",
    eval_id="eval_id",
)
page = page.data[0]
print(page.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

// Automatically fetches more pages as needed.
for await (const outputItemListResponse of client.evals.runs.outputItems.list('run_id', {
  eval_id: 'eval_id',
})) {
  console.log(outputItemListResponse.id);
}

####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.evals.runs.outputitems.OutputItemListPage;
import com.openai.models.evals.runs.outputitems.OutputItemListParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        OutputItemListParams params = OutputItemListParams.builder()
            .evalId("eval_id")
            .runId("run_id")
            .build();
        OutputItemListPage page = client.evals().runs().outputItems().list(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

page = openai.evals.runs.output_items.list("run_id", eval_id: "eval_id")

puts(page)

#### description

Get a list of output items for an evaluation run.


## /evals/{eval_id}/runs/{run_id}/output_items/{output_item_id}

### get

#### operationId

getEvalRunOutputItem

#### tags

- Evals

#### summary

Get an output item of an eval run

#### parameters

##### name

eval_id

##### in

path

##### required

true

##### schema

###### type

string

##### description

The ID of the evaluation to retrieve runs for.

##### name

run_id

##### in

path

##### required

true

##### schema

###### type

string

##### description

The ID of the run to retrieve.

##### name

output_item_id

##### in

path

##### required

true

##### schema

###### type

string

##### description

The ID of the output item to retrieve.


#### responses

##### 200

###### description

The evaluation run output item

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/EvalRunOutputItem

#### x-oaiMeta

##### name

Get an output item of an eval run

##### group

evals

##### returns

The [EvalRunOutputItem](https://platform.openai.com/docs/api-reference/evals/run-output-item-object) object matching the specified ID.

##### path

get

##### examples

###### response

{
  "object": "eval.run.output_item",
  "id": "outputitem_67e5796c28e081909917bf79f6e6214d",
  "created_at": 1743092076,
  "run_id": "evalrun_67abd54d60ec8190832b46859da808f7",
  "eval_id": "eval_67abd54d9b0081909a86353f6fb9317a",
  "status": "pass",
  "datasource_item_id": 5,
  "datasource_item": {
    "input": "Stock Markets Rally After Positive Economic Data Released",
    "ground_truth": "Markets"
  },
  "results": [
    {
      "name": "String check-a2486074-d803-4445-b431-ad2262e85d47",
      "sample": null,
      "passed": true,
      "score": 1.0
    }
  ],
  "sample": {
    "input": [
      {
        "role": "developer",
        "content": "Categorize a given news headline into one of the following topics: Technology, Markets, World, Business, or Sports.\n\n# Steps\n\n1. Analyze the content of the news headline to understand its primary focus.\n2. Extract the subject matter, identifying any key indicators or keywords.\n3. Use the identified indicators to determine the most suitable category out of the five options: Technology, Markets, World, Business, or Sports.\n4. Ensure only one category is selected per headline.\n\n# Output Format\n\nRespond with the chosen category as a single word. For instance: \"Technology\", \"Markets\", \"World\", \"Business\", or \"Sports\".\n\n# Examples\n\n**Input**: \"Apple Unveils New iPhone Model, Featuring Advanced AI Features\"  \n**Output**: \"Technology\"\n\n**Input**: \"Global Stocks Mixed as Investors Await Central Bank Decisions\"  \n**Output**: \"Markets\"\n\n**Input**: \"War in Ukraine: Latest Updates on Negotiation Status\"  \n**Output**: \"World\"\n\n**Input**: \"Microsoft in Talks to Acquire Gaming Company for $2 Billion\"  \n**Output**: \"Business\"\n\n**Input**: \"Manchester United Secures Win in Premier League Football Match\"  \n**Output**: \"Sports\" \n\n# Notes\n\n- If the headline appears to fit into more than one category, choose the most dominant theme.\n- Keywords or phrases such as \"stocks\", \"company acquisition\", \"match\", or technological brands can be good indicators for classification.\n",
        "tool_call_id": null,
        "tool_calls": null,
        "function_call": null
      },
      {
        "role": "user",
        "content": "Stock Markets Rally After Positive Economic Data Released",
        "tool_call_id": null,
        "tool_calls": null,
        "function_call": null
      }
    ],
    "output": [
      {
        "role": "assistant",
        "content": "Markets",
        "tool_call_id": null,
        "tool_calls": null,
        "function_call": null
      }
    ],
    "finish_reason": "stop",
    "model": "gpt-4o-mini-2024-07-18",
    "usage": {
      "total_tokens": 325,
      "completion_tokens": 2,
      "prompt_tokens": 323,
      "cached_tokens": 0
    },
    "error": null,
    "temperature": 1.0,
    "max_completion_tokens": 2048,
    "top_p": 1.0,
    "seed": 42
  }
}


###### request

####### curl

curl https://api.openai.com/v1/evals/eval_67abd54d9b0081909a86353f6fb9317a/runs/evalrun_67abd54d60ec8190832b46859da808f7/output_items/outputitem_67abd55eb6548190bb580745d5644a33 \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
output_item = client.evals.runs.output_items.retrieve(
    output_item_id="output_item_id",
    eval_id="eval_id",
    run_id="run_id",
)
print(output_item.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const outputItem = await client.evals.runs.outputItems.retrieve('output_item_id', {
  eval_id: 'eval_id',
  run_id: 'run_id',
});

console.log(outputItem.id);

####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.evals.runs.outputitems.OutputItemRetrieveParams;
import com.openai.models.evals.runs.outputitems.OutputItemRetrieveResponse;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        OutputItemRetrieveParams params = OutputItemRetrieveParams.builder()
            .evalId("eval_id")
            .runId("run_id")
            .outputItemId("output_item_id")
            .build();
        OutputItemRetrieveResponse outputItem = client.evals().runs().outputItems().retrieve(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

output_item = openai.evals.runs.output_items.retrieve("output_item_id", eval_id: "eval_id", run_id: "run_id")

puts(output_item)

#### description

Get an evaluation run output item by ID.


## /files

### get

#### operationId

listFiles

#### tags

- Files

#### summary

List files

#### parameters

##### in

query

##### name

purpose

##### required

false

##### schema

###### type

string

##### description

Only return files with the given purpose.

##### name

limit

##### in

query

##### description

A limit on the number of objects to be returned. Limit can range between 1 and 10,000, and the default is 10,000.


##### required

false

##### schema

###### type

integer

###### default

10000

##### name

order

##### in

query

##### description

Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order.


##### schema

###### type

string

###### default

desc

###### enum

- asc
- desc

##### name

after

##### in

query

##### description

A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list.


##### schema

###### type

string


#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ListFilesResponse

#### x-oaiMeta

##### name

List files

##### group

files

##### returns

A list of [File](https://platform.openai.com/docs/api-reference/files/object) objects.

##### examples

###### response

{
  "object": "list",
  "data": [
    {
      "id": "file-abc123",
      "object": "file",
      "bytes": 175,
      "created_at": 1613677385,
      "expires_at": 1677614202,
      "filename": "salesOverview.pdf",
      "purpose": "assistants",
    },
    {
      "id": "file-abc456",
      "object": "file",
      "bytes": 140,
      "created_at": 1613779121,
      "expires_at": 1677614202,
      "filename": "puppy.jsonl",
      "purpose": "fine-tune",
    }
  ],
  "first_id": "file-abc123",
  "last_id": "file-abc456",
  "has_more": false
}


###### request

####### curl

curl https://api.openai.com/v1/files \
  -H "Authorization: Bearer $OPENAI_API_KEY"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
page = client.files.list()
page = page.data[0]
print(page)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

// Automatically fetches more pages as needed.
for await (const fileObject of client.files.list()) {
  console.log(fileObject);
}

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  page, err := client.Files.List(context.TODO(), openai.FileListParams{

  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", page)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.files.FileListPage;
import com.openai.models.files.FileListParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        FileListPage page = client.files().list();
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

page = openai.files.list

puts(page)

#### description

Returns a list of files.

### post

#### operationId

createFile

#### tags

- Files

#### summary

Upload file

#### requestBody

##### required

true

##### content

###### multipart/form-data

####### schema

######## $ref

#/components/schemas/CreateFileRequest

#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/OpenAIFile

#### x-oaiMeta

##### name

Upload file

##### group

files

##### returns

The uploaded [File](https://platform.openai.com/docs/api-reference/files/object) object.

##### examples

###### response

{
  "id": "file-abc123",
  "object": "file",
  "bytes": 120000,
  "created_at": 1677610602,
  "expires_at": 1677614202,
  "filename": "mydata.jsonl",
  "purpose": "fine-tune",
}


###### request

####### curl

curl https://api.openai.com/v1/files \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -F purpose="fine-tune" \
  -F file="@mydata.jsonl"
  -F expires_after[anchor]="created_at"
  -F expires_after[seconds]=3600


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
file_object = client.files.create(
    file=b"raw file contents",
    purpose="assistants",
)
print(file_object.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const fileObject = await client.files.create({
  file: fs.createReadStream('fine-tune.jsonl'),
  purpose: 'assistants',
});

console.log(fileObject.id);

####### go

package main

import (
  "bytes"
  "context"
  "fmt"
  "io"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  fileObject, err := client.Files.New(context.TODO(), openai.FileNewParams{
    File: io.Reader(bytes.NewBuffer([]byte("some file contents"))),
    Purpose: openai.FilePurposeAssistants,
  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", fileObject.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.files.FileCreateParams;
import com.openai.models.files.FileObject;
import com.openai.models.files.FilePurpose;
import java.io.ByteArrayInputStream;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        FileCreateParams params = FileCreateParams.builder()
            .file(ByteArrayInputStream("some content".getBytes()))
            .purpose(FilePurpose.ASSISTANTS)
            .build();
        FileObject fileObject = client.files().create(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

file_object = openai.files.create(file: Pathname(__FILE__), purpose: :assistants)

puts(file_object)

#### description

Upload a file that can be used across various endpoints. Individual files can be up to 512 MB, and the size of all files uploaded by one organization can be up to 1 TB.

The Assistants API supports files up to 2 million tokens and of specific file types. See the [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) for details.

The Fine-tuning API only supports `.jsonl` files. The input also has certain required formats for fine-tuning [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input) or [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input) models.

The Batch API only supports `.jsonl` files up to 200 MB in size. The input also has a specific required [format](https://platform.openai.com/docs/api-reference/batch/request-input).

Please [contact us](https://help.openai.com/) if you need to increase these storage limits.


## /files/{file_id}

### delete

#### operationId

deleteFile

#### tags

- Files

#### summary

Delete file

#### parameters

##### in

path

##### name

file_id

##### required

true

##### schema

###### type

string

##### description

The ID of the file to use for this request.


#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/DeleteFileResponse

#### x-oaiMeta

##### name

Delete file

##### group

files

##### returns

Deletion status.

##### examples

###### response

{
  "id": "file-abc123",
  "object": "file",
  "deleted": true
}


###### request

####### curl

curl https://api.openai.com/v1/files/file-abc123 \
  -X DELETE \
  -H "Authorization: Bearer $OPENAI_API_KEY"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
file_deleted = client.files.delete(
    "file_id",
)
print(file_deleted.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const fileDeleted = await client.files.delete('file_id');

console.log(fileDeleted.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  fileDeleted, err := client.Files.Delete(context.TODO(), "file_id")
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", fileDeleted.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.files.FileDeleteParams;
import com.openai.models.files.FileDeleted;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        FileDeleted fileDeleted = client.files().delete("file_id");
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

file_deleted = openai.files.delete("file_id")

puts(file_deleted)

#### description

Delete a file.

### get

#### operationId

retrieveFile

#### tags

- Files

#### summary

Retrieve file

#### parameters

##### in

path

##### name

file_id

##### required

true

##### schema

###### type

string

##### description

The ID of the file to use for this request.


#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/OpenAIFile

#### x-oaiMeta

##### name

Retrieve file

##### group

files

##### returns

The [File](https://platform.openai.com/docs/api-reference/files/object) object matching the specified ID.

##### examples

###### response

{
  "id": "file-abc123",
  "object": "file",
  "bytes": 120000,
  "created_at": 1677610602,
  "expires_at": 1677614202,
  "filename": "mydata.jsonl",
  "purpose": "fine-tune",
}


###### request

####### curl

curl https://api.openai.com/v1/files/file-abc123 \
  -H "Authorization: Bearer $OPENAI_API_KEY"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
file_object = client.files.retrieve(
    "file_id",
)
print(file_object.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const fileObject = await client.files.retrieve('file_id');

console.log(fileObject.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  fileObject, err := client.Files.Get(context.TODO(), "file_id")
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", fileObject.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.files.FileObject;
import com.openai.models.files.FileRetrieveParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        FileObject fileObject = client.files().retrieve("file_id");
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

file_object = openai.files.retrieve("file_id")

puts(file_object)

#### description

Returns information about a specific file.

## /files/{file_id}/content

### get

#### operationId

downloadFile

#### tags

- Files

#### summary

Retrieve file content

#### parameters

##### in

path

##### name

file_id

##### required

true

##### schema

###### type

string

##### description

The ID of the file to use for this request.


#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### type

string

#### x-oaiMeta

##### name

Retrieve file content

##### group

files

##### returns

The file content.

##### examples

###### response



###### request

####### curl

curl https://api.openai.com/v1/files/file-abc123/content \
  -H "Authorization: Bearer $OPENAI_API_KEY" > file.jsonl


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
response = client.files.content(
    "file_id",
)
print(response)
content = response.read()
print(content)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const response = await client.files.content('file_id');

console.log(response);

const content = await response.blob();
console.log(content);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  response, err := client.Files.Content(context.TODO(), "file_id")
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", response)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.http.HttpResponse;
import com.openai.models.files.FileContentParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        HttpResponse response = client.files().content("file_id");
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

response = openai.files.content("file_id")

puts(response)

#### description

Returns the contents of the specified file.

## /fine_tuning/alpha/graders/run

### post

#### operationId

runGrader

#### tags

- Fine-tuning

#### summary

Run grader

#### requestBody

##### required

true

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/RunGraderRequest

#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/RunGraderResponse

#### x-oaiMeta

##### name

Run grader

##### beta

true

##### group

graders

##### returns

The results from the grader run.

##### examples

###### response

{
  "reward": 1.0,
  "metadata": {
    "name": "Example score model grader",
    "type": "score_model",
    "errors": {
      "formula_parse_error": false,
      "sample_parse_error": false,
      "truncated_observation_error": false,
      "unresponsive_reward_error": false,
      "invalid_variable_error": false,
      "other_error": false,
      "python_grader_server_error": false,
      "python_grader_server_error_type": null,
      "python_grader_runtime_error": false,
      "python_grader_runtime_error_details": null,
      "model_grader_server_error": false,
      "model_grader_refusal_error": false,
      "model_grader_parse_error": false,
      "model_grader_server_error_details": null
    },
    "execution_time": 4.365238428115845,
    "scores": {},
    "token_usage": {
      "prompt_tokens": 190,
      "total_tokens": 324,
      "completion_tokens": 134,
      "cached_tokens": 0
    },
    "sampled_model_name": "gpt-4o-2024-08-06"
  },
  "sub_rewards": {},
  "model_grader_token_usage_per_model": {
    "gpt-4o-2024-08-06": {
      "prompt_tokens": 190,
      "total_tokens": 324,
      "completion_tokens": 134,
      "cached_tokens": 0
    }
  }
}


###### request

####### curl

curl -X POST https://api.openai.com/v1/fine_tuning/alpha/graders/run \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "grader": {
      "type": "score_model",
      "name": "Example score model grader",
      "input": [
        {
          "role": "user",
          "content": "Score how close the reference answer is to the model answer. Score 1.0 if they are the same and 0.0 if they are different. Return just a floating point score\n\nReference answer: {{item.reference_answer}}\n\nModel answer: {{sample.output_text}}"
        }
      ],
      "model": "gpt-4o-2024-08-06",
      "sampling_params": {
        "temperature": 1,
        "top_p": 1,
        "seed": 42
      }
    },
    "item": {
      "reference_answer": "fuzzy wuzzy was a bear"
    },
    "model_sample": "fuzzy wuzzy was a bear"
  }'


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const response = await client.fineTuning.alpha.graders.run({
  grader: { input: 'input', name: 'name', operation: 'eq', reference: 'reference', type: 'string_check' },
  model_sample: 'model_sample',
});

console.log(response.metadata);

####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
response = client.fine_tuning.alpha.graders.run(
    grader={
        "input": "input",
        "name": "name",
        "operation": "eq",
        "reference": "reference",
        "type": "string_check",
    },
    model_sample="model_sample",
)
print(response.metadata)

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  response, err := client.FineTuning.Alpha.Graders.Run(context.TODO(), openai.FineTuningAlphaGraderRunParams{
    Grader: openai.FineTuningAlphaGraderRunParamsGraderUnion{
      OfStringCheck: &openai.StringCheckGraderParam{
        Input: "input",
        Name: "name",
        Operation: openai.StringCheckGraderOperationEq,
        Reference: "reference",
      },
    },
    ModelSample: "model_sample",
  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", response.Metadata)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.finetuning.alpha.graders.GraderRunParams;
import com.openai.models.finetuning.alpha.graders.GraderRunResponse;
import com.openai.models.graders.gradermodels.StringCheckGrader;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        GraderRunParams params = GraderRunParams.builder()
            .grader(StringCheckGrader.builder()
                .input("input")
                .name("name")
                .operation(StringCheckGrader.Operation.EQ)
                .reference("reference")
                .build())
            .modelSample("model_sample")
            .build();
        GraderRunResponse response = client.fineTuning().alpha().graders().run(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

response = openai.fine_tuning.alpha.graders.run(
  grader: {input: "input", name: "name", operation: :eq, reference: "reference", type: :string_check},
  model_sample: "model_sample"
)

puts(response)

#### description

Run a grader.


## /fine_tuning/alpha/graders/validate

### post

#### operationId

validateGrader

#### tags

- Fine-tuning

#### summary

Validate grader

#### requestBody

##### required

true

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/ValidateGraderRequest

#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ValidateGraderResponse

#### x-oaiMeta

##### name

Validate grader

##### beta

true

##### group

graders

##### returns

The validated grader object.

##### examples

###### response

{
  "grader": {
    "type": "string_check",
    "name": "Example string check grader",
    "input": "{{sample.output_text}}",
    "reference": "{{item.label}}",
    "operation": "eq"
  }
}


###### request

####### curl

curl https://api.openai.com/v1/fine_tuning/alpha/graders/validate \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "grader": {
      "type": "string_check",
      "name": "Example string check grader",
      "input": "{{sample.output_text}}",
      "reference": "{{item.label}}",
      "operation": "eq"
    }
  }'


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const response = await client.fineTuning.alpha.graders.validate({
  grader: { input: 'input', name: 'name', operation: 'eq', reference: 'reference', type: 'string_check' },
});

console.log(response.grader);

####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
response = client.fine_tuning.alpha.graders.validate(
    grader={
        "input": "input",
        "name": "name",
        "operation": "eq",
        "reference": "reference",
        "type": "string_check",
    },
)
print(response.grader)

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  response, err := client.FineTuning.Alpha.Graders.Validate(context.TODO(), openai.FineTuningAlphaGraderValidateParams{
    Grader: openai.FineTuningAlphaGraderValidateParamsGraderUnion{
      OfStringCheckGrader: &openai.StringCheckGraderParam{
        Input: "input",
        Name: "name",
        Operation: openai.StringCheckGraderOperationEq,
        Reference: "reference",
      },
    },
  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", response.Grader)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.finetuning.alpha.graders.GraderValidateParams;
import com.openai.models.finetuning.alpha.graders.GraderValidateResponse;
import com.openai.models.graders.gradermodels.StringCheckGrader;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        GraderValidateParams params = GraderValidateParams.builder()
            .grader(StringCheckGrader.builder()
                .input("input")
                .name("name")
                .operation(StringCheckGrader.Operation.EQ)
                .reference("reference")
                .build())
            .build();
        GraderValidateResponse response = client.fineTuning().alpha().graders().validate(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

response = openai.fine_tuning.alpha.graders.validate(
  grader: {input: "input", name: "name", operation: :eq, reference: "reference", type: :string_check}
)

puts(response)

#### description

Validate a grader.


## /fine_tuning/checkpoints/{fine_tuned_model_checkpoint}/permissions

### get

#### operationId

listFineTuningCheckpointPermissions

#### tags

- Fine-tuning

#### summary

List checkpoint permissions

#### parameters

##### in

path

##### name

fine_tuned_model_checkpoint

##### required

true

##### schema

###### type

string

###### example

ft-AF1WoRqd3aJAHsqc9NY7iL8F

##### description

The ID of the fine-tuned model checkpoint to get permissions for.


##### name

project_id

##### in

query

##### description

The ID of the project to get permissions for.

##### required

false

##### schema

###### type

string

##### name

after

##### in

query

##### description

Identifier for the last permission ID from the previous pagination request.

##### required

false

##### schema

###### type

string

##### name

limit

##### in

query

##### description

Number of permissions to retrieve.

##### required

false

##### schema

###### type

integer

###### default

10

##### name

order

##### in

query

##### description

The order in which to retrieve permissions.

##### required

false

##### schema

###### type

string

###### enum

- ascending
- descending

###### default

descending


#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ListFineTuningCheckpointPermissionResponse

#### x-oaiMeta

##### name

List checkpoint permissions

##### group

fine-tuning

##### returns

A list of fine-tuned model checkpoint [permission objects](https://platform.openai.com/docs/api-reference/fine-tuning/permission-object) for a fine-tuned model checkpoint.

##### examples

###### response

{
  "object": "list",
  "data": [
    {
      "object": "checkpoint.permission",
      "id": "cp_zc4Q7MP6XxulcVzj4MZdwsAB",
      "created_at": 1721764867,
      "project_id": "proj_abGMw1llN8IrBb6SvvY5A1iH"
    },
    {
      "object": "checkpoint.permission",
      "id": "cp_enQCFmOTGj3syEpYVhBRLTSy",
      "created_at": 1721764800,
      "project_id": "proj_iqGMw1llN8IrBb6SvvY5A1oF"
    },
  ],
  "first_id": "cp_zc4Q7MP6XxulcVzj4MZdwsAB",
  "last_id": "cp_enQCFmOTGj3syEpYVhBRLTSy",
  "has_more": false
}


###### request

####### curl

curl https://api.openai.com/v1/fine_tuning/checkpoints/ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd/permissions \
  -H "Authorization: Bearer $OPENAI_API_KEY"


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const permission = await client.fineTuning.checkpoints.permissions.retrieve('ft-AF1WoRqd3aJAHsqc9NY7iL8F');

console.log(permission.first_id);

####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
permission = client.fine_tuning.checkpoints.permissions.retrieve(
    fine_tuned_model_checkpoint="ft-AF1WoRqd3aJAHsqc9NY7iL8F",
)
print(permission.first_id)

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  permission, err := client.FineTuning.Checkpoints.Permissions.Get(
    context.TODO(),
    "ft-AF1WoRqd3aJAHsqc9NY7iL8F",
    openai.FineTuningCheckpointPermissionGetParams{

    },
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", permission.FirstID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.finetuning.checkpoints.permissions.PermissionRetrieveParams;
import com.openai.models.finetuning.checkpoints.permissions.PermissionRetrieveResponse;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        PermissionRetrieveResponse permission = client.fineTuning().checkpoints().permissions().retrieve("ft-AF1WoRqd3aJAHsqc9NY7iL8F");
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

permission = openai.fine_tuning.checkpoints.permissions.retrieve("ft-AF1WoRqd3aJAHsqc9NY7iL8F")

puts(permission)

#### description

**NOTE:** This endpoint requires an [admin API key](../admin-api-keys).

Organization owners can use this endpoint to view all permissions for a fine-tuned model checkpoint.


### post

#### operationId

createFineTuningCheckpointPermission

#### tags

- Fine-tuning

#### summary

Create checkpoint permissions

#### parameters

##### in

path

##### name

fine_tuned_model_checkpoint

##### required

true

##### schema

###### type

string

###### example

ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd

##### description

The ID of the fine-tuned model checkpoint to create a permission for.



#### requestBody

##### required

true

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/CreateFineTuningCheckpointPermissionRequest

#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ListFineTuningCheckpointPermissionResponse

#### x-oaiMeta

##### name

Create checkpoint permissions

##### group

fine-tuning

##### returns

A list of fine-tuned model checkpoint [permission objects](https://platform.openai.com/docs/api-reference/fine-tuning/permission-object) for a fine-tuned model checkpoint.

##### examples

###### response

{
  "object": "list",
  "data": [
    {
      "object": "checkpoint.permission",
      "id": "cp_zc4Q7MP6XxulcVzj4MZdwsAB",
      "created_at": 1721764867,
      "project_id": "proj_abGMw1llN8IrBb6SvvY5A1iH"
    }
  ],
  "first_id": "cp_zc4Q7MP6XxulcVzj4MZdwsAB",
  "last_id": "cp_zc4Q7MP6XxulcVzj4MZdwsAB",
  "has_more": false
}


###### request

####### curl

curl https://api.openai.com/v1/fine_tuning/checkpoints/ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd/permissions \
  -H "Authorization: Bearer $OPENAI_API_KEY"
  -d '{"project_ids": ["proj_abGMw1llN8IrBb6SvvY5A1iH"]}'


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

// Automatically fetches more pages as needed.
for await (const permissionCreateResponse of client.fineTuning.checkpoints.permissions.create(
  'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd',
  { project_ids: ['string'] },
)) {
  console.log(permissionCreateResponse.id);
}

####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
page = client.fine_tuning.checkpoints.permissions.create(
    fine_tuned_model_checkpoint="ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd",
    project_ids=["string"],
)
page = page.data[0]
print(page.id)

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  page, err := client.FineTuning.Checkpoints.Permissions.New(
    context.TODO(),
    "ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd",
    openai.FineTuningCheckpointPermissionNewParams{
      ProjectIDs: []string{"string"},
    },
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", page)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.finetuning.checkpoints.permissions.PermissionCreatePage;
import com.openai.models.finetuning.checkpoints.permissions.PermissionCreateParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        PermissionCreateParams params = PermissionCreateParams.builder()
            .fineTunedModelCheckpoint("ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd")
            .addProjectId("string")
            .build();
        PermissionCreatePage page = client.fineTuning().checkpoints().permissions().create(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

page = openai.fine_tuning.checkpoints.permissions.create(
  "ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd",
  project_ids: ["string"]
)

puts(page)

#### description

**NOTE:** Calling this endpoint requires an [admin API key](../admin-api-keys).

This enables organization owners to share fine-tuned models with other projects in their organization.


## /fine_tuning/checkpoints/{fine_tuned_model_checkpoint}/permissions/{permission_id}

### delete

#### operationId

deleteFineTuningCheckpointPermission

#### tags

- Fine-tuning

#### summary

Delete checkpoint permission

#### parameters

##### in

path

##### name

fine_tuned_model_checkpoint

##### required

true

##### schema

###### type

string

###### example

ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd

##### description

The ID of the fine-tuned model checkpoint to delete a permission for.


##### in

path

##### name

permission_id

##### required

true

##### schema

###### type

string

###### example

cp_zc4Q7MP6XxulcVzj4MZdwsAB

##### description

The ID of the fine-tuned model checkpoint permission to delete.



#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/DeleteFineTuningCheckpointPermissionResponse

#### x-oaiMeta

##### name

Delete checkpoint permission

##### group

fine-tuning

##### returns

The deletion status of the fine-tuned model checkpoint [permission object](https://platform.openai.com/docs/api-reference/fine-tuning/permission-object).

##### examples

###### response

{
  "object": "checkpoint.permission",
  "id": "cp_zc4Q7MP6XxulcVzj4MZdwsAB",
  "deleted": true
}


###### request

####### curl

curl https://api.openai.com/v1/fine_tuning/checkpoints/ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd/permissions/cp_zc4Q7MP6XxulcVzj4MZdwsAB \
  -H "Authorization: Bearer $OPENAI_API_KEY"


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const permission = await client.fineTuning.checkpoints.permissions.delete('cp_zc4Q7MP6XxulcVzj4MZdwsAB', {
  fine_tuned_model_checkpoint: 'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd',
});

console.log(permission.id);

####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
permission = client.fine_tuning.checkpoints.permissions.delete(
    permission_id="cp_zc4Q7MP6XxulcVzj4MZdwsAB",
    fine_tuned_model_checkpoint="ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd",
)
print(permission.id)

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  permission, err := client.FineTuning.Checkpoints.Permissions.Delete(
    context.TODO(),
    "ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd",
    "cp_zc4Q7MP6XxulcVzj4MZdwsAB",
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", permission.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.finetuning.checkpoints.permissions.PermissionDeleteParams;
import com.openai.models.finetuning.checkpoints.permissions.PermissionDeleteResponse;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        PermissionDeleteParams params = PermissionDeleteParams.builder()
            .fineTunedModelCheckpoint("ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd")
            .permissionId("cp_zc4Q7MP6XxulcVzj4MZdwsAB")
            .build();
        PermissionDeleteResponse permission = client.fineTuning().checkpoints().permissions().delete(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

permission = openai.fine_tuning.checkpoints.permissions.delete(
  "cp_zc4Q7MP6XxulcVzj4MZdwsAB",
  fine_tuned_model_checkpoint: "ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd"
)

puts(permission)

#### description

**NOTE:** This endpoint requires an [admin API key](../admin-api-keys).

Organization owners can use this endpoint to delete a permission for a fine-tuned model checkpoint.


## /fine_tuning/jobs

### post

#### operationId

createFineTuningJob

#### tags

- Fine-tuning

#### summary

Create fine-tuning job

#### requestBody

##### required

true

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/CreateFineTuningJobRequest

#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/FineTuningJob

#### x-oaiMeta

##### name

Create fine-tuning job

##### group

fine-tuning

##### returns

A [fine-tuning.job](https://platform.openai.com/docs/api-reference/fine-tuning/object) object.

##### examples

###### title

Default

###### request

####### curl

curl https://api.openai.com/v1/fine_tuning/jobs \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "training_file": "file-BK7bzQj3FfZFXr7DbL6xJwfo",
    "model": "gpt-4o-mini"
  }'


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
fine_tuning_job = client.fine_tuning.jobs.create(
    model="gpt-4o-mini",
    training_file="file-abc123",
)
print(fine_tuning_job.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const fineTuningJob = await client.fineTuning.jobs.create({
  model: 'gpt-4o-mini',
  training_file: 'file-abc123',
});

console.log(fineTuningJob.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  fineTuningJob, err := client.FineTuning.Jobs.New(context.TODO(), openai.FineTuningJobNewParams{
    Model: openai.FineTuningJobNewParamsModelBabbage002,
    TrainingFile: "file-abc123",
  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", fineTuningJob.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.finetuning.jobs.FineTuningJob;
import com.openai.models.finetuning.jobs.JobCreateParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        JobCreateParams params = JobCreateParams.builder()
            .model(JobCreateParams.Model.BABBAGE_002)
            .trainingFile("file-abc123")
            .build();
        FineTuningJob fineTuningJob = client.fineTuning().jobs().create(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

fine_tuning_job = openai.fine_tuning.jobs.create(model: :"babbage-002", training_file: "file-abc123")

puts(fine_tuning_job)

###### response

{
  "object": "fine_tuning.job",
  "id": "ftjob-abc123",
  "model": "gpt-4o-mini-2024-07-18",
  "created_at": 1721764800,
  "fine_tuned_model": null,
  "organization_id": "org-123",
  "result_files": [],
  "status": "queued",
  "validation_file": null,
  "training_file": "file-abc123",
  "method": {
    "type": "supervised",
    "supervised": {
      "hyperparameters": {
        "batch_size": "auto",
        "learning_rate_multiplier": "auto",
        "n_epochs": "auto",
      }
    }
  },
  "metadata": null
}


###### title

Epochs

###### request

####### curl

curl https://api.openai.com/v1/fine_tuning/jobs \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "training_file": "file-abc123",
    "model": "gpt-4o-mini",
    "method": {
      "type": "supervised",
      "supervised": {
        "hyperparameters": {
          "n_epochs": 2
        }
      }
    }
  }'


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
fine_tuning_job = client.fine_tuning.jobs.create(
    model="gpt-4o-mini",
    training_file="file-abc123",
)
print(fine_tuning_job.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const fineTuningJob = await client.fineTuning.jobs.create({
  model: 'gpt-4o-mini',
  training_file: 'file-abc123',
});

console.log(fineTuningJob.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  fineTuningJob, err := client.FineTuning.Jobs.New(context.TODO(), openai.FineTuningJobNewParams{
    Model: openai.FineTuningJobNewParamsModelBabbage002,
    TrainingFile: "file-abc123",
  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", fineTuningJob.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.finetuning.jobs.FineTuningJob;
import com.openai.models.finetuning.jobs.JobCreateParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        JobCreateParams params = JobCreateParams.builder()
            .model(JobCreateParams.Model.BABBAGE_002)
            .trainingFile("file-abc123")
            .build();
        FineTuningJob fineTuningJob = client.fineTuning().jobs().create(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

fine_tuning_job = openai.fine_tuning.jobs.create(model: :"babbage-002", training_file: "file-abc123")

puts(fine_tuning_job)

###### response

{
  "object": "fine_tuning.job",
  "id": "ftjob-abc123",
  "model": "gpt-4o-mini",
  "created_at": 1721764800,
  "fine_tuned_model": null,
  "organization_id": "org-123",
  "result_files": [],
  "status": "queued",
  "validation_file": null,
  "training_file": "file-abc123",
  "hyperparameters": {
    "batch_size": "auto",
    "learning_rate_multiplier": "auto",
    "n_epochs": 2
  },
  "method": {
    "type": "supervised",
    "supervised": {
      "hyperparameters": {
        "batch_size": "auto",
        "learning_rate_multiplier": "auto",
        "n_epochs": 2
      }
    }
  },
  "metadata": null,
  "error": {
    "code": null,
    "message": null,
    "param": null
  },
  "finished_at": null,
  "seed": 683058546,
  "trained_tokens": null,
  "estimated_finish": null,
  "integrations": [],
  "user_provided_suffix": null,
  "usage_metrics": null,
  "shared_with_openai": false
}


###### title

DPO

###### request

####### curl

curl https://api.openai.com/v1/fine_tuning/jobs \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "training_file": "file-abc123",
    "validation_file": "file-abc123",
    "model": "gpt-4o-mini",
    "method": {
      "type": "dpo",
      "dpo": {
        "hyperparameters": {
          "beta": 0.1
        }
      }
    }
  }'


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const fineTuningJob = await client.fineTuning.jobs.create({
  model: 'gpt-4o-mini',
  training_file: 'file-abc123',
});

console.log(fineTuningJob.id);

####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
fine_tuning_job = client.fine_tuning.jobs.create(
    model="gpt-4o-mini",
    training_file="file-abc123",
)
print(fine_tuning_job.id)

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  fineTuningJob, err := client.FineTuning.Jobs.New(context.TODO(), openai.FineTuningJobNewParams{
    Model: openai.FineTuningJobNewParamsModelBabbage002,
    TrainingFile: "file-abc123",
  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", fineTuningJob.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.finetuning.jobs.FineTuningJob;
import com.openai.models.finetuning.jobs.JobCreateParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        JobCreateParams params = JobCreateParams.builder()
            .model(JobCreateParams.Model.BABBAGE_002)
            .trainingFile("file-abc123")
            .build();
        FineTuningJob fineTuningJob = client.fineTuning().jobs().create(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

fine_tuning_job = openai.fine_tuning.jobs.create(model: :"babbage-002", training_file: "file-abc123")

puts(fine_tuning_job)

###### python

from openai import OpenAI
from openai.types.fine_tuning import DpoMethod, DpoHyperparameters

client = OpenAI()

client.fine_tuning.jobs.create(
  training_file="file-abc",
  validation_file="file-123",
  model="gpt-4o-mini",
  method={
    "type": "dpo",
    "dpo": DpoMethod(
      hyperparameters=DpoHyperparameters(beta=0.1)
    )
  }
)


###### response

{
  "object": "fine_tuning.job",
  "id": "ftjob-abc",
  "model": "gpt-4o-mini",
  "created_at": 1746130590,
  "fine_tuned_model": null,
  "organization_id": "org-abc",
  "result_files": [],
  "status": "queued",
  "validation_file": "file-123",
  "training_file": "file-abc",
  "method": {
    "type": "dpo",
    "dpo": {
      "hyperparameters": {
        "beta": 0.1,
        "batch_size": "auto",
        "learning_rate_multiplier": "auto",
        "n_epochs": "auto"
      }
    }
  },
  "metadata": null,
  "error": {
    "code": null,
    "message": null,
    "param": null
  },
  "finished_at": null,
  "hyperparameters": null,
  "seed": 1036326793,
  "estimated_finish": null,
  "integrations": [],
  "user_provided_suffix": null,
  "usage_metrics": null,
  "shared_with_openai": false
}


###### title

Reinforcement

###### request

####### curl

curl https://api.openai.com/v1/fine_tuning/jobs \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "training_file": "file-abc",
    "validation_file": "file-123",
    "model": "o4-mini",
    "method": {
      "type": "reinforcement",
      "reinforcement": {
        "grader": {
          "type": "string_check",
          "name": "Example string check grader",
          "input": "{{sample.output_text}}",
          "reference": "{{item.label}}",
          "operation": "eq"
        },
        "hyperparameters": {
          "reasoning_effort": "medium"
        }
      }
    }
  }'


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
fine_tuning_job = client.fine_tuning.jobs.create(
    model="gpt-4o-mini",
    training_file="file-abc123",
)
print(fine_tuning_job.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const fineTuningJob = await client.fineTuning.jobs.create({
  model: 'gpt-4o-mini',
  training_file: 'file-abc123',
});

console.log(fineTuningJob.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  fineTuningJob, err := client.FineTuning.Jobs.New(context.TODO(), openai.FineTuningJobNewParams{
    Model: openai.FineTuningJobNewParamsModelBabbage002,
    TrainingFile: "file-abc123",
  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", fineTuningJob.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.finetuning.jobs.FineTuningJob;
import com.openai.models.finetuning.jobs.JobCreateParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        JobCreateParams params = JobCreateParams.builder()
            .model(JobCreateParams.Model.BABBAGE_002)
            .trainingFile("file-abc123")
            .build();
        FineTuningJob fineTuningJob = client.fineTuning().jobs().create(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

fine_tuning_job = openai.fine_tuning.jobs.create(model: :"babbage-002", training_file: "file-abc123")

puts(fine_tuning_job)

###### response

{
  "object": "fine_tuning.job",
  "id": "ftjob-abc123",
  "model": "o4-mini",
  "created_at": 1721764800,
  "finished_at": null,
  "fine_tuned_model": null,
  "organization_id": "org-123",
  "result_files": [],
  "status": "validating_files",
  "validation_file": "file-123",
  "training_file": "file-abc",
  "trained_tokens": null,
  "error": {},
  "user_provided_suffix": null,
  "seed": 950189191,
  "estimated_finish": null,
  "integrations": [],
  "method": {
    "type": "reinforcement",
    "reinforcement": {
      "hyperparameters": {
        "batch_size": "auto",
        "learning_rate_multiplier": "auto",
        "n_epochs": "auto",
        "eval_interval": "auto",
        "eval_samples": "auto",
        "compute_multiplier": "auto",
        "reasoning_effort": "medium"
      },
      "grader": {
        "type": "string_check",
        "name": "Example string check grader",
        "input": "{{sample.output_text}}",
        "reference": "{{item.label}}",
        "operation": "eq"
      },
      "response_format": null
    }
  },
  "metadata": null,
  "usage_metrics": null,
  "shared_with_openai": false
}
      


###### title

Validation file

###### request

####### curl

curl https://api.openai.com/v1/fine_tuning/jobs \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "training_file": "file-abc123",
    "validation_file": "file-abc123",
    "model": "gpt-4o-mini"
  }'


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
fine_tuning_job = client.fine_tuning.jobs.create(
    model="gpt-4o-mini",
    training_file="file-abc123",
)
print(fine_tuning_job.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const fineTuningJob = await client.fineTuning.jobs.create({
  model: 'gpt-4o-mini',
  training_file: 'file-abc123',
});

console.log(fineTuningJob.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  fineTuningJob, err := client.FineTuning.Jobs.New(context.TODO(), openai.FineTuningJobNewParams{
    Model: openai.FineTuningJobNewParamsModelBabbage002,
    TrainingFile: "file-abc123",
  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", fineTuningJob.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.finetuning.jobs.FineTuningJob;
import com.openai.models.finetuning.jobs.JobCreateParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        JobCreateParams params = JobCreateParams.builder()
            .model(JobCreateParams.Model.BABBAGE_002)
            .trainingFile("file-abc123")
            .build();
        FineTuningJob fineTuningJob = client.fineTuning().jobs().create(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

fine_tuning_job = openai.fine_tuning.jobs.create(model: :"babbage-002", training_file: "file-abc123")

puts(fine_tuning_job)

###### response

{
  "object": "fine_tuning.job",
  "id": "ftjob-abc123",
  "model": "gpt-4o-mini-2024-07-18",
  "created_at": 1721764800,
  "fine_tuned_model": null,
  "organization_id": "org-123",
  "result_files": [],
  "status": "queued",
  "validation_file": "file-abc123",
  "training_file": "file-abc123",
  "method": {
    "type": "supervised",
    "supervised": {
      "hyperparameters": {
        "batch_size": "auto",
        "learning_rate_multiplier": "auto",
        "n_epochs": "auto",
      }
    }
  },
  "metadata": null
}


###### title

W&B Integration

###### request

####### curl

curl https://api.openai.com/v1/fine_tuning/jobs \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "training_file": "file-abc123",
    "validation_file": "file-abc123",
    "model": "gpt-4o-mini",
    "integrations": [
      {
        "type": "wandb",
        "wandb": {
          "project": "my-wandb-project",
          "name": "ft-run-display-name"
          "tags": [
            "first-experiment", "v2"
          ]
        }
      }
    ]
  }'


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const fineTuningJob = await client.fineTuning.jobs.create({
  model: 'gpt-4o-mini',
  training_file: 'file-abc123',
});

console.log(fineTuningJob.id);

####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
fine_tuning_job = client.fine_tuning.jobs.create(
    model="gpt-4o-mini",
    training_file="file-abc123",
)
print(fine_tuning_job.id)

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  fineTuningJob, err := client.FineTuning.Jobs.New(context.TODO(), openai.FineTuningJobNewParams{
    Model: openai.FineTuningJobNewParamsModelBabbage002,
    TrainingFile: "file-abc123",
  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", fineTuningJob.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.finetuning.jobs.FineTuningJob;
import com.openai.models.finetuning.jobs.JobCreateParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        JobCreateParams params = JobCreateParams.builder()
            .model(JobCreateParams.Model.BABBAGE_002)
            .trainingFile("file-abc123")
            .build();
        FineTuningJob fineTuningJob = client.fineTuning().jobs().create(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

fine_tuning_job = openai.fine_tuning.jobs.create(model: :"babbage-002", training_file: "file-abc123")

puts(fine_tuning_job)

###### response

{
  "object": "fine_tuning.job",
  "id": "ftjob-abc123",
  "model": "gpt-4o-mini-2024-07-18",
  "created_at": 1721764800,
  "fine_tuned_model": null,
  "organization_id": "org-123",
  "result_files": [],
  "status": "queued",
  "validation_file": "file-abc123",
  "training_file": "file-abc123",
  "integrations": [
    {
      "type": "wandb",
      "wandb": {
        "project": "my-wandb-project",
        "entity": None,
        "run_id": "ftjob-abc123"
      }
    }
  ],
  "method": {
    "type": "supervised",
    "supervised": {
      "hyperparameters": {
        "batch_size": "auto",
        "learning_rate_multiplier": "auto",
        "n_epochs": "auto",
      }
    }
  },
  "metadata": null
}



#### description

Creates a fine-tuning job which begins the process of creating a new model from a given dataset.

Response includes details of the enqueued job including job status and the name of the fine-tuned models once complete.

[Learn more about fine-tuning](https://platform.openai.com/docs/guides/model-optimization)


### get

#### operationId

listPaginatedFineTuningJobs

#### tags

- Fine-tuning

#### summary

List fine-tuning jobs

#### parameters

##### name

after

##### in

query

##### description

Identifier for the last job from the previous pagination request.

##### required

false

##### schema

###### type

string

##### name

limit

##### in

query

##### description

Number of fine-tuning jobs to retrieve.

##### required

false

##### schema

###### type

integer

###### default

20

##### in

query

##### name

metadata

##### required

false

##### schema

###### type

object

###### nullable

true

###### additionalProperties

####### type

string

##### style

deepObject

##### explode

true

##### description

Optional metadata filter. To filter, use the syntax `metadata[k]=v`. Alternatively, set `metadata=null` to indicate no metadata.



#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ListPaginatedFineTuningJobsResponse

#### x-oaiMeta

##### name

List fine-tuning jobs

##### group

fine-tuning

##### returns

A list of paginated [fine-tuning job](https://platform.openai.com/docs/api-reference/fine-tuning/object) objects.

##### examples

###### response

{
  "object": "list",
  "data": [
    {
      "object": "fine_tuning.job",
      "id": "ftjob-abc123",
      "model": "gpt-4o-mini-2024-07-18",
      "created_at": 1721764800,
      "fine_tuned_model": null,
      "organization_id": "org-123",
      "result_files": [],
      "status": "queued",
      "validation_file": null,
      "training_file": "file-abc123",
      "metadata": {
        "key": "value"
      }
    },
    { ... },
    { ... }
  ], "has_more": true
}


###### request

####### curl

curl https://api.openai.com/v1/fine_tuning/jobs?limit=2&metadata[key]=value \
  -H "Authorization: Bearer $OPENAI_API_KEY"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
page = client.fine_tuning.jobs.list()
page = page.data[0]
print(page.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

// Automatically fetches more pages as needed.
for await (const fineTuningJob of client.fineTuning.jobs.list()) {
  console.log(fineTuningJob.id);
}

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  page, err := client.FineTuning.Jobs.List(context.TODO(), openai.FineTuningJobListParams{

  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", page)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.finetuning.jobs.JobListPage;
import com.openai.models.finetuning.jobs.JobListParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        JobListPage page = client.fineTuning().jobs().list();
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

page = openai.fine_tuning.jobs.list

puts(page)

#### description

List your organization's fine-tuning jobs


## /fine_tuning/jobs/{fine_tuning_job_id}

### get

#### operationId

retrieveFineTuningJob

#### tags

- Fine-tuning

#### summary

Retrieve fine-tuning job

#### parameters

##### in

path

##### name

fine_tuning_job_id

##### required

true

##### schema

###### type

string

###### example

ft-AF1WoRqd3aJAHsqc9NY7iL8F

##### description

The ID of the fine-tuning job.



#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/FineTuningJob

#### x-oaiMeta

##### name

Retrieve fine-tuning job

##### group

fine-tuning

##### returns

The [fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning/object) object with the given ID.

##### examples

###### response

{
  "object": "fine_tuning.job",
  "id": "ftjob-abc123",
  "model": "davinci-002",
  "created_at": 1692661014,
  "finished_at": 1692661190,
  "fine_tuned_model": "ft:davinci-002:my-org:custom_suffix:7q8mpxmy",
  "organization_id": "org-123",
  "result_files": [
      "file-abc123"
  ],
  "status": "succeeded",
  "validation_file": null,
  "training_file": "file-abc123",
  "hyperparameters": {
      "n_epochs": 4,
      "batch_size": 1,
      "learning_rate_multiplier": 1.0
  },
  "trained_tokens": 5768,
  "integrations": [],
  "seed": 0,
  "estimated_finish": 0,
  "method": {
    "type": "supervised",
    "supervised": {
      "hyperparameters": {
        "n_epochs": 4,
        "batch_size": 1,
        "learning_rate_multiplier": 1.0
      }
    }
  }
}


###### request

####### curl

curl https://api.openai.com/v1/fine_tuning/jobs/ft-AF1WoRqd3aJAHsqc9NY7iL8F \
  -H "Authorization: Bearer $OPENAI_API_KEY"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
fine_tuning_job = client.fine_tuning.jobs.retrieve(
    "ft-AF1WoRqd3aJAHsqc9NY7iL8F",
)
print(fine_tuning_job.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const fineTuningJob = await client.fineTuning.jobs.retrieve('ft-AF1WoRqd3aJAHsqc9NY7iL8F');

console.log(fineTuningJob.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  fineTuningJob, err := client.FineTuning.Jobs.Get(context.TODO(), "ft-AF1WoRqd3aJAHsqc9NY7iL8F")
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", fineTuningJob.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.finetuning.jobs.FineTuningJob;
import com.openai.models.finetuning.jobs.JobRetrieveParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        FineTuningJob fineTuningJob = client.fineTuning().jobs().retrieve("ft-AF1WoRqd3aJAHsqc9NY7iL8F");
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

fine_tuning_job = openai.fine_tuning.jobs.retrieve("ft-AF1WoRqd3aJAHsqc9NY7iL8F")

puts(fine_tuning_job)

#### description

Get info about a fine-tuning job.

[Learn more about fine-tuning](https://platform.openai.com/docs/guides/model-optimization)


## /fine_tuning/jobs/{fine_tuning_job_id}/cancel

### post

#### operationId

cancelFineTuningJob

#### tags

- Fine-tuning

#### summary

Cancel fine-tuning

#### parameters

##### in

path

##### name

fine_tuning_job_id

##### required

true

##### schema

###### type

string

###### example

ft-AF1WoRqd3aJAHsqc9NY7iL8F

##### description

The ID of the fine-tuning job to cancel.



#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/FineTuningJob

#### x-oaiMeta

##### name

Cancel fine-tuning

##### group

fine-tuning

##### returns

The cancelled [fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning/object) object.

##### examples

###### response

{
  "object": "fine_tuning.job",
  "id": "ftjob-abc123",
  "model": "gpt-4o-mini-2024-07-18",
  "created_at": 1721764800,
  "fine_tuned_model": null,
  "organization_id": "org-123",
  "result_files": [],
  "status": "cancelled",
  "validation_file": "file-abc123",
  "training_file": "file-abc123"
}


###### request

####### curl

curl -X POST https://api.openai.com/v1/fine_tuning/jobs/ftjob-abc123/cancel \
  -H "Authorization: Bearer $OPENAI_API_KEY"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
fine_tuning_job = client.fine_tuning.jobs.cancel(
    "ft-AF1WoRqd3aJAHsqc9NY7iL8F",
)
print(fine_tuning_job.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const fineTuningJob = await client.fineTuning.jobs.cancel('ft-AF1WoRqd3aJAHsqc9NY7iL8F');

console.log(fineTuningJob.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  fineTuningJob, err := client.FineTuning.Jobs.Cancel(context.TODO(), "ft-AF1WoRqd3aJAHsqc9NY7iL8F")
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", fineTuningJob.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.finetuning.jobs.FineTuningJob;
import com.openai.models.finetuning.jobs.JobCancelParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        FineTuningJob fineTuningJob = client.fineTuning().jobs().cancel("ft-AF1WoRqd3aJAHsqc9NY7iL8F");
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

fine_tuning_job = openai.fine_tuning.jobs.cancel("ft-AF1WoRqd3aJAHsqc9NY7iL8F")

puts(fine_tuning_job)

#### description

Immediately cancel a fine-tune job.


## /fine_tuning/jobs/{fine_tuning_job_id}/checkpoints

### get

#### operationId

listFineTuningJobCheckpoints

#### tags

- Fine-tuning

#### summary

List fine-tuning checkpoints

#### parameters

##### in

path

##### name

fine_tuning_job_id

##### required

true

##### schema

###### type

string

###### example

ft-AF1WoRqd3aJAHsqc9NY7iL8F

##### description

The ID of the fine-tuning job to get checkpoints for.


##### name

after

##### in

query

##### description

Identifier for the last checkpoint ID from the previous pagination request.

##### required

false

##### schema

###### type

string

##### name

limit

##### in

query

##### description

Number of checkpoints to retrieve.

##### required

false

##### schema

###### type

integer

###### default

10


#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ListFineTuningJobCheckpointsResponse

#### x-oaiMeta

##### name

List fine-tuning checkpoints

##### group

fine-tuning

##### returns

A list of fine-tuning [checkpoint objects](https://platform.openai.com/docs/api-reference/fine-tuning/checkpoint-object) for a fine-tuning job.

##### examples

###### response

{
  "object": "list",
  "data": [
    {
      "object": "fine_tuning.job.checkpoint",
      "id": "ftckpt_zc4Q7MP6XxulcVzj4MZdwsAB",
      "created_at": 1721764867,
      "fine_tuned_model_checkpoint": "ft:gpt-4o-mini-2024-07-18:my-org:custom-suffix:96olL566:ckpt-step-2000",
      "metrics": {
        "full_valid_loss": 0.134,
        "full_valid_mean_token_accuracy": 0.874
      },
      "fine_tuning_job_id": "ftjob-abc123",
      "step_number": 2000
    },
    {
      "object": "fine_tuning.job.checkpoint",
      "id": "ftckpt_enQCFmOTGj3syEpYVhBRLTSy",
      "created_at": 1721764800,
      "fine_tuned_model_checkpoint": "ft:gpt-4o-mini-2024-07-18:my-org:custom-suffix:7q8mpxmy:ckpt-step-1000",
      "metrics": {
        "full_valid_loss": 0.167,
        "full_valid_mean_token_accuracy": 0.781
      },
      "fine_tuning_job_id": "ftjob-abc123",
      "step_number": 1000
    }
  ],
  "first_id": "ftckpt_zc4Q7MP6XxulcVzj4MZdwsAB",
  "last_id": "ftckpt_enQCFmOTGj3syEpYVhBRLTSy",
  "has_more": true
}


###### request

####### curl

curl https://api.openai.com/v1/fine_tuning/jobs/ftjob-abc123/checkpoints \
  -H "Authorization: Bearer $OPENAI_API_KEY"


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

// Automatically fetches more pages as needed.
for await (const fineTuningJobCheckpoint of client.fineTuning.jobs.checkpoints.list(
  'ft-AF1WoRqd3aJAHsqc9NY7iL8F',
)) {
  console.log(fineTuningJobCheckpoint.id);
}

####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
page = client.fine_tuning.jobs.checkpoints.list(
    fine_tuning_job_id="ft-AF1WoRqd3aJAHsqc9NY7iL8F",
)
page = page.data[0]
print(page.id)

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  page, err := client.FineTuning.Jobs.Checkpoints.List(
    context.TODO(),
    "ft-AF1WoRqd3aJAHsqc9NY7iL8F",
    openai.FineTuningJobCheckpointListParams{

    },
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", page)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.finetuning.jobs.checkpoints.CheckpointListPage;
import com.openai.models.finetuning.jobs.checkpoints.CheckpointListParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        CheckpointListPage page = client.fineTuning().jobs().checkpoints().list("ft-AF1WoRqd3aJAHsqc9NY7iL8F");
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

page = openai.fine_tuning.jobs.checkpoints.list("ft-AF1WoRqd3aJAHsqc9NY7iL8F")

puts(page)

#### description

List checkpoints for a fine-tuning job.


## /fine_tuning/jobs/{fine_tuning_job_id}/events

### get

#### operationId

listFineTuningEvents

#### tags

- Fine-tuning

#### summary

List fine-tuning events

#### parameters

##### in

path

##### name

fine_tuning_job_id

##### required

true

##### schema

###### type

string

###### example

ft-AF1WoRqd3aJAHsqc9NY7iL8F

##### description

The ID of the fine-tuning job to get events for.


##### name

after

##### in

query

##### description

Identifier for the last event from the previous pagination request.

##### required

false

##### schema

###### type

string

##### name

limit

##### in

query

##### description

Number of events to retrieve.

##### required

false

##### schema

###### type

integer

###### default

20


#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ListFineTuningJobEventsResponse

#### x-oaiMeta

##### name

List fine-tuning events

##### group

fine-tuning

##### returns

A list of fine-tuning event objects.

##### examples

###### response

{
  "object": "list",
  "data": [
    {
      "object": "fine_tuning.job.event",
      "id": "ft-event-ddTJfwuMVpfLXseO0Am0Gqjm",
      "created_at": 1721764800,
      "level": "info",
      "message": "Fine tuning job successfully completed",
      "data": null,
      "type": "message"
    },
    {
      "object": "fine_tuning.job.event",
      "id": "ft-event-tyiGuB72evQncpH87xe505Sv",
      "created_at": 1721764800,
      "level": "info",
      "message": "New fine-tuned model created: ft:gpt-4o-mini:openai::7p4lURel",
      "data": null,
      "type": "message"
    }
  ],
  "has_more": true
}


###### request

####### curl

curl https://api.openai.com/v1/fine_tuning/jobs/ftjob-abc123/events \
  -H "Authorization: Bearer $OPENAI_API_KEY"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
page = client.fine_tuning.jobs.list_events(
    fine_tuning_job_id="ft-AF1WoRqd3aJAHsqc9NY7iL8F",
)
page = page.data[0]
print(page.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

// Automatically fetches more pages as needed.
for await (const fineTuningJobEvent of client.fineTuning.jobs.listEvents('ft-AF1WoRqd3aJAHsqc9NY7iL8F')) {
  console.log(fineTuningJobEvent.id);
}

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  page, err := client.FineTuning.Jobs.ListEvents(
    context.TODO(),
    "ft-AF1WoRqd3aJAHsqc9NY7iL8F",
    openai.FineTuningJobListEventsParams{

    },
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", page)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.finetuning.jobs.JobListEventsPage;
import com.openai.models.finetuning.jobs.JobListEventsParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        JobListEventsPage page = client.fineTuning().jobs().listEvents("ft-AF1WoRqd3aJAHsqc9NY7iL8F");
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

page = openai.fine_tuning.jobs.list_events("ft-AF1WoRqd3aJAHsqc9NY7iL8F")

puts(page)

#### description

Get status updates for a fine-tuning job.


## /fine_tuning/jobs/{fine_tuning_job_id}/pause

### post

#### operationId

pauseFineTuningJob

#### tags

- Fine-tuning

#### summary

Pause fine-tuning

#### parameters

##### in

path

##### name

fine_tuning_job_id

##### required

true

##### schema

###### type

string

###### example

ft-AF1WoRqd3aJAHsqc9NY7iL8F

##### description

The ID of the fine-tuning job to pause.



#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/FineTuningJob

#### x-oaiMeta

##### name

Pause fine-tuning

##### group

fine-tuning

##### returns

The paused [fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning/object) object.

##### examples

###### response

{
  "object": "fine_tuning.job",
  "id": "ftjob-abc123",
  "model": "gpt-4o-mini-2024-07-18",
  "created_at": 1721764800,
  "fine_tuned_model": null,
  "organization_id": "org-123",
  "result_files": [],
  "status": "paused",
  "validation_file": "file-abc123",
  "training_file": "file-abc123"
}


###### request

####### curl

curl -X POST https://api.openai.com/v1/fine_tuning/jobs/ftjob-abc123/pause \
  -H "Authorization: Bearer $OPENAI_API_KEY"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
fine_tuning_job = client.fine_tuning.jobs.pause(
    "ft-AF1WoRqd3aJAHsqc9NY7iL8F",
)
print(fine_tuning_job.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const fineTuningJob = await client.fineTuning.jobs.pause('ft-AF1WoRqd3aJAHsqc9NY7iL8F');

console.log(fineTuningJob.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  fineTuningJob, err := client.FineTuning.Jobs.Pause(context.TODO(), "ft-AF1WoRqd3aJAHsqc9NY7iL8F")
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", fineTuningJob.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.finetuning.jobs.FineTuningJob;
import com.openai.models.finetuning.jobs.JobPauseParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        FineTuningJob fineTuningJob = client.fineTuning().jobs().pause("ft-AF1WoRqd3aJAHsqc9NY7iL8F");
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

fine_tuning_job = openai.fine_tuning.jobs.pause("ft-AF1WoRqd3aJAHsqc9NY7iL8F")

puts(fine_tuning_job)

#### description

Pause a fine-tune job.


## /fine_tuning/jobs/{fine_tuning_job_id}/resume

### post

#### operationId

resumeFineTuningJob

#### tags

- Fine-tuning

#### summary

Resume fine-tuning

#### parameters

##### in

path

##### name

fine_tuning_job_id

##### required

true

##### schema

###### type

string

###### example

ft-AF1WoRqd3aJAHsqc9NY7iL8F

##### description

The ID of the fine-tuning job to resume.



#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/FineTuningJob

#### x-oaiMeta

##### name

Resume fine-tuning

##### group

fine-tuning

##### returns

The resumed [fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning/object) object.

##### examples

###### response

{
  "object": "fine_tuning.job",
  "id": "ftjob-abc123",
  "model": "gpt-4o-mini-2024-07-18",
  "created_at": 1721764800,
  "fine_tuned_model": null,
  "organization_id": "org-123",
  "result_files": [],
  "status": "queued",
  "validation_file": "file-abc123",
  "training_file": "file-abc123"
}


###### request

####### curl

curl -X POST https://api.openai.com/v1/fine_tuning/jobs/ftjob-abc123/resume \
  -H "Authorization: Bearer $OPENAI_API_KEY"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
fine_tuning_job = client.fine_tuning.jobs.resume(
    "ft-AF1WoRqd3aJAHsqc9NY7iL8F",
)
print(fine_tuning_job.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const fineTuningJob = await client.fineTuning.jobs.resume('ft-AF1WoRqd3aJAHsqc9NY7iL8F');

console.log(fineTuningJob.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  fineTuningJob, err := client.FineTuning.Jobs.Resume(context.TODO(), "ft-AF1WoRqd3aJAHsqc9NY7iL8F")
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", fineTuningJob.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.finetuning.jobs.FineTuningJob;
import com.openai.models.finetuning.jobs.JobResumeParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        FineTuningJob fineTuningJob = client.fineTuning().jobs().resume("ft-AF1WoRqd3aJAHsqc9NY7iL8F");
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

fine_tuning_job = openai.fine_tuning.jobs.resume("ft-AF1WoRqd3aJAHsqc9NY7iL8F")

puts(fine_tuning_job)

#### description

Resume a fine-tune job.


## /images/edits

### post

#### operationId

createImageEdit

#### tags

- Images

#### summary

Create image edit

#### requestBody

##### required

true

##### content

###### multipart/form-data

####### schema

######## $ref

#/components/schemas/CreateImageEditRequest

#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ImagesResponse

####### text/event-stream

######## schema

######### $ref

#/components/schemas/ImageEditStreamEvent

#### x-oaiMeta

##### name

Create image edit

##### group

images

##### returns

Returns an [image](https://platform.openai.com/docs/api-reference/images/object) object.

##### examples

###### title

Edit image

###### request

####### curl

curl -s -D >(grep -i x-request-id >&2) \
  -o >(jq -r '.data[0].b64_json' | base64 --decode > gift-basket.png) \
  -X POST "https://api.openai.com/v1/images/edits" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -F "model=gpt-image-1" \
  -F "image[]=@body-lotion.png" \
  -F "image[]=@bath-bomb.png" \
  -F "image[]=@incense-kit.png" \
  -F "image[]=@soap.png" \
  -F 'prompt=Create a lovely gift basket with these four items in it'


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
images_response = client.images.edit(
    image=b"raw file contents",
    prompt="A cute baby sea otter wearing a beret",
)
print(images_response)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const imagesResponse = await client.images.edit({
  image: fs.createReadStream('path/to/file'),
  prompt: 'A cute baby sea otter wearing a beret',
});

console.log(imagesResponse);

####### go

package main

import (
  "bytes"
  "context"
  "fmt"
  "io"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  imagesResponse, err := client.Images.Edit(context.TODO(), openai.ImageEditParams{
    Image: openai.ImageEditParamsImageUnion{
      OfFile: io.Reader(bytes.NewBuffer([]byte("some file contents"))),
    },
    Prompt: "A cute baby sea otter wearing a beret",
  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", imagesResponse)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.images.ImageEditParams;
import com.openai.models.images.ImagesResponse;
import java.io.ByteArrayInputStream;
import java.io.InputStream;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        ImageEditParams params = ImageEditParams.builder()
            .image(ByteArrayInputStream("some content".getBytes()))
            .prompt("A cute baby sea otter wearing a beret")
            .build();
        ImagesResponse imagesResponse = client.images().edit(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

images_response = openai.images.edit(image: Pathname(__FILE__), prompt: "A cute baby sea otter wearing a beret")

puts(images_response)

###### title

Streaming

###### request

####### curl

curl -s -N -X POST "https://api.openai.com/v1/images/edits" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -F "model=gpt-image-1" \
  -F "image[]=@body-lotion.png" \
  -F "image[]=@bath-bomb.png" \
  -F "image[]=@incense-kit.png" \
  -F "image[]=@soap.png" \
  -F 'prompt=Create a lovely gift basket with these four items in it' \
  -F "stream=true"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
images_response = client.images.edit(
    image=b"raw file contents",
    prompt="A cute baby sea otter wearing a beret",
)
print(images_response)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const imagesResponse = await client.images.edit({
  image: fs.createReadStream('path/to/file'),
  prompt: 'A cute baby sea otter wearing a beret',
});

console.log(imagesResponse);

####### go

package main

import (
  "bytes"
  "context"
  "fmt"
  "io"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  imagesResponse, err := client.Images.Edit(context.TODO(), openai.ImageEditParams{
    Image: openai.ImageEditParamsImageUnion{
      OfFile: io.Reader(bytes.NewBuffer([]byte("some file contents"))),
    },
    Prompt: "A cute baby sea otter wearing a beret",
  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", imagesResponse)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.images.ImageEditParams;
import com.openai.models.images.ImagesResponse;
import java.io.ByteArrayInputStream;
import java.io.InputStream;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        ImageEditParams params = ImageEditParams.builder()
            .image(ByteArrayInputStream("some content".getBytes()))
            .prompt("A cute baby sea otter wearing a beret")
            .build();
        ImagesResponse imagesResponse = client.images().edit(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

images_response = openai.images.edit(image: Pathname(__FILE__), prompt: "A cute baby sea otter wearing a beret")

puts(images_response)

###### response

event: image_edit.partial_image
data: {"type":"image_edit.partial_image","b64_json":"...","partial_image_index":0}

event: image_edit.completed
data: {"type":"image_edit.completed","b64_json":"...","usage":{"total_tokens":100,"input_tokens":50,"output_tokens":50,"input_tokens_details":{"text_tokens":10,"image_tokens":40}}}



#### description

Creates an edited or extended image given one or more source images and a prompt. This endpoint only supports `gpt-image-1` and `dall-e-2`.

## /images/generations

### post

#### operationId

createImage

#### tags

- Images

#### summary

Create image

#### requestBody

##### required

true

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/CreateImageRequest

#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ImagesResponse

####### text/event-stream

######## schema

######### $ref

#/components/schemas/ImageGenStreamEvent

#### x-oaiMeta

##### name

Create image

##### group

images

##### returns

Returns an [image](https://platform.openai.com/docs/api-reference/images/object) object.

##### examples

###### title

Generate image

###### request

####### curl

curl https://api.openai.com/v1/images/generations \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "gpt-image-1",
    "prompt": "A cute baby sea otter",
    "n": 1,
    "size": "1024x1024"
  }'


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
images_response = client.images.generate(
    prompt="A cute baby sea otter",
)
print(images_response)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const imagesResponse = await client.images.generate({ prompt: 'A cute baby sea otter' });

console.log(imagesResponse);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  imagesResponse, err := client.Images.Generate(context.TODO(), openai.ImageGenerateParams{
    Prompt: "A cute baby sea otter",
  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", imagesResponse)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.images.ImageGenerateParams;
import com.openai.models.images.ImagesResponse;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        ImageGenerateParams params = ImageGenerateParams.builder()
            .prompt("A cute baby sea otter")
            .build();
        ImagesResponse imagesResponse = client.images().generate(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

images_response = openai.images.generate(prompt: "A cute baby sea otter")

puts(images_response)

###### response

{
  "created": 1713833628,
  "data": [
    {
      "b64_json": "..."
    }
  ],
  "usage": {
    "total_tokens": 100,
    "input_tokens": 50,
    "output_tokens": 50,
    "input_tokens_details": {
      "text_tokens": 10,
      "image_tokens": 40
    }
  }
}


###### title

Streaming

###### request

####### curl

curl https://api.openai.com/v1/images/generations \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "gpt-image-1",
    "prompt": "A cute baby sea otter",
    "n": 1,
    "size": "1024x1024",
    "stream": true
  }' \
  --no-buffer


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
images_response = client.images.generate(
    prompt="A cute baby sea otter",
)
print(images_response)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const imagesResponse = await client.images.generate({ prompt: 'A cute baby sea otter' });

console.log(imagesResponse);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  imagesResponse, err := client.Images.Generate(context.TODO(), openai.ImageGenerateParams{
    Prompt: "A cute baby sea otter",
  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", imagesResponse)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.images.ImageGenerateParams;
import com.openai.models.images.ImagesResponse;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        ImageGenerateParams params = ImageGenerateParams.builder()
            .prompt("A cute baby sea otter")
            .build();
        ImagesResponse imagesResponse = client.images().generate(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

images_response = openai.images.generate(prompt: "A cute baby sea otter")

puts(images_response)

###### response

event: image_generation.partial_image
data: {"type":"image_generation.partial_image","b64_json":"...","partial_image_index":0}

event: image_generation.completed
data: {"type":"image_generation.completed","b64_json":"...","usage":{"total_tokens":100,"input_tokens":50,"output_tokens":50,"input_tokens_details":{"text_tokens":10,"image_tokens":40}}}



#### description

Creates an image given a prompt. [Learn more](https://platform.openai.com/docs/guides/images).


## /images/variations

### post

#### operationId

createImageVariation

#### tags

- Images

#### summary

Create image variation

#### requestBody

##### required

true

##### content

###### multipart/form-data

####### schema

######## $ref

#/components/schemas/CreateImageVariationRequest

#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ImagesResponse

#### x-oaiMeta

##### name

Create image variation

##### group

images

##### returns

Returns a list of [image](https://platform.openai.com/docs/api-reference/images/object) objects.

##### examples

###### response

{
  "created": 1589478378,
  "data": [
    {
      "url": "https://..."
    },
    {
      "url": "https://..."
    }
  ]
}


###### request

####### curl

curl https://api.openai.com/v1/images/variations \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -F image="@otter.png" \
  -F n=2 \
  -F size="1024x1024"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
images_response = client.images.create_variation(
    image=b"raw file contents",
)
print(images_response.created)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const imagesResponse = await client.images.createVariation({ image: fs.createReadStream('otter.png') });

console.log(imagesResponse.created);

####### csharp

using System;

using OpenAI.Images;

ImageClient client = new(
    model: "dall-e-2",
    apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY")
);

GeneratedImage image = client.GenerateImageVariation(imageFilePath: "otter.png");

Console.WriteLine(image.ImageUri);


####### go

package main

import (
  "bytes"
  "context"
  "fmt"
  "io"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  imagesResponse, err := client.Images.NewVariation(context.TODO(), openai.ImageNewVariationParams{
    Image: io.Reader(bytes.NewBuffer([]byte("some file contents"))),
  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", imagesResponse.Created)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.images.ImageCreateVariationParams;
import com.openai.models.images.ImagesResponse;
import java.io.ByteArrayInputStream;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        ImageCreateVariationParams params = ImageCreateVariationParams.builder()
            .image(ByteArrayInputStream("some content".getBytes()))
            .build();
        ImagesResponse imagesResponse = client.images().createVariation(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

images_response = openai.images.create_variation(image: Pathname(__FILE__))

puts(images_response)

#### description

Creates a variation of a given image. This endpoint only supports `dall-e-2`.

## /models

### get

#### operationId

listModels

#### tags

- Models

#### summary

List models

#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ListModelsResponse

#### x-oaiMeta

##### name

List models

##### group

models

##### returns

A list of [model](https://platform.openai.com/docs/api-reference/models/object) objects.

##### examples

###### response

{
  "object": "list",
  "data": [
    {
      "id": "model-id-0",
      "object": "model",
      "created": 1686935002,
      "owned_by": "organization-owner"
    },
    {
      "id": "model-id-1",
      "object": "model",
      "created": 1686935002,
      "owned_by": "organization-owner",
    },
    {
      "id": "model-id-2",
      "object": "model",
      "created": 1686935002,
      "owned_by": "openai"
    },
  ],
  "object": "list"
}


###### request

####### curl

curl https://api.openai.com/v1/models \
  -H "Authorization: Bearer $OPENAI_API_KEY"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
page = client.models.list()
page = page.data[0]
print(page.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

// Automatically fetches more pages as needed.
for await (const model of client.models.list()) {
  console.log(model.id);
}

####### csharp

using System;

using OpenAI.Models;

OpenAIModelClient client = new(
    apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY")
);

foreach (var model in client.GetModels().Value)
{
    Console.WriteLine(model.Id);
}


####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  page, err := client.Models.List(context.TODO())
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", page)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.models.ModelListPage;
import com.openai.models.models.ModelListParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        ModelListPage page = client.models().list();
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

page = openai.models.list

puts(page)

#### description

Lists the currently available models, and provides basic information about each one such as the owner and availability.

## /models/{model}

### get

#### operationId

retrieveModel

#### tags

- Models

#### summary

Retrieve model

#### parameters

##### in

path

##### name

model

##### required

true

##### schema

###### type

string

###### example

gpt-4o-mini

##### description

The ID of the model to use for this request


#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/Model

#### x-oaiMeta

##### name

Retrieve model

##### group

models

##### returns

The [model](https://platform.openai.com/docs/api-reference/models/object) object matching the specified ID.

##### examples

###### response

{
  "id": "VAR_chat_model_id",
  "object": "model",
  "created": 1686935002,
  "owned_by": "openai"
}


###### request

####### curl

curl https://api.openai.com/v1/models/VAR_chat_model_id \
  -H "Authorization: Bearer $OPENAI_API_KEY"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
model = client.models.retrieve(
    "gpt-4o-mini",
)
print(model.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const model = await client.models.retrieve('gpt-4o-mini');

console.log(model.id);

####### csharp

using System;
using System.ClientModel;

using OpenAI.Models;

  OpenAIModelClient client = new(
    apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY")
);

ClientResult<OpenAIModel> model = client.GetModel("babbage-002");
Console.WriteLine(model.Value.Id);


####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  model, err := client.Models.Get(context.TODO(), "gpt-4o-mini")
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", model.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.models.Model;
import com.openai.models.models.ModelRetrieveParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        Model model = client.models().retrieve("gpt-4o-mini");
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

model = openai.models.retrieve("gpt-4o-mini")

puts(model)

#### description

Retrieves a model instance, providing basic information about the model such as the owner and permissioning.

### delete

#### operationId

deleteModel

#### tags

- Models

#### summary

Delete a fine-tuned model

#### parameters

##### in

path

##### name

model

##### required

true

##### schema

###### type

string

###### example

ft:gpt-4o-mini:acemeco:suffix:abc123

##### description

The model to delete


#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/DeleteModelResponse

#### x-oaiMeta

##### name

Delete a fine-tuned model

##### group

models

##### returns

Deletion status.

##### examples

###### response

{
  "id": "ft:gpt-4o-mini:acemeco:suffix:abc123",
  "object": "model",
  "deleted": true
}


###### request

####### curl

curl https://api.openai.com/v1/models/ft:gpt-4o-mini:acemeco:suffix:abc123 \
  -X DELETE \
  -H "Authorization: Bearer $OPENAI_API_KEY"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
model_deleted = client.models.delete(
    "ft:gpt-4o-mini:acemeco:suffix:abc123",
)
print(model_deleted.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const modelDeleted = await client.models.delete('ft:gpt-4o-mini:acemeco:suffix:abc123');

console.log(modelDeleted.id);

####### csharp

using System;
using System.ClientModel;

using OpenAI.Models;

OpenAIModelClient client = new(
    apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY")
);

ClientResult success = client.DeleteModel("ft:gpt-4o-mini:acemeco:suffix:abc123");
Console.WriteLine(success);


####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  modelDeleted, err := client.Models.Delete(context.TODO(), "ft:gpt-4o-mini:acemeco:suffix:abc123")
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", modelDeleted.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.models.ModelDeleteParams;
import com.openai.models.models.ModelDeleted;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        ModelDeleted modelDeleted = client.models().delete("ft:gpt-4o-mini:acemeco:suffix:abc123");
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

model_deleted = openai.models.delete("ft:gpt-4o-mini:acemeco:suffix:abc123")

puts(model_deleted)

#### description

Delete a fine-tuned model. You must have the Owner role in your organization to delete a model.

## /moderations

### post

#### operationId

createModeration

#### tags

- Moderations

#### summary

Create moderation

#### requestBody

##### required

true

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/CreateModerationRequest

#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/CreateModerationResponse

#### x-oaiMeta

##### name

Create moderation

##### group

moderations

##### returns

A [moderation](https://platform.openai.com/docs/api-reference/moderations/object) object.

##### examples

###### title

Single string

###### request

####### curl

curl https://api.openai.com/v1/moderations \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "input": "I want to kill them."
  }'


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
moderation = client.moderations.create(
    input="I want to kill them.",
)
print(moderation.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const moderation = await client.moderations.create({ input: 'I want to kill them.' });

console.log(moderation.id);

####### csharp

using System;
using System.ClientModel;

using OpenAI.Moderations;

ModerationClient client = new(
    model: "omni-moderation-latest",
    apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY")
);

ClientResult<ModerationResult> moderation = client.ClassifyText("I want to kill them.");


####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  moderation, err := client.Moderations.New(context.TODO(), openai.ModerationNewParams{
    Input: openai.ModerationNewParamsInputUnion{
      OfString: openai.String("I want to kill them."),
    },
  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", moderation.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.moderations.ModerationCreateParams;
import com.openai.models.moderations.ModerationCreateResponse;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        ModerationCreateParams params = ModerationCreateParams.builder()
            .input("I want to kill them.")
            .build();
        ModerationCreateResponse moderation = client.moderations().create(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

moderation = openai.moderations.create(input: "I want to kill them.")

puts(moderation)

###### response

{
  "id": "modr-AB8CjOTu2jiq12hp1AQPfeqFWaORR",
  "model": "text-moderation-007",
  "results": [
    {
      "flagged": true,
      "categories": {
        "sexual": false,
        "hate": false,
        "harassment": true,
        "self-harm": false,
        "sexual/minors": false,
        "hate/threatening": false,
        "violence/graphic": false,
        "self-harm/intent": false,
        "self-harm/instructions": false,
        "harassment/threatening": true,
        "violence": true
      },
      "category_scores": {
        "sexual": 0.000011726012417057063,
        "hate": 0.22706663608551025,
        "harassment": 0.5215635299682617,
        "self-harm": 2.227119921371923e-6,
        "sexual/minors": 7.107352217872176e-8,
        "hate/threatening": 0.023547329008579254,
        "violence/graphic": 0.00003391829886822961,
        "self-harm/intent": 1.646940972932498e-6,
        "self-harm/instructions": 1.1198755256458526e-9,
        "harassment/threatening": 0.5694745779037476,
        "violence": 0.9971134662628174
      }
    }
  ]
}


###### title

Image and text

###### request

####### curl

curl https://api.openai.com/v1/moderations \
  -X POST \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "omni-moderation-latest",
    "input": [
      { "type": "text", "text": "...text to classify goes here..." },
      {
        "type": "image_url",
        "image_url": {
          "url": "https://example.com/image.png"
        }
      }
    ]
  }'


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
moderation = client.moderations.create(
    input="I want to kill them.",
)
print(moderation.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const moderation = await client.moderations.create({ input: 'I want to kill them.' });

console.log(moderation.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  moderation, err := client.Moderations.New(context.TODO(), openai.ModerationNewParams{
    Input: openai.ModerationNewParamsInputUnion{
      OfString: openai.String("I want to kill them."),
    },
  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", moderation.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.moderations.ModerationCreateParams;
import com.openai.models.moderations.ModerationCreateResponse;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        ModerationCreateParams params = ModerationCreateParams.builder()
            .input("I want to kill them.")
            .build();
        ModerationCreateResponse moderation = client.moderations().create(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

moderation = openai.moderations.create(input: "I want to kill them.")

puts(moderation)

###### response

{
  "id": "modr-0d9740456c391e43c445bf0f010940c7",
  "model": "omni-moderation-latest",
  "results": [
    {
      "flagged": true,
      "categories": {
        "harassment": true,
        "harassment/threatening": true,
        "sexual": false,
        "hate": false,
        "hate/threatening": false,
        "illicit": false,
        "illicit/violent": false,
        "self-harm/intent": false,
        "self-harm/instructions": false,
        "self-harm": false,
        "sexual/minors": false,
        "violence": true,
        "violence/graphic": true
      },
      "category_scores": {
        "harassment": 0.8189693396524255,
        "harassment/threatening": 0.804985420696006,
        "sexual": 1.573112165348997e-6,
        "hate": 0.007562942636942845,
        "hate/threatening": 0.004208854591835476,
        "illicit": 0.030535955153511665,
        "illicit/violent": 0.008925306722380033,
        "self-harm/intent": 0.00023023930975076432,
        "self-harm/instructions": 0.0002293869201073356,
        "self-harm": 0.012598046106750154,
        "sexual/minors": 2.212566909570261e-8,
        "violence": 0.9999992735124786,
        "violence/graphic": 0.843064871157054
      },
      "category_applied_input_types": {
        "harassment": [
          "text"
        ],
        "harassment/threatening": [
          "text"
        ],
        "sexual": [
          "text",
          "image"
        ],
        "hate": [
          "text"
        ],
        "hate/threatening": [
          "text"
        ],
        "illicit": [
          "text"
        ],
        "illicit/violent": [
          "text"
        ],
        "self-harm/intent": [
          "text",
          "image"
        ],
        "self-harm/instructions": [
          "text",
          "image"
        ],
        "self-harm": [
          "text",
          "image"
        ],
        "sexual/minors": [
          "text"
        ],
        "violence": [
          "text",
          "image"
        ],
        "violence/graphic": [
          "text",
          "image"
        ]
      }
    }
  ]
}



#### description

Classifies if text and/or image inputs are potentially harmful. Learn
more in the [moderation guide](https://platform.openai.com/docs/guides/moderation).


## /organization/admin_api_keys

### get

#### summary

List all organization and project API keys.

#### operationId

admin-api-keys-list

#### description

List organization API keys

#### parameters

##### in

query

##### name

after

##### required

false

##### schema

###### type

string

###### nullable

true

###### description

Return keys with IDs that come after this ID in the pagination order.

##### in

query

##### name

order

##### required

false

##### schema

###### type

string

###### enum

- asc
- desc

###### default

asc

###### description

Order results by creation time, ascending or descending.

##### in

query

##### name

limit

##### required

false

##### schema

###### type

integer

###### default

20

###### description

Maximum number of keys to return.


#### responses

##### 200

###### description

A list of organization API keys.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ApiKeyList

#### x-oaiMeta

##### name

List all organization and project API keys.

##### group

administration

##### returns

A list of admin and project API key objects.

##### examples

###### response

{
  "object": "list",
  "data": [
    {
      "object": "organization.admin_api_key",
      "id": "key_abc",
      "name": "Main Admin Key",
      "redacted_value": "sk-admin...def",
      "created_at": 1711471533,
      "last_used_at": 1711471534,
      "owner": {
        "type": "service_account",
        "object": "organization.service_account",
        "id": "sa_456",
        "name": "My Service Account",
        "created_at": 1711471533,
        "role": "member"
      }
    }
  ],
  "first_id": "key_abc",
  "last_id": "key_abc",
  "has_more": false
}


###### request

####### curl

curl https://api.openai.com/v1/organization/admin_api_keys?after=key_abc&limit=20 \
  -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \
  -H "Content-Type: application/json"


### post

#### summary

Create admin API key

#### operationId

admin-api-keys-create

#### description

Create an organization admin API key

#### requestBody

##### required

true

##### content

###### application/json

####### schema

######## type

object

######## required

- name

######## properties

######### name

########## type

string

########## example

New Admin Key

#### responses

##### 200

###### description

The newly created admin API key.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/AdminApiKey

#### x-oaiMeta

##### name

Create admin API key

##### group

administration

##### returns

The created [AdminApiKey](https://platform.openai.com/docs/api-reference/admin-api-keys/object) object.

##### examples

###### response

{
  "object": "organization.admin_api_key",
  "id": "key_xyz",
  "name": "New Admin Key",
  "redacted_value": "sk-admin...xyz",
  "created_at": 1711471533,
  "last_used_at": 1711471534,
  "owner": {
    "type": "user",
    "object": "organization.user",
    "id": "user_123",
    "name": "John Doe",
    "created_at": 1711471533,
    "role": "owner"
  },
  "value": "sk-admin-1234abcd"
}


###### request

####### curl

curl -X POST https://api.openai.com/v1/organization/admin_api_keys \
  -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \
  -H "Content-Type: application/json" \
  -d '{
      "name": "New Admin Key"
  }'


## /organization/admin_api_keys/{key_id}

### get

#### summary

Retrieve admin API key

#### operationId

admin-api-keys-get

#### description

Retrieve a single organization API key

#### parameters

##### in

path

##### name

key_id

##### required

true

##### schema

###### type

string

###### description

The ID of the API key.


#### responses

##### 200

###### description

Details of the requested API key.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/AdminApiKey

#### x-oaiMeta

##### name

Retrieve admin API key

##### group

administration

##### returns

The requested [AdminApiKey](https://platform.openai.com/docs/api-reference/admin-api-keys/object) object.

##### examples

###### response

{
  "object": "organization.admin_api_key",
  "id": "key_abc",
  "name": "Main Admin Key",
  "redacted_value": "sk-admin...xyz",
  "created_at": 1711471533,
  "last_used_at": 1711471534,
  "owner": {
    "type": "user",
    "object": "organization.user",
    "id": "user_123",
    "name": "John Doe",
    "created_at": 1711471533,
    "role": "owner"
  }
}


###### request

####### curl

curl https://api.openai.com/v1/organization/admin_api_keys/key_abc \
  -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \
  -H "Content-Type: application/json"


### delete

#### summary

Delete admin API key

#### operationId

admin-api-keys-delete

#### description

Delete an organization admin API key

#### parameters

##### in

path

##### name

key_id

##### required

true

##### schema

###### type

string

###### description

The ID of the API key to be deleted.


#### responses

##### 200

###### description

Confirmation that the API key was deleted.

###### content

####### application/json

######## schema

######### type

object

######### properties

########## id

########### type

string

########### example

key_abc

########## object

########### type

string

########### example

organization.admin_api_key.deleted

########## deleted

########### type

boolean

########### example

true

#### x-oaiMeta

##### name

Delete admin API key

##### group

administration

##### returns

A confirmation object indicating the key was deleted.

##### examples

###### response

{
  "id": "key_abc",
  "object": "organization.admin_api_key.deleted",
  "deleted": true
}


###### request

####### curl

curl -X DELETE https://api.openai.com/v1/organization/admin_api_keys/key_abc \
  -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \
  -H "Content-Type: application/json"


## /organization/audit_logs

### get

#### summary

List audit logs

#### operationId

list-audit-logs

#### tags

- Audit Logs

#### parameters

##### name

effective_at

##### in

query

##### description

Return only events whose `effective_at` (Unix seconds) is in this range.

##### required

false

##### schema

###### type

object

###### properties

####### gt

######## type

integer

######## description

Return only events whose `effective_at` (Unix seconds) is greater than this value.

####### gte

######## type

integer

######## description

Return only events whose `effective_at` (Unix seconds) is greater than or equal to this value.

####### lt

######## type

integer

######## description

Return only events whose `effective_at` (Unix seconds) is less than this value.

####### lte

######## type

integer

######## description

Return only events whose `effective_at` (Unix seconds) is less than or equal to this value.

##### name

project_ids[]

##### in

query

##### description

Return only events for these projects.

##### required

false

##### schema

###### type

array

###### items

####### type

string

##### name

event_types[]

##### in

query

##### description

Return only events with a `type` in one of these values. For example, `project.created`. For all options, see the documentation for the [audit log object](https://platform.openai.com/docs/api-reference/audit-logs/object).

##### required

false

##### schema

###### type

array

###### items

####### $ref

#/components/schemas/AuditLogEventType

##### name

actor_ids[]

##### in

query

##### description

Return only events performed by these actors. Can be a user ID, a service account ID, or an api key tracking ID.

##### required

false

##### schema

###### type

array

###### items

####### type

string

##### name

actor_emails[]

##### in

query

##### description

Return only events performed by users with these emails.

##### required

false

##### schema

###### type

array

###### items

####### type

string

##### name

resource_ids[]

##### in

query

##### description

Return only events performed on these targets. For example, a project ID updated.

##### required

false

##### schema

###### type

array

###### items

####### type

string

##### name

limit

##### in

query

##### description

A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20.


##### required

false

##### schema

###### type

integer

###### default

20

##### name

after

##### in

query

##### description

A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list.


##### schema

###### type

string

##### name

before

##### in

query

##### description

A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list.


##### schema

###### type

string


#### responses

##### 200

###### description

Audit logs listed successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ListAuditLogsResponse

#### x-oaiMeta

##### name

List audit logs

##### group

audit-logs

##### returns

A list of paginated [Audit Log](https://platform.openai.com/docs/api-reference/audit-logs/object) objects.

##### examples

###### response

{
    "object": "list",
    "data": [
        {
            "id": "audit_log-xxx_yyyymmdd",
            "type": "project.archived",
            "effective_at": 1722461446,
            "actor": {
                "type": "api_key",
                "api_key": {
                    "type": "user",
                    "user": {
                        "id": "user-xxx",
                        "email": "user@example.com"
                    }
                }
            },
            "project.archived": {
                "id": "proj_abc"
            },
        },
        {
            "id": "audit_log-yyy__20240101",
            "type": "api_key.updated",
            "effective_at": 1720804190,
            "actor": {
                "type": "session",
                "session": {
                    "user": {
                        "id": "user-xxx",
                        "email": "user@example.com"
                    },
                    "ip_address": "127.0.0.1",
                    "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
                    "ja3": "a497151ce4338a12c4418c44d375173e",
                    "ja4": "q13d0313h3_55b375c5d22e_c7319ce65786",
                    "ip_address_details": {
                      "country": "US",
                      "city": "San Francisco",
                      "region": "California",
                      "region_code": "CA",
                      "asn": "1234",
                      "latitude": "37.77490",
                      "longitude": "-122.41940"
                    }
                }
            },
            "api_key.updated": {
                "id": "key_xxxx",
                "data": {
                    "scopes": ["resource_2.operation_2"]
                }
            },
        }
    ],
    "first_id": "audit_log-xxx__20240101",
    "last_id": "audit_log_yyy__20240101",
    "has_more": true
}


###### request

####### curl

curl https://api.openai.com/v1/organization/audit_logs \
-H "Authorization: Bearer $OPENAI_ADMIN_KEY" \
-H "Content-Type: application/json"


#### description

List user actions and configuration changes within this organization.

## /organization/certificates

### get

#### summary

List organization certificates

#### operationId

listOrganizationCertificates

#### tags

- Certificates

#### parameters

##### name

limit

##### in

query

##### description

A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20.


##### required

false

##### schema

###### type

integer

###### default

20

##### name

after

##### in

query

##### description

A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list.


##### required

false

##### schema

###### type

string

##### name

order

##### in

query

##### description

Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order.


##### schema

###### type

string

###### default

desc

###### enum

- asc
- desc


#### responses

##### 200

###### description

Certificates listed successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ListCertificatesResponse

#### x-oaiMeta

##### name

List organization certificates

##### group

administration

##### returns

A list of [Certificate](https://platform.openai.com/docs/api-reference/certificates/object) objects.

##### examples

###### request

####### curl

curl https://api.openai.com/v1/organization/certificates \
-H "Authorization: Bearer $OPENAI_ADMIN_KEY"


###### response

{
  "object": "list",
  "data": [
    {
      "object": "organization.certificate",
      "id": "cert_abc",
      "name": "My Example Certificate",
      "active": true,
      "created_at": 1234567,
      "certificate_details": {
        "valid_at": 12345667,
        "expires_at": 12345678
      }
    },
  ],
  "first_id": "cert_abc",
  "last_id": "cert_abc",
  "has_more": false
}


#### description

List uploaded certificates for this organization.

### post

#### summary

Upload certificate

#### operationId

uploadCertificate

#### tags

- Certificates

#### requestBody

##### description

The certificate upload payload.

##### required

true

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/UploadCertificateRequest

#### responses

##### 200

###### description

Certificate uploaded successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/Certificate

#### x-oaiMeta

##### name

Upload certificate

##### group

administration

##### returns

A single [Certificate](https://platform.openai.com/docs/api-reference/certificates/object) object.

##### examples

###### request

####### curl

curl -X POST https://api.openai.com/v1/organization/certificates \
-H "Authorization: Bearer $OPENAI_ADMIN_KEY" \
-H "Content-Type: application/json" \
-d '{
  "name": "My Example Certificate",
  "certificate": "-----BEGIN CERTIFICATE-----\\nMIIDeT...\\n-----END CERTIFICATE-----"
}'


###### response

{
  "object": "certificate",
  "id": "cert_abc",
  "name": "My Example Certificate",
  "created_at": 1234567,
  "certificate_details": {
    "valid_at": 12345667,
    "expires_at": 12345678
  }
}


#### description

Upload a certificate to the organization. This does **not** automatically activate the certificate.

Organizations can upload up to 50 certificates.


## /organization/certificates/activate

### post

#### summary

Activate certificates for organization

#### operationId

activateOrganizationCertificates

#### tags

- Certificates

#### requestBody

##### description

The certificate activation payload.

##### required

true

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/ToggleCertificatesRequest

#### responses

##### 200

###### description

Certificates activated successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ListCertificatesResponse

#### x-oaiMeta

##### name

Activate certificates for organization

##### group

administration

##### returns

A list of [Certificate](https://platform.openai.com/docs/api-reference/certificates/object) objects that were activated.

##### examples

###### request

####### curl

curl https://api.openai.com/v1/organization/certificates/activate \
-H "Authorization: Bearer $OPENAI_ADMIN_KEY" \
-H "Content-Type: application/json" \
-d '{
  "data": ["cert_abc", "cert_def"]
}'


###### response

{
  "object": "organization.certificate.activation",
  "data": [
    {
      "object": "organization.certificate",
      "id": "cert_abc",
      "name": "My Example Certificate",
      "active": true,
      "created_at": 1234567,
      "certificate_details": {
        "valid_at": 12345667,
        "expires_at": 12345678
      }
    },
    {
      "object": "organization.certificate",
      "id": "cert_def",
      "name": "My Example Certificate 2",
      "active": true,
      "created_at": 1234567,
      "certificate_details": {
        "valid_at": 12345667,
        "expires_at": 12345678
      }
    },
  ],
}


#### description

Activate certificates at the organization level.

You can atomically and idempotently activate up to 10 certificates at a time.


## /organization/certificates/deactivate

### post

#### summary

Deactivate certificates for organization

#### operationId

deactivateOrganizationCertificates

#### tags

- Certificates

#### requestBody

##### description

The certificate deactivation payload.

##### required

true

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/ToggleCertificatesRequest

#### responses

##### 200

###### description

Certificates deactivated successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ListCertificatesResponse

#### x-oaiMeta

##### name

Deactivate certificates for organization

##### group

administration

##### returns

A list of [Certificate](https://platform.openai.com/docs/api-reference/certificates/object) objects that were deactivated.

##### examples

###### request

####### curl

curl https://api.openai.com/v1/organization/certificates/deactivate \
-H "Authorization: Bearer $OPENAI_ADMIN_KEY" \
-H "Content-Type: application/json" \
-d '{
  "data": ["cert_abc", "cert_def"]
}'


###### response

{
  "object": "organization.certificate.deactivation",
  "data": [
    {
      "object": "organization.certificate",
      "id": "cert_abc",
      "name": "My Example Certificate",
      "active": false,
      "created_at": 1234567,
      "certificate_details": {
        "valid_at": 12345667,
        "expires_at": 12345678
      }
    },
    {
      "object": "organization.certificate",
      "id": "cert_def",
      "name": "My Example Certificate 2",
      "active": false,
      "created_at": 1234567,
      "certificate_details": {
        "valid_at": 12345667,
        "expires_at": 12345678
      }
    },
  ],
}


#### description

Deactivate certificates at the organization level.

You can atomically and idempotently deactivate up to 10 certificates at a time.


## /organization/certificates/{certificate_id}

### get

#### summary

Get certificate

#### operationId

getCertificate

#### tags

- Certificates

#### parameters

##### name

certificate_id

##### in

path

##### description

Unique ID of the certificate to retrieve.

##### required

true

##### schema

###### type

string

##### name

include

##### in

query

##### description

A list of additional fields to include in the response. Currently the only supported value is `content` to fetch the PEM content of the certificate.

##### required

false

##### schema

###### type

array

###### items

####### type

string

####### enum

- content


#### responses

##### 200

###### description

Certificate retrieved successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/Certificate

#### x-oaiMeta

##### name

Get certificate

##### group

administration

##### returns

A single [Certificate](https://platform.openai.com/docs/api-reference/certificates/object) object.

##### examples

###### request

####### curl

curl "https://api.openai.com/v1/organization/certificates/cert_abc?include[]=content" \
-H "Authorization: Bearer $OPENAI_ADMIN_KEY"


###### response

{
  "object": "certificate",
  "id": "cert_abc",
  "name": "My Example Certificate",
  "created_at": 1234567,
  "certificate_details": {
    "valid_at": 1234567,
    "expires_at": 12345678,
    "content": "-----BEGIN CERTIFICATE-----MIIDeT...-----END CERTIFICATE-----"
  }
}


#### description

Get a certificate that has been uploaded to the organization.

You can get a certificate regardless of whether it is active or not.


### post

#### summary

Modify certificate

#### operationId

modifyCertificate

#### tags

- Certificates

#### requestBody

##### description

The certificate modification payload.

##### required

true

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/ModifyCertificateRequest

#### responses

##### 200

###### description

Certificate modified successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/Certificate

#### x-oaiMeta

##### name

Modify certificate

##### group

administration

##### returns

The updated [Certificate](https://platform.openai.com/docs/api-reference/certificates/object) object.

##### examples

###### request

####### curl

curl -X POST https://api.openai.com/v1/organization/certificates/cert_abc \
-H "Authorization: Bearer $OPENAI_ADMIN_KEY" \
-H "Content-Type: application/json" \
-d '{
  "name": "Renamed Certificate"
}'


###### response

{
  "object": "certificate",
  "id": "cert_abc",
  "name": "Renamed Certificate",
  "created_at": 1234567,
  "certificate_details": {
    "valid_at": 12345667,
    "expires_at": 12345678
  }
}


#### description

Modify a certificate. Note that only the name can be modified.


### delete

#### summary

Delete certificate

#### operationId

deleteCertificate

#### tags

- Certificates

#### responses

##### 200

###### description

Certificate deleted successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/DeleteCertificateResponse

#### x-oaiMeta

##### name

Delete certificate

##### group

administration

##### returns

A confirmation object indicating the certificate was deleted.

##### examples

###### request

####### curl

curl -X DELETE https://api.openai.com/v1/organization/certificates/cert_abc \
-H "Authorization: Bearer $OPENAI_ADMIN_KEY"


###### response

{
  "object": "certificate.deleted",
  "id": "cert_abc"
}


#### description

Delete a certificate from the organization.

The certificate must be inactive for the organization and all projects.


## /organization/costs

### get

#### summary

Costs

#### operationId

usage-costs

#### tags

- Usage

#### parameters

##### name

start_time

##### in

query

##### description

Start time (Unix seconds) of the query time range, inclusive.

##### required

true

##### schema

###### type

integer

##### name

end_time

##### in

query

##### description

End time (Unix seconds) of the query time range, exclusive.

##### required

false

##### schema

###### type

integer

##### name

bucket_width

##### in

query

##### description

Width of each time bucket in response. Currently only `1d` is supported, default to `1d`.

##### required

false

##### schema

###### type

string

###### enum

- 1d

###### default

1d

##### name

project_ids

##### in

query

##### description

Return only costs for these projects.

##### required

false

##### schema

###### type

array

###### items

####### type

string

##### name

group_by

##### in

query

##### description

Group the costs by the specified fields. Support fields include `project_id`, `line_item` and any combination of them.

##### required

false

##### schema

###### type

array

###### items

####### type

string

####### enum

- project_id
- line_item

##### name

limit

##### in

query

##### description

A limit on the number of buckets to be returned. Limit can range between 1 and 180, and the default is 7.


##### required

false

##### schema

###### type

integer

###### default

7

##### name

page

##### in

query

##### description

A cursor for use in pagination. Corresponding to the `next_page` field from the previous response.

##### schema

###### type

string


#### responses

##### 200

###### description

Costs data retrieved successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/UsageResponse

#### x-oaiMeta

##### name

Costs

##### group

usage-costs

##### returns

A list of paginated, time bucketed [Costs](https://platform.openai.com/docs/api-reference/usage/costs_object) objects.

##### examples

###### response

{
    "object": "page",
    "data": [
        {
            "object": "bucket",
            "start_time": 1730419200,
            "end_time": 1730505600,
            "results": [
                {
                    "object": "organization.costs.result",
                    "amount": {
                        "value": 0.06,
                        "currency": "usd"
                    },
                    "line_item": null,
                    "project_id": null
                }
            ]
        }
    ],
    "has_more": false,
    "next_page": null
}


###### request

####### curl

curl "https://api.openai.com/v1/organization/costs?start_time=1730419200&limit=1" \
-H "Authorization: Bearer $OPENAI_ADMIN_KEY" \
-H "Content-Type: application/json"


#### description

Get costs details for the organization.

## /organization/invites

### get

#### summary

List invites

#### operationId

list-invites

#### tags

- Invites

#### parameters

##### name

limit

##### in

query

##### description

A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20.


##### required

false

##### schema

###### type

integer

###### default

20

##### name

after

##### in

query

##### description

A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list.


##### required

false

##### schema

###### type

string


#### responses

##### 200

###### description

Invites listed successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/InviteListResponse

#### x-oaiMeta

##### name

List invites

##### group

administration

##### returns

A list of [Invite](https://platform.openai.com/docs/api-reference/invite/object) objects.

##### examples

###### response

{
  "object": "list",
  "data": [
    {
      "object": "organization.invite",
      "id": "invite-abc",
      "email": "user@example.com",
      "role": "owner",
      "status": "accepted",
      "invited_at": 1711471533,
      "expires_at": 1711471533,
      "accepted_at": 1711471533
    }
  ],
  "first_id": "invite-abc",
  "last_id": "invite-abc",
  "has_more": false
}


###### request

####### curl

curl https://api.openai.com/v1/organization/invites?after=invite-abc&limit=20 \
  -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \
  -H "Content-Type: application/json"


#### description

Returns a list of invites in the organization.

### post

#### summary

Create invite

#### operationId

inviteUser

#### tags

- Invites

#### requestBody

##### description

The invite request payload.

##### required

true

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/InviteRequest

#### responses

##### 200

###### description

User invited successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/Invite

#### x-oaiMeta

##### name

Create invite

##### group

administration

##### returns

The created [Invite](https://platform.openai.com/docs/api-reference/invite/object) object.

##### examples

###### response

{
  "object": "organization.invite",
  "id": "invite-def",
  "email": "anotheruser@example.com",
  "role": "reader",
  "status": "pending",
  "invited_at": 1711471533,
  "expires_at": 1711471533,
  "accepted_at": null,
  "projects": [
    {
      "id": "project-xyz",
      "role": "member"
    },
    {
      "id": "project-abc",
      "role": "owner"
    }
  ]
}


###### request

####### curl

curl -X POST https://api.openai.com/v1/organization/invites \
  -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \
  -H "Content-Type: application/json" \
  -d '{
      "email": "anotheruser@example.com",
      "role": "reader",
      "projects": [
        {
          "id": "project-xyz",
          "role": "member"
        },
        {
          "id": "project-abc",
          "role": "owner"
        }
      ]
  }'


#### description

Create an invite for a user to the organization. The invite must be accepted by the user before they have access to the organization.

## /organization/invites/{invite_id}

### get

#### summary

Retrieve invite

#### operationId

retrieve-invite

#### tags

- Invites

#### parameters

##### in

path

##### name

invite_id

##### required

true

##### schema

###### type

string

##### description

The ID of the invite to retrieve.


#### responses

##### 200

###### description

Invite retrieved successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/Invite

#### x-oaiMeta

##### name

Retrieve invite

##### group

administration

##### returns

The [Invite](https://platform.openai.com/docs/api-reference/invite/object) object matching the specified ID.

##### examples

###### response

{
    "object": "organization.invite",
    "id": "invite-abc",
    "email": "user@example.com",
    "role": "owner",
    "status": "accepted",
    "invited_at": 1711471533,
    "expires_at": 1711471533,
    "accepted_at": 1711471533
}


###### request

####### curl

curl https://api.openai.com/v1/organization/invites/invite-abc \
  -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \
  -H "Content-Type: application/json"


#### description

Retrieves an invite.

### delete

#### summary

Delete invite

#### operationId

delete-invite

#### tags

- Invites

#### parameters

##### in

path

##### name

invite_id

##### required

true

##### schema

###### type

string

##### description

The ID of the invite to delete.


#### responses

##### 200

###### description

Invite deleted successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/InviteDeleteResponse

#### x-oaiMeta

##### name

Delete invite

##### group

administration

##### returns

Confirmation that the invite has been deleted

##### examples

###### response

{
    "object": "organization.invite.deleted",
    "id": "invite-abc",
    "deleted": true
}


###### request

####### curl

curl -X DELETE https://api.openai.com/v1/organization/invites/invite-abc \
  -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \
  -H "Content-Type: application/json"


#### description

Delete an invite. If the invite has already been accepted, it cannot be deleted.

## /organization/projects

### get

#### summary

List projects

#### operationId

list-projects

#### tags

- Projects

#### parameters

##### name

limit

##### in

query

##### description

A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20.


##### required

false

##### schema

###### type

integer

###### default

20

##### name

after

##### in

query

##### description

A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list.


##### required

false

##### schema

###### type

string

##### name

include_archived

##### in

query

##### schema

###### type

boolean

###### default

false

##### description

If `true` returns all projects including those that have been `archived`. Archived projects are not included by default.


#### responses

##### 200

###### description

Projects listed successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ProjectListResponse

#### x-oaiMeta

##### name

List projects

##### group

administration

##### returns

A list of [Project](https://platform.openai.com/docs/api-reference/projects/object) objects.

##### examples

###### response

{
    "object": "list",
    "data": [
        {
            "id": "proj_abc",
            "object": "organization.project",
            "name": "Project example",
            "created_at": 1711471533,
            "archived_at": null,
            "status": "active"
        }
    ],
    "first_id": "proj-abc",
    "last_id": "proj-xyz",
    "has_more": false
}


###### request

####### curl

curl https://api.openai.com/v1/organization/projects?after=proj_abc&limit=20&include_archived=false \
  -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \
  -H "Content-Type: application/json"


#### description

Returns a list of projects.

### post

#### summary

Create project

#### operationId

create-project

#### tags

- Projects

#### requestBody

##### description

The project create request payload.

##### required

true

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/ProjectCreateRequest

#### responses

##### 200

###### description

Project created successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/Project

#### x-oaiMeta

##### name

Create project

##### group

administration

##### returns

The created [Project](https://platform.openai.com/docs/api-reference/projects/object) object.

##### examples

###### response

{
    "id": "proj_abc",
    "object": "organization.project",
    "name": "Project ABC",
    "created_at": 1711471533,
    "archived_at": null,
    "status": "active"
}


###### request

####### curl

curl -X POST https://api.openai.com/v1/organization/projects \
  -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \
  -H "Content-Type: application/json" \
  -d '{
      "name": "Project ABC"
  }'


#### description

Create a new project in the organization. Projects can be created and archived, but cannot be deleted.

## /organization/projects/{project_id}

### get

#### summary

Retrieve project

#### operationId

retrieve-project

#### tags

- Projects

#### parameters

##### name

project_id

##### in

path

##### description

The ID of the project.

##### required

true

##### schema

###### type

string


#### responses

##### 200

###### description

Project retrieved successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/Project

#### x-oaiMeta

##### name

Retrieve project

##### group

administration

##### description

Retrieve a project.

##### returns

The [Project](https://platform.openai.com/docs/api-reference/projects/object) object matching the specified ID.

##### examples

###### response

{
    "id": "proj_abc",
    "object": "organization.project",
    "name": "Project example",
    "created_at": 1711471533,
    "archived_at": null,
    "status": "active"
}


###### request

####### curl

curl https://api.openai.com/v1/organization/projects/proj_abc \
  -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \
  -H "Content-Type: application/json"


#### description

Retrieves a project.

### post

#### summary

Modify project

#### operationId

modify-project

#### tags

- Projects

#### parameters

##### name

project_id

##### in

path

##### description

The ID of the project.

##### required

true

##### schema

###### type

string


#### requestBody

##### description

The project update request payload.

##### required

true

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/ProjectUpdateRequest

#### responses

##### 200

###### description

Project updated successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/Project

##### 400

###### description

Error response when updating the default project.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ErrorResponse

#### x-oaiMeta

##### name

Modify project

##### group

administration

##### returns

The updated [Project](https://platform.openai.com/docs/api-reference/projects/object) object.

##### examples

###### response



###### request

####### curl

curl -X POST https://api.openai.com/v1/organization/projects/proj_abc \
  -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \
  -H "Content-Type: application/json" \
  -d '{
      "name": "Project DEF"
  }'


#### description

Modifies a project in the organization.

## /organization/projects/{project_id}/api_keys

### get

#### summary

List project API keys

#### operationId

list-project-api-keys

#### tags

- Projects

#### parameters

##### name

project_id

##### in

path

##### description

The ID of the project.

##### required

true

##### schema

###### type

string

##### name

limit

##### in

query

##### description

A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20.


##### required

false

##### schema

###### type

integer

###### default

20

##### name

after

##### in

query

##### description

A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list.


##### required

false

##### schema

###### type

string


#### responses

##### 200

###### description

Project API keys listed successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ProjectApiKeyListResponse

#### x-oaiMeta

##### name

List project API keys

##### group

administration

##### returns

A list of [ProjectApiKey](https://platform.openai.com/docs/api-reference/project-api-keys/object) objects.

##### examples

###### response

{
    "object": "list",
    "data": [
        {
            "object": "organization.project.api_key",
            "redacted_value": "sk-abc...def",
            "name": "My API Key",
            "created_at": 1711471533,
            "last_used_at": 1711471534,
            "id": "key_abc",
            "owner": {
                "type": "user",
                "user": {
                    "object": "organization.project.user",
                    "id": "user_abc",
                    "name": "First Last",
                    "email": "user@example.com",
                    "role": "owner",
                    "added_at": 1711471533
                }
            }
        }
    ],
    "first_id": "key_abc",
    "last_id": "key_xyz",
    "has_more": false
}


###### request

####### curl

curl https://api.openai.com/v1/organization/projects/proj_abc/api_keys?after=key_abc&limit=20 \
  -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \
  -H "Content-Type: application/json"


#### description

Returns a list of API keys in the project.

## /organization/projects/{project_id}/api_keys/{key_id}

### get

#### summary

Retrieve project API key

#### operationId

retrieve-project-api-key

#### tags

- Projects

#### parameters

##### name

project_id

##### in

path

##### description

The ID of the project.

##### required

true

##### schema

###### type

string

##### name

key_id

##### in

path

##### description

The ID of the API key.

##### required

true

##### schema

###### type

string


#### responses

##### 200

###### description

Project API key retrieved successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ProjectApiKey

#### x-oaiMeta

##### name

Retrieve project API key

##### group

administration

##### returns

The [ProjectApiKey](https://platform.openai.com/docs/api-reference/project-api-keys/object) object matching the specified ID.

##### examples

###### response

{
    "object": "organization.project.api_key",
    "redacted_value": "sk-abc...def",
    "name": "My API Key",
    "created_at": 1711471533,
    "last_used_at": 1711471534,
    "id": "key_abc",
    "owner": {
        "type": "user",
        "user": {
            "object": "organization.project.user",
            "id": "user_abc",
            "name": "First Last",
            "email": "user@example.com",
            "role": "owner",
            "added_at": 1711471533
        }
    }
}


###### request

####### curl

curl https://api.openai.com/v1/organization/projects/proj_abc/api_keys/key_abc \
  -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \
  -H "Content-Type: application/json"


#### description

Retrieves an API key in the project.

### delete

#### summary

Delete project API key

#### operationId

delete-project-api-key

#### tags

- Projects

#### parameters

##### name

project_id

##### in

path

##### description

The ID of the project.

##### required

true

##### schema

###### type

string

##### name

key_id

##### in

path

##### description

The ID of the API key.

##### required

true

##### schema

###### type

string


#### responses

##### 200

###### description

Project API key deleted successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ProjectApiKeyDeleteResponse

##### 400

###### description

Error response for various conditions.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ErrorResponse

#### x-oaiMeta

##### name

Delete project API key

##### group

administration

##### returns

Confirmation of the key's deletion or an error if the key belonged to a service account

##### examples

###### response

{
    "object": "organization.project.api_key.deleted",
    "id": "key_abc",
    "deleted": true
}


###### request

####### curl

curl -X DELETE https://api.openai.com/v1/organization/projects/proj_abc/api_keys/key_abc \
  -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \
  -H "Content-Type: application/json"


#### description

Deletes an API key from the project.

## /organization/projects/{project_id}/archive

### post

#### summary

Archive project

#### operationId

archive-project

#### tags

- Projects

#### parameters

##### name

project_id

##### in

path

##### description

The ID of the project.

##### required

true

##### schema

###### type

string


#### responses

##### 200

###### description

Project archived successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/Project

#### x-oaiMeta

##### name

Archive project

##### group

administration

##### returns

The archived [Project](https://platform.openai.com/docs/api-reference/projects/object) object.

##### examples

###### response

{
    "id": "proj_abc",
    "object": "organization.project",
    "name": "Project DEF",
    "created_at": 1711471533,
    "archived_at": 1711471533,
    "status": "archived"
}


###### request

####### curl

curl -X POST https://api.openai.com/v1/organization/projects/proj_abc/archive \
  -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \
  -H "Content-Type: application/json"


#### description

Archives a project in the organization. Archived projects cannot be used or updated.

## /organization/projects/{project_id}/certificates

### get

#### summary

List project certificates

#### operationId

listProjectCertificates

#### tags

- Certificates

#### parameters

##### name

project_id

##### in

path

##### description

The ID of the project.

##### required

true

##### schema

###### type

string

##### name

limit

##### in

query

##### description

A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20.


##### required

false

##### schema

###### type

integer

###### default

20

##### name

after

##### in

query

##### description

A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list.


##### required

false

##### schema

###### type

string

##### name

order

##### in

query

##### description

Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order.


##### schema

###### type

string

###### default

desc

###### enum

- asc
- desc


#### responses

##### 200

###### description

Certificates listed successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ListCertificatesResponse

#### x-oaiMeta

##### name

List project certificates

##### group

administration

##### returns

A list of [Certificate](https://platform.openai.com/docs/api-reference/certificates/object) objects.

##### examples

###### request

####### curl

curl https://api.openai.com/v1/organization/projects/proj_abc/certificates \
-H "Authorization: Bearer $OPENAI_ADMIN_KEY"


###### response

{
  "object": "list",
  "data": [
    {
      "object": "organization.project.certificate",
      "id": "cert_abc",
      "name": "My Example Certificate",
      "active": true,
      "created_at": 1234567,
      "certificate_details": {
        "valid_at": 12345667,
        "expires_at": 12345678
      }
    },
  ],
  "first_id": "cert_abc",
  "last_id": "cert_abc",
  "has_more": false
}


#### description

List certificates for this project.

## /organization/projects/{project_id}/certificates/activate

### post

#### summary

Activate certificates for project

#### operationId

activateProjectCertificates

#### tags

- Certificates

#### parameters

##### name

project_id

##### in

path

##### description

The ID of the project.

##### required

true

##### schema

###### type

string


#### requestBody

##### description

The certificate activation payload.

##### required

true

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/ToggleCertificatesRequest

#### responses

##### 200

###### description

Certificates activated successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ListCertificatesResponse

#### x-oaiMeta

##### name

Activate certificates for project

##### group

administration

##### returns

A list of [Certificate](https://platform.openai.com/docs/api-reference/certificates/object) objects that were activated.

##### examples

###### request

####### curl

curl https://api.openai.com/v1/organization/projects/proj_abc/certificates/activate \
-H "Authorization: Bearer $OPENAI_ADMIN_KEY" \
-H "Content-Type: application/json" \
-d '{
  "data": ["cert_abc", "cert_def"]
}'


###### response

{
  "object": "organization.project.certificate.activation",
  "data": [
    {
      "object": "organization.project.certificate",
      "id": "cert_abc",
      "name": "My Example Certificate",
      "active": true,
      "created_at": 1234567,
      "certificate_details": {
        "valid_at": 12345667,
        "expires_at": 12345678
      }
    },
    {
      "object": "organization.project.certificate",
      "id": "cert_def",
      "name": "My Example Certificate 2",
      "active": true,
      "created_at": 1234567,
      "certificate_details": {
        "valid_at": 12345667,
        "expires_at": 12345678
      }
    },
  ],
}


#### description

Activate certificates at the project level.

You can atomically and idempotently activate up to 10 certificates at a time.


## /organization/projects/{project_id}/certificates/deactivate

### post

#### summary

Deactivate certificates for project

#### operationId

deactivateProjectCertificates

#### tags

- Certificates

#### parameters

##### name

project_id

##### in

path

##### description

The ID of the project.

##### required

true

##### schema

###### type

string


#### requestBody

##### description

The certificate deactivation payload.

##### required

true

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/ToggleCertificatesRequest

#### responses

##### 200

###### description

Certificates deactivated successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ListCertificatesResponse

#### x-oaiMeta

##### name

Deactivate certificates for project

##### group

administration

##### returns

A list of [Certificate](https://platform.openai.com/docs/api-reference/certificates/object) objects that were deactivated.

##### examples

###### request

####### curl

curl https://api.openai.com/v1/organization/projects/proj_abc/certificates/deactivate \
-H "Authorization: Bearer $OPENAI_ADMIN_KEY" \
-H "Content-Type: application/json" \
-d '{
  "data": ["cert_abc", "cert_def"]
}'


###### response

{
  "object": "organization.project.certificate.deactivation",
  "data": [
    {
      "object": "organization.project.certificate",
      "id": "cert_abc",
      "name": "My Example Certificate",
      "active": false,
      "created_at": 1234567,
      "certificate_details": {
        "valid_at": 12345667,
        "expires_at": 12345678
      }
    },
    {
      "object": "organization.project.certificate",
      "id": "cert_def",
      "name": "My Example Certificate 2",
      "active": false,
      "created_at": 1234567,
      "certificate_details": {
        "valid_at": 12345667,
        "expires_at": 12345678
      }
    },
  ],
}


#### description

Deactivate certificates at the project level. You can atomically and 
idempotently deactivate up to 10 certificates at a time.


## /organization/projects/{project_id}/rate_limits

### get

#### summary

List project rate limits

#### operationId

list-project-rate-limits

#### tags

- Projects

#### parameters

##### name

project_id

##### in

path

##### description

The ID of the project.

##### required

true

##### schema

###### type

string

##### name

limit

##### in

query

##### description

A limit on the number of objects to be returned. The default is 100.


##### required

false

##### schema

###### type

integer

###### default

100

##### name

after

##### in

query

##### description

A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list.


##### required

false

##### schema

###### type

string

##### name

before

##### in

query

##### description

A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, beginning with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list.


##### required

false

##### schema

###### type

string


#### responses

##### 200

###### description

Project rate limits listed successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ProjectRateLimitListResponse

#### x-oaiMeta

##### name

List project rate limits

##### group

administration

##### returns

A list of [ProjectRateLimit](https://platform.openai.com/docs/api-reference/project-rate-limits/object) objects.

##### examples

###### response

{
    "object": "list",
    "data": [
        {
          "object": "project.rate_limit",
          "id": "rl-ada",
          "model": "ada",
          "max_requests_per_1_minute": 600,
          "max_tokens_per_1_minute": 150000,
          "max_images_per_1_minute": 10
        }
    ],
    "first_id": "rl-ada",
    "last_id": "rl-ada",
    "has_more": false
}


###### request

####### curl

curl https://api.openai.com/v1/organization/projects/proj_abc/rate_limits?after=rl_xxx&limit=20 \
  -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \
  -H "Content-Type: application/json"


###### error_response

{
    "code": 404,
    "message": "The project {project_id} was not found"
}


#### description

Returns the rate limits per model for a project.

## /organization/projects/{project_id}/rate_limits/{rate_limit_id}

### post

#### summary

Modify project rate limit

#### operationId

update-project-rate-limits

#### tags

- Projects

#### parameters

##### name

project_id

##### in

path

##### description

The ID of the project.

##### required

true

##### schema

###### type

string

##### name

rate_limit_id

##### in

path

##### description

The ID of the rate limit.

##### required

true

##### schema

###### type

string


#### requestBody

##### description

The project rate limit update request payload.

##### required

true

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/ProjectRateLimitUpdateRequest

#### responses

##### 200

###### description

Project rate limit updated successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ProjectRateLimit

##### 400

###### description

Error response for various conditions.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ErrorResponse

#### x-oaiMeta

##### name

Modify project rate limit

##### group

administration

##### returns

The updated [ProjectRateLimit](https://platform.openai.com/docs/api-reference/project-rate-limits/object) object.

##### examples

###### response

{
    "object": "project.rate_limit",
    "id": "rl-ada",
    "model": "ada",
    "max_requests_per_1_minute": 600,
    "max_tokens_per_1_minute": 150000,
    "max_images_per_1_minute": 10
  }


###### request

####### curl

curl -X POST https://api.openai.com/v1/organization/projects/proj_abc/rate_limits/rl_xxx \
  -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \
  -H "Content-Type: application/json" \
  -d '{
      "max_requests_per_1_minute": 500
  }'


###### error_response

{
    "code": 404,
    "message": "The project {project_id} was not found"
}


#### description

Updates a project rate limit.

## /organization/projects/{project_id}/service_accounts

### get

#### summary

List project service accounts

#### operationId

list-project-service-accounts

#### tags

- Projects

#### parameters

##### name

project_id

##### in

path

##### description

The ID of the project.

##### required

true

##### schema

###### type

string

##### name

limit

##### in

query

##### description

A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20.


##### required

false

##### schema

###### type

integer

###### default

20

##### name

after

##### in

query

##### description

A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list.


##### required

false

##### schema

###### type

string


#### responses

##### 200

###### description

Project service accounts listed successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ProjectServiceAccountListResponse

##### 400

###### description

Error response when project is archived.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ErrorResponse

#### x-oaiMeta

##### name

List project service accounts

##### group

administration

##### returns

A list of [ProjectServiceAccount](https://platform.openai.com/docs/api-reference/project-service-accounts/object) objects.

##### examples

###### response

{
    "object": "list",
    "data": [
        {
            "object": "organization.project.service_account",
            "id": "svc_acct_abc",
            "name": "Service Account",
            "role": "owner",
            "created_at": 1711471533
        }
    ],
    "first_id": "svc_acct_abc",
    "last_id": "svc_acct_xyz",
    "has_more": false
}


###### request

####### curl

curl https://api.openai.com/v1/organization/projects/proj_abc/service_accounts?after=custom_id&limit=20 \
  -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \
  -H "Content-Type: application/json"


#### description

Returns a list of service accounts in the project.

### post

#### summary

Create project service account

#### operationId

create-project-service-account

#### tags

- Projects

#### parameters

##### name

project_id

##### in

path

##### description

The ID of the project.

##### required

true

##### schema

###### type

string


#### requestBody

##### description

The project service account create request payload.

##### required

true

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/ProjectServiceAccountCreateRequest

#### responses

##### 200

###### description

Project service account created successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ProjectServiceAccountCreateResponse

##### 400

###### description

Error response when project is archived.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ErrorResponse

#### x-oaiMeta

##### name

Create project service account

##### group

administration

##### returns

The created [ProjectServiceAccount](https://platform.openai.com/docs/api-reference/project-service-accounts/object) object.

##### examples

###### response

{
    "object": "organization.project.service_account",
    "id": "svc_acct_abc",
    "name": "Production App",
    "role": "member",
    "created_at": 1711471533,
    "api_key": {
        "object": "organization.project.service_account.api_key",
        "value": "sk-abcdefghijklmnop123",
        "name": "Secret Key",
        "created_at": 1711471533,
        "id": "key_abc"
    }
}


###### request

####### curl

curl -X POST https://api.openai.com/v1/organization/projects/proj_abc/service_accounts \
  -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \
  -H "Content-Type: application/json" \
  -d '{
      "name": "Production App"
  }'


#### description

Creates a new service account in the project. This also returns an unredacted API key for the service account.

## /organization/projects/{project_id}/service_accounts/{service_account_id}

### get

#### summary

Retrieve project service account

#### operationId

retrieve-project-service-account

#### tags

- Projects

#### parameters

##### name

project_id

##### in

path

##### description

The ID of the project.

##### required

true

##### schema

###### type

string

##### name

service_account_id

##### in

path

##### description

The ID of the service account.

##### required

true

##### schema

###### type

string


#### responses

##### 200

###### description

Project service account retrieved successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ProjectServiceAccount

#### x-oaiMeta

##### name

Retrieve project service account

##### group

administration

##### returns

The [ProjectServiceAccount](https://platform.openai.com/docs/api-reference/project-service-accounts/object) object matching the specified ID.

##### examples

###### response

{
    "object": "organization.project.service_account",
    "id": "svc_acct_abc",
    "name": "Service Account",
    "role": "owner",
    "created_at": 1711471533
}


###### request

####### curl

curl https://api.openai.com/v1/organization/projects/proj_abc/service_accounts/svc_acct_abc \
  -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \
  -H "Content-Type: application/json"


#### description

Retrieves a service account in the project.

### delete

#### summary

Delete project service account

#### operationId

delete-project-service-account

#### tags

- Projects

#### parameters

##### name

project_id

##### in

path

##### description

The ID of the project.

##### required

true

##### schema

###### type

string

##### name

service_account_id

##### in

path

##### description

The ID of the service account.

##### required

true

##### schema

###### type

string


#### responses

##### 200

###### description

Project service account deleted successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ProjectServiceAccountDeleteResponse

#### x-oaiMeta

##### name

Delete project service account

##### group

administration

##### returns

Confirmation of service account being deleted, or an error in case of an archived project, which has no service accounts

##### examples

###### response

{
    "object": "organization.project.service_account.deleted",
    "id": "svc_acct_abc",
    "deleted": true
}


###### request

####### curl

curl -X DELETE https://api.openai.com/v1/organization/projects/proj_abc/service_accounts/svc_acct_abc \
  -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \
  -H "Content-Type: application/json"


#### description

Deletes a service account from the project.

## /organization/projects/{project_id}/users

### get

#### summary

List project users

#### operationId

list-project-users

#### tags

- Projects

#### parameters

##### name

project_id

##### in

path

##### description

The ID of the project.

##### required

true

##### schema

###### type

string

##### name

limit

##### in

query

##### description

A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20.


##### required

false

##### schema

###### type

integer

###### default

20

##### name

after

##### in

query

##### description

A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list.


##### required

false

##### schema

###### type

string


#### responses

##### 200

###### description

Project users listed successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ProjectUserListResponse

##### 400

###### description

Error response when project is archived.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ErrorResponse

#### x-oaiMeta

##### name

List project users

##### group

administration

##### returns

A list of [ProjectUser](https://platform.openai.com/docs/api-reference/project-users/object) objects.

##### examples

###### response

{
    "object": "list",
    "data": [
        {
            "object": "organization.project.user",
            "id": "user_abc",
            "name": "First Last",
            "email": "user@example.com",
            "role": "owner",
            "added_at": 1711471533
        }
    ],
    "first_id": "user-abc",
    "last_id": "user-xyz",
    "has_more": false
}


###### request

####### curl

curl https://api.openai.com/v1/organization/projects/proj_abc/users?after=user_abc&limit=20 \
  -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \
  -H "Content-Type: application/json"


#### description

Returns a list of users in the project.

### post

#### summary

Create project user

#### operationId

create-project-user

#### parameters

##### name

project_id

##### in

path

##### description

The ID of the project.

##### required

true

##### schema

###### type

string


#### tags

- Projects

#### requestBody

##### description

The project user create request payload.

##### required

true

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/ProjectUserCreateRequest

#### responses

##### 200

###### description

User added to project successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ProjectUser

##### 400

###### description

Error response for various conditions.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ErrorResponse

#### x-oaiMeta

##### name

Create project user

##### group

administration

##### returns

The created [ProjectUser](https://platform.openai.com/docs/api-reference/project-users/object) object.

##### examples

###### response

{
    "object": "organization.project.user",
    "id": "user_abc",
    "email": "user@example.com",
    "role": "owner",
    "added_at": 1711471533
}


###### request

####### curl

curl -X POST https://api.openai.com/v1/organization/projects/proj_abc/users \
  -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \
  -H "Content-Type: application/json" \
  -d '{
      "user_id": "user_abc",
      "role": "member"
  }'


#### description

Adds a user to the project. Users must already be members of the organization to be added to a project.

## /organization/projects/{project_id}/users/{user_id}

### get

#### summary

Retrieve project user

#### operationId

retrieve-project-user

#### tags

- Projects

#### parameters

##### name

project_id

##### in

path

##### description

The ID of the project.

##### required

true

##### schema

###### type

string

##### name

user_id

##### in

path

##### description

The ID of the user.

##### required

true

##### schema

###### type

string


#### responses

##### 200

###### description

Project user retrieved successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ProjectUser

#### x-oaiMeta

##### name

Retrieve project user

##### group

administration

##### returns

The [ProjectUser](https://platform.openai.com/docs/api-reference/project-users/object) object matching the specified ID.

##### examples

###### response

{
    "object": "organization.project.user",
    "id": "user_abc",
    "name": "First Last",
    "email": "user@example.com",
    "role": "owner",
    "added_at": 1711471533
}


###### request

####### curl

curl https://api.openai.com/v1/organization/projects/proj_abc/users/user_abc \
  -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \
  -H "Content-Type: application/json"


#### description

Retrieves a user in the project.

### post

#### summary

Modify project user

#### operationId

modify-project-user

#### tags

- Projects

#### parameters

##### name

project_id

##### in

path

##### description

The ID of the project.

##### required

true

##### schema

###### type

string

##### name

user_id

##### in

path

##### description

The ID of the user.

##### required

true

##### schema

###### type

string


#### requestBody

##### description

The project user update request payload.

##### required

true

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/ProjectUserUpdateRequest

#### responses

##### 200

###### description

Project user's role updated successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ProjectUser

##### 400

###### description

Error response for various conditions.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ErrorResponse

#### x-oaiMeta

##### name

Modify project user

##### group

administration

##### returns

The updated [ProjectUser](https://platform.openai.com/docs/api-reference/project-users/object) object.

##### examples

###### response

{
    "object": "organization.project.user",
    "id": "user_abc",
    "name": "First Last",
    "email": "user@example.com",
    "role": "owner",
    "added_at": 1711471533
}


###### request

####### curl

curl -X POST https://api.openai.com/v1/organization/projects/proj_abc/users/user_abc \
  -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \
  -H "Content-Type: application/json" \
  -d '{
      "role": "owner"
  }'


#### description

Modifies a user's role in the project.

### delete

#### summary

Delete project user

#### operationId

delete-project-user

#### tags

- Projects

#### parameters

##### name

project_id

##### in

path

##### description

The ID of the project.

##### required

true

##### schema

###### type

string

##### name

user_id

##### in

path

##### description

The ID of the user.

##### required

true

##### schema

###### type

string


#### responses

##### 200

###### description

Project user deleted successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ProjectUserDeleteResponse

##### 400

###### description

Error response for various conditions.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ErrorResponse

#### x-oaiMeta

##### name

Delete project user

##### group

administration

##### returns

Confirmation that project has been deleted or an error in case of an archived project, which has no users

##### examples

###### response

{
    "object": "organization.project.user.deleted",
    "id": "user_abc",
    "deleted": true
}


###### request

####### curl

curl -X DELETE https://api.openai.com/v1/organization/projects/proj_abc/users/user_abc \
  -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \
  -H "Content-Type: application/json"


#### description

Deletes a user from the project.

## /organization/usage/audio_speeches

### get

#### summary

Audio speeches

#### operationId

usage-audio-speeches

#### tags

- Usage

#### parameters

##### name

start_time

##### in

query

##### description

Start time (Unix seconds) of the query time range, inclusive.

##### required

true

##### schema

###### type

integer

##### name

end_time

##### in

query

##### description

End time (Unix seconds) of the query time range, exclusive.

##### required

false

##### schema

###### type

integer

##### name

bucket_width

##### in

query

##### description

Width of each time bucket in response. Currently `1m`, `1h` and `1d` are supported, default to `1d`.

##### required

false

##### schema

###### type

string

###### enum

- 1m
- 1h
- 1d

###### default

1d

##### name

project_ids

##### in

query

##### description

Return only usage for these projects.

##### required

false

##### schema

###### type

array

###### items

####### type

string

##### name

user_ids

##### in

query

##### description

Return only usage for these users.

##### required

false

##### schema

###### type

array

###### items

####### type

string

##### name

api_key_ids

##### in

query

##### description

Return only usage for these API keys.

##### required

false

##### schema

###### type

array

###### items

####### type

string

##### name

models

##### in

query

##### description

Return only usage for these models.

##### required

false

##### schema

###### type

array

###### items

####### type

string

##### name

group_by

##### in

query

##### description

Group the usage data by the specified fields. Support fields include `project_id`, `user_id`, `api_key_id`, `model` or any combination of them.

##### required

false

##### schema

###### type

array

###### items

####### type

string

####### enum

- project_id
- user_id
- api_key_id
- model

##### name

limit

##### in

query

##### description

Specifies the number of buckets to return.
- `bucket_width=1d`: default: 7, max: 31
- `bucket_width=1h`: default: 24, max: 168
- `bucket_width=1m`: default: 60, max: 1440


##### required

false

##### schema

###### type

integer

##### name

page

##### in

query

##### description

A cursor for use in pagination. Corresponding to the `next_page` field from the previous response.

##### schema

###### type

string


#### responses

##### 200

###### description

Usage data retrieved successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/UsageResponse

#### x-oaiMeta

##### name

Audio speeches

##### group

usage-audio-speeches

##### returns

A list of paginated, time bucketed [Audio speeches usage](https://platform.openai.com/docs/api-reference/usage/audio_speeches_object) objects.

##### examples

###### response

{
    "object": "page",
    "data": [
        {
            "object": "bucket",
            "start_time": 1730419200,
            "end_time": 1730505600,
            "results": [
                {
                    "object": "organization.usage.audio_speeches.result",
                    "characters": 45,
                    "num_model_requests": 1,
                    "project_id": null,
                    "user_id": null,
                    "api_key_id": null,
                    "model": null
                }
            ]
        }
    ],
    "has_more": false,
    "next_page": null
}


###### request

####### curl

curl "https://api.openai.com/v1/organization/usage/audio_speeches?start_time=1730419200&limit=1" \
-H "Authorization: Bearer $OPENAI_ADMIN_KEY" \
-H "Content-Type: application/json"


#### description

Get audio speeches usage details for the organization.

## /organization/usage/audio_transcriptions

### get

#### summary

Audio transcriptions

#### operationId

usage-audio-transcriptions

#### tags

- Usage

#### parameters

##### name

start_time

##### in

query

##### description

Start time (Unix seconds) of the query time range, inclusive.

##### required

true

##### schema

###### type

integer

##### name

end_time

##### in

query

##### description

End time (Unix seconds) of the query time range, exclusive.

##### required

false

##### schema

###### type

integer

##### name

bucket_width

##### in

query

##### description

Width of each time bucket in response. Currently `1m`, `1h` and `1d` are supported, default to `1d`.

##### required

false

##### schema

###### type

string

###### enum

- 1m
- 1h
- 1d

###### default

1d

##### name

project_ids

##### in

query

##### description

Return only usage for these projects.

##### required

false

##### schema

###### type

array

###### items

####### type

string

##### name

user_ids

##### in

query

##### description

Return only usage for these users.

##### required

false

##### schema

###### type

array

###### items

####### type

string

##### name

api_key_ids

##### in

query

##### description

Return only usage for these API keys.

##### required

false

##### schema

###### type

array

###### items

####### type

string

##### name

models

##### in

query

##### description

Return only usage for these models.

##### required

false

##### schema

###### type

array

###### items

####### type

string

##### name

group_by

##### in

query

##### description

Group the usage data by the specified fields. Support fields include `project_id`, `user_id`, `api_key_id`, `model` or any combination of them.

##### required

false

##### schema

###### type

array

###### items

####### type

string

####### enum

- project_id
- user_id
- api_key_id
- model

##### name

limit

##### in

query

##### description

Specifies the number of buckets to return.
- `bucket_width=1d`: default: 7, max: 31
- `bucket_width=1h`: default: 24, max: 168
- `bucket_width=1m`: default: 60, max: 1440


##### required

false

##### schema

###### type

integer

##### name

page

##### in

query

##### description

A cursor for use in pagination. Corresponding to the `next_page` field from the previous response.

##### schema

###### type

string


#### responses

##### 200

###### description

Usage data retrieved successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/UsageResponse

#### x-oaiMeta

##### name

Audio transcriptions

##### group

usage-audio-transcriptions

##### returns

A list of paginated, time bucketed [Audio transcriptions usage](https://platform.openai.com/docs/api-reference/usage/audio_transcriptions_object) objects.

##### examples

###### response

{
    "object": "page",
    "data": [
        {
            "object": "bucket",
            "start_time": 1730419200,
            "end_time": 1730505600,
            "results": [
                {
                    "object": "organization.usage.audio_transcriptions.result",
                    "seconds": 20,
                    "num_model_requests": 1,
                    "project_id": null,
                    "user_id": null,
                    "api_key_id": null,
                    "model": null
                }
            ]
        }
    ],
    "has_more": false,
    "next_page": null
}


###### request

####### curl

curl "https://api.openai.com/v1/organization/usage/audio_transcriptions?start_time=1730419200&limit=1" \
-H "Authorization: Bearer $OPENAI_ADMIN_KEY" \
-H "Content-Type: application/json"


#### description

Get audio transcriptions usage details for the organization.

## /organization/usage/code_interpreter_sessions

### get

#### summary

Code interpreter sessions

#### operationId

usage-code-interpreter-sessions

#### tags

- Usage

#### parameters

##### name

start_time

##### in

query

##### description

Start time (Unix seconds) of the query time range, inclusive.

##### required

true

##### schema

###### type

integer

##### name

end_time

##### in

query

##### description

End time (Unix seconds) of the query time range, exclusive.

##### required

false

##### schema

###### type

integer

##### name

bucket_width

##### in

query

##### description

Width of each time bucket in response. Currently `1m`, `1h` and `1d` are supported, default to `1d`.

##### required

false

##### schema

###### type

string

###### enum

- 1m
- 1h
- 1d

###### default

1d

##### name

project_ids

##### in

query

##### description

Return only usage for these projects.

##### required

false

##### schema

###### type

array

###### items

####### type

string

##### name

group_by

##### in

query

##### description

Group the usage data by the specified fields. Support fields include `project_id`.

##### required

false

##### schema

###### type

array

###### items

####### type

string

####### enum

- project_id

##### name

limit

##### in

query

##### description

Specifies the number of buckets to return.
- `bucket_width=1d`: default: 7, max: 31
- `bucket_width=1h`: default: 24, max: 168
- `bucket_width=1m`: default: 60, max: 1440


##### required

false

##### schema

###### type

integer

##### name

page

##### in

query

##### description

A cursor for use in pagination. Corresponding to the `next_page` field from the previous response.

##### schema

###### type

string


#### responses

##### 200

###### description

Usage data retrieved successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/UsageResponse

#### x-oaiMeta

##### name

Code interpreter sessions

##### group

usage-code-interpreter-sessions

##### returns

A list of paginated, time bucketed [Code interpreter sessions usage](https://platform.openai.com/docs/api-reference/usage/code_interpreter_sessions_object) objects.

##### examples

###### response

{
    "object": "page",
    "data": [
        {
            "object": "bucket",
            "start_time": 1730419200,
            "end_time": 1730505600,
            "results": [
                {
                    "object": "organization.usage.code_interpreter_sessions.result",
                    "num_sessions": 1,
                    "project_id": null
                }
            ]
        }
    ],
    "has_more": false,
    "next_page": null
}


###### request

####### curl

curl "https://api.openai.com/v1/organization/usage/code_interpreter_sessions?start_time=1730419200&limit=1" \
-H "Authorization: Bearer $OPENAI_ADMIN_KEY" \
-H "Content-Type: application/json"


#### description

Get code interpreter sessions usage details for the organization.

## /organization/usage/completions

### get

#### summary

Completions

#### operationId

usage-completions

#### tags

- Usage

#### parameters

##### name

start_time

##### in

query

##### description

Start time (Unix seconds) of the query time range, inclusive.

##### required

true

##### schema

###### type

integer

##### name

end_time

##### in

query

##### description

End time (Unix seconds) of the query time range, exclusive.

##### required

false

##### schema

###### type

integer

##### name

bucket_width

##### in

query

##### description

Width of each time bucket in response. Currently `1m`, `1h` and `1d` are supported, default to `1d`.

##### required

false

##### schema

###### type

string

###### enum

- 1m
- 1h
- 1d

###### default

1d

##### name

project_ids

##### in

query

##### description

Return only usage for these projects.

##### required

false

##### schema

###### type

array

###### items

####### type

string

##### name

user_ids

##### in

query

##### description

Return only usage for these users.

##### required

false

##### schema

###### type

array

###### items

####### type

string

##### name

api_key_ids

##### in

query

##### description

Return only usage for these API keys.

##### required

false

##### schema

###### type

array

###### items

####### type

string

##### name

models

##### in

query

##### description

Return only usage for these models.

##### required

false

##### schema

###### type

array

###### items

####### type

string

##### name

batch

##### in

query

##### description

If `true`, return batch jobs only. If `false`, return non-batch jobs only. By default, return both.


##### required

false

##### schema

###### type

boolean

##### name

group_by

##### in

query

##### description

Group the usage data by the specified fields. Support fields include `project_id`, `user_id`, `api_key_id`, `model`, `batch` or any combination of them.

##### required

false

##### schema

###### type

array

###### items

####### type

string

####### enum

- project_id
- user_id
- api_key_id
- model
- batch

##### name

limit

##### in

query

##### description

Specifies the number of buckets to return.
- `bucket_width=1d`: default: 7, max: 31
- `bucket_width=1h`: default: 24, max: 168
- `bucket_width=1m`: default: 60, max: 1440


##### required

false

##### schema

###### type

integer

##### name

page

##### in

query

##### description

A cursor for use in pagination. Corresponding to the `next_page` field from the previous response.

##### schema

###### type

string


#### responses

##### 200

###### description

Usage data retrieved successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/UsageResponse

#### x-oaiMeta

##### name

Completions

##### group

usage-completions

##### returns

A list of paginated, time bucketed [Completions usage](https://platform.openai.com/docs/api-reference/usage/completions_object) objects.

##### examples

###### response

{
    "object": "page",
    "data": [
        {
            "object": "bucket",
            "start_time": 1730419200,
            "end_time": 1730505600,
            "results": [
                {
                    "object": "organization.usage.completions.result",
                    "input_tokens": 1000,
                    "output_tokens": 500,
                    "input_cached_tokens": 800,
                    "input_audio_tokens": 0,
                    "output_audio_tokens": 0,
                    "num_model_requests": 5,
                    "project_id": null,
                    "user_id": null,
                    "api_key_id": null,
                    "model": null,
                    "batch": null
                }
            ]
        }
    ],
    "has_more": true,
    "next_page": "page_AAAAAGdGxdEiJdKOAAAAAGcqsYA="
}


###### request

####### curl

curl "https://api.openai.com/v1/organization/usage/completions?start_time=1730419200&limit=1" \
-H "Authorization: Bearer $OPENAI_ADMIN_KEY" \
-H "Content-Type: application/json"


#### description

Get completions usage details for the organization.

## /organization/usage/embeddings

### get

#### summary

Embeddings

#### operationId

usage-embeddings

#### tags

- Usage

#### parameters

##### name

start_time

##### in

query

##### description

Start time (Unix seconds) of the query time range, inclusive.

##### required

true

##### schema

###### type

integer

##### name

end_time

##### in

query

##### description

End time (Unix seconds) of the query time range, exclusive.

##### required

false

##### schema

###### type

integer

##### name

bucket_width

##### in

query

##### description

Width of each time bucket in response. Currently `1m`, `1h` and `1d` are supported, default to `1d`.

##### required

false

##### schema

###### type

string

###### enum

- 1m
- 1h
- 1d

###### default

1d

##### name

project_ids

##### in

query

##### description

Return only usage for these projects.

##### required

false

##### schema

###### type

array

###### items

####### type

string

##### name

user_ids

##### in

query

##### description

Return only usage for these users.

##### required

false

##### schema

###### type

array

###### items

####### type

string

##### name

api_key_ids

##### in

query

##### description

Return only usage for these API keys.

##### required

false

##### schema

###### type

array

###### items

####### type

string

##### name

models

##### in

query

##### description

Return only usage for these models.

##### required

false

##### schema

###### type

array

###### items

####### type

string

##### name

group_by

##### in

query

##### description

Group the usage data by the specified fields. Support fields include `project_id`, `user_id`, `api_key_id`, `model` or any combination of them.

##### required

false

##### schema

###### type

array

###### items

####### type

string

####### enum

- project_id
- user_id
- api_key_id
- model

##### name

limit

##### in

query

##### description

Specifies the number of buckets to return.
- `bucket_width=1d`: default: 7, max: 31
- `bucket_width=1h`: default: 24, max: 168
- `bucket_width=1m`: default: 60, max: 1440


##### required

false

##### schema

###### type

integer

##### name

page

##### in

query

##### description

A cursor for use in pagination. Corresponding to the `next_page` field from the previous response.

##### schema

###### type

string


#### responses

##### 200

###### description

Usage data retrieved successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/UsageResponse

#### x-oaiMeta

##### name

Embeddings

##### group

usage-embeddings

##### returns

A list of paginated, time bucketed [Embeddings usage](https://platform.openai.com/docs/api-reference/usage/embeddings_object) objects.

##### examples

###### response

{
    "object": "page",
    "data": [
        {
            "object": "bucket",
            "start_time": 1730419200,
            "end_time": 1730505600,
            "results": [
                {
                    "object": "organization.usage.embeddings.result",
                    "input_tokens": 16,
                    "num_model_requests": 2,
                    "project_id": null,
                    "user_id": null,
                    "api_key_id": null,
                    "model": null
                }
            ]
        }
    ],
    "has_more": false,
    "next_page": null
}


###### request

####### curl

curl "https://api.openai.com/v1/organization/usage/embeddings?start_time=1730419200&limit=1" \
-H "Authorization: Bearer $OPENAI_ADMIN_KEY" \
-H "Content-Type: application/json"


#### description

Get embeddings usage details for the organization.

## /organization/usage/images

### get

#### summary

Images

#### operationId

usage-images

#### tags

- Usage

#### parameters

##### name

start_time

##### in

query

##### description

Start time (Unix seconds) of the query time range, inclusive.

##### required

true

##### schema

###### type

integer

##### name

end_time

##### in

query

##### description

End time (Unix seconds) of the query time range, exclusive.

##### required

false

##### schema

###### type

integer

##### name

bucket_width

##### in

query

##### description

Width of each time bucket in response. Currently `1m`, `1h` and `1d` are supported, default to `1d`.

##### required

false

##### schema

###### type

string

###### enum

- 1m
- 1h
- 1d

###### default

1d

##### name

sources

##### in

query

##### description

Return only usages for these sources. Possible values are `image.generation`, `image.edit`, `image.variation` or any combination of them.

##### required

false

##### schema

###### type

array

###### items

####### type

string

####### enum

- image.generation
- image.edit
- image.variation

##### name

sizes

##### in

query

##### description

Return only usages for these image sizes. Possible values are `256x256`, `512x512`, `1024x1024`, `1792x1792`, `1024x1792` or any combination of them.

##### required

false

##### schema

###### type

array

###### items

####### type

string

####### enum

- 256x256
- 512x512
- 1024x1024
- 1792x1792
- 1024x1792

##### name

project_ids

##### in

query

##### description

Return only usage for these projects.

##### required

false

##### schema

###### type

array

###### items

####### type

string

##### name

user_ids

##### in

query

##### description

Return only usage for these users.

##### required

false

##### schema

###### type

array

###### items

####### type

string

##### name

api_key_ids

##### in

query

##### description

Return only usage for these API keys.

##### required

false

##### schema

###### type

array

###### items

####### type

string

##### name

models

##### in

query

##### description

Return only usage for these models.

##### required

false

##### schema

###### type

array

###### items

####### type

string

##### name

group_by

##### in

query

##### description

Group the usage data by the specified fields. Support fields include `project_id`, `user_id`, `api_key_id`, `model`, `size`, `source` or any combination of them.

##### required

false

##### schema

###### type

array

###### items

####### type

string

####### enum

- project_id
- user_id
- api_key_id
- model
- size
- source

##### name

limit

##### in

query

##### description

Specifies the number of buckets to return.
- `bucket_width=1d`: default: 7, max: 31
- `bucket_width=1h`: default: 24, max: 168
- `bucket_width=1m`: default: 60, max: 1440


##### required

false

##### schema

###### type

integer

##### name

page

##### in

query

##### description

A cursor for use in pagination. Corresponding to the `next_page` field from the previous response.

##### schema

###### type

string


#### responses

##### 200

###### description

Usage data retrieved successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/UsageResponse

#### x-oaiMeta

##### name

Images

##### group

usage-images

##### returns

A list of paginated, time bucketed [Images usage](https://platform.openai.com/docs/api-reference/usage/images_object) objects.

##### examples

###### response

{
    "object": "page",
    "data": [
        {
            "object": "bucket",
            "start_time": 1730419200,
            "end_time": 1730505600,
            "results": [
                {
                    "object": "organization.usage.images.result",
                    "images": 2,
                    "num_model_requests": 2,
                    "size": null,
                    "source": null,
                    "project_id": null,
                    "user_id": null,
                    "api_key_id": null,
                    "model": null
                }
            ]
        }
    ],
    "has_more": false,
    "next_page": null
}


###### request

####### curl

curl "https://api.openai.com/v1/organization/usage/images?start_time=1730419200&limit=1" \
-H "Authorization: Bearer $OPENAI_ADMIN_KEY" \
-H "Content-Type: application/json"


#### description

Get images usage details for the organization.

## /organization/usage/moderations

### get

#### summary

Moderations

#### operationId

usage-moderations

#### tags

- Usage

#### parameters

##### name

start_time

##### in

query

##### description

Start time (Unix seconds) of the query time range, inclusive.

##### required

true

##### schema

###### type

integer

##### name

end_time

##### in

query

##### description

End time (Unix seconds) of the query time range, exclusive.

##### required

false

##### schema

###### type

integer

##### name

bucket_width

##### in

query

##### description

Width of each time bucket in response. Currently `1m`, `1h` and `1d` are supported, default to `1d`.

##### required

false

##### schema

###### type

string

###### enum

- 1m
- 1h
- 1d

###### default

1d

##### name

project_ids

##### in

query

##### description

Return only usage for these projects.

##### required

false

##### schema

###### type

array

###### items

####### type

string

##### name

user_ids

##### in

query

##### description

Return only usage for these users.

##### required

false

##### schema

###### type

array

###### items

####### type

string

##### name

api_key_ids

##### in

query

##### description

Return only usage for these API keys.

##### required

false

##### schema

###### type

array

###### items

####### type

string

##### name

models

##### in

query

##### description

Return only usage for these models.

##### required

false

##### schema

###### type

array

###### items

####### type

string

##### name

group_by

##### in

query

##### description

Group the usage data by the specified fields. Support fields include `project_id`, `user_id`, `api_key_id`, `model` or any combination of them.

##### required

false

##### schema

###### type

array

###### items

####### type

string

####### enum

- project_id
- user_id
- api_key_id
- model

##### name

limit

##### in

query

##### description

Specifies the number of buckets to return.
- `bucket_width=1d`: default: 7, max: 31
- `bucket_width=1h`: default: 24, max: 168
- `bucket_width=1m`: default: 60, max: 1440


##### required

false

##### schema

###### type

integer

##### name

page

##### in

query

##### description

A cursor for use in pagination. Corresponding to the `next_page` field from the previous response.

##### schema

###### type

string


#### responses

##### 200

###### description

Usage data retrieved successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/UsageResponse

#### x-oaiMeta

##### name

Moderations

##### group

usage-moderations

##### returns

A list of paginated, time bucketed [Moderations usage](https://platform.openai.com/docs/api-reference/usage/moderations_object) objects.

##### examples

###### response

{
    "object": "page",
    "data": [
        {
            "object": "bucket",
            "start_time": 1730419200,
            "end_time": 1730505600,
            "results": [
                {
                    "object": "organization.usage.moderations.result",
                    "input_tokens": 16,
                    "num_model_requests": 2,
                    "project_id": null,
                    "user_id": null,
                    "api_key_id": null,
                    "model": null
                }
            ]
        }
    ],
    "has_more": false,
    "next_page": null
}


###### request

####### curl

curl "https://api.openai.com/v1/organization/usage/moderations?start_time=1730419200&limit=1" \
-H "Authorization: Bearer $OPENAI_ADMIN_KEY" \
-H "Content-Type: application/json"


#### description

Get moderations usage details for the organization.

## /organization/usage/vector_stores

### get

#### summary

Vector stores

#### operationId

usage-vector-stores

#### tags

- Usage

#### parameters

##### name

start_time

##### in

query

##### description

Start time (Unix seconds) of the query time range, inclusive.

##### required

true

##### schema

###### type

integer

##### name

end_time

##### in

query

##### description

End time (Unix seconds) of the query time range, exclusive.

##### required

false

##### schema

###### type

integer

##### name

bucket_width

##### in

query

##### description

Width of each time bucket in response. Currently `1m`, `1h` and `1d` are supported, default to `1d`.

##### required

false

##### schema

###### type

string

###### enum

- 1m
- 1h
- 1d

###### default

1d

##### name

project_ids

##### in

query

##### description

Return only usage for these projects.

##### required

false

##### schema

###### type

array

###### items

####### type

string

##### name

group_by

##### in

query

##### description

Group the usage data by the specified fields. Support fields include `project_id`.

##### required

false

##### schema

###### type

array

###### items

####### type

string

####### enum

- project_id

##### name

limit

##### in

query

##### description

Specifies the number of buckets to return.
- `bucket_width=1d`: default: 7, max: 31
- `bucket_width=1h`: default: 24, max: 168
- `bucket_width=1m`: default: 60, max: 1440


##### required

false

##### schema

###### type

integer

##### name

page

##### in

query

##### description

A cursor for use in pagination. Corresponding to the `next_page` field from the previous response.

##### schema

###### type

string


#### responses

##### 200

###### description

Usage data retrieved successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/UsageResponse

#### x-oaiMeta

##### name

Vector stores

##### group

usage-vector-stores

##### returns

A list of paginated, time bucketed [Vector stores usage](https://platform.openai.com/docs/api-reference/usage/vector_stores_object) objects.

##### examples

###### response

{
    "object": "page",
    "data": [
        {
            "object": "bucket",
            "start_time": 1730419200,
            "end_time": 1730505600,
            "results": [
                {
                    "object": "organization.usage.vector_stores.result",
                    "usage_bytes": 1024,
                    "project_id": null
                }
            ]
        }
    ],
    "has_more": false,
    "next_page": null
}


###### request

####### curl

curl "https://api.openai.com/v1/organization/usage/vector_stores?start_time=1730419200&limit=1" \
-H "Authorization: Bearer $OPENAI_ADMIN_KEY" \
-H "Content-Type: application/json"


#### description

Get vector stores usage details for the organization.

## /organization/users

### get

#### summary

List users

#### operationId

list-users

#### tags

- Users

#### parameters

##### name

limit

##### in

query

##### description

A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20.


##### required

false

##### schema

###### type

integer

###### default

20

##### name

after

##### in

query

##### description

A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list.


##### required

false

##### schema

###### type

string

##### name

emails

##### in

query

##### description

Filter by the email address of users.

##### required

false

##### schema

###### type

array

###### items

####### type

string


#### responses

##### 200

###### description

Users listed successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/UserListResponse

#### x-oaiMeta

##### name

List users

##### group

administration

##### returns

A list of [User](https://platform.openai.com/docs/api-reference/users/object) objects.

##### examples

###### response

{
    "object": "list",
    "data": [
        {
            "object": "organization.user",
            "id": "user_abc",
            "name": "First Last",
            "email": "user@example.com",
            "role": "owner",
            "added_at": 1711471533
        }
    ],
    "first_id": "user-abc",
    "last_id": "user-xyz",
    "has_more": false
}


###### request

####### curl

curl https://api.openai.com/v1/organization/users?after=user_abc&limit=20 \
  -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \
  -H "Content-Type: application/json"


#### description

Lists all of the users in the organization.

## /organization/users/{user_id}

### get

#### summary

Retrieve user

#### operationId

retrieve-user

#### tags

- Users

#### parameters

##### name

user_id

##### in

path

##### description

The ID of the user.

##### required

true

##### schema

###### type

string


#### responses

##### 200

###### description

User retrieved successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/User

#### x-oaiMeta

##### name

Retrieve user

##### group

administration

##### returns

The [User](https://platform.openai.com/docs/api-reference/users/object) object matching the specified ID.

##### examples

###### response

{
    "object": "organization.user",
    "id": "user_abc",
    "name": "First Last",
    "email": "user@example.com",
    "role": "owner",
    "added_at": 1711471533
}


###### request

####### curl

curl https://api.openai.com/v1/organization/users/user_abc \
  -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \
  -H "Content-Type: application/json"


#### description

Retrieves a user by their identifier.

### post

#### summary

Modify user

#### operationId

modify-user

#### tags

- Users

#### parameters

##### name

user_id

##### in

path

##### description

The ID of the user.

##### required

true

##### schema

###### type

string


#### requestBody

##### description

The new user role to modify. This must be one of `owner` or `member`.

##### required

true

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/UserRoleUpdateRequest

#### responses

##### 200

###### description

User role updated successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/User

#### x-oaiMeta

##### name

Modify user

##### group

administration

##### returns

The updated [User](https://platform.openai.com/docs/api-reference/users/object) object.

##### examples

###### response

{
    "object": "organization.user",
    "id": "user_abc",
    "name": "First Last",
    "email": "user@example.com",
    "role": "owner",
    "added_at": 1711471533
}


###### request

####### curl

curl -X POST https://api.openai.com/v1/organization/users/user_abc \
  -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \
  -H "Content-Type: application/json" \
  -d '{
      "role": "owner"
  }'


#### description

Modifies a user's role in the organization.

### delete

#### summary

Delete user

#### operationId

delete-user

#### tags

- Users

#### parameters

##### name

user_id

##### in

path

##### description

The ID of the user.

##### required

true

##### schema

###### type

string


#### responses

##### 200

###### description

User deleted successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/UserDeleteResponse

#### x-oaiMeta

##### name

Delete user

##### group

administration

##### returns

Confirmation of the deleted user

##### examples

###### response

{
    "object": "organization.user.deleted",
    "id": "user_abc",
    "deleted": true
}


###### request

####### curl

curl -X DELETE https://api.openai.com/v1/organization/users/user_abc \
  -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \
  -H "Content-Type: application/json"


#### description

Deletes a user from the organization.

## /realtime/sessions

### post

#### summary

Create session

#### operationId

create-realtime-session

#### tags

- Realtime

#### requestBody

##### description

Create an ephemeral API key with the given session configuration.

##### required

true

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/RealtimeSessionCreateRequest

#### responses

##### 200

###### description

Session created successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/RealtimeSessionCreateResponse

#### x-oaiMeta

##### name

Create session

##### group

realtime

##### returns

The created Realtime session object, plus an ephemeral key

##### examples

###### response

{
  "id": "sess_001",
  "object": "realtime.session",
  "model": "gpt-4o-realtime-preview",
  "modalities": ["audio", "text"],
  "instructions": "You are a friendly assistant.",
  "voice": "alloy",
  "input_audio_format": "pcm16",
  "output_audio_format": "pcm16",
  "input_audio_transcription": {
      "model": "whisper-1"
  },
  "turn_detection": null,
  "tools": [],
  "tool_choice": "none",
  "temperature": 0.7,
  "max_response_output_tokens": 200,
  "speed": 1.1,
  "tracing": "auto",
  "client_secret": {
    "value": "ek_abc123", 
    "expires_at": 1234567890
  }
}


###### request

####### curl

curl -X POST https://api.openai.com/v1/realtime/sessions \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4o-realtime-preview",
    "modalities": ["audio", "text"],
    "instructions": "You are a friendly assistant."
  }'


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const session = await client.beta.realtime.sessions.create();

console.log(session.client_secret);

####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
session = client.beta.realtime.sessions.create()
print(session.client_secret)

####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.beta.realtime.sessions.SessionCreateParams;
import com.openai.models.beta.realtime.sessions.SessionCreateResponse;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        SessionCreateResponse session = client.beta().realtime().sessions().create();
    }
}

#### description

Create an ephemeral API token for use in client-side applications with the
Realtime API. Can be configured with the same session parameters as the
`session.update` client event.

It responds with a session object, plus a `client_secret` key which contains
a usable ephemeral API token that can be used to authenticate browser clients
for the Realtime API.


## /realtime/transcription_sessions

### post

#### summary

Create transcription session

#### operationId

create-realtime-transcription-session

#### tags

- Realtime

#### requestBody

##### description

Create an ephemeral API key with the given session configuration.

##### required

true

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/RealtimeTranscriptionSessionCreateRequest

#### responses

##### 200

###### description

Session created successfully.

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/RealtimeTranscriptionSessionCreateResponse

#### x-oaiMeta

##### name

Create transcription session

##### group

realtime

##### returns

The created [Realtime transcription session object](https://platform.openai.com/docs/api-reference/realtime-sessions/transcription_session_object), plus an ephemeral key

##### examples

###### response

{
  "id": "sess_BBwZc7cFV3XizEyKGDCGL",
  "object": "realtime.transcription_session",
  "modalities": ["audio", "text"],
  "turn_detection": {
    "type": "server_vad",
    "threshold": 0.5,
    "prefix_padding_ms": 300,
    "silence_duration_ms": 200
  },
  "input_audio_format": "pcm16",
  "input_audio_transcription": {
    "model": "gpt-4o-transcribe",
    "language": null,
    "prompt": ""
  },
  "client_secret": null
}


###### request

####### curl

curl -X POST https://api.openai.com/v1/realtime/transcription_sessions \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{}'


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const transcriptionSession = await client.beta.realtime.transcriptionSessions.create();

console.log(transcriptionSession.client_secret);

####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
transcription_session = client.beta.realtime.transcription_sessions.create()
print(transcription_session.client_secret)

####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.beta.realtime.transcriptionsessions.TranscriptionSession;
import com.openai.models.beta.realtime.transcriptionsessions.TranscriptionSessionCreateParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        TranscriptionSession transcriptionSession = client.beta().realtime().transcriptionSessions().create();
    }
}

#### description

Create an ephemeral API token for use in client-side applications with the
Realtime API specifically for realtime transcriptions. 
Can be configured with the same session parameters as the `transcription_session.update` client event.

It responds with a session object, plus a `client_secret` key which contains
a usable ephemeral API token that can be used to authenticate browser clients
for the Realtime API.


## /responses

### post

#### operationId

createResponse

#### tags

- Responses

#### summary

Create a model response

#### requestBody

##### required

true

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/CreateResponse

#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/Response

####### text/event-stream

######## schema

######### $ref

#/components/schemas/ResponseStreamEvent

#### x-oaiMeta

##### name

Create a model response

##### group

responses

##### returns

Returns a [Response](https://platform.openai.com/docs/api-reference/responses/object) object.


##### path

create

##### examples

###### title

Text input

###### request

####### curl

curl https://api.openai.com/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "gpt-4.1",
    "input": "Tell me a three sentence bedtime story about a unicorn."
  }'


####### javascript

import OpenAI from "openai";

const openai = new OpenAI();

const response = await openai.responses.create({
    model: "gpt-4.1",
    input: "Tell me a three sentence bedtime story about a unicorn."
});

console.log(response);


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
response = client.responses.create()
print(response.id)

####### csharp

using System;
using OpenAI.Responses;

OpenAIResponseClient client = new(
    model: "gpt-4.1",
    apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY")
);

OpenAIResponse response = client.CreateResponse("Tell me a three sentence bedtime story about a unicorn.");

Console.WriteLine(response.GetOutputText());


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const response = await client.responses.create();

console.log(response.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
  "github.com/openai/openai-go/responses"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  response, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{

  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", response.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        Response response = client.responses().create();
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

response = openai.responses.create

puts(response)

###### response

{
  "id": "resp_67ccd2bed1ec8190b14f964abc0542670bb6a6b452d3795b",
  "object": "response",
  "created_at": 1741476542,
  "status": "completed",
  "error": null,
  "incomplete_details": null,
  "instructions": null,
  "max_output_tokens": null,
  "model": "gpt-4.1-2025-04-14",
  "output": [
    {
      "type": "message",
      "id": "msg_67ccd2bf17f0819081ff3bb2cf6508e60bb6a6b452d3795b",
      "status": "completed",
      "role": "assistant",
      "content": [
        {
          "type": "output_text",
          "text": "In a peaceful grove beneath a silver moon, a unicorn named Lumina discovered a hidden pool that reflected the stars. As she dipped her horn into the water, the pool began to shimmer, revealing a pathway to a magical realm of endless night skies. Filled with wonder, Lumina whispered a wish for all who dream to find their own hidden magic, and as she glanced back, her hoofprints sparkled like stardust.",
          "annotations": []
        }
      ]
    }
  ],
  "parallel_tool_calls": true,
  "previous_response_id": null,
  "reasoning": {
    "effort": null,
    "summary": null
  },
  "store": true,
  "temperature": 1.0,
  "text": {
    "format": {
      "type": "text"
    }
  },
  "tool_choice": "auto",
  "tools": [],
  "top_p": 1.0,
  "truncation": "disabled",
  "usage": {
    "input_tokens": 36,
    "input_tokens_details": {
      "cached_tokens": 0
    },
    "output_tokens": 87,
    "output_tokens_details": {
      "reasoning_tokens": 0
    },
    "total_tokens": 123
  },
  "user": null,
  "metadata": {}
}


###### title

Image input

###### request

####### curl

curl https://api.openai.com/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "gpt-4.1",
    "input": [
      {
        "role": "user",
        "content": [
          {"type": "input_text", "text": "what is in this image?"},
          {
            "type": "input_image",
            "image_url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg"
          }
        ]
      }
    ]
  }'


####### javascript

import OpenAI from "openai";

const openai = new OpenAI();

const response = await openai.responses.create({
    model: "gpt-4.1",
    input: [
        {
            role: "user",
            content: [
                { type: "input_text", text: "what is in this image?" },
                {
                    type: "input_image",
                    image_url:
                        "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg",
                },
            ],
        },
    ],
});

console.log(response);


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
response = client.responses.create()
print(response.id)

####### csharp

using System;
using System.Collections.Generic;

using OpenAI.Responses;

OpenAIResponseClient client = new(
    model: "gpt-4.1",
    apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY")
);

List<ResponseItem> inputItems =
[
    ResponseItem.CreateUserMessageItem(
        [
            ResponseContentPart.CreateInputTextPart("What is in this image?"),
            ResponseContentPart.CreateInputImagePart(new Uri("https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg"))
        ]
    )
];

OpenAIResponse response = client.CreateResponse(inputItems);

Console.WriteLine(response.GetOutputText());


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const response = await client.responses.create();

console.log(response.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
  "github.com/openai/openai-go/responses"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  response, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{

  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", response.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        Response response = client.responses().create();
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

response = openai.responses.create

puts(response)

###### response

{
  "id": "resp_67ccd3a9da748190baa7f1570fe91ac604becb25c45c1d41",
  "object": "response",
  "created_at": 1741476777,
  "status": "completed",
  "error": null,
  "incomplete_details": null,
  "instructions": null,
  "max_output_tokens": null,
  "model": "gpt-4.1-2025-04-14",
  "output": [
    {
      "type": "message",
      "id": "msg_67ccd3acc8d48190a77525dc6de64b4104becb25c45c1d41",
      "status": "completed",
      "role": "assistant",
      "content": [
        {
          "type": "output_text",
          "text": "The image depicts a scenic landscape with a wooden boardwalk or pathway leading through lush, green grass under a blue sky with some clouds. The setting suggests a peaceful natural area, possibly a park or nature reserve. There are trees and shrubs in the background.",
          "annotations": []
        }
      ]
    }
  ],
  "parallel_tool_calls": true,
  "previous_response_id": null,
  "reasoning": {
    "effort": null,
    "summary": null
  },
  "store": true,
  "temperature": 1.0,
  "text": {
    "format": {
      "type": "text"
    }
  },
  "tool_choice": "auto",
  "tools": [],
  "top_p": 1.0,
  "truncation": "disabled",
  "usage": {
    "input_tokens": 328,
    "input_tokens_details": {
      "cached_tokens": 0
    },
    "output_tokens": 52,
    "output_tokens_details": {
      "reasoning_tokens": 0
    },
    "total_tokens": 380
  },
  "user": null,
  "metadata": {}
}


###### title

File input

###### request

####### curl

curl https://api.openai.com/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "gpt-4.1",
    "input": [
      {
        "role": "user",
        "content": [
          {"type": "input_text", "text": "what is in this file?"},
          {
            "type": "input_file",
            "file_url": "https://www.berkshirehathaway.com/letters/2024ltr.pdf"
          }
        ]
      }
    ]
  }'


####### javascript

import OpenAI from "openai";

const openai = new OpenAI();

const response = await openai.responses.create({
    model: "gpt-4.1",
    input: [
        {
            role: "user",
            content: [
                { type: "input_text", text: "what is in this file?" },
                {
                    type: "input_file",
                    file_url: "https://www.berkshirehathaway.com/letters/2024ltr.pdf",
                },
            ],
        },
    ],
});

console.log(response);


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
response = client.responses.create()
print(response.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const response = await client.responses.create();

console.log(response.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
  "github.com/openai/openai-go/responses"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  response, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{

  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", response.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        Response response = client.responses().create();
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

response = openai.responses.create

puts(response)

###### response

{
  "id": "resp_686eef60237881a2bd1180bb8b13de430e34c516d176ff86",
  "object": "response",
  "created_at": 1752100704,
  "status": "completed",
  "background": false,
  "error": null,
  "incomplete_details": null,
  "instructions": null,
  "max_output_tokens": null,
  "max_tool_calls": null,
  "model": "gpt-4.1-2025-04-14",
  "output": [
    {
      "id": "msg_686eef60d3e081a29283bdcbc4322fd90e34c516d176ff86",
      "type": "message",
      "status": "completed",
      "content": [
        {
          "type": "output_text",
          "annotations": [],
          "logprobs": [],
          "text": "The file seems to contain excerpts from a letter to the shareholders of Berkshire Hathaway Inc., likely written by Warren Buffett. It covers several topics:\n\n1. **Communication Philosophy**: Buffett emphasizes the importance of transparency and candidness in reporting mistakes and successes to shareholders.\n\n2. **Mistakes and Learnings**: The letter acknowledges past mistakes in business assessments and management hires, highlighting the importance of correcting errors promptly.\n\n3. **CEO Succession**: Mention of Greg Abel stepping in as the new CEO and continuing the tradition of honest communication.\n\n4. **Pete Liegl Story**: A detailed account of acquiring Forest River and the relationship with its founder, highlighting trust and effective business decisions.\n\n5. **2024 Performance**: Overview of business performance, particularly in insurance and investment activities, with a focus on GEICO's improvement.\n\n6. **Tax Contributions**: Discussion of significant tax payments to the U.S. Treasury, credited to shareholders' reinvestments.\n\n7. **Investment Strategy**: A breakdown of Berkshire\u2019s investments in both controlled subsidiaries and marketable equities, along with a focus on long-term holding strategies.\n\n8. **American Capitalism**: Reflections on America\u2019s economic development and Berkshire\u2019s role within it.\n\n9. **Property-Casualty Insurance**: Insights into the P/C insurance business model and its challenges and benefits.\n\n10. **Japanese Investments**: Information about Berkshire\u2019s investments in Japanese companies and future plans.\n\n11. **Annual Meeting**: Details about the upcoming annual gathering in Omaha, including schedule changes and new book releases.\n\n12. **Personal Anecdotes**: Light-hearted stories about family and interactions, conveying Buffett's personable approach.\n\n13. **Financial Performance Data**: Tables comparing Berkshire\u2019s annual performance to the S&P 500, showing impressive long-term gains.\n\nOverall, the letter reinforces Berkshire Hathaway's commitment to transparency, investment in both its businesses and the wider economy, and emphasizes strong leadership and prudent financial management."
        }
      ],
      "role": "assistant"
    }
  ],
  "parallel_tool_calls": true,
  "previous_response_id": null,
  "reasoning": {
    "effort": null,
    "summary": null
  },
  "service_tier": "default",
  "store": true,
  "temperature": 1.0,
  "text": {
    "format": {
      "type": "text"
    }
  },
  "tool_choice": "auto",
  "tools": [],
  "top_logprobs": 0,
  "top_p": 1.0,
  "truncation": "disabled",
  "usage": {
    "input_tokens": 8438,
    "input_tokens_details": {
      "cached_tokens": 0
    },
    "output_tokens": 398,
    "output_tokens_details": {
      "reasoning_tokens": 0
    },
    "total_tokens": 8836
  },
  "user": null,
  "metadata": {}
}


###### title

Web search

###### request

####### curl

curl https://api.openai.com/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "gpt-4.1",
    "tools": [{ "type": "web_search_preview" }],
    "input": "What was a positive news story from today?"
  }'


####### javascript

import OpenAI from "openai";

const openai = new OpenAI();

const response = await openai.responses.create({
    model: "gpt-4.1",
    tools: [{ type: "web_search_preview" }],
    input: "What was a positive news story from today?",
});

console.log(response);


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
response = client.responses.create()
print(response.id)

####### csharp

using System;

using OpenAI.Responses;

OpenAIResponseClient client = new(
    model: "gpt-4.1",
    apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY")
);

string userInputText = "What was a positive news story from today?";

ResponseCreationOptions options = new()
{
    Tools =
    {
        ResponseTool.CreateWebSearchTool()
    },
};

OpenAIResponse response = client.CreateResponse(userInputText, options);

Console.WriteLine(response.GetOutputText());


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const response = await client.responses.create();

console.log(response.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
  "github.com/openai/openai-go/responses"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  response, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{

  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", response.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        Response response = client.responses().create();
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

response = openai.responses.create

puts(response)

###### response

{
  "id": "resp_67ccf18ef5fc8190b16dbee19bc54e5f087bb177ab789d5c",
  "object": "response",
  "created_at": 1741484430,
  "status": "completed",
  "error": null,
  "incomplete_details": null,
  "instructions": null,
  "max_output_tokens": null,
  "model": "gpt-4.1-2025-04-14",
  "output": [
    {
      "type": "web_search_call",
      "id": "ws_67ccf18f64008190a39b619f4c8455ef087bb177ab789d5c",
      "status": "completed"
    },
    {
      "type": "message",
      "id": "msg_67ccf190ca3881909d433c50b1f6357e087bb177ab789d5c",
      "status": "completed",
      "role": "assistant",
      "content": [
        {
          "type": "output_text",
          "text": "As of today, March 9, 2025, one notable positive news story...",
          "annotations": [
            {
              "type": "url_citation",
              "start_index": 442,
              "end_index": 557,
              "url": "https://.../?utm_source=chatgpt.com",
              "title": "..."
            },
            {
              "type": "url_citation",
              "start_index": 962,
              "end_index": 1077,
              "url": "https://.../?utm_source=chatgpt.com",
              "title": "..."
            },
            {
              "type": "url_citation",
              "start_index": 1336,
              "end_index": 1451,
              "url": "https://.../?utm_source=chatgpt.com",
              "title": "..."
            }
          ]
        }
      ]
    }
  ],
  "parallel_tool_calls": true,
  "previous_response_id": null,
  "reasoning": {
    "effort": null,
    "summary": null
  },
  "store": true,
  "temperature": 1.0,
  "text": {
    "format": {
      "type": "text"
    }
  },
  "tool_choice": "auto",
  "tools": [
    {
      "type": "web_search_preview",
      "domains": [],
      "search_context_size": "medium",
      "user_location": {
        "type": "approximate",
        "city": null,
        "country": "US",
        "region": null,
        "timezone": null
      }
    }
  ],
  "top_p": 1.0,
  "truncation": "disabled",
  "usage": {
    "input_tokens": 328,
    "input_tokens_details": {
      "cached_tokens": 0
    },
    "output_tokens": 356,
    "output_tokens_details": {
      "reasoning_tokens": 0
    },
    "total_tokens": 684
  },
  "user": null,
  "metadata": {}
}


###### title

File search

###### request

####### curl

curl https://api.openai.com/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "gpt-4.1",
    "tools": [{
      "type": "file_search",
      "vector_store_ids": ["vs_1234567890"],
      "max_num_results": 20
    }],
    "input": "What are the attributes of an ancient brown dragon?"
  }'


####### javascript

import OpenAI from "openai";

const openai = new OpenAI();

const response = await openai.responses.create({
    model: "gpt-4.1",
    tools: [{
      type: "file_search",
      vector_store_ids: ["vs_1234567890"],
      max_num_results: 20
    }],
    input: "What are the attributes of an ancient brown dragon?",
});

console.log(response);


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
response = client.responses.create()
print(response.id)

####### csharp

using System;

using OpenAI.Responses;

OpenAIResponseClient client = new(
    model: "gpt-4.1",
    apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY")
);

string userInputText = "What are the attributes of an ancient brown dragon?";

ResponseCreationOptions options = new()
{
    Tools =
    {
        ResponseTool.CreateFileSearchTool(
            vectorStoreIds: ["vs_1234567890"],
            maxResultCount: 20
        )
    },
};

OpenAIResponse response = client.CreateResponse(userInputText, options);

Console.WriteLine(response.GetOutputText());


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const response = await client.responses.create();

console.log(response.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
  "github.com/openai/openai-go/responses"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  response, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{

  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", response.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        Response response = client.responses().create();
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

response = openai.responses.create

puts(response)

###### response

{
  "id": "resp_67ccf4c55fc48190b71bd0463ad3306d09504fb6872380d7",
  "object": "response",
  "created_at": 1741485253,
  "status": "completed",
  "error": null,
  "incomplete_details": null,
  "instructions": null,
  "max_output_tokens": null,
  "model": "gpt-4.1-2025-04-14",
  "output": [
    {
      "type": "file_search_call",
      "id": "fs_67ccf4c63cd08190887ef6464ba5681609504fb6872380d7",
      "status": "completed",
      "queries": [
        "attributes of an ancient brown dragon"
      ],
      "results": null
    },
    {
      "type": "message",
      "id": "msg_67ccf4c93e5c81909d595b369351a9d309504fb6872380d7",
      "status": "completed",
      "role": "assistant",
      "content": [
        {
          "type": "output_text",
          "text": "The attributes of an ancient brown dragon include...",
          "annotations": [
            {
              "type": "file_citation",
              "index": 320,
              "file_id": "file-4wDz5b167pAf72nx1h9eiN",
              "filename": "dragons.pdf"
            },
            {
              "type": "file_citation",
              "index": 576,
              "file_id": "file-4wDz5b167pAf72nx1h9eiN",
              "filename": "dragons.pdf"
            },
            {
              "type": "file_citation",
              "index": 815,
              "file_id": "file-4wDz5b167pAf72nx1h9eiN",
              "filename": "dragons.pdf"
            },
            {
              "type": "file_citation",
              "index": 815,
              "file_id": "file-4wDz5b167pAf72nx1h9eiN",
              "filename": "dragons.pdf"
            },
            {
              "type": "file_citation",
              "index": 1030,
              "file_id": "file-4wDz5b167pAf72nx1h9eiN",
              "filename": "dragons.pdf"
            },
            {
              "type": "file_citation",
              "index": 1030,
              "file_id": "file-4wDz5b167pAf72nx1h9eiN",
              "filename": "dragons.pdf"
            },
            {
              "type": "file_citation",
              "index": 1156,
              "file_id": "file-4wDz5b167pAf72nx1h9eiN",
              "filename": "dragons.pdf"
            },
            {
              "type": "file_citation",
              "index": 1225,
              "file_id": "file-4wDz5b167pAf72nx1h9eiN",
              "filename": "dragons.pdf"
            }
          ]
        }
      ]
    }
  ],
  "parallel_tool_calls": true,
  "previous_response_id": null,
  "reasoning": {
    "effort": null,
    "summary": null
  },
  "store": true,
  "temperature": 1.0,
  "text": {
    "format": {
      "type": "text"
    }
  },
  "tool_choice": "auto",
  "tools": [
    {
      "type": "file_search",
      "filters": null,
      "max_num_results": 20,
      "ranking_options": {
        "ranker": "auto",
        "score_threshold": 0.0
      },
      "vector_store_ids": [
        "vs_1234567890"
      ]
    }
  ],
  "top_p": 1.0,
  "truncation": "disabled",
  "usage": {
    "input_tokens": 18307,
    "input_tokens_details": {
      "cached_tokens": 0
    },
    "output_tokens": 348,
    "output_tokens_details": {
      "reasoning_tokens": 0
    },
    "total_tokens": 18655
  },
  "user": null,
  "metadata": {}
}      


###### title

Streaming

###### request

####### curl

curl https://api.openai.com/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "gpt-4.1",
    "instructions": "You are a helpful assistant.",
    "input": "Hello!",
    "stream": true
  }'


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
response = client.responses.create()
print(response.id)

####### javascript

import OpenAI from "openai";

const openai = new OpenAI();

const response = await openai.responses.create({
    model: "gpt-4.1",
    instructions: "You are a helpful assistant.",
    input: "Hello!",
    stream: true,
});

for await (const event of response) {
    console.log(event);
}


####### csharp

using System;
using System.ClientModel;
using System.Threading.Tasks;

using OpenAI.Responses;

OpenAIResponseClient client = new(
    model: "gpt-4.1",
    apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY")
);

string userInputText = "Hello!";

ResponseCreationOptions options = new()
{
    Instructions = "You are a helpful assistant.",
};

AsyncCollectionResult<StreamingResponseUpdate> responseUpdates = client.CreateResponseStreamingAsync(userInputText, options);

await foreach (StreamingResponseUpdate responseUpdate in responseUpdates)
{
    if (responseUpdate is StreamingResponseOutputTextDeltaUpdate outputTextDeltaUpdate)
    {
        Console.Write(outputTextDeltaUpdate.Delta);
    }
}


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const response = await client.responses.create();

console.log(response.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
  "github.com/openai/openai-go/responses"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  response, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{

  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", response.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        Response response = client.responses().create();
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

response = openai.responses.create

puts(response)

###### response

event: response.created
data: {"type":"response.created","response":{"id":"resp_67c9fdcecf488190bdd9a0409de3a1ec07b8b0ad4e5eb654","object":"response","created_at":1741290958,"status":"in_progress","error":null,"incomplete_details":null,"instructions":"You are a helpful assistant.","max_output_tokens":null,"model":"gpt-4.1-2025-04-14","output":[],"parallel_tool_calls":true,"previous_response_id":null,"reasoning":{"effort":null,"summary":null},"store":true,"temperature":1.0,"text":{"format":{"type":"text"}},"tool_choice":"auto","tools":[],"top_p":1.0,"truncation":"disabled","usage":null,"user":null,"metadata":{}}}

event: response.in_progress
data: {"type":"response.in_progress","response":{"id":"resp_67c9fdcecf488190bdd9a0409de3a1ec07b8b0ad4e5eb654","object":"response","created_at":1741290958,"status":"in_progress","error":null,"incomplete_details":null,"instructions":"You are a helpful assistant.","max_output_tokens":null,"model":"gpt-4.1-2025-04-14","output":[],"parallel_tool_calls":true,"previous_response_id":null,"reasoning":{"effort":null,"summary":null},"store":true,"temperature":1.0,"text":{"format":{"type":"text"}},"tool_choice":"auto","tools":[],"top_p":1.0,"truncation":"disabled","usage":null,"user":null,"metadata":{}}}

event: response.output_item.added
data: {"type":"response.output_item.added","output_index":0,"item":{"id":"msg_67c9fdcf37fc8190ba82116e33fb28c507b8b0ad4e5eb654","type":"message","status":"in_progress","role":"assistant","content":[]}}

event: response.content_part.added
data: {"type":"response.content_part.added","item_id":"msg_67c9fdcf37fc8190ba82116e33fb28c507b8b0ad4e5eb654","output_index":0,"content_index":0,"part":{"type":"output_text","text":"","annotations":[]}}

event: response.output_text.delta
data: {"type":"response.output_text.delta","item_id":"msg_67c9fdcf37fc8190ba82116e33fb28c507b8b0ad4e5eb654","output_index":0,"content_index":0,"delta":"Hi"}

...

event: response.output_text.done
data: {"type":"response.output_text.done","item_id":"msg_67c9fdcf37fc8190ba82116e33fb28c507b8b0ad4e5eb654","output_index":0,"content_index":0,"text":"Hi there! How can I assist you today?"}

event: response.content_part.done
data: {"type":"response.content_part.done","item_id":"msg_67c9fdcf37fc8190ba82116e33fb28c507b8b0ad4e5eb654","output_index":0,"content_index":0,"part":{"type":"output_text","text":"Hi there! How can I assist you today?","annotations":[]}}

event: response.output_item.done
data: {"type":"response.output_item.done","output_index":0,"item":{"id":"msg_67c9fdcf37fc8190ba82116e33fb28c507b8b0ad4e5eb654","type":"message","status":"completed","role":"assistant","content":[{"type":"output_text","text":"Hi there! How can I assist you today?","annotations":[]}]}}

event: response.completed
data: {"type":"response.completed","response":{"id":"resp_67c9fdcecf488190bdd9a0409de3a1ec07b8b0ad4e5eb654","object":"response","created_at":1741290958,"status":"completed","error":null,"incomplete_details":null,"instructions":"You are a helpful assistant.","max_output_tokens":null,"model":"gpt-4.1-2025-04-14","output":[{"id":"msg_67c9fdcf37fc8190ba82116e33fb28c507b8b0ad4e5eb654","type":"message","status":"completed","role":"assistant","content":[{"type":"output_text","text":"Hi there! How can I assist you today?","annotations":[]}]}],"parallel_tool_calls":true,"previous_response_id":null,"reasoning":{"effort":null,"summary":null},"store":true,"temperature":1.0,"text":{"format":{"type":"text"}},"tool_choice":"auto","tools":[],"top_p":1.0,"truncation":"disabled","usage":{"input_tokens":37,"output_tokens":11,"output_tokens_details":{"reasoning_tokens":0},"total_tokens":48},"user":null,"metadata":{}}}


###### title

Functions

###### request

####### curl

curl https://api.openai.com/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "gpt-4.1",
    "input": "What is the weather like in Boston today?",
    "tools": [
      {
        "type": "function",
        "name": "get_current_weather",
        "description": "Get the current weather in a given location",
        "parameters": {
          "type": "object",
          "properties": {
            "location": {
              "type": "string",
              "description": "The city and state, e.g. San Francisco, CA"
            },
            "unit": {
              "type": "string",
              "enum": ["celsius", "fahrenheit"]
            }
          },
          "required": ["location", "unit"]
        }
      }
    ],
    "tool_choice": "auto"
  }'


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
response = client.responses.create()
print(response.id)

####### javascript

import OpenAI from "openai";

const openai = new OpenAI();

const tools = [
    {
        type: "function",
        name: "get_current_weather",
        description: "Get the current weather in a given location",
        parameters: {
            type: "object",
            properties: {
                location: {
                    type: "string",
                    description: "The city and state, e.g. San Francisco, CA",
                },
                unit: { type: "string", enum: ["celsius", "fahrenheit"] },
            },
            required: ["location", "unit"],
        },
    },
];

const response = await openai.responses.create({
    model: "gpt-4.1",
    tools: tools,
    input: "What is the weather like in Boston today?",
    tool_choice: "auto",
});

console.log(response);


####### csharp

using System;
using OpenAI.Responses;

OpenAIResponseClient client = new(
    model: "gpt-4.1",
    apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY")
);

ResponseTool getCurrentWeatherFunctionTool = ResponseTool.CreateFunctionTool(
    functionName: "get_current_weather",
    functionDescription: "Get the current weather in a given location",
    functionParameters: BinaryData.FromString("""
        {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "The city and state, e.g. San Francisco, CA"
                },
                "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
            },
            "required": ["location", "unit"]
        }
        """
    )
);

string userInputText = "What is the weather like in Boston today?";

ResponseCreationOptions options = new()
{
    Tools =
    {
        getCurrentWeatherFunctionTool
    },
    ToolChoice = ResponseToolChoice.CreateAutoChoice(),
};

OpenAIResponse response = client.CreateResponse(userInputText, options);


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const response = await client.responses.create();

console.log(response.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
  "github.com/openai/openai-go/responses"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  response, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{

  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", response.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        Response response = client.responses().create();
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

response = openai.responses.create

puts(response)

###### response

{
  "id": "resp_67ca09c5efe0819096d0511c92b8c890096610f474011cc0",
  "object": "response",
  "created_at": 1741294021,
  "status": "completed",
  "error": null,
  "incomplete_details": null,
  "instructions": null,
  "max_output_tokens": null,
  "model": "gpt-4.1-2025-04-14",
  "output": [
    {
      "type": "function_call",
      "id": "fc_67ca09c6bedc8190a7abfec07b1a1332096610f474011cc0",
      "call_id": "call_unLAR8MvFNptuiZK6K6HCy5k",
      "name": "get_current_weather",
      "arguments": "{\"location\":\"Boston, MA\",\"unit\":\"celsius\"}",
      "status": "completed"
    }
  ],
  "parallel_tool_calls": true,
  "previous_response_id": null,
  "reasoning": {
    "effort": null,
    "summary": null
  },
  "store": true,
  "temperature": 1.0,
  "text": {
    "format": {
      "type": "text"
    }
  },
  "tool_choice": "auto",
  "tools": [
    {
      "type": "function",
      "description": "Get the current weather in a given location",
      "name": "get_current_weather",
      "parameters": {
        "type": "object",
        "properties": {
          "location": {
            "type": "string",
            "description": "The city and state, e.g. San Francisco, CA"
          },
          "unit": {
            "type": "string",
            "enum": [
              "celsius",
              "fahrenheit"
            ]
          }
        },
        "required": [
          "location",
          "unit"
        ]
      },
      "strict": true
    }
  ],
  "top_p": 1.0,
  "truncation": "disabled",
  "usage": {
    "input_tokens": 291,
    "output_tokens": 23,
    "output_tokens_details": {
      "reasoning_tokens": 0
    },
    "total_tokens": 314
  },
  "user": null,
  "metadata": {}
}


###### title

Reasoning

###### request

####### curl

curl https://api.openai.com/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "o3-mini",
    "input": "How much wood would a woodchuck chuck?",
    "reasoning": {
      "effort": "high"
    }
  }'


####### javascript

import OpenAI from "openai";
const openai = new OpenAI();

const response = await openai.responses.create({
    model: "o3-mini",
    input: "How much wood would a woodchuck chuck?",
    reasoning: {
      effort: "high"
    }
});

console.log(response);


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
response = client.responses.create()
print(response.id)

####### csharp

using System;
using OpenAI.Responses;

OpenAIResponseClient client = new(
    model: "o3-mini",
    apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY")
);

string userInputText = "How much wood would a woodchuck chuck?";

ResponseCreationOptions options = new()
{
    ReasoningOptions = new()
    {
        ReasoningEffortLevel = ResponseReasoningEffortLevel.High,
    },
};

OpenAIResponse response = client.CreateResponse(userInputText, options);

Console.WriteLine(response.GetOutputText());


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const response = await client.responses.create();

console.log(response.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
  "github.com/openai/openai-go/responses"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  response, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{

  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", response.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        Response response = client.responses().create();
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

response = openai.responses.create

puts(response)

###### response

{
  "id": "resp_67ccd7eca01881908ff0b5146584e408072912b2993db808",
  "object": "response",
  "created_at": 1741477868,
  "status": "completed",
  "error": null,
  "incomplete_details": null,
  "instructions": null,
  "max_output_tokens": null,
  "model": "o1-2024-12-17",
  "output": [
    {
      "type": "message",
      "id": "msg_67ccd7f7b5848190a6f3e95d809f6b44072912b2993db808",
      "status": "completed",
      "role": "assistant",
      "content": [
        {
          "type": "output_text",
          "text": "The classic tongue twister...",
          "annotations": []
        }
      ]
    }
  ],
  "parallel_tool_calls": true,
  "previous_response_id": null,
  "reasoning": {
    "effort": "high",
    "summary": null
  },
  "store": true,
  "temperature": 1.0,
  "text": {
    "format": {
      "type": "text"
    }
  },
  "tool_choice": "auto",
  "tools": [],
  "top_p": 1.0,
  "truncation": "disabled",
  "usage": {
    "input_tokens": 81,
    "input_tokens_details": {
      "cached_tokens": 0
    },
    "output_tokens": 1035,
    "output_tokens_details": {
      "reasoning_tokens": 832
    },
    "total_tokens": 1116
  },
  "user": null,
  "metadata": {}
}



#### description

Creates a model response. Provide [text](https://platform.openai.com/docs/guides/text) or
[image](https://platform.openai.com/docs/guides/images) inputs to generate [text](https://platform.openai.com/docs/guides/text)
or [JSON](https://platform.openai.com/docs/guides/structured-outputs) outputs. Have the model call
your own [custom code](https://platform.openai.com/docs/guides/function-calling) or use built-in
[tools](https://platform.openai.com/docs/guides/tools) like [web search](https://platform.openai.com/docs/guides/tools-web-search)
or [file search](https://platform.openai.com/docs/guides/tools-file-search) to use your own data
as input for the model's response.


## /responses/{response_id}

### get

#### operationId

getResponse

#### tags

- Responses

#### summary

Get a model response

#### parameters

##### in

path

##### name

response_id

##### required

true

##### schema

###### type

string

###### example

resp_677efb5139a88190b512bc3fef8e535d

##### description

The ID of the response to retrieve.

##### in

query

##### name

include

##### schema

###### type

array

###### items

####### $ref

#/components/schemas/Includable

##### description

Additional fields to include in the response. See the `include`
parameter for Response creation above for more information.


##### in

query

##### name

stream

##### schema

###### type

boolean

##### description

If set to true, the model response data will be streamed to the client
as it is generated using [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format).
See the [Streaming section below](https://platform.openai.com/docs/api-reference/responses-streaming)
for more information.


##### in

query

##### name

starting_after

##### schema

###### type

integer

##### description

The sequence number of the event after which to start streaming.


##### in

query

##### name

include_obfuscation

##### schema

###### type

boolean

##### description

When true, stream obfuscation will be enabled. Stream obfuscation adds
random characters to an `obfuscation` field on streaming delta events
to normalize payload sizes as a mitigation to certain side-channel
attacks. These obfuscation fields are included by default, but add a
small amount of overhead to the data stream. You can set
`include_obfuscation` to false to optimize for bandwidth if you trust
the network links between your application and the OpenAI API.



#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/Response

#### x-oaiMeta

##### name

Get a model response

##### group

responses

##### returns

The [Response](https://platform.openai.com/docs/api-reference/responses/object) object matching the
specified ID.


##### examples

###### response

{
  "id": "resp_67cb71b351908190a308f3859487620d06981a8637e6bc44",
  "object": "response",
  "created_at": 1741386163,
  "status": "completed",
  "error": null,
  "incomplete_details": null,
  "instructions": null,
  "max_output_tokens": null,
  "model": "gpt-4o-2024-08-06",
  "output": [
    {
      "type": "message",
      "id": "msg_67cb71b3c2b0819084d481baaaf148f206981a8637e6bc44",
      "status": "completed",
      "role": "assistant",
      "content": [
        {
          "type": "output_text",
          "text": "Silent circuits hum,  \nThoughts emerge in data streamsâ  \nDigital dawn breaks.",
          "annotations": []
        }
      ]
    }
  ],
  "parallel_tool_calls": true,
  "previous_response_id": null,
  "reasoning": {
    "effort": null,
    "summary": null
  },
  "store": true,
  "temperature": 1.0,
  "text": {
    "format": {
      "type": "text"
    }
  },
  "tool_choice": "auto",
  "tools": [],
  "top_p": 1.0,
  "truncation": "disabled",
  "usage": {
    "input_tokens": 32,
    "input_tokens_details": {
      "cached_tokens": 0
    },
    "output_tokens": 18,
    "output_tokens_details": {
      "reasoning_tokens": 0
    },
    "total_tokens": 50
  },
  "user": null,
  "metadata": {}
}


###### request

####### curl

curl https://api.openai.com/v1/responses/resp_123 \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $OPENAI_API_KEY"


####### javascript

import OpenAI from "openai";
const client = new OpenAI();

const response = await client.responses.retrieve("resp_123");
console.log(response);


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
response = client.responses.retrieve(
    response_id="resp_677efb5139a88190b512bc3fef8e535d",
)
print(response.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const response = await client.responses.retrieve('resp_677efb5139a88190b512bc3fef8e535d');

console.log(response.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
  "github.com/openai/openai-go/responses"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  response, err := client.Responses.Get(
    context.TODO(),
    "resp_677efb5139a88190b512bc3fef8e535d",
    responses.ResponseGetParams{

    },
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", response.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseRetrieveParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        Response response = client.responses().retrieve("resp_677efb5139a88190b512bc3fef8e535d");
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

response = openai.responses.retrieve("resp_677efb5139a88190b512bc3fef8e535d")

puts(response)

#### description

Retrieves a model response with the given ID.


### delete

#### operationId

deleteResponse

#### tags

- Responses

#### summary

Delete a model response

#### parameters

##### in

path

##### name

response_id

##### required

true

##### schema

###### type

string

###### example

resp_677efb5139a88190b512bc3fef8e535d

##### description

The ID of the response to delete.


#### responses

##### 200

###### description

OK

##### 404

###### description

Not Found

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/Error

#### x-oaiMeta

##### name

Delete a model response

##### group

responses

##### returns

A success message.


##### examples

###### response

{
  "id": "resp_6786a1bec27481909a17d673315b29f6",
  "object": "response",
  "deleted": true
}


###### request

####### curl

curl -X DELETE https://api.openai.com/v1/responses/resp_123 \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $OPENAI_API_KEY"


####### javascript

import OpenAI from "openai";
const client = new OpenAI();

const response = await client.responses.delete("resp_123");
console.log(response);


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
client.responses.delete(
    "resp_677efb5139a88190b512bc3fef8e535d",
)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

await client.responses.delete('resp_677efb5139a88190b512bc3fef8e535d');

####### go

package main

import (
  "context"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  err := client.Responses.Delete(context.TODO(), "resp_677efb5139a88190b512bc3fef8e535d")
  if err != nil {
    panic(err.Error())
  }
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.ResponseDeleteParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        client.responses().delete("resp_677efb5139a88190b512bc3fef8e535d");
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

result = openai.responses.delete("resp_677efb5139a88190b512bc3fef8e535d")

puts(result)

#### description

Deletes a model response with the given ID.


## /responses/{response_id}/cancel

### post

#### operationId

cancelResponse

#### tags

- Responses

#### summary

Cancel a response

#### parameters

##### in

path

##### name

response_id

##### required

true

##### schema

###### type

string

###### example

resp_677efb5139a88190b512bc3fef8e535d

##### description

The ID of the response to cancel.


#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/Response

##### 404

###### description

Not Found

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/Error

#### x-oaiMeta

##### name

Cancel a response

##### group

responses

##### returns

A [Response](https://platform.openai.com/docs/api-reference/responses/object) object.


##### examples

###### response

{
  "id": "resp_67cb71b351908190a308f3859487620d06981a8637e6bc44",
  "object": "response",
  "created_at": 1741386163,
  "status": "completed",
  "error": null,
  "incomplete_details": null,
  "instructions": null,
  "max_output_tokens": null,
  "model": "gpt-4o-2024-08-06",
  "output": [
    {
      "type": "message",
      "id": "msg_67cb71b3c2b0819084d481baaaf148f206981a8637e6bc44",
      "status": "completed",
      "role": "assistant",
      "content": [
        {
          "type": "output_text",
          "text": "Silent circuits hum,  \nThoughts emerge in data streamsâ  \nDigital dawn breaks.",
          "annotations": []
        }
      ]
    }
  ],
  "parallel_tool_calls": true,
  "previous_response_id": null,
  "reasoning": {
    "effort": null,
    "summary": null
  },
  "store": true,
  "temperature": 1.0,
  "text": {
    "format": {
      "type": "text"
    }
  },
  "tool_choice": "auto",
  "tools": [],
  "top_p": 1.0,
  "truncation": "disabled",
  "usage": {
    "input_tokens": 32,
    "input_tokens_details": {
      "cached_tokens": 0
    },
    "output_tokens": 18,
    "output_tokens_details": {
      "reasoning_tokens": 0
    },
    "total_tokens": 50
  },
  "user": null,
  "metadata": {}
}


###### request

####### curl

curl -X POST https://api.openai.com/v1/responses/resp_123/cancel \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $OPENAI_API_KEY"


####### javascript

import OpenAI from "openai";
const client = new OpenAI();

const response = await client.responses.cancel("resp_123");
console.log(response);  


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
response = client.responses.cancel(
    "resp_677efb5139a88190b512bc3fef8e535d",
)
print(response.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const response = await client.responses.cancel('resp_677efb5139a88190b512bc3fef8e535d');

console.log(response.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  response, err := client.Responses.Cancel(context.TODO(), "resp_677efb5139a88190b512bc3fef8e535d")
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", response.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCancelParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        Response response = client.responses().cancel("resp_677efb5139a88190b512bc3fef8e535d");
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

response = openai.responses.cancel("resp_677efb5139a88190b512bc3fef8e535d")

puts(response)

#### description

Cancels a model response with the given ID. Only responses created with
the `background` parameter set to `true` can be cancelled. 
[Learn more](https://platform.openai.com/docs/guides/background).


## /responses/{response_id}/input_items

### get

#### operationId

listInputItems

#### tags

- Responses

#### summary

List input items

#### parameters

##### in

path

##### name

response_id

##### required

true

##### schema

###### type

string

##### description

The ID of the response to retrieve input items for.

##### name

limit

##### in

query

##### description

A limit on the number of objects to be returned. Limit can range between
1 and 100, and the default is 20.


##### required

false

##### schema

###### type

integer

###### default

20

##### in

query

##### name

order

##### schema

###### type

string

###### enum

- asc
- desc

##### description

The order to return the input items in. Default is `desc`.
- `asc`: Return the input items in ascending order.
- `desc`: Return the input items in descending order.


##### in

query

##### name

after

##### schema

###### type

string

##### description

An item ID to list items after, used in pagination.


##### in

query

##### name

include

##### schema

###### type

array

###### items

####### $ref

#/components/schemas/Includable

##### description

Additional fields to include in the response. See the `include`
parameter for Response creation above for more information.



#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ResponseItemList

#### x-oaiMeta

##### name

List input items

##### group

responses

##### returns

A list of input item objects.

##### examples

###### response

{
  "object": "list",
  "data": [
    {
      "id": "msg_abc123",
      "type": "message",
      "role": "user",
      "content": [
        {
          "type": "input_text",
          "text": "Tell me a three sentence bedtime story about a unicorn."
        }
      ]
    }
  ],
  "first_id": "msg_abc123",
  "last_id": "msg_abc123",
  "has_more": false
}


###### request

####### curl

curl https://api.openai.com/v1/responses/resp_abc123/input_items \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY"


####### javascript

import OpenAI from "openai";
const client = new OpenAI();

const response = await client.responses.inputItems.list("resp_123");
console.log(response.data);


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
page = client.responses.input_items.list(
    response_id="response_id",
)
page = page.data[0]
print(page)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

// Automatically fetches more pages as needed.
for await (const responseItem of client.responses.inputItems.list('response_id')) {
  console.log(responseItem);
}

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
  "github.com/openai/openai-go/responses"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  page, err := client.Responses.InputItems.List(
    context.TODO(),
    "response_id",
    responses.InputItemListParams{

    },
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", page)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.inputitems.InputItemListPage;
import com.openai.models.responses.inputitems.InputItemListParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        InputItemListPage page = client.responses().inputItems().list("response_id");
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

page = openai.responses.input_items.list("response_id")

puts(page)

#### description

Returns a list of input items for a given response.

## /threads

### post

#### operationId

createThread

#### tags

- Assistants

#### summary

Create thread

#### requestBody

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/CreateThreadRequest

#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ThreadObject

#### x-oaiMeta

##### name

Create thread

##### group

threads

##### beta

true

##### returns

A [thread](https://platform.openai.com/docs/api-reference/threads) object.

##### examples

###### title

Empty

###### request

####### curl

curl https://api.openai.com/v1/threads \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "OpenAI-Beta: assistants=v2" \
  -d ''


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
thread = client.beta.threads.create()
print(thread.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const thread = await client.beta.threads.create();

console.log(thread.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  thread, err := client.Beta.Threads.New(context.TODO(), openai.BetaThreadNewParams{

  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", thread.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.beta.threads.Thread;
import com.openai.models.beta.threads.ThreadCreateParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        Thread thread = client.beta().threads().create();
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

thread = openai.beta.threads.create

puts(thread)

###### response

{
  "id": "thread_abc123",
  "object": "thread",
  "created_at": 1699012949,
  "metadata": {},
  "tool_resources": {}
}


###### title

Messages

###### request

####### curl

curl https://api.openai.com/v1/threads \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "OpenAI-Beta: assistants=v2" \
-d '{
    "messages": [{
      "role": "user",
      "content": "Hello, what is AI?"
    }, {
      "role": "user",
      "content": "How does AI work? Explain it in simple terms."
    }]
  }'


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
thread = client.beta.threads.create()
print(thread.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const thread = await client.beta.threads.create();

console.log(thread.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  thread, err := client.Beta.Threads.New(context.TODO(), openai.BetaThreadNewParams{

  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", thread.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.beta.threads.Thread;
import com.openai.models.beta.threads.ThreadCreateParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        Thread thread = client.beta().threads().create();
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

thread = openai.beta.threads.create

puts(thread)

###### response

{
  "id": "thread_abc123",
  "object": "thread",
  "created_at": 1699014083,
  "metadata": {},
  "tool_resources": {}
}



#### description

Create a thread.

## /threads/runs

### post

#### operationId

createThreadAndRun

#### tags

- Assistants

#### summary

Create thread and run

#### requestBody

##### required

true

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/CreateThreadAndRunRequest

#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/RunObject

#### x-oaiMeta

##### name

Create thread and run

##### group

threads

##### beta

true

##### returns

A [run](https://platform.openai.com/docs/api-reference/runs/object) object.

##### examples

###### title

Default

###### request

####### curl

curl https://api.openai.com/v1/threads/runs \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -H "OpenAI-Beta: assistants=v2" \
  -d '{
      "assistant_id": "asst_abc123",
      "thread": {
        "messages": [
          {"role": "user", "content": "Explain deep learning to a 5 year old."}
        ]
      }
    }'


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
run = client.beta.threads.create_and_run(
    assistant_id="assistant_id",
)
print(run.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const run = await client.beta.threads.createAndRun({ assistant_id: 'assistant_id' });

console.log(run.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  run, err := client.Beta.Threads.NewAndRun(context.TODO(), openai.BetaThreadNewAndRunParams{
    AssistantID: "assistant_id",
  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", run.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.beta.threads.ThreadCreateAndRunParams;
import com.openai.models.beta.threads.runs.Run;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        ThreadCreateAndRunParams params = ThreadCreateAndRunParams.builder()
            .assistantId("assistant_id")
            .build();
        Run run = client.beta().threads().createAndRun(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

run = openai.beta.threads.create_and_run(assistant_id: "assistant_id")

puts(run)

###### response

{
  "id": "run_abc123",
  "object": "thread.run",
  "created_at": 1699076792,
  "assistant_id": "asst_abc123",
  "thread_id": "thread_abc123",
  "status": "queued",
  "started_at": null,
  "expires_at": 1699077392,
  "cancelled_at": null,
  "failed_at": null,
  "completed_at": null,
  "required_action": null,
  "last_error": null,
  "model": "gpt-4o",
  "instructions": "You are a helpful assistant.",
  "tools": [],
  "tool_resources": {},
  "metadata": {},
  "temperature": 1.0,
  "top_p": 1.0,
  "max_completion_tokens": null,
  "max_prompt_tokens": null,
  "truncation_strategy": {
    "type": "auto",
    "last_messages": null
  },
  "incomplete_details": null,
  "usage": null,
  "response_format": "auto",
  "tool_choice": "auto",
  "parallel_tool_calls": true
}


###### title

Streaming

###### request

####### curl

curl https://api.openai.com/v1/threads/runs \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -H "OpenAI-Beta: assistants=v2" \
  -d '{
    "assistant_id": "asst_123",
    "thread": {
      "messages": [
        {"role": "user", "content": "Hello"}
      ]
    },
    "stream": true
  }'


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
run = client.beta.threads.create_and_run(
    assistant_id="assistant_id",
)
print(run.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const run = await client.beta.threads.createAndRun({ assistant_id: 'assistant_id' });

console.log(run.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  run, err := client.Beta.Threads.NewAndRun(context.TODO(), openai.BetaThreadNewAndRunParams{
    AssistantID: "assistant_id",
  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", run.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.beta.threads.ThreadCreateAndRunParams;
import com.openai.models.beta.threads.runs.Run;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        ThreadCreateAndRunParams params = ThreadCreateAndRunParams.builder()
            .assistantId("assistant_id")
            .build();
        Run run = client.beta().threads().createAndRun(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

run = openai.beta.threads.create_and_run(assistant_id: "assistant_id")

puts(run)

###### response

event: thread.created
data: {"id":"thread_123","object":"thread","created_at":1710348075,"metadata":{}}

event: thread.run.created
data: {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710348675,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"tool_resources":{},"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}

event: thread.run.queued
data: {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710348675,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"tool_resources":{},"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}

event: thread.run.in_progress
data: {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"in_progress","started_at":null,"expires_at":1710348675,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"tool_resources":{},"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}

event: thread.run.step.created
data: {"id":"step_001","object":"thread.run.step","created_at":1710348076,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710348675,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":null}

event: thread.run.step.in_progress
data: {"id":"step_001","object":"thread.run.step","created_at":1710348076,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710348675,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":null}

event: thread.message.created
data: {"id":"msg_001","object":"thread.message","created_at":1710348076,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"in_progress","incomplete_details":null,"incomplete_at":null,"completed_at":null,"role":"assistant","content":[], "metadata":{}}

event: thread.message.in_progress
data: {"id":"msg_001","object":"thread.message","created_at":1710348076,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"in_progress","incomplete_details":null,"incomplete_at":null,"completed_at":null,"role":"assistant","content":[], "metadata":{}}

event: thread.message.delta
data: {"id":"msg_001","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":"Hello","annotations":[]}}]}}

...

event: thread.message.delta
data: {"id":"msg_001","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":" today"}}]}}

event: thread.message.delta
data: {"id":"msg_001","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":"?"}}]}}

event: thread.message.completed
data: {"id":"msg_001","object":"thread.message","created_at":1710348076,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"completed","incomplete_details":null,"incomplete_at":null,"completed_at":1710348077,"role":"assistant","content":[{"type":"text","text":{"value":"Hello! How can I assist you today?","annotations":[]}}], "metadata":{}}

event: thread.run.step.completed
data: {"id":"step_001","object":"thread.run.step","created_at":1710348076,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"completed","cancelled_at":null,"completed_at":1710348077,"expires_at":1710348675,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":{"prompt_tokens":20,"completion_tokens":11,"total_tokens":31}}

event: thread.run.completed
{"id":"run_123","object":"thread.run","created_at":1710348076,"assistant_id":"asst_123","thread_id":"thread_123","status":"completed","started_at":1713226836,"expires_at":null,"cancelled_at":null,"failed_at":null,"completed_at":1713226837,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":{"prompt_tokens":345,"completion_tokens":11,"total_tokens":356},"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}

event: done
data: [DONE]


###### title

Streaming with Functions

###### request

####### curl

curl https://api.openai.com/v1/threads/runs \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -H "OpenAI-Beta: assistants=v2" \
  -d '{
    "assistant_id": "asst_abc123",
    "thread": {
      "messages": [
        {"role": "user", "content": "What is the weather like in San Francisco?"}
      ]
    },
    "tools": [
      {
        "type": "function",
        "function": {
          "name": "get_current_weather",
          "description": "Get the current weather in a given location",
          "parameters": {
            "type": "object",
            "properties": {
              "location": {
                "type": "string",
                "description": "The city and state, e.g. San Francisco, CA"
              },
              "unit": {
                "type": "string",
                "enum": ["celsius", "fahrenheit"]
              }
            },
            "required": ["location"]
          }
        }
      }
    ],
    "stream": true
  }'


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
run = client.beta.threads.create_and_run(
    assistant_id="assistant_id",
)
print(run.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const run = await client.beta.threads.createAndRun({ assistant_id: 'assistant_id' });

console.log(run.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  run, err := client.Beta.Threads.NewAndRun(context.TODO(), openai.BetaThreadNewAndRunParams{
    AssistantID: "assistant_id",
  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", run.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.beta.threads.ThreadCreateAndRunParams;
import com.openai.models.beta.threads.runs.Run;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        ThreadCreateAndRunParams params = ThreadCreateAndRunParams.builder()
            .assistantId("assistant_id")
            .build();
        Run run = client.beta().threads().createAndRun(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

run = openai.beta.threads.create_and_run(assistant_id: "assistant_id")

puts(run)

###### response

event: thread.created
data: {"id":"thread_123","object":"thread","created_at":1710351818,"metadata":{}}

event: thread.run.created
data: {"id":"run_123","object":"thread.run","created_at":1710351818,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710352418,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather in a given location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and state, e.g. San Francisco, CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}}

event: thread.run.queued
data: {"id":"run_123","object":"thread.run","created_at":1710351818,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710352418,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather in a given location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and state, e.g. San Francisco, CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}}

event: thread.run.in_progress
data: {"id":"run_123","object":"thread.run","created_at":1710351818,"assistant_id":"asst_123","thread_id":"thread_123","status":"in_progress","started_at":1710351818,"expires_at":1710352418,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather in a given location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and state, e.g. San Francisco, CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}}

event: thread.run.step.created
data: {"id":"step_001","object":"thread.run.step","created_at":1710351819,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"tool_calls","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710352418,"failed_at":null,"last_error":null,"step_details":{"type":"tool_calls","tool_calls":[]},"usage":null}

event: thread.run.step.in_progress
data: {"id":"step_001","object":"thread.run.step","created_at":1710351819,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"tool_calls","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710352418,"failed_at":null,"last_error":null,"step_details":{"type":"tool_calls","tool_calls":[]},"usage":null}

event: thread.run.step.delta
data: {"id":"step_001","object":"thread.run.step.delta","delta":{"step_details":{"type":"tool_calls","tool_calls":[{"index":0,"id":"call_XXNp8YGaFrjrSjgqxtC8JJ1B","type":"function","function":{"name":"get_current_weather","arguments":"","output":null}}]}}}

event: thread.run.step.delta
data: {"id":"step_001","object":"thread.run.step.delta","delta":{"step_details":{"type":"tool_calls","tool_calls":[{"index":0,"type":"function","function":{"arguments":"{\""}}]}}}

event: thread.run.step.delta
data: {"id":"step_001","object":"thread.run.step.delta","delta":{"step_details":{"type":"tool_calls","tool_calls":[{"index":0,"type":"function","function":{"arguments":"location"}}]}}}

...

event: thread.run.step.delta
data: {"id":"step_001","object":"thread.run.step.delta","delta":{"step_details":{"type":"tool_calls","tool_calls":[{"index":0,"type":"function","function":{"arguments":"ahrenheit"}}]}}}

event: thread.run.step.delta
data: {"id":"step_001","object":"thread.run.step.delta","delta":{"step_details":{"type":"tool_calls","tool_calls":[{"index":0,"type":"function","function":{"arguments":"\"}"}}]}}}

event: thread.run.requires_action
data: {"id":"run_123","object":"thread.run","created_at":1710351818,"assistant_id":"asst_123","thread_id":"thread_123","status":"requires_action","started_at":1710351818,"expires_at":1710352418,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":{"type":"submit_tool_outputs","submit_tool_outputs":{"tool_calls":[{"id":"call_XXNp8YGaFrjrSjgqxtC8JJ1B","type":"function","function":{"name":"get_current_weather","arguments":"{\"location\":\"San Francisco, CA\",\"unit\":\"fahrenheit\"}"}}]}},"last_error":null,"model":"gpt-4o","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather in a given location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and state, e.g. San Francisco, CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":{"prompt_tokens":345,"completion_tokens":11,"total_tokens":356},"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}}

event: done
data: [DONE]



#### description

Create a thread and run it in one request.

## /threads/{thread_id}

### get

#### operationId

getThread

#### tags

- Assistants

#### summary

Retrieve thread

#### parameters

##### in

path

##### name

thread_id

##### required

true

##### schema

###### type

string

##### description

The ID of the thread to retrieve.


#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ThreadObject

#### x-oaiMeta

##### name

Retrieve thread

##### group

threads

##### beta

true

##### returns

The [thread](https://platform.openai.com/docs/api-reference/threads/object) object matching the specified ID.

##### examples

###### response

{
  "id": "thread_abc123",
  "object": "thread",
  "created_at": 1699014083,
  "metadata": {},
  "tool_resources": {
    "code_interpreter": {
      "file_ids": []
    }
  }
}


###### request

####### curl

curl https://api.openai.com/v1/threads/thread_abc123 \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "OpenAI-Beta: assistants=v2"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
thread = client.beta.threads.retrieve(
    "thread_id",
)
print(thread.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const thread = await client.beta.threads.retrieve('thread_id');

console.log(thread.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  thread, err := client.Beta.Threads.Get(context.TODO(), "thread_id")
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", thread.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.beta.threads.Thread;
import com.openai.models.beta.threads.ThreadRetrieveParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        Thread thread = client.beta().threads().retrieve("thread_id");
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

thread = openai.beta.threads.retrieve("thread_id")

puts(thread)

#### description

Retrieves a thread.

### post

#### operationId

modifyThread

#### tags

- Assistants

#### summary

Modify thread

#### parameters

##### in

path

##### name

thread_id

##### required

true

##### schema

###### type

string

##### description

The ID of the thread to modify. Only the `metadata` can be modified.


#### requestBody

##### required

true

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/ModifyThreadRequest

#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ThreadObject

#### x-oaiMeta

##### name

Modify thread

##### group

threads

##### beta

true

##### returns

The modified [thread](https://platform.openai.com/docs/api-reference/threads/object) object matching the specified ID.

##### examples

###### response

{
  "id": "thread_abc123",
  "object": "thread",
  "created_at": 1699014083,
  "metadata": {
    "modified": "true",
    "user": "abc123"
  },
  "tool_resources": {}
}


###### request

####### curl

curl https://api.openai.com/v1/threads/thread_abc123 \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "OpenAI-Beta: assistants=v2" \
  -d '{
      "metadata": {
        "modified": "true",
        "user": "abc123"
      }
    }'


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
thread = client.beta.threads.update(
    thread_id="thread_id",
)
print(thread.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const thread = await client.beta.threads.update('thread_id');

console.log(thread.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  thread, err := client.Beta.Threads.Update(
    context.TODO(),
    "thread_id",
    openai.BetaThreadUpdateParams{

    },
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", thread.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.beta.threads.Thread;
import com.openai.models.beta.threads.ThreadUpdateParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        Thread thread = client.beta().threads().update("thread_id");
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

thread = openai.beta.threads.update("thread_id")

puts(thread)

#### description

Modifies a thread.

### delete

#### operationId

deleteThread

#### tags

- Assistants

#### summary

Delete thread

#### parameters

##### in

path

##### name

thread_id

##### required

true

##### schema

###### type

string

##### description

The ID of the thread to delete.


#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/DeleteThreadResponse

#### x-oaiMeta

##### name

Delete thread

##### group

threads

##### beta

true

##### returns

Deletion status

##### examples

###### response

{
  "id": "thread_abc123",
  "object": "thread.deleted",
  "deleted": true
}


###### request

####### curl

curl https://api.openai.com/v1/threads/thread_abc123 \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "OpenAI-Beta: assistants=v2" \
  -X DELETE


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
thread_deleted = client.beta.threads.delete(
    "thread_id",
)
print(thread_deleted.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const threadDeleted = await client.beta.threads.delete('thread_id');

console.log(threadDeleted.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  threadDeleted, err := client.Beta.Threads.Delete(context.TODO(), "thread_id")
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", threadDeleted.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.beta.threads.ThreadDeleteParams;
import com.openai.models.beta.threads.ThreadDeleted;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        ThreadDeleted threadDeleted = client.beta().threads().delete("thread_id");
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

thread_deleted = openai.beta.threads.delete("thread_id")

puts(thread_deleted)

#### description

Delete a thread.

## /threads/{thread_id}/messages

### get

#### operationId

listMessages

#### tags

- Assistants

#### summary

List messages

#### parameters

##### in

path

##### name

thread_id

##### required

true

##### schema

###### type

string

##### description

The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) the messages belong to.

##### name

limit

##### in

query

##### description

A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20.


##### required

false

##### schema

###### type

integer

###### default

20

##### name

order

##### in

query

##### description

Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order.


##### schema

###### type

string

###### default

desc

###### enum

- asc
- desc

##### name

after

##### in

query

##### description

A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list.


##### schema

###### type

string

##### name

before

##### in

query

##### description

A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list.


##### schema

###### type

string

##### name

run_id

##### in

query

##### description

Filter messages by the run ID that generated them.


##### schema

###### type

string


#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ListMessagesResponse

#### x-oaiMeta

##### name

List messages

##### group

threads

##### beta

true

##### returns

A list of [message](https://platform.openai.com/docs/api-reference/messages) objects.

##### examples

###### response

{
  "object": "list",
  "data": [
    {
      "id": "msg_abc123",
      "object": "thread.message",
      "created_at": 1699016383,
      "assistant_id": null,
      "thread_id": "thread_abc123",
      "run_id": null,
      "role": "user",
      "content": [
        {
          "type": "text",
          "text": {
            "value": "How does AI work? Explain it in simple terms.",
            "annotations": []
          }
        }
      ],
      "attachments": [],
      "metadata": {}
    },
    {
      "id": "msg_abc456",
      "object": "thread.message",
      "created_at": 1699016383,
      "assistant_id": null,
      "thread_id": "thread_abc123",
      "run_id": null,
      "role": "user",
      "content": [
        {
          "type": "text",
          "text": {
            "value": "Hello, what is AI?",
            "annotations": []
          }
        }
      ],
      "attachments": [],
      "metadata": {}
    }
  ],
  "first_id": "msg_abc123",
  "last_id": "msg_abc456",
  "has_more": false
}


###### request

####### curl

curl https://api.openai.com/v1/threads/thread_abc123/messages \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "OpenAI-Beta: assistants=v2"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
page = client.beta.threads.messages.list(
    thread_id="thread_id",
)
page = page.data[0]
print(page.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

// Automatically fetches more pages as needed.
for await (const message of client.beta.threads.messages.list('thread_id')) {
  console.log(message.id);
}

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  page, err := client.Beta.Threads.Messages.List(
    context.TODO(),
    "thread_id",
    openai.BetaThreadMessageListParams{

    },
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", page)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.beta.threads.messages.MessageListPage;
import com.openai.models.beta.threads.messages.MessageListParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        MessageListPage page = client.beta().threads().messages().list("thread_id");
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

page = openai.beta.threads.messages.list("thread_id")

puts(page)

#### description

Returns a list of messages for a given thread.

### post

#### operationId

createMessage

#### tags

- Assistants

#### summary

Create message

#### parameters

##### in

path

##### name

thread_id

##### required

true

##### schema

###### type

string

##### description

The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) to create a message for.


#### requestBody

##### required

true

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/CreateMessageRequest

#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/MessageObject

#### x-oaiMeta

##### name

Create message

##### group

threads

##### beta

true

##### returns

A [message](https://platform.openai.com/docs/api-reference/messages/object) object.

##### examples

###### response

{
  "id": "msg_abc123",
  "object": "thread.message",
  "created_at": 1713226573,
  "assistant_id": null,
  "thread_id": "thread_abc123",
  "run_id": null,
  "role": "user",
  "content": [
    {
      "type": "text",
      "text": {
        "value": "How does AI work? Explain it in simple terms.",
        "annotations": []
      }
    }
  ],
  "attachments": [],
  "metadata": {}
}


###### request

####### curl

curl https://api.openai.com/v1/threads/thread_abc123/messages \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "OpenAI-Beta: assistants=v2" \
  -d '{
      "role": "user",
      "content": "How does AI work? Explain it in simple terms."
    }'


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
message = client.beta.threads.messages.create(
    thread_id="thread_id",
    content="string",
    role="user",
)
print(message.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const message = await client.beta.threads.messages.create('thread_id', { content: 'string', role: 'user' });

console.log(message.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  message, err := client.Beta.Threads.Messages.New(
    context.TODO(),
    "thread_id",
    openai.BetaThreadMessageNewParams{
      Content: openai.BetaThreadMessageNewParamsContentUnion{
        OfString: openai.String("string"),
      },
      Role: openai.BetaThreadMessageNewParamsRoleUser,
    },
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", message.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.beta.threads.messages.Message;
import com.openai.models.beta.threads.messages.MessageCreateParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        MessageCreateParams params = MessageCreateParams.builder()
            .threadId("thread_id")
            .content("string")
            .role(MessageCreateParams.Role.USER)
            .build();
        Message message = client.beta().threads().messages().create(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

message = openai.beta.threads.messages.create("thread_id", content: "string", role: :user)

puts(message)

#### description

Create a message.

## /threads/{thread_id}/messages/{message_id}

### get

#### operationId

getMessage

#### tags

- Assistants

#### summary

Retrieve message

#### parameters

##### in

path

##### name

thread_id

##### required

true

##### schema

###### type

string

##### description

The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) to which this message belongs.

##### in

path

##### name

message_id

##### required

true

##### schema

###### type

string

##### description

The ID of the message to retrieve.


#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/MessageObject

#### x-oaiMeta

##### name

Retrieve message

##### group

threads

##### beta

true

##### returns

The [message](https://platform.openai.com/docs/api-reference/messages/object) object matching the specified ID.

##### examples

###### response

{
  "id": "msg_abc123",
  "object": "thread.message",
  "created_at": 1699017614,
  "assistant_id": null,
  "thread_id": "thread_abc123",
  "run_id": null,
  "role": "user",
  "content": [
    {
      "type": "text",
      "text": {
        "value": "How does AI work? Explain it in simple terms.",
        "annotations": []
      }
    }
  ],
  "attachments": [],
  "metadata": {}
}


###### request

####### curl

curl https://api.openai.com/v1/threads/thread_abc123/messages/msg_abc123 \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "OpenAI-Beta: assistants=v2"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
message = client.beta.threads.messages.retrieve(
    message_id="message_id",
    thread_id="thread_id",
)
print(message.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const message = await client.beta.threads.messages.retrieve('message_id', { thread_id: 'thread_id' });

console.log(message.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  message, err := client.Beta.Threads.Messages.Get(
    context.TODO(),
    "thread_id",
    "message_id",
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", message.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.beta.threads.messages.Message;
import com.openai.models.beta.threads.messages.MessageRetrieveParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        MessageRetrieveParams params = MessageRetrieveParams.builder()
            .threadId("thread_id")
            .messageId("message_id")
            .build();
        Message message = client.beta().threads().messages().retrieve(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

message = openai.beta.threads.messages.retrieve("message_id", thread_id: "thread_id")

puts(message)

#### description

Retrieve a message.

### post

#### operationId

modifyMessage

#### tags

- Assistants

#### summary

Modify message

#### parameters

##### in

path

##### name

thread_id

##### required

true

##### schema

###### type

string

##### description

The ID of the thread to which this message belongs.

##### in

path

##### name

message_id

##### required

true

##### schema

###### type

string

##### description

The ID of the message to modify.


#### requestBody

##### required

true

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/ModifyMessageRequest

#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/MessageObject

#### x-oaiMeta

##### name

Modify message

##### group

threads

##### beta

true

##### returns

The modified [message](https://platform.openai.com/docs/api-reference/messages/object) object.

##### examples

###### response

{
  "id": "msg_abc123",
  "object": "thread.message",
  "created_at": 1699017614,
  "assistant_id": null,
  "thread_id": "thread_abc123",
  "run_id": null,
  "role": "user",
  "content": [
    {
      "type": "text",
      "text": {
        "value": "How does AI work? Explain it in simple terms.",
        "annotations": []
      }
    }
  ],
  "file_ids": [],
  "metadata": {
    "modified": "true",
    "user": "abc123"
  }
}


###### request

####### curl

curl https://api.openai.com/v1/threads/thread_abc123/messages/msg_abc123 \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "OpenAI-Beta: assistants=v2" \
  -d '{
      "metadata": {
        "modified": "true",
        "user": "abc123"
      }
    }'


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
message = client.beta.threads.messages.update(
    message_id="message_id",
    thread_id="thread_id",
)
print(message.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const message = await client.beta.threads.messages.update('message_id', { thread_id: 'thread_id' });

console.log(message.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  message, err := client.Beta.Threads.Messages.Update(
    context.TODO(),
    "thread_id",
    "message_id",
    openai.BetaThreadMessageUpdateParams{

    },
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", message.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.beta.threads.messages.Message;
import com.openai.models.beta.threads.messages.MessageUpdateParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        MessageUpdateParams params = MessageUpdateParams.builder()
            .threadId("thread_id")
            .messageId("message_id")
            .build();
        Message message = client.beta().threads().messages().update(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

message = openai.beta.threads.messages.update("message_id", thread_id: "thread_id")

puts(message)

#### description

Modifies a message.

### delete

#### operationId

deleteMessage

#### tags

- Assistants

#### summary

Delete message

#### parameters

##### in

path

##### name

thread_id

##### required

true

##### schema

###### type

string

##### description

The ID of the thread to which this message belongs.

##### in

path

##### name

message_id

##### required

true

##### schema

###### type

string

##### description

The ID of the message to delete.


#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/DeleteMessageResponse

#### x-oaiMeta

##### name

Delete message

##### group

threads

##### beta

true

##### returns

Deletion status

##### examples

###### response

{
  "id": "msg_abc123",
  "object": "thread.message.deleted",
  "deleted": true
}


###### request

####### curl

curl -X DELETE https://api.openai.com/v1/threads/thread_abc123/messages/msg_abc123 \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "OpenAI-Beta: assistants=v2"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
message_deleted = client.beta.threads.messages.delete(
    message_id="message_id",
    thread_id="thread_id",
)
print(message_deleted.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const messageDeleted = await client.beta.threads.messages.delete('message_id', { thread_id: 'thread_id' });

console.log(messageDeleted.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  messageDeleted, err := client.Beta.Threads.Messages.Delete(
    context.TODO(),
    "thread_id",
    "message_id",
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", messageDeleted.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.beta.threads.messages.MessageDeleteParams;
import com.openai.models.beta.threads.messages.MessageDeleted;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        MessageDeleteParams params = MessageDeleteParams.builder()
            .threadId("thread_id")
            .messageId("message_id")
            .build();
        MessageDeleted messageDeleted = client.beta().threads().messages().delete(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

message_deleted = openai.beta.threads.messages.delete("message_id", thread_id: "thread_id")

puts(message_deleted)

#### description

Deletes a message.

## /threads/{thread_id}/runs

### get

#### operationId

listRuns

#### tags

- Assistants

#### summary

List runs

#### parameters

##### name

thread_id

##### in

path

##### required

true

##### schema

###### type

string

##### description

The ID of the thread the run belongs to.

##### name

limit

##### in

query

##### description

A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20.


##### required

false

##### schema

###### type

integer

###### default

20

##### name

order

##### in

query

##### description

Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order.


##### schema

###### type

string

###### default

desc

###### enum

- asc
- desc

##### name

after

##### in

query

##### description

A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list.


##### schema

###### type

string

##### name

before

##### in

query

##### description

A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list.


##### schema

###### type

string


#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ListRunsResponse

#### x-oaiMeta

##### name

List runs

##### group

threads

##### beta

true

##### returns

A list of [run](https://platform.openai.com/docs/api-reference/runs/object) objects.

##### examples

###### response

{
  "object": "list",
  "data": [
    {
      "id": "run_abc123",
      "object": "thread.run",
      "created_at": 1699075072,
      "assistant_id": "asst_abc123",
      "thread_id": "thread_abc123",
      "status": "completed",
      "started_at": 1699075072,
      "expires_at": null,
      "cancelled_at": null,
      "failed_at": null,
      "completed_at": 1699075073,
      "last_error": null,
      "model": "gpt-4o",
      "instructions": null,
      "incomplete_details": null,
      "tools": [
        {
          "type": "code_interpreter"
        }
      ],
      "tool_resources": {
        "code_interpreter": {
          "file_ids": [
            "file-abc123",
            "file-abc456"
          ]
        }
      },
      "metadata": {},
      "usage": {
        "prompt_tokens": 123,
        "completion_tokens": 456,
        "total_tokens": 579
      },
      "temperature": 1.0,
      "top_p": 1.0,
      "max_prompt_tokens": 1000,
      "max_completion_tokens": 1000,
      "truncation_strategy": {
        "type": "auto",
        "last_messages": null
      },
      "response_format": "auto",
      "tool_choice": "auto",
      "parallel_tool_calls": true
    },
    {
      "id": "run_abc456",
      "object": "thread.run",
      "created_at": 1699063290,
      "assistant_id": "asst_abc123",
      "thread_id": "thread_abc123",
      "status": "completed",
      "started_at": 1699063290,
      "expires_at": null,
      "cancelled_at": null,
      "failed_at": null,
      "completed_at": 1699063291,
      "last_error": null,
      "model": "gpt-4o",
      "instructions": null,
      "incomplete_details": null,
      "tools": [
        {
          "type": "code_interpreter"
        }
      ],
      "tool_resources": {
        "code_interpreter": {
          "file_ids": [
            "file-abc123",
            "file-abc456"
          ]
        }
      },
      "metadata": {},
      "usage": {
        "prompt_tokens": 123,
        "completion_tokens": 456,
        "total_tokens": 579
      },
      "temperature": 1.0,
      "top_p": 1.0,
      "max_prompt_tokens": 1000,
      "max_completion_tokens": 1000,
      "truncation_strategy": {
        "type": "auto",
        "last_messages": null
      },
      "response_format": "auto",
      "tool_choice": "auto",
      "parallel_tool_calls": true
    }
  ],
  "first_id": "run_abc123",
  "last_id": "run_abc456",
  "has_more": false
}


###### request

####### curl

curl https://api.openai.com/v1/threads/thread_abc123/runs \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -H "OpenAI-Beta: assistants=v2"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
page = client.beta.threads.runs.list(
    thread_id="thread_id",
)
page = page.data[0]
print(page.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

// Automatically fetches more pages as needed.
for await (const run of client.beta.threads.runs.list('thread_id')) {
  console.log(run.id);
}

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  page, err := client.Beta.Threads.Runs.List(
    context.TODO(),
    "thread_id",
    openai.BetaThreadRunListParams{

    },
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", page)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.beta.threads.runs.RunListPage;
import com.openai.models.beta.threads.runs.RunListParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        RunListPage page = client.beta().threads().runs().list("thread_id");
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

page = openai.beta.threads.runs.list("thread_id")

puts(page)

#### description

Returns a list of runs belonging to a thread.

### post

#### operationId

createRun

#### tags

- Assistants

#### summary

Create run

#### parameters

##### in

path

##### name

thread_id

##### required

true

##### schema

###### type

string

##### description

The ID of the thread to run.

##### name

include[]

##### in

query

##### description

A list of additional fields to include in the response. Currently the only supported value is `step_details.tool_calls[*].file_search.results[*].content` to fetch the file search result content.

See the [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) for more information.


##### schema

###### type

array

###### items

####### type

string

####### enum

- step_details.tool_calls[*].file_search.results[*].content


#### requestBody

##### required

true

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/CreateRunRequest

#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/RunObject

#### x-oaiMeta

##### name

Create run

##### group

threads

##### beta

true

##### returns

A [run](https://platform.openai.com/docs/api-reference/runs/object) object.

##### examples

###### title

Default

###### request

####### curl

curl https://api.openai.com/v1/threads/thread_abc123/runs \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -H "OpenAI-Beta: assistants=v2" \
  -d '{
    "assistant_id": "asst_abc123"
  }'


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
run = client.beta.threads.runs.create(
    thread_id="thread_id",
    assistant_id="assistant_id",
)
print(run.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const run = await client.beta.threads.runs.create('thread_id', { assistant_id: 'assistant_id' });

console.log(run.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  run, err := client.Beta.Threads.Runs.New(
    context.TODO(),
    "thread_id",
    openai.BetaThreadRunNewParams{
      AssistantID: "assistant_id",
    },
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", run.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.beta.threads.runs.Run;
import com.openai.models.beta.threads.runs.RunCreateParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        RunCreateParams params = RunCreateParams.builder()
            .threadId("thread_id")
            .assistantId("assistant_id")
            .build();
        Run run = client.beta().threads().runs().create(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

run = openai.beta.threads.runs.create("thread_id", assistant_id: "assistant_id")

puts(run)

###### response

{
  "id": "run_abc123",
  "object": "thread.run",
  "created_at": 1699063290,
  "assistant_id": "asst_abc123",
  "thread_id": "thread_abc123",
  "status": "queued",
  "started_at": 1699063290,
  "expires_at": null,
  "cancelled_at": null,
  "failed_at": null,
  "completed_at": 1699063291,
  "last_error": null,
  "model": "gpt-4o",
  "instructions": null,
  "incomplete_details": null,
  "tools": [
    {
      "type": "code_interpreter"
    }
  ],
  "metadata": {},
  "usage": null,
  "temperature": 1.0,
  "top_p": 1.0,
  "max_prompt_tokens": 1000,
  "max_completion_tokens": 1000,
  "truncation_strategy": {
    "type": "auto",
    "last_messages": null
  },
  "response_format": "auto",
  "tool_choice": "auto",
  "parallel_tool_calls": true
}


###### title

Streaming

###### request

####### curl

curl https://api.openai.com/v1/threads/thread_123/runs \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -H "OpenAI-Beta: assistants=v2" \
  -d '{
    "assistant_id": "asst_123",
    "stream": true
  }'


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
run = client.beta.threads.runs.create(
    thread_id="thread_id",
    assistant_id="assistant_id",
)
print(run.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const run = await client.beta.threads.runs.create('thread_id', { assistant_id: 'assistant_id' });

console.log(run.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  run, err := client.Beta.Threads.Runs.New(
    context.TODO(),
    "thread_id",
    openai.BetaThreadRunNewParams{
      AssistantID: "assistant_id",
    },
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", run.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.beta.threads.runs.Run;
import com.openai.models.beta.threads.runs.RunCreateParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        RunCreateParams params = RunCreateParams.builder()
            .threadId("thread_id")
            .assistantId("assistant_id")
            .build();
        Run run = client.beta().threads().runs().create(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

run = openai.beta.threads.runs.create("thread_id", assistant_id: "assistant_id")

puts(run)

###### response

event: thread.run.created
data: {"id":"run_123","object":"thread.run","created_at":1710330640,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710331240,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}}

event: thread.run.queued
data: {"id":"run_123","object":"thread.run","created_at":1710330640,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710331240,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}}

event: thread.run.in_progress
data: {"id":"run_123","object":"thread.run","created_at":1710330640,"assistant_id":"asst_123","thread_id":"thread_123","status":"in_progress","started_at":1710330641,"expires_at":1710331240,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}}

event: thread.run.step.created
data: {"id":"step_001","object":"thread.run.step","created_at":1710330641,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710331240,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":null}

event: thread.run.step.in_progress
data: {"id":"step_001","object":"thread.run.step","created_at":1710330641,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710331240,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":null}

event: thread.message.created
data: {"id":"msg_001","object":"thread.message","created_at":1710330641,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"in_progress","incomplete_details":null,"incomplete_at":null,"completed_at":null,"role":"assistant","content":[],"metadata":{}}

event: thread.message.in_progress
data: {"id":"msg_001","object":"thread.message","created_at":1710330641,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"in_progress","incomplete_details":null,"incomplete_at":null,"completed_at":null,"role":"assistant","content":[],"metadata":{}}

event: thread.message.delta
data: {"id":"msg_001","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":"Hello","annotations":[]}}]}}

...

event: thread.message.delta
data: {"id":"msg_001","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":" today"}}]}}

event: thread.message.delta
data: {"id":"msg_001","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":"?"}}]}}

event: thread.message.completed
data: {"id":"msg_001","object":"thread.message","created_at":1710330641,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"completed","incomplete_details":null,"incomplete_at":null,"completed_at":1710330642,"role":"assistant","content":[{"type":"text","text":{"value":"Hello! How can I assist you today?","annotations":[]}}],"metadata":{}}

event: thread.run.step.completed
data: {"id":"step_001","object":"thread.run.step","created_at":1710330641,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"completed","cancelled_at":null,"completed_at":1710330642,"expires_at":1710331240,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":{"prompt_tokens":20,"completion_tokens":11,"total_tokens":31}}

event: thread.run.completed
data: {"id":"run_123","object":"thread.run","created_at":1710330640,"assistant_id":"asst_123","thread_id":"thread_123","status":"completed","started_at":1710330641,"expires_at":null,"cancelled_at":null,"failed_at":null,"completed_at":1710330642,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":{"prompt_tokens":20,"completion_tokens":11,"total_tokens":31},"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}}

event: done
data: [DONE]


###### title

Streaming with Functions

###### request

####### curl

curl https://api.openai.com/v1/threads/thread_abc123/runs \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -H "OpenAI-Beta: assistants=v2" \
  -d '{
    "assistant_id": "asst_abc123",
    "tools": [
      {
        "type": "function",
        "function": {
          "name": "get_current_weather",
          "description": "Get the current weather in a given location",
          "parameters": {
            "type": "object",
            "properties": {
              "location": {
                "type": "string",
                "description": "The city and state, e.g. San Francisco, CA"
              },
              "unit": {
                "type": "string",
                "enum": ["celsius", "fahrenheit"]
              }
            },
            "required": ["location"]
          }
        }
      }
    ],
    "stream": true
  }'


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
run = client.beta.threads.runs.create(
    thread_id="thread_id",
    assistant_id="assistant_id",
)
print(run.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const run = await client.beta.threads.runs.create('thread_id', { assistant_id: 'assistant_id' });

console.log(run.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  run, err := client.Beta.Threads.Runs.New(
    context.TODO(),
    "thread_id",
    openai.BetaThreadRunNewParams{
      AssistantID: "assistant_id",
    },
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", run.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.beta.threads.runs.Run;
import com.openai.models.beta.threads.runs.RunCreateParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        RunCreateParams params = RunCreateParams.builder()
            .threadId("thread_id")
            .assistantId("assistant_id")
            .build();
        Run run = client.beta().threads().runs().create(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

run = openai.beta.threads.runs.create("thread_id", assistant_id: "assistant_id")

puts(run)

###### response

event: thread.run.created
data: {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710348675,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}}

event: thread.run.queued
data: {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710348675,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}}

event: thread.run.in_progress
data: {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"in_progress","started_at":1710348075,"expires_at":1710348675,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}}

event: thread.run.step.created
data: {"id":"step_001","object":"thread.run.step","created_at":1710348076,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710348675,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":null}

event: thread.run.step.in_progress
data: {"id":"step_001","object":"thread.run.step","created_at":1710348076,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710348675,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":null}

event: thread.message.created
data: {"id":"msg_001","object":"thread.message","created_at":1710348076,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"in_progress","incomplete_details":null,"incomplete_at":null,"completed_at":null,"role":"assistant","content":[],"metadata":{}}

event: thread.message.in_progress
data: {"id":"msg_001","object":"thread.message","created_at":1710348076,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"in_progress","incomplete_details":null,"incomplete_at":null,"completed_at":null,"role":"assistant","content":[],"metadata":{}}

event: thread.message.delta
data: {"id":"msg_001","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":"Hello","annotations":[]}}]}}

...

event: thread.message.delta
data: {"id":"msg_001","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":" today"}}]}}

event: thread.message.delta
data: {"id":"msg_001","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":"?"}}]}}

event: thread.message.completed
data: {"id":"msg_001","object":"thread.message","created_at":1710348076,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"completed","incomplete_details":null,"incomplete_at":null,"completed_at":1710348077,"role":"assistant","content":[{"type":"text","text":{"value":"Hello! How can I assist you today?","annotations":[]}}],"metadata":{}}

event: thread.run.step.completed
data: {"id":"step_001","object":"thread.run.step","created_at":1710348076,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"completed","cancelled_at":null,"completed_at":1710348077,"expires_at":1710348675,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":{"prompt_tokens":20,"completion_tokens":11,"total_tokens":31}}

event: thread.run.completed
data: {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"completed","started_at":1710348075,"expires_at":null,"cancelled_at":null,"failed_at":null,"completed_at":1710348077,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":{"prompt_tokens":20,"completion_tokens":11,"total_tokens":31},"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}}

event: done
data: [DONE]



#### description

Create a run.

## /threads/{thread_id}/runs/{run_id}

### get

#### operationId

getRun

#### tags

- Assistants

#### summary

Retrieve run

#### parameters

##### in

path

##### name

thread_id

##### required

true

##### schema

###### type

string

##### description

The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) that was run.

##### in

path

##### name

run_id

##### required

true

##### schema

###### type

string

##### description

The ID of the run to retrieve.


#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/RunObject

#### x-oaiMeta

##### name

Retrieve run

##### group

threads

##### beta

true

##### returns

The [run](https://platform.openai.com/docs/api-reference/runs/object) object matching the specified ID.

##### examples

###### response

{
  "id": "run_abc123",
  "object": "thread.run",
  "created_at": 1699075072,
  "assistant_id": "asst_abc123",
  "thread_id": "thread_abc123",
  "status": "completed",
  "started_at": 1699075072,
  "expires_at": null,
  "cancelled_at": null,
  "failed_at": null,
  "completed_at": 1699075073,
  "last_error": null,
  "model": "gpt-4o",
  "instructions": null,
  "incomplete_details": null,
  "tools": [
    {
      "type": "code_interpreter"
    }
  ],
  "metadata": {},
  "usage": {
    "prompt_tokens": 123,
    "completion_tokens": 456,
    "total_tokens": 579
  },
  "temperature": 1.0,
  "top_p": 1.0,
  "max_prompt_tokens": 1000,
  "max_completion_tokens": 1000,
  "truncation_strategy": {
    "type": "auto",
    "last_messages": null
  },
  "response_format": "auto",
  "tool_choice": "auto",
  "parallel_tool_calls": true
}


###### request

####### curl

curl https://api.openai.com/v1/threads/thread_abc123/runs/run_abc123 \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "OpenAI-Beta: assistants=v2"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
run = client.beta.threads.runs.retrieve(
    run_id="run_id",
    thread_id="thread_id",
)
print(run.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const run = await client.beta.threads.runs.retrieve('run_id', { thread_id: 'thread_id' });

console.log(run.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  run, err := client.Beta.Threads.Runs.Get(
    context.TODO(),
    "thread_id",
    "run_id",
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", run.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.beta.threads.runs.Run;
import com.openai.models.beta.threads.runs.RunRetrieveParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        RunRetrieveParams params = RunRetrieveParams.builder()
            .threadId("thread_id")
            .runId("run_id")
            .build();
        Run run = client.beta().threads().runs().retrieve(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

run = openai.beta.threads.runs.retrieve("run_id", thread_id: "thread_id")

puts(run)

#### description

Retrieves a run.

### post

#### operationId

modifyRun

#### tags

- Assistants

#### summary

Modify run

#### parameters

##### in

path

##### name

thread_id

##### required

true

##### schema

###### type

string

##### description

The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) that was run.

##### in

path

##### name

run_id

##### required

true

##### schema

###### type

string

##### description

The ID of the run to modify.


#### requestBody

##### required

true

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/ModifyRunRequest

#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/RunObject

#### x-oaiMeta

##### name

Modify run

##### group

threads

##### beta

true

##### returns

The modified [run](https://platform.openai.com/docs/api-reference/runs/object) object matching the specified ID.

##### examples

###### response

{
  "id": "run_abc123",
  "object": "thread.run",
  "created_at": 1699075072,
  "assistant_id": "asst_abc123",
  "thread_id": "thread_abc123",
  "status": "completed",
  "started_at": 1699075072,
  "expires_at": null,
  "cancelled_at": null,
  "failed_at": null,
  "completed_at": 1699075073,
  "last_error": null,
  "model": "gpt-4o",
  "instructions": null,
  "incomplete_details": null,
  "tools": [
    {
      "type": "code_interpreter"
    }
  ],
  "tool_resources": {
    "code_interpreter": {
      "file_ids": [
        "file-abc123",
        "file-abc456"
      ]
    }
  },
  "metadata": {
    "user_id": "user_abc123"
  },
  "usage": {
    "prompt_tokens": 123,
    "completion_tokens": 456,
    "total_tokens": 579
  },
  "temperature": 1.0,
  "top_p": 1.0,
  "max_prompt_tokens": 1000,
  "max_completion_tokens": 1000,
  "truncation_strategy": {
    "type": "auto",
    "last_messages": null
  },
  "response_format": "auto",
  "tool_choice": "auto",
  "parallel_tool_calls": true
}


###### request

####### curl

curl https://api.openai.com/v1/threads/thread_abc123/runs/run_abc123 \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -H "OpenAI-Beta: assistants=v2" \
  -d '{
    "metadata": {
      "user_id": "user_abc123"
    }
  }'


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
run = client.beta.threads.runs.update(
    run_id="run_id",
    thread_id="thread_id",
)
print(run.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const run = await client.beta.threads.runs.update('run_id', { thread_id: 'thread_id' });

console.log(run.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  run, err := client.Beta.Threads.Runs.Update(
    context.TODO(),
    "thread_id",
    "run_id",
    openai.BetaThreadRunUpdateParams{

    },
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", run.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.beta.threads.runs.Run;
import com.openai.models.beta.threads.runs.RunUpdateParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        RunUpdateParams params = RunUpdateParams.builder()
            .threadId("thread_id")
            .runId("run_id")
            .build();
        Run run = client.beta().threads().runs().update(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

run = openai.beta.threads.runs.update("run_id", thread_id: "thread_id")

puts(run)

#### description

Modifies a run.

## /threads/{thread_id}/runs/{run_id}/cancel

### post

#### operationId

cancelRun

#### tags

- Assistants

#### summary

Cancel a run

#### parameters

##### in

path

##### name

thread_id

##### required

true

##### schema

###### type

string

##### description

The ID of the thread to which this run belongs.

##### in

path

##### name

run_id

##### required

true

##### schema

###### type

string

##### description

The ID of the run to cancel.


#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/RunObject

#### x-oaiMeta

##### name

Cancel a run

##### group

threads

##### beta

true

##### returns

The modified [run](https://platform.openai.com/docs/api-reference/runs/object) object matching the specified ID.

##### examples

###### response

{
  "id": "run_abc123",
  "object": "thread.run",
  "created_at": 1699076126,
  "assistant_id": "asst_abc123",
  "thread_id": "thread_abc123",
  "status": "cancelling",
  "started_at": 1699076126,
  "expires_at": 1699076726,
  "cancelled_at": null,
  "failed_at": null,
  "completed_at": null,
  "last_error": null,
  "model": "gpt-4o",
  "instructions": "You summarize books.",
  "tools": [
    {
      "type": "file_search"
    }
  ],
  "tool_resources": {
    "file_search": {
      "vector_store_ids": ["vs_123"]
    }
  },
  "metadata": {},
  "usage": null,
  "temperature": 1.0,
  "top_p": 1.0,
  "response_format": "auto",
  "tool_choice": "auto",
  "parallel_tool_calls": true
}


###### request

####### curl

curl https://api.openai.com/v1/threads/thread_abc123/runs/run_abc123/cancel \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "OpenAI-Beta: assistants=v2" \
  -X POST


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
run = client.beta.threads.runs.cancel(
    run_id="run_id",
    thread_id="thread_id",
)
print(run.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const run = await client.beta.threads.runs.cancel('run_id', { thread_id: 'thread_id' });

console.log(run.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  run, err := client.Beta.Threads.Runs.Cancel(
    context.TODO(),
    "thread_id",
    "run_id",
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", run.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.beta.threads.runs.Run;
import com.openai.models.beta.threads.runs.RunCancelParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        RunCancelParams params = RunCancelParams.builder()
            .threadId("thread_id")
            .runId("run_id")
            .build();
        Run run = client.beta().threads().runs().cancel(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

run = openai.beta.threads.runs.cancel("run_id", thread_id: "thread_id")

puts(run)

#### description

Cancels a run that is `in_progress`.

## /threads/{thread_id}/runs/{run_id}/steps

### get

#### operationId

listRunSteps

#### tags

- Assistants

#### summary

List run steps

#### parameters

##### name

thread_id

##### in

path

##### required

true

##### schema

###### type

string

##### description

The ID of the thread the run and run steps belong to.

##### name

run_id

##### in

path

##### required

true

##### schema

###### type

string

##### description

The ID of the run the run steps belong to.

##### name

limit

##### in

query

##### description

A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20.


##### required

false

##### schema

###### type

integer

###### default

20

##### name

order

##### in

query

##### description

Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order.


##### schema

###### type

string

###### default

desc

###### enum

- asc
- desc

##### name

after

##### in

query

##### description

A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list.


##### schema

###### type

string

##### name

before

##### in

query

##### description

A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list.


##### schema

###### type

string

##### name

include[]

##### in

query

##### description

A list of additional fields to include in the response. Currently the only supported value is `step_details.tool_calls[*].file_search.results[*].content` to fetch the file search result content.

See the [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) for more information.


##### schema

###### type

array

###### items

####### type

string

####### enum

- step_details.tool_calls[*].file_search.results[*].content


#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ListRunStepsResponse

#### x-oaiMeta

##### name

List run steps

##### group

threads

##### beta

true

##### returns

A list of [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) objects.

##### examples

###### response

{
  "object": "list",
  "data": [
    {
      "id": "step_abc123",
      "object": "thread.run.step",
      "created_at": 1699063291,
      "run_id": "run_abc123",
      "assistant_id": "asst_abc123",
      "thread_id": "thread_abc123",
      "type": "message_creation",
      "status": "completed",
      "cancelled_at": null,
      "completed_at": 1699063291,
      "expired_at": null,
      "failed_at": null,
      "last_error": null,
      "step_details": {
        "type": "message_creation",
        "message_creation": {
          "message_id": "msg_abc123"
        }
      },
      "usage": {
        "prompt_tokens": 123,
        "completion_tokens": 456,
        "total_tokens": 579
      }
    }
  ],
  "first_id": "step_abc123",
  "last_id": "step_abc456",
  "has_more": false
}


###### request

####### curl

curl https://api.openai.com/v1/threads/thread_abc123/runs/run_abc123/steps \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -H "OpenAI-Beta: assistants=v2"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
page = client.beta.threads.runs.steps.list(
    run_id="run_id",
    thread_id="thread_id",
)
page = page.data[0]
print(page.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

// Automatically fetches more pages as needed.
for await (const runStep of client.beta.threads.runs.steps.list('run_id', { thread_id: 'thread_id' })) {
  console.log(runStep.id);
}

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  page, err := client.Beta.Threads.Runs.Steps.List(
    context.TODO(),
    "thread_id",
    "run_id",
    openai.BetaThreadRunStepListParams{

    },
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", page)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.beta.threads.runs.steps.StepListPage;
import com.openai.models.beta.threads.runs.steps.StepListParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        StepListParams params = StepListParams.builder()
            .threadId("thread_id")
            .runId("run_id")
            .build();
        StepListPage page = client.beta().threads().runs().steps().list(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

page = openai.beta.threads.runs.steps.list("run_id", thread_id: "thread_id")

puts(page)

#### description

Returns a list of run steps belonging to a run.

## /threads/{thread_id}/runs/{run_id}/steps/{step_id}

### get

#### operationId

getRunStep

#### tags

- Assistants

#### summary

Retrieve run step

#### parameters

##### in

path

##### name

thread_id

##### required

true

##### schema

###### type

string

##### description

The ID of the thread to which the run and run step belongs.

##### in

path

##### name

run_id

##### required

true

##### schema

###### type

string

##### description

The ID of the run to which the run step belongs.

##### in

path

##### name

step_id

##### required

true

##### schema

###### type

string

##### description

The ID of the run step to retrieve.

##### name

include[]

##### in

query

##### description

A list of additional fields to include in the response. Currently the only supported value is `step_details.tool_calls[*].file_search.results[*].content` to fetch the file search result content.

See the [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) for more information.


##### schema

###### type

array

###### items

####### type

string

####### enum

- step_details.tool_calls[*].file_search.results[*].content


#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/RunStepObject

#### x-oaiMeta

##### name

Retrieve run step

##### group

threads

##### beta

true

##### returns

The [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) object matching the specified ID.

##### examples

###### response

{
  "id": "step_abc123",
  "object": "thread.run.step",
  "created_at": 1699063291,
  "run_id": "run_abc123",
  "assistant_id": "asst_abc123",
  "thread_id": "thread_abc123",
  "type": "message_creation",
  "status": "completed",
  "cancelled_at": null,
  "completed_at": 1699063291,
  "expired_at": null,
  "failed_at": null,
  "last_error": null,
  "step_details": {
    "type": "message_creation",
    "message_creation": {
      "message_id": "msg_abc123"
    }
  },
  "usage": {
    "prompt_tokens": 123,
    "completion_tokens": 456,
    "total_tokens": 579
  }
}


###### request

####### curl

curl https://api.openai.com/v1/threads/thread_abc123/runs/run_abc123/steps/step_abc123 \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -H "OpenAI-Beta: assistants=v2"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
run_step = client.beta.threads.runs.steps.retrieve(
    step_id="step_id",
    thread_id="thread_id",
    run_id="run_id",
)
print(run_step.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const runStep = await client.beta.threads.runs.steps.retrieve('step_id', {
  thread_id: 'thread_id',
  run_id: 'run_id',
});

console.log(runStep.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  runStep, err := client.Beta.Threads.Runs.Steps.Get(
    context.TODO(),
    "thread_id",
    "run_id",
    "step_id",
    openai.BetaThreadRunStepGetParams{

    },
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", runStep.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.beta.threads.runs.steps.RunStep;
import com.openai.models.beta.threads.runs.steps.StepRetrieveParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        StepRetrieveParams params = StepRetrieveParams.builder()
            .threadId("thread_id")
            .runId("run_id")
            .stepId("step_id")
            .build();
        RunStep runStep = client.beta().threads().runs().steps().retrieve(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

run_step = openai.beta.threads.runs.steps.retrieve("step_id", thread_id: "thread_id", run_id: "run_id")

puts(run_step)

#### description

Retrieves a run step.

## /threads/{thread_id}/runs/{run_id}/submit_tool_outputs

### post

#### operationId

submitToolOuputsToRun

#### tags

- Assistants

#### summary

Submit tool outputs to run

#### parameters

##### in

path

##### name

thread_id

##### required

true

##### schema

###### type

string

##### description

The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) to which this run belongs.

##### in

path

##### name

run_id

##### required

true

##### schema

###### type

string

##### description

The ID of the run that requires the tool output submission.


#### requestBody

##### required

true

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/SubmitToolOutputsRunRequest

#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/RunObject

#### x-oaiMeta

##### name

Submit tool outputs to run

##### group

threads

##### beta

true

##### returns

The modified [run](https://platform.openai.com/docs/api-reference/runs/object) object matching the specified ID.

##### examples

###### title

Default

###### request

####### curl

curl https://api.openai.com/v1/threads/thread_123/runs/run_123/submit_tool_outputs \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -H "OpenAI-Beta: assistants=v2" \
  -d '{
    "tool_outputs": [
      {
        "tool_call_id": "call_001",
        "output": "70 degrees and sunny."
      }
    ]
  }'


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
run = client.beta.threads.runs.submit_tool_outputs(
    run_id="run_id",
    thread_id="thread_id",
    tool_outputs=[{}],
)
print(run.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const run = await client.beta.threads.runs.submitToolOutputs('run_id', {
  thread_id: 'thread_id',
  tool_outputs: [{}],
});

console.log(run.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  run, err := client.Beta.Threads.Runs.SubmitToolOutputs(
    context.TODO(),
    "thread_id",
    "run_id",
    openai.BetaThreadRunSubmitToolOutputsParams{
      ToolOutputs: []openai.BetaThreadRunSubmitToolOutputsParamsToolOutput{openai.BetaThreadRunSubmitToolOutputsParamsToolOutput{

      }},
    },
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", run.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.beta.threads.runs.Run;
import com.openai.models.beta.threads.runs.RunSubmitToolOutputsParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        RunSubmitToolOutputsParams params = RunSubmitToolOutputsParams.builder()
            .threadId("thread_id")
            .runId("run_id")
            .addToolOutput(RunSubmitToolOutputsParams.ToolOutput.builder().build())
            .build();
        Run run = client.beta().threads().runs().submitToolOutputs(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

run = openai.beta.threads.runs.submit_tool_outputs("run_id", thread_id: "thread_id", tool_outputs: [{}])

puts(run)

###### response

{
  "id": "run_123",
  "object": "thread.run",
  "created_at": 1699075592,
  "assistant_id": "asst_123",
  "thread_id": "thread_123",
  "status": "queued",
  "started_at": 1699075592,
  "expires_at": 1699076192,
  "cancelled_at": null,
  "failed_at": null,
  "completed_at": null,
  "last_error": null,
  "model": "gpt-4o",
  "instructions": null,
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "get_current_weather",
        "description": "Get the current weather in a given location",
        "parameters": {
          "type": "object",
          "properties": {
            "location": {
              "type": "string",
              "description": "The city and state, e.g. San Francisco, CA"
            },
            "unit": {
              "type": "string",
              "enum": ["celsius", "fahrenheit"]
            }
          },
          "required": ["location"]
        }
      }
    }
  ],
  "metadata": {},
  "usage": null,
  "temperature": 1.0,
  "top_p": 1.0,
  "max_prompt_tokens": 1000,
  "max_completion_tokens": 1000,
  "truncation_strategy": {
    "type": "auto",
    "last_messages": null
  },
  "response_format": "auto",
  "tool_choice": "auto",
  "parallel_tool_calls": true
}


###### title

Streaming

###### request

####### curl

curl https://api.openai.com/v1/threads/thread_123/runs/run_123/submit_tool_outputs \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -H "OpenAI-Beta: assistants=v2" \
  -d '{
    "tool_outputs": [
      {
        "tool_call_id": "call_001",
        "output": "70 degrees and sunny."
      }
    ],
    "stream": true
  }'


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
run = client.beta.threads.runs.submit_tool_outputs(
    run_id="run_id",
    thread_id="thread_id",
    tool_outputs=[{}],
)
print(run.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const run = await client.beta.threads.runs.submitToolOutputs('run_id', {
  thread_id: 'thread_id',
  tool_outputs: [{}],
});

console.log(run.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  run, err := client.Beta.Threads.Runs.SubmitToolOutputs(
    context.TODO(),
    "thread_id",
    "run_id",
    openai.BetaThreadRunSubmitToolOutputsParams{
      ToolOutputs: []openai.BetaThreadRunSubmitToolOutputsParamsToolOutput{openai.BetaThreadRunSubmitToolOutputsParamsToolOutput{

      }},
    },
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", run.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.beta.threads.runs.Run;
import com.openai.models.beta.threads.runs.RunSubmitToolOutputsParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        RunSubmitToolOutputsParams params = RunSubmitToolOutputsParams.builder()
            .threadId("thread_id")
            .runId("run_id")
            .addToolOutput(RunSubmitToolOutputsParams.ToolOutput.builder().build())
            .build();
        Run run = client.beta().threads().runs().submitToolOutputs(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

run = openai.beta.threads.runs.submit_tool_outputs("run_id", thread_id: "thread_id", tool_outputs: [{}])

puts(run)

###### response

event: thread.run.step.completed
data: {"id":"step_001","object":"thread.run.step","created_at":1710352449,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"tool_calls","status":"completed","cancelled_at":null,"completed_at":1710352475,"expires_at":1710353047,"failed_at":null,"last_error":null,"step_details":{"type":"tool_calls","tool_calls":[{"id":"call_iWr0kQ2EaYMaxNdl0v3KYkx7","type":"function","function":{"name":"get_current_weather","arguments":"{\"location\":\"San Francisco, CA\",\"unit\":\"fahrenheit\"}","output":"70 degrees and sunny."}}]},"usage":{"prompt_tokens":291,"completion_tokens":24,"total_tokens":315}}

event: thread.run.queued
data: {"id":"run_123","object":"thread.run","created_at":1710352447,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":1710352448,"expires_at":1710353047,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather in a given location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and state, e.g. San Francisco, CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}}

event: thread.run.in_progress
data: {"id":"run_123","object":"thread.run","created_at":1710352447,"assistant_id":"asst_123","thread_id":"thread_123","status":"in_progress","started_at":1710352475,"expires_at":1710353047,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather in a given location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and state, e.g. San Francisco, CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}}

event: thread.run.step.created
data: {"id":"step_002","object":"thread.run.step","created_at":1710352476,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710353047,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_002"}},"usage":null}

event: thread.run.step.in_progress
data: {"id":"step_002","object":"thread.run.step","created_at":1710352476,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710353047,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_002"}},"usage":null}

event: thread.message.created
data: {"id":"msg_002","object":"thread.message","created_at":1710352476,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"in_progress","incomplete_details":null,"incomplete_at":null,"completed_at":null,"role":"assistant","content":[],"metadata":{}}

event: thread.message.in_progress
data: {"id":"msg_002","object":"thread.message","created_at":1710352476,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"in_progress","incomplete_details":null,"incomplete_at":null,"completed_at":null,"role":"assistant","content":[],"metadata":{}}

event: thread.message.delta
data: {"id":"msg_002","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":"The","annotations":[]}}]}}

event: thread.message.delta
data: {"id":"msg_002","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":" current"}}]}}

event: thread.message.delta
data: {"id":"msg_002","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":" weather"}}]}}

...

event: thread.message.delta
data: {"id":"msg_002","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":" sunny"}}]}}

event: thread.message.delta
data: {"id":"msg_002","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":"."}}]}}

event: thread.message.completed
data: {"id":"msg_002","object":"thread.message","created_at":1710352476,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"completed","incomplete_details":null,"incomplete_at":null,"completed_at":1710352477,"role":"assistant","content":[{"type":"text","text":{"value":"The current weather in San Francisco, CA is 70 degrees Fahrenheit and sunny.","annotations":[]}}],"metadata":{}}

event: thread.run.step.completed
data: {"id":"step_002","object":"thread.run.step","created_at":1710352476,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"completed","cancelled_at":null,"completed_at":1710352477,"expires_at":1710353047,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_002"}},"usage":{"prompt_tokens":329,"completion_tokens":18,"total_tokens":347}}

event: thread.run.completed
data: {"id":"run_123","object":"thread.run","created_at":1710352447,"assistant_id":"asst_123","thread_id":"thread_123","status":"completed","started_at":1710352475,"expires_at":null,"cancelled_at":null,"failed_at":null,"completed_at":1710352477,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather in a given location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and state, e.g. San Francisco, CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":{"prompt_tokens":20,"completion_tokens":11,"total_tokens":31},"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}}

event: done
data: [DONE]



#### description

When a run has the `status: "requires_action"` and `required_action.type` is `submit_tool_outputs`, this endpoint can be used to submit the outputs from the tool calls once they're all completed. All outputs must be submitted in a single request.


## /uploads

### post

#### operationId

createUpload

#### tags

- Uploads

#### summary

Create upload

#### requestBody

##### required

true

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/CreateUploadRequest

#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/Upload

#### x-oaiMeta

##### name

Create upload

##### group

uploads

##### returns

The [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object with status `pending`.

##### examples

###### response

{
  "id": "upload_abc123",
  "object": "upload",
  "bytes": 2147483648,
  "created_at": 1719184911,
  "filename": "training_examples.jsonl",
  "purpose": "fine-tune",
  "status": "pending",
  "expires_at": 1719127296
}


###### request

####### curl

curl https://api.openai.com/v1/uploads \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "purpose": "fine-tune",
    "filename": "training_examples.jsonl",
    "bytes": 2147483648,
    "mime_type": "text/jsonl",
    "expires_after": {
      "anchor": "created_at",
      "seconds": 3600
    }
  }'


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const upload = await client.uploads.create({
  bytes: 0,
  filename: 'filename',
  mime_type: 'mime_type',
  purpose: 'assistants',
});

console.log(upload.id);

####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
upload = client.uploads.create(
    bytes=0,
    filename="filename",
    mime_type="mime_type",
    purpose="assistants",
)
print(upload.id)

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  upload, err := client.Uploads.New(context.TODO(), openai.UploadNewParams{
    Bytes: 0,
    Filename: "filename",
    MimeType: "mime_type",
    Purpose: openai.FilePurposeAssistants,
  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", upload.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.files.FilePurpose;
import com.openai.models.uploads.Upload;
import com.openai.models.uploads.UploadCreateParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        UploadCreateParams params = UploadCreateParams.builder()
            .bytes(0L)
            .filename("filename")
            .mimeType("mime_type")
            .purpose(FilePurpose.ASSISTANTS)
            .build();
        Upload upload = client.uploads().create(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

upload = openai.uploads.create(bytes: 0, filename: "filename", mime_type: "mime_type", purpose: :assistants)

puts(upload)

#### description

Creates an intermediate [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object
that you can add [Parts](https://platform.openai.com/docs/api-reference/uploads/part-object) to.
Currently, an Upload can accept at most 8 GB in total and expires after an
hour after you create it.

Once you complete the Upload, we will create a
[File](https://platform.openai.com/docs/api-reference/files/object) object that contains all the parts
you uploaded. This File is usable in the rest of our platform as a regular
File object.

For certain `purpose` values, the correct `mime_type` must be specified. 
Please refer to documentation for the 
[supported MIME types for your use case](https://platform.openai.com/docs/assistants/tools/file-search#supported-files).

For guidance on the proper filename extensions for each purpose, please
follow the documentation on [creating a
File](https://platform.openai.com/docs/api-reference/files/create).


## /uploads/{upload_id}/cancel

### post

#### operationId

cancelUpload

#### tags

- Uploads

#### summary

Cancel upload

#### parameters

##### in

path

##### name

upload_id

##### required

true

##### schema

###### type

string

###### example

upload_abc123

##### description

The ID of the Upload.



#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/Upload

#### x-oaiMeta

##### name

Cancel upload

##### group

uploads

##### returns

The [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object with status `cancelled`.

##### examples

###### response

{
  "id": "upload_abc123",
  "object": "upload",
  "bytes": 2147483648,
  "created_at": 1719184911,
  "filename": "training_examples.jsonl",
  "purpose": "fine-tune",
  "status": "cancelled",
  "expires_at": 1719127296
}


###### request

####### curl

curl https://api.openai.com/v1/uploads/upload_abc123/cancel


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const upload = await client.uploads.cancel('upload_abc123');

console.log(upload.id);

####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
upload = client.uploads.cancel(
    "upload_abc123",
)
print(upload.id)

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  upload, err := client.Uploads.Cancel(context.TODO(), "upload_abc123")
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", upload.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.uploads.Upload;
import com.openai.models.uploads.UploadCancelParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        Upload upload = client.uploads().cancel("upload_abc123");
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

upload = openai.uploads.cancel("upload_abc123")

puts(upload)

#### description

Cancels the Upload. No Parts may be added after an Upload is cancelled.


## /uploads/{upload_id}/complete

### post

#### operationId

completeUpload

#### tags

- Uploads

#### summary

Complete upload

#### parameters

##### in

path

##### name

upload_id

##### required

true

##### schema

###### type

string

###### example

upload_abc123

##### description

The ID of the Upload.



#### requestBody

##### required

true

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/CompleteUploadRequest

#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/Upload

#### x-oaiMeta

##### name

Complete upload

##### group

uploads

##### returns

The [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object with status `completed` with an additional `file` property containing the created usable File object.

##### examples

###### response

{
  "id": "upload_abc123",
  "object": "upload",
  "bytes": 2147483648,
  "created_at": 1719184911,
  "filename": "training_examples.jsonl",
  "purpose": "fine-tune",
  "status": "completed",
  "expires_at": 1719127296,
  "file": {
    "id": "file-xyz321",
    "object": "file",
    "bytes": 2147483648,
    "created_at": 1719186911,
    "expires_at": 1719127296,
    "filename": "training_examples.jsonl",
    "purpose": "fine-tune",
  }
}


###### request

####### curl

curl https://api.openai.com/v1/uploads/upload_abc123/complete
  -d '{
    "part_ids": ["part_def456", "part_ghi789"]
  }'


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const upload = await client.uploads.complete('upload_abc123', { part_ids: ['string'] });

console.log(upload.id);

####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
upload = client.uploads.complete(
    upload_id="upload_abc123",
    part_ids=["string"],
)
print(upload.id)

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  upload, err := client.Uploads.Complete(
    context.TODO(),
    "upload_abc123",
    openai.UploadCompleteParams{
      PartIDs: []string{"string"},
    },
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", upload.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.uploads.Upload;
import com.openai.models.uploads.UploadCompleteParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        UploadCompleteParams params = UploadCompleteParams.builder()
            .uploadId("upload_abc123")
            .addPartId("string")
            .build();
        Upload upload = client.uploads().complete(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

upload = openai.uploads.complete("upload_abc123", part_ids: ["string"])

puts(upload)

#### description

Completes the [Upload](https://platform.openai.com/docs/api-reference/uploads/object). 

Within the returned Upload object, there is a nested [File](https://platform.openai.com/docs/api-reference/files/object) object that is ready to use in the rest of the platform.

You can specify the order of the Parts by passing in an ordered list of the Part IDs.

The number of bytes uploaded upon completion must match the number of bytes initially specified when creating the Upload object. No Parts may be added after an Upload is completed.


## /uploads/{upload_id}/parts

### post

#### operationId

addUploadPart

#### tags

- Uploads

#### summary

Add upload part

#### parameters

##### in

path

##### name

upload_id

##### required

true

##### schema

###### type

string

###### example

upload_abc123

##### description

The ID of the Upload.



#### requestBody

##### required

true

##### content

###### multipart/form-data

####### schema

######## $ref

#/components/schemas/AddUploadPartRequest

#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/UploadPart

#### x-oaiMeta

##### name

Add upload part

##### group

uploads

##### returns

The upload [Part](https://platform.openai.com/docs/api-reference/uploads/part-object) object.

##### examples

###### response

{
  "id": "part_def456",
  "object": "upload.part",
  "created_at": 1719185911,
  "upload_id": "upload_abc123"
}


###### request

####### curl

curl https://api.openai.com/v1/uploads/upload_abc123/parts
  -F data="aHR0cHM6Ly9hcGkub3BlbmFpLmNvbS92MS91cGxvYWRz..."


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const uploadPart = await client.uploads.parts.create('upload_abc123', {
  data: fs.createReadStream('path/to/file'),
});

console.log(uploadPart.id);

####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
upload_part = client.uploads.parts.create(
    upload_id="upload_abc123",
    data=b"raw file contents",
)
print(upload_part.id)

####### go

package main

import (
  "bytes"
  "context"
  "fmt"
  "io"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  uploadPart, err := client.Uploads.Parts.New(
    context.TODO(),
    "upload_abc123",
    openai.UploadPartNewParams{
      Data: io.Reader(bytes.NewBuffer([]byte("some file contents"))),
    },
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", uploadPart.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.uploads.parts.PartCreateParams;
import com.openai.models.uploads.parts.UploadPart;
import java.io.ByteArrayInputStream;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        PartCreateParams params = PartCreateParams.builder()
            .uploadId("upload_abc123")
            .data(ByteArrayInputStream("some content".getBytes()))
            .build();
        UploadPart uploadPart = client.uploads().parts().create(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

upload_part = openai.uploads.parts.create("upload_abc123", data: Pathname(__FILE__))

puts(upload_part)

#### description

Adds a [Part](https://platform.openai.com/docs/api-reference/uploads/part-object) to an [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object. A Part represents a chunk of bytes from the file you are trying to upload. 

Each Part can be at most 64 MB, and you can add Parts until you hit the Upload maximum of 8 GB.

It is possible to add multiple Parts in parallel. You can decide the intended order of the Parts when you [complete the Upload](https://platform.openai.com/docs/api-reference/uploads/complete).


## /vector_stores

### get

#### operationId

listVectorStores

#### tags

- Vector stores

#### summary

List vector stores

#### parameters

##### name

limit

##### in

query

##### description

A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20.


##### required

false

##### schema

###### type

integer

###### default

20

##### name

order

##### in

query

##### description

Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order.


##### schema

###### type

string

###### default

desc

###### enum

- asc
- desc

##### name

after

##### in

query

##### description

A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list.


##### schema

###### type

string

##### name

before

##### in

query

##### description

A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list.


##### schema

###### type

string


#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ListVectorStoresResponse

#### x-oaiMeta

##### name

List vector stores

##### group

vector_stores

##### returns

A list of [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) objects.

##### examples

###### response

{
  "object": "list",
  "data": [
    {
      "id": "vs_abc123",
      "object": "vector_store",
      "created_at": 1699061776,
      "name": "Support FAQ",
      "bytes": 139920,
      "file_counts": {
        "in_progress": 0,
        "completed": 3,
        "failed": 0,
        "cancelled": 0,
        "total": 3
      }
    },
    {
      "id": "vs_abc456",
      "object": "vector_store",
      "created_at": 1699061776,
      "name": "Support FAQ v2",
      "bytes": 139920,
      "file_counts": {
        "in_progress": 0,
        "completed": 3,
        "failed": 0,
        "cancelled": 0,
        "total": 3
      }
    }
  ],
  "first_id": "vs_abc123",
  "last_id": "vs_abc456",
  "has_more": false
}


###### request

####### curl

curl https://api.openai.com/v1/vector_stores \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -H "OpenAI-Beta: assistants=v2"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
page = client.vector_stores.list()
page = page.data[0]
print(page.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

// Automatically fetches more pages as needed.
for await (const vectorStore of client.vectorStores.list()) {
  console.log(vectorStore.id);
}

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  page, err := client.VectorStores.List(context.TODO(), openai.VectorStoreListParams{

  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", page)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.vectorstores.VectorStoreListPage;
import com.openai.models.vectorstores.VectorStoreListParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        VectorStoreListPage page = client.vectorStores().list();
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

page = openai.vector_stores.list

puts(page)

#### description

Returns a list of vector stores.

### post

#### operationId

createVectorStore

#### tags

- Vector stores

#### summary

Create vector store

#### requestBody

##### required

true

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/CreateVectorStoreRequest

#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/VectorStoreObject

#### x-oaiMeta

##### name

Create vector store

##### group

vector_stores

##### returns

A [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) object.

##### examples

###### response

{
  "id": "vs_abc123",
  "object": "vector_store",
  "created_at": 1699061776,
  "name": "Support FAQ",
  "bytes": 139920,
  "file_counts": {
    "in_progress": 0,
    "completed": 3,
    "failed": 0,
    "cancelled": 0,
    "total": 3
  }
}


###### request

####### curl

curl https://api.openai.com/v1/vector_stores \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -H "OpenAI-Beta: assistants=v2" \
  -d '{
    "name": "Support FAQ"
  }'


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
vector_store = client.vector_stores.create()
print(vector_store.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const vectorStore = await client.vectorStores.create();

console.log(vectorStore.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  vectorStore, err := client.VectorStores.New(context.TODO(), openai.VectorStoreNewParams{

  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", vectorStore.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.vectorstores.VectorStore;
import com.openai.models.vectorstores.VectorStoreCreateParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        VectorStore vectorStore = client.vectorStores().create();
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

vector_store = openai.vector_stores.create

puts(vector_store)

#### description

Create a vector store.

## /vector_stores/{vector_store_id}

### get

#### operationId

getVectorStore

#### tags

- Vector stores

#### summary

Retrieve vector store

#### parameters

##### in

path

##### name

vector_store_id

##### required

true

##### schema

###### type

string

##### description

The ID of the vector store to retrieve.


#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/VectorStoreObject

#### x-oaiMeta

##### name

Retrieve vector store

##### group

vector_stores

##### returns

The [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) object matching the specified ID.

##### examples

###### response

{
  "id": "vs_abc123",
  "object": "vector_store",
  "created_at": 1699061776
}


###### request

####### curl

curl https://api.openai.com/v1/vector_stores/vs_abc123 \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -H "OpenAI-Beta: assistants=v2"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
vector_store = client.vector_stores.retrieve(
    "vector_store_id",
)
print(vector_store.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const vectorStore = await client.vectorStores.retrieve('vector_store_id');

console.log(vectorStore.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  vectorStore, err := client.VectorStores.Get(context.TODO(), "vector_store_id")
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", vectorStore.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.vectorstores.VectorStore;
import com.openai.models.vectorstores.VectorStoreRetrieveParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        VectorStore vectorStore = client.vectorStores().retrieve("vector_store_id");
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

vector_store = openai.vector_stores.retrieve("vector_store_id")

puts(vector_store)

#### description

Retrieves a vector store.

### post

#### operationId

modifyVectorStore

#### tags

- Vector stores

#### summary

Modify vector store

#### parameters

##### in

path

##### name

vector_store_id

##### required

true

##### schema

###### type

string

##### description

The ID of the vector store to modify.


#### requestBody

##### required

true

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/UpdateVectorStoreRequest

#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/VectorStoreObject

#### x-oaiMeta

##### name

Modify vector store

##### group

vector_stores

##### returns

The modified [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) object.

##### examples

###### response

{
  "id": "vs_abc123",
  "object": "vector_store",
  "created_at": 1699061776,
  "name": "Support FAQ",
  "bytes": 139920,
  "file_counts": {
    "in_progress": 0,
    "completed": 3,
    "failed": 0,
    "cancelled": 0,
    "total": 3
  }
}


###### request

####### curl

curl https://api.openai.com/v1/vector_stores/vs_abc123 \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -H "OpenAI-Beta: assistants=v2"
  -d '{
    "name": "Support FAQ"
  }'


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
vector_store = client.vector_stores.update(
    vector_store_id="vector_store_id",
)
print(vector_store.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const vectorStore = await client.vectorStores.update('vector_store_id');

console.log(vectorStore.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  vectorStore, err := client.VectorStores.Update(
    context.TODO(),
    "vector_store_id",
    openai.VectorStoreUpdateParams{

    },
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", vectorStore.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.vectorstores.VectorStore;
import com.openai.models.vectorstores.VectorStoreUpdateParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        VectorStore vectorStore = client.vectorStores().update("vector_store_id");
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

vector_store = openai.vector_stores.update("vector_store_id")

puts(vector_store)

#### description

Modifies a vector store.

### delete

#### operationId

deleteVectorStore

#### tags

- Vector stores

#### summary

Delete vector store

#### parameters

##### in

path

##### name

vector_store_id

##### required

true

##### schema

###### type

string

##### description

The ID of the vector store to delete.


#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/DeleteVectorStoreResponse

#### x-oaiMeta

##### name

Delete vector store

##### group

vector_stores

##### returns

Deletion status

##### examples

###### response

{
  id: "vs_abc123",
  object: "vector_store.deleted",
  deleted: true
}


###### request

####### curl

curl https://api.openai.com/v1/vector_stores/vs_abc123 \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -H "OpenAI-Beta: assistants=v2" \
  -X DELETE


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
vector_store_deleted = client.vector_stores.delete(
    "vector_store_id",
)
print(vector_store_deleted.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const vectorStoreDeleted = await client.vectorStores.delete('vector_store_id');

console.log(vectorStoreDeleted.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  vectorStoreDeleted, err := client.VectorStores.Delete(context.TODO(), "vector_store_id")
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", vectorStoreDeleted.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.vectorstores.VectorStoreDeleteParams;
import com.openai.models.vectorstores.VectorStoreDeleted;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        VectorStoreDeleted vectorStoreDeleted = client.vectorStores().delete("vector_store_id");
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

vector_store_deleted = openai.vector_stores.delete("vector_store_id")

puts(vector_store_deleted)

#### description

Delete a vector store.

## /vector_stores/{vector_store_id}/file_batches

### post

#### operationId

createVectorStoreFileBatch

#### tags

- Vector stores

#### summary

Create vector store file batch

#### parameters

##### in

path

##### name

vector_store_id

##### required

true

##### schema

###### type

string

###### example

vs_abc123

##### description

The ID of the vector store for which to create a File Batch.



#### requestBody

##### required

true

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/CreateVectorStoreFileBatchRequest

#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/VectorStoreFileBatchObject

#### x-oaiMeta

##### name

Create vector store file batch

##### group

vector_stores

##### returns

A [vector store file batch](https://platform.openai.com/docs/api-reference/vector-stores-file-batches/batch-object) object.

##### examples

###### response

{
  "id": "vsfb_abc123",
  "object": "vector_store.file_batch",
  "created_at": 1699061776,
  "vector_store_id": "vs_abc123",
  "status": "in_progress",
  "file_counts": {
    "in_progress": 1,
    "completed": 1,
    "failed": 0,
    "cancelled": 0,
    "total": 0,
  }
}


###### request

####### curl

curl https://api.openai.com/v1/vector_stores/vs_abc123/file_batches \
    -H "Authorization: Bearer $OPENAI_API_KEY" \
    -H "Content-Type: application/json \
    -H "OpenAI-Beta: assistants=v2" \
    -d '{
      "file_ids": ["file-abc123", "file-abc456"]
    }'


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
vector_store_file_batch = client.vector_stores.file_batches.create(
    vector_store_id="vs_abc123",
    file_ids=["string"],
)
print(vector_store_file_batch.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const vectorStoreFileBatch = await client.vectorStores.fileBatches.create('vs_abc123', {
  file_ids: ['string'],
});

console.log(vectorStoreFileBatch.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  vectorStoreFileBatch, err := client.VectorStores.FileBatches.New(
    context.TODO(),
    "vs_abc123",
    openai.VectorStoreFileBatchNewParams{
      FileIDs: []string{"string"},
    },
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", vectorStoreFileBatch.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.vectorstores.filebatches.FileBatchCreateParams;
import com.openai.models.vectorstores.filebatches.VectorStoreFileBatch;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        FileBatchCreateParams params = FileBatchCreateParams.builder()
            .vectorStoreId("vs_abc123")
            .addFileId("string")
            .build();
        VectorStoreFileBatch vectorStoreFileBatch = client.vectorStores().fileBatches().create(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

vector_store_file_batch = openai.vector_stores.file_batches.create("vs_abc123", file_ids: ["string"])

puts(vector_store_file_batch)

#### description

Create a vector store file batch.

## /vector_stores/{vector_store_id}/file_batches/{batch_id}

### get

#### operationId

getVectorStoreFileBatch

#### tags

- Vector stores

#### summary

Retrieve vector store file batch

#### parameters

##### in

path

##### name

vector_store_id

##### required

true

##### schema

###### type

string

###### example

vs_abc123

##### description

The ID of the vector store that the file batch belongs to.

##### in

path

##### name

batch_id

##### required

true

##### schema

###### type

string

###### example

vsfb_abc123

##### description

The ID of the file batch being retrieved.


#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/VectorStoreFileBatchObject

#### x-oaiMeta

##### name

Retrieve vector store file batch

##### group

vector_stores

##### returns

The [vector store file batch](https://platform.openai.com/docs/api-reference/vector-stores-file-batches/batch-object) object.

##### examples

###### response

{
  "id": "vsfb_abc123",
  "object": "vector_store.file_batch",
  "created_at": 1699061776,
  "vector_store_id": "vs_abc123",
  "status": "in_progress",
  "file_counts": {
    "in_progress": 1,
    "completed": 1,
    "failed": 0,
    "cancelled": 0,
    "total": 0,
  }
}


###### request

####### curl

curl https://api.openai.com/v1/vector_stores/vs_abc123/files_batches/vsfb_abc123 \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -H "OpenAI-Beta: assistants=v2"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
vector_store_file_batch = client.vector_stores.file_batches.retrieve(
    batch_id="vsfb_abc123",
    vector_store_id="vs_abc123",
)
print(vector_store_file_batch.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const vectorStoreFileBatch = await client.vectorStores.fileBatches.retrieve('vsfb_abc123', {
  vector_store_id: 'vs_abc123',
});

console.log(vectorStoreFileBatch.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  vectorStoreFileBatch, err := client.VectorStores.FileBatches.Get(
    context.TODO(),
    "vs_abc123",
    "vsfb_abc123",
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", vectorStoreFileBatch.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.vectorstores.filebatches.FileBatchRetrieveParams;
import com.openai.models.vectorstores.filebatches.VectorStoreFileBatch;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        FileBatchRetrieveParams params = FileBatchRetrieveParams.builder()
            .vectorStoreId("vs_abc123")
            .batchId("vsfb_abc123")
            .build();
        VectorStoreFileBatch vectorStoreFileBatch = client.vectorStores().fileBatches().retrieve(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

vector_store_file_batch = openai.vector_stores.file_batches.retrieve("vsfb_abc123", vector_store_id: "vs_abc123")

puts(vector_store_file_batch)

#### description

Retrieves a vector store file batch.

## /vector_stores/{vector_store_id}/file_batches/{batch_id}/cancel

### post

#### operationId

cancelVectorStoreFileBatch

#### tags

- Vector stores

#### summary

Cancel vector store file batch

#### parameters

##### in

path

##### name

vector_store_id

##### required

true

##### schema

###### type

string

##### description

The ID of the vector store that the file batch belongs to.

##### in

path

##### name

batch_id

##### required

true

##### schema

###### type

string

##### description

The ID of the file batch to cancel.


#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/VectorStoreFileBatchObject

#### x-oaiMeta

##### name

Cancel vector store file batch

##### group

vector_stores

##### returns

The modified vector store file batch object.

##### examples

###### response

{
  "id": "vsfb_abc123",
  "object": "vector_store.file_batch",
  "created_at": 1699061776,
  "vector_store_id": "vs_abc123",
  "status": "in_progress",
  "file_counts": {
    "in_progress": 12,
    "completed": 3,
    "failed": 0,
    "cancelled": 0,
    "total": 15,
  }
}


###### request

####### curl

curl https://api.openai.com/v1/vector_stores/vs_abc123/files_batches/vsfb_abc123/cancel \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -H "OpenAI-Beta: assistants=v2" \
  -X POST


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
vector_store_file_batch = client.vector_stores.file_batches.cancel(
    batch_id="batch_id",
    vector_store_id="vector_store_id",
)
print(vector_store_file_batch.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const vectorStoreFileBatch = await client.vectorStores.fileBatches.cancel('batch_id', {
  vector_store_id: 'vector_store_id',
});

console.log(vectorStoreFileBatch.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  vectorStoreFileBatch, err := client.VectorStores.FileBatches.Cancel(
    context.TODO(),
    "vector_store_id",
    "batch_id",
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", vectorStoreFileBatch.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.vectorstores.filebatches.FileBatchCancelParams;
import com.openai.models.vectorstores.filebatches.VectorStoreFileBatch;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        FileBatchCancelParams params = FileBatchCancelParams.builder()
            .vectorStoreId("vector_store_id")
            .batchId("batch_id")
            .build();
        VectorStoreFileBatch vectorStoreFileBatch = client.vectorStores().fileBatches().cancel(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

vector_store_file_batch = openai.vector_stores.file_batches.cancel("batch_id", vector_store_id: "vector_store_id")

puts(vector_store_file_batch)

#### description

Cancel a vector store file batch. This attempts to cancel the processing of files in this batch as soon as possible.

## /vector_stores/{vector_store_id}/file_batches/{batch_id}/files

### get

#### operationId

listFilesInVectorStoreBatch

#### tags

- Vector stores

#### summary

List vector store files in a batch

#### parameters

##### name

vector_store_id

##### in

path

##### description

The ID of the vector store that the files belong to.

##### required

true

##### schema

###### type

string

##### name

batch_id

##### in

path

##### description

The ID of the file batch that the files belong to.

##### required

true

##### schema

###### type

string

##### name

limit

##### in

query

##### description

A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20.


##### required

false

##### schema

###### type

integer

###### default

20

##### name

order

##### in

query

##### description

Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order.


##### schema

###### type

string

###### default

desc

###### enum

- asc
- desc

##### name

after

##### in

query

##### description

A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list.


##### schema

###### type

string

##### name

before

##### in

query

##### description

A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list.


##### schema

###### type

string

##### name

filter

##### in

query

##### description

Filter by file status. One of `in_progress`, `completed`, `failed`, `cancelled`.

##### schema

###### type

string

###### enum

- in_progress
- completed
- failed
- cancelled


#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ListVectorStoreFilesResponse

#### x-oaiMeta

##### name

List vector store files in a batch

##### group

vector_stores

##### returns

A list of [vector store file](https://platform.openai.com/docs/api-reference/vector-stores-files/file-object) objects.

##### examples

###### response

{
  "object": "list",
  "data": [
    {
      "id": "file-abc123",
      "object": "vector_store.file",
      "created_at": 1699061776,
      "vector_store_id": "vs_abc123"
    },
    {
      "id": "file-abc456",
      "object": "vector_store.file",
      "created_at": 1699061776,
      "vector_store_id": "vs_abc123"
    }
  ],
  "first_id": "file-abc123",
  "last_id": "file-abc456",
  "has_more": false
}


###### request

####### curl

curl https://api.openai.com/v1/vector_stores/vs_abc123/files_batches/vsfb_abc123/files \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -H "OpenAI-Beta: assistants=v2"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
page = client.vector_stores.file_batches.list_files(
    batch_id="batch_id",
    vector_store_id="vector_store_id",
)
page = page.data[0]
print(page.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

// Automatically fetches more pages as needed.
for await (const vectorStoreFile of client.vectorStores.fileBatches.listFiles('batch_id', {
  vector_store_id: 'vector_store_id',
})) {
  console.log(vectorStoreFile.id);
}

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  page, err := client.VectorStores.FileBatches.ListFiles(
    context.TODO(),
    "vector_store_id",
    "batch_id",
    openai.VectorStoreFileBatchListFilesParams{

    },
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", page)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.vectorstores.filebatches.FileBatchListFilesPage;
import com.openai.models.vectorstores.filebatches.FileBatchListFilesParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        FileBatchListFilesParams params = FileBatchListFilesParams.builder()
            .vectorStoreId("vector_store_id")
            .batchId("batch_id")
            .build();
        FileBatchListFilesPage page = client.vectorStores().fileBatches().listFiles(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

page = openai.vector_stores.file_batches.list_files("batch_id", vector_store_id: "vector_store_id")

puts(page)

#### description

Returns a list of vector store files in a batch.

## /vector_stores/{vector_store_id}/files

### get

#### operationId

listVectorStoreFiles

#### tags

- Vector stores

#### summary

List vector store files

#### parameters

##### name

vector_store_id

##### in

path

##### description

The ID of the vector store that the files belong to.

##### required

true

##### schema

###### type

string

##### name

limit

##### in

query

##### description

A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20.


##### required

false

##### schema

###### type

integer

###### default

20

##### name

order

##### in

query

##### description

Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order.


##### schema

###### type

string

###### default

desc

###### enum

- asc
- desc

##### name

after

##### in

query

##### description

A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list.


##### schema

###### type

string

##### name

before

##### in

query

##### description

A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list.


##### schema

###### type

string

##### name

filter

##### in

query

##### description

Filter by file status. One of `in_progress`, `completed`, `failed`, `cancelled`.

##### schema

###### type

string

###### enum

- in_progress
- completed
- failed
- cancelled


#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/ListVectorStoreFilesResponse

#### x-oaiMeta

##### name

List vector store files

##### group

vector_stores

##### returns

A list of [vector store file](https://platform.openai.com/docs/api-reference/vector-stores-files/file-object) objects.

##### examples

###### response

{
  "object": "list",
  "data": [
    {
      "id": "file-abc123",
      "object": "vector_store.file",
      "created_at": 1699061776,
      "vector_store_id": "vs_abc123"
    },
    {
      "id": "file-abc456",
      "object": "vector_store.file",
      "created_at": 1699061776,
      "vector_store_id": "vs_abc123"
    }
  ],
  "first_id": "file-abc123",
  "last_id": "file-abc456",
  "has_more": false
}


###### request

####### curl

curl https://api.openai.com/v1/vector_stores/vs_abc123/files \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -H "OpenAI-Beta: assistants=v2"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
page = client.vector_stores.files.list(
    vector_store_id="vector_store_id",
)
page = page.data[0]
print(page.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

// Automatically fetches more pages as needed.
for await (const vectorStoreFile of client.vectorStores.files.list('vector_store_id')) {
  console.log(vectorStoreFile.id);
}

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  page, err := client.VectorStores.Files.List(
    context.TODO(),
    "vector_store_id",
    openai.VectorStoreFileListParams{

    },
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", page)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.vectorstores.files.FileListPage;
import com.openai.models.vectorstores.files.FileListParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        FileListPage page = client.vectorStores().files().list("vector_store_id");
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

page = openai.vector_stores.files.list("vector_store_id")

puts(page)

#### description

Returns a list of vector store files.

### post

#### operationId

createVectorStoreFile

#### tags

- Vector stores

#### summary

Create vector store file

#### parameters

##### in

path

##### name

vector_store_id

##### required

true

##### schema

###### type

string

###### example

vs_abc123

##### description

The ID of the vector store for which to create a File.



#### requestBody

##### required

true

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/CreateVectorStoreFileRequest

#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/VectorStoreFileObject

#### x-oaiMeta

##### name

Create vector store file

##### group

vector_stores

##### returns

A [vector store file](https://platform.openai.com/docs/api-reference/vector-stores-files/file-object) object.

##### examples

###### response

{
  "id": "file-abc123",
  "object": "vector_store.file",
  "created_at": 1699061776,
  "usage_bytes": 1234,
  "vector_store_id": "vs_abcd",
  "status": "completed",
  "last_error": null
}


###### request

####### curl

curl https://api.openai.com/v1/vector_stores/vs_abc123/files \
    -H "Authorization: Bearer $OPENAI_API_KEY" \
    -H "Content-Type: application/json" \
    -H "OpenAI-Beta: assistants=v2" \
    -d '{
      "file_id": "file-abc123"
    }'


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
vector_store_file = client.vector_stores.files.create(
    vector_store_id="vs_abc123",
    file_id="file_id",
)
print(vector_store_file.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const vectorStoreFile = await client.vectorStores.files.create('vs_abc123', { file_id: 'file_id' });

console.log(vectorStoreFile.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  vectorStoreFile, err := client.VectorStores.Files.New(
    context.TODO(),
    "vs_abc123",
    openai.VectorStoreFileNewParams{
      FileID: "file_id",
    },
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", vectorStoreFile.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.vectorstores.files.FileCreateParams;
import com.openai.models.vectorstores.files.VectorStoreFile;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        FileCreateParams params = FileCreateParams.builder()
            .vectorStoreId("vs_abc123")
            .fileId("file_id")
            .build();
        VectorStoreFile vectorStoreFile = client.vectorStores().files().create(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

vector_store_file = openai.vector_stores.files.create("vs_abc123", file_id: "file_id")

puts(vector_store_file)

#### description

Create a vector store file by attaching a [File](https://platform.openai.com/docs/api-reference/files) to a [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object).

## /vector_stores/{vector_store_id}/files/{file_id}

### get

#### operationId

getVectorStoreFile

#### tags

- Vector stores

#### summary

Retrieve vector store file

#### parameters

##### in

path

##### name

vector_store_id

##### required

true

##### schema

###### type

string

###### example

vs_abc123

##### description

The ID of the vector store that the file belongs to.

##### in

path

##### name

file_id

##### required

true

##### schema

###### type

string

###### example

file-abc123

##### description

The ID of the file being retrieved.


#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/VectorStoreFileObject

#### x-oaiMeta

##### name

Retrieve vector store file

##### group

vector_stores

##### returns

The [vector store file](https://platform.openai.com/docs/api-reference/vector-stores-files/file-object) object.

##### examples

###### response

{
  "id": "file-abc123",
  "object": "vector_store.file",
  "created_at": 1699061776,
  "vector_store_id": "vs_abcd",
  "status": "completed",
  "last_error": null
}


###### request

####### curl

curl https://api.openai.com/v1/vector_stores/vs_abc123/files/file-abc123 \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -H "OpenAI-Beta: assistants=v2"


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
vector_store_file = client.vector_stores.files.retrieve(
    file_id="file-abc123",
    vector_store_id="vs_abc123",
)
print(vector_store_file.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const vectorStoreFile = await client.vectorStores.files.retrieve('file-abc123', {
  vector_store_id: 'vs_abc123',
});

console.log(vectorStoreFile.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  vectorStoreFile, err := client.VectorStores.Files.Get(
    context.TODO(),
    "vs_abc123",
    "file-abc123",
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", vectorStoreFile.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.vectorstores.files.FileRetrieveParams;
import com.openai.models.vectorstores.files.VectorStoreFile;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        FileRetrieveParams params = FileRetrieveParams.builder()
            .vectorStoreId("vs_abc123")
            .fileId("file-abc123")
            .build();
        VectorStoreFile vectorStoreFile = client.vectorStores().files().retrieve(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

vector_store_file = openai.vector_stores.files.retrieve("file-abc123", vector_store_id: "vs_abc123")

puts(vector_store_file)

#### description

Retrieves a vector store file.

### delete

#### operationId

deleteVectorStoreFile

#### tags

- Vector stores

#### summary

Delete vector store file

#### parameters

##### in

path

##### name

vector_store_id

##### required

true

##### schema

###### type

string

##### description

The ID of the vector store that the file belongs to.

##### in

path

##### name

file_id

##### required

true

##### schema

###### type

string

##### description

The ID of the file to delete.


#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/DeleteVectorStoreFileResponse

#### x-oaiMeta

##### name

Delete vector store file

##### group

vector_stores

##### returns

Deletion status

##### examples

###### response

{
  id: "file-abc123",
  object: "vector_store.file.deleted",
  deleted: true
}


###### request

####### curl

curl https://api.openai.com/v1/vector_stores/vs_abc123/files/file-abc123 \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -H "OpenAI-Beta: assistants=v2" \
  -X DELETE


####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
vector_store_file_deleted = client.vector_stores.files.delete(
    file_id="file_id",
    vector_store_id="vector_store_id",
)
print(vector_store_file_deleted.id)

####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const vectorStoreFileDeleted = await client.vectorStores.files.delete('file_id', {
  vector_store_id: 'vector_store_id',
});

console.log(vectorStoreFileDeleted.id);

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  vectorStoreFileDeleted, err := client.VectorStores.Files.Delete(
    context.TODO(),
    "vector_store_id",
    "file_id",
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", vectorStoreFileDeleted.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.vectorstores.files.FileDeleteParams;
import com.openai.models.vectorstores.files.VectorStoreFileDeleted;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        FileDeleteParams params = FileDeleteParams.builder()
            .vectorStoreId("vector_store_id")
            .fileId("file_id")
            .build();
        VectorStoreFileDeleted vectorStoreFileDeleted = client.vectorStores().files().delete(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

vector_store_file_deleted = openai.vector_stores.files.delete("file_id", vector_store_id: "vector_store_id")

puts(vector_store_file_deleted)

#### description

Delete a vector store file. This will remove the file from the vector store but the file itself will not be deleted. To delete the file, use the [delete file](https://platform.openai.com/docs/api-reference/files/delete) endpoint.

### post

#### operationId

updateVectorStoreFileAttributes

#### tags

- Vector stores

#### summary

Update vector store file attributes

#### parameters

##### in

path

##### name

vector_store_id

##### required

true

##### schema

###### type

string

###### example

vs_abc123

##### description

The ID of the vector store the file belongs to.

##### in

path

##### name

file_id

##### required

true

##### schema

###### type

string

###### example

file-abc123

##### description

The ID of the file to update attributes.


#### requestBody

##### required

true

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/UpdateVectorStoreFileAttributesRequest

#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/VectorStoreFileObject

#### x-oaiMeta

##### name

Update vector store file attributes

##### group

vector_stores

##### returns

The updated [vector store file](https://platform.openai.com/docs/api-reference/vector-stores-files/file-object) object.

##### examples

###### response

{
  "id": "file-abc123",
  "object": "vector_store.file",
  "usage_bytes": 1234,
  "created_at": 1699061776,
  "vector_store_id": "vs_abcd",
  "status": "completed",
  "last_error": null,
  "chunking_strategy": {...},
  "attributes": {"key1": "value1", "key2": 2}
}


###### request

####### curl

curl https://api.openai.com/v1/vector_stores/{vector_store_id}/files/{file_id} \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"attributes": {"key1": "value1", "key2": 2}}'


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

const vectorStoreFile = await client.vectorStores.files.update('file-abc123', {
  vector_store_id: 'vs_abc123',
  attributes: { foo: 'string' },
});

console.log(vectorStoreFile.id);

####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
vector_store_file = client.vector_stores.files.update(
    file_id="file-abc123",
    vector_store_id="vs_abc123",
    attributes={
        "foo": "string"
    },
)
print(vector_store_file.id)

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  vectorStoreFile, err := client.VectorStores.Files.Update(
    context.TODO(),
    "vs_abc123",
    "file-abc123",
    openai.VectorStoreFileUpdateParams{
      Attributes: map[string]openai.VectorStoreFileUpdateParamsAttributeUnion{
      "foo": openai.VectorStoreFileUpdateParamsAttributeUnion{
        OfString: openai.String("string"),
      },
      },
    },
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", vectorStoreFile.ID)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.JsonValue;
import com.openai.models.vectorstores.files.FileUpdateParams;
import com.openai.models.vectorstores.files.VectorStoreFile;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        FileUpdateParams params = FileUpdateParams.builder()
            .vectorStoreId("vs_abc123")
            .fileId("file-abc123")
            .attributes(FileUpdateParams.Attributes.builder()
                .putAdditionalProperty("foo", JsonValue.from("string"))
                .build())
            .build();
        VectorStoreFile vectorStoreFile = client.vectorStores().files().update(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

vector_store_file = openai.vector_stores.files.update(
  "file-abc123",
  vector_store_id: "vs_abc123",
  attributes: {foo: "string"}
)

puts(vector_store_file)

#### description

Update attributes on a vector store file.

## /vector_stores/{vector_store_id}/files/{file_id}/content

### get

#### operationId

retrieveVectorStoreFileContent

#### tags

- Vector stores

#### summary

Retrieve vector store file content

#### parameters

##### in

path

##### name

vector_store_id

##### required

true

##### schema

###### type

string

###### example

vs_abc123

##### description

The ID of the vector store.

##### in

path

##### name

file_id

##### required

true

##### schema

###### type

string

###### example

file-abc123

##### description

The ID of the file within the vector store.


#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/VectorStoreFileContentResponse

#### x-oaiMeta

##### name

Retrieve vector store file content

##### group

vector_stores

##### returns

The parsed contents of the specified vector store file.

##### examples

###### response

{
  "file_id": "file-abc123",
  "filename": "example.txt",
  "attributes": {"key": "value"},
  "content": [
    {"type": "text", "text": "..."},
    ...
  ]
}


###### request

####### curl

curl \
https://api.openai.com/v1/vector_stores/vs_abc123/files/file-abc123/content \
-H "Authorization: Bearer $OPENAI_API_KEY"


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

// Automatically fetches more pages as needed.
for await (const fileContentResponse of client.vectorStores.files.content('file-abc123', {
  vector_store_id: 'vs_abc123',
})) {
  console.log(fileContentResponse.text);
}

####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
page = client.vector_stores.files.content(
    file_id="file-abc123",
    vector_store_id="vs_abc123",
)
page = page.data[0]
print(page.text)

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  page, err := client.VectorStores.Files.Content(
    context.TODO(),
    "vs_abc123",
    "file-abc123",
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", page)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.vectorstores.files.FileContentPage;
import com.openai.models.vectorstores.files.FileContentParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        FileContentParams params = FileContentParams.builder()
            .vectorStoreId("vs_abc123")
            .fileId("file-abc123")
            .build();
        FileContentPage page = client.vectorStores().files().content(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

page = openai.vector_stores.files.content("file-abc123", vector_store_id: "vs_abc123")

puts(page)

#### description

Retrieve the parsed contents of a vector store file.

## /vector_stores/{vector_store_id}/search

### post

#### operationId

searchVectorStore

#### tags

- Vector stores

#### summary

Search vector store

#### parameters

##### in

path

##### name

vector_store_id

##### required

true

##### schema

###### type

string

###### example

vs_abc123

##### description

The ID of the vector store to search.


#### requestBody

##### required

true

##### content

###### application/json

####### schema

######## $ref

#/components/schemas/VectorStoreSearchRequest

#### responses

##### 200

###### description

OK

###### content

####### application/json

######## schema

######### $ref

#/components/schemas/VectorStoreSearchResultsPage

#### x-oaiMeta

##### name

Search vector store

##### group

vector_stores

##### returns

A page of search results from the vector store.

##### examples

###### response

{
  "object": "vector_store.search_results.page",
  "search_query": "What is the return policy?",
  "data": [
    {
      "file_id": "file_123",
      "filename": "document.pdf",
      "score": 0.95,
      "attributes": {
        "author": "John Doe",
        "date": "2023-01-01"
      },
      "content": [
        {
          "type": "text",
          "text": "Relevant chunk"
        }
      ]
    },
    {
      "file_id": "file_456",
      "filename": "notes.txt",
      "score": 0.89,
      "attributes": {
        "author": "Jane Smith",
        "date": "2023-01-02"
      },
      "content": [
        {
          "type": "text",
          "text": "Sample text content from the vector store."
        }
      ]
    }
  ],
  "has_more": false,
  "next_page": null
}


###### request

####### curl

curl -X POST \
https://api.openai.com/v1/vector_stores/vs_abc123/search \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{"query": "What is the return policy?", "filters": {...}}'


####### node.js

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'My API Key',
});

// Automatically fetches more pages as needed.
for await (const vectorStoreSearchResponse of client.vectorStores.search('vs_abc123', { query: 'string' })) {
  console.log(vectorStoreSearchResponse.file_id);
}

####### python

from openai import OpenAI

client = OpenAI(
    api_key="My API Key",
)
page = client.vector_stores.search(
    vector_store_id="vs_abc123",
    query="string",
)
page = page.data[0]
print(page.file_id)

####### go

package main

import (
  "context"
  "fmt"

  "github.com/openai/openai-go"
  "github.com/openai/openai-go/option"
)

func main() {
  client := openai.NewClient(
    option.WithAPIKey("My API Key"),
  )
  page, err := client.VectorStores.Search(
    context.TODO(),
    "vs_abc123",
    openai.VectorStoreSearchParams{
      Query: openai.VectorStoreSearchParamsQueryUnion{
        OfString: openai.String("string"),
      },
    },
  )
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", page)
}


####### java

package com.openai.example;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.vectorstores.VectorStoreSearchPage;
import com.openai.models.vectorstores.VectorStoreSearchParams;

public final class Main {
    private Main() {}

    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.fromEnv();

        VectorStoreSearchParams params = VectorStoreSearchParams.builder()
            .vectorStoreId("vs_abc123")
            .query("string")
            .build();
        VectorStoreSearchPage page = client.vectorStores().search(params);
    }
}

####### ruby

require "openai"

openai = OpenAI::Client.new(api_key: "My API Key")

page = openai.vector_stores.search("vs_abc123", query: "string")

puts(page)

#### description

Search a vector store for relevant chunks based on a query and file attributes filter.