commit 65b44423c65902617bef86a41852f6d0e4552f1d Author: Niklas Nielsen Date: Fri May 24 18:26:16 2024 -0700 Updating github integration diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..e6a9944 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# This allows generated code to be indexed correctly +*.go linguist-generated=false \ No newline at end of file diff --git a/.github/workflows/sdk_generation.yaml b/.github/workflows/sdk_generation.yaml new file mode 100644 index 0000000..7525d1f --- /dev/null +++ b/.github/workflows/sdk_generation.yaml @@ -0,0 +1,25 @@ +name: Generate +permissions: + checks: write + contents: write + pull-requests: write + statuses: write +"on": + workflow_dispatch: + inputs: + force: + description: Force generation of SDKs + type: boolean + default: false + schedule: + - cron: 0 0 * * * +jobs: + generate: + uses: speakeasy-api/sdk-generation-action/.github/workflows/workflow-executor.yaml@v15 + with: + force: ${{ github.event.inputs.force }} + mode: pr + speakeasy_version: latest + secrets: + github_access_token: ${{ secrets.GITHUB_TOKEN }} + speakeasy_api_key: ${{ secrets.SPEAKEASY_API_KEY }} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d3c2f59 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +# .gitignore diff --git a/.speakeasy/gen.lock b/.speakeasy/gen.lock new file mode 100755 index 0000000..1154fda --- /dev/null +++ b/.speakeasy/gen.lock @@ -0,0 +1,199 @@ +lockVersion: 2.0.0 +id: af921c1a-d48f-4ab5-a412-4cf4ba8a50ad +management: + docChecksum: 5e7cc152f137f5919734cc70b836a4d6 + docVersion: 1.0.0 + speakeasyVersion: 1.296.1 + generationVersion: 2.338.1 + releaseVersion: 0.0.1 + configChecksum: e63fe754c82a6ad123e8ccf7b0e616cd +features: + go: + additionalDependencies: 0.1.0 + constsAndDefaults: 0.1.4 + core: 3.4.10 + deprecations: 2.81.1 + examples: 2.81.3 + flattening: 2.81.1 + getRequestBodies: 2.81.1 + globalSecurity: 2.82.9 + globalSecurityCallbacks: 0.1.0 + globalSecurityFlattening: 0.1.0 + globalServerURLs: 2.82.2 + globals: 2.82.2 + intellisenseMarkdownSupport: 0.1.0 + nameOverrides: 2.81.2 + nullables: 0.1.0 + responseFormat: 0.1.2 + sdkHooks: 0.1.0 + typeOverrides: 2.81.1 + unions: 2.85.8 +generatedFiles: + - completions.go + - sessions.go + - feedback.go + - feedbacktasks.go + - log10.go + - go.mod + - models/sdkerrors/sdkerror.go + - types/bigint.go + - types/date.go + - types/datetime.go + - types/decimal.go + - types/pointers.go + - internal/utils/contenttype.go + - internal/utils/form.go + - internal/utils/headers.go + - internal/utils/json.go + - internal/utils/pathparams.go + - internal/utils/queryparams.go + - internal/utils/requestbody.go + - internal/utils/retries.go + - internal/utils/security.go + - internal/utils/utils.go + - internal/globals/globals.go + - /models/operations/create.go + - /models/operations/update.go + - /models/operations/listungraded.go + - /models/operations/createsession.go + - /models/operations/get.go + - /models/operations/list.go + - /models/operations/upload.go + - /models/operations/listfeedbacktasks.go + - /models/operations/createfeedbacktask.go + - /models/operations/getfeedbacktask.go + - /models/components/completion.go + - /models/components/createchatcompletionresponse.go + - /models/components/completionusage.go + - /models/components/chatcompletiontokenlogprob.go + - /models/components/chatcompletionresponsemessage.go + - /models/components/chatcompletionmessagetoolcall.go + - /models/components/createchatcompletionrequest.go + - /models/components/chatcompletionfunctions.go + - /models/components/chatcompletionfunctioncalloption.go + - /models/components/chatcompletiontoolchoiceoption.go + - /models/components/chatcompletionnamedtoolchoice.go + - /models/components/chatcompletiontool.go + - /models/components/functionobject.go + - /models/components/chatcompletionstreamoptions.go + - /models/components/chatcompletionrequestmessage.go + - /models/components/chatcompletionrequestsystemmessage.go + - /models/components/chatcompletionrequestusermessage.go + - /models/components/chatcompletionrequestmessagecontentpart.go + - /models/components/chatcompletionrequestmessagecontentparttext.go + - /models/components/chatcompletionrequestmessagecontentpartimage.go + - /models/components/chatcompletionrequestassistantmessage.go + - /models/components/chatcompletionrequesttoolmessage.go + - /models/components/chatcompletionrequestfunctionmessage.go + - /models/components/httpmetadata.go + - /models/components/session.go + - /models/components/feedback.go + - /models/components/task.go + - /models/components/security.go + - docs/models/operations/createglobals.md + - docs/models/operations/createrequest.md + - docs/models/operations/createresponse.md + - docs/models/operations/updateglobals.md + - docs/models/operations/updaterequest.md + - docs/models/operations/updateresponse.md + - docs/models/operations/listungradedglobals.md + - docs/models/operations/listungradedrequest.md + - docs/models/operations/listungradedresponsebody.md + - docs/models/operations/listungradedresponse.md + - docs/models/operations/createsessionglobals.md + - docs/models/operations/createsessionrequest.md + - docs/models/operations/createsessionresponsebody.md + - docs/models/operations/createsessionresponse.md + - docs/models/operations/getglobals.md + - docs/models/operations/getrequest.md + - docs/models/operations/getresponse.md + - docs/models/operations/listglobals.md + - docs/models/operations/listrequestbody.md + - docs/models/operations/listrequest.md + - docs/models/operations/listresponsebody.md + - docs/models/operations/listresponse.md + - docs/models/operations/uploadglobals.md + - docs/models/operations/requestbodyjsonvalues.md + - docs/models/operations/two.md + - docs/models/operations/jsonvalues.md + - docs/models/operations/one.md + - docs/models/operations/uploadrequestbody.md + - docs/models/operations/uploadrequest.md + - docs/models/operations/uploadresponse.md + - docs/models/operations/listfeedbacktasksresponse.md + - docs/models/operations/createfeedbacktaskresponse.md + - docs/models/operations/getfeedbacktaskrequest.md + - docs/models/operations/getfeedbacktaskresponse.md + - docs/models/components/kind.md + - docs/models/components/status.md + - docs/models/components/stacktrace.md + - docs/models/components/completion.md + - docs/models/components/finishreason.md + - docs/models/components/logprobs.md + - docs/models/components/choices.md + - docs/models/components/object.md + - docs/models/components/createchatcompletionresponse.md + - docs/models/components/completionusage.md + - docs/models/components/toplogprobs.md + - docs/models/components/chatcompletiontokenlogprob.md + - docs/models/components/chatcompletionresponsemessagerole.md + - docs/models/components/chatcompletionresponsemessagefunctioncall.md + - docs/models/components/chatcompletionresponsemessage.md + - docs/models/components/chatcompletionmessagetoolcalltype.md + - docs/models/components/function.md + - docs/models/components/chatcompletionmessagetoolcall.md + - docs/models/components/two.md + - docs/models/components/model.md + - docs/models/components/createchatcompletionrequesttype.md + - docs/models/components/responseformat.md + - docs/models/components/stop.md + - docs/models/components/one.md + - docs/models/components/createchatcompletionrequestfunctioncall.md + - docs/models/components/createchatcompletionrequest.md + - docs/models/components/chatcompletionfunctions.md + - docs/models/components/chatcompletionfunctioncalloption.md + - docs/models/components/chatcompletiontoolchoiceoption1.md + - docs/models/components/chatcompletiontoolchoiceoption.md + - docs/models/components/chatcompletionnamedtoolchoicetype.md + - docs/models/components/chatcompletionnamedtoolchoicefunction.md + - docs/models/components/chatcompletionnamedtoolchoice.md + - docs/models/components/chatcompletiontooltype.md + - docs/models/components/chatcompletiontool.md + - docs/models/components/functionobject.md + - docs/models/components/chatcompletionstreamoptions.md + - docs/models/components/chatcompletionrequestmessage.md + - docs/models/components/role.md + - docs/models/components/chatcompletionrequestsystemmessage.md + - docs/models/components/content.md + - docs/models/components/chatcompletionrequestusermessagerole.md + - docs/models/components/chatcompletionrequestusermessage.md + - docs/models/components/chatcompletionrequestmessagecontentpart.md + - docs/models/components/type.md + - docs/models/components/chatcompletionrequestmessagecontentparttext.md + - docs/models/components/chatcompletionrequestmessagecontentpartimagetype.md + - docs/models/components/detail.md + - docs/models/components/imageurl.md + - docs/models/components/chatcompletionrequestmessagecontentpartimage.md + - docs/models/components/chatcompletionrequestassistantmessagerole.md + - docs/models/components/functioncall.md + - docs/models/components/chatcompletionrequestassistantmessage.md + - docs/models/components/chatcompletionrequesttoolmessagerole.md + - docs/models/components/chatcompletionrequesttoolmessage.md + - docs/models/components/chatcompletionrequestfunctionmessagerole.md + - docs/models/components/chatcompletionrequestfunctionmessage.md + - docs/models/components/httpmetadata.md + - docs/models/components/session.md + - docs/models/components/jsonvalues.md + - docs/models/components/feedback.md + - docs/models/components/jsonschema.md + - docs/models/components/completiontagsselector.md + - docs/models/components/task.md + - docs/models/components/security.md + - docs/sdks/log10/README.md + - docs/sdks/completions/README.md + - docs/sdks/sessions/README.md + - docs/sdks/feedback/README.md + - docs/sdks/feedbacktasks/README.md + - USAGE.md + - .gitattributes + - internal/hooks/hooks.go diff --git a/.speakeasy/gen.yaml b/.speakeasy/gen.yaml new file mode 100755 index 0000000..c8fcbc8 --- /dev/null +++ b/.speakeasy/gen.yaml @@ -0,0 +1,33 @@ +configVersion: 2.0.0 +generation: + sdkClassName: Log10 + maintainOpenAPIOrder: true + usageSnippets: + optionalPropertyRendering: withExample + useClassNamesForArrayFields: true + fixes: + nameResolutionDec2023: true + parameterOrderingFeb2024: true + requestResponseComponentNamesFeb2024: true + auth: + oAuth2ClientCredentialsEnabled: false +go: + version: 0.0.1 + additionalDependencies: {} + allowUnknownFieldsInWeakUnions: false + clientServerStatusCodesAsErrors: true + flattenGlobalSecurity: true + imports: + option: openapi + paths: + callbacks: models/callbacks + errors: models/sdkerrors + operations: models/operations + shared: models/components + webhooks: models/webhooks + inputModelSuffix: input + maxMethodParams: 4 + methodArguments: require-security-and-request + outputModelSuffix: output + packageName: github.com/log10-io/log10go + responseFormat: envelope-http diff --git a/.speakeasy/workflow.lock b/.speakeasy/workflow.lock new file mode 100644 index 0000000..c154ffa --- /dev/null +++ b/.speakeasy/workflow.lock @@ -0,0 +1,28 @@ +speakeasyVersion: 1.296.1 +sources: + default: + sourceNamespace: default + sourceRevisionDigest: sha256:e13d61f8be0f7ff07045d20f2e0671b5c93c2f2f185d768d991ab68ca99760e0 + sourceBlobDigest: sha256:7811f9a53e442babdafdc93fd2ec222a80fe0a260d6dfc2603b48c0aa05350db + tags: + - latest +targets: + my-first-target: + source: default + sourceNamespace: default + sourceRevisionDigest: sha256:e13d61f8be0f7ff07045d20f2e0671b5c93c2f2f185d768d991ab68ca99760e0 + sourceBlobDigest: sha256:7811f9a53e442babdafdc93fd2ec222a80fe0a260d6dfc2603b48c0aa05350db + outLocation: /Users/niklasqnielsen/workspace/log10/log10go +workflow: + workflowVersion: 1.0.0 + speakeasyVersion: latest + sources: + default: + inputs: + - location: openapi.yaml + registry: + location: registry.speakeasyapi.dev/log10/log10/default + targets: + my-first-target: + target: go + source: default diff --git a/.speakeasy/workflow.yaml b/.speakeasy/workflow.yaml new file mode 100644 index 0000000..266593e --- /dev/null +++ b/.speakeasy/workflow.yaml @@ -0,0 +1,12 @@ +workflowVersion: 1.0.0 +speakeasyVersion: latest +sources: + default: + inputs: + - location: openapi.yaml + registry: + location: registry.speakeasyapi.dev/log10/log10/default +targets: + my-first-target: + target: go + source: default diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..cb5127b --- /dev/null +++ b/Makefile @@ -0,0 +1,3 @@ +download_specs: + wget -q https://raw.githubusercontent.com/log10-io/openapi/main/openapi.yaml -O openapi.yaml + wget -q https://raw.githubusercontent.com/log10-io/openapi/main/openai.yaml -O openai.yaml diff --git a/README.md b/README.md new file mode 100644 index 0000000..134ffc3 --- /dev/null +++ b/README.md @@ -0,0 +1,464 @@ +# github.com/log10-io/log10go + +
+ + + + +
+ + +## 🏗 **Welcome to your new SDK!** 🏗 + +It has been generated successfully based on your OpenAPI spec. However, it is not yet ready for production use. Here are some next steps: +- [ ] 🛠 Make your SDK feel handcrafted by [customizing it](https://www.speakeasyapi.dev/docs/customize-sdks) +- [ ] ♻️ Refine your SDK quickly by iterating locally with the [Speakeasy CLI](https://github.com/speakeasy-api/speakeasy) +- [ ] 🎁 Publish your SDK to package managers by [configuring automatic publishing](https://www.speakeasyapi.dev/docs/advanced-setup/publish-sdks) +- [ ] ✨ When ready to productionize, delete this section from the README + + +## SDK Installation + +```bash +go get github.com/log10-io/log10go +``` + + + +## SDK Example Usage + +### Example + +```go +package main + +import ( + "context" + "github.com/log10-io/log10go" + "log" +) + +func main() { + s := log10go.New( + log10go.WithSecurity(""), + log10go.WithXLog10Organization(""), + ) + var xLog10Organization *string = log10go.String("") + ctx := context.Background() + res, err := s.Sessions.Create(ctx, xLog10Organization) + if err != nil { + log.Fatal(err) + } + if res.Object != nil { + // handle response + } +} + +``` + + + +## Available Resources and Operations + +### [Completions](docs/sdks/completions/README.md) + +* [Create](docs/sdks/completions/README.md#create) - Create a completion +* [Update](docs/sdks/completions/README.md#update) - Update completion by id. +* [ListUngraded](docs/sdks/completions/README.md#listungraded) - List ungraded completions i.e. completions that have not been associated with feedback but matches task selector. + +### [Sessions](docs/sdks/sessions/README.md) + +* [Create](docs/sdks/sessions/README.md#create) - Create a session + +### [Feedback](docs/sdks/feedback/README.md) + +* [Get](docs/sdks/feedback/README.md#get) - Fetch feedback by id. +* [List](docs/sdks/feedback/README.md#list) - List feedback +* [Upload](docs/sdks/feedback/README.md#upload) - Upload a piece of feedback + +### [FeedbackTasks](docs/sdks/feedbacktasks/README.md) + +* [List](docs/sdks/feedbacktasks/README.md#list) - List feedback tasks. +* [Create](docs/sdks/feedbacktasks/README.md#create) - Create a new task. +* [Get](docs/sdks/feedbacktasks/README.md#get) - Retrieves feedback task `taskId`. + + + +## Global Parameters + +A parameter is configured globally. This parameter must be set on the SDK client instance itself during initialization. When configured as an option during SDK initialization, This global value will be used as the default on the operations that use it. When such operations are called, there is a place in each to override the global value, if needed. + +For example, you can set `X-Log10-Organization` to `""` at SDK initialization and then you do not have to pass the same value on calls to operations like `Update`. But if you want to do so you may, which will locally override the global setting. See the example code below for a demonstration. + + +### Available Globals + +The following global parameter is available. The required parameter must be set when you initialize the SDK client. + +| Name | Type | Required | Description | +| ---- | ---- |:--------:| ----------- | +| XLog10Organization | string | ✔️ | The XLog10Organization parameter. | + + +### Example + +```go +package main + +import ( + "context" + "github.com/log10-io/log10go" + "github.com/log10-io/log10go/models/components" + "log" +) + +func main() { + s := log10go.New( + log10go.WithSecurity(""), + log10go.WithXLog10Organization(""), + ) + var completionID string = "" + + completion := components.Completion{ + OrganizationID: "", + Request: &components.CreateChatCompletionRequest{ + Messages: []components.ChatCompletionRequestMessage{ + components.CreateChatCompletionRequestMessageChatCompletionRequestFunctionMessage( + components.ChatCompletionRequestFunctionMessage{ + Role: components.ChatCompletionRequestFunctionMessageRoleFunction, + Content: "", + Name: "", + }, + ), + }, + Model: components.CreateModelTwo( + components.TwoGpt4Turbo, + ), + N: log10go.Int64(1), + ResponseFormat: &components.ResponseFormat{ + Type: components.CreateChatCompletionRequestTypeJSONObject.ToPointer(), + }, + Temperature: log10go.Float64(1), + TopP: log10go.Float64(1), + User: log10go.String("user-1234"), + }, + } + + var xLog10Organization *string = log10go.String("") + ctx := context.Background() + res, err := s.Completions.Update(ctx, completionID, completion, xLog10Organization) + if err != nil { + log.Fatal(err) + } + if res.Completion != nil { + // handle response + } +} + +``` + + + +## Error Handling + +Handling errors in this SDK should largely match your expectations. All operations return a response object or an error, they will never return both. When specified by the OpenAPI spec document, the SDK will return the appropriate subclass. + +| Error Object | Status Code | Content Type | +| ------------------ | ------------------ | ------------------ | +| sdkerrors.SDKError | 4xx-5xx | */* | + +### Example + +```go +package main + +import ( + "context" + "errors" + "github.com/log10-io/log10go" + "github.com/log10-io/log10go/models/components" + "github.com/log10-io/log10go/models/sdkerrors" + "log" +) + +func main() { + s := log10go.New( + log10go.WithSecurity(""), + log10go.WithXLog10Organization(""), + ) + completion := components.Completion{ + OrganizationID: "", + Request: &components.CreateChatCompletionRequest{ + Messages: []components.ChatCompletionRequestMessage{ + components.CreateChatCompletionRequestMessageChatCompletionRequestAssistantMessage( + components.ChatCompletionRequestAssistantMessage{ + Role: components.ChatCompletionRequestAssistantMessageRoleAssistant, + }, + ), + }, + Model: components.CreateModelTwo( + components.TwoGpt4Turbo, + ), + N: log10go.Int64(1), + ResponseFormat: &components.ResponseFormat{ + Type: components.CreateChatCompletionRequestTypeJSONObject.ToPointer(), + }, + Temperature: log10go.Float64(1), + TopP: log10go.Float64(1), + User: log10go.String("user-1234"), + }, + } + + var xLog10Organization *string = log10go.String("") + ctx := context.Background() + res, err := s.Completions.Create(ctx, completion, xLog10Organization) + if err != nil { + + var e *sdkerrors.SDKError + if errors.As(err, &e) { + // handle error + log.Fatal(e.Error()) + } + } +} + +``` + + + +## Server Selection + +### Select Server by Index + +You can override the default server globally using the `WithServerIndex` option when initializing the SDK client instance. The selected server will then be used as the default on the operations that use it. This table lists the indexes associated with the available servers: + +| # | Server | Variables | +| - | ------ | --------- | +| 0 | `https://log10.io` | None | + +#### Example + +```go +package main + +import ( + "context" + "github.com/log10-io/log10go" + "github.com/log10-io/log10go/models/components" + "log" +) + +func main() { + s := log10go.New( + log10go.WithServerIndex(0), + log10go.WithSecurity(""), + log10go.WithXLog10Organization(""), + ) + completion := components.Completion{ + OrganizationID: "", + Request: &components.CreateChatCompletionRequest{ + Messages: []components.ChatCompletionRequestMessage{ + components.CreateChatCompletionRequestMessageChatCompletionRequestAssistantMessage( + components.ChatCompletionRequestAssistantMessage{ + Role: components.ChatCompletionRequestAssistantMessageRoleAssistant, + }, + ), + }, + Model: components.CreateModelTwo( + components.TwoGpt4Turbo, + ), + N: log10go.Int64(1), + ResponseFormat: &components.ResponseFormat{ + Type: components.CreateChatCompletionRequestTypeJSONObject.ToPointer(), + }, + Temperature: log10go.Float64(1), + TopP: log10go.Float64(1), + User: log10go.String("user-1234"), + }, + } + + var xLog10Organization *string = log10go.String("") + ctx := context.Background() + res, err := s.Completions.Create(ctx, completion, xLog10Organization) + if err != nil { + log.Fatal(err) + } + if res.Any != nil { + // handle response + } +} + +``` + + +### Override Server URL Per-Client + +The default server can also be overridden globally using the `WithServerURL` option when initializing the SDK client instance. For example: +```go +package main + +import ( + "context" + "github.com/log10-io/log10go" + "github.com/log10-io/log10go/models/components" + "log" +) + +func main() { + s := log10go.New( + log10go.WithServerURL("https://log10.io"), + log10go.WithSecurity(""), + log10go.WithXLog10Organization(""), + ) + completion := components.Completion{ + OrganizationID: "", + Request: &components.CreateChatCompletionRequest{ + Messages: []components.ChatCompletionRequestMessage{ + components.CreateChatCompletionRequestMessageChatCompletionRequestAssistantMessage( + components.ChatCompletionRequestAssistantMessage{ + Role: components.ChatCompletionRequestAssistantMessageRoleAssistant, + }, + ), + }, + Model: components.CreateModelTwo( + components.TwoGpt4Turbo, + ), + N: log10go.Int64(1), + ResponseFormat: &components.ResponseFormat{ + Type: components.CreateChatCompletionRequestTypeJSONObject.ToPointer(), + }, + Temperature: log10go.Float64(1), + TopP: log10go.Float64(1), + User: log10go.String("user-1234"), + }, + } + + var xLog10Organization *string = log10go.String("") + ctx := context.Background() + res, err := s.Completions.Create(ctx, completion, xLog10Organization) + if err != nil { + log.Fatal(err) + } + if res.Any != nil { + // handle response + } +} + +``` + + + +## Custom HTTP Client + +The Go SDK makes API calls that wrap an internal HTTP client. The requirements for the HTTP client are very simple. It must match this interface: + +```go +type HTTPClient interface { + Do(req *http.Request) (*http.Response, error) +} +``` + +The built-in `net/http` client satisfies this interface and a default client based on the built-in is provided by default. To replace this default with a client of your own, you can implement this interface yourself or provide your own client configured as desired. Here's a simple example, which adds a client with a 30 second timeout. + +```go +import ( + "net/http" + "time" + "github.com/myorg/your-go-sdk" +) + +var ( + httpClient = &http.Client{Timeout: 30 * time.Second} + sdkClient = sdk.New(sdk.WithClient(httpClient)) +) +``` + +This can be a convenient way to configure timeouts, cookies, proxies, custom headers, and other low-level configuration. + + + +## Authentication + +### Per-Client Security Schemes + +This SDK supports the following security scheme globally: + +| Name | Type | Scheme | +| ------------ | ------------ | ------------ | +| `Log10Token` | apiKey | API key | + +You can configure it using the `WithSecurity` option when initializing the SDK client instance. For example: +```go +package main + +import ( + "context" + "github.com/log10-io/log10go" + "github.com/log10-io/log10go/models/components" + "log" +) + +func main() { + s := log10go.New( + log10go.WithSecurity(""), + log10go.WithXLog10Organization(""), + ) + completion := components.Completion{ + OrganizationID: "", + Request: &components.CreateChatCompletionRequest{ + Messages: []components.ChatCompletionRequestMessage{ + components.CreateChatCompletionRequestMessageChatCompletionRequestAssistantMessage( + components.ChatCompletionRequestAssistantMessage{ + Role: components.ChatCompletionRequestAssistantMessageRoleAssistant, + }, + ), + }, + Model: components.CreateModelTwo( + components.TwoGpt4Turbo, + ), + N: log10go.Int64(1), + ResponseFormat: &components.ResponseFormat{ + Type: components.CreateChatCompletionRequestTypeJSONObject.ToPointer(), + }, + Temperature: log10go.Float64(1), + TopP: log10go.Float64(1), + User: log10go.String("user-1234"), + }, + } + + var xLog10Organization *string = log10go.String("") + ctx := context.Background() + res, err := s.Completions.Create(ctx, completion, xLog10Organization) + if err != nil { + log.Fatal(err) + } + if res.Any != nil { + // handle response + } +} + +``` + + + +## Special Types + + + + + + +# Development + +## Maturity + +This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage +to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally +looking for the latest version. + +## Contributions + +While we value open-source contributions to this SDK, this library is generated programmatically. +Feel free to open a PR or a Github issue as a proof of concept and we'll do our best to include it in a future release! + +### SDK Created by [Speakeasy](https://docs.speakeasyapi.dev/docs/using-speakeasy/client-sdks) diff --git a/USAGE.md b/USAGE.md new file mode 100644 index 0000000..f80117f --- /dev/null +++ b/USAGE.md @@ -0,0 +1,28 @@ + +```go +package main + +import ( + "context" + "github.com/log10-io/log10go" + "log" +) + +func main() { + s := log10go.New( + log10go.WithSecurity(""), + log10go.WithXLog10Organization(""), + ) + var xLog10Organization *string = log10go.String("") + ctx := context.Background() + res, err := s.Sessions.Create(ctx, xLog10Organization) + if err != nil { + log.Fatal(err) + } + if res.Object != nil { + // handle response + } +} + +``` + \ No newline at end of file diff --git a/completions.go b/completions.go new file mode 100644 index 0000000..2a61ea0 --- /dev/null +++ b/completions.go @@ -0,0 +1,375 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package log10go + +import ( + "bytes" + "context" + "fmt" + "github.com/log10-io/log10go/internal/hooks" + "github.com/log10-io/log10go/internal/utils" + "github.com/log10-io/log10go/models/components" + "github.com/log10-io/log10go/models/operations" + "github.com/log10-io/log10go/models/sdkerrors" + "io" + "net/http" +) + +// Completions +type Completions struct { + sdkConfiguration sdkConfiguration +} + +func newCompletions(sdkConfig sdkConfiguration) *Completions { + return &Completions{ + sdkConfiguration: sdkConfig, + } +} + +// Create a completion +func (s *Completions) Create(ctx context.Context, completion components.Completion, xLog10Organization *string) (*operations.CreateResponse, error) { + hookCtx := hooks.HookContext{ + Context: ctx, + OperationID: "create", + SecuritySource: s.sdkConfiguration.Security, + } + + request := operations.CreateRequest{ + XLog10Organization: xLog10Organization, + Completion: completion, + } + + globals := operations.CreateGlobals{ + XLog10Organization: s.sdkConfiguration.Globals.XLog10Organization, + } + + baseURL := utils.ReplaceParameters(s.sdkConfiguration.GetServerDetails()) + opURL, err := utils.GenerateURL(ctx, baseURL, "/api/v1/completions", request, globals) + if err != nil { + return nil, fmt.Errorf("error generating URL: %w", err) + } + + bodyReader, reqContentType, err := utils.SerializeRequestBody(ctx, request, false, false, "Completion", "json", `request:"mediaType=application/json"`) + if err != nil { + return nil, err + } + + req, err := http.NewRequestWithContext(ctx, "POST", opURL, bodyReader) + if err != nil { + return nil, fmt.Errorf("error creating request: %w", err) + } + req.Header.Set("Accept", "application/json") + req.Header.Set("User-Agent", s.sdkConfiguration.UserAgent) + req.Header.Set("Content-Type", reqContentType) + + utils.PopulateHeaders(ctx, req, request, globals) + + if err := utils.PopulateQueryParams(ctx, req, request, globals); err != nil { + return nil, fmt.Errorf("error populating query params: %w", err) + } + + if err := utils.PopulateSecurity(ctx, req, s.sdkConfiguration.Security); err != nil { + return nil, err + } + + req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + if err != nil { + return nil, err + } + + httpRes, err := s.sdkConfiguration.Client.Do(req) + if err != nil || httpRes == nil { + if err != nil { + err = fmt.Errorf("error sending request: %w", err) + } else { + err = fmt.Errorf("error sending request: no response") + } + + _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + return nil, err + } else if utils.MatchStatusCodes([]string{"4XX", "5XX"}, httpRes.StatusCode) { + _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) + if err != nil { + return nil, err + } else if _httpRes != nil { + httpRes = _httpRes + } + } else { + httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) + if err != nil { + return nil, err + } + } + + res := &operations.CreateResponse{ + HTTPMeta: components.HTTPMetadata{ + Request: req, + Response: httpRes, + }, + } + + rawBody, err := io.ReadAll(httpRes.Body) + if err != nil { + return nil, fmt.Errorf("error reading response body: %w", err) + } + httpRes.Body.Close() + httpRes.Body = io.NopCloser(bytes.NewBuffer(rawBody)) + + switch { + case httpRes.StatusCode == 200: + switch { + case utils.MatchContentType(httpRes.Header.Get("Content-Type"), `application/json`): + var out any + if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { + return nil, err + } + + res.Any = out + default: + return nil, sdkerrors.NewSDKError(fmt.Sprintf("unknown content-type received: %s", httpRes.Header.Get("Content-Type")), httpRes.StatusCode, string(rawBody), httpRes) + } + case httpRes.StatusCode == 201: + switch { + case utils.MatchContentType(httpRes.Header.Get("Content-Type"), `application/json`): + var out components.Completion + if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { + return nil, err + } + + res.Completion = &out + default: + return nil, sdkerrors.NewSDKError(fmt.Sprintf("unknown content-type received: %s", httpRes.Header.Get("Content-Type")), httpRes.StatusCode, string(rawBody), httpRes) + } + case httpRes.StatusCode >= 400 && httpRes.StatusCode < 500: + fallthrough + case httpRes.StatusCode >= 500 && httpRes.StatusCode < 600: + return nil, sdkerrors.NewSDKError("API error occurred", httpRes.StatusCode, string(rawBody), httpRes) + default: + return nil, sdkerrors.NewSDKError("unknown status code returned", httpRes.StatusCode, string(rawBody), httpRes) + } + + return res, nil + +} + +// Update completion by id. +func (s *Completions) Update(ctx context.Context, completionID string, completion components.Completion, xLog10Organization *string) (*operations.UpdateResponse, error) { + hookCtx := hooks.HookContext{ + Context: ctx, + OperationID: "update", + SecuritySource: s.sdkConfiguration.Security, + } + + request := operations.UpdateRequest{ + CompletionID: completionID, + XLog10Organization: xLog10Organization, + Completion: completion, + } + + globals := operations.UpdateGlobals{ + XLog10Organization: s.sdkConfiguration.Globals.XLog10Organization, + } + + baseURL := utils.ReplaceParameters(s.sdkConfiguration.GetServerDetails()) + opURL, err := utils.GenerateURL(ctx, baseURL, "/api/v1/completions/{completionId}", request, globals) + if err != nil { + return nil, fmt.Errorf("error generating URL: %w", err) + } + + bodyReader, reqContentType, err := utils.SerializeRequestBody(ctx, request, false, false, "Completion", "json", `request:"mediaType=application/json"`) + if err != nil { + return nil, err + } + + req, err := http.NewRequestWithContext(ctx, "POST", opURL, bodyReader) + if err != nil { + return nil, fmt.Errorf("error creating request: %w", err) + } + req.Header.Set("Accept", "application/json") + req.Header.Set("User-Agent", s.sdkConfiguration.UserAgent) + req.Header.Set("Content-Type", reqContentType) + + utils.PopulateHeaders(ctx, req, request, globals) + + if err := utils.PopulateQueryParams(ctx, req, request, globals); err != nil { + return nil, fmt.Errorf("error populating query params: %w", err) + } + + if err := utils.PopulateSecurity(ctx, req, s.sdkConfiguration.Security); err != nil { + return nil, err + } + + req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + if err != nil { + return nil, err + } + + httpRes, err := s.sdkConfiguration.Client.Do(req) + if err != nil || httpRes == nil { + if err != nil { + err = fmt.Errorf("error sending request: %w", err) + } else { + err = fmt.Errorf("error sending request: no response") + } + + _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + return nil, err + } else if utils.MatchStatusCodes([]string{"4XX", "5XX"}, httpRes.StatusCode) { + _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) + if err != nil { + return nil, err + } else if _httpRes != nil { + httpRes = _httpRes + } + } else { + httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) + if err != nil { + return nil, err + } + } + + res := &operations.UpdateResponse{ + HTTPMeta: components.HTTPMetadata{ + Request: req, + Response: httpRes, + }, + } + + rawBody, err := io.ReadAll(httpRes.Body) + if err != nil { + return nil, fmt.Errorf("error reading response body: %w", err) + } + httpRes.Body.Close() + httpRes.Body = io.NopCloser(bytes.NewBuffer(rawBody)) + + switch { + case httpRes.StatusCode == 200: + switch { + case utils.MatchContentType(httpRes.Header.Get("Content-Type"), `application/json`): + var out components.Completion + if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { + return nil, err + } + + res.Completion = &out + default: + return nil, sdkerrors.NewSDKError(fmt.Sprintf("unknown content-type received: %s", httpRes.Header.Get("Content-Type")), httpRes.StatusCode, string(rawBody), httpRes) + } + case httpRes.StatusCode >= 400 && httpRes.StatusCode < 500: + fallthrough + case httpRes.StatusCode >= 500 && httpRes.StatusCode < 600: + return nil, sdkerrors.NewSDKError("API error occurred", httpRes.StatusCode, string(rawBody), httpRes) + default: + return nil, sdkerrors.NewSDKError("unknown status code returned", httpRes.StatusCode, string(rawBody), httpRes) + } + + return res, nil + +} + +// ListUngraded - List ungraded completions i.e. completions that have not been associated with feedback but matches task selector. +func (s *Completions) ListUngraded(ctx context.Context, xLog10Organization *string) (*operations.ListUngradedResponse, error) { + hookCtx := hooks.HookContext{ + Context: ctx, + OperationID: "listUngraded", + SecuritySource: s.sdkConfiguration.Security, + } + + request := operations.ListUngradedRequest{ + XLog10Organization: xLog10Organization, + } + + globals := operations.ListUngradedGlobals{ + XLog10Organization: s.sdkConfiguration.Globals.XLog10Organization, + } + + baseURL := utils.ReplaceParameters(s.sdkConfiguration.GetServerDetails()) + opURL, err := utils.GenerateURL(ctx, baseURL, "/api/v1/completions/ungraded", request, globals) + if err != nil { + return nil, fmt.Errorf("error generating URL: %w", err) + } + + req, err := http.NewRequestWithContext(ctx, "GET", opURL, nil) + if err != nil { + return nil, fmt.Errorf("error creating request: %w", err) + } + req.Header.Set("Accept", "application/json") + req.Header.Set("User-Agent", s.sdkConfiguration.UserAgent) + + utils.PopulateHeaders(ctx, req, request, globals) + + if err := utils.PopulateQueryParams(ctx, req, request, globals); err != nil { + return nil, fmt.Errorf("error populating query params: %w", err) + } + + if err := utils.PopulateSecurity(ctx, req, s.sdkConfiguration.Security); err != nil { + return nil, err + } + + req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + if err != nil { + return nil, err + } + + httpRes, err := s.sdkConfiguration.Client.Do(req) + if err != nil || httpRes == nil { + if err != nil { + err = fmt.Errorf("error sending request: %w", err) + } else { + err = fmt.Errorf("error sending request: no response") + } + + _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + return nil, err + } else if utils.MatchStatusCodes([]string{"4XX", "5XX"}, httpRes.StatusCode) { + _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) + if err != nil { + return nil, err + } else if _httpRes != nil { + httpRes = _httpRes + } + } else { + httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) + if err != nil { + return nil, err + } + } + + res := &operations.ListUngradedResponse{ + HTTPMeta: components.HTTPMetadata{ + Request: req, + Response: httpRes, + }, + } + + rawBody, err := io.ReadAll(httpRes.Body) + if err != nil { + return nil, fmt.Errorf("error reading response body: %w", err) + } + httpRes.Body.Close() + httpRes.Body = io.NopCloser(bytes.NewBuffer(rawBody)) + + switch { + case httpRes.StatusCode == 200: + switch { + case utils.MatchContentType(httpRes.Header.Get("Content-Type"), `application/json`): + var out operations.ListUngradedResponseBody + if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { + return nil, err + } + + res.Object = &out + default: + return nil, sdkerrors.NewSDKError(fmt.Sprintf("unknown content-type received: %s", httpRes.Header.Get("Content-Type")), httpRes.StatusCode, string(rawBody), httpRes) + } + case httpRes.StatusCode >= 400 && httpRes.StatusCode < 500: + fallthrough + case httpRes.StatusCode >= 500 && httpRes.StatusCode < 600: + return nil, sdkerrors.NewSDKError("API error occurred", httpRes.StatusCode, string(rawBody), httpRes) + default: + return nil, sdkerrors.NewSDKError("unknown status code returned", httpRes.StatusCode, string(rawBody), httpRes) + } + + return res, nil + +} diff --git a/docs/models/components/chatcompletionfunctioncalloption.md b/docs/models/components/chatcompletionfunctioncalloption.md new file mode 100644 index 0000000..86e74de --- /dev/null +++ b/docs/models/components/chatcompletionfunctioncalloption.md @@ -0,0 +1,11 @@ +# ChatCompletionFunctionCallOption + +Specifying a particular function via `{"name": "my_function"}` forces the model to call that function. + + + +## Fields + +| Field | Type | Required | Description | +| --------------------------------- | --------------------------------- | --------------------------------- | --------------------------------- | +| `Name` | *string* | :heavy_check_mark: | The name of the function to call. | \ No newline at end of file diff --git a/docs/models/components/chatcompletionfunctions.md b/docs/models/components/chatcompletionfunctions.md new file mode 100644 index 0000000..caf61ec --- /dev/null +++ b/docs/models/components/chatcompletionfunctions.md @@ -0,0 +1,12 @@ +# ~~ChatCompletionFunctions~~ + +> :warning: **DEPRECATED**: This will be removed in a future release, please migrate away from it as soon as possible. + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `Description` | **string* | :heavy_minus_sign: | A description of what the function does, used by the model to choose when and how to call the function. | +| `Name` | *string* | :heavy_check_mark: | The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64. | +| `Parameters` | map[string]*any* | :heavy_minus_sign: | The parameters the functions accepts, described as a JSON Schema object. See the [guide](/docs/guides/text-generation/function-calling) for examples, and the [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for documentation about the format.

Omitting `parameters` defines a function with an empty parameter list. | \ No newline at end of file diff --git a/docs/models/components/chatcompletionmessagetoolcall.md b/docs/models/components/chatcompletionmessagetoolcall.md new file mode 100644 index 0000000..2e12fed --- /dev/null +++ b/docs/models/components/chatcompletionmessagetoolcall.md @@ -0,0 +1,10 @@ +# ChatCompletionMessageToolCall + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ | +| `ID` | *string* | :heavy_check_mark: | The ID of the tool call. | +| `Type` | [components.ChatCompletionMessageToolCallType](../../models/components/chatcompletionmessagetoolcalltype.md) | :heavy_check_mark: | The type of the tool. Currently, only `function` is supported. | +| `Function` | [components.Function](../../models/components/function.md) | :heavy_check_mark: | The function that the model called. | \ No newline at end of file diff --git a/docs/models/components/chatcompletionmessagetoolcalltype.md b/docs/models/components/chatcompletionmessagetoolcalltype.md new file mode 100644 index 0000000..3c48719 --- /dev/null +++ b/docs/models/components/chatcompletionmessagetoolcalltype.md @@ -0,0 +1,10 @@ +# ChatCompletionMessageToolCallType + +The type of the tool. Currently, only `function` is supported. + + +## Values + +| Name | Value | +| ------------------------------------------- | ------------------------------------------- | +| `ChatCompletionMessageToolCallTypeFunction` | function | \ No newline at end of file diff --git a/docs/models/components/chatcompletionnamedtoolchoice.md b/docs/models/components/chatcompletionnamedtoolchoice.md new file mode 100644 index 0000000..2c81386 --- /dev/null +++ b/docs/models/components/chatcompletionnamedtoolchoice.md @@ -0,0 +1,11 @@ +# ChatCompletionNamedToolChoice + +Specifies a tool the model should use. Use to force the model to call a specific function. + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | +| `Type` | [components.ChatCompletionNamedToolChoiceType](../../models/components/chatcompletionnamedtoolchoicetype.md) | :heavy_check_mark: | The type of the tool. Currently, only `function` is supported. | +| `Function` | [components.ChatCompletionNamedToolChoiceFunction](../../models/components/chatcompletionnamedtoolchoicefunction.md) | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/components/chatcompletionnamedtoolchoicefunction.md b/docs/models/components/chatcompletionnamedtoolchoicefunction.md new file mode 100644 index 0000000..19150a9 --- /dev/null +++ b/docs/models/components/chatcompletionnamedtoolchoicefunction.md @@ -0,0 +1,8 @@ +# ChatCompletionNamedToolChoiceFunction + + +## Fields + +| Field | Type | Required | Description | +| --------------------------------- | --------------------------------- | --------------------------------- | --------------------------------- | +| `Name` | *string* | :heavy_check_mark: | The name of the function to call. | \ No newline at end of file diff --git a/docs/models/components/chatcompletionnamedtoolchoicetype.md b/docs/models/components/chatcompletionnamedtoolchoicetype.md new file mode 100644 index 0000000..e9fd716 --- /dev/null +++ b/docs/models/components/chatcompletionnamedtoolchoicetype.md @@ -0,0 +1,10 @@ +# ChatCompletionNamedToolChoiceType + +The type of the tool. Currently, only `function` is supported. + + +## Values + +| Name | Value | +| ------------------------------------------- | ------------------------------------------- | +| `ChatCompletionNamedToolChoiceTypeFunction` | function | \ No newline at end of file diff --git a/docs/models/components/chatcompletionrequestassistantmessage.md b/docs/models/components/chatcompletionrequestassistantmessage.md new file mode 100644 index 0000000..b8abb3b --- /dev/null +++ b/docs/models/components/chatcompletionrequestassistantmessage.md @@ -0,0 +1,12 @@ +# ChatCompletionRequestAssistantMessage + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `Content` | **string* | :heavy_minus_sign: | The contents of the assistant message. Required unless `tool_calls` or `function_call` is specified.
| +| `Role` | [components.ChatCompletionRequestAssistantMessageRole](../../models/components/chatcompletionrequestassistantmessagerole.md) | :heavy_check_mark: | The role of the messages author, in this case `assistant`. | +| `Name` | **string* | :heavy_minus_sign: | An optional name for the participant. Provides the model information to differentiate between participants of the same role. | +| `ToolCalls` | [][components.ChatCompletionMessageToolCall](../../models/components/chatcompletionmessagetoolcall.md) | :heavy_minus_sign: | The tool calls generated by the model, such as function calls. | +| ~~`FunctionCall`~~ | [*components.FunctionCall](../../models/components/functioncall.md) | :heavy_minus_sign: | : warning: ** DEPRECATED **: This will be removed in a future release, please migrate away from it as soon as possible.

Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be called, as generated by the model. | \ No newline at end of file diff --git a/docs/models/components/chatcompletionrequestassistantmessagerole.md b/docs/models/components/chatcompletionrequestassistantmessagerole.md new file mode 100644 index 0000000..a038f67 --- /dev/null +++ b/docs/models/components/chatcompletionrequestassistantmessagerole.md @@ -0,0 +1,10 @@ +# ChatCompletionRequestAssistantMessageRole + +The role of the messages author, in this case `assistant`. + + +## Values + +| Name | Value | +| ---------------------------------------------------- | ---------------------------------------------------- | +| `ChatCompletionRequestAssistantMessageRoleAssistant` | assistant | \ No newline at end of file diff --git a/docs/models/components/chatcompletionrequestfunctionmessage.md b/docs/models/components/chatcompletionrequestfunctionmessage.md new file mode 100644 index 0000000..91e46c9 --- /dev/null +++ b/docs/models/components/chatcompletionrequestfunctionmessage.md @@ -0,0 +1,12 @@ +# ~~ChatCompletionRequestFunctionMessage~~ + +> :warning: **DEPRECATED**: This will be removed in a future release, please migrate away from it as soon as possible. + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | +| `Role` | [components.ChatCompletionRequestFunctionMessageRole](../../models/components/chatcompletionrequestfunctionmessagerole.md) | :heavy_check_mark: | The role of the messages author, in this case `function`. | +| `Content` | *string* | :heavy_check_mark: | The contents of the function message. | +| `Name` | *string* | :heavy_check_mark: | The name of the function to call. | \ No newline at end of file diff --git a/docs/models/components/chatcompletionrequestfunctionmessagerole.md b/docs/models/components/chatcompletionrequestfunctionmessagerole.md new file mode 100644 index 0000000..454bb59 --- /dev/null +++ b/docs/models/components/chatcompletionrequestfunctionmessagerole.md @@ -0,0 +1,10 @@ +# ChatCompletionRequestFunctionMessageRole + +The role of the messages author, in this case `function`. + + +## Values + +| Name | Value | +| -------------------------------------------------- | -------------------------------------------------- | +| `ChatCompletionRequestFunctionMessageRoleFunction` | function | \ No newline at end of file diff --git a/docs/models/components/chatcompletionrequestmessage.md b/docs/models/components/chatcompletionrequestmessage.md new file mode 100644 index 0000000..cc89b2e --- /dev/null +++ b/docs/models/components/chatcompletionrequestmessage.md @@ -0,0 +1,35 @@ +# ChatCompletionRequestMessage + + +## Supported Types + +### ChatCompletionRequestSystemMessage + +```go +chatCompletionRequestMessage := components.CreateChatCompletionRequestMessageChatCompletionRequestSystemMessage(components.ChatCompletionRequestSystemMessage{/* values here */}) +``` + +### ChatCompletionRequestUserMessage + +```go +chatCompletionRequestMessage := components.CreateChatCompletionRequestMessageChatCompletionRequestUserMessage(components.ChatCompletionRequestUserMessage{/* values here */}) +``` + +### ChatCompletionRequestAssistantMessage + +```go +chatCompletionRequestMessage := components.CreateChatCompletionRequestMessageChatCompletionRequestAssistantMessage(components.ChatCompletionRequestAssistantMessage{/* values here */}) +``` + +### ChatCompletionRequestToolMessage + +```go +chatCompletionRequestMessage := components.CreateChatCompletionRequestMessageChatCompletionRequestToolMessage(components.ChatCompletionRequestToolMessage{/* values here */}) +``` + +### ChatCompletionRequestFunctionMessage + +```go +chatCompletionRequestMessage := components.CreateChatCompletionRequestMessageChatCompletionRequestFunctionMessage(components.ChatCompletionRequestFunctionMessage{/* values here */}) +``` + diff --git a/docs/models/components/chatcompletionrequestmessagecontentpart.md b/docs/models/components/chatcompletionrequestmessagecontentpart.md new file mode 100644 index 0000000..dec53f5 --- /dev/null +++ b/docs/models/components/chatcompletionrequestmessagecontentpart.md @@ -0,0 +1,17 @@ +# ChatCompletionRequestMessageContentPart + + +## Supported Types + +### ChatCompletionRequestMessageContentPartText + +```go +chatCompletionRequestMessageContentPart := components.CreateChatCompletionRequestMessageContentPartChatCompletionRequestMessageContentPartText(components.ChatCompletionRequestMessageContentPartText{/* values here */}) +``` + +### ChatCompletionRequestMessageContentPartImage + +```go +chatCompletionRequestMessageContentPart := components.CreateChatCompletionRequestMessageContentPartChatCompletionRequestMessageContentPartImage(components.ChatCompletionRequestMessageContentPartImage{/* values here */}) +``` + diff --git a/docs/models/components/chatcompletionrequestmessagecontentpartimage.md b/docs/models/components/chatcompletionrequestmessagecontentpartimage.md new file mode 100644 index 0000000..205829c --- /dev/null +++ b/docs/models/components/chatcompletionrequestmessagecontentpartimage.md @@ -0,0 +1,9 @@ +# ChatCompletionRequestMessageContentPartImage + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------ | +| `Type` | [components.ChatCompletionRequestMessageContentPartImageType](../../models/components/chatcompletionrequestmessagecontentpartimagetype.md) | :heavy_check_mark: | The type of the content part. | +| `ImageURL` | [components.ImageURL](../../models/components/imageurl.md) | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/components/chatcompletionrequestmessagecontentpartimagetype.md b/docs/models/components/chatcompletionrequestmessagecontentpartimagetype.md new file mode 100644 index 0000000..d07bb31 --- /dev/null +++ b/docs/models/components/chatcompletionrequestmessagecontentpartimagetype.md @@ -0,0 +1,10 @@ +# ChatCompletionRequestMessageContentPartImageType + +The type of the content part. + + +## Values + +| Name | Value | +| ---------------------------------------------------------- | ---------------------------------------------------------- | +| `ChatCompletionRequestMessageContentPartImageTypeImageURL` | image_url | \ No newline at end of file diff --git a/docs/models/components/chatcompletionrequestmessagecontentparttext.md b/docs/models/components/chatcompletionrequestmessagecontentparttext.md new file mode 100644 index 0000000..e7783c5 --- /dev/null +++ b/docs/models/components/chatcompletionrequestmessagecontentparttext.md @@ -0,0 +1,9 @@ +# ChatCompletionRequestMessageContentPartText + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------------- | -------------------------------------------------- | -------------------------------------------------- | -------------------------------------------------- | +| `Type` | [components.Type](../../models/components/type.md) | :heavy_check_mark: | The type of the content part. | +| `Text` | *string* | :heavy_check_mark: | The text content. | \ No newline at end of file diff --git a/docs/models/components/chatcompletionrequestsystemmessage.md b/docs/models/components/chatcompletionrequestsystemmessage.md new file mode 100644 index 0000000..462e3cf --- /dev/null +++ b/docs/models/components/chatcompletionrequestsystemmessage.md @@ -0,0 +1,10 @@ +# ChatCompletionRequestSystemMessage + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | +| `Content` | *string* | :heavy_check_mark: | The contents of the system message. | +| `Role` | [components.Role](../../models/components/role.md) | :heavy_check_mark: | The role of the messages author, in this case `system`. | +| `Name` | **string* | :heavy_minus_sign: | An optional name for the participant. Provides the model information to differentiate between participants of the same role. | \ No newline at end of file diff --git a/docs/models/components/chatcompletionrequesttoolmessage.md b/docs/models/components/chatcompletionrequesttoolmessage.md new file mode 100644 index 0000000..14a5905 --- /dev/null +++ b/docs/models/components/chatcompletionrequesttoolmessage.md @@ -0,0 +1,10 @@ +# ChatCompletionRequestToolMessage + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ | +| `Role` | [components.ChatCompletionRequestToolMessageRole](../../models/components/chatcompletionrequesttoolmessagerole.md) | :heavy_check_mark: | The role of the messages author, in this case `tool`. | +| `Content` | *string* | :heavy_check_mark: | The contents of the tool message. | +| `ToolCallID` | *string* | :heavy_check_mark: | Tool call that this message is responding to. | \ No newline at end of file diff --git a/docs/models/components/chatcompletionrequesttoolmessagerole.md b/docs/models/components/chatcompletionrequesttoolmessagerole.md new file mode 100644 index 0000000..721ba51 --- /dev/null +++ b/docs/models/components/chatcompletionrequesttoolmessagerole.md @@ -0,0 +1,10 @@ +# ChatCompletionRequestToolMessageRole + +The role of the messages author, in this case `tool`. + + +## Values + +| Name | Value | +| ------------------------------------------ | ------------------------------------------ | +| `ChatCompletionRequestToolMessageRoleTool` | tool | \ No newline at end of file diff --git a/docs/models/components/chatcompletionrequestusermessage.md b/docs/models/components/chatcompletionrequestusermessage.md new file mode 100644 index 0000000..cb9746a --- /dev/null +++ b/docs/models/components/chatcompletionrequestusermessage.md @@ -0,0 +1,10 @@ +# ChatCompletionRequestUserMessage + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | +| `Content` | [components.Content](../../models/components/content.md) | :heavy_check_mark: | The contents of the user message.
| +| `Role` | [components.ChatCompletionRequestUserMessageRole](../../models/components/chatcompletionrequestusermessagerole.md) | :heavy_check_mark: | The role of the messages author, in this case `user`. | +| `Name` | **string* | :heavy_minus_sign: | An optional name for the participant. Provides the model information to differentiate between participants of the same role. | \ No newline at end of file diff --git a/docs/models/components/chatcompletionrequestusermessagerole.md b/docs/models/components/chatcompletionrequestusermessagerole.md new file mode 100644 index 0000000..7acec46 --- /dev/null +++ b/docs/models/components/chatcompletionrequestusermessagerole.md @@ -0,0 +1,10 @@ +# ChatCompletionRequestUserMessageRole + +The role of the messages author, in this case `user`. + + +## Values + +| Name | Value | +| ------------------------------------------ | ------------------------------------------ | +| `ChatCompletionRequestUserMessageRoleUser` | user | \ No newline at end of file diff --git a/docs/models/components/chatcompletionresponsemessage.md b/docs/models/components/chatcompletionresponsemessage.md new file mode 100644 index 0000000..83780c8 --- /dev/null +++ b/docs/models/components/chatcompletionresponsemessage.md @@ -0,0 +1,13 @@ +# ChatCompletionResponseMessage + +A chat completion message generated by the model. + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `Content` | *string* | :heavy_check_mark: | The contents of the message. | +| `ToolCalls` | [][components.ChatCompletionMessageToolCall](../../models/components/chatcompletionmessagetoolcall.md) | :heavy_minus_sign: | The tool calls generated by the model, such as function calls. | +| `Role` | [components.ChatCompletionResponseMessageRole](../../models/components/chatcompletionresponsemessagerole.md) | :heavy_check_mark: | The role of the author of this message. | +| ~~`FunctionCall`~~ | [*components.ChatCompletionResponseMessageFunctionCall](../../models/components/chatcompletionresponsemessagefunctioncall.md) | :heavy_minus_sign: | : warning: ** DEPRECATED **: This will be removed in a future release, please migrate away from it as soon as possible.

Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be called, as generated by the model. | \ No newline at end of file diff --git a/docs/models/components/chatcompletionresponsemessagefunctioncall.md b/docs/models/components/chatcompletionresponsemessagefunctioncall.md new file mode 100644 index 0000000..6e57b78 --- /dev/null +++ b/docs/models/components/chatcompletionresponsemessagefunctioncall.md @@ -0,0 +1,13 @@ +# ~~ChatCompletionResponseMessageFunctionCall~~ + +Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be called, as generated by the model. + +> :warning: **DEPRECATED**: This will be removed in a future release, please migrate away from it as soon as possible. + + +## Fields + +| Field | Type | Required | Description | +| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `Arguments` | *string* | :heavy_check_mark: | The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function. | +| `Name` | *string* | :heavy_check_mark: | The name of the function to call. | \ No newline at end of file diff --git a/docs/models/components/chatcompletionresponsemessagerole.md b/docs/models/components/chatcompletionresponsemessagerole.md new file mode 100644 index 0000000..0afbecf --- /dev/null +++ b/docs/models/components/chatcompletionresponsemessagerole.md @@ -0,0 +1,10 @@ +# ChatCompletionResponseMessageRole + +The role of the author of this message. + + +## Values + +| Name | Value | +| -------------------------------------------- | -------------------------------------------- | +| `ChatCompletionResponseMessageRoleAssistant` | assistant | \ No newline at end of file diff --git a/docs/models/components/chatcompletionstreamoptions.md b/docs/models/components/chatcompletionstreamoptions.md new file mode 100644 index 0000000..f2ee645 --- /dev/null +++ b/docs/models/components/chatcompletionstreamoptions.md @@ -0,0 +1,11 @@ +# ChatCompletionStreamOptions + +Options for streaming response. Only set this when you set `stream: true`. + + + +## Fields + +| Field | Type | Required | Description | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `IncludeUsage` | **bool* | :heavy_minus_sign: | If set, an additional chunk will be streamed before the `data: [DONE]` message. The `usage` field on this chunk shows the token usage statistics for the entire request, and the `choices` field will always be an empty array. All other chunks will also include a `usage` field, but with a null value.
| \ No newline at end of file diff --git a/docs/models/components/chatcompletiontokenlogprob.md b/docs/models/components/chatcompletiontokenlogprob.md new file mode 100644 index 0000000..7231525 --- /dev/null +++ b/docs/models/components/chatcompletiontokenlogprob.md @@ -0,0 +1,11 @@ +# ChatCompletionTokenLogprob + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `Token` | *string* | :heavy_check_mark: | The token. | +| `Logprob` | *float64* | :heavy_check_mark: | The log probability of this token, if it is within the top 20 most likely tokens. Otherwise, the value `-9999.0` is used to signify that the token is very unlikely. | +| `Bytes` | []*int64* | :heavy_check_mark: | A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and their byte representations must be combined to generate the correct text representation. Can be `null` if there is no bytes representation for the token. | +| `TopLogprobs` | [][components.TopLogprobs](../../models/components/toplogprobs.md) | :heavy_check_mark: | List of the most likely tokens and their log probability, at this token position. In rare cases, there may be fewer than the number of requested `top_logprobs` returned. | \ No newline at end of file diff --git a/docs/models/components/chatcompletiontool.md b/docs/models/components/chatcompletiontool.md new file mode 100644 index 0000000..994bf1d --- /dev/null +++ b/docs/models/components/chatcompletiontool.md @@ -0,0 +1,9 @@ +# ChatCompletionTool + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | +| `Type` | [components.ChatCompletionToolType](../../models/components/chatcompletiontooltype.md) | :heavy_check_mark: | The type of the tool. Currently, only `function` is supported. | +| `Function` | [components.FunctionObject](../../models/components/functionobject.md) | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/components/chatcompletiontoolchoiceoption.md b/docs/models/components/chatcompletiontoolchoiceoption.md new file mode 100644 index 0000000..6308053 --- /dev/null +++ b/docs/models/components/chatcompletiontoolchoiceoption.md @@ -0,0 +1,26 @@ +# ChatCompletionToolChoiceOption + +Controls which (if any) tool is called by the model. +`none` means the model will not call any tool and instead generates a message. +`auto` means the model can pick between generating a message or calling one or more tools. +`required` means the model must call one or more tools. +Specifying a particular tool via `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. + +`none` is the default when no tools are present. `auto` is the default if tools are present. + + + +## Supported Types + +### ChatCompletionToolChoiceOption1 + +```go +chatCompletionToolChoiceOption := components.CreateChatCompletionToolChoiceOptionChatCompletionToolChoiceOption1(components.ChatCompletionToolChoiceOption1{/* values here */}) +``` + +### ChatCompletionNamedToolChoice + +```go +chatCompletionToolChoiceOption := components.CreateChatCompletionToolChoiceOptionChatCompletionNamedToolChoice(components.ChatCompletionNamedToolChoice{/* values here */}) +``` + diff --git a/docs/models/components/chatcompletiontoolchoiceoption1.md b/docs/models/components/chatcompletiontoolchoiceoption1.md new file mode 100644 index 0000000..dec9248 --- /dev/null +++ b/docs/models/components/chatcompletiontoolchoiceoption1.md @@ -0,0 +1,13 @@ +# ChatCompletionToolChoiceOption1 + +`none` means the model will not call any tool and instead generates a message. `auto` means the model can pick between generating a message or calling one or more tools. `required` means the model must call one or more tools. + + + +## Values + +| Name | Value | +| ----------------------------------------- | ----------------------------------------- | +| `ChatCompletionToolChoiceOption1None` | none | +| `ChatCompletionToolChoiceOption1Auto` | auto | +| `ChatCompletionToolChoiceOption1Required` | required | \ No newline at end of file diff --git a/docs/models/components/chatcompletiontooltype.md b/docs/models/components/chatcompletiontooltype.md new file mode 100644 index 0000000..f5a0a29 --- /dev/null +++ b/docs/models/components/chatcompletiontooltype.md @@ -0,0 +1,10 @@ +# ChatCompletionToolType + +The type of the tool. Currently, only `function` is supported. + + +## Values + +| Name | Value | +| -------------------------------- | -------------------------------- | +| `ChatCompletionToolTypeFunction` | function | \ No newline at end of file diff --git a/docs/models/components/choices.md b/docs/models/components/choices.md new file mode 100644 index 0000000..bcb0b36 --- /dev/null +++ b/docs/models/components/choices.md @@ -0,0 +1,11 @@ +# Choices + + +## Fields + +| Field | Type | Required | Description | +| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `FinishReason` | [components.FinishReason](../../models/components/finishreason.md) | :heavy_check_mark: | The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence,
`length` if the maximum number of tokens specified in the request was reached,
`content_filter` if content was omitted due to a flag from our content filters,
`tool_calls` if the model called a tool, or `function_call` (deprecated) if the model called a function.
| +| `Index` | *int64* | :heavy_check_mark: | The index of the choice in the list of choices. | +| `Message` | [components.ChatCompletionResponseMessage](../../models/components/chatcompletionresponsemessage.md) | :heavy_check_mark: | A chat completion message generated by the model. | +| `Logprobs` | [components.Logprobs](../../models/components/logprobs.md) | :heavy_check_mark: | Log probability information for the choice. | \ No newline at end of file diff --git a/docs/models/components/completion.md b/docs/models/components/completion.md new file mode 100644 index 0000000..6771eea --- /dev/null +++ b/docs/models/components/completion.md @@ -0,0 +1,19 @@ +# Completion + + +## Fields + +| Field | Type | Required | Description | +| --------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- | +| `ID` | **string* | :heavy_minus_sign: | The unique identifier for this task. | +| `OrganizationID` | *string* | :heavy_check_mark: | The unique identifier for the organization. | +| `Kind` | [*components.Kind](../../models/components/kind.md) | :heavy_minus_sign: | The kind of completion i.e. chat messages or prompt | +| `Status` | [*components.Status](../../models/components/status.md) | :heavy_minus_sign: | The status of this completion. | +| `Tags` | []*string* | :heavy_minus_sign: | The tags for this completion. | +| `Request` | [*components.CreateChatCompletionRequest](../../models/components/createchatcompletionrequest.md) | :heavy_minus_sign: | N/A | +| `Response` | [*components.CreateChatCompletionResponse](../../models/components/createchatcompletionresponse.md) | :heavy_minus_sign: | Represents a chat completion response returned by model, based on the provided input. | +| `Stacktrace` | [][components.Stacktrace](../../models/components/stacktrace.md) | :heavy_minus_sign: | The stacktrace for this completion. | +| `SessionID` | **string* | :heavy_minus_sign: | The session id for this completion. | +| `Duration` | **float64* | :heavy_minus_sign: | The duration of this completion in seconds. | +| `FailureKind` | **string* | :heavy_minus_sign: | The failure kind of this completion. | +| `FailureReason` | **string* | :heavy_minus_sign: | The failure reason of this completion. | \ No newline at end of file diff --git a/docs/models/components/completiontagsselector.md b/docs/models/components/completiontagsselector.md new file mode 100644 index 0000000..8644225 --- /dev/null +++ b/docs/models/components/completiontagsselector.md @@ -0,0 +1,9 @@ +# CompletionTagsSelector + +The completion tag matching with this task i.e. surfaced as needing feedback. + + +## Fields + +| Field | Type | Required | Description | +| ----------- | ----------- | ----------- | ----------- | \ No newline at end of file diff --git a/docs/models/components/completionusage.md b/docs/models/components/completionusage.md new file mode 100644 index 0000000..d62d7e7 --- /dev/null +++ b/docs/models/components/completionusage.md @@ -0,0 +1,12 @@ +# CompletionUsage + +Usage statistics for the completion request. + + +## Fields + +| Field | Type | Required | Description | +| ----------------------------------------------------------------- | ----------------------------------------------------------------- | ----------------------------------------------------------------- | ----------------------------------------------------------------- | +| `CompletionTokens` | *int64* | :heavy_check_mark: | Number of tokens in the generated completion. | +| `PromptTokens` | *int64* | :heavy_check_mark: | Number of tokens in the prompt. | +| `TotalTokens` | *int64* | :heavy_check_mark: | Total number of tokens used in the request (prompt + completion). | \ No newline at end of file diff --git a/docs/models/components/content.md b/docs/models/components/content.md new file mode 100644 index 0000000..0b48754 --- /dev/null +++ b/docs/models/components/content.md @@ -0,0 +1,20 @@ +# Content + +The contents of the user message. + + + +## Supported Types + +### + +```go +content := components.CreateContentStr(string{/* values here */}) +``` + +### + +```go +content := components.CreateContentArrayOfChatCompletionRequestMessageContentPart([]components.ChatCompletionRequestMessageContentPart{/* values here */}) +``` + diff --git a/docs/models/components/createchatcompletionrequest.md b/docs/models/components/createchatcompletionrequest.md new file mode 100644 index 0000000..feb44cb --- /dev/null +++ b/docs/models/components/createchatcompletionrequest.md @@ -0,0 +1,28 @@ +# CreateChatCompletionRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `Messages` | [][components.ChatCompletionRequestMessage](../../models/components/chatcompletionrequestmessage.md) | :heavy_check_mark: | A list of messages comprising the conversation so far. [Example Python code](https://cookbook.openai.com/examples/how_to_format_inputs_to_chatgpt_models). | | +| `Model` | [components.Model](../../models/components/model.md) | :heavy_check_mark: | ID of the model to use. See the [model endpoint compatibility](/docs/models/model-endpoint-compatibility) table for details on which models work with the Chat API. | gpt-4-turbo | +| `FrequencyPenalty` | **float64* | :heavy_minus_sign: | Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim.

[See more information about frequency and presence penalties.](/docs/guides/text-generation/parameter-details)
| | +| `LogitBias` | map[string]*int64* | :heavy_minus_sign: | Modify the likelihood of specified tokens appearing in the completion.

Accepts a JSON object that maps tokens (specified by their token ID in the tokenizer) to an associated bias value from -100 to 100. Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model, but values between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 should result in a ban or exclusive selection of the relevant token.
| | +| `Logprobs` | **bool* | :heavy_minus_sign: | Whether to return log probabilities of the output tokens or not. If true, returns the log probabilities of each output token returned in the `content` of `message`. | | +| `TopLogprobs` | **int64* | :heavy_minus_sign: | An integer between 0 and 20 specifying the number of most likely tokens to return at each token position, each with an associated log probability. `logprobs` must be set to `true` if this parameter is used. | | +| `MaxTokens` | **int64* | :heavy_minus_sign: | The maximum number of [tokens](/tokenizer) that can be generated in the chat completion.

The total length of input tokens and generated tokens is limited by the model's context length. [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) for counting tokens.
| | +| `N` | **int64* | :heavy_minus_sign: | How many chat completion choices to generate for each input message. Note that you will be charged based on the number of generated tokens across all of the choices. Keep `n` as `1` to minimize costs. | 1 | +| `PresencePenalty` | **float64* | :heavy_minus_sign: | Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics.

[See more information about frequency and presence penalties.](/docs/guides/text-generation/parameter-details)
| | +| `ResponseFormat` | [*components.ResponseFormat](../../models/components/responseformat.md) | :heavy_minus_sign: | An object specifying the format that the model must output. Compatible with [GPT-4 Turbo](/docs/models/gpt-4-and-gpt-4-turbo) and all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`.

Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON.

**Important:** when using JSON mode, you **must** also instruct the model to produce JSON yourself via a system or user message. Without this, the model may generate an unending stream of whitespace until the generation reaches the token limit, resulting in a long-running and seemingly "stuck" request. Also note that the message content may be partially cut off if `finish_reason="length"`, which indicates the generation exceeded `max_tokens` or the conversation exceeded the max context length.
| | +| `Seed` | **int64* | :heavy_minus_sign: | This feature is in Beta.
If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return the same result.
Determinism is not guaranteed, and you should refer to the `system_fingerprint` response parameter to monitor changes in the backend.
| | +| `Stop` | [*components.Stop](../../models/components/stop.md) | :heavy_minus_sign: | Up to 4 sequences where the API will stop generating further tokens.
| | +| `Stream` | **bool* | :heavy_minus_sign: | If set, partial message deltas will be sent, like in ChatGPT. Tokens will be sent as data-only [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) as they become available, with the stream terminated by a `data: [DONE]` message. [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions).
| | +| `StreamOptions` | [*components.ChatCompletionStreamOptions](../../models/components/chatcompletionstreamoptions.md) | :heavy_minus_sign: | Options for streaming response. Only set this when you set `stream: true`.
| | +| `Temperature` | **float64* | :heavy_minus_sign: | What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.

We generally recommend altering this or `top_p` but not both.
| 1 | +| `TopP` | **float64* | :heavy_minus_sign: | An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.

We generally recommend altering this or `temperature` but not both.
| 1 | +| `Tools` | [][components.ChatCompletionTool](../../models/components/chatcompletiontool.md) | :heavy_minus_sign: | A list of tools the model may call. Currently, only functions are supported as a tool. Use this to provide a list of functions the model may generate JSON inputs for. A max of 128 functions are supported.
| | +| `ToolChoice` | [*components.ChatCompletionToolChoiceOption](../../models/components/chatcompletiontoolchoiceoption.md) | :heavy_minus_sign: | Controls which (if any) tool is called by the model.
`none` means the model will not call any tool and instead generates a message.
`auto` means the model can pick between generating a message or calling one or more tools.
`required` means the model must call one or more tools.
Specifying a particular tool via `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool.

`none` is the default when no tools are present. `auto` is the default if tools are present.
| | +| `User` | **string* | :heavy_minus_sign: | A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](/docs/guides/safety-best-practices/end-user-ids).
| user-1234 | +| ~~`FunctionCall`~~ | [*components.CreateChatCompletionRequestFunctionCall](../../models/components/createchatcompletionrequestfunctioncall.md) | :heavy_minus_sign: | : warning: ** DEPRECATED **: This will be removed in a future release, please migrate away from it as soon as possible.

Deprecated in favor of `tool_choice`.

Controls which (if any) function is called by the model.
`none` means the model will not call a function and instead generates a message.
`auto` means the model can pick between generating a message or calling a function.
Specifying a particular function via `{"name": "my_function"}` forces the model to call that function.

`none` is the default when no functions are present. `auto` is the default if functions are present.
| | +| ~~`Functions`~~ | [][components.ChatCompletionFunctions](../../models/components/chatcompletionfunctions.md) | :heavy_minus_sign: | : warning: ** DEPRECATED **: This will be removed in a future release, please migrate away from it as soon as possible.

Deprecated in favor of `tools`.

A list of functions the model may generate JSON inputs for.
| | \ No newline at end of file diff --git a/docs/models/components/createchatcompletionrequestfunctioncall.md b/docs/models/components/createchatcompletionrequestfunctioncall.md new file mode 100644 index 0000000..a0bdd25 --- /dev/null +++ b/docs/models/components/createchatcompletionrequestfunctioncall.md @@ -0,0 +1,29 @@ +# ~~CreateChatCompletionRequestFunctionCall~~ + +Deprecated in favor of `tool_choice`. + +Controls which (if any) function is called by the model. +`none` means the model will not call a function and instead generates a message. +`auto` means the model can pick between generating a message or calling a function. +Specifying a particular function via `{"name": "my_function"}` forces the model to call that function. + +`none` is the default when no functions are present. `auto` is the default if functions are present. + + +> :warning: **DEPRECATED**: This will be removed in a future release, please migrate away from it as soon as possible. + + +## Supported Types + +### One + +```go +createChatCompletionRequestFunctionCall := components.CreateCreateChatCompletionRequestFunctionCallOne(components.One{/* values here */}) +``` + +### ChatCompletionFunctionCallOption + +```go +createChatCompletionRequestFunctionCall := components.CreateCreateChatCompletionRequestFunctionCallChatCompletionFunctionCallOption(components.ChatCompletionFunctionCallOption{/* values here */}) +``` + diff --git a/docs/models/components/createchatcompletionrequesttype.md b/docs/models/components/createchatcompletionrequesttype.md new file mode 100644 index 0000000..7c83e56 --- /dev/null +++ b/docs/models/components/createchatcompletionrequesttype.md @@ -0,0 +1,11 @@ +# CreateChatCompletionRequestType + +Must be one of `text` or `json_object`. + + +## Values + +| Name | Value | +| ------------------------------------------- | ------------------------------------------- | +| `CreateChatCompletionRequestTypeText` | text | +| `CreateChatCompletionRequestTypeJSONObject` | json_object | \ No newline at end of file diff --git a/docs/models/components/createchatcompletionresponse.md b/docs/models/components/createchatcompletionresponse.md new file mode 100644 index 0000000..0b14ac9 --- /dev/null +++ b/docs/models/components/createchatcompletionresponse.md @@ -0,0 +1,16 @@ +# CreateChatCompletionResponse + +Represents a chat completion response returned by model, based on the provided input. + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `ID` | *string* | :heavy_check_mark: | A unique identifier for the chat completion. | +| `Choices` | [][components.Choices](../../models/components/choices.md) | :heavy_check_mark: | A list of chat completion choices. Can be more than one if `n` is greater than 1. | +| `Created` | *int64* | :heavy_check_mark: | The Unix timestamp (in seconds) of when the chat completion was created. | +| `Model` | *string* | :heavy_check_mark: | The model used for the chat completion. | +| `SystemFingerprint` | **string* | :heavy_minus_sign: | This fingerprint represents the backend configuration that the model runs with.

Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism.
| +| `Object` | [components.Object](../../models/components/object.md) | :heavy_check_mark: | The object type, which is always `chat.completion`. | +| `Usage` | [*components.CompletionUsage](../../models/components/completionusage.md) | :heavy_minus_sign: | Usage statistics for the completion request. | \ No newline at end of file diff --git a/docs/models/components/detail.md b/docs/models/components/detail.md new file mode 100644 index 0000000..07c3a54 --- /dev/null +++ b/docs/models/components/detail.md @@ -0,0 +1,12 @@ +# Detail + +Specifies the detail level of the image. Learn more in the [Vision guide](/docs/guides/vision/low-or-high-fidelity-image-understanding). + + +## Values + +| Name | Value | +| ------------ | ------------ | +| `DetailAuto` | auto | +| `DetailLow` | low | +| `DetailHigh` | high | \ No newline at end of file diff --git a/docs/models/components/feedback.md b/docs/models/components/feedback.md new file mode 100644 index 0000000..e6391c5 --- /dev/null +++ b/docs/models/components/feedback.md @@ -0,0 +1,14 @@ +# Feedback + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | +| `ID` | **string* | :heavy_minus_sign: | The unique identifier for this feedback. | +| `CreatedAtMs` | **float64* | :heavy_minus_sign: | The epoch this schema was created. | +| `TaskID` | *string* | :heavy_check_mark: | The unique identifier for the task associated with this feedback. | +| `JSONValues` | [components.JSONValues](../../models/components/jsonvalues.md) | :heavy_check_mark: | The values of the feedback. Must be valid JSON according to the task schema. | +| `MatchedCompletionIds` | []*string* | :heavy_check_mark: | The matched completion ids associated with this feedback. | +| `Comment` | *string* | :heavy_check_mark: | The comment associated with this feedback. | +| `CompletionsSummary` | **string* | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/components/finishreason.md b/docs/models/components/finishreason.md new file mode 100644 index 0000000..41ff81d --- /dev/null +++ b/docs/models/components/finishreason.md @@ -0,0 +1,18 @@ +# FinishReason + +The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence, +`length` if the maximum number of tokens specified in the request was reached, +`content_filter` if content was omitted due to a flag from our content filters, +`tool_calls` if the model called a tool, or `function_call` (deprecated) if the model called a function. + + + +## Values + +| Name | Value | +| --------------------------- | --------------------------- | +| `FinishReasonStop` | stop | +| `FinishReasonLength` | length | +| `FinishReasonToolCalls` | tool_calls | +| `FinishReasonContentFilter` | content_filter | +| `FinishReasonFunctionCall` | function_call | \ No newline at end of file diff --git a/docs/models/components/function.md b/docs/models/components/function.md new file mode 100644 index 0000000..aec751d --- /dev/null +++ b/docs/models/components/function.md @@ -0,0 +1,11 @@ +# Function + +The function that the model called. + + +## Fields + +| Field | Type | Required | Description | +| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `Name` | *string* | :heavy_check_mark: | The name of the function to call. | +| `Arguments` | *string* | :heavy_check_mark: | The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function. | \ No newline at end of file diff --git a/docs/models/components/functioncall.md b/docs/models/components/functioncall.md new file mode 100644 index 0000000..cf3a6d5 --- /dev/null +++ b/docs/models/components/functioncall.md @@ -0,0 +1,13 @@ +# ~~FunctionCall~~ + +Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be called, as generated by the model. + +> :warning: **DEPRECATED**: This will be removed in a future release, please migrate away from it as soon as possible. + + +## Fields + +| Field | Type | Required | Description | +| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `Arguments` | *string* | :heavy_check_mark: | The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function. | +| `Name` | *string* | :heavy_check_mark: | The name of the function to call. | \ No newline at end of file diff --git a/docs/models/components/functionobject.md b/docs/models/components/functionobject.md new file mode 100644 index 0000000..b7579fc --- /dev/null +++ b/docs/models/components/functionobject.md @@ -0,0 +1,10 @@ +# FunctionObject + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `Description` | **string* | :heavy_minus_sign: | A description of what the function does, used by the model to choose when and how to call the function. | +| `Name` | *string* | :heavy_check_mark: | The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64. | +| `Parameters` | map[string]*any* | :heavy_minus_sign: | The parameters the functions accepts, described as a JSON Schema object. See the [guide](/docs/guides/text-generation/function-calling) for examples, and the [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for documentation about the format.

Omitting `parameters` defines a function with an empty parameter list. | \ No newline at end of file diff --git a/docs/models/components/httpmetadata.md b/docs/models/components/httpmetadata.md new file mode 100644 index 0000000..df1fdd5 --- /dev/null +++ b/docs/models/components/httpmetadata.md @@ -0,0 +1,9 @@ +# HTTPMetadata + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------- | ------------------------------------------------------- | ------------------------------------------------------- | ------------------------------------------------------- | +| `Response` | [*http.Response](https://pkg.go.dev/net/http#Response) | :heavy_check_mark: | Raw HTTP response; suitable for custom response parsing | +| `Request` | [*http.Request](https://pkg.go.dev/net/http#Request) | :heavy_check_mark: | Raw HTTP request; suitable for debugging | \ No newline at end of file diff --git a/docs/models/components/imageurl.md b/docs/models/components/imageurl.md new file mode 100644 index 0000000..4302653 --- /dev/null +++ b/docs/models/components/imageurl.md @@ -0,0 +1,9 @@ +# ImageURL + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | +| `URL` | *string* | :heavy_check_mark: | Either a URL of the image or the base64 encoded image data. | +| `Detail` | [*components.Detail](../../models/components/detail.md) | :heavy_minus_sign: | Specifies the detail level of the image. Learn more in the [Vision guide](/docs/guides/vision/low-or-high-fidelity-image-understanding). | \ No newline at end of file diff --git a/docs/models/components/jsonschema.md b/docs/models/components/jsonschema.md new file mode 100644 index 0000000..f807e6f --- /dev/null +++ b/docs/models/components/jsonschema.md @@ -0,0 +1,9 @@ +# JSONSchema + +The schema of the task. Must be valid JSON Schema. + + +## Fields + +| Field | Type | Required | Description | +| ----------- | ----------- | ----------- | ----------- | \ No newline at end of file diff --git a/docs/models/components/jsonvalues.md b/docs/models/components/jsonvalues.md new file mode 100644 index 0000000..ec0c8be --- /dev/null +++ b/docs/models/components/jsonvalues.md @@ -0,0 +1,9 @@ +# JSONValues + +The values of the feedback. Must be valid JSON according to the task schema. + + +## Fields + +| Field | Type | Required | Description | +| ----------- | ----------- | ----------- | ----------- | \ No newline at end of file diff --git a/docs/models/components/kind.md b/docs/models/components/kind.md new file mode 100644 index 0000000..04e8b6c --- /dev/null +++ b/docs/models/components/kind.md @@ -0,0 +1,11 @@ +# Kind + +The kind of completion i.e. chat messages or prompt + + +## Values + +| Name | Value | +| ------------ | ------------ | +| `KindChat` | chat | +| `KindPrompt` | prompt | \ No newline at end of file diff --git a/docs/models/components/logprobs.md b/docs/models/components/logprobs.md new file mode 100644 index 0000000..4f9963d --- /dev/null +++ b/docs/models/components/logprobs.md @@ -0,0 +1,10 @@ +# Logprobs + +Log probability information for the choice. + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | +| `Content` | [][components.ChatCompletionTokenLogprob](../../models/components/chatcompletiontokenlogprob.md) | :heavy_check_mark: | A list of message content tokens with log probability information. | \ No newline at end of file diff --git a/docs/models/components/model.md b/docs/models/components/model.md new file mode 100644 index 0000000..630c663 --- /dev/null +++ b/docs/models/components/model.md @@ -0,0 +1,19 @@ +# Model + +ID of the model to use. See the [model endpoint compatibility](/docs/models/model-endpoint-compatibility) table for details on which models work with the Chat API. + + +## Supported Types + +### + +```go +model := components.CreateModelStr(string{/* values here */}) +``` + +### Two + +```go +model := components.CreateModelTwo(components.Two{/* values here */}) +``` + diff --git a/docs/models/components/object.md b/docs/models/components/object.md new file mode 100644 index 0000000..dcc0e5a --- /dev/null +++ b/docs/models/components/object.md @@ -0,0 +1,10 @@ +# Object + +The object type, which is always `chat.completion`. + + +## Values + +| Name | Value | +| ---------------------- | ---------------------- | +| `ObjectChatCompletion` | chat.completion | \ No newline at end of file diff --git a/docs/models/components/one.md b/docs/models/components/one.md new file mode 100644 index 0000000..b00e0a2 --- /dev/null +++ b/docs/models/components/one.md @@ -0,0 +1,12 @@ +# One + +`none` means the model will not call a function and instead generates a message. `auto` means the model can pick between generating a message or calling a function. + + + +## Values + +| Name | Value | +| --------- | --------- | +| `OneNone` | none | +| `OneAuto` | auto | \ No newline at end of file diff --git a/docs/models/components/responseformat.md b/docs/models/components/responseformat.md new file mode 100644 index 0000000..19b3a7b --- /dev/null +++ b/docs/models/components/responseformat.md @@ -0,0 +1,15 @@ +# ResponseFormat + +An object specifying the format that the model must output. Compatible with [GPT-4 Turbo](/docs/models/gpt-4-and-gpt-4-turbo) and all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + +Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. + +**Important:** when using JSON mode, you **must** also instruct the model to produce JSON yourself via a system or user message. Without this, the model may generate an unending stream of whitespace until the generation reaches the token limit, resulting in a long-running and seemingly "stuck" request. Also note that the message content may be partially cut off if `finish_reason="length"`, which indicates the generation exceeded `max_tokens` or the conversation exceeded the max context length. + + + +## Fields + +| Field | Type | Required | Description | Example | +| --------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | +| `Type` | [*components.CreateChatCompletionRequestType](../../models/components/createchatcompletionrequesttype.md) | :heavy_minus_sign: | Must be one of `text` or `json_object`. | json_object | \ No newline at end of file diff --git a/docs/models/components/role.md b/docs/models/components/role.md new file mode 100644 index 0000000..4cebd3e --- /dev/null +++ b/docs/models/components/role.md @@ -0,0 +1,10 @@ +# Role + +The role of the messages author, in this case `system`. + + +## Values + +| Name | Value | +| ------------ | ------------ | +| `RoleSystem` | system | \ No newline at end of file diff --git a/docs/models/components/security.md b/docs/models/components/security.md new file mode 100644 index 0000000..478391c --- /dev/null +++ b/docs/models/components/security.md @@ -0,0 +1,8 @@ +# Security + + +## Fields + +| Field | Type | Required | Description | +| ------------------ | ------------------ | ------------------ | ------------------ | +| `Log10Token` | **string* | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/components/session.md b/docs/models/components/session.md new file mode 100644 index 0000000..5e27c73 --- /dev/null +++ b/docs/models/components/session.md @@ -0,0 +1,8 @@ +# Session + + +## Fields + +| Field | Type | Required | Description | +| --------------------------------------- | --------------------------------------- | --------------------------------------- | --------------------------------------- | +| `ID` | **string* | :heavy_minus_sign: | The unique identifier for this session. | \ No newline at end of file diff --git a/docs/models/components/stacktrace.md b/docs/models/components/stacktrace.md new file mode 100644 index 0000000..30ea9fc --- /dev/null +++ b/docs/models/components/stacktrace.md @@ -0,0 +1,11 @@ +# Stacktrace + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------- | ------------------------------------------------------- | ------------------------------------------------------- | ------------------------------------------------------- | +| `File` | *string* | :heavy_check_mark: | The file associated with this stacktrace. | +| `Line` | *string* | :heavy_check_mark: | The line associated with this stacktrace. | +| `Lineno` | *float64* | :heavy_check_mark: | The line number associated with this stacktrace. | +| `Name` | *string* | :heavy_check_mark: | The function or module associated with this stacktrace. | \ No newline at end of file diff --git a/docs/models/components/status.md b/docs/models/components/status.md new file mode 100644 index 0000000..c803c64 --- /dev/null +++ b/docs/models/components/status.md @@ -0,0 +1,12 @@ +# Status + +The status of this completion. + + +## Values + +| Name | Value | +| ---------------- | ---------------- | +| `StatusStarted` | started | +| `StatusFinished` | finished | +| `StatusFailed` | failed | \ No newline at end of file diff --git a/docs/models/components/stop.md b/docs/models/components/stop.md new file mode 100644 index 0000000..e4f8b95 --- /dev/null +++ b/docs/models/components/stop.md @@ -0,0 +1,20 @@ +# Stop + +Up to 4 sequences where the API will stop generating further tokens. + + + +## Supported Types + +### + +```go +stop := components.CreateStopStr(string{/* values here */}) +``` + +### + +```go +stop := components.CreateStopArrayOfStr([]string{/* values here */}) +``` + diff --git a/docs/models/components/task.md b/docs/models/components/task.md new file mode 100644 index 0000000..9119aa3 --- /dev/null +++ b/docs/models/components/task.md @@ -0,0 +1,13 @@ +# Task + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | +| `ID` | **string* | :heavy_minus_sign: | The unique identifier for this task. | +| `CreatedAtMs` | **float64* | :heavy_minus_sign: | The epoch this schema was created. | +| `JSONSchema` | [components.JSONSchema](../../models/components/jsonschema.md) | :heavy_check_mark: | The schema of the task. Must be valid JSON Schema. | +| `Name` | *string* | :heavy_check_mark: | The name of the task. | +| `Instruction` | *string* | :heavy_check_mark: | The instructions for this task. | +| `CompletionTagsSelector` | [components.CompletionTagsSelector](../../models/components/completiontagsselector.md) | :heavy_check_mark: | The completion tag matching with this task i.e. surfaced as needing feedback. | \ No newline at end of file diff --git a/docs/models/components/toplogprobs.md b/docs/models/components/toplogprobs.md new file mode 100644 index 0000000..4f5931d --- /dev/null +++ b/docs/models/components/toplogprobs.md @@ -0,0 +1,10 @@ +# TopLogprobs + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `Token` | *string* | :heavy_check_mark: | The token. | +| `Logprob` | *float64* | :heavy_check_mark: | The log probability of this token, if it is within the top 20 most likely tokens. Otherwise, the value `-9999.0` is used to signify that the token is very unlikely. | +| `Bytes` | []*int64* | :heavy_check_mark: | A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and their byte representations must be combined to generate the correct text representation. Can be `null` if there is no bytes representation for the token. | \ No newline at end of file diff --git a/docs/models/components/two.md b/docs/models/components/two.md new file mode 100644 index 0000000..1735f96 --- /dev/null +++ b/docs/models/components/two.md @@ -0,0 +1,26 @@ +# Two + + +## Values + +| Name | Value | +| ---------------------- | ---------------------- | +| `TwoGpt4Turbo` | gpt-4-turbo | +| `TwoGpt4Turbo20240409` | gpt-4-turbo-2024-04-09 | +| `TwoGpt40125Preview` | gpt-4-0125-preview | +| `TwoGpt4TurboPreview` | gpt-4-turbo-preview | +| `TwoGpt41106Preview` | gpt-4-1106-preview | +| `TwoGpt4VisionPreview` | gpt-4-vision-preview | +| `TwoGpt4` | gpt-4 | +| `TwoGpt40314` | gpt-4-0314 | +| `TwoGpt40613` | gpt-4-0613 | +| `TwoGpt432k` | gpt-4-32k | +| `TwoGpt432k0314` | gpt-4-32k-0314 | +| `TwoGpt432k0613` | gpt-4-32k-0613 | +| `TwoGpt35Turbo` | gpt-3.5-turbo | +| `TwoGpt35Turbo16k` | gpt-3.5-turbo-16k | +| `TwoGpt35Turbo0301` | gpt-3.5-turbo-0301 | +| `TwoGpt35Turbo0613` | gpt-3.5-turbo-0613 | +| `TwoGpt35Turbo1106` | gpt-3.5-turbo-1106 | +| `TwoGpt35Turbo0125` | gpt-3.5-turbo-0125 | +| `TwoGpt35Turbo16k0613` | gpt-3.5-turbo-16k-0613 | \ No newline at end of file diff --git a/docs/models/components/type.md b/docs/models/components/type.md new file mode 100644 index 0000000..a802879 --- /dev/null +++ b/docs/models/components/type.md @@ -0,0 +1,10 @@ +# Type + +The type of the content part. + + +## Values + +| Name | Value | +| ---------- | ---------- | +| `TypeText` | text | \ No newline at end of file diff --git a/docs/models/operations/createfeedbacktaskresponse.md b/docs/models/operations/createfeedbacktaskresponse.md new file mode 100644 index 0000000..cce9192 --- /dev/null +++ b/docs/models/operations/createfeedbacktaskresponse.md @@ -0,0 +1,9 @@ +# CreateFeedbackTaskResponse + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | +| `HTTPMeta` | [components.HTTPMetadata](../../models/components/httpmetadata.md) | :heavy_check_mark: | N/A | +| `Task` | [*components.Task](../../models/components/task.md) | :heavy_minus_sign: | OK | \ No newline at end of file diff --git a/docs/models/operations/createglobals.md b/docs/models/operations/createglobals.md new file mode 100644 index 0000000..a93a094 --- /dev/null +++ b/docs/models/operations/createglobals.md @@ -0,0 +1,8 @@ +# CreateGlobals + + +## Fields + +| Field | Type | Required | Description | +| -------------------- | -------------------- | -------------------- | -------------------- | +| `XLog10Organization` | *string* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/operations/createrequest.md b/docs/models/operations/createrequest.md new file mode 100644 index 0000000..290cac6 --- /dev/null +++ b/docs/models/operations/createrequest.md @@ -0,0 +1,9 @@ +# CreateRequest + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------- | +| `XLog10Organization` | **string* | :heavy_minus_sign: | N/A | +| `Completion` | [components.Completion](../../models/components/completion.md) | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/operations/createresponse.md b/docs/models/operations/createresponse.md new file mode 100644 index 0000000..39a2479 --- /dev/null +++ b/docs/models/operations/createresponse.md @@ -0,0 +1,10 @@ +# CreateResponse + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | +| `HTTPMeta` | [components.HTTPMetadata](../../models/components/httpmetadata.md) | :heavy_check_mark: | N/A | +| `Any` | *any* | :heavy_minus_sign: | Created | +| `Completion` | [*components.Completion](../../models/components/completion.md) | :heavy_minus_sign: | Created | \ No newline at end of file diff --git a/docs/models/operations/createsessionglobals.md b/docs/models/operations/createsessionglobals.md new file mode 100644 index 0000000..f7446e9 --- /dev/null +++ b/docs/models/operations/createsessionglobals.md @@ -0,0 +1,8 @@ +# CreateSessionGlobals + + +## Fields + +| Field | Type | Required | Description | +| -------------------- | -------------------- | -------------------- | -------------------- | +| `XLog10Organization` | *string* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/operations/createsessionrequest.md b/docs/models/operations/createsessionrequest.md new file mode 100644 index 0000000..f6f134c --- /dev/null +++ b/docs/models/operations/createsessionrequest.md @@ -0,0 +1,8 @@ +# CreateSessionRequest + + +## Fields + +| Field | Type | Required | Description | +| -------------------- | -------------------- | -------------------- | -------------------- | +| `XLog10Organization` | **string* | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/operations/createsessionresponse.md b/docs/models/operations/createsessionresponse.md new file mode 100644 index 0000000..56d2aea --- /dev/null +++ b/docs/models/operations/createsessionresponse.md @@ -0,0 +1,9 @@ +# CreateSessionResponse + + +## Fields + +| Field | Type | Required | Description | +| --------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | +| `HTTPMeta` | [components.HTTPMetadata](../../models/components/httpmetadata.md) | :heavy_check_mark: | N/A | +| `Object` | [*operations.CreateSessionResponseBody](../../models/operations/createsessionresponsebody.md) | :heavy_minus_sign: | Created | \ No newline at end of file diff --git a/docs/models/operations/createsessionresponsebody.md b/docs/models/operations/createsessionresponsebody.md new file mode 100644 index 0000000..d0c6a83 --- /dev/null +++ b/docs/models/operations/createsessionresponsebody.md @@ -0,0 +1,10 @@ +# CreateSessionResponseBody + +Created + + +## Fields + +| Field | Type | Required | Description | +| --------------------------------------------------------- | --------------------------------------------------------- | --------------------------------------------------------- | --------------------------------------------------------- | +| `Session` | [*components.Session](../../models/components/session.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/operations/getfeedbacktaskrequest.md b/docs/models/operations/getfeedbacktaskrequest.md new file mode 100644 index 0000000..c681a57 --- /dev/null +++ b/docs/models/operations/getfeedbacktaskrequest.md @@ -0,0 +1,8 @@ +# GetFeedbackTaskRequest + + +## Fields + +| Field | Type | Required | Description | +| --------------------- | --------------------- | --------------------- | --------------------- | +| `TaskID` | *string* | :heavy_check_mark: | The task id to fetch. | \ No newline at end of file diff --git a/docs/models/operations/getfeedbacktaskresponse.md b/docs/models/operations/getfeedbacktaskresponse.md new file mode 100644 index 0000000..66b4f0c --- /dev/null +++ b/docs/models/operations/getfeedbacktaskresponse.md @@ -0,0 +1,9 @@ +# GetFeedbackTaskResponse + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | +| `HTTPMeta` | [components.HTTPMetadata](../../models/components/httpmetadata.md) | :heavy_check_mark: | N/A | +| `Task` | [*components.Task](../../models/components/task.md) | :heavy_minus_sign: | OK | \ No newline at end of file diff --git a/docs/models/operations/getglobals.md b/docs/models/operations/getglobals.md new file mode 100644 index 0000000..4fd851e --- /dev/null +++ b/docs/models/operations/getglobals.md @@ -0,0 +1,8 @@ +# GetGlobals + + +## Fields + +| Field | Type | Required | Description | +| -------------------- | -------------------- | -------------------- | -------------------- | +| `XLog10Organization` | *string* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/operations/getrequest.md b/docs/models/operations/getrequest.md new file mode 100644 index 0000000..b0bca38 --- /dev/null +++ b/docs/models/operations/getrequest.md @@ -0,0 +1,9 @@ +# GetRequest + + +## Fields + +| Field | Type | Required | Description | +| ------------------------- | ------------------------- | ------------------------- | ------------------------- | +| `FeedbackID` | *string* | :heavy_check_mark: | The feedback id to fetch. | +| `XLog10Organization` | **string* | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/operations/getresponse.md b/docs/models/operations/getresponse.md new file mode 100644 index 0000000..d9ff3fd --- /dev/null +++ b/docs/models/operations/getresponse.md @@ -0,0 +1,9 @@ +# GetResponse + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | +| `HTTPMeta` | [components.HTTPMetadata](../../models/components/httpmetadata.md) | :heavy_check_mark: | N/A | +| `Feedback` | [*components.Feedback](../../models/components/feedback.md) | :heavy_minus_sign: | OK | \ No newline at end of file diff --git a/docs/models/operations/jsonvalues.md b/docs/models/operations/jsonvalues.md new file mode 100644 index 0000000..ec0c8be --- /dev/null +++ b/docs/models/operations/jsonvalues.md @@ -0,0 +1,9 @@ +# JSONValues + +The values of the feedback. Must be valid JSON according to the task schema. + + +## Fields + +| Field | Type | Required | Description | +| ----------- | ----------- | ----------- | ----------- | \ No newline at end of file diff --git a/docs/models/operations/listfeedbacktasksresponse.md b/docs/models/operations/listfeedbacktasksresponse.md new file mode 100644 index 0000000..6ee1c80 --- /dev/null +++ b/docs/models/operations/listfeedbacktasksresponse.md @@ -0,0 +1,9 @@ +# ListFeedbackTasksResponse + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | +| `HTTPMeta` | [components.HTTPMetadata](../../models/components/httpmetadata.md) | :heavy_check_mark: | N/A | +| `Tasks` | [][components.Task](../../models/components/task.md) | :heavy_minus_sign: | OK | \ No newline at end of file diff --git a/docs/models/operations/listglobals.md b/docs/models/operations/listglobals.md new file mode 100644 index 0000000..9c28bd7 --- /dev/null +++ b/docs/models/operations/listglobals.md @@ -0,0 +1,8 @@ +# ListGlobals + + +## Fields + +| Field | Type | Required | Description | +| -------------------- | -------------------- | -------------------- | -------------------- | +| `XLog10Organization` | *string* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/operations/listrequest.md b/docs/models/operations/listrequest.md new file mode 100644 index 0000000..9c3039b --- /dev/null +++ b/docs/models/operations/listrequest.md @@ -0,0 +1,9 @@ +# ListRequest + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | +| `XLog10Organization` | **string* | :heavy_minus_sign: | N/A | +| `RequestBody` | [*operations.ListRequestBody](../../models/operations/listrequestbody.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/operations/listrequestbody.md b/docs/models/operations/listrequestbody.md new file mode 100644 index 0000000..f2d66cf --- /dev/null +++ b/docs/models/operations/listrequestbody.md @@ -0,0 +1,11 @@ +# ListRequestBody + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------- | ------------------------------------------- | ------------------------------------------- | ------------------------------------------- | +| `Offset` | **int64* | :heavy_minus_sign: | The offset to start fetching feedback from. | +| `Limit` | **int64* | :heavy_minus_sign: | The number of feedback to fetch. | +| `CompletionID` | **string* | :heavy_minus_sign: | The completion id to fetch feedback for. | +| `TaskID` | **string* | :heavy_minus_sign: | The task id to fetch feedback for. | \ No newline at end of file diff --git a/docs/models/operations/listresponse.md b/docs/models/operations/listresponse.md new file mode 100644 index 0000000..c42ec82 --- /dev/null +++ b/docs/models/operations/listresponse.md @@ -0,0 +1,9 @@ +# ListResponse + + +## Fields + +| Field | Type | Required | Description | +| --------------------------------------------------------------------------- | --------------------------------------------------------------------------- | --------------------------------------------------------------------------- | --------------------------------------------------------------------------- | +| `HTTPMeta` | [components.HTTPMetadata](../../models/components/httpmetadata.md) | :heavy_check_mark: | N/A | +| `Object` | [*operations.ListResponseBody](../../models/operations/listresponsebody.md) | :heavy_minus_sign: | OK | \ No newline at end of file diff --git a/docs/models/operations/listresponsebody.md b/docs/models/operations/listresponsebody.md new file mode 100644 index 0000000..f7dc2b5 --- /dev/null +++ b/docs/models/operations/listresponsebody.md @@ -0,0 +1,10 @@ +# ListResponseBody + +OK + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | +| `Feedback` | [][components.Feedback](../../models/components/feedback.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/operations/listungradedglobals.md b/docs/models/operations/listungradedglobals.md new file mode 100644 index 0000000..83bd85c --- /dev/null +++ b/docs/models/operations/listungradedglobals.md @@ -0,0 +1,8 @@ +# ListUngradedGlobals + + +## Fields + +| Field | Type | Required | Description | +| -------------------- | -------------------- | -------------------- | -------------------- | +| `XLog10Organization` | *string* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/operations/listungradedrequest.md b/docs/models/operations/listungradedrequest.md new file mode 100644 index 0000000..653811f --- /dev/null +++ b/docs/models/operations/listungradedrequest.md @@ -0,0 +1,8 @@ +# ListUngradedRequest + + +## Fields + +| Field | Type | Required | Description | +| -------------------- | -------------------- | -------------------- | -------------------- | +| `XLog10Organization` | **string* | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/operations/listungradedresponse.md b/docs/models/operations/listungradedresponse.md new file mode 100644 index 0000000..f7754ab --- /dev/null +++ b/docs/models/operations/listungradedresponse.md @@ -0,0 +1,9 @@ +# ListUngradedResponse + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- | +| `HTTPMeta` | [components.HTTPMetadata](../../models/components/httpmetadata.md) | :heavy_check_mark: | N/A | +| `Object` | [*operations.ListUngradedResponseBody](../../models/operations/listungradedresponsebody.md) | :heavy_minus_sign: | OK | \ No newline at end of file diff --git a/docs/models/operations/listungradedresponsebody.md b/docs/models/operations/listungradedresponsebody.md new file mode 100644 index 0000000..f655b81 --- /dev/null +++ b/docs/models/operations/listungradedresponsebody.md @@ -0,0 +1,10 @@ +# ListUngradedResponseBody + +OK + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------- | ---------------------------------------------------------------- | ---------------------------------------------------------------- | ---------------------------------------------------------------- | +| `Completions` | [][components.Completion](../../models/components/completion.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/operations/one.md b/docs/models/operations/one.md new file mode 100644 index 0000000..64a9bf7 --- /dev/null +++ b/docs/models/operations/one.md @@ -0,0 +1,17 @@ +# One + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | +| `ID` | **string* | :heavy_minus_sign: | The unique identifier for this feedback. | +| `CreatedAtMs` | **float64* | :heavy_minus_sign: | The epoch this schema was created. | +| `TaskID` | *string* | :heavy_check_mark: | The unique identifier for the task associated with this feedback. | +| `JSONValues` | [operations.JSONValues](../../models/operations/jsonvalues.md) | :heavy_check_mark: | The values of the feedback. Must be valid JSON according to the task schema. | +| `MatchedCompletionIds` | []*string* | :heavy_check_mark: | The matched completion ids associated with this feedback. | +| `Comment` | *string* | :heavy_check_mark: | The comment associated with this feedback. | +| `CompletionsSummary` | **string* | :heavy_minus_sign: | N/A | +| `AllowUnmatchedFeedback` | **bool* | :heavy_minus_sign: | Whether to allow unmatched feedback. Defaults to false. | +| `MaxMatchedCompletions` | **int64* | :heavy_minus_sign: | The maximum number of matched completions. Returns error if exceeded. Defaults to 100. | +| `CompletionTagsSelector` | []*string* | :heavy_check_mark: | The completion tags associated with this feedback. | \ No newline at end of file diff --git a/docs/models/operations/requestbodyjsonvalues.md b/docs/models/operations/requestbodyjsonvalues.md new file mode 100644 index 0000000..89a5da3 --- /dev/null +++ b/docs/models/operations/requestbodyjsonvalues.md @@ -0,0 +1,9 @@ +# RequestBodyJSONValues + +The values of the feedback. Must be valid JSON according to the task schema. + + +## Fields + +| Field | Type | Required | Description | +| ----------- | ----------- | ----------- | ----------- | \ No newline at end of file diff --git a/docs/models/operations/two.md b/docs/models/operations/two.md new file mode 100644 index 0000000..6e26e67 --- /dev/null +++ b/docs/models/operations/two.md @@ -0,0 +1,15 @@ +# Two + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | +| `ID` | **string* | :heavy_minus_sign: | The unique identifier for this feedback. | +| `CreatedAtMs` | **float64* | :heavy_minus_sign: | The epoch this schema was created. | +| `TaskID` | *string* | :heavy_check_mark: | The unique identifier for the task associated with this feedback. | +| `JSONValues` | [operations.RequestBodyJSONValues](../../models/operations/requestbodyjsonvalues.md) | :heavy_check_mark: | The values of the feedback. Must be valid JSON according to the task schema. | +| `MatchedCompletionIds` | []*string* | :heavy_check_mark: | The matched completion ids associated with this feedback. | +| `Comment` | *string* | :heavy_check_mark: | The comment associated with this feedback. | +| `CompletionsSummary` | **string* | :heavy_minus_sign: | N/A | +| `CompletionIds` | []*string* | :heavy_check_mark: | The completion ids to associate with this feedback. | \ No newline at end of file diff --git a/docs/models/operations/updateglobals.md b/docs/models/operations/updateglobals.md new file mode 100644 index 0000000..7a45786 --- /dev/null +++ b/docs/models/operations/updateglobals.md @@ -0,0 +1,8 @@ +# UpdateGlobals + + +## Fields + +| Field | Type | Required | Description | +| -------------------- | -------------------- | -------------------- | -------------------- | +| `XLog10Organization` | *string* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/operations/updaterequest.md b/docs/models/operations/updaterequest.md new file mode 100644 index 0000000..d2b8160 --- /dev/null +++ b/docs/models/operations/updaterequest.md @@ -0,0 +1,10 @@ +# UpdateRequest + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------- | +| `CompletionID` | *string* | :heavy_check_mark: | The completion id to update. | +| `XLog10Organization` | **string* | :heavy_minus_sign: | N/A | +| `Completion` | [components.Completion](../../models/components/completion.md) | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/operations/updateresponse.md b/docs/models/operations/updateresponse.md new file mode 100644 index 0000000..0eba2ac --- /dev/null +++ b/docs/models/operations/updateresponse.md @@ -0,0 +1,9 @@ +# UpdateResponse + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | +| `HTTPMeta` | [components.HTTPMetadata](../../models/components/httpmetadata.md) | :heavy_check_mark: | N/A | +| `Completion` | [*components.Completion](../../models/components/completion.md) | :heavy_minus_sign: | OK | \ No newline at end of file diff --git a/docs/models/operations/uploadglobals.md b/docs/models/operations/uploadglobals.md new file mode 100644 index 0000000..ba7439b --- /dev/null +++ b/docs/models/operations/uploadglobals.md @@ -0,0 +1,8 @@ +# UploadGlobals + + +## Fields + +| Field | Type | Required | Description | +| -------------------- | -------------------- | -------------------- | -------------------- | +| `XLog10Organization` | *string* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/operations/uploadrequest.md b/docs/models/operations/uploadrequest.md new file mode 100644 index 0000000..18cc37c --- /dev/null +++ b/docs/models/operations/uploadrequest.md @@ -0,0 +1,9 @@ +# UploadRequest + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | +| `XLog10Organization` | **string* | :heavy_minus_sign: | N/A | +| `RequestBody` | [operations.UploadRequestBody](../../models/operations/uploadrequestbody.md) | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/operations/uploadrequestbody.md b/docs/models/operations/uploadrequestbody.md new file mode 100644 index 0000000..136f09b --- /dev/null +++ b/docs/models/operations/uploadrequestbody.md @@ -0,0 +1,17 @@ +# UploadRequestBody + + +## Supported Types + +### One + +```go +uploadRequestBody := operations.CreateUploadRequestBodyOne(operations.One{/* values here */}) +``` + +### Two + +```go +uploadRequestBody := operations.CreateUploadRequestBodyTwo(operations.Two{/* values here */}) +``` + diff --git a/docs/models/operations/uploadresponse.md b/docs/models/operations/uploadresponse.md new file mode 100644 index 0000000..208d26b --- /dev/null +++ b/docs/models/operations/uploadresponse.md @@ -0,0 +1,9 @@ +# UploadResponse + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | +| `HTTPMeta` | [components.HTTPMetadata](../../models/components/httpmetadata.md) | :heavy_check_mark: | N/A | +| `Feedback` | [*components.Feedback](../../models/components/feedback.md) | :heavy_minus_sign: | OK | \ No newline at end of file diff --git a/docs/sdks/completions/README.md b/docs/sdks/completions/README.md new file mode 100644 index 0000000..33bb0c0 --- /dev/null +++ b/docs/sdks/completions/README.md @@ -0,0 +1,208 @@ +# Completions +(*Completions*) + +## Overview + +Completions + +### Available Operations + +* [Create](#create) - Create a completion +* [Update](#update) - Update completion by id. +* [ListUngraded](#listungraded) - List ungraded completions i.e. completions that have not been associated with feedback but matches task selector. + +## Create + +Create a completion + +### Example Usage + +```go +package main + +import( + "github.com/log10-io/log10go" + "github.com/log10-io/log10go/models/components" + "context" + "log" +) + +func main() { + s := log10go.New( + log10go.WithSecurity(""), + log10go.WithXLog10Organization(""), + ) + completion := components.Completion{ + OrganizationID: "", + Request: &components.CreateChatCompletionRequest{ + Messages: []components.ChatCompletionRequestMessage{ + components.CreateChatCompletionRequestMessageChatCompletionRequestAssistantMessage( + components.ChatCompletionRequestAssistantMessage{ + Role: components.ChatCompletionRequestAssistantMessageRoleAssistant, + }, + ), + }, + Model: components.CreateModelTwo( + components.TwoGpt4Turbo, + ), + N: log10go.Int64(1), + ResponseFormat: &components.ResponseFormat{ + Type: components.CreateChatCompletionRequestTypeJSONObject.ToPointer(), + }, + Temperature: log10go.Float64(1), + TopP: log10go.Float64(1), + User: log10go.String("user-1234"), + }, + } + + var xLog10Organization *string = log10go.String("") + ctx := context.Background() + res, err := s.Completions.Create(ctx, completion, xLog10Organization) + if err != nil { + log.Fatal(err) + } + if res.Any != nil { + // handle response + } +} +``` + +### Parameters + +| Parameter | Type | Required | Description | +| -------------------------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------- | +| `ctx` | [context.Context](https://pkg.go.dev/context#Context) | :heavy_check_mark: | The context to use for the request. | +| `completion` | [components.Completion](../../models/components/completion.md) | :heavy_check_mark: | N/A | +| `xLog10Organization` | **string* | :heavy_minus_sign: | N/A | + + +### Response + +**[*operations.CreateResponse](../../models/operations/createresponse.md), error** +| Error Object | Status Code | Content Type | +| ------------------ | ------------------ | ------------------ | +| sdkerrors.SDKError | 4xx-5xx | */* | + +## Update + +Update completion by id. + +### Example Usage + +```go +package main + +import( + "github.com/log10-io/log10go" + "github.com/log10-io/log10go/models/components" + "context" + "log" +) + +func main() { + s := log10go.New( + log10go.WithSecurity(""), + log10go.WithXLog10Organization(""), + ) + var completionID string = "" + + completion := components.Completion{ + OrganizationID: "", + Request: &components.CreateChatCompletionRequest{ + Messages: []components.ChatCompletionRequestMessage{ + components.CreateChatCompletionRequestMessageChatCompletionRequestFunctionMessage( + components.ChatCompletionRequestFunctionMessage{ + Role: components.ChatCompletionRequestFunctionMessageRoleFunction, + Content: "", + Name: "", + }, + ), + }, + Model: components.CreateModelTwo( + components.TwoGpt4Turbo, + ), + N: log10go.Int64(1), + ResponseFormat: &components.ResponseFormat{ + Type: components.CreateChatCompletionRequestTypeJSONObject.ToPointer(), + }, + Temperature: log10go.Float64(1), + TopP: log10go.Float64(1), + User: log10go.String("user-1234"), + }, + } + + var xLog10Organization *string = log10go.String("") + ctx := context.Background() + res, err := s.Completions.Update(ctx, completionID, completion, xLog10Organization) + if err != nil { + log.Fatal(err) + } + if res.Completion != nil { + // handle response + } +} +``` + +### Parameters + +| Parameter | Type | Required | Description | +| -------------------------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------- | +| `ctx` | [context.Context](https://pkg.go.dev/context#Context) | :heavy_check_mark: | The context to use for the request. | +| `completionID` | *string* | :heavy_check_mark: | The completion id to update. | +| `completion` | [components.Completion](../../models/components/completion.md) | :heavy_check_mark: | N/A | +| `xLog10Organization` | **string* | :heavy_minus_sign: | N/A | + + +### Response + +**[*operations.UpdateResponse](../../models/operations/updateresponse.md), error** +| Error Object | Status Code | Content Type | +| ------------------ | ------------------ | ------------------ | +| sdkerrors.SDKError | 4xx-5xx | */* | + +## ListUngraded + +List ungraded completions i.e. completions that have not been associated with feedback but matches task selector. + +### Example Usage + +```go +package main + +import( + "github.com/log10-io/log10go" + "context" + "log" +) + +func main() { + s := log10go.New( + log10go.WithSecurity(""), + log10go.WithXLog10Organization(""), + ) + var xLog10Organization *string = log10go.String("") + ctx := context.Background() + res, err := s.Completions.ListUngraded(ctx, xLog10Organization) + if err != nil { + log.Fatal(err) + } + if res.Object != nil { + // handle response + } +} +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ----------------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------- | +| `ctx` | [context.Context](https://pkg.go.dev/context#Context) | :heavy_check_mark: | The context to use for the request. | +| `xLog10Organization` | **string* | :heavy_minus_sign: | N/A | + + +### Response + +**[*operations.ListUngradedResponse](../../models/operations/listungradedresponse.md), error** +| Error Object | Status Code | Content Type | +| ------------------ | ------------------ | ------------------ | +| sdkerrors.SDKError | 4xx-5xx | */* | diff --git a/docs/sdks/feedback/README.md b/docs/sdks/feedback/README.md new file mode 100644 index 0000000..7dcfede --- /dev/null +++ b/docs/sdks/feedback/README.md @@ -0,0 +1,176 @@ +# Feedback +(*Feedback*) + +## Overview + +Feedback + +### Available Operations + +* [Get](#get) - Fetch feedback by id. +* [List](#list) - List feedback +* [Upload](#upload) - Upload a piece of feedback + +## Get + +Fetch feedback by id. + +### Example Usage + +```go +package main + +import( + "github.com/log10-io/log10go" + "context" + "log" +) + +func main() { + s := log10go.New( + log10go.WithSecurity(""), + log10go.WithXLog10Organization(""), + ) + var feedbackID string = "" + + var xLog10Organization *string = log10go.String("") + ctx := context.Background() + res, err := s.Feedback.Get(ctx, feedbackID, xLog10Organization) + if err != nil { + log.Fatal(err) + } + if res.Feedback != nil { + // handle response + } +} +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ----------------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------- | +| `ctx` | [context.Context](https://pkg.go.dev/context#Context) | :heavy_check_mark: | The context to use for the request. | +| `feedbackID` | *string* | :heavy_check_mark: | The feedback id to fetch. | +| `xLog10Organization` | **string* | :heavy_minus_sign: | N/A | + + +### Response + +**[*operations.GetResponse](../../models/operations/getresponse.md), error** +| Error Object | Status Code | Content Type | +| ------------------ | ------------------ | ------------------ | +| sdkerrors.SDKError | 4xx-5xx | */* | + +## List + +List feedback + +### Example Usage + +```go +package main + +import( + "github.com/log10-io/log10go" + "github.com/log10-io/log10go/models/operations" + "context" + "log" +) + +func main() { + s := log10go.New( + log10go.WithSecurity(""), + log10go.WithXLog10Organization(""), + ) + var xLog10Organization *string = log10go.String("") + + var requestBody *operations.ListRequestBody = &operations.ListRequestBody{} + ctx := context.Background() + res, err := s.Feedback.List(ctx, xLog10Organization, requestBody) + if err != nil { + log.Fatal(err) + } + if res.Object != nil { + // handle response + } +} +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | +| `ctx` | [context.Context](https://pkg.go.dev/context#Context) | :heavy_check_mark: | The context to use for the request. | +| `xLog10Organization` | **string* | :heavy_minus_sign: | N/A | +| `requestBody` | [*operations.ListRequestBody](../../models/operations/listrequestbody.md) | :heavy_minus_sign: | N/A | + + +### Response + +**[*operations.ListResponse](../../models/operations/listresponse.md), error** +| Error Object | Status Code | Content Type | +| ------------------ | ------------------ | ------------------ | +| sdkerrors.SDKError | 4xx-5xx | */* | + +## Upload + +Upload a piece of feedback + +### Example Usage + +```go +package main + +import( + "github.com/log10-io/log10go" + "github.com/log10-io/log10go/models/operations" + "context" + "log" +) + +func main() { + s := log10go.New( + log10go.WithSecurity(""), + log10go.WithXLog10Organization(""), + ) + var requestBody operations.UploadRequestBody = operations.CreateUploadRequestBodyOne( + operations.One{ + TaskID: "", + JSONValues: operations.JSONValues{}, + MatchedCompletionIds: []string{ + "", + }, + Comment: "The slim & simple Maple Gaming Keyboard from Dev Byte comes with a sleek body and 7- Color RGB LED Back-lighting for smart functionality", + CompletionTagsSelector: []string{ + "", + }, + }, + ) + + var xLog10Organization *string = log10go.String("") + ctx := context.Background() + res, err := s.Feedback.Upload(ctx, requestBody, xLog10Organization) + if err != nil { + log.Fatal(err) + } + if res.Feedback != nil { + // handle response + } +} +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | +| `ctx` | [context.Context](https://pkg.go.dev/context#Context) | :heavy_check_mark: | The context to use for the request. | +| `requestBody` | [operations.UploadRequestBody](../../models/operations/uploadrequestbody.md) | :heavy_check_mark: | N/A | +| `xLog10Organization` | **string* | :heavy_minus_sign: | N/A | + + +### Response + +**[*operations.UploadResponse](../../models/operations/uploadresponse.md), error** +| Error Object | Status Code | Content Type | +| ------------------ | ------------------ | ------------------ | +| sdkerrors.SDKError | 4xx-5xx | */* | diff --git a/docs/sdks/feedbacktasks/README.md b/docs/sdks/feedbacktasks/README.md new file mode 100644 index 0000000..c229014 --- /dev/null +++ b/docs/sdks/feedbacktasks/README.md @@ -0,0 +1,158 @@ +# FeedbackTasks +(*FeedbackTasks*) + +## Overview + +FeedbackTasks + +### Available Operations + +* [List](#list) - List feedback tasks. +* [Create](#create) - Create a new task. +* [Get](#get) - Retrieves feedback task `taskId`. + +## List + +List feedback tasks. + +### Example Usage + +```go +package main + +import( + "github.com/log10-io/log10go" + "context" + "log" +) + +func main() { + s := log10go.New( + log10go.WithSecurity(""), + log10go.WithXLog10Organization(""), + ) + + ctx := context.Background() + res, err := s.FeedbackTasks.List(ctx) + if err != nil { + log.Fatal(err) + } + if res.Tasks != nil { + // handle response + } +} +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ----------------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------- | +| `ctx` | [context.Context](https://pkg.go.dev/context#Context) | :heavy_check_mark: | The context to use for the request. | + + +### Response + +**[*operations.ListFeedbackTasksResponse](../../models/operations/listfeedbacktasksresponse.md), error** +| Error Object | Status Code | Content Type | +| ------------------ | ------------------ | ------------------ | +| sdkerrors.SDKError | 4xx-5xx | */* | + +## Create + +Create a new task. + +### Example Usage + +```go +package main + +import( + "github.com/log10-io/log10go" + "github.com/log10-io/log10go/models/components" + "context" + "log" +) + +func main() { + s := log10go.New( + log10go.WithSecurity(""), + log10go.WithXLog10Organization(""), + ) + var request *components.Task = &components.Task{ + JSONSchema: components.JSONSchema{}, + Name: "", + Instruction: "", + CompletionTagsSelector: components.CompletionTagsSelector{}, + } + ctx := context.Background() + res, err := s.FeedbackTasks.Create(ctx, request) + if err != nil { + log.Fatal(err) + } + if res.Task != nil { + // handle response + } +} +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ----------------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------- | +| `ctx` | [context.Context](https://pkg.go.dev/context#Context) | :heavy_check_mark: | The context to use for the request. | +| `request` | [components.Task](../../models/components/task.md) | :heavy_check_mark: | The request object to use for the request. | + + +### Response + +**[*operations.CreateFeedbackTaskResponse](../../models/operations/createfeedbacktaskresponse.md), error** +| Error Object | Status Code | Content Type | +| ------------------ | ------------------ | ------------------ | +| sdkerrors.SDKError | 4xx-5xx | */* | + +## Get + +Retrieves feedback task `taskId`. + +### Example Usage + +```go +package main + +import( + "github.com/log10-io/log10go" + "context" + "log" +) + +func main() { + s := log10go.New( + log10go.WithSecurity(""), + log10go.WithXLog10Organization(""), + ) + var taskID string = "" + ctx := context.Background() + res, err := s.FeedbackTasks.Get(ctx, taskID) + if err != nil { + log.Fatal(err) + } + if res.Task != nil { + // handle response + } +} +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ----------------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------- | +| `ctx` | [context.Context](https://pkg.go.dev/context#Context) | :heavy_check_mark: | The context to use for the request. | +| `taskID` | *string* | :heavy_check_mark: | The task id to fetch. | + + +### Response + +**[*operations.GetFeedbackTaskResponse](../../models/operations/getfeedbacktaskresponse.md), error** +| Error Object | Status Code | Content Type | +| ------------------ | ------------------ | ------------------ | +| sdkerrors.SDKError | 4xx-5xx | */* | diff --git a/docs/sdks/log10/README.md b/docs/sdks/log10/README.md new file mode 100644 index 0000000..89307d2 --- /dev/null +++ b/docs/sdks/log10/README.md @@ -0,0 +1,9 @@ +# Log10 SDK + + +## Overview + +Log10 Feedback API Spec: Log10 Feedback API Spec + +### Available Operations + diff --git a/docs/sdks/sessions/README.md b/docs/sdks/sessions/README.md new file mode 100644 index 0000000..8b42e7a --- /dev/null +++ b/docs/sdks/sessions/README.md @@ -0,0 +1,57 @@ +# Sessions +(*Sessions*) + +## Overview + +Sessions + +### Available Operations + +* [Create](#create) - Create a session + +## Create + +Create a session + +### Example Usage + +```go +package main + +import( + "github.com/log10-io/log10go" + "context" + "log" +) + +func main() { + s := log10go.New( + log10go.WithSecurity(""), + log10go.WithXLog10Organization(""), + ) + var xLog10Organization *string = log10go.String("") + ctx := context.Background() + res, err := s.Sessions.Create(ctx, xLog10Organization) + if err != nil { + log.Fatal(err) + } + if res.Object != nil { + // handle response + } +} +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ----------------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------- | +| `ctx` | [context.Context](https://pkg.go.dev/context#Context) | :heavy_check_mark: | The context to use for the request. | +| `xLog10Organization` | **string* | :heavy_minus_sign: | N/A | + + +### Response + +**[*operations.CreateSessionResponse](../../models/operations/createsessionresponse.md), error** +| Error Object | Status Code | Content Type | +| ------------------ | ------------------ | ------------------ | +| sdkerrors.SDKError | 4xx-5xx | */* | diff --git a/feedback.go b/feedback.go new file mode 100644 index 0000000..4229699 --- /dev/null +++ b/feedback.go @@ -0,0 +1,363 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package log10go + +import ( + "bytes" + "context" + "fmt" + "github.com/log10-io/log10go/internal/hooks" + "github.com/log10-io/log10go/internal/utils" + "github.com/log10-io/log10go/models/components" + "github.com/log10-io/log10go/models/operations" + "github.com/log10-io/log10go/models/sdkerrors" + "io" + "net/http" +) + +// Feedback +type Feedback struct { + sdkConfiguration sdkConfiguration +} + +func newFeedback(sdkConfig sdkConfiguration) *Feedback { + return &Feedback{ + sdkConfiguration: sdkConfig, + } +} + +// Get - Fetch feedback by id. +func (s *Feedback) Get(ctx context.Context, feedbackID string, xLog10Organization *string) (*operations.GetResponse, error) { + hookCtx := hooks.HookContext{ + Context: ctx, + OperationID: "get", + SecuritySource: s.sdkConfiguration.Security, + } + + request := operations.GetRequest{ + FeedbackID: feedbackID, + XLog10Organization: xLog10Organization, + } + + globals := operations.GetGlobals{ + XLog10Organization: s.sdkConfiguration.Globals.XLog10Organization, + } + + baseURL := utils.ReplaceParameters(s.sdkConfiguration.GetServerDetails()) + opURL, err := utils.GenerateURL(ctx, baseURL, "/api/v1/feedback/{feedbackId}", request, globals) + if err != nil { + return nil, fmt.Errorf("error generating URL: %w", err) + } + + req, err := http.NewRequestWithContext(ctx, "GET", opURL, nil) + if err != nil { + return nil, fmt.Errorf("error creating request: %w", err) + } + req.Header.Set("Accept", "application/json") + req.Header.Set("User-Agent", s.sdkConfiguration.UserAgent) + + utils.PopulateHeaders(ctx, req, request, globals) + + if err := utils.PopulateQueryParams(ctx, req, request, globals); err != nil { + return nil, fmt.Errorf("error populating query params: %w", err) + } + + if err := utils.PopulateSecurity(ctx, req, s.sdkConfiguration.Security); err != nil { + return nil, err + } + + req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + if err != nil { + return nil, err + } + + httpRes, err := s.sdkConfiguration.Client.Do(req) + if err != nil || httpRes == nil { + if err != nil { + err = fmt.Errorf("error sending request: %w", err) + } else { + err = fmt.Errorf("error sending request: no response") + } + + _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + return nil, err + } else if utils.MatchStatusCodes([]string{"4XX", "5XX"}, httpRes.StatusCode) { + _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) + if err != nil { + return nil, err + } else if _httpRes != nil { + httpRes = _httpRes + } + } else { + httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) + if err != nil { + return nil, err + } + } + + res := &operations.GetResponse{ + HTTPMeta: components.HTTPMetadata{ + Request: req, + Response: httpRes, + }, + } + + rawBody, err := io.ReadAll(httpRes.Body) + if err != nil { + return nil, fmt.Errorf("error reading response body: %w", err) + } + httpRes.Body.Close() + httpRes.Body = io.NopCloser(bytes.NewBuffer(rawBody)) + + switch { + case httpRes.StatusCode == 200: + switch { + case utils.MatchContentType(httpRes.Header.Get("Content-Type"), `application/json`): + var out components.Feedback + if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { + return nil, err + } + + res.Feedback = &out + default: + return nil, sdkerrors.NewSDKError(fmt.Sprintf("unknown content-type received: %s", httpRes.Header.Get("Content-Type")), httpRes.StatusCode, string(rawBody), httpRes) + } + case httpRes.StatusCode >= 400 && httpRes.StatusCode < 500: + fallthrough + case httpRes.StatusCode >= 500 && httpRes.StatusCode < 600: + return nil, sdkerrors.NewSDKError("API error occurred", httpRes.StatusCode, string(rawBody), httpRes) + default: + return nil, sdkerrors.NewSDKError("unknown status code returned", httpRes.StatusCode, string(rawBody), httpRes) + } + + return res, nil + +} + +// List feedback +func (s *Feedback) List(ctx context.Context, xLog10Organization *string, requestBody *operations.ListRequestBody) (*operations.ListResponse, error) { + hookCtx := hooks.HookContext{ + Context: ctx, + OperationID: "list", + SecuritySource: s.sdkConfiguration.Security, + } + + request := operations.ListRequest{ + XLog10Organization: xLog10Organization, + RequestBody: requestBody, + } + + globals := operations.ListGlobals{ + XLog10Organization: s.sdkConfiguration.Globals.XLog10Organization, + } + + baseURL := utils.ReplaceParameters(s.sdkConfiguration.GetServerDetails()) + opURL, err := utils.GenerateURL(ctx, baseURL, "/api/v1/feedback", request, globals) + if err != nil { + return nil, fmt.Errorf("error generating URL: %w", err) + } + + bodyReader, reqContentType, err := utils.SerializeRequestBody(ctx, request, false, true, "RequestBody", "json", `request:"mediaType=application/json"`) + if err != nil { + return nil, err + } + + req, err := http.NewRequestWithContext(ctx, "GET", opURL, bodyReader) + if err != nil { + return nil, fmt.Errorf("error creating request: %w", err) + } + req.Header.Set("Accept", "application/json") + req.Header.Set("User-Agent", s.sdkConfiguration.UserAgent) + req.Header.Set("Content-Type", reqContentType) + + utils.PopulateHeaders(ctx, req, request, globals) + + if err := utils.PopulateQueryParams(ctx, req, request, globals); err != nil { + return nil, fmt.Errorf("error populating query params: %w", err) + } + + if err := utils.PopulateSecurity(ctx, req, s.sdkConfiguration.Security); err != nil { + return nil, err + } + + req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + if err != nil { + return nil, err + } + + httpRes, err := s.sdkConfiguration.Client.Do(req) + if err != nil || httpRes == nil { + if err != nil { + err = fmt.Errorf("error sending request: %w", err) + } else { + err = fmt.Errorf("error sending request: no response") + } + + _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + return nil, err + } else if utils.MatchStatusCodes([]string{"4XX", "5XX"}, httpRes.StatusCode) { + _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) + if err != nil { + return nil, err + } else if _httpRes != nil { + httpRes = _httpRes + } + } else { + httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) + if err != nil { + return nil, err + } + } + + res := &operations.ListResponse{ + HTTPMeta: components.HTTPMetadata{ + Request: req, + Response: httpRes, + }, + } + + rawBody, err := io.ReadAll(httpRes.Body) + if err != nil { + return nil, fmt.Errorf("error reading response body: %w", err) + } + httpRes.Body.Close() + httpRes.Body = io.NopCloser(bytes.NewBuffer(rawBody)) + + switch { + case httpRes.StatusCode == 200: + switch { + case utils.MatchContentType(httpRes.Header.Get("Content-Type"), `application/json`): + var out operations.ListResponseBody + if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { + return nil, err + } + + res.Object = &out + default: + return nil, sdkerrors.NewSDKError(fmt.Sprintf("unknown content-type received: %s", httpRes.Header.Get("Content-Type")), httpRes.StatusCode, string(rawBody), httpRes) + } + case httpRes.StatusCode >= 400 && httpRes.StatusCode < 500: + fallthrough + case httpRes.StatusCode >= 500 && httpRes.StatusCode < 600: + return nil, sdkerrors.NewSDKError("API error occurred", httpRes.StatusCode, string(rawBody), httpRes) + default: + return nil, sdkerrors.NewSDKError("unknown status code returned", httpRes.StatusCode, string(rawBody), httpRes) + } + + return res, nil + +} + +// Upload a piece of feedback +func (s *Feedback) Upload(ctx context.Context, requestBody operations.UploadRequestBody, xLog10Organization *string) (*operations.UploadResponse, error) { + hookCtx := hooks.HookContext{ + Context: ctx, + OperationID: "upload", + SecuritySource: s.sdkConfiguration.Security, + } + + request := operations.UploadRequest{ + XLog10Organization: xLog10Organization, + RequestBody: requestBody, + } + + globals := operations.UploadGlobals{ + XLog10Organization: s.sdkConfiguration.Globals.XLog10Organization, + } + + baseURL := utils.ReplaceParameters(s.sdkConfiguration.GetServerDetails()) + opURL, err := utils.GenerateURL(ctx, baseURL, "/api/v1/feedback", request, globals) + if err != nil { + return nil, fmt.Errorf("error generating URL: %w", err) + } + + bodyReader, reqContentType, err := utils.SerializeRequestBody(ctx, request, false, false, "RequestBody", "json", `request:"mediaType=application/json"`) + if err != nil { + return nil, err + } + + req, err := http.NewRequestWithContext(ctx, "POST", opURL, bodyReader) + if err != nil { + return nil, fmt.Errorf("error creating request: %w", err) + } + req.Header.Set("Accept", "application/json") + req.Header.Set("User-Agent", s.sdkConfiguration.UserAgent) + req.Header.Set("Content-Type", reqContentType) + + utils.PopulateHeaders(ctx, req, request, globals) + + if err := utils.PopulateQueryParams(ctx, req, request, globals); err != nil { + return nil, fmt.Errorf("error populating query params: %w", err) + } + + if err := utils.PopulateSecurity(ctx, req, s.sdkConfiguration.Security); err != nil { + return nil, err + } + + req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + if err != nil { + return nil, err + } + + httpRes, err := s.sdkConfiguration.Client.Do(req) + if err != nil || httpRes == nil { + if err != nil { + err = fmt.Errorf("error sending request: %w", err) + } else { + err = fmt.Errorf("error sending request: no response") + } + + _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + return nil, err + } else if utils.MatchStatusCodes([]string{"4XX", "5XX"}, httpRes.StatusCode) { + _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) + if err != nil { + return nil, err + } else if _httpRes != nil { + httpRes = _httpRes + } + } else { + httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) + if err != nil { + return nil, err + } + } + + res := &operations.UploadResponse{ + HTTPMeta: components.HTTPMetadata{ + Request: req, + Response: httpRes, + }, + } + + rawBody, err := io.ReadAll(httpRes.Body) + if err != nil { + return nil, fmt.Errorf("error reading response body: %w", err) + } + httpRes.Body.Close() + httpRes.Body = io.NopCloser(bytes.NewBuffer(rawBody)) + + switch { + case httpRes.StatusCode == 200: + switch { + case utils.MatchContentType(httpRes.Header.Get("Content-Type"), `application/json`): + var out components.Feedback + if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { + return nil, err + } + + res.Feedback = &out + default: + return nil, sdkerrors.NewSDKError(fmt.Sprintf("unknown content-type received: %s", httpRes.Header.Get("Content-Type")), httpRes.StatusCode, string(rawBody), httpRes) + } + case httpRes.StatusCode >= 400 && httpRes.StatusCode < 500: + fallthrough + case httpRes.StatusCode >= 500 && httpRes.StatusCode < 600: + return nil, sdkerrors.NewSDKError("API error occurred", httpRes.StatusCode, string(rawBody), httpRes) + default: + return nil, sdkerrors.NewSDKError("unknown status code returned", httpRes.StatusCode, string(rawBody), httpRes) + } + + return res, nil + +} diff --git a/feedbacktasks.go b/feedbacktasks.go new file mode 100644 index 0000000..963cc70 --- /dev/null +++ b/feedbacktasks.go @@ -0,0 +1,317 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package log10go + +import ( + "bytes" + "context" + "fmt" + "github.com/log10-io/log10go/internal/hooks" + "github.com/log10-io/log10go/internal/utils" + "github.com/log10-io/log10go/models/components" + "github.com/log10-io/log10go/models/operations" + "github.com/log10-io/log10go/models/sdkerrors" + "io" + "net/http" + "net/url" +) + +// FeedbackTasks +type FeedbackTasks struct { + sdkConfiguration sdkConfiguration +} + +func newFeedbackTasks(sdkConfig sdkConfiguration) *FeedbackTasks { + return &FeedbackTasks{ + sdkConfiguration: sdkConfig, + } +} + +// List feedback tasks. +func (s *FeedbackTasks) List(ctx context.Context) (*operations.ListFeedbackTasksResponse, error) { + hookCtx := hooks.HookContext{ + Context: ctx, + OperationID: "listFeedbackTasks", + SecuritySource: s.sdkConfiguration.Security, + } + + baseURL := utils.ReplaceParameters(s.sdkConfiguration.GetServerDetails()) + opURL, err := url.JoinPath(baseURL, "/api/v1/feedback_task") + if err != nil { + return nil, fmt.Errorf("error generating URL: %w", err) + } + + req, err := http.NewRequestWithContext(ctx, "GET", opURL, nil) + if err != nil { + return nil, fmt.Errorf("error creating request: %w", err) + } + req.Header.Set("Accept", "application/json") + req.Header.Set("User-Agent", s.sdkConfiguration.UserAgent) + + if err := utils.PopulateSecurity(ctx, req, s.sdkConfiguration.Security); err != nil { + return nil, err + } + + req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + if err != nil { + return nil, err + } + + httpRes, err := s.sdkConfiguration.Client.Do(req) + if err != nil || httpRes == nil { + if err != nil { + err = fmt.Errorf("error sending request: %w", err) + } else { + err = fmt.Errorf("error sending request: no response") + } + + _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + return nil, err + } else if utils.MatchStatusCodes([]string{"4XX", "5XX"}, httpRes.StatusCode) { + _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) + if err != nil { + return nil, err + } else if _httpRes != nil { + httpRes = _httpRes + } + } else { + httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) + if err != nil { + return nil, err + } + } + + res := &operations.ListFeedbackTasksResponse{ + HTTPMeta: components.HTTPMetadata{ + Request: req, + Response: httpRes, + }, + } + + rawBody, err := io.ReadAll(httpRes.Body) + if err != nil { + return nil, fmt.Errorf("error reading response body: %w", err) + } + httpRes.Body.Close() + httpRes.Body = io.NopCloser(bytes.NewBuffer(rawBody)) + + switch { + case httpRes.StatusCode == 200: + switch { + case utils.MatchContentType(httpRes.Header.Get("Content-Type"), `application/json`): + var out []components.Task + if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { + return nil, err + } + + res.Tasks = out + default: + return nil, sdkerrors.NewSDKError(fmt.Sprintf("unknown content-type received: %s", httpRes.Header.Get("Content-Type")), httpRes.StatusCode, string(rawBody), httpRes) + } + case httpRes.StatusCode >= 400 && httpRes.StatusCode < 500: + fallthrough + case httpRes.StatusCode >= 500 && httpRes.StatusCode < 600: + return nil, sdkerrors.NewSDKError("API error occurred", httpRes.StatusCode, string(rawBody), httpRes) + default: + return nil, sdkerrors.NewSDKError("unknown status code returned", httpRes.StatusCode, string(rawBody), httpRes) + } + + return res, nil + +} + +// Create a new task. +func (s *FeedbackTasks) Create(ctx context.Context, request *components.Task) (*operations.CreateFeedbackTaskResponse, error) { + hookCtx := hooks.HookContext{ + Context: ctx, + OperationID: "createFeedbackTask", + SecuritySource: s.sdkConfiguration.Security, + } + + baseURL := utils.ReplaceParameters(s.sdkConfiguration.GetServerDetails()) + opURL, err := url.JoinPath(baseURL, "/api/v1/feedback_task") + if err != nil { + return nil, fmt.Errorf("error generating URL: %w", err) + } + + bodyReader, reqContentType, err := utils.SerializeRequestBody(ctx, request, false, true, "Request", "json", `request:"mediaType=application/json"`) + if err != nil { + return nil, err + } + + req, err := http.NewRequestWithContext(ctx, "POST", opURL, bodyReader) + if err != nil { + return nil, fmt.Errorf("error creating request: %w", err) + } + req.Header.Set("Accept", "application/json") + req.Header.Set("User-Agent", s.sdkConfiguration.UserAgent) + req.Header.Set("Content-Type", reqContentType) + + if err := utils.PopulateSecurity(ctx, req, s.sdkConfiguration.Security); err != nil { + return nil, err + } + + req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + if err != nil { + return nil, err + } + + httpRes, err := s.sdkConfiguration.Client.Do(req) + if err != nil || httpRes == nil { + if err != nil { + err = fmt.Errorf("error sending request: %w", err) + } else { + err = fmt.Errorf("error sending request: no response") + } + + _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + return nil, err + } else if utils.MatchStatusCodes([]string{"4XX", "5XX"}, httpRes.StatusCode) { + _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) + if err != nil { + return nil, err + } else if _httpRes != nil { + httpRes = _httpRes + } + } else { + httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) + if err != nil { + return nil, err + } + } + + res := &operations.CreateFeedbackTaskResponse{ + HTTPMeta: components.HTTPMetadata{ + Request: req, + Response: httpRes, + }, + } + + rawBody, err := io.ReadAll(httpRes.Body) + if err != nil { + return nil, fmt.Errorf("error reading response body: %w", err) + } + httpRes.Body.Close() + httpRes.Body = io.NopCloser(bytes.NewBuffer(rawBody)) + + switch { + case httpRes.StatusCode == 200: + switch { + case utils.MatchContentType(httpRes.Header.Get("Content-Type"), `application/json`): + var out components.Task + if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { + return nil, err + } + + res.Task = &out + default: + return nil, sdkerrors.NewSDKError(fmt.Sprintf("unknown content-type received: %s", httpRes.Header.Get("Content-Type")), httpRes.StatusCode, string(rawBody), httpRes) + } + case httpRes.StatusCode >= 400 && httpRes.StatusCode < 500: + fallthrough + case httpRes.StatusCode >= 500 && httpRes.StatusCode < 600: + return nil, sdkerrors.NewSDKError("API error occurred", httpRes.StatusCode, string(rawBody), httpRes) + default: + return nil, sdkerrors.NewSDKError("unknown status code returned", httpRes.StatusCode, string(rawBody), httpRes) + } + + return res, nil + +} + +// Get - Retrieves feedback task `taskId`. +func (s *FeedbackTasks) Get(ctx context.Context, taskID string) (*operations.GetFeedbackTaskResponse, error) { + hookCtx := hooks.HookContext{ + Context: ctx, + OperationID: "getFeedbackTask", + SecuritySource: s.sdkConfiguration.Security, + } + + request := operations.GetFeedbackTaskRequest{ + TaskID: taskID, + } + + baseURL := utils.ReplaceParameters(s.sdkConfiguration.GetServerDetails()) + opURL, err := utils.GenerateURL(ctx, baseURL, "/api/v1/feedback_task/{taskId}", request, nil) + if err != nil { + return nil, fmt.Errorf("error generating URL: %w", err) + } + + req, err := http.NewRequestWithContext(ctx, "GET", opURL, nil) + if err != nil { + return nil, fmt.Errorf("error creating request: %w", err) + } + req.Header.Set("Accept", "application/json") + req.Header.Set("User-Agent", s.sdkConfiguration.UserAgent) + + if err := utils.PopulateSecurity(ctx, req, s.sdkConfiguration.Security); err != nil { + return nil, err + } + + req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + if err != nil { + return nil, err + } + + httpRes, err := s.sdkConfiguration.Client.Do(req) + if err != nil || httpRes == nil { + if err != nil { + err = fmt.Errorf("error sending request: %w", err) + } else { + err = fmt.Errorf("error sending request: no response") + } + + _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + return nil, err + } else if utils.MatchStatusCodes([]string{"4XX", "5XX"}, httpRes.StatusCode) { + _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) + if err != nil { + return nil, err + } else if _httpRes != nil { + httpRes = _httpRes + } + } else { + httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) + if err != nil { + return nil, err + } + } + + res := &operations.GetFeedbackTaskResponse{ + HTTPMeta: components.HTTPMetadata{ + Request: req, + Response: httpRes, + }, + } + + rawBody, err := io.ReadAll(httpRes.Body) + if err != nil { + return nil, fmt.Errorf("error reading response body: %w", err) + } + httpRes.Body.Close() + httpRes.Body = io.NopCloser(bytes.NewBuffer(rawBody)) + + switch { + case httpRes.StatusCode == 200: + switch { + case utils.MatchContentType(httpRes.Header.Get("Content-Type"), `application/json`): + var out components.Task + if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { + return nil, err + } + + res.Task = &out + default: + return nil, sdkerrors.NewSDKError(fmt.Sprintf("unknown content-type received: %s", httpRes.Header.Get("Content-Type")), httpRes.StatusCode, string(rawBody), httpRes) + } + case httpRes.StatusCode >= 400 && httpRes.StatusCode < 500: + fallthrough + case httpRes.StatusCode >= 500 && httpRes.StatusCode < 600: + return nil, sdkerrors.NewSDKError("API error occurred", httpRes.StatusCode, string(rawBody), httpRes) + default: + return nil, sdkerrors.NewSDKError("unknown status code returned", httpRes.StatusCode, string(rawBody), httpRes) + } + + return res, nil + +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..6547c96 --- /dev/null +++ b/go.mod @@ -0,0 +1,8 @@ +module github.com/log10-io/log10go + +go 1.20 + +require ( + github.com/cenkalti/backoff/v4 v4.2.0 + github.com/ericlagergren/decimal v0.0.0-20221120152707-495c53812d05 +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..f955779 --- /dev/null +++ b/go.sum @@ -0,0 +1,4 @@ +github.com/cenkalti/backoff/v4 v4.2.0 h1:HN5dHm3WBOgndBH6E8V0q2jIYIR3s9yglV8k/+MN3u4= +github.com/cenkalti/backoff/v4 v4.2.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= +github.com/ericlagergren/decimal v0.0.0-20221120152707-495c53812d05 h1:S92OBrGuLLZsyM5ybUzgc/mPjIYk2AZqufieooe98uw= +github.com/ericlagergren/decimal v0.0.0-20221120152707-495c53812d05/go.mod h1:M9R1FoZ3y//hwwnJtO51ypFGwm8ZfpxPT/ZLtO1mcgQ= diff --git a/internal/globals/globals.go b/internal/globals/globals.go new file mode 100644 index 0000000..5acf2ef --- /dev/null +++ b/internal/globals/globals.go @@ -0,0 +1,14 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package globals + +type Globals struct { + XLog10Organization string `header:"style=simple,explode=false,name=X-Log10-Organization"` +} + +func (o *Globals) GetXLog10Organization() string { + if o == nil { + return "" + } + return o.XLog10Organization +} diff --git a/internal/hooks/hooks.go b/internal/hooks/hooks.go new file mode 100644 index 0000000..58e5a4e --- /dev/null +++ b/internal/hooks/hooks.go @@ -0,0 +1,142 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package hooks + +import ( + "context" + "errors" + "net/http" +) + +type FailEarly struct { + Cause error +} + +var _ error = (*FailEarly)(nil) + +func (f *FailEarly) Error() string { + return f.Cause.Error() +} + +// HTTPClient provides an interface for supplying the SDK with a custom HTTP client +type HTTPClient interface { + Do(req *http.Request) (*http.Response, error) +} + +type HookContext struct { + Context context.Context + OperationID string + OAuth2Scopes []string + SecuritySource func(context.Context) (interface{}, error) +} + +type BeforeRequestContext struct { + HookContext +} + +type AfterSuccessContext struct { + HookContext +} + +type AfterErrorContext struct { + HookContext +} + +// sdkInitHook is called when the SDK is initializing. The hook can modify and return a new baseURL and HTTP client to be used by the SDK. +type sdkInitHook interface { + SDKInit(baseURL string, client HTTPClient) (string, HTTPClient) +} + +// beforeRequestHook is called before the SDK sends a request. The hook can modify the request before it is sent or return an error to stop the request from being sent. +type beforeRequestHook interface { + BeforeRequest(hookCtx BeforeRequestContext, req *http.Request) (*http.Request, error) +} + +// afterSuccessHook is called after the SDK receives a response. The hook can modify the response before it is handled or return an error to stop the response from being handled. +type afterSuccessHook interface { + AfterSuccess(hookCtx AfterSuccessContext, res *http.Response) (*http.Response, error) +} + +// afterErrorHook is called after the SDK encounters an error, or a non-successful response. The hook can modify the response if available otherwise modify the error. +// All afterErrorHook hooks are called and returning an error won't stop the other hooks from being called. But if you want to stop the other hooks from being called, you can return a FailEarly error wrapping your error. +type afterErrorHook interface { + AfterError(hookCtx AfterErrorContext, res *http.Response, err error) (*http.Response, error) +} + +type Hooks struct { + sdkInitHooks []sdkInitHook + beforeRequestHook []beforeRequestHook + afterSuccessHook []afterSuccessHook + afterErrorHook []afterErrorHook +} + +func New() *Hooks { + h := &Hooks{ + sdkInitHooks: []sdkInitHook{}, + beforeRequestHook: []beforeRequestHook{}, + afterSuccessHook: []afterSuccessHook{}, + afterErrorHook: []afterErrorHook{}, + } + + return h +} + +// registerSDKInitHook registers a hook to be used by the SDK for the initialization event. +func (h *Hooks) registerSDKInitHook(hook sdkInitHook) { + h.sdkInitHooks = append(h.sdkInitHooks, hook) +} + +// registerBeforeRequestHook registers a hook to be used by the SDK for the before request event. +func (h *Hooks) registerBeforeRequestHook(hook beforeRequestHook) { + h.beforeRequestHook = append(h.beforeRequestHook, hook) +} + +// registerAfterSuccessHook registers a hook to be used by the SDK for the after success event. +func (h *Hooks) registerAfterSuccessHook(hook afterSuccessHook) { + h.afterSuccessHook = append(h.afterSuccessHook, hook) +} + +// registerAfterErrorHook registers a hook to be used by the SDK for the after error event. +func (h *Hooks) registerAfterErrorHook(hook afterErrorHook) { + h.afterErrorHook = append(h.afterErrorHook, hook) +} + +func (h *Hooks) SDKInit(baseURL string, client HTTPClient) (string, HTTPClient) { + for _, hook := range h.sdkInitHooks { + baseURL, client = hook.SDKInit(baseURL, client) + } + return baseURL, client +} + +func (h *Hooks) BeforeRequest(hookCtx BeforeRequestContext, req *http.Request) (*http.Request, error) { + for _, hook := range h.beforeRequestHook { + var err error + req, err = hook.BeforeRequest(hookCtx, req) + if err != nil { + return req, err + } + } + return req, nil +} + +func (h *Hooks) AfterSuccess(hookCtx AfterSuccessContext, res *http.Response) (*http.Response, error) { + for _, hook := range h.afterSuccessHook { + var err error + res, err = hook.AfterSuccess(hookCtx, res) + if err != nil { + return res, err + } + } + return res, nil +} + +func (h *Hooks) AfterError(hookCtx AfterErrorContext, res *http.Response, err error) (*http.Response, error) { + for _, hook := range h.afterErrorHook { + res, err = hook.AfterError(hookCtx, res, err) + var fe *FailEarly + if errors.As(err, &fe) { + return nil, fe.Cause + } + } + return res, err +} diff --git a/internal/utils/contenttype.go b/internal/utils/contenttype.go new file mode 100644 index 0000000..8ed13e2 --- /dev/null +++ b/internal/utils/contenttype.go @@ -0,0 +1,33 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package utils + +import ( + "fmt" + "mime" + "strings" +) + +func MatchContentType(contentType string, pattern string) bool { + if contentType == pattern || pattern == "*" || pattern == "*/*" { + return true + } + + mediaType, _, err := mime.ParseMediaType(contentType) + if err != nil { + return false + } + + if mediaType == pattern { + return true + } + + parts := strings.Split(mediaType, "/") + if len(parts) == 2 { + if fmt.Sprintf("%s/*", parts[0]) == pattern || fmt.Sprintf("*/%s", parts[1]) == pattern { + return true + } + } + + return false +} diff --git a/internal/utils/form.go b/internal/utils/form.go new file mode 100644 index 0000000..11daa62 --- /dev/null +++ b/internal/utils/form.go @@ -0,0 +1,117 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package utils + +import ( + "fmt" + "math/big" + "net/url" + "reflect" + "strings" + "time" + + "github.com/ericlagergren/decimal" + + "github.com/log10-io/log10go/types" +) + +func populateForm(paramName string, explode bool, objType reflect.Type, objValue reflect.Value, delimiter string, getFieldName func(reflect.StructField) string) url.Values { + + formValues := url.Values{} + + if isNil(objType, objValue) { + return formValues + } + + if objType.Kind() == reflect.Pointer { + objType = objType.Elem() + objValue = objValue.Elem() + } + + switch objType.Kind() { + case reflect.Struct: + switch objValue.Interface().(type) { + case time.Time: + formValues.Add(paramName, valToString(objValue.Interface())) + case types.Date: + formValues.Add(paramName, valToString(objValue.Interface())) + case big.Int: + formValues.Add(paramName, valToString(objValue.Interface())) + case decimal.Big: + formValues.Add(paramName, valToString(objValue.Interface())) + default: + var items []string + + for i := 0; i < objType.NumField(); i++ { + fieldType := objType.Field(i) + valType := objValue.Field(i) + + if isNil(fieldType.Type, valType) { + continue + } + + if valType.Kind() == reflect.Pointer { + valType = valType.Elem() + } + + fieldName := getFieldName(fieldType) + if fieldName == "" { + continue + } + + if explode { + formValues.Add(fieldName, valToString(valType.Interface())) + } else { + items = append(items, fmt.Sprintf("%s%s%s", fieldName, delimiter, valToString(valType.Interface()))) + } + } + + if len(items) > 0 { + formValues.Add(paramName, strings.Join(items, delimiter)) + } + } + case reflect.Map: + items := []string{} + + iter := objValue.MapRange() + for iter.Next() { + if explode { + formValues.Add(iter.Key().String(), valToString(iter.Value().Interface())) + } else { + items = append(items, fmt.Sprintf("%s%s%s", iter.Key().String(), delimiter, valToString(iter.Value().Interface()))) + } + } + + if len(items) > 0 { + formValues.Add(paramName, strings.Join(items, delimiter)) + } + case reflect.Slice, reflect.Array: + values := parseDelimitedArray(explode, objValue, delimiter) + for _, v := range values { + formValues.Add(paramName, v) + } + default: + formValues.Add(paramName, valToString(objValue.Interface())) + } + + return formValues +} + +func parseDelimitedArray(explode bool, objValue reflect.Value, delimiter string) []string { + values := []string{} + items := []string{} + + for i := 0; i < objValue.Len(); i++ { + if explode { + values = append(values, valToString(objValue.Index(i).Interface())) + } else { + items = append(items, valToString(objValue.Index(i).Interface())) + } + } + + if len(items) > 0 { + values = append(values, strings.Join(items, delimiter)) + } + + return values +} diff --git a/internal/utils/headers.go b/internal/utils/headers.go new file mode 100644 index 0000000..107d210 --- /dev/null +++ b/internal/utils/headers.go @@ -0,0 +1,124 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package utils + +import ( + "context" + "fmt" + "net/http" + "reflect" + "strings" +) + +func PopulateHeaders(_ context.Context, req *http.Request, headers interface{}, globals interface{}) { + globalsAlreadyPopulated := populateHeaders(headers, globals, req.Header, []string{}) + if globals != nil { + _ = populateHeaders(globals, nil, req.Header, globalsAlreadyPopulated) + } +} + +func populateHeaders(headers interface{}, globals interface{}, reqHeaders http.Header, skipFields []string) []string { + headerParamsStructType, headerParamsValType := dereferencePointers(reflect.TypeOf(headers), reflect.ValueOf(headers)) + + globalsAlreadyPopulated := []string{} + + for i := 0; i < headerParamsStructType.NumField(); i++ { + fieldType := headerParamsStructType.Field(i) + valType := headerParamsValType.Field(i) + + if contains(skipFields, fieldType.Name) { + continue + } + + if globals != nil { + var globalFound bool + fieldType, valType, globalFound = populateFromGlobals(fieldType, valType, headerParamTagKey, globals) + if globalFound { + globalsAlreadyPopulated = append(globalsAlreadyPopulated, fieldType.Name) + } + } + + tag := parseParamTag(headerParamTagKey, fieldType, "simple", false) + if tag == nil { + continue + } + + value := serializeHeader(fieldType.Type, valType, tag.Explode) + if value != "" { + reqHeaders.Add(tag.ParamName, value) + } + } + + return globalsAlreadyPopulated +} + +func serializeHeader(objType reflect.Type, objValue reflect.Value, explode bool) string { + if isNil(objType, objValue) { + return "" + } + + if objType.Kind() == reflect.Pointer { + objType = objType.Elem() + objValue = objValue.Elem() + } + + switch objType.Kind() { + case reflect.Struct: + items := []string{} + + for i := 0; i < objType.NumField(); i++ { + fieldType := objType.Field(i) + valType := objValue.Field(i) + + if isNil(fieldType.Type, valType) { + continue + } + + if fieldType.Type.Kind() == reflect.Pointer { + valType = valType.Elem() + } + + tag := parseParamTag(headerParamTagKey, fieldType, "simple", false) + if tag == nil { + continue + } + + fieldName := tag.ParamName + + if fieldName == "" { + continue + } + + if explode { + items = append(items, fmt.Sprintf("%s=%s", fieldName, valToString(valType.Interface()))) + } else { + items = append(items, fieldName, valToString(valType.Interface())) + } + } + + return strings.Join(items, ",") + case reflect.Map: + items := []string{} + + iter := objValue.MapRange() + for iter.Next() { + if explode { + items = append(items, fmt.Sprintf("%s=%s", iter.Key().String(), valToString(iter.Value().Interface()))) + } else { + items = append(items, iter.Key().String(), valToString(iter.Value().Interface())) + } + } + + return strings.Join(items, ",") + case reflect.Slice, reflect.Array: + items := []string{} + + for i := 0; i < objValue.Len(); i++ { + items = append(items, valToString(objValue.Index(i).Interface())) + } + + return strings.Join(items, ",") + default: + return valToString(objValue.Interface()) + } +} diff --git a/internal/utils/json.go b/internal/utils/json.go new file mode 100644 index 0000000..9fca6c8 --- /dev/null +++ b/internal/utils/json.go @@ -0,0 +1,670 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package utils + +import ( + "bytes" + "encoding/json" + "fmt" + "math/big" + "reflect" + "strconv" + "strings" + "time" + "unsafe" + + "github.com/log10-io/log10go/types" + + "github.com/ericlagergren/decimal" +) + +func MarshalJSON(v interface{}, tag reflect.StructTag, topLevel bool) ([]byte, error) { + typ, val := dereferencePointers(reflect.TypeOf(v), reflect.ValueOf(v)) + + switch { + case isModelType(typ): + if topLevel { + return json.Marshal(v) + } + + if isNil(typ, val) { + return []byte("null"), nil + } + + out := map[string]json.RawMessage{} + + for i := 0; i < typ.NumField(); i++ { + field := typ.Field(i) + fieldVal := val.Field(i) + + fieldName := field.Name + + omitEmpty := false + jsonTag := field.Tag.Get("json") + if jsonTag != "" { + for _, tag := range strings.Split(jsonTag, ",") { + if tag == "omitempty" { + omitEmpty = true + } else { + fieldName = tag + } + } + } + + if isNil(field.Type, fieldVal) && field.Tag.Get("const") == "" { + if omitEmpty { + continue + } + } + + if !field.IsExported() && field.Tag.Get("const") == "" { + continue + } + + additionalProperties := field.Tag.Get("additionalProperties") + if fieldName == "-" && additionalProperties == "" { + continue + } + + if additionalProperties == "true" { + if isNil(field.Type, fieldVal) { + continue + } + fieldVal := trueReflectValue(fieldVal) + if fieldVal.Type().Kind() != reflect.Map { + return nil, fmt.Errorf("additionalProperties must be a map") + } + + for _, key := range fieldVal.MapKeys() { + r, err := marshalValue(fieldVal.MapIndex(key).Interface(), field.Tag) + if err != nil { + return nil, err + } + + out[key.String()] = r + } + + continue + } + + var fv interface{} + + if field.IsExported() { + fv = fieldVal.Interface() + } else { + pt := reflect.New(typ).Elem() + pt.Set(val) + + pf := pt.Field(i) + + fv = reflect.NewAt(pf.Type(), unsafe.Pointer(pf.UnsafeAddr())).Elem().Interface() + } + + r, err := marshalValue(fv, field.Tag) + if err != nil { + return nil, err + } + + out[fieldName] = r + } + + return json.Marshal(out) + default: + return marshalValue(v, tag) + } +} + +func UnmarshalJSON(b []byte, v interface{}, tag reflect.StructTag, topLevel bool, disallowUnknownFields bool) error { + if reflect.TypeOf(v).Kind() != reflect.Ptr { + return fmt.Errorf("v must be a pointer") + } + + typ, val := dereferencePointers(reflect.TypeOf(v), reflect.ValueOf(v)) + + switch { + case isModelType(typ): + if topLevel || bytes.Equal(b, []byte("null")) { + d := json.NewDecoder(bytes.NewReader(b)) + if disallowUnknownFields { + d.DisallowUnknownFields() + } + return d.Decode(v) + } + + var unmarhsaled map[string]json.RawMessage + + if err := json.Unmarshal(b, &unmarhsaled); err != nil { + return err + } + + var additionalPropertiesField *reflect.StructField + var additionalPropertiesValue *reflect.Value + + for i := 0; i < typ.NumField(); i++ { + field := typ.Field(i) + fieldVal := val.Field(i) + + fieldName := field.Name + + jsonTag := field.Tag.Get("json") + if jsonTag != "" { + for _, tag := range strings.Split(jsonTag, ",") { + if tag != "omitempty" { + fieldName = tag + } + } + } + + if field.Tag.Get("additionalProperties") == "true" { + additionalPropertiesField = &field + additionalPropertiesValue = &fieldVal + continue + } + + // If we receive a value for a const field ignore it but mark it as unmarshaled + if field.Tag.Get("const") != "" { + if r, ok := unmarhsaled[fieldName]; ok { + val := string(r) + if strings.HasPrefix(val, `"`) && strings.HasSuffix(val, `"`) { + val = val[1 : len(val)-1] + } + if val != field.Tag.Get("const") { + return fmt.Errorf("const field %s does not match expected value %s", fieldName, field.Tag.Get("const")) + } + + delete(unmarhsaled, fieldName) + } + } else if !field.IsExported() { + continue + } + + value, ok := unmarhsaled[fieldName] + if !ok { + defaultTag := field.Tag.Get("default") + if defaultTag != "" { + value = handleDefaultConstValue(defaultTag, fieldVal.Interface(), field.Tag) + ok = true + } + } else { + delete(unmarhsaled, fieldName) + } + + if ok { + if err := unmarshalValue(value, fieldVal, field.Tag, disallowUnknownFields); err != nil { + return err + } + } + } + + keys := make([]string, 0, len(unmarhsaled)) + for k := range unmarhsaled { + keys = append(keys, k) + } + + if len(keys) > 0 { + if disallowUnknownFields && (additionalPropertiesField == nil || additionalPropertiesValue == nil) { + return fmt.Errorf("unknown fields: %v", keys) + } + + if additionalPropertiesField != nil && additionalPropertiesValue != nil { + typeOfMap := additionalPropertiesField.Type + if additionalPropertiesValue.Type().Kind() == reflect.Interface { + typeOfMap = reflect.TypeOf(map[string]interface{}{}) + } else if additionalPropertiesValue.Type().Kind() != reflect.Map { + return fmt.Errorf("additionalProperties must be a map") + } + + mapValue := reflect.MakeMap(typeOfMap) + + for key, value := range unmarhsaled { + val := reflect.New(typeOfMap.Elem()) + + if err := unmarshalValue(value, val, additionalPropertiesField.Tag, disallowUnknownFields); err != nil { + return err + } + + if val.Elem().Type().String() == typeOfMap.Elem().String() { + mapValue.SetMapIndex(reflect.ValueOf(key), val.Elem()) + } else { + mapValue.SetMapIndex(reflect.ValueOf(key), trueReflectValue(val)) + } + + } + if additionalPropertiesValue.Type().Kind() == reflect.Interface { + additionalPropertiesValue.Set(mapValue) + } else { + additionalPropertiesValue.Set(mapValue) + } + } + } + default: + return unmarshalValue(b, reflect.ValueOf(v), tag, disallowUnknownFields) + } + + return nil +} + +func marshalValue(v interface{}, tag reflect.StructTag) (json.RawMessage, error) { + constTag := tag.Get("const") + if constTag != "" { + return handleDefaultConstValue(constTag, v, tag), nil + } + + if isNil(reflect.TypeOf(v), reflect.ValueOf(v)) { + defaultTag := tag.Get("default") + if defaultTag != "" { + return handleDefaultConstValue(defaultTag, v, tag), nil + } + + return []byte("null"), nil + } + + typ, val := dereferencePointers(reflect.TypeOf(v), reflect.ValueOf(v)) + switch typ.Kind() { + case reflect.Int64: + format := tag.Get("integer") + if format == "string" { + b := val.Interface().(int64) + return []byte(fmt.Sprintf(`"%d"`, b)), nil + } + case reflect.Float64: + format := tag.Get("number") + if format == "string" { + b := val.Interface().(float64) + return []byte(fmt.Sprintf(`"%g"`, b)), nil + } + case reflect.Map: + if isNil(typ, val) { + return []byte("null"), nil + } + + out := map[string]json.RawMessage{} + + for _, key := range val.MapKeys() { + itemVal := val.MapIndex(key) + + if isNil(itemVal.Type(), itemVal) { + out[key.String()] = []byte("null") + continue + } + + r, err := marshalValue(itemVal.Interface(), tag) + if err != nil { + return nil, err + } + + out[key.String()] = r + } + + return json.Marshal(out) + case reflect.Slice, reflect.Array: + if isNil(typ, val) { + return []byte("null"), nil + } + + out := []json.RawMessage{} + + for i := 0; i < val.Len(); i++ { + itemVal := val.Index(i) + + if isNil(itemVal.Type(), itemVal) { + out = append(out, []byte("null")) + continue + } + + r, err := marshalValue(itemVal.Interface(), tag) + if err != nil { + return nil, err + } + + out = append(out, r) + } + + return json.Marshal(out) + case reflect.Struct: + switch typ { + case reflect.TypeOf(time.Time{}): + return []byte(fmt.Sprintf(`"%s"`, val.Interface().(time.Time).Format(time.RFC3339Nano))), nil + case reflect.TypeOf(big.Int{}): + format := tag.Get("bigint") + if format == "string" { + b := val.Interface().(big.Int) + return []byte(fmt.Sprintf(`"%s"`, (&b).String())), nil + } + case reflect.TypeOf(decimal.Big{}): + format := tag.Get("decimal") + if format == "number" { + b := val.Interface().(decimal.Big) + f, ok := (&b).Float64() + if ok { + return []byte(b.String()), nil + } + + return []byte(fmt.Sprintf(`%f`, f)), nil + } + } + } + + return json.Marshal(v) +} + +func handleDefaultConstValue(tagValue string, val interface{}, tag reflect.StructTag) json.RawMessage { + if tagValue == "null" { + return []byte("null") + } + + typ := dereferenceTypePointer(reflect.TypeOf(val)) + switch typ { + case reflect.TypeOf(time.Time{}): + return []byte(fmt.Sprintf(`"%s"`, tagValue)) + case reflect.TypeOf(big.Int{}): + bigIntTag := tag.Get("bigint") + if bigIntTag == "string" { + return []byte(fmt.Sprintf(`"%s"`, tagValue)) + } + case reflect.TypeOf(int64(0)): + format := tag.Get("integer") + if format == "string" { + return []byte(fmt.Sprintf(`"%s"`, tagValue)) + } + case reflect.TypeOf(float64(0)): + format := tag.Get("number") + if format == "string" { + return []byte(fmt.Sprintf(`"%s"`, tagValue)) + } + case reflect.TypeOf(decimal.Big{}): + decimalTag := tag.Get("decimal") + if decimalTag != "number" { + return []byte(fmt.Sprintf(`"%s"`, tagValue)) + } + case reflect.TypeOf(types.Date{}): + return []byte(fmt.Sprintf(`"%s"`, tagValue)) + default: + if typ.Kind() == reflect.String { + return []byte(fmt.Sprintf("%q", tagValue)) + } + } + + return []byte(tagValue) +} + +func unmarshalValue(value json.RawMessage, v reflect.Value, tag reflect.StructTag, disallowUnknownFields bool) error { + if bytes.Equal(value, []byte("null")) { + if v.CanAddr() { + return json.Unmarshal(value, v.Addr().Interface()) + } else { + return json.Unmarshal(value, v.Interface()) + } + } + + typ := dereferenceTypePointer(v.Type()) + + switch typ.Kind() { + case reflect.Int64: + var b int64 + + format := tag.Get("integer") + if format == "string" { + var s string + if err := json.Unmarshal(value, &s); err != nil { + return err + } + + var err error + b, err = strconv.ParseInt(s, 10, 64) + if err != nil { + return fmt.Errorf("failed to parse string as int64: %w", err) + } + if v.Kind() == reflect.Ptr { + if v.IsNil() { + v.Set(reflect.New(typ)) + } + v = v.Elem() + } + + v.Set(reflect.ValueOf(b)) + return nil + } + case reflect.Float64: + var b float64 + + format := tag.Get("number") + if format == "string" { + var s string + if err := json.Unmarshal(value, &s); err != nil { + return err + } + + var err error + b, err = strconv.ParseFloat(s, 64) + if err != nil { + return fmt.Errorf("failed to parse string as float64: %w", err) + } + + if v.Kind() == reflect.Ptr { + if v.IsNil() { + v.Set(reflect.New(typ)) + } + v = v.Elem() + } + + v.Set(reflect.ValueOf(b)) + return nil + } + case reflect.Map: + if bytes.Equal(value, []byte("null")) || !isComplexValueType(dereferenceTypePointer(typ.Elem())) { + if v.CanAddr() { + return json.Unmarshal(value, v.Addr().Interface()) + } else { + return json.Unmarshal(value, v.Interface()) + } + } + + var unmarhsaled map[string]json.RawMessage + + if err := json.Unmarshal(value, &unmarhsaled); err != nil { + return err + } + + m := reflect.MakeMap(typ) + + for k, value := range unmarhsaled { + itemVal := reflect.New(typ.Elem()) + + if err := unmarshalValue(value, itemVal, tag, disallowUnknownFields); err != nil { + return err + } + + m.SetMapIndex(reflect.ValueOf(k), itemVal.Elem()) + } + + v.Set(m) + return nil + case reflect.Slice, reflect.Array: + if bytes.Equal(value, []byte("null")) || !isComplexValueType(dereferenceTypePointer(typ.Elem())) { + if v.CanAddr() { + return json.Unmarshal(value, v.Addr().Interface()) + } else { + return json.Unmarshal(value, v.Interface()) + } + } + + var unmarhsaled []json.RawMessage + + if err := json.Unmarshal(value, &unmarhsaled); err != nil { + return err + } + + arrVal := v + + for _, value := range unmarhsaled { + itemVal := reflect.New(typ.Elem()) + + if err := unmarshalValue(value, itemVal, tag, disallowUnknownFields); err != nil { + return err + } + + arrVal = reflect.Append(arrVal, itemVal.Elem()) + } + + v.Set(arrVal) + return nil + case reflect.Struct: + switch typ { + case reflect.TypeOf(time.Time{}): + var s string + if err := json.Unmarshal(value, &s); err != nil { + return err + } + + t, err := time.Parse(time.RFC3339Nano, s) + if err != nil { + return fmt.Errorf("failed to parse string as time.Time: %w", err) + } + + if v.Kind() == reflect.Ptr { + if v.IsNil() { + v.Set(reflect.New(typ)) + } + v = v.Elem() + } + + v.Set(reflect.ValueOf(t)) + return nil + case reflect.TypeOf(big.Int{}): + var b *big.Int + + format := tag.Get("bigint") + if format == "string" { + var s string + if err := json.Unmarshal(value, &s); err != nil { + return err + } + + var ok bool + b, ok = new(big.Int).SetString(s, 10) + if !ok { + return fmt.Errorf("failed to parse string as big.Int") + } + } else { + if err := json.Unmarshal(value, &b); err != nil { + return err + } + } + + if v.Kind() == reflect.Ptr && v.Elem().Kind() == reflect.Ptr { + v = v.Elem() + } + + v.Set(reflect.ValueOf(b)) + return nil + case reflect.TypeOf(decimal.Big{}): + var d *decimal.Big + format := tag.Get("decimal") + if format == "number" { + var ok bool + d, ok = new(decimal.Big).SetString(string(value)) + if !ok { + return fmt.Errorf("failed to parse number as decimal.Big") + } + } else { + if err := json.Unmarshal(value, &d); err != nil { + return err + } + } + + if v.Kind() == reflect.Ptr && v.Elem().Kind() == reflect.Ptr { + v = v.Elem() + } + + v.Set(reflect.ValueOf(d)) + return nil + case reflect.TypeOf(types.Date{}): + var s string + + if err := json.Unmarshal(value, &s); err != nil { + return err + } + + d, err := types.DateFromString(s) + if err != nil { + return fmt.Errorf("failed to parse string as types.Date: %w", err) + } + + if v.Kind() == reflect.Ptr { + if v.IsNil() { + v.Set(reflect.New(typ)) + } + v = v.Elem() + } + + v.Set(reflect.ValueOf(d)) + return nil + } + } + + var val interface{} + + if v.CanAddr() { + val = v.Addr().Interface() + } else { + val = v.Interface() + } + + d := json.NewDecoder(bytes.NewReader(value)) + if disallowUnknownFields { + d.DisallowUnknownFields() + } + return d.Decode(val) +} + +func dereferencePointers(typ reflect.Type, val reflect.Value) (reflect.Type, reflect.Value) { + if typ.Kind() == reflect.Ptr { + typ = typ.Elem() + val = val.Elem() + } else { + return typ, val + } + + return dereferencePointers(typ, val) +} + +func dereferenceTypePointer(typ reflect.Type) reflect.Type { + if typ.Kind() == reflect.Ptr { + typ = typ.Elem() + } else { + return typ + } + + return dereferenceTypePointer(typ) +} + +func isComplexValueType(typ reflect.Type) bool { + switch typ.Kind() { + case reflect.Struct: + switch typ { + case reflect.TypeOf(time.Time{}): + fallthrough + case reflect.TypeOf(big.Int{}): + fallthrough + case reflect.TypeOf(decimal.Big{}): + fallthrough + case reflect.TypeOf(types.Date{}): + return true + } + } + + return false +} + +func isModelType(typ reflect.Type) bool { + if isComplexValueType(typ) { + return false + } + + if typ.Kind() == reflect.Struct { + return true + } + + return false +} diff --git a/internal/utils/pathparams.go b/internal/utils/pathparams.go new file mode 100644 index 0000000..5bba66a --- /dev/null +++ b/internal/utils/pathparams.go @@ -0,0 +1,172 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package utils + +import ( + "context" + "fmt" + "math/big" + "net/url" + "reflect" + "strings" + "time" + + "github.com/ericlagergren/decimal" + + "github.com/log10-io/log10go/types" +) + +func GenerateURL(_ context.Context, serverURL, path string, pathParams interface{}, globals interface{}) (string, error) { + uri := strings.TrimSuffix(serverURL, "/") + path + + parsedParameters := map[string]string{} + + globalsAlreadyPopulated, err := populateParsedParameters(pathParams, globals, parsedParameters, []string{}) + if err != nil { + return "", err + } + + if globals != nil { + _, err = populateParsedParameters(globals, nil, parsedParameters, globalsAlreadyPopulated) + if err != nil { + return "", err + } + } + + // TODO should we handle the case where there are no matching path params? + return ReplaceParameters(uri, parsedParameters), nil +} + +func populateParsedParameters(pathParams interface{}, globals interface{}, parsedParameters map[string]string, skipFields []string) ([]string, error) { + pathParamsStructType, pathParamsValType := dereferencePointers(reflect.TypeOf(pathParams), reflect.ValueOf(pathParams)) + + globalsAlreadyPopulated := []string{} + + for i := 0; i < pathParamsStructType.NumField(); i++ { + fieldType := pathParamsStructType.Field(i) + valType := pathParamsValType.Field(i) + + if contains(skipFields, fieldType.Name) { + continue + } + + requestTag := getRequestTag(fieldType) + if requestTag != nil { + continue + } + + ppTag := parseParamTag(pathParamTagKey, fieldType, "simple", false) + if ppTag == nil { + continue + } + + if globals != nil { + var globalFound bool + fieldType, valType, globalFound = populateFromGlobals(fieldType, valType, pathParamTagKey, globals) + if globalFound { + globalsAlreadyPopulated = append(globalsAlreadyPopulated, fieldType.Name) + } + } + + if ppTag.Serialization != "" { + vals, err := populateSerializedParams(ppTag, fieldType.Type, valType) + if err != nil { + return nil, err + } + for k, v := range vals { + parsedParameters[k] = url.PathEscape(v) + } + } else { + // TODO: support other styles + switch ppTag.Style { + case "simple": + simpleParams := getSimplePathParams(ppTag.ParamName, fieldType.Type, valType, ppTag.Explode) + for k, v := range simpleParams { + parsedParameters[k] = v + } + } + } + } + + return globalsAlreadyPopulated, nil +} + +func getSimplePathParams(parentName string, objType reflect.Type, objValue reflect.Value, explode bool) map[string]string { + pathParams := make(map[string]string) + + if isNil(objType, objValue) { + return nil + } + + if objType.Kind() == reflect.Ptr { + objType = objType.Elem() + objValue = objValue.Elem() + } + + switch objType.Kind() { + case reflect.Array, reflect.Slice: + if objValue.Len() == 0 { + return nil + } + var ppVals []string + for i := 0; i < objValue.Len(); i++ { + ppVals = append(ppVals, valToString(objValue.Index(i).Interface())) + } + pathParams[parentName] = strings.Join(ppVals, ",") + case reflect.Map: + if objValue.Len() == 0 { + return nil + } + var ppVals []string + objMap := objValue.MapRange() + for objMap.Next() { + if explode { + ppVals = append(ppVals, fmt.Sprintf("%s=%s", objMap.Key().String(), valToString(objMap.Value().Interface()))) + } else { + ppVals = append(ppVals, fmt.Sprintf("%s,%s", objMap.Key().String(), valToString(objMap.Value().Interface()))) + } + } + pathParams[parentName] = strings.Join(ppVals, ",") + case reflect.Struct: + switch objValue.Interface().(type) { + case time.Time: + pathParams[parentName] = valToString(objValue.Interface()) + case types.Date: + pathParams[parentName] = valToString(objValue.Interface()) + case big.Int: + pathParams[parentName] = valToString(objValue.Interface()) + case decimal.Big: + pathParams[parentName] = valToString(objValue.Interface()) + default: + var ppVals []string + for i := 0; i < objType.NumField(); i++ { + fieldType := objType.Field(i) + valType := objValue.Field(i) + + ppTag := parseParamTag(pathParamTagKey, fieldType, "simple", explode) + if ppTag == nil { + continue + } + + if isNil(fieldType.Type, valType) { + continue + } + + if fieldType.Type.Kind() == reflect.Pointer { + valType = valType.Elem() + } + + if explode { + ppVals = append(ppVals, fmt.Sprintf("%s=%s", ppTag.ParamName, valToString(valType.Interface()))) + } else { + ppVals = append(ppVals, fmt.Sprintf("%s,%s", ppTag.ParamName, valToString(valType.Interface()))) + } + } + pathParams[parentName] = strings.Join(ppVals, ",") + } + default: + pathParams[parentName] = valToString(objValue.Interface()) + } + + return pathParams +} diff --git a/internal/utils/queryparams.go b/internal/utils/queryparams.go new file mode 100644 index 0000000..e2c5b9d --- /dev/null +++ b/internal/utils/queryparams.go @@ -0,0 +1,205 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package utils + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/url" + "reflect" +) + +func PopulateQueryParams(_ context.Context, req *http.Request, queryParams interface{}, globals interface{}) error { + values := url.Values{} + + globalsAlreadyPopulated, err := populateQueryParams(queryParams, globals, values, []string{}) + if err != nil { + return err + } + + if globals != nil { + _, err = populateQueryParams(globals, nil, values, globalsAlreadyPopulated) + if err != nil { + return err + } + } + + req.URL.RawQuery = values.Encode() + + return nil +} + +func populateQueryParams(queryParams interface{}, globals interface{}, values url.Values, skipFields []string) ([]string, error) { + queryParamsStructType, queryParamsValType := dereferencePointers(reflect.TypeOf(queryParams), reflect.ValueOf(queryParams)) + + globalsAlreadyPopulated := []string{} + + for i := 0; i < queryParamsStructType.NumField(); i++ { + fieldType := queryParamsStructType.Field(i) + valType := queryParamsValType.Field(i) + + if contains(skipFields, fieldType.Name) { + continue + } + + requestTag := getRequestTag(fieldType) + if requestTag != nil { + continue + } + + qpTag := parseQueryParamTag(fieldType) + if qpTag == nil { + continue + } + + if globals != nil { + var globalFound bool + fieldType, valType, globalFound = populateFromGlobals(fieldType, valType, queryParamTagKey, globals) + if globalFound { + globalsAlreadyPopulated = append(globalsAlreadyPopulated, fieldType.Name) + } + } + + if qpTag.Serialization != "" { + vals, err := populateSerializedParams(qpTag, fieldType.Type, valType) + if err != nil { + return nil, err + } + for k, v := range vals { + values.Add(k, v) + } + } else { + switch qpTag.Style { + case "deepObject": + vals := populateDeepObjectParams(qpTag, fieldType.Type, valType) + for k, v := range vals { + for _, vv := range v { + values.Add(k, vv) + } + } + case "form": + vals := populateFormParams(qpTag, fieldType.Type, valType, ",") + for k, v := range vals { + for _, vv := range v { + values.Add(k, vv) + } + } + case "pipeDelimited": + vals := populateFormParams(qpTag, fieldType.Type, valType, "|") + for k, v := range vals { + for _, vv := range v { + values.Add(k, vv) + } + } + default: + return nil, fmt.Errorf("unsupported style: %s", qpTag.Style) + } + } + } + + return globalsAlreadyPopulated, nil +} + +func populateSerializedParams(tag *paramTag, objType reflect.Type, objValue reflect.Value) (map[string]string, error) { + if isNil(objType, objValue) { + return nil, nil + } + + if objType.Kind() == reflect.Pointer { + objValue = objValue.Elem() + } + + values := map[string]string{} + + switch tag.Serialization { + case "json": + data, err := json.Marshal(objValue.Interface()) + if err != nil { + return nil, fmt.Errorf("error marshaling json: %v", err) + } + values[tag.ParamName] = string(data) + } + + return values, nil +} + +func populateDeepObjectParams(tag *paramTag, objType reflect.Type, objValue reflect.Value) url.Values { + values := url.Values{} + + if isNil(objType, objValue) { + return values + } + + if objType.Kind() == reflect.Pointer { + objType = objType.Elem() + objValue = objValue.Elem() + } + + switch objType.Kind() { + case reflect.Struct: + for i := 0; i < objType.NumField(); i++ { + fieldType := objType.Field(i) + valType := objValue.Field(i) + + if isNil(fieldType.Type, valType) { + continue + } + + if fieldType.Type.Kind() == reflect.Pointer { + valType = valType.Elem() + } + + qpTag := parseQueryParamTag(fieldType) + if qpTag == nil { + continue + } + + switch valType.Kind() { + case reflect.Array, reflect.Slice: + for i := 0; i < valType.Len(); i++ { + values.Add(fmt.Sprintf("%s[%s]", tag.ParamName, qpTag.ParamName), valToString(valType.Index(i).Interface())) + } + default: + values.Add(fmt.Sprintf("%s[%s]", tag.ParamName, qpTag.ParamName), valToString(valType.Interface())) + } + } + case reflect.Map: + iter := objValue.MapRange() + for iter.Next() { + switch iter.Value().Kind() { + case reflect.Array, reflect.Slice: + for i := 0; i < iter.Value().Len(); i++ { + values.Add(fmt.Sprintf("%s[%s]", tag.ParamName, iter.Key().String()), valToString(iter.Value().Index(i).Interface())) + } + default: + values.Add(fmt.Sprintf("%s[%s]", tag.ParamName, iter.Key().String()), valToString(iter.Value().Interface())) + } + } + } + + return values +} + +func populateFormParams(tag *paramTag, objType reflect.Type, objValue reflect.Value, delimiter string) url.Values { + return populateForm(tag.ParamName, tag.Explode, objType, objValue, delimiter, func(fieldType reflect.StructField) string { + qpTag := parseQueryParamTag(fieldType) + if qpTag == nil { + return "" + } + + return qpTag.ParamName + }) +} + +type paramTag struct { + Style string + Explode bool + ParamName string + Serialization string +} + +func parseQueryParamTag(field reflect.StructField) *paramTag { + return parseParamTag(queryParamTagKey, field, "form", true) +} diff --git a/internal/utils/requestbody.go b/internal/utils/requestbody.go new file mode 100644 index 0000000..cfb2ba6 --- /dev/null +++ b/internal/utils/requestbody.go @@ -0,0 +1,409 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package utils + +import ( + "bytes" + "context" + "fmt" + "io" + "mime/multipart" + "net/url" + "reflect" + "regexp" +) + +const ( + requestTagKey = "request" + multipartFormTagKey = "multipartForm" + formTagKey = "form" +) + +var ( + jsonEncodingRegex = regexp.MustCompile(`(application|text)\/.*?\+*json.*`) + multipartEncodingRegex = regexp.MustCompile(`multipart\/.*`) + urlEncodedEncodingRegex = regexp.MustCompile(`application\/x-www-form-urlencoded.*`) +) + +func SerializeRequestBody(_ context.Context, request interface{}, nullable, optional bool, requestFieldName, serializationMethod, tag string) (io.Reader, string, error) { + bodyReader, contentType, err := serializeRequestBody(request, nullable, optional, requestFieldName, serializationMethod, tag) + if err != nil { + return nil, "", fmt.Errorf("error serializing request body: %w", err) + } + + if bodyReader == nil && !optional { + return nil, "", fmt.Errorf("request body is required") + } + + return bodyReader, contentType, nil +} + +func serializeRequestBody(request interface{}, nullable, optional bool, requestFieldName, serializationMethod, tag string) (io.Reader, string, error) { + requestStructType := reflect.TypeOf(request) + requestValType := reflect.ValueOf(request) + + if isNil(requestStructType, requestValType) { + if !nullable && optional { + return nil, "", nil + } + + return serializeContentType(requestFieldName, SerializationMethodToContentType[serializationMethod], requestValType, tag) + } + + if requestStructType.Kind() == reflect.Pointer { + requestStructType = requestStructType.Elem() + requestValType = requestValType.Elem() + } + + if requestStructType.Kind() != reflect.Struct { + return serializeContentType(requestFieldName, SerializationMethodToContentType[serializationMethod], requestValType, tag) + } + + requestField, ok := requestStructType.FieldByName(requestFieldName) + + if ok { + tag := getRequestTag(requestField) + if tag != nil { + // request object (non-flattened) + requestVal := requestValType.FieldByName(requestFieldName) + if isNil(requestField.Type, requestVal) { + if !nullable && optional { + return nil, "", nil + } + + return serializeContentType(requestFieldName, tag.MediaType, requestVal, string(requestField.Tag)) + } + + return serializeContentType(requestFieldName, tag.MediaType, requestVal, string(requestField.Tag)) + } + } + + // flattened request object + return serializeContentType(requestFieldName, SerializationMethodToContentType[serializationMethod], reflect.ValueOf(request), tag) +} + +func serializeContentType(fieldName string, mediaType string, val reflect.Value, tag string) (*bytes.Buffer, string, error) { + buf := &bytes.Buffer{} + + if isNil(val.Type(), val) { + // TODO: what does a null mean for other content types? Just returning an empty buffer for now + if jsonEncodingRegex.MatchString(mediaType) { + if _, err := buf.Write([]byte("null")); err != nil { + return nil, "", err + } + } + + return buf, mediaType, nil + } + + switch { + case jsonEncodingRegex.MatchString(mediaType): + data, err := MarshalJSON(val.Interface(), reflect.StructTag(tag), true) + if err != nil { + return nil, "", err + } + + if _, err := buf.Write(data); err != nil { + return nil, "", err + } + case multipartEncodingRegex.MatchString(mediaType): + var err error + mediaType, err = encodeMultipartFormData(buf, val.Interface()) + if err != nil { + return nil, "", err + } + case urlEncodedEncodingRegex.MatchString(mediaType): + if err := encodeFormData(fieldName, buf, val.Interface()); err != nil { + return nil, "", err + } + default: + val = reflect.Indirect(val) + + switch { + case val.Type().Kind() == reflect.String: + if _, err := buf.WriteString(valToString(val.Interface())); err != nil { + return nil, "", err + } + case val.Type() == reflect.TypeOf([]byte(nil)): + if _, err := buf.Write(val.Bytes()); err != nil { + return nil, "", err + } + default: + return nil, "", fmt.Errorf("invalid request body type %s for mediaType %s", val.Type(), mediaType) + } + } + + return buf, mediaType, nil +} + +func encodeMultipartFormData(w io.Writer, data interface{}) (string, error) { + requestStructType := reflect.TypeOf(data) + requestValType := reflect.ValueOf(data) + + if requestStructType.Kind() == reflect.Pointer { + requestStructType = requestStructType.Elem() + requestValType = requestValType.Elem() + } + + writer := multipart.NewWriter(w) + + for i := 0; i < requestStructType.NumField(); i++ { + field := requestStructType.Field(i) + fieldType := field.Type + valType := requestValType.Field(i) + + if isNil(fieldType, valType) { + continue + } + + if fieldType.Kind() == reflect.Pointer { + fieldType = fieldType.Elem() + valType = valType.Elem() + } + + tag := parseMultipartFormTag(field) + if tag.File { + if err := encodeMultipartFormDataFile(writer, fieldType, valType); err != nil { + writer.Close() + return "", err + } + } else if tag.JSON { + jw, err := writer.CreateFormField(tag.Name) + if err != nil { + writer.Close() + return "", err + } + d, err := MarshalJSON(valType.Interface(), field.Tag, true) + if err != nil { + writer.Close() + return "", err + } + if _, err := jw.Write(d); err != nil { + writer.Close() + return "", err + } + } else { + switch fieldType.Kind() { + case reflect.Slice, reflect.Array: + values := parseDelimitedArray(true, valType, ",") + for _, v := range values { + if err := writer.WriteField(tag.Name+"[]", v); err != nil { + writer.Close() + return "", err + } + } + default: + if err := writer.WriteField(tag.Name, valToString(valType.Interface())); err != nil { + writer.Close() + return "", err + } + } + } + } + + if err := writer.Close(); err != nil { + return "", err + } + + return writer.FormDataContentType(), nil +} + +func encodeMultipartFormDataFile(w *multipart.Writer, fieldType reflect.Type, valType reflect.Value) error { + if fieldType.Kind() != reflect.Struct { + return fmt.Errorf("invalid type %s for multipart/form-data file", valType.Type()) + } + + var fieldName string + var fileName string + var content []byte + + for i := 0; i < fieldType.NumField(); i++ { + field := fieldType.Field(i) + val := valType.Field(i) + + tag := parseMultipartFormTag(field) + if !tag.Content && tag.Name == "" { + continue + } + + if tag.Content { + content = val.Bytes() + } else { + fieldName = tag.Name + fileName = val.String() + } + } + + if fieldName == "" || fileName == "" || content == nil { + return fmt.Errorf("invalid multipart/form-data file") + } + + fw, err := w.CreateFormFile(fieldName, fileName) + if err != nil { + return err + } + if _, err := fw.Write(content); err != nil { + return err + } + + return nil +} + +func encodeFormData(fieldName string, w io.Writer, data interface{}) error { + requestType := reflect.TypeOf(data) + requestValType := reflect.ValueOf(data) + + if requestType.Kind() == reflect.Pointer { + requestType = requestType.Elem() + requestValType = requestValType.Elem() + } + + dataValues := url.Values{} + + switch requestType.Kind() { + case reflect.Struct: + for i := 0; i < requestType.NumField(); i++ { + field := requestType.Field(i) + fieldType := field.Type + valType := requestValType.Field(i) + + if isNil(fieldType, valType) { + continue + } + + if fieldType.Kind() == reflect.Pointer { + fieldType = fieldType.Elem() + valType = valType.Elem() + } + + tag := parseFormTag(field) + if tag.JSON { + data, err := MarshalJSON(valType.Interface(), field.Tag, true) + if err != nil { + return err + } + dataValues.Set(tag.Name, string(data)) + } else { + switch tag.Style { + // TODO: support other styles + case "form": + values := populateForm(tag.Name, tag.Explode, fieldType, valType, ",", func(sf reflect.StructField) string { + tag := parseFormTag(field) + if tag == nil { + return "" + } + + return tag.Name + }) + for k, v := range values { + for _, vv := range v { + dataValues.Add(k, vv) + } + } + } + } + } + case reflect.Map: + for _, k := range requestValType.MapKeys() { + v := requestValType.MapIndex(k) + dataValues.Set(fmt.Sprintf("%v", k.Interface()), valToString(v.Interface())) + } + case reflect.Slice, reflect.Array: + for i := 0; i < requestValType.Len(); i++ { + v := requestValType.Index(i) + dataValues.Set(fieldName, valToString(v.Interface())) + } + } + + if _, err := w.Write([]byte(dataValues.Encode())); err != nil { + return err + } + + return nil +} + +type requestTag struct { + MediaType string +} + +func getRequestTag(field reflect.StructField) *requestTag { + // example `request:"mediaType=multipart/form-data"` + values := parseStructTag(requestTagKey, field) + if values == nil { + return nil + } + + tag := &requestTag{ + MediaType: "application/octet-stream", + } + + for k, v := range values { + switch k { + case "mediaType": + tag.MediaType = v + } + } + + return tag +} + +type multipartFormTag struct { + File bool + Content bool + JSON bool + Name string +} + +func parseMultipartFormTag(field reflect.StructField) *multipartFormTag { + // example `multipartForm:"name=file"` + values := parseStructTag(multipartFormTagKey, field) + + tag := &multipartFormTag{} + + for k, v := range values { + switch k { + case "file": + tag.File = v == "true" + case "content": + tag.Content = v == "true" + case "name": + tag.Name = v + case "json": + tag.JSON = v == "true" + } + } + + return tag +} + +type formTag struct { + Name string + JSON bool + Style string + Explode bool +} + +func parseFormTag(field reflect.StructField) *formTag { + // example `form:"name=propName,style=spaceDelimited,explode"` + values := parseStructTag(formTagKey, field) + + tag := &formTag{ + Style: "form", + Explode: true, + } + + for k, v := range values { + switch k { + case "name": + tag.Name = v + case "json": + tag.JSON = v == "true" + case "style": + tag.Style = v + case "explode": + tag.Explode = v == "true" + } + } + + return tag +} diff --git a/internal/utils/retries.go b/internal/utils/retries.go new file mode 100644 index 0000000..ff39d0d --- /dev/null +++ b/internal/utils/retries.go @@ -0,0 +1,117 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package utils + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strconv" + "strings" + "time" + + "github.com/cenkalti/backoff/v4" +) + +var errRequestFailed = errors.New("request failed") + +type BackoffStrategy struct { + InitialInterval int + MaxInterval int + Exponent float64 + MaxElapsedTime int +} + +type RetryConfig struct { + Strategy string + Backoff *BackoffStrategy + RetryConnectionErrors bool +} + +type Retries struct { + Config *RetryConfig + StatusCodes []string +} + +func Retry(ctx context.Context, r Retries, action func() (*http.Response, error)) (*http.Response, error) { + switch r.Config.Strategy { + case "backoff": + if r.Config.Backoff == nil { + return action() + } + + config := backoff.NewExponentialBackOff() + config.InitialInterval = time.Duration(r.Config.Backoff.InitialInterval) * time.Millisecond + config.MaxInterval = time.Duration(r.Config.Backoff.MaxInterval) * time.Millisecond + config.Multiplier = r.Config.Backoff.Exponent + config.MaxElapsedTime = time.Duration(r.Config.Backoff.MaxElapsedTime) * time.Millisecond + config.Reset() + + var resp *http.Response + + err := backoff.Retry(func() error { + if resp != nil { + resp.Body.Close() + } + + select { + case <-ctx.Done(): + return backoff.Permanent(ctx.Err()) + default: + } + + res, err := action() + if err != nil { + urlError := new(url.Error) + if errors.As(err, &urlError) { + if (urlError.Temporary() || urlError.Timeout()) && r.Config.RetryConnectionErrors { + return err + } + } + + return backoff.Permanent(err) + } + resp = res + if res == nil { + return fmt.Errorf("no response") + } + + for _, code := range r.StatusCodes { + if strings.Contains(strings.ToUpper(code), "X") { + codeRange, err := strconv.Atoi(code[:1]) + if err != nil { + continue + } + + s := res.StatusCode / 100 + + if s >= codeRange && s < codeRange+1 { + return errRequestFailed + } + } else { + parsedCode, err := strconv.Atoi(code) + if err != nil { + continue + } + + if res.StatusCode == parsedCode { + return errRequestFailed + } + } + } + + resp = res + + return nil + }, config) + if err != nil && !errors.Is(err, errRequestFailed) { + return nil, err + } + + return resp, nil + default: + return action() + } +} diff --git a/internal/utils/security.go b/internal/utils/security.go new file mode 100644 index 0000000..f7abb69 --- /dev/null +++ b/internal/utils/security.go @@ -0,0 +1,274 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package utils + +import ( + "context" + "encoding/base64" + "fmt" + "net/http" + "reflect" + "strings" +) + +const ( + securityTagKey = "security" +) + +type securityTag struct { + Option bool + Scheme bool + Name string + Type string + SubType string +} + +func PopulateSecurity(ctx context.Context, req *http.Request, securitySource func(context.Context) (interface{}, error)) error { + if securitySource == nil { + return nil + } + + security, err := securitySource(ctx) + if err != nil { + return err + } + + headers := make(map[string]string) + queryParams := make(map[string]string) + + securityValType := trueReflectValue(reflect.ValueOf(security)) + securityStructType := securityValType.Type() + + if isNil(securityStructType, securityValType) { + return nil + } + + if securityStructType.Kind() == reflect.Ptr { + securityStructType = securityStructType.Elem() + securityValType = securityValType.Elem() + } + + for i := 0; i < securityStructType.NumField(); i++ { + fieldType := securityStructType.Field(i) + valType := securityValType.Field(i) + + kind := valType.Kind() + + if isNil(fieldType.Type, valType) { + continue + } + + if fieldType.Type.Kind() == reflect.Pointer { + kind = valType.Elem().Kind() + } + + secTag := parseSecurityTag(fieldType) + if secTag != nil { + if secTag.Option { + handleSecurityOption(headers, queryParams, valType.Interface()) + } else if secTag.Scheme { + // Special case for basic auth which could be a flattened struct + if secTag.SubType == "basic" && kind != reflect.Struct { + parseSecurityScheme(headers, queryParams, secTag, security) + } else { + parseSecurityScheme(headers, queryParams, secTag, valType.Interface()) + } + } + } + } + + for key, value := range headers { + req.Header.Add(key, value) + } + + query := req.URL.Query() + for key, value := range queryParams { + query.Add(key, value) + } + req.URL.RawQuery = query.Encode() + + return nil +} + +func handleSecurityOption(headers, queryParams map[string]string, option interface{}) { + optionValType := trueReflectValue(reflect.ValueOf(option)) + optionStructType := optionValType.Type() + + if isNil(optionStructType, optionValType) { + return + } + + for i := 0; i < optionStructType.NumField(); i++ { + fieldType := optionStructType.Field(i) + valType := optionValType.Field(i) + + secTag := parseSecurityTag(fieldType) + if secTag != nil && secTag.Scheme { + parseSecurityScheme(headers, queryParams, secTag, valType.Interface()) + } + } +} + +func parseSecurityScheme(headers, queryParams map[string]string, schemeTag *securityTag, scheme interface{}) { + schemeVal := trueReflectValue(reflect.ValueOf(scheme)) + schemeType := schemeVal.Type() + + if isNil(schemeType, schemeVal) { + return + } + + if schemeType.Kind() == reflect.Struct { + if schemeTag.Type == "http" && schemeTag.SubType == "basic" { + handleBasicAuthScheme(headers, schemeVal.Interface()) + return + } + + for i := 0; i < schemeType.NumField(); i++ { + fieldType := schemeType.Field(i) + valType := schemeVal.Field(i) + + if isNil(fieldType.Type, valType) { + continue + } + + if fieldType.Type.Kind() == reflect.Ptr { + valType = valType.Elem() + } + + secTag := parseSecurityTag(fieldType) + if secTag == nil || secTag.Name == "" { + return + } + + parseSecuritySchemeValue(headers, queryParams, schemeTag, secTag, valType.Interface()) + } + } else { + parseSecuritySchemeValue(headers, queryParams, schemeTag, schemeTag, schemeVal.Interface()) + } +} + +func parseSecuritySchemeValue(headers, queryParams map[string]string, schemeTag *securityTag, secTag *securityTag, val interface{}) { + switch schemeTag.Type { + case "apiKey": + switch schemeTag.SubType { + case "header": + headers[secTag.Name] = valToString(val) + case "query": + queryParams[secTag.Name] = valToString(val) + case "cookie": + headers["Cookie"] = fmt.Sprintf("%s=%s", secTag.Name, valToString(val)) + default: + panic("not supported") + } + case "openIdConnect": + headers[secTag.Name] = prefixBearer(valToString(val)) + case "oauth2": + if schemeTag.SubType != "client_credentials" { + headers[secTag.Name] = prefixBearer(valToString(val)) + } + case "http": + switch schemeTag.SubType { + case "bearer": + headers[secTag.Name] = prefixBearer(valToString(val)) + default: + panic("not supported") + } + default: + panic("not supported") + } +} + +func prefixBearer(authHeaderValue string) string { + if strings.HasPrefix(strings.ToLower(authHeaderValue), "bearer ") { + return authHeaderValue + } + + return fmt.Sprintf("Bearer %s", authHeaderValue) +} + +func handleBasicAuthScheme(headers map[string]string, scheme interface{}) { + schemeStructType := reflect.TypeOf(scheme) + schemeValType := reflect.ValueOf(scheme) + + var username, password string + + for i := 0; i < schemeStructType.NumField(); i++ { + fieldType := schemeStructType.Field(i) + valType := schemeValType.Field(i) + + if fieldType.Type.Kind() == reflect.Ptr { + valType = valType.Elem() + } + + secTag := parseSecurityTag(fieldType) + if secTag == nil || secTag.Name == "" { + continue + } + + switch secTag.Name { + case "username": + username = valType.String() + case "password": + password = valType.String() + } + } + + headers["Authorization"] = fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", username, password)))) +} + +func parseSecurityTag(field reflect.StructField) *securityTag { + tag := field.Tag.Get(securityTagKey) + if tag == "" { + return nil + } + + option := false + scheme := false + name := "" + securityType := "" + securitySubType := "" + + options := strings.Split(tag, ",") + for _, optionConf := range options { + parts := strings.Split(optionConf, "=") + if len(parts) < 1 || len(parts) > 2 { + continue + } + + switch parts[0] { + case "name": + name = parts[1] + case "type": + securityType = parts[1] + case "subtype": + securitySubType = parts[1] + case "option": + option = true + case "scheme": + scheme = true + } + } + + // TODO: validate tag? + + return &securityTag{ + Option: option, + Scheme: scheme, + Name: name, + Type: securityType, + SubType: securitySubType, + } +} + +func trueReflectValue(val reflect.Value) reflect.Value { + kind := val.Type().Kind() + for kind == reflect.Interface || kind == reflect.Ptr { + innerVal := val.Elem() + if !innerVal.IsValid() { + break + } + val = innerVal + kind = val.Type().Kind() + } + return val +} diff --git a/internal/utils/utils.go b/internal/utils/utils.go new file mode 100644 index 0000000..eab3682 --- /dev/null +++ b/internal/utils/utils.go @@ -0,0 +1,230 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package utils + +import ( + "context" + "fmt" + "io" + "math/big" + "reflect" + "regexp" + "strconv" + "strings" + "time" + + "github.com/ericlagergren/decimal" +) + +const ( + queryParamTagKey = "queryParam" + headerParamTagKey = "header" + pathParamTagKey = "pathParam" +) + +var ( + paramRegex = regexp.MustCompile(`({.*?})`) + SerializationMethodToContentType = map[string]string{ + "json": "application/json", + "form": "application/x-www-form-urlencoded", + "multipart": "multipart/form-data", + "raw": "application/octet-stream", + "string": "text/plain", + } +) + +func UnmarshalJsonFromResponseBody(body io.Reader, out interface{}, tag string) error { + data, err := io.ReadAll(body) + if err != nil { + return fmt.Errorf("error reading response body: %w", err) + } + if err := UnmarshalJSON(data, out, reflect.StructTag(tag), true, false); err != nil { + return fmt.Errorf("error unmarshalling json response body: %w", err) + } + + return nil +} + +func ReplaceParameters(stringWithParams string, params map[string]string) string { + if len(params) == 0 { + return stringWithParams + } + + return paramRegex.ReplaceAllStringFunc(stringWithParams, func(match string) string { + match = match[1 : len(match)-1] + return params[match] + }) +} + +func Contains(slice []string, item string) bool { + for _, s := range slice { + if s == item { + return true + } + } + return false +} + +func MatchStatusCodes(expectedCodes []string, statusCode int) bool { + for _, codeStr := range expectedCodes { + code, err := strconv.Atoi(codeStr) + if err == nil { + if code == statusCode { + return true + } + continue + } + + codeRange, err := strconv.Atoi(string(codeStr[0])) + if err != nil { + continue + } + + if statusCode >= (codeRange*100) && statusCode < ((codeRange+1)*100) { + return true + } + } + + return false +} + +func AsSecuritySource(security interface{}) func(context.Context) (interface{}, error) { + return func(context.Context) (interface{}, error) { + return security, nil + } +} + +func parseStructTag(tagKey string, field reflect.StructField) map[string]string { + tag := field.Tag.Get(tagKey) + if tag == "" { + return nil + } + + values := map[string]string{} + + options := strings.Split(tag, ",") + for _, optionConf := range options { + parts := strings.Split(optionConf, "=") + + switch len(parts) { + case 1: + // flag option + parts = append(parts, "true") + case 2: + // key=value option + default: + // invalid option + continue + } + + values[parts[0]] = parts[1] + } + + return values +} + +func parseParamTag(tagKey string, field reflect.StructField, defaultStyle string, defaultExplode bool) *paramTag { + // example `{tagKey}:"style=simple,explode=false,name=apiID"` + values := parseStructTag(tagKey, field) + if values == nil { + return nil + } + + tag := ¶mTag{ + Style: defaultStyle, + Explode: defaultExplode, + ParamName: strings.ToLower(field.Name), + } + + for k, v := range values { + switch k { + case "style": + tag.Style = v + case "explode": + tag.Explode = v == "true" + case "name": + tag.ParamName = v + case "serialization": + tag.Serialization = v + } + } + + return tag +} + +func valToString(val interface{}) string { + switch v := val.(type) { + case time.Time: + return v.Format(time.RFC3339Nano) + case big.Int: + return v.String() + case decimal.Big: + return v.String() + default: + return fmt.Sprintf("%v", v) + } +} + +func populateFromGlobals(fieldType reflect.StructField, valType reflect.Value, paramType string, globals interface{}) (reflect.StructField, reflect.Value, bool) { + if globals == nil { + return fieldType, valType, false + } + + globalsStruct := reflect.TypeOf(globals) + globalsStructVal := reflect.ValueOf(globals) + + globalsField, found := globalsStruct.FieldByName(fieldType.Name) + if !found { + return fieldType, valType, false + } + + if fieldType.Type.Kind() != reflect.Ptr || !valType.IsNil() { + return fieldType, valType, true + } + + globalsVal := globalsStructVal.FieldByName(fieldType.Name) + + if !globalsVal.IsValid() { + return fieldType, valType, false + } + + switch paramType { + case queryParamTagKey: + qpTag := parseQueryParamTag(globalsField) + if qpTag == nil { + return fieldType, valType, false + } + default: + tag := parseParamTag(paramType, fieldType, "simple", false) + if tag == nil { + return fieldType, valType, false + } + } + + return globalsField, globalsVal, true +} + +func isNil(typ reflect.Type, val reflect.Value) bool { + // `reflect.TypeOf(nil) == nil` so calling typ.Kind() will cause a nil pointer + // dereference panic. Catch it and return early. + // https://github.com/golang/go/issues/51649 + // https://github.com/golang/go/issues/54208 + if typ == nil { + return true + } + + if typ.Kind() == reflect.Ptr || typ.Kind() == reflect.Map || typ.Kind() == reflect.Slice || typ.Kind() == reflect.Interface { + return val.IsNil() + } + + return false +} + +func contains(arr []string, str string) bool { + for _, a := range arr { + if a == str { + return true + } + } + return false +} diff --git a/log10.go b/log10.go new file mode 100644 index 0000000..82ab1a3 --- /dev/null +++ b/log10.go @@ -0,0 +1,187 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package log10go + +import ( + "context" + "fmt" + "github.com/log10-io/log10go/internal/globals" + "github.com/log10-io/log10go/internal/hooks" + "github.com/log10-io/log10go/internal/utils" + "github.com/log10-io/log10go/models/components" + "net/http" + "time" +) + +// ServerList contains the list of servers available to the SDK +var ServerList = []string{ + "https://log10.io", +} + +// HTTPClient provides an interface for suplying the SDK with a custom HTTP client +type HTTPClient interface { + Do(req *http.Request) (*http.Response, error) +} + +// String provides a helper function to return a pointer to a string +func String(s string) *string { return &s } + +// Bool provides a helper function to return a pointer to a bool +func Bool(b bool) *bool { return &b } + +// Int provides a helper function to return a pointer to an int +func Int(i int) *int { return &i } + +// Int64 provides a helper function to return a pointer to an int64 +func Int64(i int64) *int64 { return &i } + +// Float32 provides a helper function to return a pointer to a float32 +func Float32(f float32) *float32 { return &f } + +// Float64 provides a helper function to return a pointer to a float64 +func Float64(f float64) *float64 { return &f } + +type sdkConfiguration struct { + Client HTTPClient + Security func(context.Context) (interface{}, error) + ServerURL string + ServerIndex int + Language string + OpenAPIDocVersion string + SDKVersion string + GenVersion string + UserAgent string + Globals globals.Globals + RetryConfig *utils.RetryConfig + Hooks *hooks.Hooks +} + +func (c *sdkConfiguration) GetServerDetails() (string, map[string]string) { + if c.ServerURL != "" { + return c.ServerURL, nil + } + + return ServerList[c.ServerIndex], nil +} + +// Log10 Feedback API Spec: Log10 Feedback API Spec +type Log10 struct { + // Completions + Completions *Completions + // Sessions + Sessions *Sessions + // Feedback + Feedback *Feedback + // FeedbackTasks + FeedbackTasks *FeedbackTasks + + sdkConfiguration sdkConfiguration +} + +type SDKOption func(*Log10) + +// WithServerURL allows the overriding of the default server URL +func WithServerURL(serverURL string) SDKOption { + return func(sdk *Log10) { + sdk.sdkConfiguration.ServerURL = serverURL + } +} + +// WithTemplatedServerURL allows the overriding of the default server URL with a templated URL populated with the provided parameters +func WithTemplatedServerURL(serverURL string, params map[string]string) SDKOption { + return func(sdk *Log10) { + if params != nil { + serverURL = utils.ReplaceParameters(serverURL, params) + } + + sdk.sdkConfiguration.ServerURL = serverURL + } +} + +// WithServerIndex allows the overriding of the default server by index +func WithServerIndex(serverIndex int) SDKOption { + return func(sdk *Log10) { + if serverIndex < 0 || serverIndex >= len(ServerList) { + panic(fmt.Errorf("server index %d out of range", serverIndex)) + } + + sdk.sdkConfiguration.ServerIndex = serverIndex + } +} + +// WithClient allows the overriding of the default HTTP client used by the SDK +func WithClient(client HTTPClient) SDKOption { + return func(sdk *Log10) { + sdk.sdkConfiguration.Client = client + } +} + +// WithSecurity configures the SDK to use the provided security details +func WithSecurity(log10Token string) SDKOption { + return func(sdk *Log10) { + security := components.Security{Log10Token: &log10Token} + sdk.sdkConfiguration.Security = utils.AsSecuritySource(&security) + } +} + +// WithSecuritySource configures the SDK to invoke the Security Source function on each method call to determine authentication +func WithSecuritySource(security func(context.Context) (components.Security, error)) SDKOption { + return func(sdk *Log10) { + sdk.sdkConfiguration.Security = func(ctx context.Context) (interface{}, error) { + return security(ctx) + } + } +} + +// WithXLog10Organization allows setting the XLog10Organization parameter for all supported operations +func WithXLog10Organization(xLog10Organization string) SDKOption { + return func(sdk *Log10) { + sdk.sdkConfiguration.Globals.XLog10Organization = xLog10Organization + } +} + +func WithRetryConfig(retryConfig utils.RetryConfig) SDKOption { + return func(sdk *Log10) { + sdk.sdkConfiguration.RetryConfig = &retryConfig + } +} + +// New creates a new instance of the SDK with the provided options +func New(opts ...SDKOption) *Log10 { + sdk := &Log10{ + sdkConfiguration: sdkConfiguration{ + Language: "go", + OpenAPIDocVersion: "1.0.0", + SDKVersion: "0.0.1", + GenVersion: "2.338.1", + UserAgent: "speakeasy-sdk/go 0.0.1 2.338.1 1.0.0 github.com/log10-io/log10go", + Globals: globals.Globals{}, + Hooks: hooks.New(), + }, + } + for _, opt := range opts { + opt(sdk) + } + + // Use WithClient to override the default client if you would like to customize the timeout + if sdk.sdkConfiguration.Client == nil { + sdk.sdkConfiguration.Client = &http.Client{Timeout: 60 * time.Second} + } + + currentServerURL, _ := sdk.sdkConfiguration.GetServerDetails() + serverURL := currentServerURL + serverURL, sdk.sdkConfiguration.Client = sdk.sdkConfiguration.Hooks.SDKInit(currentServerURL, sdk.sdkConfiguration.Client) + if serverURL != currentServerURL { + sdk.sdkConfiguration.ServerURL = serverURL + } + + sdk.Completions = newCompletions(sdk.sdkConfiguration) + + sdk.Sessions = newSessions(sdk.sdkConfiguration) + + sdk.Feedback = newFeedback(sdk.sdkConfiguration) + + sdk.FeedbackTasks = newFeedbackTasks(sdk.sdkConfiguration) + + return sdk +} diff --git a/models/components/chatcompletionfunctioncalloption.go b/models/components/chatcompletionfunctioncalloption.go new file mode 100644 index 0000000..204c95d --- /dev/null +++ b/models/components/chatcompletionfunctioncalloption.go @@ -0,0 +1,16 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package components + +// ChatCompletionFunctionCallOption - Specifying a particular function via `{"name": "my_function"}` forces the model to call that function. +type ChatCompletionFunctionCallOption struct { + // The name of the function to call. + Name string `json:"name"` +} + +func (o *ChatCompletionFunctionCallOption) GetName() string { + if o == nil { + return "" + } + return o.Name +} diff --git a/models/components/chatcompletionfunctions.go b/models/components/chatcompletionfunctions.go new file mode 100644 index 0000000..3dffdb5 --- /dev/null +++ b/models/components/chatcompletionfunctions.go @@ -0,0 +1,38 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package components + +// ChatCompletionFunctions +// +// Deprecated type: This will be removed in a future release, please migrate away from it as soon as possible. +type ChatCompletionFunctions struct { + // A description of what the function does, used by the model to choose when and how to call the function. + Description *string `json:"description,omitempty"` + // The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64. + Name string `json:"name"` + // The parameters the functions accepts, described as a JSON Schema object. See the [guide](/docs/guides/text-generation/function-calling) for examples, and the [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for documentation about the format. + // + // Omitting `parameters` defines a function with an empty parameter list. + Parameters map[string]any `json:"parameters,omitempty"` +} + +func (o *ChatCompletionFunctions) GetDescription() *string { + if o == nil { + return nil + } + return o.Description +} + +func (o *ChatCompletionFunctions) GetName() string { + if o == nil { + return "" + } + return o.Name +} + +func (o *ChatCompletionFunctions) GetParameters() map[string]any { + if o == nil { + return nil + } + return o.Parameters +} diff --git a/models/components/chatcompletionmessagetoolcall.go b/models/components/chatcompletionmessagetoolcall.go new file mode 100644 index 0000000..91ba092 --- /dev/null +++ b/models/components/chatcompletionmessagetoolcall.go @@ -0,0 +1,84 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package components + +import ( + "encoding/json" + "fmt" +) + +// ChatCompletionMessageToolCallType - The type of the tool. Currently, only `function` is supported. +type ChatCompletionMessageToolCallType string + +const ( + ChatCompletionMessageToolCallTypeFunction ChatCompletionMessageToolCallType = "function" +) + +func (e ChatCompletionMessageToolCallType) ToPointer() *ChatCompletionMessageToolCallType { + return &e +} +func (e *ChatCompletionMessageToolCallType) UnmarshalJSON(data []byte) error { + var v string + if err := json.Unmarshal(data, &v); err != nil { + return err + } + switch v { + case "function": + *e = ChatCompletionMessageToolCallType(v) + return nil + default: + return fmt.Errorf("invalid value for ChatCompletionMessageToolCallType: %v", v) + } +} + +// Function - The function that the model called. +type Function struct { + // The name of the function to call. + Name string `json:"name"` + // The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function. + Arguments string `json:"arguments"` +} + +func (o *Function) GetName() string { + if o == nil { + return "" + } + return o.Name +} + +func (o *Function) GetArguments() string { + if o == nil { + return "" + } + return o.Arguments +} + +type ChatCompletionMessageToolCall struct { + // The ID of the tool call. + ID string `json:"id"` + // The type of the tool. Currently, only `function` is supported. + Type ChatCompletionMessageToolCallType `json:"type"` + // The function that the model called. + Function Function `json:"function"` +} + +func (o *ChatCompletionMessageToolCall) GetID() string { + if o == nil { + return "" + } + return o.ID +} + +func (o *ChatCompletionMessageToolCall) GetType() ChatCompletionMessageToolCallType { + if o == nil { + return ChatCompletionMessageToolCallType("") + } + return o.Type +} + +func (o *ChatCompletionMessageToolCall) GetFunction() Function { + if o == nil { + return Function{} + } + return o.Function +} diff --git a/models/components/chatcompletionnamedtoolchoice.go b/models/components/chatcompletionnamedtoolchoice.go new file mode 100644 index 0000000..df7831b --- /dev/null +++ b/models/components/chatcompletionnamedtoolchoice.go @@ -0,0 +1,65 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package components + +import ( + "encoding/json" + "fmt" +) + +// ChatCompletionNamedToolChoiceType - The type of the tool. Currently, only `function` is supported. +type ChatCompletionNamedToolChoiceType string + +const ( + ChatCompletionNamedToolChoiceTypeFunction ChatCompletionNamedToolChoiceType = "function" +) + +func (e ChatCompletionNamedToolChoiceType) ToPointer() *ChatCompletionNamedToolChoiceType { + return &e +} +func (e *ChatCompletionNamedToolChoiceType) UnmarshalJSON(data []byte) error { + var v string + if err := json.Unmarshal(data, &v); err != nil { + return err + } + switch v { + case "function": + *e = ChatCompletionNamedToolChoiceType(v) + return nil + default: + return fmt.Errorf("invalid value for ChatCompletionNamedToolChoiceType: %v", v) + } +} + +type ChatCompletionNamedToolChoiceFunction struct { + // The name of the function to call. + Name string `json:"name"` +} + +func (o *ChatCompletionNamedToolChoiceFunction) GetName() string { + if o == nil { + return "" + } + return o.Name +} + +// ChatCompletionNamedToolChoice - Specifies a tool the model should use. Use to force the model to call a specific function. +type ChatCompletionNamedToolChoice struct { + // The type of the tool. Currently, only `function` is supported. + Type ChatCompletionNamedToolChoiceType `json:"type"` + Function ChatCompletionNamedToolChoiceFunction `json:"function"` +} + +func (o *ChatCompletionNamedToolChoice) GetType() ChatCompletionNamedToolChoiceType { + if o == nil { + return ChatCompletionNamedToolChoiceType("") + } + return o.Type +} + +func (o *ChatCompletionNamedToolChoice) GetFunction() ChatCompletionNamedToolChoiceFunction { + if o == nil { + return ChatCompletionNamedToolChoiceFunction{} + } + return o.Function +} diff --git a/models/components/chatcompletionrequestassistantmessage.go b/models/components/chatcompletionrequestassistantmessage.go new file mode 100644 index 0000000..edac52d --- /dev/null +++ b/models/components/chatcompletionrequestassistantmessage.go @@ -0,0 +1,107 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package components + +import ( + "encoding/json" + "fmt" +) + +// ChatCompletionRequestAssistantMessageRole - The role of the messages author, in this case `assistant`. +type ChatCompletionRequestAssistantMessageRole string + +const ( + ChatCompletionRequestAssistantMessageRoleAssistant ChatCompletionRequestAssistantMessageRole = "assistant" +) + +func (e ChatCompletionRequestAssistantMessageRole) ToPointer() *ChatCompletionRequestAssistantMessageRole { + return &e +} +func (e *ChatCompletionRequestAssistantMessageRole) UnmarshalJSON(data []byte) error { + var v string + if err := json.Unmarshal(data, &v); err != nil { + return err + } + switch v { + case "assistant": + *e = ChatCompletionRequestAssistantMessageRole(v) + return nil + default: + return fmt.Errorf("invalid value for ChatCompletionRequestAssistantMessageRole: %v", v) + } +} + +// FunctionCall - Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be called, as generated by the model. +// +// Deprecated type: This will be removed in a future release, please migrate away from it as soon as possible. +type FunctionCall struct { + // The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function. + Arguments string `json:"arguments"` + // The name of the function to call. + Name string `json:"name"` +} + +func (o *FunctionCall) GetArguments() string { + if o == nil { + return "" + } + return o.Arguments +} + +func (o *FunctionCall) GetName() string { + if o == nil { + return "" + } + return o.Name +} + +type ChatCompletionRequestAssistantMessage struct { + // The contents of the assistant message. Required unless `tool_calls` or `function_call` is specified. + // + Content *string `json:"content,omitempty"` + // The role of the messages author, in this case `assistant`. + Role ChatCompletionRequestAssistantMessageRole `json:"role"` + // An optional name for the participant. Provides the model information to differentiate between participants of the same role. + Name *string `json:"name,omitempty"` + // The tool calls generated by the model, such as function calls. + ToolCalls []ChatCompletionMessageToolCall `json:"tool_calls,omitempty"` + // Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be called, as generated by the model. + // + // Deprecated field: This will be removed in a future release, please migrate away from it as soon as possible. + FunctionCall *FunctionCall `json:"function_call,omitempty"` +} + +func (o *ChatCompletionRequestAssistantMessage) GetContent() *string { + if o == nil { + return nil + } + return o.Content +} + +func (o *ChatCompletionRequestAssistantMessage) GetRole() ChatCompletionRequestAssistantMessageRole { + if o == nil { + return ChatCompletionRequestAssistantMessageRole("") + } + return o.Role +} + +func (o *ChatCompletionRequestAssistantMessage) GetName() *string { + if o == nil { + return nil + } + return o.Name +} + +func (o *ChatCompletionRequestAssistantMessage) GetToolCalls() []ChatCompletionMessageToolCall { + if o == nil { + return nil + } + return o.ToolCalls +} + +func (o *ChatCompletionRequestAssistantMessage) GetFunctionCall() *FunctionCall { + if o == nil { + return nil + } + return o.FunctionCall +} diff --git a/models/components/chatcompletionrequestfunctionmessage.go b/models/components/chatcompletionrequestfunctionmessage.go new file mode 100644 index 0000000..34ba629 --- /dev/null +++ b/models/components/chatcompletionrequestfunctionmessage.go @@ -0,0 +1,65 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package components + +import ( + "encoding/json" + "fmt" +) + +// ChatCompletionRequestFunctionMessageRole - The role of the messages author, in this case `function`. +type ChatCompletionRequestFunctionMessageRole string + +const ( + ChatCompletionRequestFunctionMessageRoleFunction ChatCompletionRequestFunctionMessageRole = "function" +) + +func (e ChatCompletionRequestFunctionMessageRole) ToPointer() *ChatCompletionRequestFunctionMessageRole { + return &e +} +func (e *ChatCompletionRequestFunctionMessageRole) UnmarshalJSON(data []byte) error { + var v string + if err := json.Unmarshal(data, &v); err != nil { + return err + } + switch v { + case "function": + *e = ChatCompletionRequestFunctionMessageRole(v) + return nil + default: + return fmt.Errorf("invalid value for ChatCompletionRequestFunctionMessageRole: %v", v) + } +} + +// ChatCompletionRequestFunctionMessage +// +// Deprecated type: This will be removed in a future release, please migrate away from it as soon as possible. +type ChatCompletionRequestFunctionMessage struct { + // The role of the messages author, in this case `function`. + Role ChatCompletionRequestFunctionMessageRole `json:"role"` + // The contents of the function message. + Content *string `json:"content"` + // The name of the function to call. + Name string `json:"name"` +} + +func (o *ChatCompletionRequestFunctionMessage) GetRole() ChatCompletionRequestFunctionMessageRole { + if o == nil { + return ChatCompletionRequestFunctionMessageRole("") + } + return o.Role +} + +func (o *ChatCompletionRequestFunctionMessage) GetContent() *string { + if o == nil { + return nil + } + return o.Content +} + +func (o *ChatCompletionRequestFunctionMessage) GetName() string { + if o == nil { + return "" + } + return o.Name +} diff --git a/models/components/chatcompletionrequestmessage.go b/models/components/chatcompletionrequestmessage.go new file mode 100644 index 0000000..7315c6c --- /dev/null +++ b/models/components/chatcompletionrequestmessage.go @@ -0,0 +1,138 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package components + +import ( + "errors" + "fmt" + "github.com/log10-io/log10go/internal/utils" +) + +type ChatCompletionRequestMessageType string + +const ( + ChatCompletionRequestMessageTypeChatCompletionRequestSystemMessage ChatCompletionRequestMessageType = "ChatCompletionRequestSystemMessage" + ChatCompletionRequestMessageTypeChatCompletionRequestUserMessage ChatCompletionRequestMessageType = "ChatCompletionRequestUserMessage" + ChatCompletionRequestMessageTypeChatCompletionRequestAssistantMessage ChatCompletionRequestMessageType = "ChatCompletionRequestAssistantMessage" + ChatCompletionRequestMessageTypeChatCompletionRequestToolMessage ChatCompletionRequestMessageType = "ChatCompletionRequestToolMessage" + ChatCompletionRequestMessageTypeChatCompletionRequestFunctionMessage ChatCompletionRequestMessageType = "ChatCompletionRequestFunctionMessage" +) + +type ChatCompletionRequestMessage struct { + ChatCompletionRequestSystemMessage *ChatCompletionRequestSystemMessage + ChatCompletionRequestUserMessage *ChatCompletionRequestUserMessage + ChatCompletionRequestAssistantMessage *ChatCompletionRequestAssistantMessage + ChatCompletionRequestToolMessage *ChatCompletionRequestToolMessage + ChatCompletionRequestFunctionMessage *ChatCompletionRequestFunctionMessage + + Type ChatCompletionRequestMessageType +} + +func CreateChatCompletionRequestMessageChatCompletionRequestSystemMessage(chatCompletionRequestSystemMessage ChatCompletionRequestSystemMessage) ChatCompletionRequestMessage { + typ := ChatCompletionRequestMessageTypeChatCompletionRequestSystemMessage + + return ChatCompletionRequestMessage{ + ChatCompletionRequestSystemMessage: &chatCompletionRequestSystemMessage, + Type: typ, + } +} + +func CreateChatCompletionRequestMessageChatCompletionRequestUserMessage(chatCompletionRequestUserMessage ChatCompletionRequestUserMessage) ChatCompletionRequestMessage { + typ := ChatCompletionRequestMessageTypeChatCompletionRequestUserMessage + + return ChatCompletionRequestMessage{ + ChatCompletionRequestUserMessage: &chatCompletionRequestUserMessage, + Type: typ, + } +} + +func CreateChatCompletionRequestMessageChatCompletionRequestAssistantMessage(chatCompletionRequestAssistantMessage ChatCompletionRequestAssistantMessage) ChatCompletionRequestMessage { + typ := ChatCompletionRequestMessageTypeChatCompletionRequestAssistantMessage + + return ChatCompletionRequestMessage{ + ChatCompletionRequestAssistantMessage: &chatCompletionRequestAssistantMessage, + Type: typ, + } +} + +func CreateChatCompletionRequestMessageChatCompletionRequestToolMessage(chatCompletionRequestToolMessage ChatCompletionRequestToolMessage) ChatCompletionRequestMessage { + typ := ChatCompletionRequestMessageTypeChatCompletionRequestToolMessage + + return ChatCompletionRequestMessage{ + ChatCompletionRequestToolMessage: &chatCompletionRequestToolMessage, + Type: typ, + } +} + +func CreateChatCompletionRequestMessageChatCompletionRequestFunctionMessage(chatCompletionRequestFunctionMessage ChatCompletionRequestFunctionMessage) ChatCompletionRequestMessage { + typ := ChatCompletionRequestMessageTypeChatCompletionRequestFunctionMessage + + return ChatCompletionRequestMessage{ + ChatCompletionRequestFunctionMessage: &chatCompletionRequestFunctionMessage, + Type: typ, + } +} + +func (u *ChatCompletionRequestMessage) UnmarshalJSON(data []byte) error { + + var chatCompletionRequestSystemMessage ChatCompletionRequestSystemMessage = ChatCompletionRequestSystemMessage{} + if err := utils.UnmarshalJSON(data, &chatCompletionRequestSystemMessage, "", true, true); err == nil { + u.ChatCompletionRequestSystemMessage = &chatCompletionRequestSystemMessage + u.Type = ChatCompletionRequestMessageTypeChatCompletionRequestSystemMessage + return nil + } + + var chatCompletionRequestUserMessage ChatCompletionRequestUserMessage = ChatCompletionRequestUserMessage{} + if err := utils.UnmarshalJSON(data, &chatCompletionRequestUserMessage, "", true, true); err == nil { + u.ChatCompletionRequestUserMessage = &chatCompletionRequestUserMessage + u.Type = ChatCompletionRequestMessageTypeChatCompletionRequestUserMessage + return nil + } + + var chatCompletionRequestToolMessage ChatCompletionRequestToolMessage = ChatCompletionRequestToolMessage{} + if err := utils.UnmarshalJSON(data, &chatCompletionRequestToolMessage, "", true, true); err == nil { + u.ChatCompletionRequestToolMessage = &chatCompletionRequestToolMessage + u.Type = ChatCompletionRequestMessageTypeChatCompletionRequestToolMessage + return nil + } + + var chatCompletionRequestFunctionMessage ChatCompletionRequestFunctionMessage = ChatCompletionRequestFunctionMessage{} + if err := utils.UnmarshalJSON(data, &chatCompletionRequestFunctionMessage, "", true, true); err == nil { + u.ChatCompletionRequestFunctionMessage = &chatCompletionRequestFunctionMessage + u.Type = ChatCompletionRequestMessageTypeChatCompletionRequestFunctionMessage + return nil + } + + var chatCompletionRequestAssistantMessage ChatCompletionRequestAssistantMessage = ChatCompletionRequestAssistantMessage{} + if err := utils.UnmarshalJSON(data, &chatCompletionRequestAssistantMessage, "", true, true); err == nil { + u.ChatCompletionRequestAssistantMessage = &chatCompletionRequestAssistantMessage + u.Type = ChatCompletionRequestMessageTypeChatCompletionRequestAssistantMessage + return nil + } + + return fmt.Errorf("could not unmarshal `%s` into any supported union types for ChatCompletionRequestMessage", string(data)) +} + +func (u ChatCompletionRequestMessage) MarshalJSON() ([]byte, error) { + if u.ChatCompletionRequestSystemMessage != nil { + return utils.MarshalJSON(u.ChatCompletionRequestSystemMessage, "", true) + } + + if u.ChatCompletionRequestUserMessage != nil { + return utils.MarshalJSON(u.ChatCompletionRequestUserMessage, "", true) + } + + if u.ChatCompletionRequestAssistantMessage != nil { + return utils.MarshalJSON(u.ChatCompletionRequestAssistantMessage, "", true) + } + + if u.ChatCompletionRequestToolMessage != nil { + return utils.MarshalJSON(u.ChatCompletionRequestToolMessage, "", true) + } + + if u.ChatCompletionRequestFunctionMessage != nil { + return utils.MarshalJSON(u.ChatCompletionRequestFunctionMessage, "", true) + } + + return nil, errors.New("could not marshal union type ChatCompletionRequestMessage: all fields are null") +} diff --git a/models/components/chatcompletionrequestmessagecontentpart.go b/models/components/chatcompletionrequestmessagecontentpart.go new file mode 100644 index 0000000..1743ae7 --- /dev/null +++ b/models/components/chatcompletionrequestmessagecontentpart.go @@ -0,0 +1,72 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package components + +import ( + "errors" + "fmt" + "github.com/log10-io/log10go/internal/utils" +) + +type ChatCompletionRequestMessageContentPartType string + +const ( + ChatCompletionRequestMessageContentPartTypeChatCompletionRequestMessageContentPartText ChatCompletionRequestMessageContentPartType = "ChatCompletionRequestMessageContentPartText" + ChatCompletionRequestMessageContentPartTypeChatCompletionRequestMessageContentPartImage ChatCompletionRequestMessageContentPartType = "ChatCompletionRequestMessageContentPartImage" +) + +type ChatCompletionRequestMessageContentPart struct { + ChatCompletionRequestMessageContentPartText *ChatCompletionRequestMessageContentPartText + ChatCompletionRequestMessageContentPartImage *ChatCompletionRequestMessageContentPartImage + + Type ChatCompletionRequestMessageContentPartType +} + +func CreateChatCompletionRequestMessageContentPartChatCompletionRequestMessageContentPartText(chatCompletionRequestMessageContentPartText ChatCompletionRequestMessageContentPartText) ChatCompletionRequestMessageContentPart { + typ := ChatCompletionRequestMessageContentPartTypeChatCompletionRequestMessageContentPartText + + return ChatCompletionRequestMessageContentPart{ + ChatCompletionRequestMessageContentPartText: &chatCompletionRequestMessageContentPartText, + Type: typ, + } +} + +func CreateChatCompletionRequestMessageContentPartChatCompletionRequestMessageContentPartImage(chatCompletionRequestMessageContentPartImage ChatCompletionRequestMessageContentPartImage) ChatCompletionRequestMessageContentPart { + typ := ChatCompletionRequestMessageContentPartTypeChatCompletionRequestMessageContentPartImage + + return ChatCompletionRequestMessageContentPart{ + ChatCompletionRequestMessageContentPartImage: &chatCompletionRequestMessageContentPartImage, + Type: typ, + } +} + +func (u *ChatCompletionRequestMessageContentPart) UnmarshalJSON(data []byte) error { + + var chatCompletionRequestMessageContentPartText ChatCompletionRequestMessageContentPartText = ChatCompletionRequestMessageContentPartText{} + if err := utils.UnmarshalJSON(data, &chatCompletionRequestMessageContentPartText, "", true, true); err == nil { + u.ChatCompletionRequestMessageContentPartText = &chatCompletionRequestMessageContentPartText + u.Type = ChatCompletionRequestMessageContentPartTypeChatCompletionRequestMessageContentPartText + return nil + } + + var chatCompletionRequestMessageContentPartImage ChatCompletionRequestMessageContentPartImage = ChatCompletionRequestMessageContentPartImage{} + if err := utils.UnmarshalJSON(data, &chatCompletionRequestMessageContentPartImage, "", true, true); err == nil { + u.ChatCompletionRequestMessageContentPartImage = &chatCompletionRequestMessageContentPartImage + u.Type = ChatCompletionRequestMessageContentPartTypeChatCompletionRequestMessageContentPartImage + return nil + } + + return fmt.Errorf("could not unmarshal `%s` into any supported union types for ChatCompletionRequestMessageContentPart", string(data)) +} + +func (u ChatCompletionRequestMessageContentPart) MarshalJSON() ([]byte, error) { + if u.ChatCompletionRequestMessageContentPartText != nil { + return utils.MarshalJSON(u.ChatCompletionRequestMessageContentPartText, "", true) + } + + if u.ChatCompletionRequestMessageContentPartImage != nil { + return utils.MarshalJSON(u.ChatCompletionRequestMessageContentPartImage, "", true) + } + + return nil, errors.New("could not marshal union type ChatCompletionRequestMessageContentPart: all fields are null") +} diff --git a/models/components/chatcompletionrequestmessagecontentpartimage.go b/models/components/chatcompletionrequestmessagecontentpartimage.go new file mode 100644 index 0000000..67faaf2 --- /dev/null +++ b/models/components/chatcompletionrequestmessagecontentpartimage.go @@ -0,0 +1,115 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package components + +import ( + "encoding/json" + "fmt" + "github.com/log10-io/log10go/internal/utils" +) + +// ChatCompletionRequestMessageContentPartImageType - The type of the content part. +type ChatCompletionRequestMessageContentPartImageType string + +const ( + ChatCompletionRequestMessageContentPartImageTypeImageURL ChatCompletionRequestMessageContentPartImageType = "image_url" +) + +func (e ChatCompletionRequestMessageContentPartImageType) ToPointer() *ChatCompletionRequestMessageContentPartImageType { + return &e +} +func (e *ChatCompletionRequestMessageContentPartImageType) UnmarshalJSON(data []byte) error { + var v string + if err := json.Unmarshal(data, &v); err != nil { + return err + } + switch v { + case "image_url": + *e = ChatCompletionRequestMessageContentPartImageType(v) + return nil + default: + return fmt.Errorf("invalid value for ChatCompletionRequestMessageContentPartImageType: %v", v) + } +} + +// Detail - Specifies the detail level of the image. Learn more in the [Vision guide](/docs/guides/vision/low-or-high-fidelity-image-understanding). +type Detail string + +const ( + DetailAuto Detail = "auto" + DetailLow Detail = "low" + DetailHigh Detail = "high" +) + +func (e Detail) ToPointer() *Detail { + return &e +} +func (e *Detail) UnmarshalJSON(data []byte) error { + var v string + if err := json.Unmarshal(data, &v); err != nil { + return err + } + switch v { + case "auto": + fallthrough + case "low": + fallthrough + case "high": + *e = Detail(v) + return nil + default: + return fmt.Errorf("invalid value for Detail: %v", v) + } +} + +type ImageURL struct { + // Either a URL of the image or the base64 encoded image data. + URL string `json:"url"` + // Specifies the detail level of the image. Learn more in the [Vision guide](/docs/guides/vision/low-or-high-fidelity-image-understanding). + Detail *Detail `default:"auto" json:"detail"` +} + +func (i ImageURL) MarshalJSON() ([]byte, error) { + return utils.MarshalJSON(i, "", false) +} + +func (i *ImageURL) UnmarshalJSON(data []byte) error { + if err := utils.UnmarshalJSON(data, &i, "", false, false); err != nil { + return err + } + return nil +} + +func (o *ImageURL) GetURL() string { + if o == nil { + return "" + } + return o.URL +} + +func (o *ImageURL) GetDetail() *Detail { + if o == nil { + return nil + } + return o.Detail +} + +type ChatCompletionRequestMessageContentPartImage struct { + // The type of the content part. + Type ChatCompletionRequestMessageContentPartImageType `json:"type"` + ImageURL ImageURL `json:"image_url"` +} + +func (o *ChatCompletionRequestMessageContentPartImage) GetType() ChatCompletionRequestMessageContentPartImageType { + if o == nil { + return ChatCompletionRequestMessageContentPartImageType("") + } + return o.Type +} + +func (o *ChatCompletionRequestMessageContentPartImage) GetImageURL() ImageURL { + if o == nil { + return ImageURL{} + } + return o.ImageURL +} diff --git a/models/components/chatcompletionrequestmessagecontentparttext.go b/models/components/chatcompletionrequestmessagecontentparttext.go new file mode 100644 index 0000000..b4e631b --- /dev/null +++ b/models/components/chatcompletionrequestmessagecontentparttext.go @@ -0,0 +1,53 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package components + +import ( + "encoding/json" + "fmt" +) + +// Type - The type of the content part. +type Type string + +const ( + TypeText Type = "text" +) + +func (e Type) ToPointer() *Type { + return &e +} +func (e *Type) UnmarshalJSON(data []byte) error { + var v string + if err := json.Unmarshal(data, &v); err != nil { + return err + } + switch v { + case "text": + *e = Type(v) + return nil + default: + return fmt.Errorf("invalid value for Type: %v", v) + } +} + +type ChatCompletionRequestMessageContentPartText struct { + // The type of the content part. + Type Type `json:"type"` + // The text content. + Text string `json:"text"` +} + +func (o *ChatCompletionRequestMessageContentPartText) GetType() Type { + if o == nil { + return Type("") + } + return o.Type +} + +func (o *ChatCompletionRequestMessageContentPartText) GetText() string { + if o == nil { + return "" + } + return o.Text +} diff --git a/models/components/chatcompletionrequestsystemmessage.go b/models/components/chatcompletionrequestsystemmessage.go new file mode 100644 index 0000000..8a56569 --- /dev/null +++ b/models/components/chatcompletionrequestsystemmessage.go @@ -0,0 +1,62 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package components + +import ( + "encoding/json" + "fmt" +) + +// Role - The role of the messages author, in this case `system`. +type Role string + +const ( + RoleSystem Role = "system" +) + +func (e Role) ToPointer() *Role { + return &e +} +func (e *Role) UnmarshalJSON(data []byte) error { + var v string + if err := json.Unmarshal(data, &v); err != nil { + return err + } + switch v { + case "system": + *e = Role(v) + return nil + default: + return fmt.Errorf("invalid value for Role: %v", v) + } +} + +type ChatCompletionRequestSystemMessage struct { + // The contents of the system message. + Content string `json:"content"` + // The role of the messages author, in this case `system`. + Role Role `json:"role"` + // An optional name for the participant. Provides the model information to differentiate between participants of the same role. + Name *string `json:"name,omitempty"` +} + +func (o *ChatCompletionRequestSystemMessage) GetContent() string { + if o == nil { + return "" + } + return o.Content +} + +func (o *ChatCompletionRequestSystemMessage) GetRole() Role { + if o == nil { + return Role("") + } + return o.Role +} + +func (o *ChatCompletionRequestSystemMessage) GetName() *string { + if o == nil { + return nil + } + return o.Name +} diff --git a/models/components/chatcompletionrequesttoolmessage.go b/models/components/chatcompletionrequesttoolmessage.go new file mode 100644 index 0000000..a68b303 --- /dev/null +++ b/models/components/chatcompletionrequesttoolmessage.go @@ -0,0 +1,62 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package components + +import ( + "encoding/json" + "fmt" +) + +// ChatCompletionRequestToolMessageRole - The role of the messages author, in this case `tool`. +type ChatCompletionRequestToolMessageRole string + +const ( + ChatCompletionRequestToolMessageRoleTool ChatCompletionRequestToolMessageRole = "tool" +) + +func (e ChatCompletionRequestToolMessageRole) ToPointer() *ChatCompletionRequestToolMessageRole { + return &e +} +func (e *ChatCompletionRequestToolMessageRole) UnmarshalJSON(data []byte) error { + var v string + if err := json.Unmarshal(data, &v); err != nil { + return err + } + switch v { + case "tool": + *e = ChatCompletionRequestToolMessageRole(v) + return nil + default: + return fmt.Errorf("invalid value for ChatCompletionRequestToolMessageRole: %v", v) + } +} + +type ChatCompletionRequestToolMessage struct { + // The role of the messages author, in this case `tool`. + Role ChatCompletionRequestToolMessageRole `json:"role"` + // The contents of the tool message. + Content string `json:"content"` + // Tool call that this message is responding to. + ToolCallID string `json:"tool_call_id"` +} + +func (o *ChatCompletionRequestToolMessage) GetRole() ChatCompletionRequestToolMessageRole { + if o == nil { + return ChatCompletionRequestToolMessageRole("") + } + return o.Role +} + +func (o *ChatCompletionRequestToolMessage) GetContent() string { + if o == nil { + return "" + } + return o.Content +} + +func (o *ChatCompletionRequestToolMessage) GetToolCallID() string { + if o == nil { + return "" + } + return o.ToolCallID +} diff --git a/models/components/chatcompletionrequestusermessage.go b/models/components/chatcompletionrequestusermessage.go new file mode 100644 index 0000000..a5eb19c --- /dev/null +++ b/models/components/chatcompletionrequestusermessage.go @@ -0,0 +1,129 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package components + +import ( + "encoding/json" + "errors" + "fmt" + "github.com/log10-io/log10go/internal/utils" +) + +type ContentType string + +const ( + ContentTypeStr ContentType = "str" + ContentTypeArrayOfChatCompletionRequestMessageContentPart ContentType = "arrayOfChatCompletionRequestMessageContentPart" +) + +// Content - The contents of the user message. +type Content struct { + Str *string + ArrayOfChatCompletionRequestMessageContentPart []ChatCompletionRequestMessageContentPart + + Type ContentType +} + +func CreateContentStr(str string) Content { + typ := ContentTypeStr + + return Content{ + Str: &str, + Type: typ, + } +} + +func CreateContentArrayOfChatCompletionRequestMessageContentPart(arrayOfChatCompletionRequestMessageContentPart []ChatCompletionRequestMessageContentPart) Content { + typ := ContentTypeArrayOfChatCompletionRequestMessageContentPart + + return Content{ + ArrayOfChatCompletionRequestMessageContentPart: arrayOfChatCompletionRequestMessageContentPart, + Type: typ, + } +} + +func (u *Content) UnmarshalJSON(data []byte) error { + + var str string = "" + if err := utils.UnmarshalJSON(data, &str, "", true, true); err == nil { + u.Str = &str + u.Type = ContentTypeStr + return nil + } + + var arrayOfChatCompletionRequestMessageContentPart []ChatCompletionRequestMessageContentPart = []ChatCompletionRequestMessageContentPart{} + if err := utils.UnmarshalJSON(data, &arrayOfChatCompletionRequestMessageContentPart, "", true, true); err == nil { + u.ArrayOfChatCompletionRequestMessageContentPart = arrayOfChatCompletionRequestMessageContentPart + u.Type = ContentTypeArrayOfChatCompletionRequestMessageContentPart + return nil + } + + return fmt.Errorf("could not unmarshal `%s` into any supported union types for Content", string(data)) +} + +func (u Content) MarshalJSON() ([]byte, error) { + if u.Str != nil { + return utils.MarshalJSON(u.Str, "", true) + } + + if u.ArrayOfChatCompletionRequestMessageContentPart != nil { + return utils.MarshalJSON(u.ArrayOfChatCompletionRequestMessageContentPart, "", true) + } + + return nil, errors.New("could not marshal union type Content: all fields are null") +} + +// ChatCompletionRequestUserMessageRole - The role of the messages author, in this case `user`. +type ChatCompletionRequestUserMessageRole string + +const ( + ChatCompletionRequestUserMessageRoleUser ChatCompletionRequestUserMessageRole = "user" +) + +func (e ChatCompletionRequestUserMessageRole) ToPointer() *ChatCompletionRequestUserMessageRole { + return &e +} +func (e *ChatCompletionRequestUserMessageRole) UnmarshalJSON(data []byte) error { + var v string + if err := json.Unmarshal(data, &v); err != nil { + return err + } + switch v { + case "user": + *e = ChatCompletionRequestUserMessageRole(v) + return nil + default: + return fmt.Errorf("invalid value for ChatCompletionRequestUserMessageRole: %v", v) + } +} + +type ChatCompletionRequestUserMessage struct { + // The contents of the user message. + // + Content Content `json:"content"` + // The role of the messages author, in this case `user`. + Role ChatCompletionRequestUserMessageRole `json:"role"` + // An optional name for the participant. Provides the model information to differentiate between participants of the same role. + Name *string `json:"name,omitempty"` +} + +func (o *ChatCompletionRequestUserMessage) GetContent() Content { + if o == nil { + return Content{} + } + return o.Content +} + +func (o *ChatCompletionRequestUserMessage) GetRole() ChatCompletionRequestUserMessageRole { + if o == nil { + return ChatCompletionRequestUserMessageRole("") + } + return o.Role +} + +func (o *ChatCompletionRequestUserMessage) GetName() *string { + if o == nil { + return nil + } + return o.Name +} diff --git a/models/components/chatcompletionresponsemessage.go b/models/components/chatcompletionresponsemessage.go new file mode 100644 index 0000000..97a74b0 --- /dev/null +++ b/models/components/chatcompletionresponsemessage.go @@ -0,0 +1,98 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package components + +import ( + "encoding/json" + "fmt" +) + +// ChatCompletionResponseMessageRole - The role of the author of this message. +type ChatCompletionResponseMessageRole string + +const ( + ChatCompletionResponseMessageRoleAssistant ChatCompletionResponseMessageRole = "assistant" +) + +func (e ChatCompletionResponseMessageRole) ToPointer() *ChatCompletionResponseMessageRole { + return &e +} +func (e *ChatCompletionResponseMessageRole) UnmarshalJSON(data []byte) error { + var v string + if err := json.Unmarshal(data, &v); err != nil { + return err + } + switch v { + case "assistant": + *e = ChatCompletionResponseMessageRole(v) + return nil + default: + return fmt.Errorf("invalid value for ChatCompletionResponseMessageRole: %v", v) + } +} + +// ChatCompletionResponseMessageFunctionCall - Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be called, as generated by the model. +// +// Deprecated type: This will be removed in a future release, please migrate away from it as soon as possible. +type ChatCompletionResponseMessageFunctionCall struct { + // The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function. + Arguments string `json:"arguments"` + // The name of the function to call. + Name string `json:"name"` +} + +func (o *ChatCompletionResponseMessageFunctionCall) GetArguments() string { + if o == nil { + return "" + } + return o.Arguments +} + +func (o *ChatCompletionResponseMessageFunctionCall) GetName() string { + if o == nil { + return "" + } + return o.Name +} + +// ChatCompletionResponseMessage - A chat completion message generated by the model. +type ChatCompletionResponseMessage struct { + // The contents of the message. + Content *string `json:"content"` + // The tool calls generated by the model, such as function calls. + ToolCalls []ChatCompletionMessageToolCall `json:"tool_calls,omitempty"` + // The role of the author of this message. + Role ChatCompletionResponseMessageRole `json:"role"` + // Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be called, as generated by the model. + // + // Deprecated field: This will be removed in a future release, please migrate away from it as soon as possible. + FunctionCall *ChatCompletionResponseMessageFunctionCall `json:"function_call,omitempty"` +} + +func (o *ChatCompletionResponseMessage) GetContent() *string { + if o == nil { + return nil + } + return o.Content +} + +func (o *ChatCompletionResponseMessage) GetToolCalls() []ChatCompletionMessageToolCall { + if o == nil { + return nil + } + return o.ToolCalls +} + +func (o *ChatCompletionResponseMessage) GetRole() ChatCompletionResponseMessageRole { + if o == nil { + return ChatCompletionResponseMessageRole("") + } + return o.Role +} + +func (o *ChatCompletionResponseMessage) GetFunctionCall() *ChatCompletionResponseMessageFunctionCall { + if o == nil { + return nil + } + return o.FunctionCall +} diff --git a/models/components/chatcompletionstreamoptions.go b/models/components/chatcompletionstreamoptions.go new file mode 100644 index 0000000..4dfdecd --- /dev/null +++ b/models/components/chatcompletionstreamoptions.go @@ -0,0 +1,17 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package components + +// ChatCompletionStreamOptions - Options for streaming response. Only set this when you set `stream: true`. +type ChatCompletionStreamOptions struct { + // If set, an additional chunk will be streamed before the `data: [DONE]` message. The `usage` field on this chunk shows the token usage statistics for the entire request, and the `choices` field will always be an empty array. All other chunks will also include a `usage` field, but with a null value. + // + IncludeUsage *bool `json:"include_usage,omitempty"` +} + +func (o *ChatCompletionStreamOptions) GetIncludeUsage() *bool { + if o == nil { + return nil + } + return o.IncludeUsage +} diff --git a/models/components/chatcompletiontokenlogprob.go b/models/components/chatcompletiontokenlogprob.go new file mode 100644 index 0000000..c6b244c --- /dev/null +++ b/models/components/chatcompletiontokenlogprob.go @@ -0,0 +1,72 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package components + +type TopLogprobs struct { + // The token. + Token string `json:"token"` + // The log probability of this token, if it is within the top 20 most likely tokens. Otherwise, the value `-9999.0` is used to signify that the token is very unlikely. + Logprob float64 `json:"logprob"` + // A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and their byte representations must be combined to generate the correct text representation. Can be `null` if there is no bytes representation for the token. + Bytes []int64 `json:"bytes"` +} + +func (o *TopLogprobs) GetToken() string { + if o == nil { + return "" + } + return o.Token +} + +func (o *TopLogprobs) GetLogprob() float64 { + if o == nil { + return 0.0 + } + return o.Logprob +} + +func (o *TopLogprobs) GetBytes() []int64 { + if o == nil { + return nil + } + return o.Bytes +} + +type ChatCompletionTokenLogprob struct { + // The token. + Token string `json:"token"` + // The log probability of this token, if it is within the top 20 most likely tokens. Otherwise, the value `-9999.0` is used to signify that the token is very unlikely. + Logprob float64 `json:"logprob"` + // A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and their byte representations must be combined to generate the correct text representation. Can be `null` if there is no bytes representation for the token. + Bytes []int64 `json:"bytes"` + // List of the most likely tokens and their log probability, at this token position. In rare cases, there may be fewer than the number of requested `top_logprobs` returned. + TopLogprobs []TopLogprobs `json:"top_logprobs"` +} + +func (o *ChatCompletionTokenLogprob) GetToken() string { + if o == nil { + return "" + } + return o.Token +} + +func (o *ChatCompletionTokenLogprob) GetLogprob() float64 { + if o == nil { + return 0.0 + } + return o.Logprob +} + +func (o *ChatCompletionTokenLogprob) GetBytes() []int64 { + if o == nil { + return nil + } + return o.Bytes +} + +func (o *ChatCompletionTokenLogprob) GetTopLogprobs() []TopLogprobs { + if o == nil { + return []TopLogprobs{} + } + return o.TopLogprobs +} diff --git a/models/components/chatcompletiontool.go b/models/components/chatcompletiontool.go new file mode 100644 index 0000000..73ed115 --- /dev/null +++ b/models/components/chatcompletiontool.go @@ -0,0 +1,52 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package components + +import ( + "encoding/json" + "fmt" +) + +// ChatCompletionToolType - The type of the tool. Currently, only `function` is supported. +type ChatCompletionToolType string + +const ( + ChatCompletionToolTypeFunction ChatCompletionToolType = "function" +) + +func (e ChatCompletionToolType) ToPointer() *ChatCompletionToolType { + return &e +} +func (e *ChatCompletionToolType) UnmarshalJSON(data []byte) error { + var v string + if err := json.Unmarshal(data, &v); err != nil { + return err + } + switch v { + case "function": + *e = ChatCompletionToolType(v) + return nil + default: + return fmt.Errorf("invalid value for ChatCompletionToolType: %v", v) + } +} + +type ChatCompletionTool struct { + // The type of the tool. Currently, only `function` is supported. + Type ChatCompletionToolType `json:"type"` + Function FunctionObject `json:"function"` +} + +func (o *ChatCompletionTool) GetType() ChatCompletionToolType { + if o == nil { + return ChatCompletionToolType("") + } + return o.Type +} + +func (o *ChatCompletionTool) GetFunction() FunctionObject { + if o == nil { + return FunctionObject{} + } + return o.Function +} diff --git a/models/components/chatcompletiontoolchoiceoption.go b/models/components/chatcompletiontoolchoiceoption.go new file mode 100644 index 0000000..dca2eee --- /dev/null +++ b/models/components/chatcompletiontoolchoiceoption.go @@ -0,0 +1,110 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package components + +import ( + "encoding/json" + "errors" + "fmt" + "github.com/log10-io/log10go/internal/utils" +) + +// ChatCompletionToolChoiceOption1 - `none` means the model will not call any tool and instead generates a message. `auto` means the model can pick between generating a message or calling one or more tools. `required` means the model must call one or more tools. +type ChatCompletionToolChoiceOption1 string + +const ( + ChatCompletionToolChoiceOption1None ChatCompletionToolChoiceOption1 = "none" + ChatCompletionToolChoiceOption1Auto ChatCompletionToolChoiceOption1 = "auto" + ChatCompletionToolChoiceOption1Required ChatCompletionToolChoiceOption1 = "required" +) + +func (e ChatCompletionToolChoiceOption1) ToPointer() *ChatCompletionToolChoiceOption1 { + return &e +} +func (e *ChatCompletionToolChoiceOption1) UnmarshalJSON(data []byte) error { + var v string + if err := json.Unmarshal(data, &v); err != nil { + return err + } + switch v { + case "none": + fallthrough + case "auto": + fallthrough + case "required": + *e = ChatCompletionToolChoiceOption1(v) + return nil + default: + return fmt.Errorf("invalid value for ChatCompletionToolChoiceOption1: %v", v) + } +} + +type ChatCompletionToolChoiceOptionType string + +const ( + ChatCompletionToolChoiceOptionTypeChatCompletionToolChoiceOption1 ChatCompletionToolChoiceOptionType = "ChatCompletionToolChoiceOption_1" + ChatCompletionToolChoiceOptionTypeChatCompletionNamedToolChoice ChatCompletionToolChoiceOptionType = "ChatCompletionNamedToolChoice" +) + +// ChatCompletionToolChoiceOption - Controls which (if any) tool is called by the model. +// `none` means the model will not call any tool and instead generates a message. +// `auto` means the model can pick between generating a message or calling one or more tools. +// `required` means the model must call one or more tools. +// Specifying a particular tool via `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. +// +// `none` is the default when no tools are present. `auto` is the default if tools are present. +type ChatCompletionToolChoiceOption struct { + ChatCompletionToolChoiceOption1 *ChatCompletionToolChoiceOption1 + ChatCompletionNamedToolChoice *ChatCompletionNamedToolChoice + + Type ChatCompletionToolChoiceOptionType +} + +func CreateChatCompletionToolChoiceOptionChatCompletionToolChoiceOption1(chatCompletionToolChoiceOption1 ChatCompletionToolChoiceOption1) ChatCompletionToolChoiceOption { + typ := ChatCompletionToolChoiceOptionTypeChatCompletionToolChoiceOption1 + + return ChatCompletionToolChoiceOption{ + ChatCompletionToolChoiceOption1: &chatCompletionToolChoiceOption1, + Type: typ, + } +} + +func CreateChatCompletionToolChoiceOptionChatCompletionNamedToolChoice(chatCompletionNamedToolChoice ChatCompletionNamedToolChoice) ChatCompletionToolChoiceOption { + typ := ChatCompletionToolChoiceOptionTypeChatCompletionNamedToolChoice + + return ChatCompletionToolChoiceOption{ + ChatCompletionNamedToolChoice: &chatCompletionNamedToolChoice, + Type: typ, + } +} + +func (u *ChatCompletionToolChoiceOption) UnmarshalJSON(data []byte) error { + + var chatCompletionNamedToolChoice ChatCompletionNamedToolChoice = ChatCompletionNamedToolChoice{} + if err := utils.UnmarshalJSON(data, &chatCompletionNamedToolChoice, "", true, true); err == nil { + u.ChatCompletionNamedToolChoice = &chatCompletionNamedToolChoice + u.Type = ChatCompletionToolChoiceOptionTypeChatCompletionNamedToolChoice + return nil + } + + var chatCompletionToolChoiceOption1 ChatCompletionToolChoiceOption1 = ChatCompletionToolChoiceOption1("") + if err := utils.UnmarshalJSON(data, &chatCompletionToolChoiceOption1, "", true, true); err == nil { + u.ChatCompletionToolChoiceOption1 = &chatCompletionToolChoiceOption1 + u.Type = ChatCompletionToolChoiceOptionTypeChatCompletionToolChoiceOption1 + return nil + } + + return fmt.Errorf("could not unmarshal `%s` into any supported union types for ChatCompletionToolChoiceOption", string(data)) +} + +func (u ChatCompletionToolChoiceOption) MarshalJSON() ([]byte, error) { + if u.ChatCompletionToolChoiceOption1 != nil { + return utils.MarshalJSON(u.ChatCompletionToolChoiceOption1, "", true) + } + + if u.ChatCompletionNamedToolChoice != nil { + return utils.MarshalJSON(u.ChatCompletionNamedToolChoice, "", true) + } + + return nil, errors.New("could not marshal union type ChatCompletionToolChoiceOption: all fields are null") +} diff --git a/models/components/completion.go b/models/components/completion.go new file mode 100644 index 0000000..24c27f4 --- /dev/null +++ b/models/components/completion.go @@ -0,0 +1,214 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package components + +import ( + "encoding/json" + "fmt" +) + +// Kind - The kind of completion i.e. chat messages or prompt +type Kind string + +const ( + KindChat Kind = "chat" + KindPrompt Kind = "prompt" +) + +func (e Kind) ToPointer() *Kind { + return &e +} +func (e *Kind) UnmarshalJSON(data []byte) error { + var v string + if err := json.Unmarshal(data, &v); err != nil { + return err + } + switch v { + case "chat": + fallthrough + case "prompt": + *e = Kind(v) + return nil + default: + return fmt.Errorf("invalid value for Kind: %v", v) + } +} + +// Status - The status of this completion. +type Status string + +const ( + StatusStarted Status = "started" + StatusFinished Status = "finished" + StatusFailed Status = "failed" +) + +func (e Status) ToPointer() *Status { + return &e +} +func (e *Status) UnmarshalJSON(data []byte) error { + var v string + if err := json.Unmarshal(data, &v); err != nil { + return err + } + switch v { + case "started": + fallthrough + case "finished": + fallthrough + case "failed": + *e = Status(v) + return nil + default: + return fmt.Errorf("invalid value for Status: %v", v) + } +} + +type Stacktrace struct { + // The file associated with this stacktrace. + File string `json:"file"` + // The line associated with this stacktrace. + Line string `json:"line"` + // The line number associated with this stacktrace. + Lineno float64 `json:"lineno"` + // The function or module associated with this stacktrace. + Name string `json:"name"` +} + +func (o *Stacktrace) GetFile() string { + if o == nil { + return "" + } + return o.File +} + +func (o *Stacktrace) GetLine() string { + if o == nil { + return "" + } + return o.Line +} + +func (o *Stacktrace) GetLineno() float64 { + if o == nil { + return 0.0 + } + return o.Lineno +} + +func (o *Stacktrace) GetName() string { + if o == nil { + return "" + } + return o.Name +} + +type Completion struct { + // The unique identifier for this task. + ID *string `json:"id,omitempty"` + // The unique identifier for the organization. + OrganizationID string `json:"organization_id"` + // The kind of completion i.e. chat messages or prompt + Kind *Kind `json:"kind,omitempty"` + // The status of this completion. + Status *Status `json:"status,omitempty"` + // The tags for this completion. + Tags []string `json:"tags,omitempty"` + Request *CreateChatCompletionRequest `json:"request,omitempty"` + // Represents a chat completion response returned by model, based on the provided input. + Response *CreateChatCompletionResponse `json:"response,omitempty"` + // The stacktrace for this completion. + Stacktrace []Stacktrace `json:"stacktrace,omitempty"` + // The session id for this completion. + SessionID *string `json:"session_id,omitempty"` + // The duration of this completion in seconds. + Duration *float64 `json:"duration,omitempty"` + // The failure kind of this completion. + FailureKind *string `json:"failure_kind,omitempty"` + // The failure reason of this completion. + FailureReason *string `json:"failure_reason,omitempty"` +} + +func (o *Completion) GetID() *string { + if o == nil { + return nil + } + return o.ID +} + +func (o *Completion) GetOrganizationID() string { + if o == nil { + return "" + } + return o.OrganizationID +} + +func (o *Completion) GetKind() *Kind { + if o == nil { + return nil + } + return o.Kind +} + +func (o *Completion) GetStatus() *Status { + if o == nil { + return nil + } + return o.Status +} + +func (o *Completion) GetTags() []string { + if o == nil { + return nil + } + return o.Tags +} + +func (o *Completion) GetRequest() *CreateChatCompletionRequest { + if o == nil { + return nil + } + return o.Request +} + +func (o *Completion) GetResponse() *CreateChatCompletionResponse { + if o == nil { + return nil + } + return o.Response +} + +func (o *Completion) GetStacktrace() []Stacktrace { + if o == nil { + return nil + } + return o.Stacktrace +} + +func (o *Completion) GetSessionID() *string { + if o == nil { + return nil + } + return o.SessionID +} + +func (o *Completion) GetDuration() *float64 { + if o == nil { + return nil + } + return o.Duration +} + +func (o *Completion) GetFailureKind() *string { + if o == nil { + return nil + } + return o.FailureKind +} + +func (o *Completion) GetFailureReason() *string { + if o == nil { + return nil + } + return o.FailureReason +} diff --git a/models/components/completionusage.go b/models/components/completionusage.go new file mode 100644 index 0000000..26c1454 --- /dev/null +++ b/models/components/completionusage.go @@ -0,0 +1,34 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package components + +// CompletionUsage - Usage statistics for the completion request. +type CompletionUsage struct { + // Number of tokens in the generated completion. + CompletionTokens int64 `json:"completion_tokens"` + // Number of tokens in the prompt. + PromptTokens int64 `json:"prompt_tokens"` + // Total number of tokens used in the request (prompt + completion). + TotalTokens int64 `json:"total_tokens"` +} + +func (o *CompletionUsage) GetCompletionTokens() int64 { + if o == nil { + return 0 + } + return o.CompletionTokens +} + +func (o *CompletionUsage) GetPromptTokens() int64 { + if o == nil { + return 0 + } + return o.PromptTokens +} + +func (o *CompletionUsage) GetTotalTokens() int64 { + if o == nil { + return 0 + } + return o.TotalTokens +} diff --git a/models/components/createchatcompletionrequest.go b/models/components/createchatcompletionrequest.go new file mode 100644 index 0000000..200e6ad --- /dev/null +++ b/models/components/createchatcompletionrequest.go @@ -0,0 +1,626 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package components + +import ( + "encoding/json" + "errors" + "fmt" + "github.com/log10-io/log10go/internal/utils" +) + +type Two string + +const ( + TwoGpt4Turbo Two = "gpt-4-turbo" + TwoGpt4Turbo20240409 Two = "gpt-4-turbo-2024-04-09" + TwoGpt40125Preview Two = "gpt-4-0125-preview" + TwoGpt4TurboPreview Two = "gpt-4-turbo-preview" + TwoGpt41106Preview Two = "gpt-4-1106-preview" + TwoGpt4VisionPreview Two = "gpt-4-vision-preview" + TwoGpt4 Two = "gpt-4" + TwoGpt40314 Two = "gpt-4-0314" + TwoGpt40613 Two = "gpt-4-0613" + TwoGpt432k Two = "gpt-4-32k" + TwoGpt432k0314 Two = "gpt-4-32k-0314" + TwoGpt432k0613 Two = "gpt-4-32k-0613" + TwoGpt35Turbo Two = "gpt-3.5-turbo" + TwoGpt35Turbo16k Two = "gpt-3.5-turbo-16k" + TwoGpt35Turbo0301 Two = "gpt-3.5-turbo-0301" + TwoGpt35Turbo0613 Two = "gpt-3.5-turbo-0613" + TwoGpt35Turbo1106 Two = "gpt-3.5-turbo-1106" + TwoGpt35Turbo0125 Two = "gpt-3.5-turbo-0125" + TwoGpt35Turbo16k0613 Two = "gpt-3.5-turbo-16k-0613" +) + +func (e Two) ToPointer() *Two { + return &e +} +func (e *Two) UnmarshalJSON(data []byte) error { + var v string + if err := json.Unmarshal(data, &v); err != nil { + return err + } + switch v { + case "gpt-4-turbo": + fallthrough + case "gpt-4-turbo-2024-04-09": + fallthrough + case "gpt-4-0125-preview": + fallthrough + case "gpt-4-turbo-preview": + fallthrough + case "gpt-4-1106-preview": + fallthrough + case "gpt-4-vision-preview": + fallthrough + case "gpt-4": + fallthrough + case "gpt-4-0314": + fallthrough + case "gpt-4-0613": + fallthrough + case "gpt-4-32k": + fallthrough + case "gpt-4-32k-0314": + fallthrough + case "gpt-4-32k-0613": + fallthrough + case "gpt-3.5-turbo": + fallthrough + case "gpt-3.5-turbo-16k": + fallthrough + case "gpt-3.5-turbo-0301": + fallthrough + case "gpt-3.5-turbo-0613": + fallthrough + case "gpt-3.5-turbo-1106": + fallthrough + case "gpt-3.5-turbo-0125": + fallthrough + case "gpt-3.5-turbo-16k-0613": + *e = Two(v) + return nil + default: + return fmt.Errorf("invalid value for Two: %v", v) + } +} + +type ModelType string + +const ( + ModelTypeStr ModelType = "str" + ModelTypeTwo ModelType = "2" +) + +// Model - ID of the model to use. See the [model endpoint compatibility](/docs/models/model-endpoint-compatibility) table for details on which models work with the Chat API. +type Model struct { + Str *string + Two *Two + + Type ModelType +} + +func CreateModelStr(str string) Model { + typ := ModelTypeStr + + return Model{ + Str: &str, + Type: typ, + } +} + +func CreateModelTwo(two Two) Model { + typ := ModelTypeTwo + + return Model{ + Two: &two, + Type: typ, + } +} + +func (u *Model) UnmarshalJSON(data []byte) error { + + var str string = "" + if err := utils.UnmarshalJSON(data, &str, "", true, true); err == nil { + u.Str = &str + u.Type = ModelTypeStr + return nil + } + + var two Two = Two("") + if err := utils.UnmarshalJSON(data, &two, "", true, true); err == nil { + u.Two = &two + u.Type = ModelTypeTwo + return nil + } + + return fmt.Errorf("could not unmarshal `%s` into any supported union types for Model", string(data)) +} + +func (u Model) MarshalJSON() ([]byte, error) { + if u.Str != nil { + return utils.MarshalJSON(u.Str, "", true) + } + + if u.Two != nil { + return utils.MarshalJSON(u.Two, "", true) + } + + return nil, errors.New("could not marshal union type Model: all fields are null") +} + +// CreateChatCompletionRequestType - Must be one of `text` or `json_object`. +type CreateChatCompletionRequestType string + +const ( + CreateChatCompletionRequestTypeText CreateChatCompletionRequestType = "text" + CreateChatCompletionRequestTypeJSONObject CreateChatCompletionRequestType = "json_object" +) + +func (e CreateChatCompletionRequestType) ToPointer() *CreateChatCompletionRequestType { + return &e +} +func (e *CreateChatCompletionRequestType) UnmarshalJSON(data []byte) error { + var v string + if err := json.Unmarshal(data, &v); err != nil { + return err + } + switch v { + case "text": + fallthrough + case "json_object": + *e = CreateChatCompletionRequestType(v) + return nil + default: + return fmt.Errorf("invalid value for CreateChatCompletionRequestType: %v", v) + } +} + +// ResponseFormat - An object specifying the format that the model must output. Compatible with [GPT-4 Turbo](/docs/models/gpt-4-and-gpt-4-turbo) and all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. +// +// Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. +// +// **Important:** when using JSON mode, you **must** also instruct the model to produce JSON yourself via a system or user message. Without this, the model may generate an unending stream of whitespace until the generation reaches the token limit, resulting in a long-running and seemingly "stuck" request. Also note that the message content may be partially cut off if `finish_reason="length"`, which indicates the generation exceeded `max_tokens` or the conversation exceeded the max context length. +type ResponseFormat struct { + // Must be one of `text` or `json_object`. + Type *CreateChatCompletionRequestType `default:"text" json:"type"` +} + +func (r ResponseFormat) MarshalJSON() ([]byte, error) { + return utils.MarshalJSON(r, "", false) +} + +func (r *ResponseFormat) UnmarshalJSON(data []byte) error { + if err := utils.UnmarshalJSON(data, &r, "", false, false); err != nil { + return err + } + return nil +} + +func (o *ResponseFormat) GetType() *CreateChatCompletionRequestType { + if o == nil { + return nil + } + return o.Type +} + +type StopType string + +const ( + StopTypeStr StopType = "str" + StopTypeArrayOfStr StopType = "arrayOfStr" +) + +// Stop - Up to 4 sequences where the API will stop generating further tokens. +type Stop struct { + Str *string + ArrayOfStr []string + + Type StopType +} + +func CreateStopStr(str string) Stop { + typ := StopTypeStr + + return Stop{ + Str: &str, + Type: typ, + } +} + +func CreateStopArrayOfStr(arrayOfStr []string) Stop { + typ := StopTypeArrayOfStr + + return Stop{ + ArrayOfStr: arrayOfStr, + Type: typ, + } +} + +func (u *Stop) UnmarshalJSON(data []byte) error { + + var str string = "" + if err := utils.UnmarshalJSON(data, &str, "", true, true); err == nil { + u.Str = &str + u.Type = StopTypeStr + return nil + } + + var arrayOfStr []string = []string{} + if err := utils.UnmarshalJSON(data, &arrayOfStr, "", true, true); err == nil { + u.ArrayOfStr = arrayOfStr + u.Type = StopTypeArrayOfStr + return nil + } + + return fmt.Errorf("could not unmarshal `%s` into any supported union types for Stop", string(data)) +} + +func (u Stop) MarshalJSON() ([]byte, error) { + if u.Str != nil { + return utils.MarshalJSON(u.Str, "", true) + } + + if u.ArrayOfStr != nil { + return utils.MarshalJSON(u.ArrayOfStr, "", true) + } + + return nil, errors.New("could not marshal union type Stop: all fields are null") +} + +// One - `none` means the model will not call a function and instead generates a message. `auto` means the model can pick between generating a message or calling a function. +type One string + +const ( + OneNone One = "none" + OneAuto One = "auto" +) + +func (e One) ToPointer() *One { + return &e +} +func (e *One) UnmarshalJSON(data []byte) error { + var v string + if err := json.Unmarshal(data, &v); err != nil { + return err + } + switch v { + case "none": + fallthrough + case "auto": + *e = One(v) + return nil + default: + return fmt.Errorf("invalid value for One: %v", v) + } +} + +type CreateChatCompletionRequestFunctionCallType string + +const ( + CreateChatCompletionRequestFunctionCallTypeOne CreateChatCompletionRequestFunctionCallType = "1" + CreateChatCompletionRequestFunctionCallTypeChatCompletionFunctionCallOption CreateChatCompletionRequestFunctionCallType = "ChatCompletionFunctionCallOption" +) + +// CreateChatCompletionRequestFunctionCall - Deprecated in favor of `tool_choice`. +// +// Controls which (if any) function is called by the model. +// `none` means the model will not call a function and instead generates a message. +// `auto` means the model can pick between generating a message or calling a function. +// Specifying a particular function via `{"name": "my_function"}` forces the model to call that function. +// +// `none` is the default when no functions are present. `auto` is the default if functions are present. +// +// Deprecated type: This will be removed in a future release, please migrate away from it as soon as possible. +type CreateChatCompletionRequestFunctionCall struct { + One *One + ChatCompletionFunctionCallOption *ChatCompletionFunctionCallOption + + Type CreateChatCompletionRequestFunctionCallType +} + +func CreateCreateChatCompletionRequestFunctionCallOne(one One) CreateChatCompletionRequestFunctionCall { + typ := CreateChatCompletionRequestFunctionCallTypeOne + + return CreateChatCompletionRequestFunctionCall{ + One: &one, + Type: typ, + } +} + +func CreateCreateChatCompletionRequestFunctionCallChatCompletionFunctionCallOption(chatCompletionFunctionCallOption ChatCompletionFunctionCallOption) CreateChatCompletionRequestFunctionCall { + typ := CreateChatCompletionRequestFunctionCallTypeChatCompletionFunctionCallOption + + return CreateChatCompletionRequestFunctionCall{ + ChatCompletionFunctionCallOption: &chatCompletionFunctionCallOption, + Type: typ, + } +} + +func (u *CreateChatCompletionRequestFunctionCall) UnmarshalJSON(data []byte) error { + + var chatCompletionFunctionCallOption ChatCompletionFunctionCallOption = ChatCompletionFunctionCallOption{} + if err := utils.UnmarshalJSON(data, &chatCompletionFunctionCallOption, "", true, true); err == nil { + u.ChatCompletionFunctionCallOption = &chatCompletionFunctionCallOption + u.Type = CreateChatCompletionRequestFunctionCallTypeChatCompletionFunctionCallOption + return nil + } + + var one One = One("") + if err := utils.UnmarshalJSON(data, &one, "", true, true); err == nil { + u.One = &one + u.Type = CreateChatCompletionRequestFunctionCallTypeOne + return nil + } + + return fmt.Errorf("could not unmarshal `%s` into any supported union types for CreateChatCompletionRequestFunctionCall", string(data)) +} + +func (u CreateChatCompletionRequestFunctionCall) MarshalJSON() ([]byte, error) { + if u.One != nil { + return utils.MarshalJSON(u.One, "", true) + } + + if u.ChatCompletionFunctionCallOption != nil { + return utils.MarshalJSON(u.ChatCompletionFunctionCallOption, "", true) + } + + return nil, errors.New("could not marshal union type CreateChatCompletionRequestFunctionCall: all fields are null") +} + +type CreateChatCompletionRequest struct { + // A list of messages comprising the conversation so far. [Example Python code](https://cookbook.openai.com/examples/how_to_format_inputs_to_chatgpt_models). + Messages []ChatCompletionRequestMessage `json:"messages"` + // ID of the model to use. See the [model endpoint compatibility](/docs/models/model-endpoint-compatibility) table for details on which models work with the Chat API. + Model Model `json:"model"` + // Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. + // + // [See more information about frequency and presence penalties.](/docs/guides/text-generation/parameter-details) + // + FrequencyPenalty *float64 `default:"0" json:"frequency_penalty"` + // Modify the likelihood of specified tokens appearing in the completion. + // + // Accepts a JSON object that maps tokens (specified by their token ID in the tokenizer) to an associated bias value from -100 to 100. Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model, but values between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 should result in a ban or exclusive selection of the relevant token. + // + LogitBias map[string]int64 `json:"logit_bias,omitempty"` + // Whether to return log probabilities of the output tokens or not. If true, returns the log probabilities of each output token returned in the `content` of `message`. + Logprobs *bool `default:"false" json:"logprobs"` + // An integer between 0 and 20 specifying the number of most likely tokens to return at each token position, each with an associated log probability. `logprobs` must be set to `true` if this parameter is used. + TopLogprobs *int64 `json:"top_logprobs,omitempty"` + // The maximum number of [tokens](/tokenizer) that can be generated in the chat completion. + // + // The total length of input tokens and generated tokens is limited by the model's context length. [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) for counting tokens. + // + MaxTokens *int64 `json:"max_tokens,omitempty"` + // How many chat completion choices to generate for each input message. Note that you will be charged based on the number of generated tokens across all of the choices. Keep `n` as `1` to minimize costs. + N *int64 `default:"1" json:"n"` + // Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics. + // + // [See more information about frequency and presence penalties.](/docs/guides/text-generation/parameter-details) + // + PresencePenalty *float64 `default:"0" json:"presence_penalty"` + // An object specifying the format that the model must output. Compatible with [GPT-4 Turbo](/docs/models/gpt-4-and-gpt-4-turbo) and all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + // + // Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. + // + // **Important:** when using JSON mode, you **must** also instruct the model to produce JSON yourself via a system or user message. Without this, the model may generate an unending stream of whitespace until the generation reaches the token limit, resulting in a long-running and seemingly "stuck" request. Also note that the message content may be partially cut off if `finish_reason="length"`, which indicates the generation exceeded `max_tokens` or the conversation exceeded the max context length. + // + ResponseFormat *ResponseFormat `json:"response_format,omitempty"` + // This feature is in Beta. + // If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return the same result. + // Determinism is not guaranteed, and you should refer to the `system_fingerprint` response parameter to monitor changes in the backend. + // + Seed *int64 `json:"seed,omitempty"` + // Up to 4 sequences where the API will stop generating further tokens. + // + Stop *Stop `json:"stop,omitempty"` + // If set, partial message deltas will be sent, like in ChatGPT. Tokens will be sent as data-only [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) as they become available, with the stream terminated by a `data: [DONE]` message. [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + // + Stream *bool `default:"false" json:"stream"` + // Options for streaming response. Only set this when you set `stream: true`. + // + StreamOptions *ChatCompletionStreamOptions `json:"stream_options,omitempty"` + // What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. + // + // We generally recommend altering this or `top_p` but not both. + // + Temperature *float64 `default:"1" json:"temperature"` + // An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. + // + // We generally recommend altering this or `temperature` but not both. + // + TopP *float64 `default:"1" json:"top_p"` + // A list of tools the model may call. Currently, only functions are supported as a tool. Use this to provide a list of functions the model may generate JSON inputs for. A max of 128 functions are supported. + // + Tools []ChatCompletionTool `json:"tools,omitempty"` + // Controls which (if any) tool is called by the model. + // `none` means the model will not call any tool and instead generates a message. + // `auto` means the model can pick between generating a message or calling one or more tools. + // `required` means the model must call one or more tools. + // Specifying a particular tool via `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. + // + // `none` is the default when no tools are present. `auto` is the default if tools are present. + // + ToolChoice *ChatCompletionToolChoiceOption `json:"tool_choice,omitempty"` + // A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](/docs/guides/safety-best-practices/end-user-ids). + // + User *string `json:"user,omitempty"` + // Deprecated in favor of `tool_choice`. + // + // Controls which (if any) function is called by the model. + // `none` means the model will not call a function and instead generates a message. + // `auto` means the model can pick between generating a message or calling a function. + // Specifying a particular function via `{"name": "my_function"}` forces the model to call that function. + // + // `none` is the default when no functions are present. `auto` is the default if functions are present. + // + // + // Deprecated field: This will be removed in a future release, please migrate away from it as soon as possible. + FunctionCall *CreateChatCompletionRequestFunctionCall `json:"function_call,omitempty"` + // Deprecated in favor of `tools`. + // + // A list of functions the model may generate JSON inputs for. + // + // + // Deprecated field: This will be removed in a future release, please migrate away from it as soon as possible. + Functions []ChatCompletionFunctions `json:"functions,omitempty"` +} + +func (c CreateChatCompletionRequest) MarshalJSON() ([]byte, error) { + return utils.MarshalJSON(c, "", false) +} + +func (c *CreateChatCompletionRequest) UnmarshalJSON(data []byte) error { + if err := utils.UnmarshalJSON(data, &c, "", false, false); err != nil { + return err + } + return nil +} + +func (o *CreateChatCompletionRequest) GetMessages() []ChatCompletionRequestMessage { + if o == nil { + return []ChatCompletionRequestMessage{} + } + return o.Messages +} + +func (o *CreateChatCompletionRequest) GetModel() Model { + if o == nil { + return Model{} + } + return o.Model +} + +func (o *CreateChatCompletionRequest) GetFrequencyPenalty() *float64 { + if o == nil { + return nil + } + return o.FrequencyPenalty +} + +func (o *CreateChatCompletionRequest) GetLogitBias() map[string]int64 { + if o == nil { + return nil + } + return o.LogitBias +} + +func (o *CreateChatCompletionRequest) GetLogprobs() *bool { + if o == nil { + return nil + } + return o.Logprobs +} + +func (o *CreateChatCompletionRequest) GetTopLogprobs() *int64 { + if o == nil { + return nil + } + return o.TopLogprobs +} + +func (o *CreateChatCompletionRequest) GetMaxTokens() *int64 { + if o == nil { + return nil + } + return o.MaxTokens +} + +func (o *CreateChatCompletionRequest) GetN() *int64 { + if o == nil { + return nil + } + return o.N +} + +func (o *CreateChatCompletionRequest) GetPresencePenalty() *float64 { + if o == nil { + return nil + } + return o.PresencePenalty +} + +func (o *CreateChatCompletionRequest) GetResponseFormat() *ResponseFormat { + if o == nil { + return nil + } + return o.ResponseFormat +} + +func (o *CreateChatCompletionRequest) GetSeed() *int64 { + if o == nil { + return nil + } + return o.Seed +} + +func (o *CreateChatCompletionRequest) GetStop() *Stop { + if o == nil { + return nil + } + return o.Stop +} + +func (o *CreateChatCompletionRequest) GetStream() *bool { + if o == nil { + return nil + } + return o.Stream +} + +func (o *CreateChatCompletionRequest) GetStreamOptions() *ChatCompletionStreamOptions { + if o == nil { + return nil + } + return o.StreamOptions +} + +func (o *CreateChatCompletionRequest) GetTemperature() *float64 { + if o == nil { + return nil + } + return o.Temperature +} + +func (o *CreateChatCompletionRequest) GetTopP() *float64 { + if o == nil { + return nil + } + return o.TopP +} + +func (o *CreateChatCompletionRequest) GetTools() []ChatCompletionTool { + if o == nil { + return nil + } + return o.Tools +} + +func (o *CreateChatCompletionRequest) GetToolChoice() *ChatCompletionToolChoiceOption { + if o == nil { + return nil + } + return o.ToolChoice +} + +func (o *CreateChatCompletionRequest) GetUser() *string { + if o == nil { + return nil + } + return o.User +} + +func (o *CreateChatCompletionRequest) GetFunctionCall() *CreateChatCompletionRequestFunctionCall { + if o == nil { + return nil + } + return o.FunctionCall +} + +func (o *CreateChatCompletionRequest) GetFunctions() []ChatCompletionFunctions { + if o == nil { + return nil + } + return o.Functions +} diff --git a/models/components/createchatcompletionresponse.go b/models/components/createchatcompletionresponse.go new file mode 100644 index 0000000..8bf390b --- /dev/null +++ b/models/components/createchatcompletionresponse.go @@ -0,0 +1,197 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package components + +import ( + "encoding/json" + "fmt" +) + +// FinishReason - The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence, +// `length` if the maximum number of tokens specified in the request was reached, +// `content_filter` if content was omitted due to a flag from our content filters, +// `tool_calls` if the model called a tool, or `function_call` (deprecated) if the model called a function. +type FinishReason string + +const ( + FinishReasonStop FinishReason = "stop" + FinishReasonLength FinishReason = "length" + FinishReasonToolCalls FinishReason = "tool_calls" + FinishReasonContentFilter FinishReason = "content_filter" + FinishReasonFunctionCall FinishReason = "function_call" +) + +func (e FinishReason) ToPointer() *FinishReason { + return &e +} +func (e *FinishReason) UnmarshalJSON(data []byte) error { + var v string + if err := json.Unmarshal(data, &v); err != nil { + return err + } + switch v { + case "stop": + fallthrough + case "length": + fallthrough + case "tool_calls": + fallthrough + case "content_filter": + fallthrough + case "function_call": + *e = FinishReason(v) + return nil + default: + return fmt.Errorf("invalid value for FinishReason: %v", v) + } +} + +// Logprobs - Log probability information for the choice. +type Logprobs struct { + // A list of message content tokens with log probability information. + Content []ChatCompletionTokenLogprob `json:"content"` +} + +func (o *Logprobs) GetContent() []ChatCompletionTokenLogprob { + if o == nil { + return nil + } + return o.Content +} + +type Choices struct { + // The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence, + // `length` if the maximum number of tokens specified in the request was reached, + // `content_filter` if content was omitted due to a flag from our content filters, + // `tool_calls` if the model called a tool, or `function_call` (deprecated) if the model called a function. + // + FinishReason FinishReason `json:"finish_reason"` + // The index of the choice in the list of choices. + Index int64 `json:"index"` + // A chat completion message generated by the model. + Message ChatCompletionResponseMessage `json:"message"` + // Log probability information for the choice. + Logprobs *Logprobs `json:"logprobs"` +} + +func (o *Choices) GetFinishReason() FinishReason { + if o == nil { + return FinishReason("") + } + return o.FinishReason +} + +func (o *Choices) GetIndex() int64 { + if o == nil { + return 0 + } + return o.Index +} + +func (o *Choices) GetMessage() ChatCompletionResponseMessage { + if o == nil { + return ChatCompletionResponseMessage{} + } + return o.Message +} + +func (o *Choices) GetLogprobs() *Logprobs { + if o == nil { + return nil + } + return o.Logprobs +} + +// Object - The object type, which is always `chat.completion`. +type Object string + +const ( + ObjectChatCompletion Object = "chat.completion" +) + +func (e Object) ToPointer() *Object { + return &e +} +func (e *Object) UnmarshalJSON(data []byte) error { + var v string + if err := json.Unmarshal(data, &v); err != nil { + return err + } + switch v { + case "chat.completion": + *e = Object(v) + return nil + default: + return fmt.Errorf("invalid value for Object: %v", v) + } +} + +// CreateChatCompletionResponse - Represents a chat completion response returned by model, based on the provided input. +type CreateChatCompletionResponse struct { + // A unique identifier for the chat completion. + ID string `json:"id"` + // A list of chat completion choices. Can be more than one if `n` is greater than 1. + Choices []Choices `json:"choices"` + // The Unix timestamp (in seconds) of when the chat completion was created. + Created int64 `json:"created"` + // The model used for the chat completion. + Model string `json:"model"` + // This fingerprint represents the backend configuration that the model runs with. + // + // Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism. + // + SystemFingerprint *string `json:"system_fingerprint,omitempty"` + // The object type, which is always `chat.completion`. + Object Object `json:"object"` + // Usage statistics for the completion request. + Usage *CompletionUsage `json:"usage,omitempty"` +} + +func (o *CreateChatCompletionResponse) GetID() string { + if o == nil { + return "" + } + return o.ID +} + +func (o *CreateChatCompletionResponse) GetChoices() []Choices { + if o == nil { + return []Choices{} + } + return o.Choices +} + +func (o *CreateChatCompletionResponse) GetCreated() int64 { + if o == nil { + return 0 + } + return o.Created +} + +func (o *CreateChatCompletionResponse) GetModel() string { + if o == nil { + return "" + } + return o.Model +} + +func (o *CreateChatCompletionResponse) GetSystemFingerprint() *string { + if o == nil { + return nil + } + return o.SystemFingerprint +} + +func (o *CreateChatCompletionResponse) GetObject() Object { + if o == nil { + return Object("") + } + return o.Object +} + +func (o *CreateChatCompletionResponse) GetUsage() *CompletionUsage { + if o == nil { + return nil + } + return o.Usage +} diff --git a/models/components/feedback.go b/models/components/feedback.go new file mode 100644 index 0000000..79d0b7b --- /dev/null +++ b/models/components/feedback.go @@ -0,0 +1,72 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package components + +// JSONValues - The values of the feedback. Must be valid JSON according to the task schema. +type JSONValues struct { +} + +type Feedback struct { + // The unique identifier for this feedback. + ID *string `json:"id,omitempty"` + // The epoch this schema was created. + CreatedAtMs *float64 `json:"created_at_ms,omitempty"` + // The unique identifier for the task associated with this feedback. + TaskID string `json:"task_id"` + // The values of the feedback. Must be valid JSON according to the task schema. + JSONValues JSONValues `json:"json_values"` + // The matched completion ids associated with this feedback. + MatchedCompletionIds []string `json:"matched_completion_ids"` + // The comment associated with this feedback. + Comment string `json:"comment"` + CompletionsSummary *string `json:"completions_summary,omitempty"` +} + +func (o *Feedback) GetID() *string { + if o == nil { + return nil + } + return o.ID +} + +func (o *Feedback) GetCreatedAtMs() *float64 { + if o == nil { + return nil + } + return o.CreatedAtMs +} + +func (o *Feedback) GetTaskID() string { + if o == nil { + return "" + } + return o.TaskID +} + +func (o *Feedback) GetJSONValues() JSONValues { + if o == nil { + return JSONValues{} + } + return o.JSONValues +} + +func (o *Feedback) GetMatchedCompletionIds() []string { + if o == nil { + return []string{} + } + return o.MatchedCompletionIds +} + +func (o *Feedback) GetComment() string { + if o == nil { + return "" + } + return o.Comment +} + +func (o *Feedback) GetCompletionsSummary() *string { + if o == nil { + return nil + } + return o.CompletionsSummary +} diff --git a/models/components/functionobject.go b/models/components/functionobject.go new file mode 100644 index 0000000..bd04760 --- /dev/null +++ b/models/components/functionobject.go @@ -0,0 +1,35 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package components + +type FunctionObject struct { + // A description of what the function does, used by the model to choose when and how to call the function. + Description *string `json:"description,omitempty"` + // The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64. + Name string `json:"name"` + // The parameters the functions accepts, described as a JSON Schema object. See the [guide](/docs/guides/text-generation/function-calling) for examples, and the [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for documentation about the format. + // + // Omitting `parameters` defines a function with an empty parameter list. + Parameters map[string]any `json:"parameters,omitempty"` +} + +func (o *FunctionObject) GetDescription() *string { + if o == nil { + return nil + } + return o.Description +} + +func (o *FunctionObject) GetName() string { + if o == nil { + return "" + } + return o.Name +} + +func (o *FunctionObject) GetParameters() map[string]any { + if o == nil { + return nil + } + return o.Parameters +} diff --git a/models/components/httpmetadata.go b/models/components/httpmetadata.go new file mode 100644 index 0000000..f6ec394 --- /dev/null +++ b/models/components/httpmetadata.go @@ -0,0 +1,28 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package components + +import ( + "net/http" +) + +type HTTPMetadata struct { + // Raw HTTP response; suitable for custom response parsing + Response *http.Response `json:"-"` + // Raw HTTP request; suitable for debugging + Request *http.Request `json:"-"` +} + +func (o *HTTPMetadata) GetResponse() *http.Response { + if o == nil { + return nil + } + return o.Response +} + +func (o *HTTPMetadata) GetRequest() *http.Request { + if o == nil { + return nil + } + return o.Request +} diff --git a/models/components/security.go b/models/components/security.go new file mode 100644 index 0000000..7522807 --- /dev/null +++ b/models/components/security.go @@ -0,0 +1,14 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package components + +type Security struct { + Log10Token *string `security:"scheme,type=apiKey,subtype=header,name=X-Log10-Token"` +} + +func (o *Security) GetLog10Token() *string { + if o == nil { + return nil + } + return o.Log10Token +} diff --git a/models/components/session.go b/models/components/session.go new file mode 100644 index 0000000..654ff42 --- /dev/null +++ b/models/components/session.go @@ -0,0 +1,15 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package components + +type Session struct { + // The unique identifier for this session. + ID *string `json:"id,omitempty"` +} + +func (o *Session) GetID() *string { + if o == nil { + return nil + } + return o.ID +} diff --git a/models/components/task.go b/models/components/task.go new file mode 100644 index 0000000..b47532e --- /dev/null +++ b/models/components/task.go @@ -0,0 +1,68 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package components + +// JSONSchema - The schema of the task. Must be valid JSON Schema. +type JSONSchema struct { +} + +// CompletionTagsSelector - The completion tag matching with this task i.e. surfaced as needing feedback. +type CompletionTagsSelector struct { +} + +type Task struct { + // The unique identifier for this task. + ID *string `json:"id,omitempty"` + // The epoch this schema was created. + CreatedAtMs *float64 `json:"created_at_ms,omitempty"` + // The schema of the task. Must be valid JSON Schema. + JSONSchema JSONSchema `json:"json_schema"` + // The name of the task. + Name string `json:"name"` + // The instructions for this task. + Instruction string `json:"instruction"` + // The completion tag matching with this task i.e. surfaced as needing feedback. + CompletionTagsSelector CompletionTagsSelector `json:"completion_tags_selector"` +} + +func (o *Task) GetID() *string { + if o == nil { + return nil + } + return o.ID +} + +func (o *Task) GetCreatedAtMs() *float64 { + if o == nil { + return nil + } + return o.CreatedAtMs +} + +func (o *Task) GetJSONSchema() JSONSchema { + if o == nil { + return JSONSchema{} + } + return o.JSONSchema +} + +func (o *Task) GetName() string { + if o == nil { + return "" + } + return o.Name +} + +func (o *Task) GetInstruction() string { + if o == nil { + return "" + } + return o.Instruction +} + +func (o *Task) GetCompletionTagsSelector() CompletionTagsSelector { + if o == nil { + return CompletionTagsSelector{} + } + return o.CompletionTagsSelector +} diff --git a/models/operations/create.go b/models/operations/create.go new file mode 100644 index 0000000..9da3779 --- /dev/null +++ b/models/operations/create.go @@ -0,0 +1,66 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package operations + +import ( + "github.com/log10-io/log10go/models/components" +) + +type CreateGlobals struct { + XLog10Organization string `header:"style=simple,explode=false,name=X-Log10-Organization"` +} + +func (o *CreateGlobals) GetXLog10Organization() string { + if o == nil { + return "" + } + return o.XLog10Organization +} + +type CreateRequest struct { + XLog10Organization *string `header:"style=simple,explode=false,name=X-Log10-Organization"` + Completion components.Completion `request:"mediaType=application/json"` +} + +func (o *CreateRequest) GetXLog10Organization() *string { + if o == nil { + return nil + } + return o.XLog10Organization +} + +func (o *CreateRequest) GetCompletion() components.Completion { + if o == nil { + return components.Completion{} + } + return o.Completion +} + +type CreateResponse struct { + HTTPMeta components.HTTPMetadata `json:"-"` + // Created + Any any + // Created + Completion *components.Completion +} + +func (o *CreateResponse) GetHTTPMeta() components.HTTPMetadata { + if o == nil { + return components.HTTPMetadata{} + } + return o.HTTPMeta +} + +func (o *CreateResponse) GetAny() any { + if o == nil { + return nil + } + return o.Any +} + +func (o *CreateResponse) GetCompletion() *components.Completion { + if o == nil { + return nil + } + return o.Completion +} diff --git a/models/operations/createfeedbacktask.go b/models/operations/createfeedbacktask.go new file mode 100644 index 0000000..b282d8c --- /dev/null +++ b/models/operations/createfeedbacktask.go @@ -0,0 +1,27 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package operations + +import ( + "github.com/log10-io/log10go/models/components" +) + +type CreateFeedbackTaskResponse struct { + HTTPMeta components.HTTPMetadata `json:"-"` + // OK + Task *components.Task +} + +func (o *CreateFeedbackTaskResponse) GetHTTPMeta() components.HTTPMetadata { + if o == nil { + return components.HTTPMetadata{} + } + return o.HTTPMeta +} + +func (o *CreateFeedbackTaskResponse) GetTask() *components.Task { + if o == nil { + return nil + } + return o.Task +} diff --git a/models/operations/createsession.go b/models/operations/createsession.go new file mode 100644 index 0000000..58f65ae --- /dev/null +++ b/models/operations/createsession.go @@ -0,0 +1,61 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package operations + +import ( + "github.com/log10-io/log10go/models/components" +) + +type CreateSessionGlobals struct { + XLog10Organization string `header:"style=simple,explode=false,name=X-Log10-Organization"` +} + +func (o *CreateSessionGlobals) GetXLog10Organization() string { + if o == nil { + return "" + } + return o.XLog10Organization +} + +type CreateSessionRequest struct { + XLog10Organization *string `header:"style=simple,explode=false,name=X-Log10-Organization"` +} + +func (o *CreateSessionRequest) GetXLog10Organization() *string { + if o == nil { + return nil + } + return o.XLog10Organization +} + +// CreateSessionResponseBody - Created +type CreateSessionResponseBody struct { + Session *components.Session `json:"session,omitempty"` +} + +func (o *CreateSessionResponseBody) GetSession() *components.Session { + if o == nil { + return nil + } + return o.Session +} + +type CreateSessionResponse struct { + HTTPMeta components.HTTPMetadata `json:"-"` + // Created + Object *CreateSessionResponseBody +} + +func (o *CreateSessionResponse) GetHTTPMeta() components.HTTPMetadata { + if o == nil { + return components.HTTPMetadata{} + } + return o.HTTPMeta +} + +func (o *CreateSessionResponse) GetObject() *CreateSessionResponseBody { + if o == nil { + return nil + } + return o.Object +} diff --git a/models/operations/get.go b/models/operations/get.go new file mode 100644 index 0000000..99a8d1a --- /dev/null +++ b/models/operations/get.go @@ -0,0 +1,58 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package operations + +import ( + "github.com/log10-io/log10go/models/components" +) + +type GetGlobals struct { + XLog10Organization string `header:"style=simple,explode=false,name=X-Log10-Organization"` +} + +func (o *GetGlobals) GetXLog10Organization() string { + if o == nil { + return "" + } + return o.XLog10Organization +} + +type GetRequest struct { + // The feedback id to fetch. + FeedbackID string `pathParam:"style=simple,explode=false,name=feedbackId"` + XLog10Organization *string `header:"style=simple,explode=false,name=X-Log10-Organization"` +} + +func (o *GetRequest) GetFeedbackID() string { + if o == nil { + return "" + } + return o.FeedbackID +} + +func (o *GetRequest) GetXLog10Organization() *string { + if o == nil { + return nil + } + return o.XLog10Organization +} + +type GetResponse struct { + HTTPMeta components.HTTPMetadata `json:"-"` + // OK + Feedback *components.Feedback +} + +func (o *GetResponse) GetHTTPMeta() components.HTTPMetadata { + if o == nil { + return components.HTTPMetadata{} + } + return o.HTTPMeta +} + +func (o *GetResponse) GetFeedback() *components.Feedback { + if o == nil { + return nil + } + return o.Feedback +} diff --git a/models/operations/getfeedbacktask.go b/models/operations/getfeedbacktask.go new file mode 100644 index 0000000..74a38b1 --- /dev/null +++ b/models/operations/getfeedbacktask.go @@ -0,0 +1,39 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package operations + +import ( + "github.com/log10-io/log10go/models/components" +) + +type GetFeedbackTaskRequest struct { + // The task id to fetch. + TaskID string `pathParam:"style=simple,explode=false,name=taskId"` +} + +func (o *GetFeedbackTaskRequest) GetTaskID() string { + if o == nil { + return "" + } + return o.TaskID +} + +type GetFeedbackTaskResponse struct { + HTTPMeta components.HTTPMetadata `json:"-"` + // OK + Task *components.Task +} + +func (o *GetFeedbackTaskResponse) GetHTTPMeta() components.HTTPMetadata { + if o == nil { + return components.HTTPMetadata{} + } + return o.HTTPMeta +} + +func (o *GetFeedbackTaskResponse) GetTask() *components.Task { + if o == nil { + return nil + } + return o.Task +} diff --git a/models/operations/list.go b/models/operations/list.go new file mode 100644 index 0000000..2f54a57 --- /dev/null +++ b/models/operations/list.go @@ -0,0 +1,108 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package operations + +import ( + "github.com/log10-io/log10go/models/components" +) + +type ListGlobals struct { + XLog10Organization string `header:"style=simple,explode=false,name=X-Log10-Organization"` +} + +func (o *ListGlobals) GetXLog10Organization() string { + if o == nil { + return "" + } + return o.XLog10Organization +} + +type ListRequestBody struct { + // The offset to start fetching feedback from. + Offset *int64 `json:"offset,omitempty"` + // The number of feedback to fetch. + Limit *int64 `json:"limit,omitempty"` + // The completion id to fetch feedback for. + CompletionID *string `json:"completion_id,omitempty"` + // The task id to fetch feedback for. + TaskID *string `json:"task_id,omitempty"` +} + +func (o *ListRequestBody) GetOffset() *int64 { + if o == nil { + return nil + } + return o.Offset +} + +func (o *ListRequestBody) GetLimit() *int64 { + if o == nil { + return nil + } + return o.Limit +} + +func (o *ListRequestBody) GetCompletionID() *string { + if o == nil { + return nil + } + return o.CompletionID +} + +func (o *ListRequestBody) GetTaskID() *string { + if o == nil { + return nil + } + return o.TaskID +} + +type ListRequest struct { + XLog10Organization *string `header:"style=simple,explode=false,name=X-Log10-Organization"` + RequestBody *ListRequestBody `request:"mediaType=application/json"` +} + +func (o *ListRequest) GetXLog10Organization() *string { + if o == nil { + return nil + } + return o.XLog10Organization +} + +func (o *ListRequest) GetRequestBody() *ListRequestBody { + if o == nil { + return nil + } + return o.RequestBody +} + +// ListResponseBody - OK +type ListResponseBody struct { + Feedback []components.Feedback `json:"feedback,omitempty"` +} + +func (o *ListResponseBody) GetFeedback() []components.Feedback { + if o == nil { + return nil + } + return o.Feedback +} + +type ListResponse struct { + HTTPMeta components.HTTPMetadata `json:"-"` + // OK + Object *ListResponseBody +} + +func (o *ListResponse) GetHTTPMeta() components.HTTPMetadata { + if o == nil { + return components.HTTPMetadata{} + } + return o.HTTPMeta +} + +func (o *ListResponse) GetObject() *ListResponseBody { + if o == nil { + return nil + } + return o.Object +} diff --git a/models/operations/listfeedbacktasks.go b/models/operations/listfeedbacktasks.go new file mode 100644 index 0000000..c9d8387 --- /dev/null +++ b/models/operations/listfeedbacktasks.go @@ -0,0 +1,27 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package operations + +import ( + "github.com/log10-io/log10go/models/components" +) + +type ListFeedbackTasksResponse struct { + HTTPMeta components.HTTPMetadata `json:"-"` + // OK + Tasks []components.Task +} + +func (o *ListFeedbackTasksResponse) GetHTTPMeta() components.HTTPMetadata { + if o == nil { + return components.HTTPMetadata{} + } + return o.HTTPMeta +} + +func (o *ListFeedbackTasksResponse) GetTasks() []components.Task { + if o == nil { + return nil + } + return o.Tasks +} diff --git a/models/operations/listungraded.go b/models/operations/listungraded.go new file mode 100644 index 0000000..62b3463 --- /dev/null +++ b/models/operations/listungraded.go @@ -0,0 +1,61 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package operations + +import ( + "github.com/log10-io/log10go/models/components" +) + +type ListUngradedGlobals struct { + XLog10Organization string `header:"style=simple,explode=false,name=X-Log10-Organization"` +} + +func (o *ListUngradedGlobals) GetXLog10Organization() string { + if o == nil { + return "" + } + return o.XLog10Organization +} + +type ListUngradedRequest struct { + XLog10Organization *string `header:"style=simple,explode=false,name=X-Log10-Organization"` +} + +func (o *ListUngradedRequest) GetXLog10Organization() *string { + if o == nil { + return nil + } + return o.XLog10Organization +} + +// ListUngradedResponseBody - OK +type ListUngradedResponseBody struct { + Completions []components.Completion `json:"completions,omitempty"` +} + +func (o *ListUngradedResponseBody) GetCompletions() []components.Completion { + if o == nil { + return nil + } + return o.Completions +} + +type ListUngradedResponse struct { + HTTPMeta components.HTTPMetadata `json:"-"` + // OK + Object *ListUngradedResponseBody +} + +func (o *ListUngradedResponse) GetHTTPMeta() components.HTTPMetadata { + if o == nil { + return components.HTTPMetadata{} + } + return o.HTTPMeta +} + +func (o *ListUngradedResponse) GetObject() *ListUngradedResponseBody { + if o == nil { + return nil + } + return o.Object +} diff --git a/models/operations/update.go b/models/operations/update.go new file mode 100644 index 0000000..35bef45 --- /dev/null +++ b/models/operations/update.go @@ -0,0 +1,66 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package operations + +import ( + "github.com/log10-io/log10go/models/components" +) + +type UpdateGlobals struct { + XLog10Organization string `header:"style=simple,explode=false,name=X-Log10-Organization"` +} + +func (o *UpdateGlobals) GetXLog10Organization() string { + if o == nil { + return "" + } + return o.XLog10Organization +} + +type UpdateRequest struct { + // The completion id to update. + CompletionID string `pathParam:"style=simple,explode=false,name=completionId"` + XLog10Organization *string `header:"style=simple,explode=false,name=X-Log10-Organization"` + Completion components.Completion `request:"mediaType=application/json"` +} + +func (o *UpdateRequest) GetCompletionID() string { + if o == nil { + return "" + } + return o.CompletionID +} + +func (o *UpdateRequest) GetXLog10Organization() *string { + if o == nil { + return nil + } + return o.XLog10Organization +} + +func (o *UpdateRequest) GetCompletion() components.Completion { + if o == nil { + return components.Completion{} + } + return o.Completion +} + +type UpdateResponse struct { + HTTPMeta components.HTTPMetadata `json:"-"` + // OK + Completion *components.Completion +} + +func (o *UpdateResponse) GetHTTPMeta() components.HTTPMetadata { + if o == nil { + return components.HTTPMetadata{} + } + return o.HTTPMeta +} + +func (o *UpdateResponse) GetCompletion() *components.Completion { + if o == nil { + return nil + } + return o.Completion +} diff --git a/models/operations/upload.go b/models/operations/upload.go new file mode 100644 index 0000000..e7091fa --- /dev/null +++ b/models/operations/upload.go @@ -0,0 +1,308 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package operations + +import ( + "errors" + "fmt" + "github.com/log10-io/log10go/internal/utils" + "github.com/log10-io/log10go/models/components" +) + +type UploadGlobals struct { + XLog10Organization string `header:"style=simple,explode=false,name=X-Log10-Organization"` +} + +func (o *UploadGlobals) GetXLog10Organization() string { + if o == nil { + return "" + } + return o.XLog10Organization +} + +// RequestBodyJSONValues - The values of the feedback. Must be valid JSON according to the task schema. +type RequestBodyJSONValues struct { +} + +type Two struct { + // The unique identifier for this feedback. + ID *string `json:"id,omitempty"` + // The epoch this schema was created. + CreatedAtMs *float64 `json:"created_at_ms,omitempty"` + // The unique identifier for the task associated with this feedback. + TaskID string `json:"task_id"` + // The values of the feedback. Must be valid JSON according to the task schema. + JSONValues RequestBodyJSONValues `json:"json_values"` + // The matched completion ids associated with this feedback. + MatchedCompletionIds []string `json:"matched_completion_ids"` + // The comment associated with this feedback. + Comment string `json:"comment"` + CompletionsSummary *string `json:"completions_summary,omitempty"` + // The completion ids to associate with this feedback. + CompletionIds []string `json:"completion_ids"` +} + +func (o *Two) GetID() *string { + if o == nil { + return nil + } + return o.ID +} + +func (o *Two) GetCreatedAtMs() *float64 { + if o == nil { + return nil + } + return o.CreatedAtMs +} + +func (o *Two) GetTaskID() string { + if o == nil { + return "" + } + return o.TaskID +} + +func (o *Two) GetJSONValues() RequestBodyJSONValues { + if o == nil { + return RequestBodyJSONValues{} + } + return o.JSONValues +} + +func (o *Two) GetMatchedCompletionIds() []string { + if o == nil { + return []string{} + } + return o.MatchedCompletionIds +} + +func (o *Two) GetComment() string { + if o == nil { + return "" + } + return o.Comment +} + +func (o *Two) GetCompletionsSummary() *string { + if o == nil { + return nil + } + return o.CompletionsSummary +} + +func (o *Two) GetCompletionIds() []string { + if o == nil { + return []string{} + } + return o.CompletionIds +} + +// JSONValues - The values of the feedback. Must be valid JSON according to the task schema. +type JSONValues struct { +} + +type One struct { + // The unique identifier for this feedback. + ID *string `json:"id,omitempty"` + // The epoch this schema was created. + CreatedAtMs *float64 `json:"created_at_ms,omitempty"` + // The unique identifier for the task associated with this feedback. + TaskID string `json:"task_id"` + // The values of the feedback. Must be valid JSON according to the task schema. + JSONValues JSONValues `json:"json_values"` + // The matched completion ids associated with this feedback. + MatchedCompletionIds []string `json:"matched_completion_ids"` + // The comment associated with this feedback. + Comment string `json:"comment"` + CompletionsSummary *string `json:"completions_summary,omitempty"` + // Whether to allow unmatched feedback. Defaults to false. + AllowUnmatchedFeedback *bool `default:"false" json:"allow_unmatched_feedback"` + // The maximum number of matched completions. Returns error if exceeded. Defaults to 100. + MaxMatchedCompletions *int64 `default:"100" json:"max_matched_completions"` + // The completion tags associated with this feedback. + CompletionTagsSelector []string `json:"completion_tags_selector"` +} + +func (o One) MarshalJSON() ([]byte, error) { + return utils.MarshalJSON(o, "", false) +} + +func (o *One) UnmarshalJSON(data []byte) error { + if err := utils.UnmarshalJSON(data, &o, "", false, true); err != nil { + return err + } + return nil +} + +func (o *One) GetID() *string { + if o == nil { + return nil + } + return o.ID +} + +func (o *One) GetCreatedAtMs() *float64 { + if o == nil { + return nil + } + return o.CreatedAtMs +} + +func (o *One) GetTaskID() string { + if o == nil { + return "" + } + return o.TaskID +} + +func (o *One) GetJSONValues() JSONValues { + if o == nil { + return JSONValues{} + } + return o.JSONValues +} + +func (o *One) GetMatchedCompletionIds() []string { + if o == nil { + return []string{} + } + return o.MatchedCompletionIds +} + +func (o *One) GetComment() string { + if o == nil { + return "" + } + return o.Comment +} + +func (o *One) GetCompletionsSummary() *string { + if o == nil { + return nil + } + return o.CompletionsSummary +} + +func (o *One) GetAllowUnmatchedFeedback() *bool { + if o == nil { + return nil + } + return o.AllowUnmatchedFeedback +} + +func (o *One) GetMaxMatchedCompletions() *int64 { + if o == nil { + return nil + } + return o.MaxMatchedCompletions +} + +func (o *One) GetCompletionTagsSelector() []string { + if o == nil { + return []string{} + } + return o.CompletionTagsSelector +} + +type UploadRequestBodyType string + +const ( + UploadRequestBodyTypeOne UploadRequestBodyType = "1" + UploadRequestBodyTypeTwo UploadRequestBodyType = "2" +) + +type UploadRequestBody struct { + One *One + Two *Two + + Type UploadRequestBodyType +} + +func CreateUploadRequestBodyOne(one One) UploadRequestBody { + typ := UploadRequestBodyTypeOne + + return UploadRequestBody{ + One: &one, + Type: typ, + } +} + +func CreateUploadRequestBodyTwo(two Two) UploadRequestBody { + typ := UploadRequestBodyTypeTwo + + return UploadRequestBody{ + Two: &two, + Type: typ, + } +} + +func (u *UploadRequestBody) UnmarshalJSON(data []byte) error { + + var two Two = Two{} + if err := utils.UnmarshalJSON(data, &two, "", true, true); err == nil { + u.Two = &two + u.Type = UploadRequestBodyTypeTwo + return nil + } + + var one One = One{} + if err := utils.UnmarshalJSON(data, &one, "", true, true); err == nil { + u.One = &one + u.Type = UploadRequestBodyTypeOne + return nil + } + + return fmt.Errorf("could not unmarshal `%s` into any supported union types for UploadRequestBody", string(data)) +} + +func (u UploadRequestBody) MarshalJSON() ([]byte, error) { + if u.One != nil { + return utils.MarshalJSON(u.One, "", true) + } + + if u.Two != nil { + return utils.MarshalJSON(u.Two, "", true) + } + + return nil, errors.New("could not marshal union type UploadRequestBody: all fields are null") +} + +type UploadRequest struct { + XLog10Organization *string `header:"style=simple,explode=false,name=X-Log10-Organization"` + RequestBody UploadRequestBody `request:"mediaType=application/json"` +} + +func (o *UploadRequest) GetXLog10Organization() *string { + if o == nil { + return nil + } + return o.XLog10Organization +} + +func (o *UploadRequest) GetRequestBody() UploadRequestBody { + if o == nil { + return UploadRequestBody{} + } + return o.RequestBody +} + +type UploadResponse struct { + HTTPMeta components.HTTPMetadata `json:"-"` + // OK + Feedback *components.Feedback +} + +func (o *UploadResponse) GetHTTPMeta() components.HTTPMetadata { + if o == nil { + return components.HTTPMetadata{} + } + return o.HTTPMeta +} + +func (o *UploadResponse) GetFeedback() *components.Feedback { + if o == nil { + return nil + } + return o.Feedback +} diff --git a/models/sdkerrors/sdkerror.go b/models/sdkerrors/sdkerror.go new file mode 100644 index 0000000..5c1affd --- /dev/null +++ b/models/sdkerrors/sdkerror.go @@ -0,0 +1,35 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package sdkerrors + +import ( + "fmt" + "net/http" +) + +type SDKError struct { + Message string + StatusCode int + Body string + RawResponse *http.Response +} + +var _ error = &SDKError{} + +func NewSDKError(message string, statusCode int, body string, httpRes *http.Response) *SDKError { + return &SDKError{ + Message: message, + StatusCode: statusCode, + Body: body, + RawResponse: httpRes, + } +} + +func (e *SDKError) Error() string { + body := "" + if len(e.Body) > 0 { + body = fmt.Sprintf("\n%s", e.Body) + } + + return fmt.Sprintf("%s: Status %d%s", e.Message, e.StatusCode, body) +} diff --git a/openai.yaml b/openai.yaml new file mode 100644 index 0000000..b0437f6 --- /dev/null +++ b/openai.yaml @@ -0,0 +1,13360 @@ +openapi: 3.0.0 +info: + title: OpenAI API + description: The OpenAI REST API. Please see https://platform.openai.com/docs/api-reference for more details. + version: "2.0.0" + termsOfService: https://openai.com/policies/terms-of-use + contact: + name: OpenAI Support + url: https://help.openai.com/ + license: + name: MIT + url: https://github.com/openai/openai-openapi/blob/master/LICENSE +servers: + - url: https://api.openai.com/v1 +tags: + - name: Assistants + description: Build Assistants that can call models and use tools. + - name: Audio + description: Learn how to turn audio into text or text into audio. + - name: Chat + description: Given a list of messages comprising a conversation, the model will return a response. + - name: Completions + description: Given a prompt, the model will return one or more predicted completions, and can also return the probabilities of alternative tokens at each position. + - name: Embeddings + description: Get a vector representation of a given input that can be easily consumed by machine learning models and algorithms. + - name: Fine-tuning + description: Manage fine-tuning jobs to tailor a model to your specific training data. + - name: Batch + description: Create large batches of API requests to run asynchronously. + - name: Files + description: Files are used to upload documents that can be used with features like Assistants and Fine-tuning. + - name: Images + description: Given a prompt and/or an input image, the model will generate a new image. + - name: Models + description: List and describe the various models available in the API. + - name: Moderations + description: Given a input text, outputs if the model classifies it as potentially harmful. +paths: + # Note: When adding an endpoint, make sure you also add it in the `groups` section, in the end of this file, + # under the appropriate group + /chat/completions: + post: + operationId: createChatCompletion + tags: + - Chat + summary: Creates a model response for the given chat conversation. + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/CreateChatCompletionRequest" + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/CreateChatCompletionResponse" + + x-oaiMeta: + name: Create chat completion + group: chat + returns: | + Returns a [chat completion](/docs/api-reference/chat/object) object, or a streamed sequence of [chat completion chunk](/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_model_id", + "messages": [ + { + "role": "system", + "content": "You are a helpful assistant." + }, + { + "role": "user", + "content": "Hello!" + } + ] + }' + python: | + from openai import OpenAI + client = OpenAI() + + completion = client.chat.completions.create( + model="VAR_model_id", + messages=[ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": "Hello!"} + ] + ) + + print(completion.choices[0].message) + node.js: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const completion = await openai.chat.completions.create({ + messages: [{ role: "system", content: "You are a helpful assistant." }], + model: "VAR_model_id", + }); + + console.log(completion.choices[0]); + } + + main(); + response: &chat_completion_example | + { + "id": "chatcmpl-123", + "object": "chat.completion", + "created": 1677652288, + "model": "gpt-3.5-turbo-0125", + "system_fingerprint": "fp_44709d6fcb", + "choices": [{ + "index": 0, + "message": { + "role": "assistant", + "content": "\n\nHello there, how may I assist you today?", + }, + "logprobs": null, + "finish_reason": "stop" + }], + "usage": { + "prompt_tokens": 9, + "completion_tokens": 12, + "total_tokens": 21 + } + } + - 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-turbo", + "messages": [ + { + "role": "user", + "content": [ + { + "type": "text", + "text": "What'\''s 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() + + response = client.chat.completions.create( + model="gpt-4-turbo", + messages=[ + { + "role": "user", + "content": [ + {"type": "text", "text": "What's in this image?"}, + { + "type": "image_url", + "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", + }, + ], + } + ], + max_tokens=300, + ) + + print(response.choices[0]) + node.js: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const response = await openai.chat.completions.create({ + model: "gpt-4-turbo", + messages: [ + { + role: "user", + content: [ + { type: "text", text: "What's in this image?" }, + { + type: "image_url", + 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.choices[0]); + } + main(); + response: &chat_completion_image_example | + { + "id": "chatcmpl-123", + "object": "chat.completion", + "created": 1677652288, + "model": "gpt-3.5-turbo-0125", + "system_fingerprint": "fp_44709d6fcb", + "choices": [{ + "index": 0, + "message": { + "role": "assistant", + "content": "\n\nThis image shows a wooden boardwalk extending through a lush green marshland.", + }, + "logprobs": null, + "finish_reason": "stop" + }], + "usage": { + "prompt_tokens": 9, + "completion_tokens": 12, + "total_tokens": 21 + } + } + - 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_model_id", + "messages": [ + { + "role": "system", + "content": "You are a helpful assistant." + }, + { + "role": "user", + "content": "Hello!" + } + ], + "stream": true + }' + python: | + from openai import OpenAI + client = OpenAI() + + completion = client.chat.completions.create( + model="VAR_model_id", + messages=[ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": "Hello!"} + ], + stream=True + ) + + for chunk in completion: + print(chunk.choices[0].delta) + + node.js: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const completion = await openai.chat.completions.create({ + model: "VAR_model_id", + messages: [ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": "Hello!"} + ], + stream: true, + }); + + for await (const chunk of completion) { + console.log(chunk.choices[0].delta.content); + } + } + + main(); + response: &chat_completion_chunk_example | + {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1694268190,"model":"gpt-3.5-turbo-0125", "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-3.5-turbo-0125", "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-3.5-turbo-0125", "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-turbo", + "messages": [ + { + "role": "user", + "content": "What'\''s 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() + + 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"], + }, + } + } + ] + messages = [{"role": "user", "content": "What's the weather like in Boston today?"}] + completion = client.chat.completions.create( + model="VAR_model_id", + messages=messages, + tools=tools, + tool_choice="auto" + ) + + print(completion) + node.js: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const messages = [{"role": "user", "content": "What's the weather like in Boston today?"}]; + const 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"], + }, + } + } + ]; + + const response = await openai.chat.completions.create({ + model: "gpt-4-turbo", + messages: messages, + tools: tools, + tool_choice: "auto", + }); + + console.log(response); + } + + main(); + response: &chat_completion_function_example | + { + "id": "chatcmpl-abc123", + "object": "chat.completion", + "created": 1699896916, + "model": "gpt-3.5-turbo-0125", + "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 + } + } + - 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_model_id", + "messages": [ + { + "role": "user", + "content": "Hello!" + } + ], + "logprobs": true, + "top_logprobs": 2 + }' + python: | + from openai import OpenAI + client = OpenAI() + + completion = client.chat.completions.create( + model="VAR_model_id", + messages=[ + {"role": "user", "content": "Hello!"} + ], + logprobs=True, + top_logprobs=2 + ) + + print(completion.choices[0].message) + print(completion.choices[0].logprobs) + node.js: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const completion = await openai.chat.completions.create({ + messages: [{ role: "user", content: "Hello!" }], + model: "VAR_model_id", + logprobs: true, + top_logprobs: 2, + }); + + console.log(completion.choices[0]); + } + + main(); + response: | + { + "id": "chatcmpl-123", + "object": "chat.completion", + "created": 1702685778, + "model": "gpt-3.5-turbo-0125", + "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 + }, + "system_fingerprint": null + } + + /completions: + post: + operationId: createCompletion + tags: + - Completions + summary: Creates a completion for the provided prompt and parameters. + 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](/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_model_id", + "prompt": "Say this is a test", + "max_tokens": 7, + "temperature": 0 + }' + python: | + from openai import OpenAI + client = OpenAI() + + client.completions.create( + model="VAR_model_id", + prompt="Say this is a test", + max_tokens=7, + temperature=0 + ) + node.js: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const completion = await openai.completions.create({ + model: "VAR_model_id", + prompt: "Say this is a test.", + max_tokens: 7, + temperature: 0, + }); + + console.log(completion); + } + main(); + response: | + { + "id": "cmpl-uqkvlQyYK7bGYrRHQ0eXlWi7", + "object": "text_completion", + "created": 1589478378, + "model": "VAR_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_model_id", + "prompt": "Say this is a test", + "max_tokens": 7, + "temperature": 0, + "stream": true + }' + python: | + from openai import OpenAI + client = OpenAI() + + for chunk in client.completions.create( + model="VAR_model_id", + prompt="Say this is a test", + max_tokens=7, + temperature=0, + stream=True + ): + print(chunk.choices[0].text) + node.js: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const stream = await openai.completions.create({ + model: "VAR_model_id", + prompt: "Say this is a test.", + stream: true, + }); + + for await (const chunk of stream) { + console.log(chunk.choices[0].text) + } + } + main(); + 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", + } + + /images/generations: + post: + operationId: createImage + tags: + - Images + summary: Creates an image given a prompt. + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/CreateImageRequest" + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/ImagesResponse" + x-oaiMeta: + name: Create image + group: images + returns: Returns a list of [image](/docs/api-reference/images/object) objects. + examples: + request: + curl: | + curl https://api.openai.com/v1/images/generations \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -d '{ + "model": "dall-e-3", + "prompt": "A cute baby sea otter", + "n": 1, + "size": "1024x1024" + }' + python: | + from openai import OpenAI + client = OpenAI() + + client.images.generate( + model="dall-e-3", + prompt="A cute baby sea otter", + n=1, + size="1024x1024" + ) + node.js: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const image = await openai.images.generate({ model: "dall-e-3", prompt: "A cute baby sea otter" }); + + console.log(image.data); + } + main(); + response: | + { + "created": 1589478378, + "data": [ + { + "url": "https://..." + }, + { + "url": "https://..." + } + ] + } + /images/edits: + post: + operationId: createImageEdit + tags: + - Images + summary: Creates an edited or extended image given an original image and a prompt. + requestBody: + required: true + content: + multipart/form-data: + schema: + $ref: "#/components/schemas/CreateImageEditRequest" + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/ImagesResponse" + x-oaiMeta: + name: Create image edit + group: images + returns: Returns a list of [image](/docs/api-reference/images/object) objects. + examples: + request: + curl: | + curl https://api.openai.com/v1/images/edits \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -F image="@otter.png" \ + -F mask="@mask.png" \ + -F prompt="A cute baby sea otter wearing a beret" \ + -F n=2 \ + -F size="1024x1024" + python: | + from openai import OpenAI + client = OpenAI() + + client.images.edit( + image=open("otter.png", "rb"), + mask=open("mask.png", "rb"), + prompt="A cute baby sea otter wearing a beret", + n=2, + size="1024x1024" + ) + node.js: |- + import fs from "fs"; + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const image = await openai.images.edit({ + image: fs.createReadStream("otter.png"), + mask: fs.createReadStream("mask.png"), + prompt: "A cute baby sea otter wearing a beret", + }); + + console.log(image.data); + } + main(); + response: | + { + "created": 1589478378, + "data": [ + { + "url": "https://..." + }, + { + "url": "https://..." + } + ] + } + /images/variations: + post: + operationId: createImageVariation + tags: + - Images + summary: Creates a variation of a given image. + 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](/docs/api-reference/images/object) objects. + examples: + 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() + + response = client.images.create_variation( + image=open("image_edit_original.png", "rb"), + n=2, + size="1024x1024" + ) + node.js: |- + import fs from "fs"; + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const image = await openai.images.createVariation({ + image: fs.createReadStream("otter.png"), + }); + + console.log(image.data); + } + main(); + response: | + { + "created": 1589478378, + "data": [ + { + "url": "https://..." + }, + { + "url": "https://..." + } + ] + } + + /embeddings: + post: + operationId: createEmbedding + tags: + - Embeddings + summary: Creates an embedding vector representing the input text. + 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](/docs/api-reference/embeddings/object) objects. + examples: + 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() + + client.embeddings.create( + model="text-embedding-ada-002", + input="The food was delicious and the waiter...", + encoding_format="float" + ) + node.js: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const embedding = await openai.embeddings.create({ + model: "text-embedding-ada-002", + input: "The quick brown fox jumped over the lazy dog", + encoding_format: "float", + }); + + console.log(embedding); + } + + main(); + 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 + } + } + + /audio/speech: + post: + operationId: createSpeech + tags: + - Audio + summary: Generates audio from the input text. + 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 + x-oaiMeta: + name: Create speech + group: audio + returns: The audio file content. + examples: + request: + curl: | + curl https://api.openai.com/v1/audio/speech \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "model": "tts-1", + "input": "The quick brown fox jumped over the lazy dog.", + "voice": "alloy" + }' \ + --output speech.mp3 + python: | + from pathlib import Path + import openai + + speech_file_path = Path(__file__).parent / "speech.mp3" + response = openai.audio.speech.create( + model="tts-1", + voice="alloy", + input="The quick brown fox jumped over the lazy dog." + ) + response.stream_to_file(speech_file_path) + node: | + 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: "tts-1", + 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(); + /audio/transcriptions: + post: + operationId: createTranscription + tags: + - Audio + summary: Transcribes audio into the input language. + requestBody: + required: true + content: + multipart/form-data: + schema: + $ref: "#/components/schemas/CreateTranscriptionRequest" + responses: + "200": + description: OK + content: + application/json: + schema: + oneOf: + - $ref: "#/components/schemas/CreateTranscriptionResponseJson" + - $ref: "#/components/schemas/CreateTranscriptionResponseVerboseJson" + x-oaiMeta: + name: Create transcription + group: audio + returns: The [transcription object](/docs/api-reference/audio/json-object) or a [verbose transcription object](/docs/api-reference/audio/verbose-json-object). + 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="whisper-1" + python: | + from openai import OpenAI + client = OpenAI() + + audio_file = open("speech.mp3", "rb") + transcript = client.audio.transcriptions.create( + model="whisper-1", + file=audio_file + ) + node: | + 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", + }); + + console.log(transcription.text); + } + main(); + response: &basic_transcription_response_example | + { + "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." + } + - 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() + + audio_file = open("speech.mp3", "rb") + transcript = client.audio.transcriptions.create( + file=audio_file, + model="whisper-1", + response_format="verbose_json", + timestamp_granularities=["word"] + ) + + print(transcript.words) + node: | + 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(); + 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 + } + ] + } + - 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() + + audio_file = open("speech.mp3", "rb") + transcript = client.audio.transcriptions.create( + file=audio_file, + model="whisper-1", + response_format="verbose_json", + timestamp_granularities=["segment"] + ) + + print(transcript.words) + node: | + 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(); + response: &verbose_transcription_response_example | + { + "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 + }, + ... + ] + } + /audio/translations: + post: + operationId: createTranslation + tags: + - Audio + summary: Translates audio into English. + requestBody: + required: true + content: + multipart/form-data: + schema: + $ref: "#/components/schemas/CreateTranslationRequest" + responses: + "200": + description: OK + content: + application/json: + schema: + oneOf: + - $ref: "#/components/schemas/CreateTranslationResponseJson" + - $ref: "#/components/schemas/CreateTranslationResponseVerboseJson" + x-oaiMeta: + name: Create translation + group: audio + returns: The translated text. + examples: + 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() + + audio_file = open("speech.mp3", "rb") + transcript = client.audio.translations.create( + model="whisper-1", + file=audio_file + ) + node: | + 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(); + response: | + { + "text": "Hello, my name is Wolfgang and I come from Germany. Where are you heading today?" + } + + /files: + get: + operationId: listFiles + tags: + - Files + summary: Returns a list of files that belong to the user's organization. + parameters: + - in: query + name: purpose + required: false + schema: + type: string + description: Only return files with the given purpose. + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/ListFilesResponse" + x-oaiMeta: + name: List files + group: files + returns: A list of [File](/docs/api-reference/files/object) objects. + examples: + request: + curl: | + curl https://api.openai.com/v1/files \ + -H "Authorization: Bearer $OPENAI_API_KEY" + python: | + from openai import OpenAI + client = OpenAI() + + client.files.list() + node.js: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const list = await openai.files.list(); + + for await (const file of list) { + console.log(file); + } + } + + main(); + response: | + { + "data": [ + { + "id": "file-abc123", + "object": "file", + "bytes": 175, + "created_at": 1613677385, + "filename": "salesOverview.pdf", + "purpose": "assistants", + }, + { + "id": "file-abc123", + "object": "file", + "bytes": 140, + "created_at": 1613779121, + "filename": "puppy.jsonl", + "purpose": "fine-tune", + } + ], + "object": "list" + } + post: + operationId: createFile + tags: + - Files + summary: | + Upload a file that can be used across various endpoints. The size of all the files uploaded by one organization can be up to 100 GB. + + The size of individual files can be a maximum of 512 MB or 2 million tokens for Assistants. See the [Assistants Tools guide](/docs/assistants/tools) to learn more about the types of files supported. The Fine-tuning API only supports `.jsonl` files. + + Please [contact us](https://help.openai.com/) if you need to increase these storage limits. + 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](/docs/api-reference/files/object) object. + examples: + request: + curl: | + curl https://api.openai.com/v1/files \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -F purpose="fine-tune" \ + -F file="@mydata.jsonl" + python: | + from openai import OpenAI + client = OpenAI() + + client.files.create( + file=open("mydata.jsonl", "rb"), + purpose="fine-tune" + ) + node.js: |- + import fs from "fs"; + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const file = await openai.files.create({ + file: fs.createReadStream("mydata.jsonl"), + purpose: "fine-tune", + }); + + console.log(file); + } + + main(); + response: | + { + "id": "file-abc123", + "object": "file", + "bytes": 120000, + "created_at": 1677610602, + "filename": "mydata.jsonl", + "purpose": "fine-tune", + } + /files/{file_id}: + delete: + operationId: deleteFile + tags: + - Files + summary: Delete a 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: + 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() + + client.files.delete("file-abc123") + node.js: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const file = await openai.files.del("file-abc123"); + + console.log(file); + } + + main(); + response: | + { + "id": "file-abc123", + "object": "file", + "deleted": true + } + get: + operationId: retrieveFile + tags: + - Files + summary: Returns information about a specific 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](/docs/api-reference/files/object) object matching the specified ID. + examples: + request: + curl: | + curl https://api.openai.com/v1/files/file-abc123 \ + -H "Authorization: Bearer $OPENAI_API_KEY" + python: | + from openai import OpenAI + client = OpenAI() + + client.files.retrieve("file-abc123") + node.js: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const file = await openai.files.retrieve("file-abc123"); + + console.log(file); + } + + main(); + response: | + { + "id": "file-abc123", + "object": "file", + "bytes": 120000, + "created_at": 1677610602, + "filename": "mydata.jsonl", + "purpose": "fine-tune", + } + /files/{file_id}/content: + get: + operationId: downloadFile + tags: + - Files + summary: Returns the contents of the specified 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: + type: string + x-oaiMeta: + name: Retrieve file content + group: files + returns: The file content. + examples: + 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() + + content = client.files.content("file-abc123") + node.js: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const file = await openai.files.content("file-abc123"); + + console.log(file); + } + + main(); + + /fine_tuning/jobs: + post: + operationId: createFineTuningJob + tags: + - Fine-tuning + summary: | + 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](/docs/guides/fine-tuning) + 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](/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-3.5-turbo" + }' + python: | + from openai import OpenAI + client = OpenAI() + + client.fine_tuning.jobs.create( + training_file="file-abc123", + model="gpt-3.5-turbo" + ) + node.js: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const fineTune = await openai.fineTuning.jobs.create({ + training_file: "file-abc123" + }); + + console.log(fineTune); + } + + main(); + response: | + { + "object": "fine_tuning.job", + "id": "ftjob-abc123", + "model": "gpt-3.5-turbo-0125", + "created_at": 1614807352, + "fine_tuned_model": null, + "organization_id": "org-123", + "result_files": [], + "status": "queued", + "validation_file": null, + "training_file": "file-abc123", + } + - 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-3.5-turbo", + "hyperparameters": { + "n_epochs": 2 + } + }' + python: | + from openai import OpenAI + client = OpenAI() + + client.fine_tuning.jobs.create( + training_file="file-abc123", + model="gpt-3.5-turbo", + hyperparameters={ + "n_epochs":2 + } + ) + node.js: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const fineTune = await openai.fineTuning.jobs.create({ + training_file: "file-abc123", + model: "gpt-3.5-turbo", + hyperparameters: { n_epochs: 2 } + }); + + console.log(fineTune); + } + + main(); + response: | + { + "object": "fine_tuning.job", + "id": "ftjob-abc123", + "model": "gpt-3.5-turbo-0125", + "created_at": 1614807352, + "fine_tuned_model": null, + "organization_id": "org-123", + "result_files": [], + "status": "queued", + "validation_file": null, + "training_file": "file-abc123", + "hyperparameters": {"n_epochs": 2}, + } + - 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-3.5-turbo" + }' + python: | + from openai import OpenAI + client = OpenAI() + + client.fine_tuning.jobs.create( + training_file="file-abc123", + validation_file="file-def456", + model="gpt-3.5-turbo" + ) + node.js: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const fineTune = await openai.fineTuning.jobs.create({ + training_file: "file-abc123", + validation_file: "file-abc123" + }); + + console.log(fineTune); + } + + main(); + response: | + { + "object": "fine_tuning.job", + "id": "ftjob-abc123", + "model": "gpt-3.5-turbo-0125", + "created_at": 1614807352, + "fine_tuned_model": null, + "organization_id": "org-123", + "result_files": [], + "status": "queued", + "validation_file": "file-abc123", + "training_file": "file-abc123", + } + - 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-3.5-turbo", + "integrations": [ + { + "type": "wandb", + "wandb": { + "project": "my-wandb-project", + "name": "ft-run-display-name" + "tags": [ + "first-experiment", "v2" + ] + } + } + ] + }' + response: | + { + "object": "fine_tuning.job", + "id": "ftjob-abc123", + "model": "gpt-3.5-turbo-0125", + "created_at": 1614807352, + "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" + } + } + ] + } + get: + operationId: listPaginatedFineTuningJobs + tags: + - Fine-tuning + summary: | + List your organization's 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 + 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](/docs/api-reference/fine-tuning/object) objects. + examples: + request: + curl: | + curl https://api.openai.com/v1/fine_tuning/jobs?limit=2 \ + -H "Authorization: Bearer $OPENAI_API_KEY" + python: | + from openai import OpenAI + client = OpenAI() + + client.fine_tuning.jobs.list() + node.js: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const list = await openai.fineTuning.jobs.list(); + + for await (const fineTune of list) { + console.log(fineTune); + } + } + + main(); + response: | + { + "object": "list", + "data": [ + { + "object": "fine_tuning.job.event", + "id": "ft-event-TjX0lMfOniCZX64t9PUQT5hn", + "created_at": 1689813489, + "level": "warn", + "message": "Fine tuning process stopping due to job cancellation", + "data": null, + "type": "message" + }, + { ... }, + { ... } + ], "has_more": true + } + /fine_tuning/jobs/{fine_tuning_job_id}: + get: + operationId: retrieveFineTuningJob + tags: + - Fine-tuning + summary: | + Get info about a fine-tuning job. + + [Learn more about fine-tuning](/docs/guides/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. + 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](/docs/api-reference/fine-tuning/object) object with the given ID. + examples: + 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() + + client.fine_tuning.jobs.retrieve("ftjob-abc123") + node.js: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const fineTune = await openai.fineTuning.jobs.retrieve("ftjob-abc123"); + + console.log(fineTune); + } + + main(); + response: &fine_tuning_example | + { + "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 + } + /fine_tuning/jobs/{fine_tuning_job_id}/events: + get: + operationId: listFineTuningEvents + tags: + - Fine-tuning + summary: | + Get status updates for a 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 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: + 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() + + client.fine_tuning.jobs.list_events( + fine_tuning_job_id="ftjob-abc123", + limit=2 + ) + node.js: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const list = await openai.fineTuning.list_events(id="ftjob-abc123", limit=2); + + for await (const fineTune of list) { + console.log(fineTune); + } + } + + main(); + response: | + { + "object": "list", + "data": [ + { + "object": "fine_tuning.job.event", + "id": "ft-event-ddTJfwuMVpfLXseO0Am0Gqjm", + "created_at": 1692407401, + "level": "info", + "message": "Fine tuning job successfully completed", + "data": null, + "type": "message" + }, + { + "object": "fine_tuning.job.event", + "id": "ft-event-tyiGuB72evQncpH87xe505Sv", + "created_at": 1692407400, + "level": "info", + "message": "New fine-tuned model created: ft:gpt-3.5-turbo:openai::7p4lURel", + "data": null, + "type": "message" + } + ], + "has_more": true + } + /fine_tuning/jobs/{fine_tuning_job_id}/cancel: + post: + operationId: cancelFineTuningJob + tags: + - Fine-tuning + summary: | + Immediately cancel a fine-tune 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 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](/docs/api-reference/fine-tuning/object) object. + examples: + 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() + + client.fine_tuning.jobs.cancel("ftjob-abc123") + node.js: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const fineTune = await openai.fineTuning.jobs.cancel("ftjob-abc123"); + + console.log(fineTune); + } + main(); + response: | + { + "object": "fine_tuning.job", + "id": "ftjob-abc123", + "model": "gpt-3.5-turbo-0125", + "created_at": 1689376978, + "fine_tuned_model": null, + "organization_id": "org-123", + "result_files": [], + "hyperparameters": { + "n_epochs": "auto" + }, + "status": "cancelled", + "validation_file": "file-abc123", + "training_file": "file-abc123" + } + /fine_tuning/jobs/{fine_tuning_job_id}/checkpoints: + get: + operationId: listFineTuningJobCheckpoints + tags: + - Fine-tuning + summary: | + List checkpoints for a 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 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](/docs/api-reference/fine-tuning/checkpoint-object) for a fine-tuning job. + examples: + request: + curl: | + curl https://api.openai.com/v1/fine_tuning/jobs/ftjob-abc123/checkpoints \ + -H "Authorization: Bearer $OPENAI_API_KEY" + response: | + { + "object": "list" + "data": [ + { + "object": "fine_tuning.job.checkpoint", + "id": "ftckpt_zc4Q7MP6XxulcVzj4MZdwsAB", + "created_at": 1519129973, + "fine_tuned_model_checkpoint": "ft:gpt-3.5-turbo-0125: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": 1519129833, + "fine_tuned_model_checkpoint": "ft:gpt-3.5-turbo-0125: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 + } + + /models: + get: + operationId: listModels + tags: + - Models + summary: Lists the currently available models, and provides basic information about each one such as the owner and availability. + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/ListModelsResponse" + x-oaiMeta: + name: List models + group: models + returns: A list of [model](/docs/api-reference/models/object) objects. + examples: + request: + curl: | + curl https://api.openai.com/v1/models \ + -H "Authorization: Bearer $OPENAI_API_KEY" + python: | + from openai import OpenAI + client = OpenAI() + + client.models.list() + node.js: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const list = await openai.models.list(); + + for await (const model of list) { + console.log(model); + } + } + main(); + 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" + } + /models/{model}: + get: + operationId: retrieveModel + tags: + - Models + summary: Retrieves a model instance, providing basic information about the model such as the owner and permissioning. + parameters: + - in: path + name: model + required: true + schema: + type: string + # ideally this will be an actual ID, so this will always work from browser + example: gpt-3.5-turbo + 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](/docs/api-reference/models/object) object matching the specified ID. + examples: + request: + curl: | + curl https://api.openai.com/v1/models/VAR_model_id \ + -H "Authorization: Bearer $OPENAI_API_KEY" + python: | + from openai import OpenAI + client = OpenAI() + + client.models.retrieve("VAR_model_id") + node.js: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const model = await openai.models.retrieve("VAR_model_id"); + + console.log(model); + } + + main(); + response: &retrieve_model_response | + { + "id": "VAR_model_id", + "object": "model", + "created": 1686935002, + "owned_by": "openai" + } + delete: + operationId: deleteModel + tags: + - Models + summary: Delete a fine-tuned model. You must have the Owner role in your organization to delete a model. + parameters: + - in: path + name: model + required: true + schema: + type: string + example: ft:gpt-3.5-turbo: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: + request: + curl: | + curl https://api.openai.com/v1/models/ft:gpt-3.5-turbo:acemeco:suffix:abc123 \ + -X DELETE \ + -H "Authorization: Bearer $OPENAI_API_KEY" + python: | + from openai import OpenAI + client = OpenAI() + + client.models.delete("ft:gpt-3.5-turbo:acemeco:suffix:abc123") + node.js: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const model = await openai.models.del("ft:gpt-3.5-turbo:acemeco:suffix:abc123"); + + console.log(model); + } + main(); + response: | + { + "id": "ft:gpt-3.5-turbo:acemeco:suffix:abc123", + "object": "model", + "deleted": true + } + + /moderations: + post: + operationId: createModeration + tags: + - Moderations + summary: Classifies if text is potentially harmful. + 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](/docs/api-reference/moderations/object) object. + examples: + 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() + + moderation = client.moderations.create(input="I want to kill them.") + print(moderation) + node.js: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const moderation = await openai.moderations.create({ input: "I want to kill them." }); + + console.log(moderation); + } + main(); + response: &moderation_example | + { + "id": "modr-XXXXX", + "model": "text-moderation-005", + "results": [ + { + "flagged": true, + "categories": { + "sexual": false, + "hate": false, + "harassment": false, + "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": 1.2282071e-06, + "hate": 0.010696256, + "harassment": 0.29842457, + "self-harm": 1.5236925e-08, + "sexual/minors": 5.7246268e-08, + "hate/threatening": 0.0060676364, + "violence/graphic": 4.435014e-06, + "self-harm/intent": 8.098441e-10, + "self-harm/instructions": 2.8498655e-11, + "harassment/threatening": 0.63055265, + "violence": 0.99011886, + } + } + ] + } + + /assistants: + get: + operationId: listAssistants + tags: + - Assistants + summary: Returns a list of assistants. + parameters: + - name: limit + in: query + description: &pagination_limit_param_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: &pagination_order_param_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: &pagination_after_param_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: &pagination_before_param_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, ending 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](/docs/api-reference/assistants/object) objects. + examples: + 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() + + my_assistants = client.beta.assistants.list( + order="desc", + limit="20", + ) + print(my_assistants.data) + node.js: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const myAssistants = await openai.beta.assistants.list({ + order: "desc", + limit: "20", + }); + + console.log(myAssistants.data); + } + + main(); + response: &list_assistants_example | + { + "object": "list", + "data": [ + { + "id": "asst_abc123", + "object": "assistant", + "created_at": 1698982736, + "name": "Coding Tutor", + "description": null, + "model": "gpt-4-turbo", + "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-4-turbo", + "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-4-turbo", + "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 + } + post: + operationId: createAssistant + tags: + - Assistants + summary: Create an assistant with a model and instructions. + 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](/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-4-turbo" + }' + + python: | + from openai import OpenAI + client = OpenAI() + + my_assistant = client.beta.assistants.create( + 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-4-turbo", + ) + print(my_assistant) + node.js: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const myAssistant = await openai.beta.assistants.create({ + 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-4-turbo", + }); + + console.log(myAssistant); + } + + main(); + response: &create_assistants_example | + { + "id": "asst_abc123", + "object": "assistant", + "created_at": 1698984975, + "name": "Math Tutor", + "description": null, + "model": "gpt-4-turbo", + "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-4-turbo" + }' + python: | + from openai import OpenAI + client = OpenAI() + + my_assistant = client.beta.assistants.create( + instructions="You are an HR bot, and you have access to files to answer employee questions about company policies.", + name="HR Helper", + tools=[{"type": "file_search"}], + tool_resources={"file_search": {"vector_store_ids": ["vs_123"]}}, + model="gpt-4-turbo" + ) + print(my_assistant) + node.js: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const myAssistant = await openai.beta.assistants.create({ + instructions: + "You are an HR bot, and you have access to files to answer employee questions about company policies.", + name: "HR Helper", + tools: [{ type: "file_search" }], + tool_resources: { + file_search: { + vector_store_ids: ["vs_123"] + } + }, + model: "gpt-4-turbo" + }); + + console.log(myAssistant); + } + + main(); + response: | + { + "id": "asst_abc123", + "object": "assistant", + "created_at": 1699009403, + "name": "HR Helper", + "description": null, + "model": "gpt-4-turbo", + "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" + } + + /assistants/{assistant_id}: + get: + operationId: getAssistant + tags: + - Assistants + summary: Retrieves an 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](/docs/api-reference/assistants/object) object matching the specified ID. + examples: + 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() + + my_assistant = client.beta.assistants.retrieve("asst_abc123") + print(my_assistant) + node.js: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const myAssistant = await openai.beta.assistants.retrieve( + "asst_abc123" + ); + + console.log(myAssistant); + } + + main(); + response: | + { + "id": "asst_abc123", + "object": "assistant", + "created_at": 1699009709, + "name": "HR Helper", + "description": null, + "model": "gpt-4-turbo", + "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" + } + post: + operationId: modifyAssistant + tags: + - Assistants + summary: Modifies an 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](/docs/api-reference/assistants/object) object. + examples: + 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-4-turbo" + }' + python: | + from openai import OpenAI + client = OpenAI() + + my_updated_assistant = client.beta.assistants.update( + "asst_abc123", + 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.", + name="HR Helper", + tools=[{"type": "file_search"}], + model="gpt-4-turbo" + ) + + print(my_updated_assistant) + node.js: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const myUpdatedAssistant = await openai.beta.assistants.update( + "asst_abc123", + { + 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.", + name: "HR Helper", + tools: [{ type: "file_search" }], + model: "gpt-4-turbo" + } + ); + + console.log(myUpdatedAssistant); + } + + main(); + response: | + { + "id": "asst_123", + "object": "assistant", + "created_at": 1699009709, + "name": "HR Helper", + "description": null, + "model": "gpt-4-turbo", + "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" + } + delete: + operationId: deleteAssistant + tags: + - Assistants + summary: Delete an 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: + 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() + + response = client.beta.assistants.delete("asst_abc123") + print(response) + node.js: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const response = await openai.beta.assistants.del("asst_abc123"); + + console.log(response); + } + main(); + response: | + { + "id": "asst_abc123", + "object": "assistant.deleted", + "deleted": true + } + + /threads: + post: + operationId: createThread + tags: + - Assistants + summary: Create a 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](/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() + + empty_thread = client.beta.threads.create() + print(empty_thread) + node.js: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const emptyThread = await openai.beta.threads.create(); + + console.log(emptyThread); + } + + main(); + 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() + + message_thread = client.beta.threads.create( + messages=[ + { + "role": "user", + "content": "Hello, what is AI?" + }, + { + "role": "user", + "content": "How does AI work? Explain it in simple terms." + }, + ] + ) + + print(message_thread) + node.js: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const messageThread = await openai.beta.threads.create({ + messages: [ + { + role: "user", + content: "Hello, what is AI?" + }, + { + role: "user", + content: "How does AI work? Explain it in simple terms.", + }, + ], + }); + + console.log(messageThread); + } + + main(); + response: | + { + "id": "thread_abc123", + "object": "thread", + "created_at": 1699014083, + "metadata": {}, + "tool_resources": {} + } + + /threads/{thread_id}: + get: + operationId: getThread + tags: + - Assistants + summary: Retrieves a 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](/docs/api-reference/threads/object) object matching the specified ID. + examples: + 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() + + my_thread = client.beta.threads.retrieve("thread_abc123") + print(my_thread) + node.js: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const myThread = await openai.beta.threads.retrieve( + "thread_abc123" + ); + + console.log(myThread); + } + + main(); + response: | + { + "id": "thread_abc123", + "object": "thread", + "created_at": 1699014083, + "metadata": {}, + "tool_resources": { + "code_interpreter": { + "file_ids": [] + } + } + } + post: + operationId: modifyThread + tags: + - Assistants + summary: Modifies a 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](/docs/api-reference/threads/object) object matching the specified ID. + examples: + 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() + + my_updated_thread = client.beta.threads.update( + "thread_abc123", + metadata={ + "modified": "true", + "user": "abc123" + } + ) + print(my_updated_thread) + node.js: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const updatedThread = await openai.beta.threads.update( + "thread_abc123", + { + metadata: { modified: "true", user: "abc123" }, + } + ); + + console.log(updatedThread); + } + + main(); + response: | + { + "id": "thread_abc123", + "object": "thread", + "created_at": 1699014083, + "metadata": { + "modified": "true", + "user": "abc123" + }, + "tool_resources": {} + } + delete: + operationId: deleteThread + tags: + - Assistants + summary: Delete a 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: + 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() + + response = client.beta.threads.delete("thread_abc123") + print(response) + node.js: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const response = await openai.beta.threads.del("thread_abc123"); + + console.log(response); + } + main(); + response: | + { + "id": "thread_abc123", + "object": "thread.deleted", + "deleted": true + } + + /threads/{thread_id}/messages: + get: + operationId: listMessages + tags: + - Assistants + summary: Returns a list of messages for a given thread. + parameters: + - in: path + name: thread_id + required: true + schema: + type: string + description: The ID of the [thread](/docs/api-reference/threads) the messages belong to. + - name: limit + in: query + description: *pagination_limit_param_description + required: false + schema: + type: integer + default: 20 + - name: order + in: query + description: *pagination_order_param_description + schema: + type: string + default: desc + enum: ["asc", "desc"] + - name: after + in: query + description: *pagination_after_param_description + schema: + type: string + - name: before + in: query + description: *pagination_before_param_description + 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](/docs/api-reference/messages) objects. + examples: + 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() + + thread_messages = client.beta.threads.messages.list("thread_abc123") + print(thread_messages.data) + node.js: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const threadMessages = await openai.beta.threads.messages.list( + "thread_abc123" + ); + + console.log(threadMessages.data); + } + + main(); + 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 + } + post: + operationId: createMessage + tags: + - Assistants + summary: Create a message. + parameters: + - in: path + name: thread_id + required: true + schema: + type: string + description: The ID of the [thread](/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](/docs/api-reference/messages/object) object. + examples: + 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() + + thread_message = client.beta.threads.messages.create( + "thread_abc123", + role="user", + content="How does AI work? Explain it in simple terms.", + ) + print(thread_message) + node.js: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const threadMessages = await openai.beta.threads.messages.create( + "thread_abc123", + { role: "user", content: "How does AI work? Explain it in simple terms." } + ); + + console.log(threadMessages); + } + + main(); + 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": {} + } + + /threads/{thread_id}/messages/{message_id}: + get: + operationId: getMessage + tags: + - Assistants + summary: Retrieve a message. + parameters: + - in: path + name: thread_id + required: true + schema: + type: string + description: The ID of the [thread](/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](/docs/api-reference/threads/messages/object) object matching the specified ID. + examples: + 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() + + message = client.beta.threads.messages.retrieve( + message_id="msg_abc123", + thread_id="thread_abc123", + ) + print(message) + node.js: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const message = await openai.beta.threads.messages.retrieve( + "thread_abc123", + "msg_abc123" + ); + + console.log(message); + } + + main(); + 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": {} + } + post: + operationId: modifyMessage + tags: + - Assistants + summary: Modifies a 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](/docs/api-reference/threads/messages/object) object. + examples: + 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() + + message = client.beta.threads.messages.update( + message_id="msg_abc12", + thread_id="thread_abc123", + metadata={ + "modified": "true", + "user": "abc123", + }, + ) + print(message) + node.js: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const message = await openai.beta.threads.messages.update( + "thread_abc123", + "msg_abc123", + { + metadata: { + modified: "true", + user: "abc123", + }, + } + }' + 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" + } + } + delete: + operationId: deleteMessage + tags: + - Assistants + summary: Deletes a 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: + 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() + + deleted_message = client.beta.threads.messages.delete( + message_id="msg_abc12", + thread_id="thread_abc123", + ) + print(deleted_message) + node.js: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const deletedMessage = await openai.beta.threads.messages.del( + "thread_abc123", + "msg_abc123" + ); + + console.log(deletedMessage); + } + response: | + { + "id": "msg_abc123", + "object": "thread.message.deleted", + "deleted": true + } + + + /threads/runs: + post: + operationId: createThreadAndRun + tags: + - Assistants + summary: Create a thread and run it in one request. + 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](/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() + + run = client.beta.threads.create_and_run( + assistant_id="asst_abc123", + thread={ + "messages": [ + {"role": "user", "content": "Explain deep learning to a 5 year old."} + ] + } + ) + + print(run) + node.js: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const run = await openai.beta.threads.createAndRun({ + assistant_id: "asst_abc123", + thread: { + messages: [ + { role: "user", content: "Explain deep learning to a 5 year old." }, + ], + }, + }); + + console.log(run); + } + + main(); + 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-4-turbo", + "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" + } + + - 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() + + stream = client.beta.threads.create_and_run( + assistant_id="asst_123", + thread={ + "messages": [ + {"role": "user", "content": "Hello"} + ] + }, + stream=True + ) + + for event in stream: + print(event) + node.js: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const stream = await openai.beta.threads.createAndRun({ + assistant_id: "asst_123", + thread: { + messages: [ + { role: "user", content: "Hello" }, + ], + }, + stream: true + }); + + for await (const event of stream) { + console.log(event); + } + } + + main(); + 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-4-turbo","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"} + + 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-4-turbo","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"} + + 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-4-turbo","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"} + + 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-4-turbo","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"} + + 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() + + 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 = client.beta.threads.create_and_run( + thread={ + "messages": [ + {"role": "user", "content": "What is the weather like in San Francisco?"} + ] + }, + assistant_id="asst_abc123", + tools=tools, + stream=True + ) + + for event in stream: + print(event) + node.js: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + const 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"], + }, + } + } + ]; + + async function main() { + const stream = await openai.beta.threads.createAndRun({ + assistant_id: "asst_123", + thread: { + messages: [ + { role: "user", content: "What is the weather like in San Francisco?" }, + ], + }, + tools: tools, + stream: true + }); + + for await (const event of stream) { + console.log(event); + } + } + + main(); + 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-4-turbo","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"}} + + 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-4-turbo","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"}} + + 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-4-turbo","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"}} + + 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-4-turbo","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"}} + + event: done + data: [DONE] + + /threads/{thread_id}/runs: + get: + operationId: listRuns + tags: + - Assistants + summary: Returns a list of runs belonging to a thread. + 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: *pagination_limit_param_description + required: false + schema: + type: integer + default: 20 + - name: order + in: query + description: *pagination_order_param_description + schema: + type: string + default: desc + enum: ["asc", "desc"] + - name: after + in: query + description: *pagination_after_param_description + schema: + type: string + - name: before + in: query + description: *pagination_before_param_description + 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](/docs/api-reference/runs/object) objects. + examples: + 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() + + runs = client.beta.threads.runs.list( + "thread_abc123" + ) + + print(runs) + node.js: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const runs = await openai.beta.threads.runs.list( + "thread_abc123" + ); + + console.log(runs); + } + + main(); + 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-4-turbo", + "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" + }, + { + "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-4-turbo", + "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" + } + ], + "first_id": "run_abc123", + "last_id": "run_abc456", + "has_more": false + } + post: + operationId: createRun + tags: + - Assistants + summary: Create a run. + parameters: + - in: path + name: thread_id + required: true + schema: + type: string + description: The ID of the thread to run. + 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](/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() + + run = client.beta.threads.runs.create( + thread_id="thread_abc123", + assistant_id="asst_abc123" + ) + + print(run) + node.js: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const run = await openai.beta.threads.runs.create( + "thread_abc123", + { assistant_id: "asst_abc123" } + ); + + console.log(run); + } + + main(); + response: &run_object_example | + { + "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-4-turbo", + "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" + } + - 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() + + stream = client.beta.threads.runs.create( + thread_id="thread_123", + assistant_id="asst_123", + stream=True + ) + + for event in stream: + print(event) + node.js: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const stream = await openai.beta.threads.runs.create( + "thread_123", + { assistant_id: "asst_123", stream: true } + ); + + for await (const event of stream) { + console.log(event); + } + } + + main(); + 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-4-turbo","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"}} + + 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-4-turbo","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"}} + + 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-4-turbo","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"}} + + 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-4-turbo","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"}} + + 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() + + 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 = client.beta.threads.runs.create( + thread_id="thread_abc123", + assistant_id="asst_abc123", + tools=tools, + stream=True + ) + + for event in stream: + print(event) + node.js: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + const 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"], + }, + } + } + ]; + + async function main() { + const stream = await openai.beta.threads.runs.create( + "thread_abc123", + { + assistant_id: "asst_abc123", + tools: tools, + stream: true + } + ); + + for await (const event of stream) { + console.log(event); + } + } + + main(); + 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-4-turbo","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"}} + + 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-4-turbo","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"}} + + 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-4-turbo","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"}} + + 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-4-turbo","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"}} + + event: done + data: [DONE] + + /threads/{thread_id}/runs/{run_id}: + get: + operationId: getRun + tags: + - Assistants + summary: Retrieves a run. + parameters: + - in: path + name: thread_id + required: true + schema: + type: string + description: The ID of the [thread](/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](/docs/api-reference/runs/object) object matching the specified ID. + examples: + 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() + + run = client.beta.threads.runs.retrieve( + thread_id="thread_abc123", + run_id="run_abc123" + ) + + print(run) + node.js: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const run = await openai.beta.threads.runs.retrieve( + "thread_abc123", + "run_abc123" + ); + + console.log(run); + } + + main(); + 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-4-turbo", + "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" + } + post: + operationId: modifyRun + tags: + - Assistants + summary: Modifies a run. + parameters: + - in: path + name: thread_id + required: true + schema: + type: string + description: The ID of the [thread](/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](/docs/api-reference/runs/object) object matching the specified ID. + examples: + 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() + + run = client.beta.threads.runs.update( + thread_id="thread_abc123", + run_id="run_abc123", + metadata={"user_id": "user_abc123"}, + ) + + print(run) + node.js: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const run = await openai.beta.threads.runs.update( + "thread_abc123", + "run_abc123", + { + metadata: { + user_id: "user_abc123", + }, + } + ); + + console.log(run); + } + + main(); + 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-4-turbo", + "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" + } + + /threads/{thread_id}/runs/{run_id}/submit_tool_outputs: + post: + operationId: submitToolOuputsToRun + tags: + - Assistants + summary: | + 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. + parameters: + - in: path + name: thread_id + required: true + schema: + type: string + description: The ID of the [thread](/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](/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() + + run = client.beta.threads.runs.submit_tool_outputs( + thread_id="thread_123", + run_id="run_123", + tool_outputs=[ + { + "tool_call_id": "call_001", + "output": "70 degrees and sunny." + } + ] + ) + + print(run) + node.js: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const run = await openai.beta.threads.runs.submitToolOutputs( + "thread_123", + "run_123", + { + tool_outputs: [ + { + tool_call_id: "call_001", + output: "70 degrees and sunny.", + }, + ], + } + ); + + console.log(run); + } + + main(); + 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-4-turbo", + "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" + } + + - 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() + + stream = client.beta.threads.runs.submit_tool_outputs( + thread_id="thread_123", + run_id="run_123", + tool_outputs=[ + { + "tool_call_id": "call_001", + "output": "70 degrees and sunny." + } + ], + stream=True + ) + + for event in stream: + print(event) + node.js: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const stream = await openai.beta.threads.runs.submitToolOutputs( + "thread_123", + "run_123", + { + tool_outputs: [ + { + tool_call_id: "call_001", + output: "70 degrees and sunny.", + }, + ], + } + ); + + for await (const event of stream) { + console.log(event); + } + } + + main(); + 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-4-turbo","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"}} + + 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-4-turbo","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"}} + + 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-4-turbo","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"}} + + event: done + data: [DONE] + + /threads/{thread_id}/runs/{run_id}/cancel: + post: + operationId: cancelRun + tags: + - Assistants + summary: Cancels a run that is `in_progress`. + 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](/docs/api-reference/runs/object) object matching the specified ID. + examples: + 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() + + run = client.beta.threads.runs.cancel( + thread_id="thread_abc123", + run_id="run_abc123" + ) + + print(run) + node.js: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const run = await openai.beta.threads.runs.cancel( + "thread_abc123", + "run_abc123" + ); + + console.log(run); + } + + main(); + 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-4-turbo", + "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" + } + + /threads/{thread_id}/runs/{run_id}/steps: + get: + operationId: listRunSteps + tags: + - Assistants + summary: Returns a list of run steps belonging to a run. + 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: *pagination_limit_param_description + required: false + schema: + type: integer + default: 20 + - name: order + in: query + description: *pagination_order_param_description + schema: + type: string + default: desc + enum: ["asc", "desc"] + - name: after + in: query + description: *pagination_after_param_description + schema: + type: string + - name: before + in: query + description: *pagination_before_param_description + schema: + type: string + 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](/docs/api-reference/runs/step-object) objects. + examples: + 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() + + run_steps = client.beta.threads.runs.steps.list( + thread_id="thread_abc123", + run_id="run_abc123" + ) + + print(run_steps) + node.js: | + import OpenAI from "openai"; + const openai = new OpenAI(); + + async function main() { + const runStep = await openai.beta.threads.runs.steps.list( + "thread_abc123", + "run_abc123" + ); + console.log(runStep); + } + + main(); + 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 + } + + /threads/{thread_id}/runs/{run_id}/steps/{step_id}: + get: + operationId: getRunStep + tags: + - Assistants + summary: Retrieves a 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. + 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](/docs/api-reference/runs/step-object) object matching the specified ID. + examples: + 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() + + run_step = client.beta.threads.runs.steps.retrieve( + thread_id="thread_abc123", + run_id="run_abc123", + step_id="step_abc123" + ) + + print(run_step) + node.js: | + import OpenAI from "openai"; + const openai = new OpenAI(); + + async function main() { + const runStep = await openai.beta.threads.runs.steps.retrieve( + "thread_abc123", + "run_abc123", + "step_abc123" + ); + console.log(runStep); + } + + main(); + response: &run_step_object_example | + { + "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 + } + } + + /vector_stores: + get: + operationId: listVectorStores + tags: + - Vector Stores + summary: Returns a list of vector stores. + parameters: + - name: limit + in: query + description: *pagination_limit_param_description + required: false + schema: + type: integer + default: 20 + - name: order + in: query + description: *pagination_order_param_description + schema: + type: string + default: desc + enum: ["asc", "desc"] + - name: after + in: query + description: *pagination_after_param_description + schema: + type: string + - name: before + in: query + description: *pagination_before_param_description + schema: + type: string + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/ListVectorStoresResponse" + x-oaiMeta: + name: List vector stores + group: vector_stores + beta: true + returns: A list of [vector store](/docs/api-reference/vector-stores/object) objects. + examples: + 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() + + vector_stores = client.beta.vector_stores.list() + print(vector_stores) + node.js: | + import OpenAI from "openai"; + const openai = new OpenAI(); + + async function main() { + const vectorStores = await openai.beta.vectorStores.list(); + console.log(vectorStores); + } + + main(); + 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 + } + post: + operationId: createVectorStore + tags: + - Vector Stores + summary: Create a 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 + beta: true + returns: A [vector store](/docs/api-reference/vector-stores/object) object. + examples: + 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() + + vector_store = client.beta.vector_stores.create( + name="Support FAQ" + ) + print(vector_store) + node.js: | + import OpenAI from "openai"; + const openai = new OpenAI(); + + async function main() { + const vectorStore = await openai.beta.vectorStores.create({ + name: "Support FAQ" + }); + console.log(vectorStore); + } + + main(); + 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 + } + } + + /vector_stores/{vector_store_id}: + get: + operationId: getVectorStore + tags: + - Vector Stores + summary: Retrieves a 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 + beta: true + returns: The [vector store](/docs/api-reference/vector-stores/object) object matching the specified ID. + examples: + 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() + + vector_store = client.beta.vector_stores.retrieve( + vector_store_id="vs_abc123" + ) + print(vector_store) + node.js: | + import OpenAI from "openai"; + const openai = new OpenAI(); + + async function main() { + const vectorStore = await openai.beta.vectorStores.retrieve( + "vs_abc123" + ); + console.log(vectorStore); + } + + main(); + response: | + { + "id": "vs_abc123", + "object": "vector_store", + "created_at": 1699061776 + } + post: + operationId: modifyVectorStore + tags: + - Vector Stores + summary: Modifies a 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 + beta: true + returns: The modified [vector store](/docs/api-reference/vector-stores/object) object. + examples: + 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() + + vector_store = client.beta.vector_stores.update( + vector_store_id="vs_abc123", + name="Support FAQ" + ) + print(vector_store) + node.js: | + import OpenAI from "openai"; + const openai = new OpenAI(); + + async function main() { + const vectorStore = await openai.beta.vectorStores.update( + "vs_abc123", + { + name: "Support FAQ" + } + ); + console.log(vectorStore); + } + + main(); + 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 + } + } + + delete: + operationId: deleteVectorStore + tags: + - Vector Stores + summary: Delete a 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 + beta: true + returns: Deletion status + examples: + 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() + + deleted_vector_store = client.beta.vector_stores.delete( + vector_store_id="vs_abc123" + ) + print(deleted_vector_store) + node.js: | + import OpenAI from "openai"; + const openai = new OpenAI(); + + async function main() { + const deletedVectorStore = await openai.beta.vectorStores.del( + "vs_abc123" + ); + console.log(deletedVectorStore); + } + + main(); + response: | + { + id: "vs_abc123", + object: "vector_store.deleted", + deleted: true + } + + /vector_stores/{vector_store_id}/files: + get: + operationId: listVectorStoreFiles + tags: + - Vector Stores + summary: Returns a list of 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: *pagination_limit_param_description + required: false + schema: + type: integer + default: 20 + - name: order + in: query + description: *pagination_order_param_description + schema: + type: string + default: desc + enum: ["asc", "desc"] + - name: after + in: query + description: *pagination_after_param_description + schema: + type: string + - name: before + in: query + description: *pagination_before_param_description + 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 + beta: true + returns: A list of [vector store file](/docs/api-reference/vector-stores-files/file-object) objects. + examples: + 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() + + vector_store_files = client.beta.vector_stores.files.list( + vector_store_id="vs_abc123" + ) + print(vector_store_files) + node.js: | + import OpenAI from "openai"; + const openai = new OpenAI(); + + async function main() { + const vectorStoreFiles = await openai.beta.vectorStores.files.list( + "vs_abc123" + ); + console.log(vectorStoreFiles); + } + + main(); + 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 + } + post: + operationId: createVectorStoreFile + tags: + - Vector Stores + summary: Create a vector store file by attaching a [File](/docs/api-reference/files) to a [vector store](/docs/api-reference/vector-stores/object). + 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 + beta: true + returns: A [vector store file](/docs/api-reference/vector-stores-files/file-object) object. + examples: + 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() + + vector_store_file = client.beta.vector_stores.files.create( + vector_store_id="vs_abc123", + file_id="file-abc123" + ) + print(vector_store_file) + node.js: | + import OpenAI from "openai"; + const openai = new OpenAI(); + + async function main() { + const myVectorStoreFile = await openai.beta.vectorStores.files.create( + "vs_abc123", + { + file_id: "file-abc123" + } + ); + console.log(myVectorStoreFile); + } + + main(); + response: | + { + "id": "file-abc123", + "object": "vector_store.file", + "created_at": 1699061776, + "usage_bytes": 1234, + "vector_store_id": "vs_abcd", + "status": "completed", + "last_error": null + } + + /vector_stores/{vector_store_id}/files/{file_id}: + get: + operationId: getVectorStoreFile + tags: + - Vector Stores + summary: Retrieves a 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 + beta: true + returns: The [vector store file](/docs/api-reference/vector-stores-files/file-object) object. + examples: + 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() + + vector_store_file = client.beta.vector_stores.files.retrieve( + vector_store_id="vs_abc123", + file_id="file-abc123" + ) + print(vector_store_file) + node.js: | + import OpenAI from "openai"; + const openai = new OpenAI(); + + async function main() { + const vectorStoreFile = await openai.beta.vectorStores.files.retrieve( + "vs_abc123", + "file-abc123" + ); + console.log(vectorStoreFile); + } + + main(); + response: | + { + "id": "file-abc123", + "object": "vector_store.file", + "created_at": 1699061776, + "vector_store_id": "vs_abcd", + "status": "completed", + "last_error": null + } + delete: + operationId: deleteVectorStoreFile + tags: + - Vector Stores + summary: 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](/docs/api-reference/files/delete) endpoint. + 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 + beta: true + returns: Deletion status + examples: + 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() + + deleted_vector_store_file = client.beta.vector_stores.files.delete( + vector_store_id="vs_abc123", + file_id="file-abc123" + ) + print(deleted_vector_store_file) + node.js: | + import OpenAI from "openai"; + const openai = new OpenAI(); + + async function main() { + const deletedVectorStoreFile = await openai.beta.vectorStores.files.del( + "vs_abc123", + "file-abc123" + ); + console.log(deletedVectorStoreFile); + } + + main(); + response: | + { + id: "file-abc123", + object: "vector_store.file.deleted", + deleted: true + } + + /vector_stores/{vector_store_id}/file_batches: + post: + operationId: createVectorStoreFileBatch + tags: + - Vector Stores + summary: Create a 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 + beta: true + returns: A [vector store file batch](/docs/api-reference/vector-stores-file-batches/batch-object) object. + examples: + 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() + + vector_store_file_batch = client.beta.vector_stores.file_batches.create( + vector_store_id="vs_abc123", + file_ids=["file-abc123", "file-abc456"] + ) + print(vector_store_file_batch) + node.js: | + import OpenAI from "openai"; + const openai = new OpenAI(); + + async function main() { + const myVectorStoreFileBatch = await openai.beta.vectorStores.fileBatches.create( + "vs_abc123", + { + file_ids: ["file-abc123", "file-abc456"] + } + ); + console.log(myVectorStoreFileBatch); + } + + main(); + 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, + } + } + + /vector_stores/{vector_store_id}/file_batches/{batch_id}: + get: + operationId: getVectorStoreFileBatch + tags: + - Vector Stores + summary: Retrieves a 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 + beta: true + returns: The [vector store file batch](/docs/api-reference/vector-stores-file-batches/batch-object) object. + examples: + 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() + + vector_store_file_batch = client.beta.vector_stores.file_batches.retrieve( + vector_store_id="vs_abc123", + batch_id="vsfb_abc123" + ) + print(vector_store_file_batch) + node.js: | + import OpenAI from "openai"; + const openai = new OpenAI(); + + async function main() { + const vectorStoreFileBatch = await openai.beta.vectorStores.fileBatches.retrieve( + "vs_abc123", + "vsfb_abc123" + ); + console.log(vectorStoreFileBatch); + } + + main(); + 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, + } + } + + /vector_stores/{vector_store_id}/file_batches/{batch_id}/cancel: + post: + operationId: cancelVectorStoreFileBatch + tags: + - Vector Stores + summary: Cancel a vector store file batch. This attempts to cancel the processing of files in this batch as soon as possible. + 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 + beta: true + returns: The modified vector store file batch object. + examples: + 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() + + deleted_vector_store_file_batch = client.beta.vector_stores.file_batches.cancel( + vector_store_id="vs_abc123", + file_batch_id="vsfb_abc123" + ) + print(deleted_vector_store_file_batch) + node.js: | + import OpenAI from "openai"; + const openai = new OpenAI(); + + async function main() { + const deletedVectorStoreFileBatch = await openai.vector_stores.fileBatches.cancel( + "vs_abc123", + "vsfb_abc123" + ); + console.log(deletedVectorStoreFileBatch); + } + + main(); + response: | + { + "id": "vsfb_abc123", + "object": "vector_store.file_batch", + "created_at": 1699061776, + "vector_store_id": "vs_abc123", + "status": "cancelling", + "file_counts": { + "in_progress": 12, + "completed": 3, + "failed": 0, + "cancelled": 0, + "total": 15, + } + } + + /vector_stores/{vector_store_id}/file_batches/{batch_id}/files: + get: + operationId: listFilesInVectorStoreBatch + tags: + - Vector Stores + summary: Returns a list of 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: *pagination_limit_param_description + required: false + schema: + type: integer + default: 20 + - name: order + in: query + description: *pagination_order_param_description + schema: + type: string + default: desc + enum: ["asc", "desc"] + - name: after + in: query + description: *pagination_after_param_description + schema: + type: string + - name: before + in: query + description: *pagination_before_param_description + 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 + beta: true + returns: A list of [vector store file](/docs/api-reference/vector-stores-files/file-object) objects. + examples: + 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() + + vector_store_files = client.beta.vector_stores.file_batches.list_files( + vector_store_id="vs_abc123", + batch_id="vsfb_abc123" + ) + print(vector_store_files) + node.js: | + import OpenAI from "openai"; + const openai = new OpenAI(); + + async function main() { + const vectorStoreFiles = await openai.beta.vectorStores.fileBatches.listFiles( + "vs_abc123", + "vsfb_abc123" + ); + console.log(vectorStoreFiles); + } + + main(); + 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 + } + + /batches: + post: + summary: Creates and executes a batch from an uploaded file of requests + 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](/docs/api-reference/files/create) for how to upload a file. + + Your input file must be formatted as a [JSONL file](/docs/api-reference/batch/requestInput), and must be uploaded with the purpose `batch`. + endpoint: + type: string + enum: ["/v1/chat/completions", "/v1/embeddings"] + description: The endpoint to be used for all requests in the batch. Currently `/v1/chat/completions` and `/v1/embeddings` are supported. + completion_window: + type: string + enum: ["24h"] + description: The time frame within which the batch should be processed. Currently only `24h` is supported. + metadata: + type: object + additionalProperties: + type: string + description: Optional custom metadata for the batch. + nullable: true + 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](/docs/api-reference/batch/object) object. + examples: + 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() + + client.batches.create( + input_file_id="file-abc123", + endpoint="/v1/chat/completions", + completion_window="24h" + ) + 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(); + response: | + { + "id": "batch_abc123", + "object": "batch", + "endpoint": "/v1/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", + } + } + get: + operationId: listBatches + tags: + - Batch + summary: List your organization's batches. + parameters: + - in: query + name: after + required: false + schema: + type: string + description: *pagination_after_param_description + - name: limit + in: query + description: *pagination_limit_param_description + 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](/docs/api-reference/batch/object) objects. + examples: + 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() + + client.batches.list() + 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(); + response: | + { + "object": "list", + "data": [ + { + "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 job", + } + }, + { ... }, + ], + "first_id": "batch_abc123", + "last_id": "batch_abc456", + "has_more": true + } + + /batches/{batch_id}: + get: + operationId: retrieveBatch + tags: + - Batch + summary: Retrieves a 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](/docs/api-reference/batch/object) object matching the specified ID. + examples: + 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() + + client.batches.retrieve("batch_abc123") + node: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const batch = await openai.batches.retrieve("batch_abc123"); + + console.log(batch); + } + + main(); + response: &batch_object | + { + "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", + } + } + + /batches/{batch_id}/cancel: + post: + operationId: cancelBatch + tags: + - Batch + summary: Cancels an in-progress 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](/docs/api-reference/batch/object) object matching the specified ID. + examples: + 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() + + client.batches.cancel("batch_abc123") + node: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const batch = await openai.batches.cancel("batch_abc123"); + + console.log(batch); + } + + main(); + response: | + { + "id": "batch_abc123", + "object": "batch", + "endpoint": "/v1/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", + } + } + +components: + securitySchemes: + ApiKeyAuth: + type: http + scheme: "bearer" + + schemas: + Error: + type: object + properties: + code: + type: string + nullable: true + message: + type: string + nullable: false + param: + type: string + nullable: true + type: + type: string + nullable: false + required: + - type + - message + - param + - code + ErrorResponse: + type: object + properties: + error: + $ref: "#/components/schemas/Error" + required: + - error + + ListModelsResponse: + type: object + properties: + object: + type: string + enum: [list] + data: + type: array + items: + $ref: "#/components/schemas/Model" + required: + - object + - data + DeleteModelResponse: + type: object + properties: + id: + type: string + deleted: + type: boolean + object: + type: string + required: + - id + - object + - deleted + + CreateCompletionRequest: + type: object + properties: + model: + description: &model_description | + ID of the model to use. You can use the [List models](/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](/docs/models/overview) for descriptions of them. + anyOf: + - type: string + - type: string + enum: ["gpt-3.5-turbo-instruct", "davinci-002", "babbage-002"] + x-oaiTypeLabel: string + prompt: + description: &completions_prompt_description | + The prompt(s) to generate completions for, encoded as a string, array of strings, array of tokens, or array of token arrays. + + Note that <|endoftext|> is the document separator that the model sees during training, so if a prompt is not specified the model will generate as if from the beginning of a new document. + default: "<|endoftext|>" + nullable: true + oneOf: + - type: string + default: "" + example: "This is a test." + - type: array + items: + type: string + default: "" + example: "This is a test." + - type: array + minItems: 1 + items: + type: integer + example: "[1212, 318, 257, 1332, 13]" + - type: array + minItems: 1 + items: + type: array + minItems: 1 + items: + type: integer + example: "[[1212, 318, 257, 1332, 13]]" + best_of: + type: integer + default: 1 + minimum: 0 + maximum: 20 + nullable: true + description: &completions_best_of_description | + Generates `best_of` completions server-side and returns the "best" (the one with the highest log probability per token). Results cannot be streamed. + + When used with `n`, `best_of` controls the number of candidate completions and `n` specifies how many to return – `best_of` must be greater than `n`. + + **Note:** Because this parameter generates many completions, it can quickly consume your token quota. Use carefully and ensure that you have reasonable settings for `max_tokens` and `stop`. + echo: + type: boolean + default: false + nullable: true + description: &completions_echo_description > + Echo back the prompt in addition to the completion + frequency_penalty: + type: number + default: 0 + minimum: -2 + maximum: 2 + nullable: true + description: &completions_frequency_penalty_description | + Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. + + [See more information about frequency and presence penalties.](/docs/guides/text-generation/parameter-details) + logit_bias: &completions_logit_bias + type: object + x-oaiTypeLabel: map + default: null + nullable: true + additionalProperties: + type: integer + description: &completions_logit_bias_description | + Modify the likelihood of specified tokens appearing in the completion. + + Accepts a JSON object that maps tokens (specified by their token ID in the GPT tokenizer) to an associated bias value from -100 to 100. You can use this [tokenizer tool](/tokenizer?view=bpe) to convert text to token IDs. Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model, but values between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 should result in a ban or exclusive selection of the relevant token. + + As an example, you can pass `{"50256": -100}` to prevent the <|endoftext|> token from being generated. + logprobs: &completions_logprobs_configuration + type: integer + minimum: 0 + maximum: 5 + default: null + nullable: true + description: &completions_logprobs_description | + Include the log probabilities on the `logprobs` most likely output tokens, as well the chosen tokens. For example, if `logprobs` is 5, the API will return a list of the 5 most likely tokens. The API will always return the `logprob` of the sampled token, so there may be up to `logprobs+1` elements in the response. + + The maximum value for `logprobs` is 5. + max_tokens: + type: integer + minimum: 0 + default: 16 + example: 16 + nullable: true + description: &completions_max_tokens_description | + The maximum number of [tokens](/tokenizer) that can be generated in the completion. + + The token count of your prompt plus `max_tokens` cannot exceed the model's context length. [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) for counting tokens. + n: + type: integer + minimum: 1 + maximum: 128 + default: 1 + example: 1 + nullable: true + description: &completions_completions_description | + How many completions to generate for each prompt. + + **Note:** Because this parameter generates many completions, it can quickly consume your token quota. Use carefully and ensure that you have reasonable settings for `max_tokens` and `stop`. + presence_penalty: + type: number + default: 0 + minimum: -2 + maximum: 2 + nullable: true + description: &completions_presence_penalty_description | + Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics. + + [See more information about frequency and presence penalties.](/docs/guides/text-generation/parameter-details) + seed: &completions_seed_param + type: integer + minimum: -9223372036854775808 + maximum: 9223372036854775807 + nullable: true + description: | + If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return the same result. + + Determinism is not guaranteed, and you should refer to the `system_fingerprint` response parameter to monitor changes in the backend. + stop: + description: &completions_stop_description > + Up to 4 sequences where the API will stop generating further tokens. The returned text will not contain the stop sequence. + default: null + nullable: true + oneOf: + - type: string + default: <|endoftext|> + example: "\n" + nullable: true + - type: array + minItems: 1 + maxItems: 4 + items: + type: string + example: '["\n"]' + stream: + description: > + Whether to stream back partial progress. If set, tokens will be sent as data-only [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) + as they become available, with the stream terminated by a `data: [DONE]` message. [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + type: boolean + nullable: true + default: false + stream_options: + $ref: "#/components/schemas/ChatCompletionStreamOptions" + suffix: + description: | + The suffix that comes after a completion of inserted text. + + This parameter is only supported for `gpt-3.5-turbo-instruct`. + default: null + nullable: true + type: string + example: "test." + temperature: + type: number + minimum: 0 + maximum: 2 + default: 1 + example: 1 + nullable: true + description: &completions_temperature_description | + What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. + + We generally recommend altering this or `top_p` but not both. + top_p: + type: number + minimum: 0 + maximum: 1 + default: 1 + example: 1 + nullable: true + description: &completions_top_p_description | + An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. + + We generally recommend altering this or `temperature` but not both. + user: &end_user_param_configuration + type: string + example: user-1234 + description: | + A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](/docs/guides/safety-best-practices/end-user-ids). + required: + - model + - prompt + + CreateCompletionResponse: + type: object + description: | + Represents a completion response from the API. Note: both the streamed and non-streamed response objects share the same shape (unlike the chat endpoint). + properties: + id: + type: string + description: A unique identifier for the completion. + choices: + type: array + description: The list of completion choices the model generated for the input prompt. + items: + type: object + required: + - finish_reason + - index + - logprobs + - text + properties: + finish_reason: + type: string + description: &completion_finish_reason_description | + The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence, + `length` if the maximum number of tokens specified in the request was reached, + or `content_filter` if content was omitted due to a flag from our content filters. + enum: ["stop", "length", "content_filter"] + index: + type: integer + logprobs: + type: object + nullable: true + properties: + text_offset: + type: array + items: + type: integer + token_logprobs: + type: array + items: + type: number + tokens: + type: array + items: + type: string + top_logprobs: + type: array + items: + type: object + additionalProperties: + type: number + text: + type: string + created: + type: integer + description: The Unix timestamp (in seconds) of when the completion was created. + model: + type: string + description: The model used for completion. + system_fingerprint: + type: string + description: | + This fingerprint represents the backend configuration that the model runs with. + + Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism. + object: + type: string + description: The object type, which is always "text_completion" + enum: [text_completion] + usage: + $ref: "#/components/schemas/CompletionUsage" + required: + - id + - object + - created + - model + - choices + x-oaiMeta: + name: The completion object + legacy: true + example: | + { + "id": "cmpl-uqkvlQyYK7bGYrRHQ0eXlWi7", + "object": "text_completion", + "created": 1589478378, + "model": "gpt-4-turbo", + "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 + } + } + + ChatCompletionRequestMessageContentPart: + oneOf: + - $ref: "#/components/schemas/ChatCompletionRequestMessageContentPartText" + - $ref: "#/components/schemas/ChatCompletionRequestMessageContentPartImage" + x-oaiExpandable: true + + ChatCompletionRequestMessageContentPartImage: + type: object + title: Image content part + properties: + type: + type: string + enum: ["image_url"] + description: The type of the content part. + image_url: + type: object + properties: + url: + type: string + description: Either a URL of the image or the base64 encoded image data. + format: uri + detail: + type: string + description: Specifies the detail level of the image. Learn more in the [Vision guide](/docs/guides/vision/low-or-high-fidelity-image-understanding). + enum: ["auto", "low", "high"] + default: "auto" + required: + - url + required: + - type + - image_url + + ChatCompletionRequestMessageContentPartText: + type: object + title: Text content part + properties: + type: + type: string + enum: ["text"] + description: The type of the content part. + text: + type: string + description: The text content. + required: + - type + - text + + ChatCompletionRequestMessage: + oneOf: + - $ref: "#/components/schemas/ChatCompletionRequestSystemMessage" + - $ref: "#/components/schemas/ChatCompletionRequestUserMessage" + - $ref: "#/components/schemas/ChatCompletionRequestAssistantMessage" + - $ref: "#/components/schemas/ChatCompletionRequestToolMessage" + - $ref: "#/components/schemas/ChatCompletionRequestFunctionMessage" + x-oaiExpandable: true + + ChatCompletionRequestSystemMessage: + type: object + title: System message + properties: + content: + description: The contents of the system message. + type: string + role: + type: string + enum: ["system"] + description: The role of the messages author, in this case `system`. + name: + type: string + description: An optional name for the participant. Provides the model information to differentiate between participants of the same role. + required: + - content + - role + + ChatCompletionRequestUserMessage: + type: object + title: User message + properties: + content: + description: | + The contents of the user message. + oneOf: + - type: string + description: The text contents of the message. + title: Text content + - type: array + description: An array of content parts with a defined type, each can be of type `text` or `image_url` when passing in images. You can pass multiple images by adding multiple `image_url` content parts. Image input is only supported when using the `gpt-4-visual-preview` model. + title: Array of content parts + items: + $ref: "#/components/schemas/ChatCompletionRequestMessageContentPart" + minItems: 1 + x-oaiExpandable: true + role: + type: string + enum: ["user"] + description: The role of the messages author, in this case `user`. + name: + type: string + description: An optional name for the participant. Provides the model information to differentiate between participants of the same role. + required: + - content + - role + + ChatCompletionRequestAssistantMessage: + type: object + title: Assistant message + properties: + content: + nullable: true + type: string + description: | + The contents of the assistant message. Required unless `tool_calls` or `function_call` is specified. + role: + type: string + enum: ["assistant"] + description: The role of the messages author, in this case `assistant`. + name: + type: string + description: An optional name for the participant. Provides the model information to differentiate between participants of the same role. + tool_calls: + $ref: "#/components/schemas/ChatCompletionMessageToolCalls" + function_call: + type: object + deprecated: true + description: "Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be called, as generated by the model." + properties: + arguments: + type: string + description: The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function. + name: + type: string + description: The name of the function to call. + required: + - arguments + - name + required: + - role + + ChatCompletionRequestToolMessage: + type: object + title: Tool message + properties: + role: + type: string + enum: ["tool"] + description: The role of the messages author, in this case `tool`. + content: + type: string + description: The contents of the tool message. + tool_call_id: + type: string + description: Tool call that this message is responding to. + required: + - role + - content + - tool_call_id + + ChatCompletionRequestFunctionMessage: + type: object + title: Function message + deprecated: true + properties: + role: + type: string + enum: ["function"] + description: The role of the messages author, in this case `function`. + content: + nullable: true + type: string + description: The contents of the function message. + name: + type: string + description: The name of the function to call. + required: + - role + - content + - name + + FunctionParameters: + type: object + description: "The parameters the functions accepts, described as a JSON Schema object. See the [guide](/docs/guides/text-generation/function-calling) for examples, and the [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for documentation about the format. \n\nOmitting `parameters` defines a function with an empty parameter list." + additionalProperties: true + + ChatCompletionFunctions: + type: object + deprecated: true + properties: + description: + type: string + description: A description of what the function does, used by the model to choose when and how to call the function. + name: + type: string + description: The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64. + parameters: + $ref: "#/components/schemas/FunctionParameters" + required: + - name + + ChatCompletionFunctionCallOption: + type: object + description: > + Specifying a particular function via `{"name": "my_function"}` forces the model to call that function. + properties: + name: + type: string + description: The name of the function to call. + required: + - name + + ChatCompletionTool: + type: object + properties: + type: + type: string + enum: ["function"] + description: The type of the tool. Currently, only `function` is supported. + function: + $ref: "#/components/schemas/FunctionObject" + required: + - type + - function + + FunctionObject: + type: object + properties: + description: + type: string + description: A description of what the function does, used by the model to choose when and how to call the function. + name: + type: string + description: The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64. + parameters: + $ref: "#/components/schemas/FunctionParameters" + required: + - name + + ChatCompletionToolChoiceOption: + description: | + Controls which (if any) tool is called by the model. + `none` means the model will not call any tool and instead generates a message. + `auto` means the model can pick between generating a message or calling one or more tools. + `required` means the model must call one or more tools. + Specifying a particular tool via `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. + + `none` is the default when no tools are present. `auto` is the default if tools are present. + oneOf: + - type: string + description: > + `none` means the model will not call any tool and instead generates a message. + `auto` means the model can pick between generating a message or calling one or more tools. + `required` means the model must call one or more tools. + enum: [none, auto, required] + - $ref: "#/components/schemas/ChatCompletionNamedToolChoice" + x-oaiExpandable: true + + ChatCompletionNamedToolChoice: + type: object + description: Specifies a tool the model should use. Use to force the model to call a specific function. + properties: + type: + type: string + enum: ["function"] + description: The type of the tool. Currently, only `function` is supported. + function: + type: object + properties: + name: + type: string + description: The name of the function to call. + required: + - name + required: + - type + - function + + ChatCompletionMessageToolCalls: + type: array + description: The tool calls generated by the model, such as function calls. + items: + $ref: "#/components/schemas/ChatCompletionMessageToolCall" + + ChatCompletionMessageToolCall: + type: object + properties: + # TODO: index included when streaming + id: + type: string + description: The ID of the tool call. + type: + type: string + enum: ["function"] + description: The type of the tool. Currently, only `function` is supported. + function: + type: object + description: The function that the model called. + properties: + name: + type: string + description: The name of the function to call. + arguments: + type: string + description: The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function. + required: + - name + - arguments + required: + - id + - type + - function + + ChatCompletionMessageToolCallChunk: + type: object + properties: + index: + type: integer + id: + type: string + description: The ID of the tool call. + type: + type: string + enum: ["function"] + description: The type of the tool. Currently, only `function` is supported. + function: + type: object + properties: + name: + type: string + description: The name of the function to call. + arguments: + type: string + description: The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function. + required: + - index + + # Note, this isn't referenced anywhere, but is kept as a convenience to record all possible roles in one place. + ChatCompletionRole: + type: string + description: The role of the author of a message + enum: + - system + - user + - assistant + - tool + - function + + ChatCompletionStreamOptions: + description: | + Options for streaming response. Only set this when you set `stream: true`. + type: object + nullable: true + default: null + properties: + include_usage: + type: boolean + description: | + If set, an additional chunk will be streamed before the `data: [DONE]` message. The `usage` field on this chunk shows the token usage statistics for the entire request, and the `choices` field will always be an empty array. All other chunks will also include a `usage` field, but with a null value. + + ChatCompletionResponseMessage: + type: object + description: A chat completion message generated by the model. + properties: + content: + type: string + description: The contents of the message. + nullable: true + tool_calls: + $ref: "#/components/schemas/ChatCompletionMessageToolCalls" + role: + type: string + enum: ["assistant"] + description: The role of the author of this message. + function_call: + type: object + deprecated: true + description: "Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be called, as generated by the model." + properties: + arguments: + type: string + description: The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function. + name: + type: string + description: The name of the function to call. + required: + - name + - arguments + required: + - role + - content + + ChatCompletionStreamResponseDelta: + type: object + description: A chat completion delta generated by streamed model responses. + properties: + content: + type: string + description: The contents of the chunk message. + nullable: true + function_call: + deprecated: true + type: object + description: "Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be called, as generated by the model." + properties: + arguments: + type: string + description: The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function. + name: + type: string + description: The name of the function to call. + tool_calls: + type: array + items: + $ref: "#/components/schemas/ChatCompletionMessageToolCallChunk" + role: + type: string + enum: ["system", "user", "assistant", "tool"] + description: The role of the author of this message. + + CreateChatCompletionRequest: + type: object + properties: + messages: + description: A list of messages comprising the conversation so far. [Example Python code](https://cookbook.openai.com/examples/how_to_format_inputs_to_chatgpt_models). + type: array + minItems: 1 + items: + $ref: "#/components/schemas/ChatCompletionRequestMessage" + model: + description: ID of the model to use. See the [model endpoint compatibility](/docs/models/model-endpoint-compatibility) table for details on which models work with the Chat API. + example: "gpt-4-turbo" + anyOf: + - type: string + - type: string + enum: + [ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0301", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ] + x-oaiTypeLabel: string + frequency_penalty: + type: number + default: 0 + minimum: -2 + maximum: 2 + nullable: true + description: *completions_frequency_penalty_description + logit_bias: + type: object + x-oaiTypeLabel: map + default: null + nullable: true + additionalProperties: + type: integer + description: | + Modify the likelihood of specified tokens appearing in the completion. + + Accepts a JSON object that maps tokens (specified by their token ID in the tokenizer) to an associated bias value from -100 to 100. Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model, but values between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 should result in a ban or exclusive selection of the relevant token. + logprobs: + description: Whether to return log probabilities of the output tokens or not. If true, returns the log probabilities of each output token returned in the `content` of `message`. + type: boolean + default: false + nullable: true + top_logprobs: + description: An integer between 0 and 20 specifying the number of most likely tokens to return at each token position, each with an associated log probability. `logprobs` must be set to `true` if this parameter is used. + type: integer + minimum: 0 + maximum: 20 + nullable: true + max_tokens: + description: | + The maximum number of [tokens](/tokenizer) that can be generated in the chat completion. + + The total length of input tokens and generated tokens is limited by the model's context length. [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) for counting tokens. + type: integer + nullable: true + n: + type: integer + minimum: 1 + maximum: 128 + default: 1 + example: 1 + nullable: true + description: How many chat completion choices to generate for each input message. Note that you will be charged based on the number of generated tokens across all of the choices. Keep `n` as `1` to minimize costs. + presence_penalty: + type: number + default: 0 + minimum: -2 + maximum: 2 + nullable: true + description: *completions_presence_penalty_description + response_format: + type: object + description: | + An object specifying the format that the model must output. Compatible with [GPT-4 Turbo](/docs/models/gpt-4-and-gpt-4-turbo) and all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. + + **Important:** when using JSON mode, you **must** also instruct the model to produce JSON yourself via a system or user message. Without this, the model may generate an unending stream of whitespace until the generation reaches the token limit, resulting in a long-running and seemingly "stuck" request. Also note that the message content may be partially cut off if `finish_reason="length"`, which indicates the generation exceeded `max_tokens` or the conversation exceeded the max context length. + properties: + type: + type: string + enum: ["text", "json_object"] + example: "json_object" + default: "text" + description: Must be one of `text` or `json_object`. + seed: + type: integer + minimum: -9223372036854775808 + maximum: 9223372036854775807 + nullable: true + description: | + This feature is in Beta. + If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return the same result. + Determinism is not guaranteed, and you should refer to the `system_fingerprint` response parameter to monitor changes in the backend. + x-oaiMeta: + beta: true + stop: + description: | + Up to 4 sequences where the API will stop generating further tokens. + default: null + oneOf: + - type: string + nullable: true + - type: array + minItems: 1 + maxItems: 4 + items: + type: string + stream: + description: > + If set, partial message deltas will be sent, like in ChatGPT. Tokens will be sent as data-only [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) + as they become available, with the stream terminated by a `data: [DONE]` message. [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + type: boolean + nullable: true + default: false + stream_options: + $ref: "#/components/schemas/ChatCompletionStreamOptions" + temperature: + type: number + minimum: 0 + maximum: 2 + default: 1 + example: 1 + nullable: true + description: *completions_temperature_description + top_p: + type: number + minimum: 0 + maximum: 1 + default: 1 + example: 1 + nullable: true + description: *completions_top_p_description + tools: + type: array + description: > + A list of tools the model may call. Currently, only functions are supported as a tool. + Use this to provide a list of functions the model may generate JSON inputs for. A max of 128 functions are supported. + items: + $ref: "#/components/schemas/ChatCompletionTool" + tool_choice: + $ref: "#/components/schemas/ChatCompletionToolChoiceOption" + user: *end_user_param_configuration + function_call: + deprecated: true + description: | + Deprecated in favor of `tool_choice`. + + Controls which (if any) function is called by the model. + `none` means the model will not call a function and instead generates a message. + `auto` means the model can pick between generating a message or calling a function. + Specifying a particular function via `{"name": "my_function"}` forces the model to call that function. + + `none` is the default when no functions are present. `auto` is the default if functions are present. + oneOf: + - type: string + description: > + `none` means the model will not call a function and instead generates a message. + `auto` means the model can pick between generating a message or calling a function. + enum: [none, auto] + - $ref: "#/components/schemas/ChatCompletionFunctionCallOption" + x-oaiExpandable: true + functions: + deprecated: true + description: | + Deprecated in favor of `tools`. + + A list of functions the model may generate JSON inputs for. + type: array + minItems: 1 + maxItems: 128 + items: + $ref: "#/components/schemas/ChatCompletionFunctions" + + required: + - model + - messages + + CreateChatCompletionResponse: + type: object + description: Represents a chat completion response returned by model, based on the provided input. + properties: + id: + type: string + description: A unique identifier for the chat completion. + choices: + type: array + description: A list of chat completion choices. Can be more than one if `n` is greater than 1. + items: + type: object + required: + - finish_reason + - index + - message + - logprobs + properties: + finish_reason: + type: string + description: &chat_completion_finish_reason_description | + The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence, + `length` if the maximum number of tokens specified in the request was reached, + `content_filter` if content was omitted due to a flag from our content filters, + `tool_calls` if the model called a tool, or `function_call` (deprecated) if the model called a function. + enum: + [ + "stop", + "length", + "tool_calls", + "content_filter", + "function_call", + ] + index: + type: integer + description: The index of the choice in the list of choices. + message: + $ref: "#/components/schemas/ChatCompletionResponseMessage" + logprobs: &chat_completion_response_logprobs + description: Log probability information for the choice. + type: object + nullable: true + properties: + content: + description: A list of message content tokens with log probability information. + type: array + items: + $ref: "#/components/schemas/ChatCompletionTokenLogprob" + nullable: true + required: + - content + created: + type: integer + description: The Unix timestamp (in seconds) of when the chat completion was created. + model: + type: string + description: The model used for the chat completion. + system_fingerprint: + type: string + description: | + This fingerprint represents the backend configuration that the model runs with. + + Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism. + object: + type: string + description: The object type, which is always `chat.completion`. + enum: [chat.completion] + usage: + $ref: "#/components/schemas/CompletionUsage" + required: + - choices + - created + - id + - model + - object + x-oaiMeta: + name: The chat completion object + group: chat + example: *chat_completion_example + + CreateChatCompletionFunctionResponse: + type: object + description: Represents a chat completion response returned by model, based on the provided input. + properties: + id: + type: string + description: A unique identifier for the chat completion. + choices: + type: array + description: A list of chat completion choices. Can be more than one if `n` is greater than 1. + items: + type: object + required: + - finish_reason + - index + - message + - logprobs + properties: + finish_reason: + type: string + description: + &chat_completion_function_finish_reason_description | + The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence, `length` if the maximum number of tokens specified in the request was reached, `content_filter` if content was omitted due to a flag from our content filters, or `function_call` if the model called a function. + enum: ["stop", "length", "function_call", "content_filter"] + index: + type: integer + description: The index of the choice in the list of choices. + message: + $ref: "#/components/schemas/ChatCompletionResponseMessage" + created: + type: integer + description: The Unix timestamp (in seconds) of when the chat completion was created. + model: + type: string + description: The model used for the chat completion. + system_fingerprint: + type: string + description: | + This fingerprint represents the backend configuration that the model runs with. + + Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism. + object: + type: string + description: The object type, which is always `chat.completion`. + enum: [chat.completion] + usage: + $ref: "#/components/schemas/CompletionUsage" + required: + - choices + - created + - id + - model + - object + x-oaiMeta: + name: The chat completion object + group: chat + example: *chat_completion_function_example + + ChatCompletionTokenLogprob: + type: object + properties: + token: &chat_completion_response_logprobs_token + description: The token. + type: string + logprob: &chat_completion_response_logprobs_token_logprob + description: The log probability of this token, if it is within the top 20 most likely tokens. Otherwise, the value `-9999.0` is used to signify that the token is very unlikely. + type: number + bytes: &chat_completion_response_logprobs_bytes + description: A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and their byte representations must be combined to generate the correct text representation. Can be `null` if there is no bytes representation for the token. + type: array + items: + type: integer + nullable: true + top_logprobs: + description: List of the most likely tokens and their log probability, at this token position. In rare cases, there may be fewer than the number of requested `top_logprobs` returned. + type: array + items: + type: object + properties: + token: *chat_completion_response_logprobs_token + logprob: *chat_completion_response_logprobs_token_logprob + bytes: *chat_completion_response_logprobs_bytes + required: + - token + - logprob + - bytes + required: + - token + - logprob + - bytes + - top_logprobs + + ListPaginatedFineTuningJobsResponse: + type: object + properties: + data: + type: array + items: + $ref: "#/components/schemas/FineTuningJob" + has_more: + type: boolean + object: + type: string + enum: [list] + required: + - object + - data + - has_more + + CreateChatCompletionStreamResponse: + type: object + description: Represents a streamed chunk of a chat completion response returned by model, based on the provided input. + properties: + id: + type: string + description: A unique identifier for the chat completion. Each chunk has the same ID. + choices: + type: array + description: | + A list of chat completion choices. Can contain more than one elements if `n` is greater than 1. Can also be empty for the + last chunk if you set `stream_options: {"include_usage": true}`. + items: + type: object + required: + - delta + - finish_reason + - index + properties: + delta: + $ref: "#/components/schemas/ChatCompletionStreamResponseDelta" + logprobs: *chat_completion_response_logprobs + finish_reason: + type: string + description: *chat_completion_finish_reason_description + enum: + [ + "stop", + "length", + "tool_calls", + "content_filter", + "function_call", + ] + nullable: true + index: + type: integer + description: The index of the choice in the list of choices. + created: + type: integer + description: The Unix timestamp (in seconds) of when the chat completion was created. Each chunk has the same timestamp. + model: + type: string + description: The model to generate the completion. + system_fingerprint: + type: string + description: | + This fingerprint represents the backend configuration that the model runs with. + Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism. + object: + type: string + description: The object type, which is always `chat.completion.chunk`. + enum: [chat.completion.chunk] + usage: + type: object + description: | + An optional field that will only be present when you set `stream_options: {"include_usage": true}` in your request. + When present, it contains a null value except for the last chunk which contains the token usage statistics for the entire request. + properties: + completion_tokens: + type: integer + description: Number of tokens in the generated completion. + prompt_tokens: + type: integer + description: Number of tokens in the prompt. + total_tokens: + type: integer + description: Total number of tokens used in the request (prompt + completion). + required: + - prompt_tokens + - completion_tokens + - total_tokens + required: + - choices + - created + - id + - model + - object + x-oaiMeta: + name: The chat completion chunk object + group: chat + example: *chat_completion_chunk_example + + CreateChatCompletionImageResponse: + type: object + description: Represents a streamed chunk of a chat completion response returned by model, based on the provided input. + x-oaiMeta: + name: The chat completion chunk object + group: chat + example: *chat_completion_image_example + + CreateImageRequest: + type: object + properties: + prompt: + description: A text description of the desired image(s). The maximum length is 1000 characters for `dall-e-2` and 4000 characters for `dall-e-3`. + type: string + example: "A cute baby sea otter" + model: + anyOf: + - type: string + - type: string + enum: ["dall-e-2", "dall-e-3"] + x-oaiTypeLabel: string + default: "dall-e-2" + example: "dall-e-3" + nullable: true + description: The model to use for image generation. + n: &images_n + type: integer + minimum: 1 + maximum: 10 + default: 1 + example: 1 + nullable: true + description: The number of images to generate. Must be between 1 and 10. For `dall-e-3`, only `n=1` is supported. + quality: + type: string + enum: ["standard", "hd"] + default: "standard" + example: "standard" + description: The quality of the image that will be generated. `hd` creates images with finer details and greater consistency across the image. This param is only supported for `dall-e-3`. + response_format: &images_response_format + type: string + enum: ["url", "b64_json"] + default: "url" + example: "url" + nullable: true + description: The format in which the generated images are returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes after the image has been generated. + size: &images_size + type: string + enum: ["256x256", "512x512", "1024x1024", "1792x1024", "1024x1792"] + default: "1024x1024" + example: "1024x1024" + nullable: true + description: The size of the generated images. Must be one of `256x256`, `512x512`, or `1024x1024` for `dall-e-2`. Must be one of `1024x1024`, `1792x1024`, or `1024x1792` for `dall-e-3` models. + style: + type: string + enum: ["vivid", "natural"] + default: "vivid" + example: "vivid" + nullable: true + description: The style of the generated images. Must be one of `vivid` or `natural`. Vivid causes the model to lean towards generating hyper-real and dramatic images. Natural causes the model to produce more natural, less hyper-real looking images. This param is only supported for `dall-e-3`. + user: *end_user_param_configuration + required: + - prompt + + ImagesResponse: + properties: + created: + type: integer + data: + type: array + items: + $ref: "#/components/schemas/Image" + required: + - created + - data + + Image: + type: object + description: Represents the url or the content of an image generated by the OpenAI API. + properties: + b64_json: + type: string + description: The base64-encoded JSON of the generated image, if `response_format` is `b64_json`. + url: + type: string + description: The URL of the generated image, if `response_format` is `url` (default). + revised_prompt: + type: string + description: The prompt that was used to generate the image, if there was any revision to the prompt. + x-oaiMeta: + name: The image object + example: | + { + "url": "...", + "revised_prompt": "..." + } + + CreateImageEditRequest: + type: object + properties: + image: + description: The image to edit. Must be a valid PNG file, less than 4MB, and square. If mask is not provided, image must have transparency, which will be used as the mask. + type: string + format: binary + prompt: + description: A text description of the desired image(s). The maximum length is 1000 characters. + type: string + example: "A cute baby sea otter wearing a beret" + mask: + description: An additional image whose fully transparent areas (e.g. where alpha is zero) indicate where `image` should be edited. Must be a valid PNG file, less than 4MB, and have the same dimensions as `image`. + type: string + format: binary + model: + anyOf: + - type: string + - type: string + enum: ["dall-e-2"] + x-oaiTypeLabel: string + default: "dall-e-2" + example: "dall-e-2" + nullable: true + description: The model to use for image generation. Only `dall-e-2` is supported at this time. + n: + type: integer + minimum: 1 + maximum: 10 + default: 1 + example: 1 + nullable: true + description: The number of images to generate. Must be between 1 and 10. + size: &dalle2_images_size + type: string + enum: ["256x256", "512x512", "1024x1024"] + default: "1024x1024" + example: "1024x1024" + nullable: true + description: The size of the generated images. Must be one of `256x256`, `512x512`, or `1024x1024`. + response_format: *images_response_format + user: *end_user_param_configuration + required: + - prompt + - image + + CreateImageVariationRequest: + type: object + properties: + image: + description: The image to use as the basis for the variation(s). Must be a valid PNG file, less than 4MB, and square. + type: string + format: binary + model: + anyOf: + - type: string + - type: string + enum: ["dall-e-2"] + x-oaiTypeLabel: string + default: "dall-e-2" + example: "dall-e-2" + nullable: true + description: The model to use for image generation. Only `dall-e-2` is supported at this time. + n: *images_n + response_format: *images_response_format + size: *dalle2_images_size + user: *end_user_param_configuration + required: + - image + + CreateModerationRequest: + type: object + properties: + input: + description: The input text to classify + oneOf: + - type: string + default: "" + example: "I want to kill them." + - type: array + items: + type: string + default: "" + example: "I want to kill them." + model: + description: | + Two content moderations models are available: `text-moderation-stable` and `text-moderation-latest`. + + The default is `text-moderation-latest` which will be automatically upgraded over time. This ensures you are always using our most accurate model. If you use `text-moderation-stable`, we will provide advanced notice before updating the model. Accuracy of `text-moderation-stable` may be slightly lower than for `text-moderation-latest`. + nullable: false + default: "text-moderation-latest" + example: "text-moderation-stable" + anyOf: + - type: string + - type: string + enum: ["text-moderation-latest", "text-moderation-stable"] + x-oaiTypeLabel: string + required: + - input + + CreateModerationResponse: + type: object + description: Represents if a given text input is potentially harmful. + properties: + id: + type: string + description: The unique identifier for the moderation request. + model: + type: string + description: The model used to generate the moderation results. + results: + type: array + description: A list of moderation objects. + items: + type: object + properties: + flagged: + type: boolean + description: Whether any of the below categories are flagged. + categories: + type: object + description: A list of the categories, and whether they are flagged or not. + properties: + hate: + type: boolean + description: Content that expresses, incites, or promotes hate based on race, gender, ethnicity, religion, nationality, sexual orientation, disability status, or caste. Hateful content aimed at non-protected groups (e.g., chess players) is harassment. + hate/threatening: + type: boolean + description: Hateful content that also includes violence or serious harm towards the targeted group based on race, gender, ethnicity, religion, nationality, sexual orientation, disability status, or caste. + harassment: + type: boolean + description: Content that expresses, incites, or promotes harassing language towards any target. + harassment/threatening: + type: boolean + description: Harassment content that also includes violence or serious harm towards any target. + self-harm: + type: boolean + description: Content that promotes, encourages, or depicts acts of self-harm, such as suicide, cutting, and eating disorders. + self-harm/intent: + type: boolean + description: Content where the speaker expresses that they are engaging or intend to engage in acts of self-harm, such as suicide, cutting, and eating disorders. + self-harm/instructions: + type: boolean + description: Content that encourages performing acts of self-harm, such as suicide, cutting, and eating disorders, or that gives instructions or advice on how to commit such acts. + sexual: + type: boolean + description: Content meant to arouse sexual excitement, such as the description of sexual activity, or that promotes sexual services (excluding sex education and wellness). + sexual/minors: + type: boolean + description: Sexual content that includes an individual who is under 18 years old. + violence: + type: boolean + description: Content that depicts death, violence, or physical injury. + violence/graphic: + type: boolean + description: Content that depicts death, violence, or physical injury in graphic detail. + required: + - hate + - hate/threatening + - harassment + - harassment/threatening + - self-harm + - self-harm/intent + - self-harm/instructions + - sexual + - sexual/minors + - violence + - violence/graphic + category_scores: + type: object + description: A list of the categories along with their scores as predicted by model. + properties: + hate: + type: number + description: The score for the category 'hate'. + hate/threatening: + type: number + description: The score for the category 'hate/threatening'. + harassment: + type: number + description: The score for the category 'harassment'. + harassment/threatening: + type: number + description: The score for the category 'harassment/threatening'. + self-harm: + type: number + description: The score for the category 'self-harm'. + self-harm/intent: + type: number + description: The score for the category 'self-harm/intent'. + self-harm/instructions: + type: number + description: The score for the category 'self-harm/instructions'. + sexual: + type: number + description: The score for the category 'sexual'. + sexual/minors: + type: number + description: The score for the category 'sexual/minors'. + violence: + type: number + description: The score for the category 'violence'. + violence/graphic: + type: number + description: The score for the category 'violence/graphic'. + required: + - hate + - hate/threatening + - harassment + - harassment/threatening + - self-harm + - self-harm/intent + - self-harm/instructions + - sexual + - sexual/minors + - violence + - violence/graphic + required: + - flagged + - categories + - category_scores + required: + - id + - model + - results + x-oaiMeta: + name: The moderation object + example: *moderation_example + + ListFilesResponse: + type: object + properties: + data: + type: array + items: + $ref: "#/components/schemas/OpenAIFile" + object: + type: string + enum: [list] + required: + - object + - data + + CreateFileRequest: + type: object + additionalProperties: false + properties: + file: + description: | + The File object (not file name) to be uploaded. + type: string + format: binary + purpose: + description: | + The intended purpose of the uploaded file. + + Use "fine-tune" for [Fine-tuning](/docs/api-reference/fine-tuning) and "assistants" for [Assistants](/docs/api-reference/assistants) and [Messages](/docs/api-reference/messages). This allows us to validate the format of the uploaded file is correct for fine-tuning. + type: string + enum: ["fine-tune", "assistants"] + required: + - file + - purpose + + DeleteFileResponse: + type: object + properties: + id: + type: string + object: + type: string + enum: [file] + deleted: + type: boolean + required: + - id + - object + - deleted + + CreateFineTuningJobRequest: + type: object + properties: + model: + description: | + The name of the model to fine-tune. You can select one of the + [supported models](/docs/guides/fine-tuning/what-models-can-be-fine-tuned). + example: "gpt-3.5-turbo" + anyOf: + - type: string + - type: string + enum: ["babbage-002", "davinci-002", "gpt-3.5-turbo"] + x-oaiTypeLabel: string + training_file: + description: | + The ID of an uploaded file that contains training data. + + See [upload file](/docs/api-reference/files/create) for how to upload a file. + + Your dataset must be formatted as a JSONL file. Additionally, you must upload your file with the purpose `fine-tune`. + + See the [fine-tuning guide](/docs/guides/fine-tuning) for more details. + type: string + example: "file-abc123" + hyperparameters: + type: object + description: The hyperparameters used for the fine-tuning job. + properties: + batch_size: + description: | + Number of examples in each batch. A larger batch size means that model parameters + are updated less frequently, but with lower variance. + oneOf: + - type: string + enum: [auto] + - type: integer + minimum: 1 + maximum: 256 + default: auto + learning_rate_multiplier: + description: | + Scaling factor for the learning rate. A smaller learning rate may be useful to avoid + overfitting. + oneOf: + - type: string + enum: [auto] + - type: number + minimum: 0 + exclusiveMinimum: true + default: auto + n_epochs: + description: | + The number of epochs to train the model for. An epoch refers to one full cycle + through the training dataset. + oneOf: + - type: string + enum: [auto] + - type: integer + minimum: 1 + maximum: 50 + default: auto + suffix: + description: | + A string of up to 18 characters that will be added to your fine-tuned model name. + + For example, a `suffix` of "custom-model-name" would produce a model name like `ft:gpt-3.5-turbo:openai:custom-model-name:7p4lURel`. + type: string + minLength: 1 + maxLength: 40 + default: null + nullable: true + validation_file: + description: | + The ID of an uploaded file that contains validation data. + + If you provide this file, the data is used to generate validation + metrics periodically during fine-tuning. These metrics can be viewed in + the fine-tuning results file. + The same data should not be present in both train and validation files. + + Your dataset must be formatted as a JSONL file. You must upload your file with the purpose `fine-tune`. + + See the [fine-tuning guide](/docs/guides/fine-tuning) for more details. + type: string + nullable: true + example: "file-abc123" + integrations: + type: array + description: A list of integrations to enable for your fine-tuning job. + nullable: true + items: + type: object + required: + - type + - wandb + properties: + type: + description: | + The type of integration to enable. Currently, only "wandb" (Weights and Biases) is supported. + oneOf: + - type: string + enum: [wandb] + wandb: + type: object + description: | + The settings for your integration with Weights and Biases. This payload specifies the project that + metrics will be sent to. Optionally, you can set an explicit display name for your run, add tags + to your run, and set a default entity (team, username, etc) to be associated with your run. + required: + - project + properties: + project: + description: | + The name of the project that the new run will be created under. + type: string + example: "my-wandb-project" + name: + description: | + A display name to set for the run. If not set, we will use the Job ID as the name. + nullable: true + type: string + entity: + description: | + The entity to use for the run. This allows you to set the team or username of the WandB user that you would + like associated with the run. If not set, the default entity for the registered WandB API key is used. + nullable: true + type: string + tags: + description: | + A list of tags to be attached to the newly created run. These tags are passed through directly to WandB. Some + default tags are generated by OpenAI: "openai/finetune", "openai/{base-model}", "openai/{ftjob-abcdef}". + type: array + items: + type: string + example: "custom-tag" + + seed: + description: | + The seed controls the reproducibility of the job. Passing in the same seed and job parameters should produce the same results, but may differ in rare cases. + If a seed is not specified, one will be generated for you. + type: integer + nullable: true + minimum: 0 + maximum: 2147483647 + example: 42 + required: + - model + - training_file + + ListFineTuningJobEventsResponse: + type: object + properties: + data: + type: array + items: + $ref: "#/components/schemas/FineTuningJobEvent" + object: + type: string + enum: [list] + required: + - object + - data + + ListFineTuningJobCheckpointsResponse: + type: object + properties: + data: + type: array + items: + $ref: "#/components/schemas/FineTuningJobCheckpoint" + object: + type: string + enum: [list] + first_id: + type: string + nullable: true + last_id: + type: string + nullable: true + has_more: + type: boolean + required: + - object + - data + - has_more + + CreateEmbeddingRequest: + type: object + additionalProperties: false + properties: + input: + description: | + Input text to embed, encoded as a string or array of tokens. To embed multiple inputs in a single request, pass an array of strings or array of token arrays. The input must not exceed the max input tokens for the model (8192 tokens for `text-embedding-ada-002`), cannot be an empty string, and any array must be 2048 dimensions or less. [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) for counting tokens. + example: "The quick brown fox jumped over the lazy dog" + oneOf: + - type: string + title: string + description: The string that will be turned into an embedding. + default: "" + example: "This is a test." + - type: array + title: array + description: The array of strings that will be turned into an embedding. + minItems: 1 + maxItems: 2048 + items: + type: string + default: "" + example: "['This is a test.']" + - type: array + title: array + description: The array of integers that will be turned into an embedding. + minItems: 1 + maxItems: 2048 + items: + type: integer + example: "[1212, 318, 257, 1332, 13]" + - type: array + title: array + description: The array of arrays containing integers that will be turned into an embedding. + minItems: 1 + maxItems: 2048 + items: + type: array + minItems: 1 + items: + type: integer + example: "[[1212, 318, 257, 1332, 13]]" + x-oaiExpandable: true + model: + description: *model_description + example: "text-embedding-3-small" + anyOf: + - type: string + - type: string + enum: + [ + "text-embedding-ada-002", + "text-embedding-3-small", + "text-embedding-3-large", + ] + x-oaiTypeLabel: string + encoding_format: + description: "The format to return the embeddings in. Can be either `float` or [`base64`](https://pypi.org/project/pybase64/)." + example: "float" + default: "float" + type: string + enum: ["float", "base64"] + dimensions: + description: | + The number of dimensions the resulting output embeddings should have. Only supported in `text-embedding-3` and later models. + type: integer + minimum: 1 + user: *end_user_param_configuration + required: + - model + - input + + CreateEmbeddingResponse: + type: object + properties: + data: + type: array + description: The list of embeddings generated by the model. + items: + $ref: "#/components/schemas/Embedding" + model: + type: string + description: The name of the model used to generate the embedding. + object: + type: string + description: The object type, which is always "list". + enum: [list] + usage: + type: object + description: The usage information for the request. + properties: + prompt_tokens: + type: integer + description: The number of tokens used by the prompt. + total_tokens: + type: integer + description: The total number of tokens used by the request. + required: + - prompt_tokens + - total_tokens + required: + - object + - model + - data + - usage + + CreateTranscriptionRequest: + type: object + additionalProperties: false + properties: + file: + description: | + The audio file object (not file name) to transcribe, in one of these formats: flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm. + type: string + x-oaiTypeLabel: file + format: binary + model: + description: | + ID of the model to use. Only `whisper-1` (which is powered by our open source Whisper V2 model) is currently available. + example: whisper-1 + anyOf: + - type: string + - type: string + enum: ["whisper-1"] + x-oaiTypeLabel: string + language: + description: | + The language of the input audio. Supplying the input language in [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) format will improve accuracy and latency. + type: string + prompt: + description: | + An optional text to guide the model's style or continue a previous audio segment. The [prompt](/docs/guides/speech-to-text/prompting) should match the audio language. + type: string + response_format: + description: | + The format of the transcript output, in one of these options: `json`, `text`, `srt`, `verbose_json`, or `vtt`. + type: string + enum: + - json + - text + - srt + - verbose_json + - vtt + default: json + temperature: + description: | + The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically increase the temperature until certain thresholds are hit. + type: number + default: 0 + timestamp_granularities[]: + description: | + The timestamp granularities to populate for this transcription. `response_format` must be set `verbose_json` to use timestamp granularities. Either or both of these options are supported: `word`, or `segment`. Note: There is no additional latency for segment timestamps, but generating word timestamps incurs additional latency. + type: array + items: + type: string + enum: + - word + - segment + default: [segment] + required: + - file + - model + + # Note: This does not currently support the non-default response format types. + CreateTranscriptionResponseJson: + type: object + description: Represents a transcription response returned by model, based on the provided input. + properties: + text: + type: string + description: The transcribed text. + required: + - text + x-oaiMeta: + name: The transcription object + group: audio + example: *basic_transcription_response_example + + TranscriptionSegment: + type: object + properties: + id: + type: integer + description: Unique identifier of the segment. + seek: + type: integer + description: Seek offset of the segment. + start: + type: number + format: float + description: Start time of the segment in seconds. + end: + type: number + format: float + description: End time of the segment in seconds. + text: + type: string + description: Text content of the segment. + tokens: + type: array + items: + type: integer + description: Array of token IDs for the text content. + temperature: + type: number + format: float + description: Temperature parameter used for generating the segment. + avg_logprob: + type: number + format: float + description: Average logprob of the segment. If the value is lower than -1, consider the logprobs failed. + compression_ratio: + type: number + format: float + description: Compression ratio of the segment. If the value is greater than 2.4, consider the compression failed. + no_speech_prob: + type: number + format: float + description: Probability of no speech in the segment. If the value is higher than 1.0 and the `avg_logprob` is below -1, consider this segment silent. + required: + - id + - seek + - start + - end + - text + - tokens + - temperature + - avg_logprob + - compression_ratio + - no_speech_prob + + TranscriptionWord: + type: object + properties: + word: + type: string + description: The text content of the word. + start: + type: number + format: float + description: Start time of the word in seconds. + end: + type: number + format: float + description: End time of the word in seconds. + required: [word, start, end] + + CreateTranscriptionResponseVerboseJson: + type: object + description: Represents a verbose json transcription response returned by model, based on the provided input. + properties: + language: + type: string + description: The language of the input audio. + duration: + type: string + description: The duration of the input audio. + text: + type: string + description: The transcribed text. + words: + type: array + description: Extracted words and their corresponding timestamps. + items: + $ref: "#/components/schemas/TranscriptionWord" + segments: + type: array + description: Segments of the transcribed text and their corresponding details. + items: + $ref: "#/components/schemas/TranscriptionSegment" + required: [language, duration, text] + x-oaiMeta: + name: The transcription object + group: audio + example: *verbose_transcription_response_example + + CreateTranslationRequest: + type: object + additionalProperties: false + properties: + file: + description: | + The audio file object (not file name) translate, in one of these formats: flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm. + type: string + x-oaiTypeLabel: file + format: binary + model: + description: | + ID of the model to use. Only `whisper-1` (which is powered by our open source Whisper V2 model) is currently available. + example: whisper-1 + anyOf: + - type: string + - type: string + enum: ["whisper-1"] + x-oaiTypeLabel: string + prompt: + description: | + An optional text to guide the model's style or continue a previous audio segment. The [prompt](/docs/guides/speech-to-text/prompting) should be in English. + type: string + response_format: + description: | + The format of the transcript output, in one of these options: `json`, `text`, `srt`, `verbose_json`, or `vtt`. + type: string + default: json + temperature: + description: | + The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically increase the temperature until certain thresholds are hit. + type: number + default: 0 + required: + - file + - model + + # Note: This does not currently support the non-default response format types. + CreateTranslationResponseJson: + type: object + properties: + text: + type: string + required: + - text + + CreateTranslationResponseVerboseJson: + type: object + properties: + language: + type: string + description: The language of the output translation (always `english`). + duration: + type: string + description: The duration of the input audio. + text: + type: string + description: The translated text. + segments: + type: array + description: Segments of the translated text and their corresponding details. + items: + $ref: "#/components/schemas/TranscriptionSegment" + required: [language, duration, text] + + CreateSpeechRequest: + type: object + additionalProperties: false + properties: + model: + description: | + One of the available [TTS models](/docs/models/tts): `tts-1` or `tts-1-hd` + anyOf: + - type: string + - type: string + enum: ["tts-1", "tts-1-hd"] + x-oaiTypeLabel: string + input: + type: string + description: The text to generate audio for. The maximum length is 4096 characters. + maxLength: 4096 + voice: + description: The voice to use when generating the audio. Supported voices are `alloy`, `echo`, `fable`, `onyx`, `nova`, and `shimmer`. Previews of the voices are available in the [Text to speech guide](/docs/guides/text-to-speech/voice-options). + type: string + enum: ["alloy", "echo", "fable", "onyx", "nova", "shimmer"] + response_format: + description: "The format to audio in. Supported formats are `mp3`, `opus`, `aac`, `flac`, `wav`, and `pcm`." + default: "mp3" + type: string + enum: ["mp3", "opus", "aac", "flac", "wav", "pcm"] + speed: + description: "The speed of the generated audio. Select a value from `0.25` to `4.0`. `1.0` is the default." + type: number + default: 1.0 + minimum: 0.25 + maximum: 4.0 + required: + - model + - input + - voice + + Model: + title: Model + description: Describes an OpenAI model offering that can be used with the API. + properties: + id: + type: string + description: The model identifier, which can be referenced in the API endpoints. + created: + type: integer + description: The Unix timestamp (in seconds) when the model was created. + object: + type: string + description: The object type, which is always "model". + enum: [model] + owned_by: + type: string + description: The organization that owns the model. + required: + - id + - object + - created + - owned_by + x-oaiMeta: + name: The model object + example: *retrieve_model_response + + OpenAIFile: + title: OpenAIFile + description: The `File` object represents a document that has been uploaded to OpenAI. + properties: + id: + type: string + description: The file identifier, which can be referenced in the API endpoints. + bytes: + type: integer + description: The size of the file, in bytes. + created_at: + type: integer + description: The Unix timestamp (in seconds) for when the file was created. + filename: + type: string + description: The name of the file. + object: + type: string + description: The object type, which is always `file`. + enum: ["file"] + purpose: + type: string + description: The intended purpose of the file. Supported values are `fine-tune`, `fine-tune-results`, `assistants`, and `assistants_output`. + enum: + [ + "fine-tune", + "fine-tune-results", + "assistants", + "assistants_output", + ] + status: + type: string + deprecated: true + description: Deprecated. The current status of the file, which can be either `uploaded`, `processed`, or `error`. + enum: ["uploaded", "processed", "error"] + status_details: + type: string + deprecated: true + description: Deprecated. For details on why a fine-tuning training file failed validation, see the `error` field on `fine_tuning.job`. + required: + - id + - object + - bytes + - created_at + - filename + - purpose + - status + x-oaiMeta: + name: The file object + example: | + { + "id": "file-abc123", + "object": "file", + "bytes": 120000, + "created_at": 1677610602, + "filename": "salesOverview.pdf", + "purpose": "assistants", + } + Embedding: + type: object + description: | + Represents an embedding vector returned by embedding endpoint. + properties: + index: + type: integer + description: The index of the embedding in the list of embeddings. + embedding: + type: array + description: | + The embedding vector, which is a list of floats. The length of vector depends on the model as listed in the [embedding guide](/docs/guides/embeddings). + items: + type: number + object: + type: string + description: The object type, which is always "embedding". + enum: [embedding] + required: + - index + - object + - embedding + x-oaiMeta: + name: The embedding object + example: | + { + "object": "embedding", + "embedding": [ + 0.0023064255, + -0.009327292, + .... (1536 floats total for ada-002) + -0.0028842222, + ], + "index": 0 + } + + FineTuningJob: + type: object + title: FineTuningJob + description: | + The `fine_tuning.job` object represents a fine-tuning job that has been created through the API. + properties: + id: + type: string + description: The object identifier, which can be referenced in the API endpoints. + created_at: + type: integer + description: The Unix timestamp (in seconds) for when the fine-tuning job was created. + error: + type: object + nullable: true + description: For fine-tuning jobs that have `failed`, this will contain more information on the cause of the failure. + properties: + code: + type: string + description: A machine-readable error code. + message: + type: string + description: A human-readable error message. + param: + type: string + description: The parameter that was invalid, usually `training_file` or `validation_file`. This field will be null if the failure was not parameter-specific. + nullable: true + required: + - code + - message + - param + fine_tuned_model: + type: string + nullable: true + description: The name of the fine-tuned model that is being created. The value will be null if the fine-tuning job is still running. + finished_at: + type: integer + nullable: true + description: The Unix timestamp (in seconds) for when the fine-tuning job was finished. The value will be null if the fine-tuning job is still running. + hyperparameters: + type: object + description: The hyperparameters used for the fine-tuning job. See the [fine-tuning guide](/docs/guides/fine-tuning) for more details. + properties: + n_epochs: + oneOf: + - type: string + enum: [auto] + - type: integer + minimum: 1 + maximum: 50 + default: auto + description: + The number of epochs to train the model for. An epoch refers to one full cycle through the training dataset. + + "auto" decides the optimal number of epochs based on the size of the dataset. If setting the number manually, we support any number between 1 and 50 epochs. + required: + - n_epochs + model: + type: string + description: The base model that is being fine-tuned. + object: + type: string + description: The object type, which is always "fine_tuning.job". + enum: [fine_tuning.job] + organization_id: + type: string + description: The organization that owns the fine-tuning job. + result_files: + type: array + description: The compiled results file ID(s) for the fine-tuning job. You can retrieve the results with the [Files API](/docs/api-reference/files/retrieve-contents). + items: + type: string + example: file-abc123 + status: + type: string + description: The current status of the fine-tuning job, which can be either `validating_files`, `queued`, `running`, `succeeded`, `failed`, or `cancelled`. + enum: + [ + "validating_files", + "queued", + "running", + "succeeded", + "failed", + "cancelled", + ] + trained_tokens: + type: integer + nullable: true + description: The total number of billable tokens processed by this fine-tuning job. The value will be null if the fine-tuning job is still running. + training_file: + type: string + description: The file ID used for training. You can retrieve the training data with the [Files API](/docs/api-reference/files/retrieve-contents). + validation_file: + type: string + nullable: true + description: The file ID used for validation. You can retrieve the validation results with the [Files API](/docs/api-reference/files/retrieve-contents). + integrations: + type: array + nullable: true + description: A list of integrations to enable for this fine-tuning job. + maxItems: 5 + items: + oneOf: + - $ref: "#/components/schemas/FineTuningIntegration" + x-oaiExpandable: true + seed: + type: integer + description: The seed used for the fine-tuning job. + estimated_finish: + type: integer + nullable: true + description: The Unix timestamp (in seconds) for when the fine-tuning job is estimated to finish. The value will be null if the fine-tuning job is not running. + required: + - created_at + - error + - finished_at + - fine_tuned_model + - hyperparameters + - id + - model + - object + - organization_id + - result_files + - status + - trained_tokens + - training_file + - validation_file + - seed + x-oaiMeta: + name: The fine-tuning job object + example: *fine_tuning_example + + FineTuningIntegration: + type: object + title: Fine-Tuning Job Integration + required: + - type + - wandb + properties: + type: + type: string + description: "The type of the integration being enabled for the fine-tuning job" + enum: ["wandb"] + wandb: + type: object + description: | + The settings for your integration with Weights and Biases. This payload specifies the project that + metrics will be sent to. Optionally, you can set an explicit display name for your run, add tags + to your run, and set a default entity (team, username, etc) to be associated with your run. + required: + - project + properties: + project: + description: | + The name of the project that the new run will be created under. + type: string + example: "my-wandb-project" + name: + description: | + A display name to set for the run. If not set, we will use the Job ID as the name. + nullable: true + type: string + entity: + description: | + The entity to use for the run. This allows you to set the team or username of the WandB user that you would + like associated with the run. If not set, the default entity for the registered WandB API key is used. + nullable: true + type: string + tags: + description: | + A list of tags to be attached to the newly created run. These tags are passed through directly to WandB. Some + default tags are generated by OpenAI: "openai/finetune", "openai/{base-model}", "openai/{ftjob-abcdef}". + type: array + items: + type: string + example: "custom-tag" + + FineTuningJobEvent: + type: object + description: Fine-tuning job event object + properties: + id: + type: string + created_at: + type: integer + level: + type: string + enum: ["info", "warn", "error"] + message: + type: string + object: + type: string + enum: [fine_tuning.job.event] + required: + - id + - object + - created_at + - level + - message + x-oaiMeta: + name: The fine-tuning job event object + example: | + { + "object": "fine_tuning.job.event", + "id": "ftevent-abc123" + "created_at": 1677610602, + "level": "info", + "message": "Created fine-tuning job" + } + + FineTuningJobCheckpoint: + type: object + title: FineTuningJobCheckpoint + description: | + The `fine_tuning.job.checkpoint` object represents a model checkpoint for a fine-tuning job that is ready to use. + properties: + id: + type: string + description: The checkpoint identifier, which can be referenced in the API endpoints. + created_at: + type: integer + description: The Unix timestamp (in seconds) for when the checkpoint was created. + fine_tuned_model_checkpoint: + type: string + description: The name of the fine-tuned checkpoint model that is created. + step_number: + type: integer + description: The step number that the checkpoint was created at. + metrics: + type: object + description: Metrics at the step number during the fine-tuning job. + properties: + step: + type: number + train_loss: + type: number + train_mean_token_accuracy: + type: number + valid_loss: + type: number + valid_mean_token_accuracy: + type: number + full_valid_loss: + type: number + full_valid_mean_token_accuracy: + type: number + fine_tuning_job_id: + type: string + description: The name of the fine-tuning job that this checkpoint was created from. + object: + type: string + description: The object type, which is always "fine_tuning.job.checkpoint". + enum: [fine_tuning.job.checkpoint] + required: + - created_at + - fine_tuning_job_id + - fine_tuned_model_checkpoint + - id + - metrics + - object + - step_number + x-oaiMeta: + name: The fine-tuning job checkpoint object + example: | + { + "object": "fine_tuning.job.checkpoint", + "id": "ftckpt_qtZ5Gyk4BLq1SfLFWp3RtO3P", + "created_at": 1712211699, + "fine_tuned_model_checkpoint": "ft:gpt-3.5-turbo-0125:my-org:custom_suffix:9ABel2dg:ckpt-step-88", + "fine_tuning_job_id": "ftjob-fpbNQ3H1GrMehXRf8cO97xTN", + "metrics": { + "step": 88, + "train_loss": 0.478, + "train_mean_token_accuracy": 0.924, + "valid_loss": 10.112, + "valid_mean_token_accuracy": 0.145, + "full_valid_loss": 0.567, + "full_valid_mean_token_accuracy": 0.944 + }, + "step_number": 88 + } + + CompletionUsage: + type: object + description: Usage statistics for the completion request. + properties: + completion_tokens: + type: integer + description: Number of tokens in the generated completion. + prompt_tokens: + type: integer + description: Number of tokens in the prompt. + total_tokens: + type: integer + description: Total number of tokens used in the request (prompt + completion). + required: + - prompt_tokens + - completion_tokens + - total_tokens + + RunCompletionUsage: + type: object + description: Usage statistics related to the run. This value will be `null` if the run is not in a terminal state (i.e. `in_progress`, `queued`, etc.). + properties: + completion_tokens: + type: integer + description: Number of completion tokens used over the course of the run. + prompt_tokens: + type: integer + description: Number of prompt tokens used over the course of the run. + total_tokens: + type: integer + description: Total number of tokens used (prompt + completion). + required: + - prompt_tokens + - completion_tokens + - total_tokens + nullable: true + + RunStepCompletionUsage: + type: object + description: Usage statistics related to the run step. This value will be `null` while the run step's status is `in_progress`. + properties: + completion_tokens: + type: integer + description: Number of completion tokens used over the course of the run step. + prompt_tokens: + type: integer + description: Number of prompt tokens used over the course of the run step. + total_tokens: + type: integer + description: Total number of tokens used (prompt + completion). + required: + - prompt_tokens + - completion_tokens + - total_tokens + nullable: true + + AssistantsApiResponseFormatOption: + description: | + Specifies the format that the model must output. Compatible with [GPT-4 Turbo](/docs/models/gpt-4-and-gpt-4-turbo) and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. + + **Important:** when using JSON mode, you **must** also instruct the model to produce JSON yourself via a system or user message. Without this, the model may generate an unending stream of whitespace until the generation reaches the token limit, resulting in a long-running and seemingly "stuck" request. Also note that the message content may be partially cut off if `finish_reason="length"`, which indicates the generation exceeded `max_tokens` or the conversation exceeded the max context length. + oneOf: + - type: string + description: > + `auto` is the default value + enum: [none, auto] + - $ref: "#/components/schemas/AssistantsApiResponseFormat" + x-oaiExpandable: true + + AssistantsApiResponseFormat: + type: object + description: | + An object describing the expected output of the model. If `json_object` only `function` type `tools` are allowed to be passed to the Run. If `text` the model can return text or any value needed. + properties: + type: + type: string + enum: ["text", "json_object"] + example: "json_object" + default: "text" + description: Must be one of `text` or `json_object`. + + AssistantObject: + type: object + title: Assistant + description: Represents an `assistant` that can call the model and use tools. + properties: + id: + description: The identifier, which can be referenced in API endpoints. + type: string + object: + description: The object type, which is always `assistant`. + type: string + enum: [assistant] + created_at: + description: The Unix timestamp (in seconds) for when the assistant was created. + type: integer + name: + description: &assistant_name_param_description | + The name of the assistant. The maximum length is 256 characters. + type: string + maxLength: 256 + nullable: true + description: + description: &assistant_description_param_description | + The description of the assistant. The maximum length is 512 characters. + type: string + maxLength: 512 + nullable: true + model: + description: *model_description + type: string + instructions: + description: &assistant_instructions_param_description | + The system instructions that the assistant uses. The maximum length is 256,000 characters. + type: string + maxLength: 256000 + nullable: true + tools: + description: &assistant_tools_param_description | + A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools can be of types `code_interpreter`, `file_search`, or `function`. + default: [] + type: array + maxItems: 128 + items: + oneOf: + - $ref: "#/components/schemas/AssistantToolsCode" + - $ref: "#/components/schemas/AssistantToolsFileSearch" + - $ref: "#/components/schemas/AssistantToolsFunction" + x-oaiExpandable: true + tool_resources: + type: object + description: | + A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. + properties: + code_interpreter: + type: object + properties: + file_ids: + type: array + description: | + A list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter`` tool. There can be a maximum of 20 files associated with the tool. + default: [] + maxItems: 20 + items: + type: string + file_search: + type: object + properties: + vector_store_ids: + type: array + description: | + The ID of the [vector store](/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant. + maxItems: 1 + items: + type: string + nullable: true + metadata: + description: &metadata_description | + Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long. + type: object + x-oaiTypeLabel: map + nullable: true + temperature: + description: &run_temperature_description | + What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. + type: number + minimum: 0 + maximum: 2 + default: 1 + example: 1 + nullable: true + top_p: + type: number + minimum: 0 + maximum: 1 + default: 1 + example: 1 + nullable: true + description: &run_top_p_description | + An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. + + We generally recommend altering this or temperature but not both. + response_format: + $ref: "#/components/schemas/AssistantsApiResponseFormatOption" + nullable: true + required: + - id + - object + - created_at + - name + - description + - model + - instructions + - tools + - metadata + x-oaiMeta: + name: The assistant object + beta: true + example: *create_assistants_example + + CreateAssistantRequest: + type: object + additionalProperties: false + properties: + model: + description: *model_description + example: "gpt-4-turbo" + anyOf: + - type: string + - type: string + enum: + [ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ] + x-oaiTypeLabel: string + name: + description: *assistant_name_param_description + type: string + nullable: true + maxLength: 256 + description: + description: *assistant_description_param_description + type: string + nullable: true + maxLength: 512 + instructions: + description: *assistant_instructions_param_description + type: string + nullable: true + maxLength: 256000 + tools: + description: *assistant_tools_param_description + default: [] + type: array + maxItems: 128 + items: + oneOf: + - $ref: "#/components/schemas/AssistantToolsCode" + - $ref: "#/components/schemas/AssistantToolsFileSearch" + - $ref: "#/components/schemas/AssistantToolsFunction" + x-oaiExpandable: true + tool_resources: + type: object + description: | + A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. + properties: + code_interpreter: + type: object + properties: + file_ids: + type: array + description: | + A list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. + default: [] + maxItems: 20 + items: + type: string + file_search: + type: object + properties: + vector_store_ids: + type: array + description: | + The [vector store](/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant. + maxItems: 1 + items: + type: string + vector_stores: + type: array + description: | + A helper to create a [vector store](/docs/api-reference/vector-stores/object) with file_ids and attach it to this assistant. There can be a maximum of 1 vector store attached to the assistant. + maxItems: 1 + items: + type: object + properties: + file_ids: + type: array + description: | + A list of [file](/docs/api-reference/files) IDs to add to the vector store. There can be a maximum of 10000 files in a vector store. + maxItems: 10000 + items: + type: string + metadata: + type: object + description: | + Set of 16 key-value pairs that can be attached to a vector store. This can be useful for storing additional information about the vector store in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long. + x-oaiTypeLabel: map + oneOf: + - required: [vector_store_ids] + - required: [vector_stores] + nullable: true + metadata: + description: *metadata_description + type: object + x-oaiTypeLabel: map + nullable: true + temperature: + description: &run_temperature_description | + What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. + type: number + minimum: 0 + maximum: 2 + default: 1 + example: 1 + nullable: true + top_p: + type: number + minimum: 0 + maximum: 1 + default: 1 + example: 1 + nullable: true + description: &run_top_p_description | + An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. + + We generally recommend altering this or temperature but not both. + response_format: + $ref: "#/components/schemas/AssistantsApiResponseFormatOption" + nullable: true + required: + - model + + ModifyAssistantRequest: + type: object + additionalProperties: false + properties: + model: + description: *model_description + anyOf: + - type: string + name: + description: *assistant_name_param_description + type: string + nullable: true + maxLength: 256 + description: + description: *assistant_description_param_description + type: string + nullable: true + maxLength: 512 + instructions: + description: *assistant_instructions_param_description + type: string + nullable: true + maxLength: 256000 + tools: + description: *assistant_tools_param_description + default: [] + type: array + maxItems: 128 + items: + oneOf: + - $ref: "#/components/schemas/AssistantToolsCode" + - $ref: "#/components/schemas/AssistantToolsFileSearch" + - $ref: "#/components/schemas/AssistantToolsFunction" + x-oaiExpandable: true + tool_resources: + type: object + description: | + A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. + properties: + code_interpreter: + type: object + properties: + file_ids: + type: array + description: | + Overrides the list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. + default: [] + maxItems: 20 + items: + type: string + file_search: + type: object + properties: + vector_store_ids: + type: array + description: | + Overrides the [vector store](/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant. + maxItems: 1 + items: + type: string + nullable: true + metadata: + description: *metadata_description + type: object + x-oaiTypeLabel: map + nullable: true + temperature: + description: *run_temperature_description + type: number + minimum: 0 + maximum: 2 + default: 1 + example: 1 + nullable: true + top_p: + type: number + minimum: 0 + maximum: 1 + default: 1 + example: 1 + nullable: true + description: &run_top_p_description | + An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. + + We generally recommend altering this or temperature but not both. + response_format: + $ref: "#/components/schemas/AssistantsApiResponseFormatOption" + nullable: true + + DeleteAssistantResponse: + type: object + properties: + id: + type: string + deleted: + type: boolean + object: + type: string + enum: [assistant.deleted] + required: + - id + - object + - deleted + + ListAssistantsResponse: + type: object + properties: + object: + type: string + example: "list" + data: + type: array + items: + $ref: "#/components/schemas/AssistantObject" + first_id: + type: string + example: "asst_abc123" + last_id: + type: string + example: "asst_abc456" + has_more: + type: boolean + example: false + required: + - object + - data + - first_id + - last_id + - has_more + x-oaiMeta: + name: List assistants response object + group: chat + example: *list_assistants_example + + AssistantToolsCode: + type: object + title: Code interpreter tool + properties: + type: + type: string + description: "The type of tool being defined: `code_interpreter`" + enum: ["code_interpreter"] + required: + - type + + AssistantToolsFileSearch: + type: object + title: FileSearch tool + properties: + type: + type: string + description: "The type of tool being defined: `file_search`" + enum: ["file_search"] + required: + - type + + AssistantToolsFunction: + type: object + title: Function tool + properties: + type: + type: string + description: "The type of tool being defined: `function`" + enum: ["function"] + function: + $ref: "#/components/schemas/FunctionObject" + required: + - type + - function + + TruncationObject: + type: object + title: Thread Truncation Controls + description: Controls for how a thread will be truncated prior to the run. Use this to control the intial context window of the run. + properties: + type: + type: string + description: The truncation strategy to use for the thread. The default is `auto`. If set to `last_messages`, the thread will be truncated to the n most recent messages in the thread. When set to `auto`, messages in the middle of the thread will be dropped to fit the context length of the model, `max_prompt_tokens`. + enum: ["auto", "last_messages"] + last_messages: + type: integer + description: The number of most recent messages from the thread when constructing the context for the run. + minimum: 1 + nullable: true + required: + - type + + AssistantsApiToolChoiceOption: + description: | + Controls which (if any) tool is called by the model. + `none` means the model will not call any tools and instead generates a message. + `auto` is the default value and means the model can pick between generating a message or calling one or more tools. + `required` means the model must call one or more tools before responding to the user. + Specifying a particular tool like `{"type": "file_search"}` or `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. + + oneOf: + - type: string + description: > + `none` means the model will not call any tools and instead generates a message. + `auto` means the model can pick between generating a message or calling one or more tools. + `required` means the model must call one or more tools before responding to the user. + enum: [none, auto, required] + - $ref: "#/components/schemas/AssistantsNamedToolChoice" + x-oaiExpandable: true + + AssistantsNamedToolChoice: + type: object + description: Specifies a tool the model should use. Use to force the model to call a specific tool. + properties: + type: + type: string + enum: ["function", "code_interpreter", "file_search"] + description: The type of the tool. If type is `function`, the function name must be set + function: + type: object + properties: + name: + type: string + description: The name of the function to call. + required: + - name + required: + - type + + RunObject: + type: object + title: A run on a thread + description: Represents an execution run on a [thread](/docs/api-reference/threads). + properties: + id: + description: The identifier, which can be referenced in API endpoints. + type: string + object: + description: The object type, which is always `thread.run`. + type: string + enum: ["thread.run"] + created_at: + description: The Unix timestamp (in seconds) for when the run was created. + type: integer + thread_id: + description: The ID of the [thread](/docs/api-reference/threads) that was executed on as a part of this run. + type: string + assistant_id: + description: The ID of the [assistant](/docs/api-reference/assistants) used for execution of this run. + type: string + status: + description: The status of the run, which can be either `queued`, `in_progress`, `requires_action`, `cancelling`, `cancelled`, `failed`, `completed`, or `expired`. + type: string + enum: + [ + "queued", + "in_progress", + "requires_action", + "cancelling", + "cancelled", + "failed", + "completed", + "expired", + ] + required_action: + type: object + description: Details on the action required to continue the run. Will be `null` if no action is required. + nullable: true + properties: + type: + description: For now, this is always `submit_tool_outputs`. + type: string + enum: ["submit_tool_outputs"] + submit_tool_outputs: + type: object + description: Details on the tool outputs needed for this run to continue. + properties: + tool_calls: + type: array + description: A list of the relevant tool calls. + items: + $ref: "#/components/schemas/RunToolCallObject" + required: + - tool_calls + required: + - type + - submit_tool_outputs + last_error: + type: object + description: The last error associated with this run. Will be `null` if there are no errors. + nullable: true + properties: + code: + type: string + description: One of `server_error`, `rate_limit_exceeded`, or `invalid_prompt`. + enum: ["server_error", "rate_limit_exceeded", "invalid_prompt"] + message: + type: string + description: A human-readable description of the error. + required: + - code + - message + expires_at: + description: The Unix timestamp (in seconds) for when the run will expire. + type: integer + nullable: true + started_at: + description: The Unix timestamp (in seconds) for when the run was started. + type: integer + nullable: true + cancelled_at: + description: The Unix timestamp (in seconds) for when the run was cancelled. + type: integer + nullable: true + failed_at: + description: The Unix timestamp (in seconds) for when the run failed. + type: integer + nullable: true + completed_at: + description: The Unix timestamp (in seconds) for when the run was completed. + type: integer + nullable: true + incomplete_details: + description: Details on why the run is incomplete. Will be `null` if the run is not incomplete. + type: object + nullable: true + properties: + reason: + description: The reason why the run is incomplete. This will point to which specific token limit was reached over the course of the run. + type: string + enum: ["max_completion_tokens", "max_prompt_tokens"] + model: + description: The model that the [assistant](/docs/api-reference/assistants) used for this run. + type: string + instructions: + description: The instructions that the [assistant](/docs/api-reference/assistants) used for this run. + type: string + tools: + description: The list of tools that the [assistant](/docs/api-reference/assistants) used for this run. + default: [] + type: array + maxItems: 20 + items: + oneOf: + - $ref: "#/components/schemas/AssistantToolsCode" + - $ref: "#/components/schemas/AssistantToolsFileSearch" + - $ref: "#/components/schemas/AssistantToolsFunction" + x-oaiExpandable: true + metadata: + description: *metadata_description + type: object + x-oaiTypeLabel: map + nullable: true + usage: + $ref: "#/components/schemas/RunCompletionUsage" + temperature: + description: The sampling temperature used for this run. If not set, defaults to 1. + type: number + nullable: true + top_p: + description: The nucleus sampling value used for this run. If not set, defaults to 1. + type: number + nullable: true + max_prompt_tokens: + type: integer + nullable: true + description: | + The maximum number of prompt tokens specified to have been used over the course of the run. + minimum: 256 + max_completion_tokens: + type: integer + nullable: true + description: | + The maximum number of completion tokens specified to have been used over the course of the run. + minimum: 256 + truncation_strategy: + $ref: "#/components/schemas/TruncationObject" + nullable: true + tool_choice: + $ref: "#/components/schemas/AssistantsApiToolChoiceOption" + nullable: true + response_format: + $ref: "#/components/schemas/AssistantsApiResponseFormatOption" + nullable: true + required: + - id + - object + - created_at + - thread_id + - assistant_id + - status + - required_action + - last_error + - expires_at + - started_at + - cancelled_at + - failed_at + - completed_at + - model + - instructions + - tools + - metadata + - usage + - incomplete_details + - max_prompt_tokens + - max_completion_tokens + - truncation_strategy + - tool_choice + - response_format + x-oaiMeta: + name: The run object + beta: true + example: | + { + "id": "run_abc123", + "object": "thread.run", + "created_at": 1698107661, + "assistant_id": "asst_abc123", + "thread_id": "thread_abc123", + "status": "completed", + "started_at": 1699073476, + "expires_at": null, + "cancelled_at": null, + "failed_at": null, + "completed_at": 1699073498, + "last_error": null, + "model": "gpt-4-turbo", + "instructions": null, + "tools": [{"type": "file_search"}, {"type": "code_interpreter"}], + "metadata": {}, + "incomplete_details": null, + "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" + } + CreateRunRequest: + type: object + additionalProperties: false + properties: + assistant_id: + description: The ID of the [assistant](/docs/api-reference/assistants) to use to execute this run. + type: string + model: + description: The ID of the [Model](/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the model associated with the assistant. If not, the model associated with the assistant will be used. + example: "gpt-4-turbo" + anyOf: + - type: string + - type: string + enum: + [ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ] + x-oaiTypeLabel: string + nullable: true + instructions: + description: Overrides the [instructions](/docs/api-reference/assistants/createAssistant) of the assistant. This is useful for modifying the behavior on a per-run basis. + type: string + nullable: true + additional_instructions: + description: Appends additional instructions at the end of the instructions for the run. This is useful for modifying the behavior on a per-run basis without overriding other instructions. + type: string + nullable: true + additional_messages: + description: Adds additional messages to the thread before creating the run. + type: array + items: + $ref: "#/components/schemas/CreateMessageRequest" + nullable: true + tools: + description: Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. + nullable: true + type: array + maxItems: 20 + items: + oneOf: + - $ref: "#/components/schemas/AssistantToolsCode" + - $ref: "#/components/schemas/AssistantToolsFileSearch" + - $ref: "#/components/schemas/AssistantToolsFunction" + x-oaiExpandable: true + metadata: + description: *metadata_description + type: object + x-oaiTypeLabel: map + nullable: true + temperature: + type: number + minimum: 0 + maximum: 2 + default: 1 + example: 1 + nullable: true + description: *run_temperature_description + top_p: + type: number + minimum: 0 + maximum: 1 + default: 1 + example: 1 + nullable: true + description: &run_top_p_description | + An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. + + We generally recommend altering this or temperature but not both. + stream: + type: boolean + nullable: true + description: | + If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message. + max_prompt_tokens: + type: integer + nullable: true + description: | + The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. + minimum: 256 + max_completion_tokens: + type: integer + nullable: true + description: | + The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. + minimum: 256 + truncation_strategy: + $ref: "#/components/schemas/TruncationObject" + nullable: true + tool_choice: + $ref: "#/components/schemas/AssistantsApiToolChoiceOption" + nullable: true + response_format: + $ref: "#/components/schemas/AssistantsApiResponseFormatOption" + nullable: true + required: + - thread_id + - assistant_id + ListRunsResponse: + type: object + properties: + object: + type: string + example: "list" + data: + type: array + items: + $ref: "#/components/schemas/RunObject" + first_id: + type: string + example: "run_abc123" + last_id: + type: string + example: "run_abc456" + has_more: + type: boolean + example: false + required: + - object + - data + - first_id + - last_id + - has_more + ModifyRunRequest: + type: object + additionalProperties: false + properties: + metadata: + description: *metadata_description + type: object + x-oaiTypeLabel: map + nullable: true + SubmitToolOutputsRunRequest: + type: object + additionalProperties: false + properties: + tool_outputs: + description: A list of tools for which the outputs are being submitted. + type: array + items: + type: object + properties: + tool_call_id: + type: string + description: The ID of the tool call in the `required_action` object within the run object the output is being submitted for. + output: + type: string + description: The output of the tool call to be submitted to continue the run. + stream: + type: boolean + nullable: true + description: | + If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message. + required: + - tool_outputs + + RunToolCallObject: + type: object + description: Tool call objects + properties: + id: + type: string + description: The ID of the tool call. This ID must be referenced when you submit the tool outputs in using the [Submit tool outputs to run](/docs/api-reference/runs/submitToolOutputs) endpoint. + type: + type: string + description: The type of tool call the output is required for. For now, this is always `function`. + enum: ["function"] + function: + type: object + description: The function definition. + properties: + name: + type: string + description: The name of the function. + arguments: + type: string + description: The arguments that the model expects you to pass to the function. + required: + - name + - arguments + required: + - id + - type + - function + + CreateThreadAndRunRequest: + type: object + additionalProperties: false + properties: + assistant_id: + description: The ID of the [assistant](/docs/api-reference/assistants) to use to execute this run. + type: string + thread: + $ref: "#/components/schemas/CreateThreadRequest" + description: If no thread is provided, an empty thread will be created. + model: + description: The ID of the [Model](/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the model associated with the assistant. If not, the model associated with the assistant will be used. + example: "gpt-4-turbo" + anyOf: + - type: string + - type: string + enum: + [ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ] + x-oaiTypeLabel: string + nullable: true + instructions: + description: Override the default system message of the assistant. This is useful for modifying the behavior on a per-run basis. + type: string + nullable: true + tools: + description: Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. + nullable: true + type: array + maxItems: 20 + items: + oneOf: + - $ref: "#/components/schemas/AssistantToolsCode" + - $ref: "#/components/schemas/AssistantToolsFileSearch" + - $ref: "#/components/schemas/AssistantToolsFunction" + tool_resources: + type: object + description: | + A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. + properties: + code_interpreter: + type: object + properties: + file_ids: + type: array + description: | + A list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. + default: [] + maxItems: 20 + items: + type: string + file_search: + type: object + properties: + vector_store_ids: + type: array + description: | + The ID of the [vector store](/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant. + maxItems: 1 + items: + type: string + nullable: true + metadata: + description: *metadata_description + type: object + x-oaiTypeLabel: map + nullable: true + temperature: + type: number + minimum: 0 + maximum: 2 + default: 1 + example: 1 + nullable: true + description: *run_temperature_description + top_p: + type: number + minimum: 0 + maximum: 1 + default: 1 + example: 1 + nullable: true + description: *run_top_p_description + stream: + type: boolean + nullable: true + description: | + If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message. + max_prompt_tokens: + type: integer + nullable: true + description: | + The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. + minimum: 256 + max_completion_tokens: + type: integer + nullable: true + description: | + The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. + minimum: 256 + truncation_strategy: + $ref: "#/components/schemas/TruncationObject" + nullable: true + tool_choice: + $ref: "#/components/schemas/AssistantsApiToolChoiceOption" + nullable: true + response_format: + $ref: "#/components/schemas/AssistantsApiResponseFormatOption" + nullable: true + required: + - thread_id + - assistant_id + + ThreadObject: + type: object + title: Thread + description: Represents a thread that contains [messages](/docs/api-reference/messages). + properties: + id: + description: The identifier, which can be referenced in API endpoints. + type: string + object: + description: The object type, which is always `thread`. + type: string + enum: ["thread"] + created_at: + description: The Unix timestamp (in seconds) for when the thread was created. + type: integer + tool_resources: + type: object + description: | + A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. + properties: + code_interpreter: + type: object + properties: + file_ids: + type: array + description: | + A list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. + default: [] + maxItems: 20 + items: + type: string + file_search: + type: object + properties: + vector_store_ids: + type: array + description: | + The [vector store](/docs/api-reference/vector-stores/object) attached to this thread. There can be a maximum of 1 vector store attached to the thread. + maxItems: 1 + items: + type: string + nullable: true + metadata: + description: *metadata_description + type: object + x-oaiTypeLabel: map + nullable: true + required: + - id + - object + - created_at + - tool_resources + - metadata + x-oaiMeta: + name: The thread object + beta: true + example: | + { + "id": "thread_abc123", + "object": "thread", + "created_at": 1698107661, + "metadata": {} + } + + CreateThreadRequest: + type: object + additionalProperties: false + properties: + messages: + description: A list of [messages](/docs/api-reference/messages) to start the thread with. + type: array + items: + $ref: "#/components/schemas/CreateMessageRequest" + tool_resources: + type: object + description: | + A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. + properties: + code_interpreter: + type: object + properties: + file_ids: + type: array + description: | + A list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. + default: [] + maxItems: 20 + items: + type: string + file_search: + type: object + properties: + vector_store_ids: + type: array + description: | + The [vector store](/docs/api-reference/vector-stores/object) attached to this thread. There can be a maximum of 1 vector store attached to the thread. + maxItems: 1 + items: + type: string + vector_stores: + type: array + description: | + A helper to create a [vector store](/docs/api-reference/vector-stores/object) with file_ids and attach it to this thread. There can be a maximum of 1 vector store attached to the thread. + maxItems: 1 + items: + type: object + properties: + file_ids: + type: array + description: | + A list of [file](/docs/api-reference/files) IDs to add to the vector store. There can be a maximum of 10000 files in a vector store. + maxItems: 10000 + items: + type: string + metadata: + type: object + description: | + Set of 16 key-value pairs that can be attached to a vector store. This can be useful for storing additional information about the vector store in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long. + x-oaiTypeLabel: map + oneOf: + - required: [vector_store_ids] + - required: [vector_stores] + nullable: true + metadata: + description: *metadata_description + type: object + x-oaiTypeLabel: map + nullable: true + + ModifyThreadRequest: + type: object + additionalProperties: false + properties: + tool_resources: + type: object + description: | + A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. + properties: + code_interpreter: + type: object + properties: + file_ids: + type: array + description: | + A list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool. + default: [] + maxItems: 20 + items: + type: string + file_search: + type: object + properties: + vector_store_ids: + type: array + description: | + The [vector store](/docs/api-reference/vector-stores/object) attached to this thread. There can be a maximum of 1 vector store attached to the thread. + maxItems: 1 + items: + type: string + nullable: true + metadata: + description: *metadata_description + type: object + x-oaiTypeLabel: map + nullable: true + + DeleteThreadResponse: + type: object + properties: + id: + type: string + deleted: + type: boolean + object: + type: string + enum: [thread.deleted] + required: + - id + - object + - deleted + + ListThreadsResponse: + properties: + object: + type: string + example: "list" + data: + type: array + items: + $ref: "#/components/schemas/ThreadObject" + first_id: + type: string + example: "asst_abc123" + last_id: + type: string + example: "asst_abc456" + has_more: + type: boolean + example: false + required: + - object + - data + - first_id + - last_id + - has_more + + MessageObject: + type: object + title: The message object + description: Represents a message within a [thread](/docs/api-reference/threads). + properties: + id: + description: The identifier, which can be referenced in API endpoints. + type: string + object: + description: The object type, which is always `thread.message`. + type: string + enum: ["thread.message"] + created_at: + description: The Unix timestamp (in seconds) for when the message was created. + type: integer + thread_id: + description: The [thread](/docs/api-reference/threads) ID that this message belongs to. + type: string + status: + description: The status of the message, which can be either `in_progress`, `incomplete`, or `completed`. + type: string + enum: ["in_progress", "incomplete", "completed"] + incomplete_details: + description: On an incomplete message, details about why the message is incomplete. + type: object + properties: + reason: + type: string + description: The reason the message is incomplete. + enum: + [ + "content_filter", + "max_tokens", + "run_cancelled", + "run_expired", + "run_failed", + ] + nullable: true + required: + - reason + completed_at: + description: The Unix timestamp (in seconds) for when the message was completed. + type: integer + nullable: true + incomplete_at: + description: The Unix timestamp (in seconds) for when the message was marked as incomplete. + type: integer + nullable: true + role: + description: The entity that produced the message. One of `user` or `assistant`. + type: string + enum: ["user", "assistant"] + content: + description: The content of the message in array of text and/or images. + type: array + items: + oneOf: + - $ref: "#/components/schemas/MessageContentImageFileObject" + - $ref: "#/components/schemas/MessageContentTextObject" + x-oaiExpandable: true + assistant_id: + description: If applicable, the ID of the [assistant](/docs/api-reference/assistants) that authored this message. + type: string + nullable: true + run_id: + description: The ID of the [run](/docs/api-reference/runs) associated with the creation of this message. Value is `null` when messages are created manually using the create message or create thread endpoints. + type: string + nullable: true + attachments: + type: array + items: + type: object + properties: + file_id: + type: string + description: The ID of the file to attach to the message. + tools: + description: The tools to add this file to. + type: array + items: + oneOf: + - $ref: "#/components/schemas/AssistantToolsCode" + - $ref: "#/components/schemas/AssistantToolsFileSearch" + x-oaiExpandable: true + description: A list of files attached to the message, and the tools they were added to. + nullable: true + metadata: + description: *metadata_description + type: object + x-oaiTypeLabel: map + nullable: true + required: + - id + - object + - created_at + - thread_id + - status + - incomplete_details + - completed_at + - incomplete_at + - role + - content + - assistant_id + - run_id + - attachments + - metadata + x-oaiMeta: + name: The message object + beta: true + example: | + { + "id": "msg_abc123", + "object": "thread.message", + "created_at": 1698983503, + "thread_id": "thread_abc123", + "role": "assistant", + "content": [ + { + "type": "text", + "text": { + "value": "Hi! How can I help you today?", + "annotations": [] + } + } + ], + "assistant_id": "asst_abc123", + "run_id": "run_abc123", + "attachments": [], + "metadata": {} + } + + MessageDeltaObject: + type: object + title: Message delta object + description: | + Represents a message delta i.e. any changed fields on a message during streaming. + properties: + id: + description: The identifier of the message, which can be referenced in API endpoints. + type: string + object: + description: The object type, which is always `thread.message.delta`. + type: string + enum: ["thread.message.delta"] + delta: + description: The delta containing the fields that have changed on the Message. + type: object + properties: + role: + description: The entity that produced the message. One of `user` or `assistant`. + type: string + enum: ["user", "assistant"] + content: + description: The content of the message in array of text and/or images. + type: array + items: + oneOf: + - $ref: "#/components/schemas/MessageDeltaContentImageFileObject" + - $ref: "#/components/schemas/MessageDeltaContentTextObject" + x-oaiExpandable: true + required: + - id + - object + - delta + x-oaiMeta: + name: The message delta object + beta: true + example: | + { + "id": "msg_123", + "object": "thread.message.delta", + "delta": { + "content": [ + { + "index": 0, + "type": "text", + "text": { "value": "Hello", "annotations": [] } + } + ] + } + } + + CreateMessageRequest: + type: object + additionalProperties: false + required: + - role + - content + properties: + role: + type: string + enum: ["user", "assistant"] + description: | + The role of the entity that is creating the message. Allowed values include: + - `user`: Indicates the message is sent by an actual user and should be used in most cases to represent user-generated messages. + - `assistant`: Indicates the message is generated by the assistant. Use this value to insert messages from the assistant into the conversation. + content: + type: string + minLength: 1 + maxLength: 256000 + description: The content of the message. + attachments: + type: array + items: + type: object + properties: + file_id: + type: string + description: The ID of the file to attach to the message. + tools: + description: The tools to add this file to. + type: array + items: + oneOf: + - $ref: "#/components/schemas/AssistantToolsCode" + - $ref: "#/components/schemas/AssistantToolsFileSearch" + x-oaiExpandable: true + description: A list of files attached to the message, and the tools they should be added to. + required: + - file_id + - tools + nullable: true + metadata: + description: *metadata_description + type: object + x-oaiTypeLabel: map + nullable: true + + ModifyMessageRequest: + type: object + additionalProperties: false + properties: + metadata: + description: *metadata_description + type: object + x-oaiTypeLabel: map + nullable: true + + DeleteMessageResponse: + type: object + properties: + id: + type: string + deleted: + type: boolean + object: + type: string + enum: [thread.message.deleted] + required: + - id + - object + - deleted + + ListMessagesResponse: + properties: + object: + type: string + example: "list" + data: + type: array + items: + $ref: "#/components/schemas/MessageObject" + first_id: + type: string + example: "msg_abc123" + last_id: + type: string + example: "msg_abc123" + has_more: + type: boolean + example: false + required: + - object + - data + - first_id + - last_id + - has_more + + MessageContentImageFileObject: + title: Image file + type: object + description: References an image [File](/docs/api-reference/files) in the content of a message. + properties: + type: + description: Always `image_file`. + type: string + enum: ["image_file"] + image_file: + type: object + properties: + file_id: + description: The [File](/docs/api-reference/files) ID of the image in the message content. + type: string + required: + - file_id + required: + - type + - image_file + + MessageDeltaContentImageFileObject: + title: Image file + type: object + description: References an image [File](/docs/api-reference/files) in the content of a message. + properties: + index: + type: integer + description: The index of the content part in the message. + type: + description: Always `image_file`. + type: string + enum: ["image_file"] + image_file: + type: object + properties: + file_id: + description: The [File](/docs/api-reference/files) ID of the image in the message content. + type: string + required: + - index + - type + + MessageContentTextObject: + title: Text + type: object + description: The text content that is part of a message. + properties: + type: + description: Always `text`. + type: string + enum: ["text"] + text: + type: object + properties: + value: + description: The data that makes up the text. + type: string + annotations: + type: array + items: + oneOf: + - $ref: "#/components/schemas/MessageContentTextAnnotationsFileCitationObject" + - $ref: "#/components/schemas/MessageContentTextAnnotationsFilePathObject" + x-oaiExpandable: true + required: + - value + - annotations + required: + - type + - text + + MessageContentTextAnnotationsFileCitationObject: + title: File citation + type: object + description: A citation within the message that points to a specific quote from a specific File associated with the assistant or the message. Generated when the assistant uses the "file_search" tool to search files. + properties: + type: + description: Always `file_citation`. + type: string + enum: ["file_citation"] + text: + description: The text in the message content that needs to be replaced. + type: string + file_citation: + type: object + properties: + file_id: + description: The ID of the specific File the citation is from. + type: string + quote: + description: The specific quote in the file. + type: string + required: + - file_id + - quote + start_index: + type: integer + minimum: 0 + end_index: + type: integer + minimum: 0 + required: + - type + - text + - file_citation + - start_index + - end_index + + MessageContentTextAnnotationsFilePathObject: + title: File path + type: object + description: A URL for the file that's generated when the assistant used the `code_interpreter` tool to generate a file. + properties: + type: + description: Always `file_path`. + type: string + enum: ["file_path"] + text: + description: The text in the message content that needs to be replaced. + type: string + file_path: + type: object + properties: + file_id: + description: The ID of the file that was generated. + type: string + required: + - file_id + start_index: + type: integer + minimum: 0 + end_index: + type: integer + minimum: 0 + required: + - type + - text + - file_path + - start_index + - end_index + + MessageDeltaContentTextObject: + title: Text + type: object + description: The text content that is part of a message. + properties: + index: + type: integer + description: The index of the content part in the message. + type: + description: Always `text`. + type: string + enum: ["text"] + text: + type: object + properties: + value: + description: The data that makes up the text. + type: string + annotations: + type: array + items: + oneOf: + - $ref: "#/components/schemas/MessageDeltaContentTextAnnotationsFileCitationObject" + - $ref: "#/components/schemas/MessageDeltaContentTextAnnotationsFilePathObject" + x-oaiExpandable: true + required: + - index + - type + + MessageDeltaContentTextAnnotationsFileCitationObject: + title: File citation + type: object + description: A citation within the message that points to a specific quote from a specific File associated with the assistant or the message. Generated when the assistant uses the "file_search" tool to search files. + properties: + index: + type: integer + description: The index of the annotation in the text content part. + type: + description: Always `file_citation`. + type: string + enum: ["file_citation"] + text: + description: The text in the message content that needs to be replaced. + type: string + file_citation: + type: object + properties: + file_id: + description: The ID of the specific File the citation is from. + type: string + quote: + description: The specific quote in the file. + type: string + start_index: + type: integer + minimum: 0 + end_index: + type: integer + minimum: 0 + required: + - index + - type + + MessageDeltaContentTextAnnotationsFilePathObject: + title: File path + type: object + description: A URL for the file that's generated when the assistant used the `code_interpreter` tool to generate a file. + properties: + index: + type: integer + description: The index of the annotation in the text content part. + type: + description: Always `file_path`. + type: string + enum: ["file_path"] + text: + description: The text in the message content that needs to be replaced. + type: string + file_path: + type: object + properties: + file_id: + description: The ID of the file that was generated. + type: string + start_index: + type: integer + minimum: 0 + end_index: + type: integer + minimum: 0 + required: + - index + - type + + RunStepObject: + type: object + title: Run steps + description: | + Represents a step in execution of a run. + properties: + id: + description: The identifier of the run step, which can be referenced in API endpoints. + type: string + object: + description: The object type, which is always `thread.run.step`. + type: string + enum: ["thread.run.step"] + created_at: + description: The Unix timestamp (in seconds) for when the run step was created. + type: integer + assistant_id: + description: The ID of the [assistant](/docs/api-reference/assistants) associated with the run step. + type: string + thread_id: + description: The ID of the [thread](/docs/api-reference/threads) that was run. + type: string + run_id: + description: The ID of the [run](/docs/api-reference/runs) that this run step is a part of. + type: string + type: + description: The type of run step, which can be either `message_creation` or `tool_calls`. + type: string + enum: ["message_creation", "tool_calls"] + status: + description: The status of the run step, which can be either `in_progress`, `cancelled`, `failed`, `completed`, or `expired`. + type: string + enum: ["in_progress", "cancelled", "failed", "completed", "expired"] + step_details: + type: object + description: The details of the run step. + oneOf: + - $ref: "#/components/schemas/RunStepDetailsMessageCreationObject" + - $ref: "#/components/schemas/RunStepDetailsToolCallsObject" + x-oaiExpandable: true + last_error: + type: object + description: The last error associated with this run step. Will be `null` if there are no errors. + nullable: true + properties: + code: + type: string + description: One of `server_error` or `rate_limit_exceeded`. + enum: ["server_error", "rate_limit_exceeded"] + message: + type: string + description: A human-readable description of the error. + required: + - code + - message + expired_at: + description: The Unix timestamp (in seconds) for when the run step expired. A step is considered expired if the parent run is expired. + type: integer + nullable: true + cancelled_at: + description: The Unix timestamp (in seconds) for when the run step was cancelled. + type: integer + nullable: true + failed_at: + description: The Unix timestamp (in seconds) for when the run step failed. + type: integer + nullable: true + completed_at: + description: The Unix timestamp (in seconds) for when the run step completed. + type: integer + nullable: true + metadata: + description: *metadata_description + type: object + x-oaiTypeLabel: map + nullable: true + usage: + $ref: "#/components/schemas/RunStepCompletionUsage" + required: + - id + - object + - created_at + - assistant_id + - thread_id + - run_id + - type + - status + - step_details + - last_error + - expired_at + - cancelled_at + - failed_at + - completed_at + - metadata + - usage + x-oaiMeta: + name: The run step object + beta: true + example: *run_step_object_example + + RunStepDeltaObject: + type: object + title: Run step delta object + description: | + Represents a run step delta i.e. any changed fields on a run step during streaming. + properties: + id: + description: The identifier of the run step, which can be referenced in API endpoints. + type: string + object: + description: The object type, which is always `thread.run.step.delta`. + type: string + enum: ["thread.run.step.delta"] + delta: + description: The delta containing the fields that have changed on the run step. + type: object + properties: + step_details: + type: object + description: The details of the run step. + oneOf: + - $ref: "#/components/schemas/RunStepDeltaStepDetailsMessageCreationObject" + - $ref: "#/components/schemas/RunStepDeltaStepDetailsToolCallsObject" + x-oaiExpandable: true + required: + - id + - object + - delta + x-oaiMeta: + name: The run step delta object + beta: true + example: | + { + "id": "step_123", + "object": "thread.run.step.delta", + "delta": { + "step_details": { + "type": "tool_calls", + "tool_calls": [ + { + "index": 0, + "id": "call_123", + "type": "code_interpreter", + "code_interpreter": { "input": "", "outputs": [] } + } + ] + } + } + } + + ListRunStepsResponse: + properties: + object: + type: string + example: "list" + data: + type: array + items: + $ref: "#/components/schemas/RunStepObject" + first_id: + type: string + example: "step_abc123" + last_id: + type: string + example: "step_abc456" + has_more: + type: boolean + example: false + required: + - object + - data + - first_id + - last_id + - has_more + + RunStepDetailsMessageCreationObject: + title: Message creation + type: object + description: Details of the message creation by the run step. + properties: + type: + description: Always `message_creation`. + type: string + enum: ["message_creation"] + message_creation: + type: object + properties: + message_id: + type: string + description: The ID of the message that was created by this run step. + required: + - message_id + required: + - type + - message_creation + + RunStepDeltaStepDetailsMessageCreationObject: + title: Message creation + type: object + description: Details of the message creation by the run step. + properties: + type: + description: Always `message_creation`. + type: string + enum: ["message_creation"] + message_creation: + type: object + properties: + message_id: + type: string + description: The ID of the message that was created by this run step. + required: + - type + + RunStepDetailsToolCallsObject: + title: Tool calls + type: object + description: Details of the tool call. + properties: + type: + description: Always `tool_calls`. + type: string + enum: ["tool_calls"] + tool_calls: + type: array + description: | + An array of tool calls the run step was involved in. These can be associated with one of three types of tools: `code_interpreter`, `file_search`, or `function`. + items: + oneOf: + - $ref: "#/components/schemas/RunStepDetailsToolCallsCodeObject" + - $ref: "#/components/schemas/RunStepDetailsToolCallsFileSearchObject" + - $ref: "#/components/schemas/RunStepDetailsToolCallsFunctionObject" + x-oaiExpandable: true + required: + - type + - tool_calls + + RunStepDeltaStepDetailsToolCallsObject: + title: Tool calls + type: object + description: Details of the tool call. + properties: + type: + description: Always `tool_calls`. + type: string + enum: ["tool_calls"] + tool_calls: + type: array + description: | + An array of tool calls the run step was involved in. These can be associated with one of three types of tools: `code_interpreter`, `file_search`, or `function`. + items: + oneOf: + - $ref: "#/components/schemas/RunStepDeltaStepDetailsToolCallsCodeObject" + - $ref: "#/components/schemas/RunStepDeltaStepDetailsToolCallsFileSearchObject" + - $ref: "#/components/schemas/RunStepDeltaStepDetailsToolCallsFunctionObject" + x-oaiExpandable: true + required: + - type + + RunStepDetailsToolCallsCodeObject: + title: Code Interpreter tool call + type: object + description: Details of the Code Interpreter tool call the run step was involved in. + properties: + id: + type: string + description: The ID of the tool call. + type: + type: string + description: The type of tool call. This is always going to be `code_interpreter` for this type of tool call. + enum: ["code_interpreter"] + code_interpreter: + type: object + description: The Code Interpreter tool call definition. + required: + - input + - outputs + properties: + input: + type: string + description: The input to the Code Interpreter tool call. + outputs: + type: array + description: The outputs from the Code Interpreter tool call. Code Interpreter can output one or more items, including text (`logs`) or images (`image`). Each of these are represented by a different object type. + items: + type: object + oneOf: + - $ref: "#/components/schemas/RunStepDetailsToolCallsCodeOutputLogsObject" + - $ref: "#/components/schemas/RunStepDetailsToolCallsCodeOutputImageObject" + x-oaiExpandable: true + required: + - id + - type + - code_interpreter + + RunStepDeltaStepDetailsToolCallsCodeObject: + title: Code interpreter tool call + type: object + description: Details of the Code Interpreter tool call the run step was involved in. + properties: + index: + type: integer + description: The index of the tool call in the tool calls array. + id: + type: string + description: The ID of the tool call. + type: + type: string + description: The type of tool call. This is always going to be `code_interpreter` for this type of tool call. + enum: ["code_interpreter"] + code_interpreter: + type: object + description: The Code Interpreter tool call definition. + properties: + input: + type: string + description: The input to the Code Interpreter tool call. + outputs: + type: array + description: The outputs from the Code Interpreter tool call. Code Interpreter can output one or more items, including text (`logs`) or images (`image`). Each of these are represented by a different object type. + items: + type: object + oneOf: + - $ref: "#/components/schemas/RunStepDeltaStepDetailsToolCallsCodeOutputLogsObject" + - $ref: "#/components/schemas/RunStepDeltaStepDetailsToolCallsCodeOutputImageObject" + x-oaiExpandable: true + required: + - index + - type + + RunStepDetailsToolCallsCodeOutputLogsObject: + title: Code Interpreter log output + type: object + description: Text output from the Code Interpreter tool call as part of a run step. + properties: + type: + description: Always `logs`. + type: string + enum: ["logs"] + logs: + type: string + description: The text output from the Code Interpreter tool call. + required: + - type + - logs + + RunStepDeltaStepDetailsToolCallsCodeOutputLogsObject: + title: Code interpreter log output + type: object + description: Text output from the Code Interpreter tool call as part of a run step. + properties: + index: + type: integer + description: The index of the output in the outputs array. + type: + description: Always `logs`. + type: string + enum: ["logs"] + logs: + type: string + description: The text output from the Code Interpreter tool call. + required: + - index + - type + + RunStepDetailsToolCallsCodeOutputImageObject: + title: Code Interpreter image output + type: object + properties: + type: + description: Always `image`. + type: string + enum: ["image"] + image: + type: object + properties: + file_id: + description: The [file](/docs/api-reference/files) ID of the image. + type: string + required: + - file_id + required: + - type + - image + + RunStepDeltaStepDetailsToolCallsCodeOutputImageObject: + title: Code interpreter image output + type: object + properties: + index: + type: integer + description: The index of the output in the outputs array. + type: + description: Always `image`. + type: string + enum: ["image"] + image: + type: object + properties: + file_id: + description: The [file](/docs/api-reference/files) ID of the image. + type: string + required: + - index + - type + + RunStepDetailsToolCallsFileSearchObject: + title: File search tool call + type: object + properties: + id: + type: string + description: The ID of the tool call object. + type: + type: string + description: The type of tool call. This is always going to be `file_search` for this type of tool call. + enum: ["file_search"] + file_search: + type: object + description: For now, this is always going to be an empty object. + x-oaiTypeLabel: map + required: + - id + - type + - file_search + + RunStepDeltaStepDetailsToolCallsFileSearchObject: + title: File search tool call + type: object + properties: + index: + type: integer + description: The index of the tool call in the tool calls array. + id: + type: string + description: The ID of the tool call object. + type: + type: string + description: The type of tool call. This is always going to be `file_search` for this type of tool call. + enum: ["file_search"] + file_search: + type: object + description: For now, this is always going to be an empty object. + x-oaiTypeLabel: map + required: + - index + - type + - file_search + + RunStepDetailsToolCallsFunctionObject: + type: object + title: Function tool call + properties: + id: + type: string + description: The ID of the tool call object. + type: + type: string + description: The type of tool call. This is always going to be `function` for this type of tool call. + enum: ["function"] + function: + type: object + description: The definition of the function that was called. + properties: + name: + type: string + description: The name of the function. + arguments: + type: string + description: The arguments passed to the function. + output: + type: string + description: The output of the function. This will be `null` if the outputs have not been [submitted](/docs/api-reference/runs/submitToolOutputs) yet. + nullable: true + required: + - name + - arguments + - output + required: + - id + - type + - function + + RunStepDeltaStepDetailsToolCallsFunctionObject: + type: object + title: Function tool call + properties: + index: + type: integer + description: The index of the tool call in the tool calls array. + id: + type: string + description: The ID of the tool call object. + type: + type: string + description: The type of tool call. This is always going to be `function` for this type of tool call. + enum: ["function"] + function: + type: object + description: The definition of the function that was called. + properties: + name: + type: string + description: The name of the function. + arguments: + type: string + description: The arguments passed to the function. + output: + type: string + description: The output of the function. This will be `null` if the outputs have not been [submitted](/docs/api-reference/runs/submitToolOutputs) yet. + nullable: true + required: + - index + - type + + VectorStoreExpirationAfter: + type: object + title: Vector store expiration policy + description: The expiration policy for a vector store. + properties: + anchor: + description: "Anchor timestamp after which the expiration policy applies. Supported anchors: `last_active_at`." + type: string + enum: ["last_active_at"] + days: + description: The number of days after the anchor time that the vector store will expire. + type: integer + minimum: 1 + maximum: 365 + required: + - anchor + - days + + VectorStoreObject: + type: object + title: Vector store + description: A vector store is a collection of processed files can be used by the `file_search` tool. + properties: + id: + description: The identifier, which can be referenced in API endpoints. + type: string + object: + description: The object type, which is always `vector_store`. + type: string + enum: ["vector_store"] + created_at: + description: The Unix timestamp (in seconds) for when the vector store was created. + type: integer + name: + description: The name of the vector store. + type: string + usage_bytes: + description: The total number of bytes used by the files in the vector store. + type: integer + file_counts: + type: object + properties: + in_progress: + description: The number of files that are currently being processed. + type: integer + completed: + description: The number of files that have been successfully processed. + type: integer + failed: + description: The number of files that have failed to process. + type: integer + cancelled: + description: The number of files that were cancelled. + type: integer + total: + description: The total number of files. + type: integer + required: + - in_progress + - completed + - failed + - cancelled + - total + status: + description: The status of the vector store, which can be either `expired`, `in_progress`, or `completed`. A status of `completed` indicates that the vector store is ready for use. + type: string + enum: ["expired", "in_progress", "completed"] + expires_after: + $ref: "#/components/schemas/VectorStoreExpirationAfter" + expires_at: + description: The Unix timestamp (in seconds) for when the vector store will expire. + type: integer + nullable: true + last_active_at: + description: The Unix timestamp (in seconds) for when the vector store was last active. + type: integer + nullable: true + metadata: + description: *metadata_description + type: object + x-oaiTypeLabel: map + nullable: true + required: + - id + - object + - usage_bytes + - created_at + - status + - last_active_at + - name + - file_counts + - metadata + x-oaiMeta: + name: The vector store object + beta: true + example: | + { + "id": "vs_123", + "object": "vector_store", + "created_at": 1698107661, + "usage_bytes": 123456, + "last_active_at": 1698107661, + "name": "my_vector_store", + "status": "completed", + "file_counts": { + "in_progress": 0, + "completed": 100, + "cancelled": 0, + "failed": 0, + "total": 100 + }, + "metadata": {}, + "last_used_at": 1698107661 + } + + CreateVectorStoreRequest: + type: object + additionalProperties: false + properties: + file_ids: + description: A list of [File](/docs/api-reference/files) IDs that the vector store should use. Useful for tools like `file_search` that can access files. + type: array + maxItems: 500 + items: + type: string + name: + description: The name of the vector store. + type: string + expires_after: + $ref: "#/components/schemas/VectorStoreExpirationAfter" + metadata: + description: *metadata_description + type: object + x-oaiTypeLabel: map + nullable: true + + UpdateVectorStoreRequest: + type: object + additionalProperties: false + properties: + name: + description: The name of the vector store. + type: string + nullable: true + expires_after: + $ref: "#/components/schemas/VectorStoreExpirationAfter" + nullable: true + metadata: + description: *metadata_description + type: object + x-oaiTypeLabel: map + nullable: true + + ListVectorStoresResponse: + properties: + object: + type: string + example: "list" + data: + type: array + items: + $ref: "#/components/schemas/VectorStoreObject" + first_id: + type: string + example: "vs_abc123" + last_id: + type: string + example: "vs_abc456" + has_more: + type: boolean + example: false + required: + - object + - data + - first_id + - last_id + - has_more + + DeleteVectorStoreResponse: + type: object + properties: + id: + type: string + deleted: + type: boolean + object: + type: string + enum: [vector_store.deleted] + required: + - id + - object + - deleted + + VectorStoreFileObject: + type: object + title: Vector store files + description: A list of files attached to a vector store. + properties: + id: + description: The identifier, which can be referenced in API endpoints. + type: string + object: + description: The object type, which is always `vector_store.file`. + type: string + enum: ["vector_store.file"] + usage_bytes: + description: The total vector store usage in bytes. Note that this may be different from the original file size. + type: integer + created_at: + description: The Unix timestamp (in seconds) for when the vector store file was created. + type: integer + vector_store_id: + description: The ID of the [vector store](/docs/api-reference/vector-stores/object) that the [File](/docs/api-reference/files) is attached to. + type: string + status: + description: The status of the vector store file, which can be either `in_progress`, `completed`, `cancelled`, or `failed`. The status `completed` indicates that the vector store file is ready for use. + type: string + enum: ["in_progress", "completed", "cancelled", "failed"] + last_error: + type: object + description: The last error associated with this vector store file. Will be `null` if there are no errors. + nullable: true + properties: + code: + type: string + description: One of `server_error` or `rate_limit_exceeded`. + enum: + [ + "internal_error", + "file_not_found", + "parsing_error", + "unhandled_mime_type", + ] + message: + type: string + description: A human-readable description of the error. + required: + - code + - message + required: + - id + - object + - usage_bytes + - created_at + - vector_store_id + - status + - last_error + x-oaiMeta: + name: The vector store file object + beta: true + example: | + { + "id": "file-abc123", + "object": "vector_store.file", + "usage_bytes": 1234, + "created_at": 1698107661, + "vector_store_id": "vs_abc123", + "status": "completed", + "last_error": null + } + + CreateVectorStoreFileRequest: + type: object + additionalProperties: false + properties: + file_id: + description: A [File](/docs/api-reference/files) ID that the vector store should use. Useful for tools like `file_search` that can access files. + type: string + required: + - file_id + + ListVectorStoreFilesResponse: + properties: + object: + type: string + example: "list" + data: + type: array + items: + $ref: "#/components/schemas/VectorStoreFileObject" + first_id: + type: string + example: "file-abc123" + last_id: + type: string + example: "file-abc456" + has_more: + type: boolean + example: false + required: + - object + - data + - first_id + - last_id + - has_more + + DeleteVectorStoreFileResponse: + type: object + properties: + id: + type: string + deleted: + type: boolean + object: + type: string + enum: [vector_store.file.deleted] + required: + - id + - object + - deleted + + VectorStoreFileBatchObject: + type: object + title: Vector store file batch + description: A batch of files attached to a vector store. + properties: + id: + description: The identifier, which can be referenced in API endpoints. + type: string + object: + description: The object type, which is always `vector_store.file_batch`. + type: string + enum: ["vector_store.files_batch"] + created_at: + description: The Unix timestamp (in seconds) for when the vector store files batch was created. + type: integer + vector_store_id: + description: The ID of the [vector store](/docs/api-reference/vector-stores/object) that the [File](/docs/api-reference/files) is attached to. + type: string + status: + description: The status of the vector store files batch, which can be either `in_progress`, `completed`, `cancelled` or `failed`. + type: string + enum: ["in_progress", "completed", "cancelled", "failed"] + file_counts: + type: object + properties: + in_progress: + description: The number of files that are currently being processed. + type: integer + completed: + description: The number of files that have been processed. + type: integer + failed: + description: The number of files that have failed to process. + type: integer + cancelled: + description: The number of files that where cancelled. + type: integer + total: + description: The total number of files. + type: integer + required: + - in_progress + - completed + - cancelled + - failed + - total + required: + - id + - object + - created_at + - vector_store_id + - status + - file_counts + x-oaiMeta: + name: The vector store files batch object + beta: true + example: | + { + "id": "vsfb_123", + "object": "vector_store.files_batch", + "created_at": 1698107661, + "vector_store_id": "vs_abc123", + "status": "completed", + "file_counts": { + "in_progress": 0, + "completed": 100, + "failed": 0, + "cancelled": 0, + "total": 100 + } + } + + CreateVectorStoreFileBatchRequest: + type: object + additionalProperties: false + properties: + file_ids: + description: A list of [File](/docs/api-reference/files) IDs that the vector store should use. Useful for tools like `file_search` that can access files. + type: array + minItems: 1 + maxItems: 500 + items: + type: string + required: + - file_ids + + AssistantStreamEvent: + description: | + Represents an event emitted when streaming a Run. + + Each event in a server-sent events stream has an `event` and `data` property: + + ``` + event: thread.created + data: {"id": "thread_123", "object": "thread", ...} + ``` + + We emit events whenever a new object is created, transitions to a new state, or is being + streamed in parts (deltas). For example, we emit `thread.run.created` when a new run + is created, `thread.run.completed` when a run completes, and so on. When an Assistant chooses + to create a message during a run, we emit a `thread.message.created event`, a + `thread.message.in_progress` event, many `thread.message.delta` events, and finally a + `thread.message.completed` event. + + We may add additional events over time, so we recommend handling unknown events gracefully + in your code. See the [Assistants API quickstart](/docs/assistants/overview) to learn how to + integrate the Assistants API with streaming. + oneOf: + - $ref: "#/components/schemas/ThreadStreamEvent" + - $ref: "#/components/schemas/RunStreamEvent" + - $ref: "#/components/schemas/RunStepStreamEvent" + - $ref: "#/components/schemas/MessageStreamEvent" + - $ref: "#/components/schemas/ErrorEvent" + - $ref: "#/components/schemas/DoneEvent" + x-oaiMeta: + name: Assistant stream events + beta: true + + ThreadStreamEvent: + oneOf: + - type: object + properties: + event: + type: string + enum: ["thread.created"] + data: + $ref: "#/components/schemas/ThreadObject" + required: + - event + - data + description: Occurs when a new [thread](/docs/api-reference/threads/object) is created. + x-oaiMeta: + dataDescription: "`data` is a [thread](/docs/api-reference/threads/object)" + + RunStreamEvent: + oneOf: + - type: object + properties: + event: + type: string + enum: ["thread.run.created"] + data: + $ref: "#/components/schemas/RunObject" + required: + - event + - data + description: Occurs when a new [run](/docs/api-reference/runs/object) is created. + x-oaiMeta: + dataDescription: "`data` is a [run](/docs/api-reference/runs/object)" + - type: object + properties: + event: + type: string + enum: ["thread.run.queued"] + data: + $ref: "#/components/schemas/RunObject" + required: + - event + - data + description: Occurs when a [run](/docs/api-reference/runs/object) moves to a `queued` status. + x-oaiMeta: + dataDescription: "`data` is a [run](/docs/api-reference/runs/object)" + - type: object + properties: + event: + type: string + enum: ["thread.run.in_progress"] + data: + $ref: "#/components/schemas/RunObject" + required: + - event + - data + description: Occurs when a [run](/docs/api-reference/runs/object) moves to an `in_progress` status. + x-oaiMeta: + dataDescription: "`data` is a [run](/docs/api-reference/runs/object)" + - type: object + properties: + event: + type: string + enum: ["thread.run.requires_action"] + data: + $ref: "#/components/schemas/RunObject" + required: + - event + - data + description: Occurs when a [run](/docs/api-reference/runs/object) moves to a `requires_action` status. + x-oaiMeta: + dataDescription: "`data` is a [run](/docs/api-reference/runs/object)" + - type: object + properties: + event: + type: string + enum: ["thread.run.completed"] + data: + $ref: "#/components/schemas/RunObject" + required: + - event + - data + description: Occurs when a [run](/docs/api-reference/runs/object) is completed. + x-oaiMeta: + dataDescription: "`data` is a [run](/docs/api-reference/runs/object)" + - type: object + properties: + event: + type: string + enum: ["thread.run.failed"] + data: + $ref: "#/components/schemas/RunObject" + required: + - event + - data + description: Occurs when a [run](/docs/api-reference/runs/object) fails. + x-oaiMeta: + dataDescription: "`data` is a [run](/docs/api-reference/runs/object)" + - type: object + properties: + event: + type: string + enum: ["thread.run.cancelling"] + data: + $ref: "#/components/schemas/RunObject" + required: + - event + - data + description: Occurs when a [run](/docs/api-reference/runs/object) moves to a `cancelling` status. + x-oaiMeta: + dataDescription: "`data` is a [run](/docs/api-reference/runs/object)" + - type: object + properties: + event: + type: string + enum: ["thread.run.cancelled"] + data: + $ref: "#/components/schemas/RunObject" + required: + - event + - data + description: Occurs when a [run](/docs/api-reference/runs/object) is cancelled. + x-oaiMeta: + dataDescription: "`data` is a [run](/docs/api-reference/runs/object)" + - type: object + properties: + event: + type: string + enum: ["thread.run.expired"] + data: + $ref: "#/components/schemas/RunObject" + required: + - event + - data + description: Occurs when a [run](/docs/api-reference/runs/object) expires. + x-oaiMeta: + dataDescription: "`data` is a [run](/docs/api-reference/runs/object)" + + RunStepStreamEvent: + oneOf: + - type: object + properties: + event: + type: string + enum: ["thread.run.step.created"] + data: + $ref: "#/components/schemas/RunStepObject" + required: + - event + - data + description: Occurs when a [run step](/docs/api-reference/runs/step-object) is created. + x-oaiMeta: + dataDescription: "`data` is a [run step](/docs/api-reference/runs/step-object)" + - type: object + properties: + event: + type: string + enum: ["thread.run.step.in_progress"] + data: + $ref: "#/components/schemas/RunStepObject" + required: + - event + - data + description: Occurs when a [run step](/docs/api-reference/runs/step-object) moves to an `in_progress` state. + x-oaiMeta: + dataDescription: "`data` is a [run step](/docs/api-reference/runs/step-object)" + - type: object + properties: + event: + type: string + enum: ["thread.run.step.delta"] + data: + $ref: "#/components/schemas/RunStepDeltaObject" + required: + - event + - data + description: Occurs when parts of a [run step](/docs/api-reference/runs/step-object) are being streamed. + x-oaiMeta: + dataDescription: "`data` is a [run step delta](/docs/api-reference/assistants-streaming/run-step-delta-object)" + - type: object + properties: + event: + type: string + enum: ["thread.run.step.completed"] + data: + $ref: "#/components/schemas/RunStepObject" + required: + - event + - data + description: Occurs when a [run step](/docs/api-reference/runs/step-object) is completed. + x-oaiMeta: + dataDescription: "`data` is a [run step](/docs/api-reference/runs/step-object)" + - type: object + properties: + event: + type: string + enum: ["thread.run.step.failed"] + data: + $ref: "#/components/schemas/RunStepObject" + required: + - event + - data + description: Occurs when a [run step](/docs/api-reference/runs/step-object) fails. + x-oaiMeta: + dataDescription: "`data` is a [run step](/docs/api-reference/runs/step-object)" + - type: object + properties: + event: + type: string + enum: ["thread.run.step.cancelled"] + data: + $ref: "#/components/schemas/RunStepObject" + required: + - event + - data + description: Occurs when a [run step](/docs/api-reference/runs/step-object) is cancelled. + x-oaiMeta: + dataDescription: "`data` is a [run step](/docs/api-reference/runs/step-object)" + - type: object + properties: + event: + type: string + enum: ["thread.run.step.expired"] + data: + $ref: "#/components/schemas/RunStepObject" + required: + - event + - data + description: Occurs when a [run step](/docs/api-reference/runs/step-object) expires. + x-oaiMeta: + dataDescription: "`data` is a [run step](/docs/api-reference/runs/step-object)" + + MessageStreamEvent: + oneOf: + - type: object + properties: + event: + type: string + enum: ["thread.message.created"] + data: + $ref: "#/components/schemas/MessageObject" + required: + - event + - data + description: Occurs when a [message](/docs/api-reference/messages/object) is created. + x-oaiMeta: + dataDescription: "`data` is a [message](/docs/api-reference/messages/object)" + - type: object + properties: + event: + type: string + enum: ["thread.message.in_progress"] + data: + $ref: "#/components/schemas/MessageObject" + required: + - event + - data + description: Occurs when a [message](/docs/api-reference/messages/object) moves to an `in_progress` state. + x-oaiMeta: + dataDescription: "`data` is a [message](/docs/api-reference/messages/object)" + - type: object + properties: + event: + type: string + enum: ["thread.message.delta"] + data: + $ref: "#/components/schemas/MessageDeltaObject" + required: + - event + - data + description: Occurs when parts of a [Message](/docs/api-reference/messages/object) are being streamed. + x-oaiMeta: + dataDescription: "`data` is a [message delta](/docs/api-reference/assistants-streaming/message-delta-object)" + - type: object + properties: + event: + type: string + enum: ["thread.message.completed"] + data: + $ref: "#/components/schemas/MessageObject" + required: + - event + - data + description: Occurs when a [message](/docs/api-reference/messages/object) is completed. + x-oaiMeta: + dataDescription: "`data` is a [message](/docs/api-reference/messages/object)" + - type: object + properties: + event: + type: string + enum: ["thread.message.incomplete"] + data: + $ref: "#/components/schemas/MessageObject" + required: + - event + - data + description: Occurs when a [message](/docs/api-reference/messages/object) ends before it is completed. + x-oaiMeta: + dataDescription: "`data` is a [message](/docs/api-reference/messages/object)" + + ErrorEvent: + type: object + properties: + event: + type: string + enum: ["error"] + data: + $ref: "#/components/schemas/Error" + required: + - event + - data + description: Occurs when an [error](/docs/guides/error-codes/api-errors) occurs. This can happen due to an internal server error or a timeout. + x-oaiMeta: + dataDescription: "`data` is an [error](/docs/guides/error-codes/api-errors)" + + DoneEvent: + type: object + properties: + event: + type: string + enum: ["done"] + data: + type: string + enum: ["[DONE]"] + required: + - event + - data + description: Occurs when a stream ends. + x-oaiMeta: + dataDescription: "`data` is `[DONE]`" + + Batch: + type: object + properties: + id: + type: string + object: + type: string + enum: [batch] + description: The object type, which is always `batch`. + endpoint: + type: string + description: The OpenAI API endpoint used by the batch. + + errors: + type: object + properties: + object: + type: string + description: The object type, which is always `list`. + data: + type: array + items: + type: object + properties: + code: + type: string + description: An error code identifying the error type. + message: + type: string + description: A human-readable message providing more details about the error. + param: + type: string + description: The name of the parameter that caused the error, if applicable. + nullable: true + line: + type: integer + description: The line number of the input file where the error occurred, if applicable. + nullable: true + input_file_id: + type: string + description: The ID of the input file for the batch. + completion_window: + type: string + description: The time frame within which the batch should be processed. + status: + type: string + description: The current status of the batch. + enum: + - validating + - failed + - in_progress + - finalizing + - completed + - expired + - cancelling + - cancelled + output_file_id: + type: string + description: The ID of the file containing the outputs of successfully executed requests. + error_file_id: + type: string + description: The ID of the file containing the outputs of requests with errors. + created_at: + type: integer + description: The Unix timestamp (in seconds) for when the batch was created. + in_progress_at: + type: integer + description: The Unix timestamp (in seconds) for when the batch started processing. + expires_at: + type: integer + description: The Unix timestamp (in seconds) for when the batch will expire. + finalizing_at: + type: integer + description: The Unix timestamp (in seconds) for when the batch started finalizing. + completed_at: + type: integer + description: The Unix timestamp (in seconds) for when the batch was completed. + failed_at: + type: integer + description: The Unix timestamp (in seconds) for when the batch failed. + expired_at: + type: integer + description: The Unix timestamp (in seconds) for when the batch expired. + cancelling_at: + type: integer + description: The Unix timestamp (in seconds) for when the batch started cancelling. + cancelled_at: + type: integer + description: The Unix timestamp (in seconds) for when the batch was cancelled. + request_counts: + type: object + properties: + total: + type: integer + description: Total number of requests in the batch. + completed: + type: integer + description: Number of requests that have been completed successfully. + failed: + type: integer + description: Number of requests that have failed. + required: + - total + - completed + - failed + description: The request counts for different statuses within the batch. + metadata: + description: *metadata_description + type: object + x-oaiTypeLabel: map + nullable: true + required: + - id + - object + - endpoint + - input_file_id + - completion_window + - status + - created_at + x-oaiMeta: + name: The batch object + example: *batch_object + + BatchRequestInput: + type: object + description: The per-line object of the batch input file + properties: + custom_id: + type: string + description: A developer-provided per-request id that will be used to match outputs to inputs. Must be unique for each request in a batch. + method: + type: string + enum: ["POST"] + description: The HTTP method to be used for the request. Currently only `POST` is supported. + url: + type: string + description: The OpenAI API relative URL to be used for the request. Currently `/v1/chat/completions` and `/v1/embeddings` are supported. + x-oaiMeta: + name: The request input object + example: | + {"custom_id": "request-1", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "gpt-3.5-turbo", "messages": [{"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "What is 2+2?"}]}} + + BatchRequestOutput: + type: object + description: The per-line object of the batch output and error files + properties: + id: + type: string + custom_id: + type: string + description: A developer-provided per-request id that will be used to match outputs to inputs. + response: + type: object + nullable: true + properties: + status_code: + type: integer + description: The HTTP status code of the response + request_id: + type: string + description: An unique identifier for the OpenAI API request. Please include this request ID when contacting support. + body: + type: object + x-oaiTypeLabel: map + description: The JSON body of the response + error: + type: object + nullable: true + description: For requests that failed with a non-HTTP error, this will contain more information on the cause of the failure. + properties: + code: + type: string + description: A machine-readable error code. + message: + type: string + description: A human-readable error message. + x-oaiMeta: + name: The request output object + example: | + {"id": "batch_req_wnaDys", "custom_id": "request-2", "response": {"status_code": 200, "request_id": "req_c187b3", "body": {"id": "chatcmpl-9758Iw", "object": "chat.completion", "created": 1711475054, "model": "gpt-3.5-turbo", "choices": [{"index": 0, "message": {"role": "assistant", "content": "2 + 2 equals 4."}, "finish_reason": "stop"}], "usage": {"prompt_tokens": 24, "completion_tokens": 15, "total_tokens": 39}, "system_fingerprint": null}}, "error": null} + + ListBatchesResponse: + type: object + properties: + data: + type: array + items: + $ref: "#/components/schemas/Batch" + first_id: + type: string + example: "batch_abc123" + last_id: + type: string + example: "batch_abc456" + has_more: + type: boolean + object: + type: string + enum: [list] + required: + - object + - data + - has_more + +security: + - ApiKeyAuth: [] + +x-oaiMeta: + navigationGroups: + - id: endpoints + title: Endpoints + - id: assistants + title: Assistants + - id: legacy + title: Legacy + groups: + # > General Notes + # The `groups` section is used to generate the API reference pages and navigation, in the same + # order listed below. Additionally, each `group` can have a list of `sections`, each of which + # will become a navigation subroute and subsection under the group. Each section has: + # - `type`: Currently, either an `endpoint` or `object`, depending on how the section needs to + # be rendered + # - `key`: The reference key that can be used to lookup the section definition + # - `path`: The path (url) of the section, which is used to generate the navigation link. + # + # > The `object` sections maps to a schema component and the following fields are read for rendering + # - `x-oaiMeta.name`: The name of the object, which will become the section title + # - `x-oaiMeta.example`: The example object, which will be used to generate the example sample (always JSON) + # - `description`: The description of the object, which will be used to generate the section description + # + # > The `endpoint` section maps to an operation path and the following fields are read for rendering: + # - `x-oaiMeta.name`: The name of the endpoint, which will become the section title + # - `x-oaiMeta.examples`: The endpoint examples, which can be an object (meaning a single variation, most + # endpoints, or an array of objects, meaning multiple variations, e.g. the + # chat completion and completion endpoints, with streamed and non-streamed examples. + # - `x-oaiMeta.returns`: text describing what the endpoint returns. + # - `summary`: The summary of the endpoint, which will be used to generate the section description + - id: audio + title: Audio + description: | + Learn how to turn audio into text or text into audio. + + Related guide: [Speech to text](/docs/guides/speech-to-text) + navigationGroup: endpoints + sections: + - type: endpoint + key: createSpeech + path: createSpeech + - type: endpoint + key: createTranscription + path: createTranscription + - type: endpoint + key: createTranslation + path: createTranslation + - type: object + key: CreateTranscriptionResponseJson + path: json-object + - type: object + key: CreateTranscriptionResponseVerboseJson + path: verbose-json-object + - id: chat + title: Chat + description: | + Given a list of messages comprising a conversation, the model will return a response. + + Related guide: [Chat Completions](/docs/guides/text-generation) + navigationGroup: endpoints + sections: + - type: endpoint + key: createChatCompletion + path: create + - type: object + key: CreateChatCompletionResponse + path: object + - type: object + key: CreateChatCompletionStreamResponse + path: streaming + - id: embeddings + title: Embeddings + description: | + Get a vector representation of a given input that can be easily consumed by machine learning models and algorithms. + + Related guide: [Embeddings](/docs/guides/embeddings) + navigationGroup: endpoints + sections: + - type: endpoint + key: createEmbedding + path: create + - type: object + key: Embedding + path: object + - id: fine-tuning + title: Fine-tuning + description: | + Manage fine-tuning jobs to tailor a model to your specific training data. + + Related guide: [Fine-tune models](/docs/guides/fine-tuning) + navigationGroup: endpoints + sections: + - type: endpoint + key: createFineTuningJob + path: create + - type: endpoint + key: listPaginatedFineTuningJobs + path: list + - type: endpoint + key: listFineTuningEvents + path: list-events + - type: endpoint + key: listFineTuningJobCheckpoints + path: list-checkpoints + - type: endpoint + key: retrieveFineTuningJob + path: retrieve + - type: endpoint + key: cancelFineTuningJob + path: cancel + - type: object + key: FineTuningJob + path: object + - type: object + key: FineTuningJobEvent + path: event-object + - type: object + key: FineTuningJobCheckpoint + path: checkpoint-object + - id: batch + title: Batch + description: | + Create large batches of API requests for asynchronous processing. The Batch API returns completions within 24 hours for a 50% discount. + + Related guide: [Batch](/docs/guides/batch) + navigationGroup: endpoints + sections: + - type: endpoint + key: createBatch + path: create + - type: endpoint + key: retrieveBatch + path: retrieve + - type: endpoint + key: cancelBatch + path: cancel + - type: endpoint + key: listBatches + path: list + - type: object + key: Batch + path: object + - type: object + key: BatchRequestInput + path: requestInput + - type: object + key: BatchRequestOutput + path: requestOutput + - id: files + title: Files + description: | + Files are used to upload documents that can be used with features like [Assistants](/docs/api-reference/assistants) and [Fine-tuning](/docs/api-reference/fine-tuning). + navigationGroup: endpoints + sections: + - type: endpoint + key: createFile + path: create + - type: endpoint + key: listFiles + path: list + - type: endpoint + key: retrieveFile + path: retrieve + - type: endpoint + key: deleteFile + path: delete + - type: endpoint + key: downloadFile + path: retrieve-contents + - type: object + key: OpenAIFile + path: object + - id: images + title: Images + description: | + Given a prompt and/or an input image, the model will generate a new image. + + Related guide: [Image generation](/docs/guides/images) + navigationGroup: endpoints + sections: + - type: endpoint + key: createImage + path: create + - type: endpoint + key: createImageEdit + path: createEdit + - type: endpoint + key: createImageVariation + path: createVariation + - type: object + key: Image + path: object + - id: models + title: Models + description: | + List and describe the various models available in the API. You can refer to the [Models](/docs/models) documentation to understand what models are available and the differences between them. + navigationGroup: endpoints + sections: + - type: endpoint + key: listModels + path: list + - type: endpoint + key: retrieveModel + path: retrieve + - type: endpoint + key: deleteModel + path: delete + - type: object + key: Model + path: object + - id: moderations + title: Moderations + description: | + Given some input text, outputs if the model classifies it as potentially harmful across several categories. + + Related guide: [Moderations](/docs/guides/moderation) + navigationGroup: endpoints + sections: + - type: endpoint + key: createModeration + path: create + - type: object + key: CreateModerationResponse + path: object + - id: assistants + title: Assistants + beta: true + description: | + Build assistants that can call models and use tools to perform tasks. + + [Get started with the Assistants API](/docs/assistants) + navigationGroup: assistants + sections: + - type: endpoint + key: createAssistant + path: createAssistant + - type: endpoint + key: listAssistants + path: listAssistants + - type: endpoint + key: getAssistant + path: getAssistant + - type: endpoint + key: modifyAssistant + path: modifyAssistant + - type: endpoint + key: deleteAssistant + path: deleteAssistant + - type: object + key: AssistantObject + path: object + - id: threads + title: Threads + beta: true + description: | + Create threads that assistants can interact with. + + Related guide: [Assistants](/docs/assistants/overview) + navigationGroup: assistants + sections: + - type: endpoint + key: createThread + path: createThread + - type: endpoint + key: getThread + path: getThread + - type: endpoint + key: modifyThread + path: modifyThread + - type: endpoint + key: deleteThread + path: deleteThread + - type: object + key: ThreadObject + path: object + - id: messages + title: Messages + beta: true + description: | + Create messages within threads + + Related guide: [Assistants](/docs/assistants/overview) + navigationGroup: assistants + sections: + - type: endpoint + key: createMessage + path: createMessage + - type: endpoint + key: listMessages + path: listMessages + - type: endpoint + key: getMessage + path: getMessage + - type: endpoint + key: modifyMessage + path: modifyMessage + - type: endpoint + key: deleteMessage + path: deleteMessage + - type: object + key: MessageObject + path: object + - id: runs + title: Runs + beta: true + description: | + Represents an execution run on a thread. + + Related guide: [Assistants](/docs/assistants/overview) + navigationGroup: assistants + sections: + - type: endpoint + key: createRun + path: createRun + - type: endpoint + key: createThreadAndRun + path: createThreadAndRun + - type: endpoint + key: listRuns + path: listRuns + - type: endpoint + key: getRun + path: getRun + - type: endpoint + key: modifyRun + path: modifyRun + - type: endpoint + key: submitToolOuputsToRun + path: submitToolOutputs + - type: endpoint + key: cancelRun + path: cancelRun + - type: object + key: RunObject + path: object + - id: run-steps + title: Run Steps + beta: true + description: | + Represents the steps (model and tool calls) taken during the run. + + Related guide: [Assistants](/docs/assistants/overview) + navigationGroup: assistants + sections: + - type: endpoint + key: listRunSteps + path: listRunSteps + - type: endpoint + key: getRunStep + path: getRunStep + - type: object + key: RunStepObject + path: step-object + - id: vector-stores + title: Vector Stores + beta: true + description: | + Vector stores are used to store files for use by the `file_search` tool. + + Related guide: [File Search](/docs/assistants/tools/file-search) + navigationGroup: assistants + sections: + - type: endpoint + key: createVectorStore + path: create + - type: endpoint + key: listVectorStores + path: list + - type: endpoint + key: getVectorStore + path: retrieve + - type: endpoint + key: modifyVectorStore + path: modify + - type: endpoint + key: deleteVectorStore + path: delete + - type: object + key: VectorStoreObject + path: object + - id: vector-stores-files + title: Vector Store Files + beta: true + description: | + Vector store files represent files inside a vector store. + + Related guide: [File Search](/docs/assistants/tools/file-search) + navigationGroup: assistants + sections: + - type: endpoint + key: createVectorStoreFile + path: createFile + - type: endpoint + key: listVectorStoreFiles + path: listFiles + - type: endpoint + key: getVectorStoreFile + path: getFile + - type: endpoint + key: deleteVectorStoreFile + path: deleteFile + - type: object + key: VectorStoreFileObject + path: file-object + - id: vector-stores-file-batches + title: Vector Store File Batches + beta: true + description: | + Vector store file batches represent operations to add multiple files to a vector store. + + Related guide: [File Search](/docs/assistants/tools/file-search) + navigationGroup: assistants + sections: + - type: endpoint + key: createVectorStoreFileBatch + path: createBatch + - type: endpoint + key: getVectorStoreFileBatch + path: getBatch + - type: endpoint + key: cancelVectorStoreFileBatch + path: cancelBatch + - type: endpoint + key: listFilesInVectorStoreBatch + path: listBatchFiles + - type: object + key: VectorStoreFileBatchObject + path: batch-object + - id: assistants-streaming + title: Streaming + beta: true + description: | + Stream the result of executing a Run or resuming a Run after submitting tool outputs. + + You can stream events from the [Create Thread and Run](/docs/api-reference/runs/createThreadAndRun), + [Create Run](/docs/api-reference/runs/createRun), and [Submit Tool Outputs](/docs/api-reference/runs/submitToolOutputs) + endpoints by passing `"stream": true`. The response will be a [Server-Sent events](https://html.spec.whatwg.org/multipage/server-sent-events.html#server-sent-events) stream. + + Our Node and Python SDKs provide helpful utilities to make streaming easy. Reference the + [Assistants API quickstart](/docs/assistants/overview) to learn more. + navigationGroup: assistants + sections: + - type: object + key: MessageDeltaObject + path: message-delta-object + - type: object + key: RunStepDeltaObject + path: run-step-delta-object + - type: object + key: AssistantStreamEvent + path: events + - id: completions + title: Completions + legacy: true + navigationGroup: legacy + description: | + Given a prompt, the model will return one or more predicted completions along with the probabilities of alternative tokens at each position. Most developer should use our [Chat Completions API](/docs/guides/text-generation/text-generation-models) to leverage our best and newest models. + sections: + - type: endpoint + key: createCompletion + path: create + - type: object + key: CreateCompletionResponse + path: object diff --git a/openapi.yaml b/openapi.yaml new file mode 100644 index 0000000..0cd212b --- /dev/null +++ b/openapi.yaml @@ -0,0 +1,475 @@ +openapi: 3.0.3 +info: + title: Log10 Feedback API Spec + description: Log10 Feedback API Spec + version: 1.0.0 +servers: + - url: https://log10.io +tags: + - name: Completions + description: Completions + - name: Feedback + description: Feedback + - name: FeedbackTasks + description: FeedbackTasks + - name: Sessions + description: Sessions +x-speakeasy-globals: + parameters: + - name: X-Log10-Organization + in: header + required: true + schema: + type: string +components: + securitySchemes: + Log10Token: # arbitrary name for the security scheme + type: apiKey + in: header # can be "header", "query" or "cookie" + name: X-Log10-Token # name of the header, query parameter or cookie + schemas: + Task: + type: object + required: + - name + - instruction + - json_schema + - completion_tags_selector + properties: + id: + type: string + description: The unique identifier for this task. + created_at_ms: + type: number + description: The epoch this schema was created. + json_schema: + type: object + description: The schema of the task. Must be valid JSON Schema. + name: + type: string + description: The name of the task. + instruction: + type: string + description: The instructions for this task. + completion_tags_selector: + type: object + description: The completion tag matching with this task i.e. surfaced as needing feedback. + items: + type: string + Feedback: + type: object + required: + - task_id + - json_values + - matched_completion_ids + - comment + properties: + id: + type: string + description: The unique identifier for this feedback. + created_at_ms: + type: number + description: The epoch this schema was created. + task_id: + type: string + description: The unique identifier for the task associated with this feedback. + json_values: + type: object + description: The values of the feedback. Must be valid JSON according to the task schema. + matched_completion_ids: + type: array + description: The matched completion ids associated with this feedback. + items: + type: string + comment: + type: string + description: The comment associated with this feedback. + completions_summary: + type: string + Completion: + type: object + required: + - organization_id + properties: + id: + type: string + description: The unique identifier for this task. + organization_id: + type: string + description: The unique identifier for the organization. + kind: + type: string + description: The kind of completion i.e. chat messages or prompt + enum: + - chat + - prompt + status: + type: string + description: The status of this completion. + enum: + - started + - finished + - failed + tags: + type: array + description: The tags for this completion. + items: + type: string + request: + type: object + $ref: "openai.yaml#/components/schemas/CreateChatCompletionRequest" + response: + type: object + $ref: "openai.yaml#/components/schemas/CreateChatCompletionResponse" + stacktrace: + type: array + description: The stacktrace for this completion. + items: + type: object + properties: + file: + type: string + description: The file associated with this stacktrace. + line: + type: string + description: The line associated with this stacktrace. + lineno: + type: number + description: The line number associated with this stacktrace. + name: + type: string + description: The function or module associated with this stacktrace. + required: + - file + - line + - lineno + - name + session_id: + type: string + description: The session id for this completion. + duration: + type: number + description: The duration of this completion in seconds. + failure_kind: + type: string + description: The failure kind of this completion. + failure_reason: + type: string + description: The failure reason of this completion. + Session: + type: object + properties: + id: + type: string + description: The unique identifier for this session. + +paths: + /api/v1/completions: + post: + tags: + - Completions + operationId: create + summary: Create a completion + security: + - Log10Token: [] + parameters: + - name: X-Log10-Organization + in: header + required: true + schema: + type: string + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/Completion" + responses: + "200": + description: Created + content: + application/json: + schema: + type: object + x-speakeasy-type-override: any + "201": + description: Created + content: + application/json: + schema: + $ref: "#/components/schemas/Completion" + + /api/v1/completions/{completionId}: + post: + parameters: + - name: completionId + in: path + required: true + description: The completion id to update. + schema: + type: string + - name: X-Log10-Organization + in: header + required: true + schema: + type: string + tags: + - Completions + operationId: update + summary: Update completion by id. + security: + - Log10Token: [] + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/Completion" + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/Completion" + + /api/v1/sessions: + post: + tags: + - Sessions + x-speakeasy-name-override: create + x-speakeasy-usage-example: true + operationId: createSession + summary: Create a session + security: + - Log10Token: [] + parameters: + - name: X-Log10-Organization + in: header + required: true + schema: + type: string + responses: + "201": + description: Created + content: + application/json: + schema: + type: object + properties: + session: + $ref: "#/components/schemas/Session" + + /api/v1/completions/ungraded: + get: + tags: + - Completions + operationId: listUngraded + summary: List ungraded completions i.e. completions that have not been associated with feedback but matches task selector. + security: + - Log10Token: [] + parameters: + - name: X-Log10-Organization + in: header + required: true + schema: + type: string + responses: + "200": + description: OK + content: + application/json: + schema: + type: object + properties: + completions: + type: array + items: + $ref: "#/components/schemas/Completion" + + /api/v1/feedback/{feedbackId}: + get: + tags: + - Feedback + parameters: + - name: feedbackId + in: path + required: true + description: The feedback id to fetch. + schema: + type: string + - name: X-Log10-Organization + in: header + required: true + schema: + type: string + operationId: get + summary: Fetch feedback by id. + security: + - Log10Token: [] + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/Feedback" + + /api/v1/feedback: + get: + tags: + - Feedback + operationId: list + summary: List feedback + security: + - Log10Token: [] + parameters: + - name: X-Log10-Organization + in: header + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + type: object + properties: + offset: + type: integer + description: The offset to start fetching feedback from. + limit: + type: integer + description: The number of feedback to fetch. + completion_id: + type: string + description: The completion id to fetch feedback for. + task_id: + type: string + description: The task id to fetch feedback for. + responses: + "200": + description: OK + content: + application/json: + schema: + type: object + properties: + feedback: + type: array + items: + $ref: "#/components/schemas/Feedback" + post: + summary: Upload a piece of feedback + tags: + - Feedback + operationId: upload + security: + - Log10Token: [] + parameters: + - name: X-Log10-Organization + in: header + required: true + schema: + type: string + requestBody: + required: true + content: + application/json: + schema: + oneOf: + - allOf: + - $ref: "#/components/schemas/Feedback" + - type: object + required: + - allow_unmatched_feedback + - completion_tags_selector + properties: + allow_unmatched_feedback: + type: boolean + description: Whether to allow unmatched feedback. Defaults to false. + default: false + max_matched_completions: + type: integer + description: The maximum number of matched completions. Returns error if exceeded. Defaults to 100. + default: 100 + completion_tags_selector: + type: array + description: The completion tags associated with this feedback. + items: + type: string + - allOf: + - $ref: "#/components/schemas/Feedback" + - type: object + required: + - completion_ids + properties: + completion_ids: + type: array + description: The completion ids to associate with this feedback. + items: + type: string + + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/Feedback" + + /api/v1/feedback_task: + get: + tags: + - FeedbackTasks + x-speakeasy-name-override: list + operationId: listFeedbackTasks + summary: List feedback tasks. + responses: + "200": + description: OK + content: + application/json: + schema: + type: array + items: + $ref: "#/components/schemas/Task" + post: + tags: + - FeedbackTasks + x-speakeasy-name-override: create + operationId: createFeedbackTask + summary: Create a new task. + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/Task" + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/Task" + /api/v1/feedback_task/{taskId}: + get: + parameters: + - name: taskId + in: path + required: true + description: The task id to fetch. + schema: + type: string + tags: + - FeedbackTasks + x-speakeasy-name-override: get + operationId: getFeedbackTask + summary: Retrieves feedback task `taskId`. + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/Task" \ No newline at end of file diff --git a/sessions.go b/sessions.go new file mode 100644 index 0000000..f14e6d4 --- /dev/null +++ b/sessions.go @@ -0,0 +1,134 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package log10go + +import ( + "bytes" + "context" + "fmt" + "github.com/log10-io/log10go/internal/hooks" + "github.com/log10-io/log10go/internal/utils" + "github.com/log10-io/log10go/models/components" + "github.com/log10-io/log10go/models/operations" + "github.com/log10-io/log10go/models/sdkerrors" + "io" + "net/http" +) + +// Sessions +type Sessions struct { + sdkConfiguration sdkConfiguration +} + +func newSessions(sdkConfig sdkConfiguration) *Sessions { + return &Sessions{ + sdkConfiguration: sdkConfig, + } +} + +// Create a session +func (s *Sessions) Create(ctx context.Context, xLog10Organization *string) (*operations.CreateSessionResponse, error) { + hookCtx := hooks.HookContext{ + Context: ctx, + OperationID: "createSession", + SecuritySource: s.sdkConfiguration.Security, + } + + request := operations.CreateSessionRequest{ + XLog10Organization: xLog10Organization, + } + + globals := operations.CreateSessionGlobals{ + XLog10Organization: s.sdkConfiguration.Globals.XLog10Organization, + } + + baseURL := utils.ReplaceParameters(s.sdkConfiguration.GetServerDetails()) + opURL, err := utils.GenerateURL(ctx, baseURL, "/api/v1/sessions", request, globals) + if err != nil { + return nil, fmt.Errorf("error generating URL: %w", err) + } + + req, err := http.NewRequestWithContext(ctx, "POST", opURL, nil) + if err != nil { + return nil, fmt.Errorf("error creating request: %w", err) + } + req.Header.Set("Accept", "application/json") + req.Header.Set("User-Agent", s.sdkConfiguration.UserAgent) + + utils.PopulateHeaders(ctx, req, request, globals) + + if err := utils.PopulateQueryParams(ctx, req, request, globals); err != nil { + return nil, fmt.Errorf("error populating query params: %w", err) + } + + if err := utils.PopulateSecurity(ctx, req, s.sdkConfiguration.Security); err != nil { + return nil, err + } + + req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + if err != nil { + return nil, err + } + + httpRes, err := s.sdkConfiguration.Client.Do(req) + if err != nil || httpRes == nil { + if err != nil { + err = fmt.Errorf("error sending request: %w", err) + } else { + err = fmt.Errorf("error sending request: no response") + } + + _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + return nil, err + } else if utils.MatchStatusCodes([]string{"4XX", "5XX"}, httpRes.StatusCode) { + _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) + if err != nil { + return nil, err + } else if _httpRes != nil { + httpRes = _httpRes + } + } else { + httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) + if err != nil { + return nil, err + } + } + + res := &operations.CreateSessionResponse{ + HTTPMeta: components.HTTPMetadata{ + Request: req, + Response: httpRes, + }, + } + + rawBody, err := io.ReadAll(httpRes.Body) + if err != nil { + return nil, fmt.Errorf("error reading response body: %w", err) + } + httpRes.Body.Close() + httpRes.Body = io.NopCloser(bytes.NewBuffer(rawBody)) + + switch { + case httpRes.StatusCode == 201: + switch { + case utils.MatchContentType(httpRes.Header.Get("Content-Type"), `application/json`): + var out operations.CreateSessionResponseBody + if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { + return nil, err + } + + res.Object = &out + default: + return nil, sdkerrors.NewSDKError(fmt.Sprintf("unknown content-type received: %s", httpRes.Header.Get("Content-Type")), httpRes.StatusCode, string(rawBody), httpRes) + } + case httpRes.StatusCode >= 400 && httpRes.StatusCode < 500: + fallthrough + case httpRes.StatusCode >= 500 && httpRes.StatusCode < 600: + return nil, sdkerrors.NewSDKError("API error occurred", httpRes.StatusCode, string(rawBody), httpRes) + default: + return nil, sdkerrors.NewSDKError("unknown status code returned", httpRes.StatusCode, string(rawBody), httpRes) + } + + return res, nil + +} diff --git a/types/bigint.go b/types/bigint.go new file mode 100644 index 0000000..afd0cd2 --- /dev/null +++ b/types/bigint.go @@ -0,0 +1,21 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package types + +import ( + "fmt" + "math/big" +) + +// MustNewBigIntFromString returns an instance of big.Int from a string +// The string is assumed to be base 10 and if it is not a valid big.Int +// then the function panics. +// Avoid using this function in production code. +func MustNewBigIntFromString(s string) *big.Int { + i, ok := new(big.Int).SetString(s, 10) + if !ok { + panic(fmt.Errorf("failed to parse string as big.Int")) + } + + return i +} diff --git a/types/date.go b/types/date.go new file mode 100644 index 0000000..c4648fa --- /dev/null +++ b/types/date.go @@ -0,0 +1,90 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package types + +import ( + "encoding/json" + "fmt" + "strings" + "time" +) + +// Date is a wrapper around time.Time that allows for JSON marshaling a date string formatted as "2006-01-02". +type Date struct { + time.Time +} + +var ( + _ json.Marshaler = &Date{} + _ json.Unmarshaler = &Date{} + _ fmt.Stringer = &Date{} +) + +// NewDate returns an instance of Date from a time.Time. +func NewDate(t time.Time) *Date { + d := DateFromTime(t) + return &d +} + +// DateFromTime returns a Date from a time.Time. +func DateFromTime(t time.Time) Date { + return Date{t} +} + +// NewDateFromString returns an instance of Date from a string formatted as "2006-01-02". +func NewDateFromString(str string) (*Date, error) { + d, err := DateFromString(str) + if err != nil { + return nil, err + } + + return &d, nil +} + +// DateFromString returns a Date from a string formatted as "2006-01-02". +func DateFromString(str string) (Date, error) { + var d Date + var err error + + d.Time, err = time.Parse("2006-01-02", str) + return d, err +} + +// MustNewDateFromString returns an instance of Date from a string formatted as "2006-01-02" or panics. +// Avoid using this function in production code. +func MustNewDateFromString(str string) *Date { + d := MustDateFromString(str) + return &d +} + +// MustDateFromString returns a Date from a string formatted as "2006-01-02" or panics. +// Avoid using this function in production code. +func MustDateFromString(str string) Date { + d, err := DateFromString(str) + if err != nil { + panic(err) + } + return d +} + +func (d Date) GetTime() time.Time { + return d.Time +} + +func (d Date) MarshalJSON() ([]byte, error) { + return []byte(fmt.Sprintf(`"%s"`, d.Time.Format("2006-01-02"))), nil +} + +func (d *Date) UnmarshalJSON(data []byte) error { + var err error + + str := string(data) + str = strings.Trim(str, `"`) + + d.Time, err = time.Parse("2006-01-02", str) + return err +} + +func (d Date) String() string { + return d.Time.Format("2006-01-02") +} diff --git a/types/datetime.go b/types/datetime.go new file mode 100644 index 0000000..0529b25 --- /dev/null +++ b/types/datetime.go @@ -0,0 +1,23 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package types + +import "time" + +// MustTimeFromString returns a time.Time from a string formatted as "2006-01-02T15:04:05Z07:00" or panics. +// Avoid using this function in production code. +func MustTimeFromString(str string) time.Time { + t, err := time.Parse(time.RFC3339, str) + if err != nil { + panic(err) + } + + return t +} + +// MustNewTimeFromString returns an instance of time.Time from a string formatted as "2006-01-02T15:04:05Z07:00" or panics. +// Avoid using this function in production code. +func MustNewTimeFromString(str string) *time.Time { + t := MustTimeFromString(str) + return &t +} diff --git a/types/decimal.go b/types/decimal.go new file mode 100644 index 0000000..a42284b --- /dev/null +++ b/types/decimal.go @@ -0,0 +1,20 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package types + +import ( + "fmt" + + "github.com/ericlagergren/decimal" +) + +// MustNewDecimalFromString returns an instance of Decimal from a string +// Avoid using this function in production code. +func MustNewDecimalFromString(s string) *decimal.Big { + d, ok := new(decimal.Big).SetString(s) + if !ok { + panic(fmt.Errorf("failed to parse string as decimal.Big")) + } + + return d +} diff --git a/types/pointers.go b/types/pointers.go new file mode 100644 index 0000000..4f15e99 --- /dev/null +++ b/types/pointers.go @@ -0,0 +1,10 @@ +// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + +package types + +func String(s string) *string { return &s } +func Bool(b bool) *bool { return &b } +func Int(i int) *int { return &i } +func Int64(i int64) *int64 { return &i } +func Float32(f float32) *float32 { return &f } +func Float64(f float64) *float64 { return &f }