diff --git a/.golangci.yml b/.golangci.yml index 19ffd3af..7da62d5e 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -12,22 +12,18 @@ linters: - revive settings: depguard: - # ADR 0016 dependency rules. Rules only constrain files that exist: - # internal/core is live since Phase 0 (domain moved); internal/nomos - # and its bans activate in Phase 8; full audit at Phase 9. + # ADR 0016 dependency rules. The nomos packages (and their bans) were + # removed with the nomos decommission — the agent runtime is dsh, an + # external MCP client. rules: core-no-agent-tech: files: - "**/internal/core/**" deny: - - pkg: github.com/dtoro/oikos/internal/nomos - desc: core never links agent-client packages (ADR 0016 §3.1 rule 3) - - pkg: github.com/dtoro/oikos/internal/nomos/** - desc: core never links agent-client packages (ADR 0016 §3.1 rule 3) - pkg: github.com/openai/openai-go - desc: core never links the LLM SDK — nomos is an external client + desc: core never links the LLM SDK — the agent is an external client - pkg: github.com/openai/openai-go/** - desc: core never links the LLM SDK — nomos is an external client + desc: core never links the LLM SDK — the agent is an external client - pkg: github.com/modelcontextprotocol/go-sdk desc: core never links MCP packages — mcpserver is a driving adapter - pkg: github.com/modelcontextprotocol/go-sdk/** @@ -44,18 +40,6 @@ linters: desc: core must not import composition roots - pkg: github.com/dtoro/oikos/cmd/** desc: core must not import composition roots - nomos-isolation: - files: - - "**/internal/nomos/**" - deny: - - pkg: github.com/dtoro/oikos/internal/core - desc: nomos must not import core — consume oikos via MCP/REST - - pkg: github.com/dtoro/oikos/internal/core/** - desc: nomos must not import core — consume oikos via MCP/REST - - pkg: github.com/dtoro/oikos/internal/adapters - desc: nomos must not import adapters — consume oikos via MCP/REST - - pkg: github.com/dtoro/oikos/internal/adapters/** - desc: nomos must not import adapters — consume oikos via MCP/REST errcheck: # Allow unchecked errors on common Close/Flush patterns (deferred cleanup) exclude-functions: diff --git a/VERSION b/VERSION index ca75280b..4ef2eb08 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.38.0 +0.39.0 diff --git a/compose/caddy/Caddyfile.oikos b/compose/caddy/Caddyfile.oikos index 0d1af062..1551f9d8 100644 --- a/compose/caddy/Caddyfile.oikos +++ b/compose/caddy/Caddyfile.oikos @@ -3,10 +3,9 @@ # Lives in dtoro/caddy-conf repo; auto-deploys to caddy (LXC 121). THIS COPY # IS A REFERENCE, NOT DEPLOYED FROM HERE — keep it in sync manually. # -# The SPA is no longer embedded in the oikos binary; it's built and served -# by its own container (compose/web/Dockerfile, docker-compose.yml's `web` -# service, mac-mini:8091) rather than as static files read off local disk — -# see that service's comment for why. Every API/MCP/agent route now requires +# The SPA lives in its own repo (dtoro/oikos-web) and deploys as its own +# compose project publishing mac-mini:8091 — see the docker-compose.yml +# comment. Every API/MCP route requires # a bearer token in all cases (api's dev-open bypass was removed) — # non-browser clients (Wails, curl, a future mobile client) can't complete # Authentik's browser-session login, so those routes bypass `import @@ -26,11 +25,10 @@ oikos.hubris.network { reverse_proxy 192.168.178.182:8090 } # Bearer-token clients — api's combinedAuth (internal/httpapi/server.go) - # is the real gate for all three; Authentik would just reject non-browser - # callers before they ever get there. /agent/* now goes through api's own - # (auth'd) proxy mount rather than straight to nomos:8092, so it's - # covered by the same check as /api/v1/* and /mcp. - @api path /api/v1/* /mcp /agent/* + # is the real gate; Authentik would just reject non-browser callers + # before they ever get there, so /api/v1/* and /mcp bypass `import + # authentik` and rely on api's own combinedAuth. + @api path /api/v1/* /mcp handle @api { reverse_proxy 192.168.178.182:8090 } @@ -50,10 +48,7 @@ mcp.hubris.network { reverse_proxy 192.168.178.182:8090 } -# Nomos's own gateway (workstation access) — still has NO auth of its own -# (C1, plans/2026-07-11-nomos-agent-code-review.md, still open). Anyone who -# can reach this host can talk to nomos directly, bypassing api entirely. -# Not fixed by the client/server split — tracked separately. -nomos.hubris.network { - reverse_proxy 192.168.178.182:8092 -} +# nomos.hubris.network (the retired nomos gateway, :8092) was removed with +# the nomos decommission — plans/2026-08-16-dsh-as-agent-replace-nomos.md +# section 5. The agent runtime is dsh (external MCP client, no inbound +# gateway). Remember to mirror this removal in dtoro/caddy-conf. diff --git a/go.mod b/go.mod index ab9ccdaa..954a9736 100644 --- a/go.mod +++ b/go.mod @@ -13,7 +13,6 @@ require ( github.com/jackc/pgx/v5 v5.10.0 github.com/modelcontextprotocol/go-sdk v1.6.1 github.com/oapi-codegen/runtime v1.4.2 - github.com/openai/openai-go v1.12.0 golang.org/x/crypto v0.53.0 golang.org/x/sync v0.21.0 golang.org/x/sys v0.46.0 @@ -65,10 +64,6 @@ require ( github.com/segmentio/asm v1.1.3 // indirect github.com/segmentio/encoding v0.5.4 // indirect github.com/sony/gobreaker v0.5.0 // indirect - github.com/tidwall/gjson v1.14.4 // indirect - github.com/tidwall/match v1.1.1 // indirect - github.com/tidwall/pretty v1.2.1 // indirect - github.com/tidwall/sjson v1.2.5 // indirect github.com/yosida95/uritemplate/v3 v3.0.2 // indirect github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect diff --git a/go.sum b/go.sum index 9626a973..a0115043 100644 --- a/go.sum +++ b/go.sum @@ -118,8 +118,6 @@ github.com/oasdiff/yaml v0.1.0 h1:0bqZjfKc/8S9urj4JuwepX41WX9EoA6ifhU3SV06cXg= github.com/oasdiff/yaml v0.1.0/go.mod h1:kOlRmMdL2X3vucLCEQO5u61SU22RysnfXvcttrZA1O0= github.com/oasdiff/yaml3 v0.0.13 h1:06svmvOHOVBqF81+sY2EUScvUI/iS/vl2VIeUUxZQwg= github.com/oasdiff/yaml3 v0.0.13/go.mod h1:y5+oSEHCPT/DGrS++Wc/479ERge0zTFxaF8PbGKcg2o= -github.com/openai/openai-go v1.12.0 h1:NBQCnXzqOTv5wsgNC36PrFEiskGfO5wccfCWDo9S1U0= -github.com/openai/openai-go v1.12.0/go.mod h1:g461MYGXEXBVdV5SaR/5tNzNbSfwTBBefwc+LlDCK0Y= github.com/oracle/oci-go-sdk/v65 v65.95.2 h1:0HJ0AgpLydp/DtvYrF2d4str2BjXOVAeNbuW7E07g94= github.com/oracle/oci-go-sdk/v65 v65.95.2/go.mod h1:u6XRPsw9tPziBh76K7GrrRXPa8P8W3BQeqJ6ZZt9VLA= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= @@ -151,16 +149,6 @@ github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= -github.com/tidwall/gjson v1.14.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= -github.com/tidwall/gjson v1.14.4 h1:uo0p8EbA09J7RQaflQ1aBRffTR7xedD2bcIVSYxLnkM= -github.com/tidwall/gjson v1.14.4/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= -github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA= -github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= -github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= -github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4= -github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= -github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY= -github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28= github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4= github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4= github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 h1:ilQV1hzziu+LLM3zUTJ0trRztfwgjqKnBWNtSRkbmwM= diff --git a/internal/nomos/assent/assent.go b/internal/nomos/assent/assent.go deleted file mode 100644 index a0e1f118..00000000 --- a/internal/nomos/assent/assent.go +++ /dev/null @@ -1,143 +0,0 @@ -package assent - -import ( - "regexp" - "strings" -) - -// Chat-assent approval: the operator authorizes a proposed action by -// replying normally in chat ("go ahead", "yes", "do it") instead of clicking -// a separate Approve button. This is deterministic (not LLM-judged) so it -// can't be talked around by a model that misreads intent, and it only ever -// looks at the assistant turn immediately preceding the operator's reply — -// an old "yes" from three messages ago can never retroactively approve -// something new. Destructive-risk actions are excluded: they always need the -// explicit typed-confirmation flow, never loose assent. - -// PendingApproval is one gated action proposed in the immediately-preceding -// assistant turn, extracted from its tool_result text. -type PendingApproval struct { - ExecID string - Destructive bool -} - -// executionQueuedRE matches the "execution queued" phrasing shared by -// the run and request_execution/pct_create tool result messages. -var executionQueuedRE = regexp.MustCompile(`(?i)execution\s+([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\s+queued`) - -// extractPendingApprovals scans the tool results of one assistant turn for -// gated actions that are still awaiting a decision. -func ExtractPendingApprovals(resultTexts []string) []PendingApproval { - var out []PendingApproval - for _, text := range resultTexts { - m := executionQueuedRE.FindStringSubmatch(text) - if m == nil { - continue - } - out = append(out, PendingApproval{ - ExecID: m[1], - Destructive: strings.Contains(strings.ToUpper(text), "DESTRUCTIVE"), - }) - } - return out -} - -// negationWords, checked first: any of these anywhere in the message means -// the reply is NOT assent, even if a positive word also appears (e.g. "no, -// don't restart it yet" contains neither "yes" nor "go ahead", but "wait" -// alone should also block a stray "yes" a sentence later — checking negation -// first and returning false errs toward re-confirming rather than assuming -// consent, per "when in doubt, escalate"). Includes contracted negatives -// ("haven't", "isn't", ...) alongside "don't"/"do not" — found live: "I -// haven't confirmed anything yet" was reading as an explicit confirmation -// because none of the contracted forms were covered, only "don't"/"do not". -// Deliberately does NOT include a bare "not": that's broad enough to false- -// negative ordinary assent ("go ahead, this is not risky") — the specific -// contracted-verb forms below are unambiguous negation on their own. -var negationWords = []string{ - "no", "nope", "don't", "do not", "stop", "wait", "hold on", "hold off", - "not yet", "cancel", "nevermind", "never mind", "actually don't", "skip that", - "haven't", "hasn't", "isn't", "wasn't", "aren't", "can't", "cannot", - "won't", "wouldn't", "shouldn't", "didn't", "doesn't", -} - -// assentWords, checked only if no negation matched. -var assentWords = []string{ - "go ahead", "goahead", "yes", "yep", "yeah", "yup", "do it", "proceed", - "approve", "approved", "confirm", "confirmed", "ship it", "sounds good", - "lgtm", "run it", "execute", "ok go", "okay go", "please do", -} - -// wordTokenRe splits a message into lowercase word tokens. Apostrophes -// (straight ' and curly ’) stay attached to their word so "don't"/"haven't" -// tokenize as one token, not two. -var wordTokenRe = regexp.MustCompile(`[a-z0-9'’]+`) - -func tokenize(msg string) []string { - return wordTokenRe.FindAllString(strings.ToLower(strings.ReplaceAll(msg, "’", "'")), -1) -} - -// containsPhrase reports whether phrase (one or more words) appears as a -// consecutive run of WHOLE tokens in tokens — never a mid-word substring -// match. This is the fix for a real false positive found live: the old -// substring check (`strings.Contains(m, "yes")`) matched "yes" inside -// "yesterday", and "confirm" inside "confirmed"/"unconfirmed" without regard -// for word boundaries. Negation already used a word-boundary check -// (space-padded); assent/confirm words didn't — this brings both onto the -// same, more robust tokenized comparison instead of ad-hoc string padding. -func containsPhrase(tokens []string, phrase string) bool { - words := strings.Fields(phrase) - if len(words) == 0 || len(words) > len(tokens) { - return false - } - for i := 0; i+len(words) <= len(tokens); i++ { - match := true - for j, w := range words { - if tokens[i+j] != w { - match = false - break - } - } - if match { - return true - } - } - return false -} - -// isAssent reports whether msg is a plain-language authorization of a -// pending proposal. Deliberately simple and auditable: a fixed word list, -// not a model judgment call, so behavior is predictable and can't be -// prompt-injected via the pending action's own content. -func IsAssent(msg string) bool { - tokens := tokenize(msg) - for _, w := range negationWords { - if containsPhrase(tokens, w) { - return false - } - } - for _, w := range assentWords { - if containsPhrase(tokens, w) { - return true - } - } - return false -} - -// isTypedConfirmation reports whether msg is an explicit confirmation strong -// enough to grant a DESTRUCTIVE pending action. Deliberately a separate, -// stricter check from isAssent: a bare "yes"/"go ahead"/"proceed" must never -// grant something destructive, only an explicit "confirm" statement does — -// this is the typed-confirmation phrase SOUL.md tells the operator to use -// ("I confirm destroy 135"). Still negation-aware for the same reason as -// isAssent: "don't confirm yet" must not accidentally match. -func IsTypedConfirmation(msg string) bool { - tokens := tokenize(msg) - for _, w := range negationWords { - if containsPhrase(tokens, w) { - return false - } - } - return containsPhrase(tokens, "confirm") || containsPhrase(tokens, "confirmed") -} - diff --git a/internal/nomos/assent/assent_test.go b/internal/nomos/assent/assent_test.go deleted file mode 100644 index a69f7778..00000000 --- a/internal/nomos/assent/assent_test.go +++ /dev/null @@ -1,128 +0,0 @@ -package assent - -import ( - "testing" -) - -func TestIsAssent_Positive(t *testing.T) { - cases := []string{ - "go ahead", "Go ahead.", "yes", "Yes!", "yeah", "yep", "do it", - "proceed", "approve", "ship it", "sounds good", "lgtm", "please do", - "ok go ahead and run it", - } - for _, c := range cases { - if !IsAssent(c) { - t.Errorf("IsAssent(%q) = false, want true", c) - } - } -} - -func TestIsAssent_Negative(t *testing.T) { - cases := []string{ - "no", "no, don't", "wait", "hold on", "not yet", "cancel that", - "nevermind", "what's the plan for tomorrow?", "how many CPUs does strong have?", - "maybe later", "", - } - for _, c := range cases { - if IsAssent(c) { - t.Errorf("IsAssent(%q) = true, want false", c) - } - } -} - -func TestIsAssent_NegationBeatsAssentWord(t *testing.T) { - // Contains "yes" as a substring pattern risk word but is clearly not - // assent — negation must win. - cases := []string{ - "no, don't do it yet", - "wait, not yet please", - } - for _, c := range cases { - if IsAssent(c) { - t.Errorf("IsAssent(%q) = true, want false (negation should block)", c) - } - } -} - -// TestIsAssent_WholeWordBoundary regression-tests a real false positive found -// live: the old substring check matched "yes" inside "yesterday" (and would -// equally match "confirm" inside "confirmed"/"unconfirmed" for -// IsTypedConfirmation below) because only negation used a word-boundary -// check — assent/confirm words used a bare strings.Contains. Confirmed via a -// throwaway probe before being fixed; kept here permanently so a future -// change can't silently reintroduce it. -func TestIsAssent_WholeWordBoundary(t *testing.T) { - cases := []string{ - "not sure, maybe yesterday's logs show something useful", - "my eyesight isn't great, what does that say", - } - for _, c := range cases { - if IsAssent(c) { - t.Errorf("IsAssent(%q) = true, want false (word-boundary: 'yes' must not match inside 'yesterday'/'eyesight')", c) - } - } -} - -// TestIsTypedConfirmation_ContractedNegation regression-tests the other real -// false positive: IsTypedConfirmation gates DESTRUCTIVE actions, and -// "confirm" matching inside "confirmed" combined with contracted negatives -// ("haven't") not being in negationWords meant a message that explicitly -// says the operator has NOT confirmed something could read as confirming it. -func TestIsTypedConfirmation_ContractedNegation(t *testing.T) { - cases := []string{ - "I haven't confirmed anything yet, let me think", - "that isn't confirmed on my end", - "we can't confirm that until tomorrow", - } - for _, c := range cases { - if IsTypedConfirmation(c) { - t.Errorf("IsTypedConfirmation(%q) = true, want false (contracted negation should block)", c) - } - } -} - -func TestIsTypedConfirmation(t *testing.T) { - positive := []string{ - "I confirm destroy 135 in strong", - "confirm", - "Confirmed.", - "yes I confirm", - } - for _, c := range positive { - if !IsTypedConfirmation(c) { - t.Errorf("IsTypedConfirmation(%q) = false, want true", c) - } - } - negative := []string{ - "yes", "go ahead", "do it", "proceed", "lgtm", // loose assent must NOT satisfy this - "no, don't confirm yet", "wait", "", - } - for _, c := range negative { - if IsTypedConfirmation(c) { - t.Errorf("IsTypedConfirmation(%q) = true, want false (only explicit confirm should pass)", c) - } - } -} - -func TestExtractPendingApprovals(t *testing.T) { - got := ExtractPendingApprovals([]string{ - "run on host:strong requires approval (risk: config_mutation) - execution 019f4930-e22b-7c47-8c6e-715dcd59df19 queued. Present the command...", - "some unrelated read-only result, no approval here", - "run on lxc:caddy requires approval (risk: destructive) - execution 019f4931-aaaa-7c47-8c6e-715dcd59df20 queued. This is classified DESTRUCTIVE - flag that clearly.", - }) - if len(got) != 2 { - t.Fatalf("expected 2 pending approvals, got %d", len(got)) - } - if got[0].ExecID != "019f4930-e22b-7c47-8c6e-715dcd59df19" || got[0].Destructive { - t.Errorf("first approval: ExecID=%s Destructive=%v", got[0].ExecID, got[0].Destructive) - } - if got[1].ExecID != "019f4931-aaaa-7c47-8c6e-715dcd59df20" || !got[1].Destructive { - t.Errorf("second approval should be flagged destructive: %+v", got[1]) - } -} - -func TestExtractPendingApprovals_NoneWhenNoneQueued(t *testing.T) { - if got := ExtractPendingApprovals(nil); len(got) != 0 { - t.Errorf("expected 0, got %d", len(got)) - } -} diff --git a/plans/2026-08-16-dsh-as-agent-replace-nomos.md b/plans/2026-08-16-dsh-as-agent-replace-nomos.md index c91ff490..2fff791e 100644 --- a/plans/2026-08-16-dsh-as-agent-replace-nomos.md +++ b/plans/2026-08-16-dsh-as-agent-replace-nomos.md @@ -320,18 +320,23 @@ Each plugin: - `evals/*.yaml` — nomos golden-conversation manifests (their only runner was `cmd/nomos/eval`; dsh evals live at `packages/oikos/evals` in the harness workspace) -- Script/doc cleanup: deploy.sh image list, verify-phase6.sh gateway checks, - seed-secrets.sh OpenRouter key source (host env now), README/CONTRIBUTING/ - AGENTS.md/operator-facing comments +- Script/doc cleanup: deploy.sh image list (+ one-time oikos-nomos image + prune), verify-phase6.sh gateway checks, seed-secrets.sh OpenRouter key + source (host env now), README/CONTRIBUTING/AGENTS.md/operator-facing + comments, compose/caddy/Caddyfile.oikos (`nomos.hubris.network` block and + `/agent/*` path removed — mirror in dtoro/caddy-conf), `.golangci.yml` + nomos-isolation rules, go.mod (openai-go dropped via `go mod tidy`) **Already gone before this pass:** `compose/web/` (SPA extracted to dtoro/oikos-web), `desktop/` (Wails wrapper, deleted with the SPA split). **Kept (per the stays list):** -- `internal/nomos/assent/` — chat-assent/typed-confirmation parsing; the - assent *window* logic lives in `internal/adapters/postgres` - (governance.go/approvals.go) behind the governance port and is shared by - the dsh consent flow +- ~~`internal/nomos/assent/`~~ — deleted after review: zero importers + remained once cmd/nomos was gone (the assent *window* logic lives in + `internal/adapters/postgres` — governance.go/approvals.go — behind the + governance port and is shared by the dsh consent flow; the orphaned + chat-text parser added nothing). `.golangci.yml` nomos rules removed with + it, and `go mod tidy` dropped the nomos-only openai-go dependency. - `internal/httpapi/` REST API, `internal/mcp/` (67+ tools), `internal/policy/`, `internal/scheduler/`, `internal/secrets/` - `OIKOS_NOMOS_AGENT_SLUG` config + compose env — resolves the seeded diff --git a/scripts/deploy.sh b/scripts/deploy.sh index 4c3042ef..19e7a7b3 100755 --- a/scripts/deploy.sh +++ b/scripts/deploy.sh @@ -247,6 +247,13 @@ if [ -n "$OIKOS_VERSION" ]; then done fi +# Decommission cleanup (nomos → dsh, plans/2026-08-16-dsh-as-agent-* +# section 5): the oikos-nomos image is no longer built or listed above, so +# prune every remaining tag. No-ops once they're gone. +docker image ls -q oikos-nomos 2>/dev/null | sort -u | while read -r img; do + docker rmi "$img" >/dev/null 2>&1 || true +done + # ── 7. Health check wait ────────────────────────────────────────────────── echo "[7/8] health check" healthy=0 diff --git a/vendor/github.com/openai/openai-go/.gitignore b/vendor/github.com/openai/openai-go/.gitignore deleted file mode 100644 index c6d05015..00000000 --- a/vendor/github.com/openai/openai-go/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -.prism.log -codegen.log -Brewfile.lock.json -.idea/ diff --git a/vendor/github.com/openai/openai-go/.release-please-manifest.json b/vendor/github.com/openai/openai-go/.release-please-manifest.json deleted file mode 100644 index de0960ab..00000000 --- a/vendor/github.com/openai/openai-go/.release-please-manifest.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - ".": "1.12.0" -} \ No newline at end of file diff --git a/vendor/github.com/openai/openai-go/.stats.yml b/vendor/github.com/openai/openai-go/.stats.yml deleted file mode 100644 index 2f2ae96c..00000000 --- a/vendor/github.com/openai/openai-go/.stats.yml +++ /dev/null @@ -1,4 +0,0 @@ -configured_endpoints: 97 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-721e6ccaa72205ee14c71f8163129920464fb814b95d3df9567a9476bbd9b7fb.yml -openapi_spec_hash: 2115413a21df8b5bf9e4552a74df4312 -config_hash: 9606bb315a193bfd8da0459040143242 diff --git a/vendor/github.com/openai/openai-go/Brewfile b/vendor/github.com/openai/openai-go/Brewfile deleted file mode 100644 index 577e34a4..00000000 --- a/vendor/github.com/openai/openai-go/Brewfile +++ /dev/null @@ -1 +0,0 @@ -brew "go" diff --git a/vendor/github.com/openai/openai-go/CHANGELOG.md b/vendor/github.com/openai/openai-go/CHANGELOG.md deleted file mode 100644 index 16a13929..00000000 --- a/vendor/github.com/openai/openai-go/CHANGELOG.md +++ /dev/null @@ -1,473 +0,0 @@ -# Changelog - -## 1.12.0 (2025-07-30) - -Full Changelog: [v1.11.1...v1.12.0](https://github.com/openai/openai-go/compare/v1.11.1...v1.12.0) - -### Features - -* **api:** manual updates ([16312ea](https://github.com/openai/openai-go/commit/16312ea2fea76c7cd2db4f38dfa10e0839f52d3e)) - - -### Chores - -* **client:** refactor streaming slightly to better future proof it ([0b9cb85](https://github.com/openai/openai-go/commit/0b9cb85a6bf0f2386e5db13aed34fbfad645efbe)) - -## 1.11.1 (2025-07-22) - -Full Changelog: [v1.11.0...v1.11.1](https://github.com/openai/openai-go/compare/v1.11.0...v1.11.1) - -### Bug Fixes - -* **client:** process custom base url ahead of time ([cc1c23e](https://github.com/openai/openai-go/commit/cc1c23e3b1f4645004cb07b75816e3df445e73df)) - - -### Chores - -* **api:** event shapes more accurate ([2acd10d](https://github.com/openai/openai-go/commit/2acd10df4df52d1954d9ee3a98e5a4e56531533b)) - -## 1.11.0 (2025-07-16) - -Full Changelog: [v1.10.3...v1.11.0](https://github.com/openai/openai-go/compare/v1.10.3...v1.11.0) - -### Features - -* **api:** manual updates ([97ed7fd](https://github.com/openai/openai-go/commit/97ed7fd1d432ad0144ec76bcebb61c9aaa1148de)) - -## 1.10.3 (2025-07-15) - -Full Changelog: [v1.10.2...v1.10.3](https://github.com/openai/openai-go/compare/v1.10.2...v1.10.3) - -## 1.10.2 (2025-07-15) - -Full Changelog: [v1.10.1...v1.10.2](https://github.com/openai/openai-go/compare/v1.10.1...v1.10.2) - -### Chores - -* **api:** update realtime specs, build config ([3d2afda](https://github.com/openai/openai-go/commit/3d2afda006bd1f9e7ebde27b2873efa67e5e480d)) - -## 1.10.1 (2025-07-11) - -Full Changelog: [v1.10.0...v1.10.1](https://github.com/openai/openai-go/compare/v1.10.0...v1.10.1) - -### Chores - -* **api:** specification cleanup ([5dbf6d2](https://github.com/openai/openai-go/commit/5dbf6d2cebe770d980db7888d705d1642ccd9cbc)) -* lint tests in subpackages ([02f440d](https://github.com/openai/openai-go/commit/02f440dc6d899d7816b9fec9c47c09b393a7dd6c)) - -## 1.10.0 (2025-07-10) - -Full Changelog: [v1.9.0...v1.10.0](https://github.com/openai/openai-go/compare/v1.9.0...v1.10.0) - -### Features - -* **api:** add file_url, fix event ID ([cb33971](https://github.com/openai/openai-go/commit/cb339714b65249844a87009192b2cf1508329673)) - -## 1.9.0 (2025-07-10) - -Full Changelog: [v1.8.3...v1.9.0](https://github.com/openai/openai-go/compare/v1.8.3...v1.9.0) - -### Features - -* **client:** expand max streaming buffer size ([44390c8](https://github.com/openai/openai-go/commit/44390c81fdf33144f088b3ee8fef02269634dbe9)) - -## 1.8.3 (2025-07-08) - -Full Changelog: [v1.8.2...v1.8.3](https://github.com/openai/openai-go/compare/v1.8.2...v1.8.3) - -### Chores - -* **ci:** only run for pushes and fork pull requests ([d6aab99](https://github.com/openai/openai-go/commit/d6aab99dadf267201add9812ba34ab2d5c70e0f4)) -* **internal:** fix lint script for tests ([9c0a745](https://github.com/openai/openai-go/commit/9c0a74553c57ea5c29fb55f5ca2e122ca96031a4)) -* lint tests ([2bd38d2](https://github.com/openai/openai-go/commit/2bd38d248cf2097254d1821a44c87827805732d1)) - -## 1.8.2 (2025-06-27) - -Full Changelog: [v1.8.1...v1.8.2](https://github.com/openai/openai-go/compare/v1.8.1...v1.8.2) - -### Bug Fixes - -* don't try to deserialize as json when ResponseBodyInto is []byte ([74ad0f8](https://github.com/openai/openai-go/commit/74ad0f8fab0f956234503a9ba26fbd395944dcf8)) -* **pagination:** check if page data is empty in GetNextPage ([c9becdc](https://github.com/openai/openai-go/commit/c9becdc9908f2a1961160837c6ab8cd9064e7854)) - -## 1.8.1 (2025-06-26) - -Full Changelog: [v1.8.0...v1.8.1](https://github.com/openai/openai-go/compare/v1.8.0...v1.8.1) - -### Chores - -* **api:** remove unsupported property ([e22316a](https://github.com/openai/openai-go/commit/e22316adcd8f2c5aa672b12453cbd287de0e1878)) -* **docs:** update README to include links to docs on Webhooks ([7bb8f85](https://github.com/openai/openai-go/commit/7bb8f8549fdd98997b1d145cbae98ff0146b4e43)) - -## 1.8.0 (2025-06-26) - -Full Changelog: [v1.7.0...v1.8.0](https://github.com/openai/openai-go/compare/v1.7.0...v1.8.0) - -### Features - -* **api:** webhook and deep research support ([f6a7e7d](https://github.com/openai/openai-go/commit/f6a7e7dcd8801facc4f8d981f1ca43786c10de1e)) - - -### Chores - -* **internal:** add tests for breaking change detection ([339522d](https://github.com/openai/openai-go/commit/339522d38cd31b0753a8df37b8924f7e7dfb0b1d)) - -## 1.7.0 (2025-06-23) - -Full Changelog: [v1.6.0...v1.7.0](https://github.com/openai/openai-go/compare/v1.6.0...v1.7.0) - -### Features - -* **api:** make model and inputs not required to create response ([19f0b76](https://github.com/openai/openai-go/commit/19f0b76378d35b3d81c60c85bf2e64d6bf85b9c2)) -* **api:** update api shapes for usage and code interpreter ([d24d42c](https://github.com/openai/openai-go/commit/d24d42cba60e565627e8ffb1cac63a5085ddb6da)) -* **client:** add escape hatch for null slice & maps ([9c633d6](https://github.com/openai/openai-go/commit/9c633d6f1dbcc0b153f42f831ee7e13d6fe62296)) - - -### Chores - -* fix documentation of null map ([8f3a134](https://github.com/openai/openai-go/commit/8f3a134e500b1b7791ab855adaef2d7b10d2d1c3)) - -## 1.6.0 (2025-06-17) - -Full Changelog: [v1.5.0...v1.6.0](https://github.com/openai/openai-go/compare/v1.5.0...v1.6.0) - -### Features - -* **api:** add reusable prompt IDs ([280c698](https://github.com/openai/openai-go/commit/280c698015eba5f6bd47e2fce038eb401f6ef0f2)) -* **api:** manual updates ([740f840](https://github.com/openai/openai-go/commit/740f84006ac283a25f5ad96aaf845a3c8a51c6ac)) -* **client:** add debug log helper ([5715c49](https://github.com/openai/openai-go/commit/5715c491c483f8dab4ea2a900c400384f6810024)) - - -### Chores - -* **ci:** enable for pull requests ([9ed793a](https://github.com/openai/openai-go/commit/9ed793a51010423db464a7b7bd263d2fd275967f)) - -## 1.5.0 (2025-06-10) - -Full Changelog: [v1.4.0...v1.5.0](https://github.com/openai/openai-go/compare/v1.4.0...v1.5.0) - -### Features - -* **api:** Add o3-pro model IDs ([3bbd0b8](https://github.com/openai/openai-go/commit/3bbd0b8f09030a6c571900d444742c4fc2a3c211)) - -## 1.4.0 (2025-06-09) - -Full Changelog: [v1.3.0...v1.4.0](https://github.com/openai/openai-go/compare/v1.3.0...v1.4.0) - -### Features - -* **client:** allow overriding unions ([27c6299](https://github.com/openai/openai-go/commit/27c6299cb4ac275c6542b5691d81b795e65eeff6)) - - -### Bug Fixes - -* **client:** cast to raw message when converting to params ([a3282b0](https://github.com/openai/openai-go/commit/a3282b01a8d9a2c0cd04f24b298bf2ffcd160ebd)) - -## 1.3.0 (2025-06-03) - -Full Changelog: [v1.2.1...v1.3.0](https://github.com/openai/openai-go/compare/v1.2.1...v1.3.0) - -### Features - -* **api:** add new realtime and audio models, realtime session options ([8b8f62b](https://github.com/openai/openai-go/commit/8b8f62b8e185f3fe4aaa99e892df5d35638931a1)) - -## 1.2.1 (2025-06-02) - -Full Changelog: [v1.2.0...v1.2.1](https://github.com/openai/openai-go/compare/v1.2.0...v1.2.1) - -### Bug Fixes - -* **api:** Fix evals and code interpreter interfaces ([7e244c7](https://github.com/openai/openai-go/commit/7e244c73caad6b4768cced9a798452f03b1165c8)) -* fix error ([a200fca](https://github.com/openai/openai-go/commit/a200fca92c3fa413cf724f424077d1537fa2ca3e)) - - -### Chores - -* make go mod tidy continue on error ([48f41c2](https://github.com/openai/openai-go/commit/48f41c2993bf6181018da859ae759951261f9ee2)) - -## 1.2.0 (2025-05-29) - -Full Changelog: [v1.1.0...v1.2.0](https://github.com/openai/openai-go/compare/v1.1.0...v1.2.0) - -### Features - -* **api:** Config update for pakrym-stream-param ([84d59d5](https://github.com/openai/openai-go/commit/84d59d5cbc7521ddcc04435317903fd4ec3d17f6)) - - -### Bug Fixes - -* **client:** return binary content from `get /containers/{container_id}/files/{file_id}/content` ([f8c8de1](https://github.com/openai/openai-go/commit/f8c8de18b720b224267d54da53d7d919ed0fdff3)) - - -### Chores - -* deprecate Assistants API ([027470e](https://github.com/openai/openai-go/commit/027470e066ea6bbca1aeeb4fb9a8a3430babb84c)) -* **internal:** fix release workflows ([fd46533](https://github.com/openai/openai-go/commit/fd4653316312755ccab7435fca9fb0a2d8bf8fbb)) - -## 1.1.0 (2025-05-22) - -Full Changelog: [v1.0.0...v1.1.0](https://github.com/openai/openai-go/compare/v1.0.0...v1.1.0) - -### Features - -* **api:** add container endpoint ([2bd777d](https://github.com/openai/openai-go/commit/2bd777d6813b5dfcd3a2d339047a944c478dcd64)) -* **api:** new API tools ([e7e2123](https://github.com/openai/openai-go/commit/e7e2123de7cafef515e07adde6edd45a7035b610)) -* **api:** new streaming helpers for background responses ([422a0db](https://github.com/openai/openai-go/commit/422a0db3c674135e23dd200f5d8d785bd0be33e6)) - - -### Chores - -* **docs:** grammar improvements ([f4b23dd](https://github.com/openai/openai-go/commit/f4b23dd31facfc8839310854521b48060ef76be2)) -* improve devcontainer setup ([dfdaeec](https://github.com/openai/openai-go/commit/dfdaeec2d6dd5cd679514d60c49b68c5df9e1b1e)) - -## 1.0.0 (2025-05-19) - -Full Changelog: [v0.1.0-beta.11...v1.0.0](https://github.com/openai/openai-go/compare/v0.1.0-beta.11...v1.0.0) - -### ⚠ BREAKING CHANGES - -* **client:** rename file array param variant -* **api:** improve naming and remove assistants -* **accumulator:** update casing ([#401](https://github.com/openai/openai-go/issues/401)) - -### Features - -* **api:** improve naming and remove assistants ([4c623b8](https://github.com/openai/openai-go/commit/4c623b88a9025db1961cc57985eb7374342f43e7)) - - -### Bug Fixes - -* **accumulator:** update casing ([#401](https://github.com/openai/openai-go/issues/401)) ([d59453c](https://github.com/openai/openai-go/commit/d59453c95b89fdd0b51305778dec0a39ce3a9d2a)) -* **client:** correctly set stream key for multipart ([0ec68f0](https://github.com/openai/openai-go/commit/0ec68f0d779e7726931b1115eca9ae81eab59ba8)) -* **client:** don't panic on marshal with extra null field ([9c15332](https://github.com/openai/openai-go/commit/9c153320272d212beaa516d4c70d54ae8053a958)) -* **client:** increase max stream buffer size ([9456455](https://github.com/openai/openai-go/commit/945645559c5d68d9e28cf445d9c3b83e5fc6bd35)) -* **client:** rename file array param variant ([4cfcf86](https://github.com/openai/openai-go/commit/4cfcf869280e7531fbbc8c00db0dd9271d07c423)) -* **client:** use scanner for streaming ([aa58806](https://github.com/openai/openai-go/commit/aa58806bffc3aed68425c480414ddbb4dac3fa78)) - - -### Chores - -* **docs:** typo fix ([#400](https://github.com/openai/openai-go/issues/400)) ([bececf2](https://github.com/openai/openai-go/commit/bececf24cd0324b7c991b7d7f1d3eff6bf71f996)) -* **examples:** migrate enum ([#447](https://github.com/openai/openai-go/issues/447)) ([814dd8b](https://github.com/openai/openai-go/commit/814dd8b6cfe4eeb535dc8ecd161a409ea2eb6698)) -* **examples:** migrate to latest version ([#444](https://github.com/openai/openai-go/issues/444)) ([1c8754f](https://github.com/openai/openai-go/commit/1c8754ff905ed023f6381c8493910d63039407de)) -* **examples:** remove beta assisstants examples ([#445](https://github.com/openai/openai-go/issues/445)) ([5891583](https://github.com/openai/openai-go/commit/589158372be9c0517b5508f9ccd872fdb1fe480b)) -* **example:** update fine-tuning ([#450](https://github.com/openai/openai-go/issues/450)) ([421e3c5](https://github.com/openai/openai-go/commit/421e3c5065ace2d5ddd3d13a036477fff9123e5f)) - -## 0.1.0-beta.11 (2025-05-16) - -Full Changelog: [v0.1.0-beta.10...v0.1.0-beta.11](https://github.com/openai/openai-go/compare/v0.1.0-beta.10...v0.1.0-beta.11) - -### ⚠ BREAKING CHANGES - -* **client:** clearer array variant names -* **client:** rename resp package -* **client:** improve core function names -* **client:** improve union variant names -* **client:** improve param subunions & deduplicate types - -### Features - -* **api:** add image sizes, reasoning encryption ([0852fb3](https://github.com/openai/openai-go/commit/0852fb3101dc940761f9e4f32875bfcf3669eada)) -* **api:** add o3 and o4-mini model IDs ([3fabca6](https://github.com/openai/openai-go/commit/3fabca6b5c610edfb7bcd0cab5334a06444df0b0)) -* **api:** Add reinforcement fine-tuning api support ([831a124](https://github.com/openai/openai-go/commit/831a12451cfce907b5ae4d294b9c2ac95f40d97a)) -* **api:** adding gpt-4.1 family of model IDs ([1ef19d4](https://github.com/openai/openai-go/commit/1ef19d4cc94992dc435d7d5f28b30c9b1d255cd4)) -* **api:** adding new image model support ([bf17880](https://github.com/openai/openai-go/commit/bf17880e182549c5c0fc34ec05df3184f223bc00)) -* **api:** manual updates ([11f5716](https://github.com/openai/openai-go/commit/11f5716afa86aa100f80f3fa127e1d49203e5e21)) -* **api:** responses x eval api ([183aaf7](https://github.com/openai/openai-go/commit/183aaf700f1d7ffad4ac847627d9ace65379c459)) -* **api:** Updating Assistants and Evals API schemas ([47ca619](https://github.com/openai/openai-go/commit/47ca619fa1b439cf3a68c98e48e9bf1942f0568b)) -* **client:** add dynamic streaming buffer to handle large lines ([8e6aad6](https://github.com/openai/openai-go/commit/8e6aad6d54fc73f1fcc174e1f06c9b3cf00c2689)) -* **client:** add helper method to generate constant structs ([ff82809](https://github.com/openai/openai-go/commit/ff828094b561fc11184fed83f04424b6f68f7781)) -* **client:** add support for endpoint-specific base URLs in python ([072dce4](https://github.com/openai/openai-go/commit/072dce46486d373fa0f0de5415f5270b01c2d972)) -* **client:** add support for reading base URL from environment variable ([0d37268](https://github.com/openai/openai-go/commit/0d372687d673990290bad583f1906a2b121960b2)) -* **client:** clearer array variant names ([a5d8b5d](https://github.com/openai/openai-go/commit/a5d8b5d6b161e3083184586840b2cbe0606d8de1)) -* **client:** experimental support for unmarshalling into param structs ([5234875](https://github.com/openai/openai-go/commit/523487582e15a47e2f409f183568551258f4b8fe)) -* **client:** improve param subunions & deduplicate types ([8a78f37](https://github.com/openai/openai-go/commit/8a78f37c25abf10498d16d210de3078f491ff23e)) -* **client:** rename resp package ([4433516](https://github.com/openai/openai-go/commit/443351625ee290937a25425719b099ce785bd21b)) -* **client:** support more time formats ([ec171b2](https://github.com/openai/openai-go/commit/ec171b2405c46f9cf04560760da001f7133d2fec)) -* fix lint ([9c50a1e](https://github.com/openai/openai-go/commit/9c50a1eb9f93b578cb78085616f6bfab69f21dbc)) - - -### Bug Fixes - -* **client:** clean up reader resources ([710b92e](https://github.com/openai/openai-go/commit/710b92eaa7e94c03aeeca7479668677b32acb154)) -* **client:** correctly update body in WithJSONSet ([f2d7118](https://github.com/openai/openai-go/commit/f2d7118295dd3073aa449426801d02e6f60bdaa3)) -* **client:** improve core function names ([9f312a9](https://github.com/openai/openai-go/commit/9f312a9b14f5424d44d5834f1b82f3d3fcd57db2)) -* **client:** improve union variant names ([a2c3de9](https://github.com/openai/openai-go/commit/a2c3de9e6c9f6e406b953f6de2eb78d1e72ec1b5)) -* **client:** include path for type names in example code ([69561c5](https://github.com/openai/openai-go/commit/69561c549e18bd16a3641d62769479b125a4e955)) -* **client:** resolve issue with optional multipart files ([910d173](https://github.com/openai/openai-go/commit/910d1730e97a03898e5dee7c889844a2ccec3e56)) -* **client:** time format encoding fix ([ca17553](https://github.com/openai/openai-go/commit/ca175533ac8a17d36be1f531bbaa89c770da3f58)) -* **client:** unmarshal responses properly ([fc9fec3](https://github.com/openai/openai-go/commit/fc9fec3c466ba9f633c3f7a4eebb5ebd3b85e8ac)) -* handle empty bodies in WithJSONSet ([8372464](https://github.com/openai/openai-go/commit/83724640c6c00dcef1547dcabace309f17d14afc)) -* **pagination:** handle errors when applying options ([eebf84b](https://github.com/openai/openai-go/commit/eebf84bf19f0eb6d9fa21e64bb83b0258e8cb42c)) - - -### Chores - -* **ci:** add timeout thresholds for CI jobs ([26b0dd7](https://github.com/openai/openai-go/commit/26b0dd760c142ca3aa287e8441bbe44cc8b3be0b)) -* **ci:** only use depot for staging repos ([7682154](https://github.com/openai/openai-go/commit/7682154fdbcbe2a2ffdb2df590647a1712d52275)) -* **ci:** run on more branches and use depot runners ([d7badbc](https://github.com/openai/openai-go/commit/d7badbc0d17bcf3cffec332f65cb68e531cb3176)) -* **docs:** document pre-request options ([4befa5a](https://github.com/openai/openai-go/commit/4befa5a48ca61372715f36c45e72eb159d95bf2d)) -* **docs:** update respjson package name ([9a00229](https://github.com/openai/openai-go/commit/9a002299a91e1145f053c51b1a4de10298fd2f43)) -* **readme:** improve formatting ([a847e8d](https://github.com/openai/openai-go/commit/a847e8df45f725f9652fcea53ce57d3b9046efc7)) -* **utils:** add internal resp to param utility ([239c4e2](https://github.com/openai/openai-go/commit/239c4e2cb32c7af71ab14668ccc2f52ea59653f9)) - - -### Documentation - -* update documentation links to be more uniform ([f5f0bb0](https://github.com/openai/openai-go/commit/f5f0bb05ee705d84119806f8e703bf2e0becb1fa)) - -## 0.1.0-beta.10 (2025-04-14) - -Full Changelog: [v0.1.0-beta.9...v0.1.0-beta.10](https://github.com/openai/openai-go/compare/v0.1.0-beta.9...v0.1.0-beta.10) - -### Chores - -* **internal:** expand CI branch coverage ([#369](https://github.com/openai/openai-go/issues/369)) ([258dda8](https://github.com/openai/openai-go/commit/258dda8007a69b9c2720b225ee6d27474d676a93)) -* **internal:** reduce CI branch coverage ([a2f7c03](https://github.com/openai/openai-go/commit/a2f7c03eb984d98f29f908df103ea1743f2e3d9a)) - -## 0.1.0-beta.9 (2025-04-09) - -Full Changelog: [v0.1.0-beta.8...v0.1.0-beta.9](https://github.com/openai/openai-go/compare/v0.1.0-beta.8...v0.1.0-beta.9) - -### Chores - -* workaround build errors ([#366](https://github.com/openai/openai-go/issues/366)) ([adeb003](https://github.com/openai/openai-go/commit/adeb003cab8efbfbf4424e03e96a0f5e728551cb)) - -## 0.1.0-beta.8 (2025-04-09) - -Full Changelog: [v0.1.0-beta.7...v0.1.0-beta.8](https://github.com/openai/openai-go/compare/v0.1.0-beta.7...v0.1.0-beta.8) - -### Features - -* **api:** Add evalapi to sdk ([#360](https://github.com/openai/openai-go/issues/360)) ([88977d1](https://github.com/openai/openai-go/commit/88977d1868dbbe0060c56ba5dac8eb19773e4938)) -* **api:** manual updates ([#363](https://github.com/openai/openai-go/issues/363)) ([5d068e0](https://github.com/openai/openai-go/commit/5d068e0053172db7f5b75038aa215eee074eeeed)) -* **client:** add escape hatch to omit required param fields ([#354](https://github.com/openai/openai-go/issues/354)) ([9690d6b](https://github.com/openai/openai-go/commit/9690d6b49f8b00329afc038ec15116750853e620)) -* **client:** support custom http clients ([#357](https://github.com/openai/openai-go/issues/357)) ([b5a624f](https://github.com/openai/openai-go/commit/b5a624f658cad774094427b36b05e446b41e8c52)) - - -### Chores - -* **docs:** readme improvements ([#356](https://github.com/openai/openai-go/issues/356)) ([b2f8539](https://github.com/openai/openai-go/commit/b2f8539d6316e3443aa733be2c95926696119c13)) -* **internal:** fix examples ([#361](https://github.com/openai/openai-go/issues/361)) ([de398b4](https://github.com/openai/openai-go/commit/de398b453d398299eb80c15f8fdb2bcbef5eeed6)) -* **internal:** skip broken test ([#362](https://github.com/openai/openai-go/issues/362)) ([cccead9](https://github.com/openai/openai-go/commit/cccead9ba916142ac8fbe6e8926d706511e32ae3)) -* **tests:** improve enum examples ([#359](https://github.com/openai/openai-go/issues/359)) ([e0b9739](https://github.com/openai/openai-go/commit/e0b9739920114d6e991d3947b67fdf62cfaa09c7)) - -## 0.1.0-beta.7 (2025-04-07) - -Full Changelog: [v0.1.0-beta.6...v0.1.0-beta.7](https://github.com/openai/openai-go/compare/v0.1.0-beta.6...v0.1.0-beta.7) - -### Features - -* **client:** make response union's AsAny method type safe ([#352](https://github.com/openai/openai-go/issues/352)) ([1252f56](https://github.com/openai/openai-go/commit/1252f56c917e57d6d2b031501b2ff5f89f87cf87)) - - -### Chores - -* **docs:** doc improvements ([#350](https://github.com/openai/openai-go/issues/350)) ([80debc8](https://github.com/openai/openai-go/commit/80debc824eaacb4b07c8f3e8b1d0488d860d5be5)) - -## 0.1.0-beta.6 (2025-04-04) - -Full Changelog: [v0.1.0-beta.5...v0.1.0-beta.6](https://github.com/openai/openai-go/compare/v0.1.0-beta.5...v0.1.0-beta.6) - -### Features - -* **api:** manual updates ([4e39609](https://github.com/openai/openai-go/commit/4e39609d499b88039f1c90cc4b56e26f28fd58ea)) -* **client:** support unions in query and forms ([#347](https://github.com/openai/openai-go/issues/347)) ([cf8af37](https://github.com/openai/openai-go/commit/cf8af373ab7c019c75e886855009ffaca320d0e3)) - -## 0.1.0-beta.5 (2025-04-03) - -Full Changelog: [v0.1.0-beta.4...v0.1.0-beta.5](https://github.com/openai/openai-go/compare/v0.1.0-beta.4...v0.1.0-beta.5) - -### Features - -* **api:** manual updates ([563cc50](https://github.com/openai/openai-go/commit/563cc505f2ab17749bb77e937342a6614243b975)) -* **client:** omitzero on required id parameter ([#339](https://github.com/openai/openai-go/issues/339)) ([c0b4842](https://github.com/openai/openai-go/commit/c0b484266ccd9faee66873916d8c0c92ea9f1014)) - - -### Bug Fixes - -* **client:** return error on bad custom url instead of panic ([#341](https://github.com/openai/openai-go/issues/341)) ([a06c5e6](https://github.com/openai/openai-go/commit/a06c5e632242e53d3fdcc8964931acb533a30b7e)) -* **client:** support multipart encoding array formats ([#342](https://github.com/openai/openai-go/issues/342)) ([5993b28](https://github.com/openai/openai-go/commit/5993b28309d02c2d748b54d98934ef401dcd193a)) -* **client:** unmarshal stream events into fresh memory ([#340](https://github.com/openai/openai-go/issues/340)) ([52c3e08](https://github.com/openai/openai-go/commit/52c3e08f51d471d728e5acd16b3c304b51be2d03)) - -## 0.1.0-beta.4 (2025-04-02) - -Full Changelog: [v0.1.0-beta.3...v0.1.0-beta.4](https://github.com/openai/openai-go/compare/v0.1.0-beta.3...v0.1.0-beta.4) - -### Features - -* **api:** manual updates ([bc4fe73](https://github.com/openai/openai-go/commit/bc4fe73eec9c4d39229e4beae8eaafb55b1d3364)) -* **api:** manual updates ([aa7ff10](https://github.com/openai/openai-go/commit/aa7ff10b0616a6b2ece45cb10e9c83f25e35aded)) - - -### Chores - -* **docs:** update file uploads in README ([#333](https://github.com/openai/openai-go/issues/333)) ([471c452](https://github.com/openai/openai-go/commit/471c4525c94e83cf4b78cb6c9b2f65a8a27bf3ce)) -* **internal:** codegen related update ([#335](https://github.com/openai/openai-go/issues/335)) ([48422dc](https://github.com/openai/openai-go/commit/48422dcca333ab808ccb02506c033f1c69d2aa19)) -* Remove deprecated/unused remote spec feature ([c5077a1](https://github.com/openai/openai-go/commit/c5077a154a6db79b73cf4978bdc08212c6da6423)) - -## 0.1.0-beta.3 (2025-03-28) - -Full Changelog: [v0.1.0-beta.2...v0.1.0-beta.3](https://github.com/openai/openai-go/compare/v0.1.0-beta.2...v0.1.0-beta.3) - -### ⚠ BREAKING CHANGES - -* **client:** add enums ([#327](https://github.com/openai/openai-go/issues/327)) - -### Features - -* **api:** add `get /chat/completions` endpoint ([e8ed116](https://github.com/openai/openai-go/commit/e8ed1168576c885cb26fbf819b9c8d24975749bd)) -* **api:** add `get /responses/{response_id}/input_items` endpoint ([8870c26](https://github.com/openai/openai-go/commit/8870c26f010a596adcf37ac10dba096bdd4394e3)) - - -### Bug Fixes - -* **client:** add enums ([#327](https://github.com/openai/openai-go/issues/327)) ([b0e3afb](https://github.com/openai/openai-go/commit/b0e3afbd6f18fd9fc2a5ea9174bd7ec0ac0614db)) - - -### Chores - -* add hash of OpenAPI spec/config inputs to .stats.yml ([104b786](https://github.com/openai/openai-go/commit/104b7861bb025514999b143f7d1de45d2dab659f)) -* add request options to client tests ([#321](https://github.com/openai/openai-go/issues/321)) ([f5239ce](https://github.com/openai/openai-go/commit/f5239ceecf36835341eac5121ed1770020c4806a)) -* **api:** updates to supported Voice IDs ([#325](https://github.com/openai/openai-go/issues/325)) ([477727a](https://github.com/openai/openai-go/commit/477727a44b0fb72493c4749cc60171e0d30f98ec)) -* **docs:** improve security documentation ([#319](https://github.com/openai/openai-go/issues/319)) ([0271053](https://github.com/openai/openai-go/commit/027105363ab30ac3e189234908169faf94e0ca49)) -* fix typos ([#324](https://github.com/openai/openai-go/issues/324)) ([dba15f7](https://github.com/openai/openai-go/commit/dba15f74d63814ce16f778e1017a209a42f46179)) - -## 0.1.0-beta.2 (2025-03-22) - -Full Changelog: [v0.1.0-beta.1...v0.1.0-beta.2](https://github.com/openai/openai-go/compare/v0.1.0-beta.1...v0.1.0-beta.2) - -### Bug Fixes - -* **client:** elide fields in ToAssistantParam ([#309](https://github.com/openai/openai-go/issues/309)) ([1fcd837](https://github.com/openai/openai-go/commit/1fcd83753ea806745d278a5b94797bbee0f018ed)) - -## 0.1.0-beta.1 (2025-03-22) - -Full Changelog: [v0.1.0-alpha.67...v0.1.0-beta.1](https://github.com/openai/openai-go/compare/v0.1.0-alpha.67...v0.1.0-beta.1) - -### Chores - -* **docs:** clarify breaking changes ([#306](https://github.com/openai/openai-go/issues/306)) ([db4bd1f](https://github.com/openai/openai-go/commit/db4bd1f5304aa523a6b62da6e2571487d4248518)) - -## 0.1.0-alpha.67 (2025-03-21) - -Full Changelog: [v0.1.0-alpha.66...v0.1.0-alpha.67](https://github.com/openai/openai-go/compare/v0.1.0-alpha.66...v0.1.0-alpha.67) - -### ⚠ BREAKING CHANGES - -* **api:** migrate to v2 - -### Features - -* **api:** migrate to v2 ([9377508](https://github.com/openai/openai-go/commit/9377508e45ae485d11c3199d6d3d91d345f1b76e)) -* **api:** new models for TTS, STT, + new audio features for Realtime ([#298](https://github.com/openai/openai-go/issues/298)) ([48fa064](https://github.com/openai/openai-go/commit/48fa064202a6e4a3e850d435b29f6fe9a1fe53f4)) - - -### Chores - -* **internal:** bugfix ([0d8c1f4](https://github.com/openai/openai-go/commit/0d8c1f4e801785728b6ad3342146fe38874d6c04)) - - -### Documentation - -* add migration guide ([#302](https://github.com/openai/openai-go/issues/302)) ([19e32fa](https://github.com/openai/openai-go/commit/19e32fa595e65048bb129e813c697991117abca2)) diff --git a/vendor/github.com/openai/openai-go/CONTRIBUTING.md b/vendor/github.com/openai/openai-go/CONTRIBUTING.md deleted file mode 100644 index 95426be2..00000000 --- a/vendor/github.com/openai/openai-go/CONTRIBUTING.md +++ /dev/null @@ -1,66 +0,0 @@ -## Setting up the environment - -To set up the repository, run: - -```sh -$ ./scripts/bootstrap -$ ./scripts/lint -``` - -This will install all the required dependencies and build the SDK. - -You can also [install go 1.18+ manually](https://go.dev/doc/install). - -## Modifying/Adding code - -Most of the SDK is generated code. Modifications to code will be persisted between generations, but may -result in merge conflicts between manual patches and changes from the generator. The generator will never -modify the contents of the `lib/` and `examples/` directories. - -## Adding and running examples - -All files in the `examples/` directory are not modified by the generator and can be freely edited or added to. - -```go -# add an example to examples//main.go - -package main - -func main() { - // ... -} -``` - -```sh -$ go run ./examples/ -``` - -## Using the repository from source - -To use a local version of this library from source in another project, edit the `go.mod` with a replace -directive. This can be done through the CLI with the following: - -```sh -$ go mod edit -replace github.com/openai/openai-go=/path/to/openai-go -``` - -## Running tests - -Most tests require you to [set up a mock server](https://github.com/stoplightio/prism) against the OpenAPI spec to run the tests. - -```sh -# you will need npm installed -$ npx prism mock path/to/your/openapi.yml -``` - -```sh -$ ./scripts/test -``` - -## Formatting - -This library uses the standard gofmt code formatter: - -```sh -$ ./scripts/format -``` diff --git a/vendor/github.com/openai/openai-go/LICENSE b/vendor/github.com/openai/openai-go/LICENSE deleted file mode 100644 index f011417a..00000000 --- a/vendor/github.com/openai/openai-go/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright 2025 OpenAI - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/openai/openai-go/MIGRATION.md b/vendor/github.com/openai/openai-go/MIGRATION.md deleted file mode 100644 index 54990b8a..00000000 --- a/vendor/github.com/openai/openai-go/MIGRATION.md +++ /dev/null @@ -1,284 +0,0 @@ -# OpenAI Go Migration Guide - -Go Reference - -This SDK includes breaking changes to improve the ergonomics of constructing parameters and accessing responses. - -To reduce verbosity, the `openai.F(...)` and `param.Field[T]` have been removed. -All calls to `openai.F(...)` can be deleted. - -The SDK now uses the \`json:"...,omitzero"\` struct tag to omit fields. Nested structs, arrays and maps -can be declared like normal. - -The old SDK used interfaces for unions in requests, which required -a type assertion to access variants and fields. The new design uses -structs with a field for each variant, wherein only one field can be set. -These struct unions also expose 'Get' methods to access and mutate subfields -which may be shared by multiple variants. - -# Request parameters - -## Required primitives parameters serialize their zero values (`string`, `int64`, etc.) - -> [!CAUTION] -> -> **This change can cause new behavior in existing code, without compiler warnings.** - -While migrating, ensure that all required fields are explicitly set. A required primitive -field `Age` will use the \`json:"age,required"\` struct tag without `omitzero`. - -If a required primitive field is not set, the zero value will be serialized. -This was not the case in with `param.Field[T]`. - -```diff -type FooParams struct { -- Age param.Field[int64] `json:"age,required"` -- Name param.Field[string] `json:"name"` -+ Age int64 `json:"age,required"` // <== Notice no omitzero -+ Name param.Opt[string] `json:"name,omitzero"` -} -``` - - - - - - - - - - -
PreviousNew
- -```go -_ = FooParams{ - Name: openai.String("Jerry") -} -`{"name": "Jerry"}` // (after serialization) -``` - - - -```go -_ = FooParams{ - Name: openai.String("Jerry") -} -`{"name": "Jerry", "age": 0}` // <== Notice the age field -``` - -
- -The required field `"age"` is now present as `0`. Fields without the \`json:"...,omitzero"\` struct tag -are always serialized, including their zero values. - -## Transition from `param.Field[T]` to `omitzero` - -The `openai.F(...)` function and `param.Field[T]` type are no longer present in the new SDK. - -To represent omitted fields, the SDK uses \`json:"...,omitzero"\` semantics from Go 1.24+ for JSON encoding[^1]. `omitzero` always omits fields -with zero values. - -In all cases other than optional primitives, `openai.F()` can simply be removed. -For optional primitive types, such as `param.Opt[string]`, you can use `openai.String(string)` to construct the value. -Similar functions exist for other primitive types like `openai.Int(int)`, `openai.Bool(bool)`, etc. - -`omitzero` is used for fields whose type is either a struct, slice, map, string enum, -or wrapped optional primitive (e.g. `param.Opt[T]`). Required primitive fields don't use `omitzero`. - -**Example User Code: Constructing a request** - -```diff -foo = FooParams{ -- RequiredString: openai.String("hello"), -+ RequiredString: "hello", - -- OptionalString: openai.String("hi"), -+ OptionalString: openai.String("hi"), - -- Array: openai.F([]BarParam{ -- BarParam{Prop: ... } -- }), -+ Array: []BarParam{ -+ BarParam{Prop: ... } -+ }, - -- RequiredObject: openai.F(BarParam{ ... }), -+ RequiredObject: BarParam{ ... }, - -- OptionalObject: openai.F(BarParam{ ... }), -+ OptionalObject: BarParam{ ... }, - -- StringEnum: openai.F[BazEnum]("baz-ok"), -+ StringEnum: "baz-ok", -} -``` - -**Internal SDK Code: Fields of a request struct:** - -```diff -type FooParams struct { -- RequiredString param.Field[string] `json:"required_string,required"` -+ RequiredString string `json:"required_string,required"` - -- OptionalString param.Field[string] `json:"optional_string"` -+ OptionalString param.Opt[string] `json:"optional_string,omitzero"` - -- Array param.Field[[]BarParam] `json"array"` -+ Array []BarParam `json"array,omitzero"` - -- Map param.Field[map[string]BarParam] `json"map"` -+ Map map[string]BarParam `json"map,omitzero"` - -- RequiredObject param.Field[BarParam] `json:"required_object,required"` -+ RequiredObject BarParam `json:"required_object,omitzero,required"` - -- OptionalObject param.Field[BarParam] `json:"optional_object"` -+ OptionalObject BarParam `json:"optional_object,omitzero"` - -- StringEnum param.Field[BazEnum] `json:"string_enum"` -+ StringEnum BazEnum `json:"string_enum,omitzero"` -} -``` - -## Request Unions: Removing interfaces and moving to structs - -For a type `AnimalUnionParam` which could be either a `CatParam | DogParam`. - - - - - - - - - - - - - - - - - -
Previous New
- -```go -type AnimalParam interface { - ImplAnimalParam() -} - -func (Dog) ImplAnimalParam() {} -func (Cat) ImplAnimalParam() {} -``` - - - -```go -type AnimalUnionParam struct { - OfCat *Cat `json:",omitzero,inline` - OfDog *Dog `json:",omitzero,inline` -} -``` - -
- -```go -var dog AnimalParam = DogParam{ - Name: "spot", ... -} -var cat AnimalParam = CatParam{ - Name: "whiskers", ... -} -``` - - - -```go -dog := AnimalUnionParam{ - OfDog: &DogParam{Name: "spot", ... }, -} -cat := AnimalUnionParam{ - OfCat: &CatParam{Name: "whiskers", ... }, -} -``` - -
- -```go -var name string -switch v := animal.(type) { -case Dog: - name = v.Name -case Cat: - name = v.Name -} -``` - - - -```go -// Accessing fields -var name *string = animal.GetName() -``` - -
- -## Sending explicit `null` values - -The old SDK had a function `param.Null[T]()` which could set `param.Field[T]` to `null`. - -The new SDK uses `param.Null[T]()` for to set a `param.Opt[T]` to `null`, -but `param.NullStruct[T]()` to set a param struct `T` to `null`. - -```diff -- var nullPrimitive param.Field[int64] = param.Null[int64]() -+ var nullPrimitive param.Opt[int64] = param.Null[int64]() - -- var nullStruct param.Field[BarParam] = param.Null[BarParam]() -+ var nullStruct BarParam = param.NullStruct[BarParam]() -``` - -## Sending custom values - -The `openai.Raw[T](any)` function has been removed. All request structs now support a -`.WithExtraField(map[string]any)` method to customize the fields. - -```diff -foo := FooParams{ - A: param.String("hello"), -- B: param.Raw[string](12) // sending `12` instead of a string -} -+ foo.SetExtraFields(map[string]any{ -+ "B": 12, -+ }) -``` - -# Response Properties - -## Checking for presence of optional fields - -The `.IsNull()` method has been changed to `.Valid()` to better reflect its behavior. - -```diff -- if !resp.Foo.JSON.Bar.IsNull() { -+ if resp.Foo.JSON.Bar.Valid() { - println("bar is present:", resp.Foo.Bar) -} -``` - -| Previous | New | Returns true for values | -| -------------- | ------------------------ | ----------------------- | -| `.IsNull()` | `!.Valid()` | `null` or Omitted | -| `.IsMissing()` | `.Raw() == resp.Omitted` | Omitted | -| | `.Raw() == resp.Null` | - -## Checking Raw JSON of a response - -The `.RawJSON()` method has moved to the parent of the `.JSON` property. - -```diff -- resp.Foo.JSON.RawJSON() -+ resp.Foo.RawJSON() -``` - -[^1]: The SDK doesn't require Go 1.24, despite supporting the `omitzero` feature diff --git a/vendor/github.com/openai/openai-go/README.md b/vendor/github.com/openai/openai-go/README.md deleted file mode 100644 index 153fc936..00000000 --- a/vendor/github.com/openai/openai-go/README.md +++ /dev/null @@ -1,948 +0,0 @@ -# OpenAI Go API Library - -Go Reference - -The OpenAI Go library provides convenient access to the [OpenAI REST API](https://platform.openai.com/docs) -from applications written in Go. - -> [!WARNING] -> The latest version of this package uses a new design with significant breaking changes. -> Please refer to the [migration guide](./MIGRATION.md) for more information on how to update your code. - -## Installation - - - -```go -import ( - "github.com/openai/openai-go" // imported as openai -) -``` - - - -Or to pin the version: - - - -```sh -go get -u 'github.com/openai/openai-go@v1.12.0' -``` - - - -## Requirements - -This library requires Go 1.18+. - -## Usage - -The full API of this library can be found in [api.md](api.md). - -```go -package main - -import ( - "context" - "fmt" - - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/shared" -) - -func main() { - client := openai.NewClient( - option.WithAPIKey("My API Key"), // defaults to os.LookupEnv("OPENAI_API_KEY") - ) - chatCompletion, err := client.Chat.Completions.New(context.TODO(), openai.ChatCompletionNewParams{ - Messages: []openai.ChatCompletionMessageParamUnion{ - openai.UserMessage("Say this is a test"), - }, - Model: openai.ChatModelGPT4o, - }) - if err != nil { - panic(err.Error()) - } - println(chatCompletion.Choices[0].Message.Content) -} - -``` - -
-Conversations - -```go -param := openai.ChatCompletionNewParams{ - Messages: []openai.ChatCompletionMessageParamUnion{ - openai.UserMessage("What kind of houseplant is easy to take care of?"), - }, - Seed: openai.Int(1), - Model: openai.ChatModelGPT4o, -} - -completion, err := client.Chat.Completions.New(ctx, param) - -param.Messages = append(param.Messages, completion.Choices[0].Message.ToParam()) -param.Messages = append(param.Messages, openai.UserMessage("How big are those?")) - -// continue the conversation -completion, err = client.Chat.Completions.New(ctx, param) -``` - -
- -
-Streaming responses - -```go -question := "Write an epic" - -stream := client.Chat.Completions.NewStreaming(ctx, openai.ChatCompletionNewParams{ - Messages: []openai.ChatCompletionMessageParamUnion{ - openai.UserMessage(question), - }, - Seed: openai.Int(0), - Model: openai.ChatModelGPT4o, -}) - -// optionally, an accumulator helper can be used -acc := openai.ChatCompletionAccumulator{} - -for stream.Next() { - chunk := stream.Current() - acc.AddChunk(chunk) - - if content, ok := acc.JustFinishedContent(); ok { - println("Content stream finished:", content) - } - - // if using tool calls - if tool, ok := acc.JustFinishedToolCall(); ok { - println("Tool call stream finished:", tool.Index, tool.Name, tool.Arguments) - } - - if refusal, ok := acc.JustFinishedRefusal(); ok { - println("Refusal stream finished:", refusal) - } - - // it's best to use chunks after handling JustFinished events - if len(chunk.Choices) > 0 { - println(chunk.Choices[0].Delta.Content) - } -} - -if stream.Err() != nil { - panic(stream.Err()) -} - -// After the stream is finished, acc can be used like a ChatCompletion -_ = acc.Choices[0].Message.Content -``` - -> See the [full streaming and accumulation example](./examples/chat-completion-accumulating/main.go) - -
- -
-Tool calling - -```go -import ( - "encoding/json" - // ... -) - -// ... - -question := "What is the weather in New York City?" - -params := openai.ChatCompletionNewParams{ - Messages: []openai.ChatCompletionMessageParamUnion{ - openai.UserMessage(question), - }, - Tools: []openai.ChatCompletionToolParam{ - { - Function: openai.FunctionDefinitionParam{ - Name: "get_weather", - Description: openai.String("Get weather at the given location"), - Parameters: openai.FunctionParameters{ - "type": "object", - "properties": map[string]interface{}{ - "location": map[string]string{ - "type": "string", - }, - }, - "required": []string{"location"}, - }, - }, - }, - }, - Model: openai.ChatModelGPT4o, -} - -// If there is a was a function call, continue the conversation -params.Messages = append(params.Messages, completion.Choices[0].Message.ToParam()) -for _, toolCall := range toolCalls { - if toolCall.Function.Name == "get_weather" { - // Extract the location from the function call arguments - var args map[string]interface{} - err := json.Unmarshal([]byte(toolCall.Function.Arguments), &args) - if err != nil { - panic(err) - } - location := args["location"].(string) - - // Simulate getting weather data - weatherData := getWeather(location) - - // Print the weather data - fmt.Printf("Weather in %s: %s\n", location, weatherData) - - params.Messages = append(params.Messages, openai.ToolMessage(weatherData, toolCall.ID)) - } -} - -// ... continue the conversation with the information provided by the tool -``` - -> See the [full tool calling example](./examples/chat-completion-tool-calling/main.go) - -
- -
-Structured outputs - -```go -import ( - "encoding/json" - "github.com/invopop/jsonschema" - // ... -) - -// A struct that will be converted to a Structured Outputs response schema -type HistoricalComputer struct { - Origin Origin `json:"origin" jsonschema_description:"The origin of the computer"` - Name string `json:"full_name" jsonschema_description:"The name of the device model"` - Legacy string `json:"legacy" jsonschema:"enum=positive,enum=neutral,enum=negative" jsonschema_description:"Its influence on the field of computing"` - NotableFacts []string `json:"notable_facts" jsonschema_description:"A few key facts about the computer"` -} - -type Origin struct { - YearBuilt int64 `json:"year_of_construction" jsonschema_description:"The year it was made"` - Organization string `json:"organization" jsonschema_description:"The organization that was in charge of its development"` -} - -func GenerateSchema[T any]() interface{} { - // Structured Outputs uses a subset of JSON schema - // These flags are necessary to comply with the subset - reflector := jsonschema.Reflector{ - AllowAdditionalProperties: false, - DoNotReference: true, - } - var v T - schema := reflector.Reflect(v) - return schema -} - -// Generate the JSON schema at initialization time -var HistoricalComputerResponseSchema = GenerateSchema[HistoricalComputer]() - -func main() { - - // ... - - question := "What computer ran the first neural network?" - - schemaParam := openai.ResponseFormatJSONSchemaJSONSchemaParam{ - Name: "historical_computer", - Description: openai.String("Notable information about a computer"), - Schema: HistoricalComputerResponseSchema, - Strict: openai.Bool(true), - } - - chat, _ := client.Chat.Completions.New(ctx, openai.ChatCompletionNewParams{ - // ... - ResponseFormat: openai.ChatCompletionNewParamsResponseFormatUnion{ - OfJSONSchema: &openai.ResponseFormatJSONSchemaParam{ - JSONSchema: schemaParam, - }, - }, - // only certain models can perform structured outputs - Model: openai.ChatModelGPT4o2024_08_06, - }) - - // extract into a well-typed struct - var historicalComputer HistoricalComputer - _ = json.Unmarshal([]byte(chat.Choices[0].Message.Content), &historicalComputer) - - historicalComputer.Name - historicalComputer.Origin.YearBuilt - historicalComputer.Origin.Organization - for i, fact := range historicalComputer.NotableFacts { - // ... - } -} -``` - -> See the [full structured outputs example](./examples/structured-outputs/main.go) - -
- - -### Request fields - -The openai library uses the [`omitzero`](https://tip.golang.org/doc/go1.24#encodingjsonpkgencodingjson) -semantics from the Go 1.24+ `encoding/json` release for request fields. - -Required primitive fields (`int64`, `string`, etc.) feature the tag \`json:"...,required"\`. These -fields are always serialized, even their zero values. - -Optional primitive types are wrapped in a `param.Opt[T]`. These fields can be set with the provided constructors, `openai.String(string)`, `openai.Int(int64)`, etc. - -Any `param.Opt[T]`, map, slice, struct or string enum uses the -tag \`json:"...,omitzero"\`. Its zero value is considered omitted. - -The `param.IsOmitted(any)` function can confirm the presence of any `omitzero` field. - -```go -p := openai.ExampleParams{ - ID: "id_xxx", // required property - Name: openai.String("..."), // optional property - - Point: openai.Point{ - X: 0, // required field will serialize as 0 - Y: openai.Int(1), // optional field will serialize as 1 - // ... omitted non-required fields will not be serialized - }, - - Origin: openai.Origin{}, // the zero value of [Origin] is considered omitted -} -``` - -To send `null` instead of a `param.Opt[T]`, use `param.Null[T]()`. -To send `null` instead of a struct `T`, use `param.NullStruct[T]()`. - -```go -p.Name = param.Null[string]() // 'null' instead of string -p.Point = param.NullStruct[Point]() // 'null' instead of struct - -param.IsNull(p.Name) // true -param.IsNull(p.Point) // true -``` - -Request structs contain a `.SetExtraFields(map[string]any)` method which can send non-conforming -fields in the request body. Extra fields overwrite any struct fields with a matching -key. For security reasons, only use `SetExtraFields` with trusted data. - -To send a custom value instead of a struct, use `param.Override[T](value)`. - -```go -// In cases where the API specifies a given type, -// but you want to send something else, use [SetExtraFields]: -p.SetExtraFields(map[string]any{ - "x": 0.01, // send "x" as a float instead of int -}) - -// Send a number instead of an object -custom := param.Override[openai.FooParams](12) -``` - -### Request unions - -Unions are represented as a struct with fields prefixed by "Of" for each of it's variants, -only one field can be non-zero. The non-zero field will be serialized. - -Sub-properties of the union can be accessed via methods on the union struct. -These methods return a mutable pointer to the underlying data, if present. - -```go -// Only one field can be non-zero, use param.IsOmitted() to check if a field is set -type AnimalUnionParam struct { - OfCat *Cat `json:",omitzero,inline` - OfDog *Dog `json:",omitzero,inline` -} - -animal := AnimalUnionParam{ - OfCat: &Cat{ - Name: "Whiskers", - Owner: PersonParam{ - Address: AddressParam{Street: "3333 Coyote Hill Rd", Zip: 0}, - }, - }, -} - -// Mutating a field -if address := animal.GetOwner().GetAddress(); address != nil { - address.ZipCode = 94304 -} -``` - -### Response objects - -All fields in response structs are ordinary value types (not pointers or wrappers). -Response structs also include a special `JSON` field containing metadata about -each property. - -```go -type Animal struct { - Name string `json:"name,nullable"` - Owners int `json:"owners"` - Age int `json:"age"` - JSON struct { - Name respjson.Field - Owner respjson.Field - Age respjson.Field - ExtraFields map[string]respjson.Field - } `json:"-"` -} -``` - -To handle optional data, use the `.Valid()` method on the JSON field. -`.Valid()` returns true if a field is not `null`, not present, or couldn't be marshaled. - -If `.Valid()` is false, the corresponding field will simply be its zero value. - -```go -raw := `{"owners": 1, "name": null}` - -var res Animal -json.Unmarshal([]byte(raw), &res) - -// Accessing regular fields - -res.Owners // 1 -res.Name // "" -res.Age // 0 - -// Optional field checks - -res.JSON.Owners.Valid() // true -res.JSON.Name.Valid() // false -res.JSON.Age.Valid() // false - -// Raw JSON values - -res.JSON.Owners.Raw() // "1" -res.JSON.Name.Raw() == "null" // true -res.JSON.Name.Raw() == respjson.Null // true -res.JSON.Age.Raw() == "" // true -res.JSON.Age.Raw() == respjson.Omitted // true -``` - -These `.JSON` structs also include an `ExtraFields` map containing -any properties in the json response that were not specified -in the struct. This can be useful for API features not yet -present in the SDK. - -```go -body := res.JSON.ExtraFields["my_unexpected_field"].Raw() -``` - -### Response Unions - -In responses, unions are represented by a flattened struct containing all possible fields from each of the -object variants. -To convert it to a variant use the `.AsFooVariant()` method or the `.AsAny()` method if present. - -If a response value union contains primitive values, primitive fields will be alongside -the properties but prefixed with `Of` and feature the tag `json:"...,inline"`. - -```go -type AnimalUnion struct { - // From variants [Dog], [Cat] - Owner Person `json:"owner"` - // From variant [Dog] - DogBreed string `json:"dog_breed"` - // From variant [Cat] - CatBreed string `json:"cat_breed"` - // ... - - JSON struct { - Owner respjson.Field - // ... - } `json:"-"` -} - -// If animal variant -if animal.Owner.Address.ZipCode == "" { - panic("missing zip code") -} - -// Switch on the variant -switch variant := animal.AsAny().(type) { -case Dog: -case Cat: -default: - panic("unexpected type") -} -``` - -### RequestOptions - -This library uses the functional options pattern. Functions defined in the -`option` package return a `RequestOption`, which is a closure that mutates a -`RequestConfig`. These options can be supplied to the client or at individual -requests. For example: - -```go -client := openai.NewClient( - // Adds a header to every request made by the client - option.WithHeader("X-Some-Header", "custom_header_info"), -) - -client.Chat.Completions.New(context.TODO(), ..., - // Override the header - option.WithHeader("X-Some-Header", "some_other_custom_header_info"), - // Add an undocumented field to the request body, using sjson syntax - option.WithJSONSet("some.json.path", map[string]string{"my": "object"}), -) -``` - -The request option `option.WithDebugLog(nil)` may be helpful while debugging. - -See the [full list of request options](https://pkg.go.dev/github.com/openai/openai-go/option). - -### Pagination - -This library provides some conveniences for working with paginated list endpoints. - -You can use `.ListAutoPaging()` methods to iterate through items across all pages: - -```go -iter := client.FineTuning.Jobs.ListAutoPaging(context.TODO(), openai.FineTuningJobListParams{ - Limit: openai.Int(20), -}) -// Automatically fetches more pages as needed. -for iter.Next() { - fineTuningJob := iter.Current() - fmt.Printf("%+v\n", fineTuningJob) -} -if err := iter.Err(); err != nil { - panic(err.Error()) -} -``` - -Or you can use simple `.List()` methods to fetch a single page and receive a standard response object -with additional helper methods like `.GetNextPage()`, e.g.: - -```go -page, err := client.FineTuning.Jobs.List(context.TODO(), openai.FineTuningJobListParams{ - Limit: openai.Int(20), -}) -for page != nil { - for _, job := range page.Data { - fmt.Printf("%+v\n", job) - } - page, err = page.GetNextPage() -} -if err != nil { - panic(err.Error()) -} -``` - -### Errors - -When the API returns a non-success status code, we return an error with type -`*openai.Error`. This contains the `StatusCode`, `*http.Request`, and -`*http.Response` values of the request, as well as the JSON of the error body -(much like other response objects in the SDK). - -To handle errors, we recommend that you use the `errors.As` pattern: - -```go -_, err := client.FineTuning.Jobs.New(context.TODO(), openai.FineTuningJobNewParams{ - Model: openai.FineTuningJobNewParamsModelBabbage002, - TrainingFile: "file-abc123", -}) -if err != nil { - var apierr *openai.Error - if errors.As(err, &apierr) { - println(string(apierr.DumpRequest(true))) // Prints the serialized HTTP request - println(string(apierr.DumpResponse(true))) // Prints the serialized HTTP response - } - panic(err.Error()) // GET "/fine_tuning/jobs": 400 Bad Request { ... } -} -``` - -When other errors occur, they are returned unwrapped; for example, -if HTTP transport fails, you might receive `*url.Error` wrapping `*net.OpError`. - -### Timeouts - -Requests do not time out by default; use context to configure a timeout for a request lifecycle. - -Note that if a request is [retried](#retries), the context timeout does not start over. -To set a per-retry timeout, use `option.WithRequestTimeout()`. - -```go -// This sets the timeout for the request, including all the retries. -ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) -defer cancel() -client.Chat.Completions.New( - ctx, - openai.ChatCompletionNewParams{ - Messages: []openai.ChatCompletionMessageParamUnion{{ - OfUser: &openai.ChatCompletionUserMessageParam{ - Content: openai.ChatCompletionUserMessageParamContentUnion{ - OfString: openai.String("How can I list all files in a directory using Python?"), - }, - }, - }}, - Model: shared.ChatModelGPT4_1, - }, - // This sets the per-retry timeout - option.WithRequestTimeout(20*time.Second), -) -``` - -### File uploads - -Request parameters that correspond to file uploads in multipart requests are typed as -`io.Reader`. The contents of the `io.Reader` will by default be sent as a multipart form -part with the file name of "anonymous_file" and content-type of "application/octet-stream". - -The file name and content-type can be customized by implementing `Name() string` or `ContentType() -string` on the run-time type of `io.Reader`. Note that `os.File` implements `Name() string`, so a -file returned by `os.Open` will be sent with the file name on disk. - -We also provide a helper `openai.File(reader io.Reader, filename string, contentType string)` -which can be used to wrap any `io.Reader` with the appropriate file name and content type. - -```go -// A file from the file system -file, err := os.Open("input.jsonl") -openai.FileNewParams{ - File: file, - Purpose: openai.FilePurposeFineTune, -} - -// A file from a string -openai.FileNewParams{ - File: strings.NewReader("my file contents"), - Purpose: openai.FilePurposeFineTune, -} - -// With a custom filename and contentType -openai.FileNewParams{ - File: openai.File(strings.NewReader(`{"hello": "foo"}`), "file.go", "application/json"), - Purpose: openai.FilePurposeFineTune, -} -``` - -## Webhook Verification - -Verifying webhook signatures is _optional but encouraged_. - -For more information about webhooks, see [the API docs](https://platform.openai.com/docs/guides/webhooks). - -### Parsing webhook payloads - -For most use cases, you will likely want to verify the webhook and parse the payload at the same time. To achieve this, we provide the method `client.Webhooks.Unwrap()`, which parses a webhook request and verifies that it was sent by OpenAI. This method will return an error if the signature is invalid. - -Note that the `body` parameter should be the raw JSON bytes sent from the server (do not parse it first). The `Unwrap()` method will parse this JSON for you into an event object after verifying the webhook was sent from OpenAI. - -```go -package main - -import ( - "io" - "log" - "net/http" - "os" - - "github.com/gin-gonic/gin" - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/webhooks" -) - -func main() { - client := openai.NewClient( - option.WithWebhookSecret(os.Getenv("OPENAI_WEBHOOK_SECRET")), // env var used by default; explicit here. - ) - - r := gin.Default() - - r.POST("/webhook", func(c *gin.Context) { - body, err := io.ReadAll(c.Request.Body) - if err != nil { - c.JSON(http.StatusInternalServerError, gin.H{"error": "Error reading request body"}) - return - } - defer c.Request.Body.Close() - - webhookEvent, err := client.Webhooks.Unwrap(body, c.Request.Header) - if err != nil { - log.Printf("Invalid webhook signature: %v", err) - c.JSON(http.StatusBadRequest, gin.H{"error": "invalid signature"}) - return - } - - switch event := webhookEvent.AsAny().(type) { - case webhooks.ResponseCompletedWebhookEvent: - log.Printf("Response completed: %+v", event.Data) - case webhooks.ResponseFailedWebhookEvent: - log.Printf("Response failed: %+v", event.Data) - default: - log.Printf("Unhandled event type: %T", event) - } - - c.JSON(http.StatusOK, gin.H{"message": "ok"}) - }) - - r.Run(":8000") -} -``` - -### Verifying webhook payloads directly - -In some cases, you may want to verify the webhook separately from parsing the payload. If you prefer to handle these steps separately, we provide the method `client.Webhooks.VerifySignature()` to _only verify_ the signature of a webhook request. Like `Unwrap()`, this method will return an error if the signature is invalid. - -Note that the `body` parameter should be the raw JSON bytes sent from the server (do not parse it first). You will then need to parse the body after verifying the signature. - -```go -package main - -import ( - "encoding/json" - "io" - "log" - "net/http" - "os" - - "github.com/gin-gonic/gin" - "github.com/openai/openai-go" - "github.com/openai/openai-go/option" -) - -func main() { - client := openai.NewClient( - option.WithWebhookSecret(os.Getenv("OPENAI_WEBHOOK_SECRET")), // env var used by default; explicit here. - ) - - r := gin.Default() - - r.POST("/webhook", func(c *gin.Context) { - body, err := io.ReadAll(c.Request.Body) - if err != nil { - c.JSON(http.StatusInternalServerError, gin.H{"error": "Error reading request body"}) - return - } - defer c.Request.Body.Close() - - err = client.Webhooks.VerifySignature(body, c.Request.Header) - if err != nil { - log.Printf("Invalid webhook signature: %v", err) - c.JSON(http.StatusBadRequest, gin.H{"error": "invalid signature"}) - return - } - - c.JSON(http.StatusOK, gin.H{"message": "ok"}) - }) - - r.Run(":8000") -} -``` - -### Retries - -Certain errors will be automatically retried 2 times by default, with a short exponential backoff. -We retry by default all connection errors, 408 Request Timeout, 409 Conflict, 429 Rate Limit, -and >=500 Internal errors. - -You can use the `WithMaxRetries` option to configure or disable this: - -```go -// Configure the default for all requests: -client := openai.NewClient( - option.WithMaxRetries(0), // default is 2 -) - -// Override per-request: -client.Chat.Completions.New( - context.TODO(), - openai.ChatCompletionNewParams{ - Messages: []openai.ChatCompletionMessageParamUnion{{ - OfUser: &openai.ChatCompletionUserMessageParam{ - Content: openai.ChatCompletionUserMessageParamContentUnion{ - OfString: openai.String("How can I get the name of the current day in JavaScript?"), - }, - }, - }}, - Model: shared.ChatModelGPT4_1, - }, - option.WithMaxRetries(5), -) -``` - -### Accessing raw response data (e.g. response headers) - -You can access the raw HTTP response data by using the `option.WithResponseInto()` request option. This is useful when -you need to examine response headers, status codes, or other details. - -```go -// Create a variable to store the HTTP response -var response *http.Response -chatCompletion, err := client.Chat.Completions.New( - context.TODO(), - openai.ChatCompletionNewParams{ - Messages: []openai.ChatCompletionMessageParamUnion{{ - OfUser: &openai.ChatCompletionUserMessageParam{ - Content: openai.ChatCompletionUserMessageParamContentUnion{ - OfString: openai.String("Say this is a test"), - }, - }, - }}, - Model: shared.ChatModelGPT4_1, - }, - option.WithResponseInto(&response), -) -if err != nil { - // handle error -} -fmt.Printf("%+v\n", chatCompletion) - -fmt.Printf("Status Code: %d\n", response.StatusCode) -fmt.Printf("Headers: %+#v\n", response.Header) -``` - -### Making custom/undocumented requests - -This library is typed for convenient access to the documented API. If you need to access undocumented -endpoints, params, or response properties, the library can still be used. - -#### Undocumented endpoints - -To make requests to undocumented endpoints, you can use `client.Get`, `client.Post`, and other HTTP verbs. -`RequestOptions` on the client, such as retries, will be respected when making these requests. - -```go -var ( - // params can be an io.Reader, a []byte, an encoding/json serializable object, - // or a "…Params" struct defined in this library. - params map[string]any - - // result can be an []byte, *http.Response, a encoding/json deserializable object, - // or a model defined in this library. - result *http.Response -) -err := client.Post(context.Background(), "/unspecified", params, &result) -if err != nil { - … -} -``` - -#### Undocumented request params - -To make requests using undocumented parameters, you may use either the `option.WithQuerySet()` -or the `option.WithJSONSet()` methods. - -```go -params := FooNewParams{ - ID: "id_xxxx", - Data: FooNewParamsData{ - FirstName: openai.String("John"), - }, -} -client.Foo.New(context.Background(), params, option.WithJSONSet("data.last_name", "Doe")) -``` - -#### Undocumented response properties - -To access undocumented response properties, you may either access the raw JSON of the response as a string -with `result.JSON.RawJSON()`, or get the raw JSON of a particular field on the result with -`result.JSON.Foo.Raw()`. - -Any fields that are not present on the response struct will be saved and can be accessed by `result.JSON.ExtraFields()` which returns the extra fields as a `map[string]Field`. - -### Middleware - -We provide `option.WithMiddleware` which applies the given -middleware to requests. - -```go -func Logger(req *http.Request, next option.MiddlewareNext) (res *http.Response, err error) { - // Before the request - start := time.Now() - LogReq(req) - - // Forward the request to the next handler - res, err = next(req) - - // Handle stuff after the request - end := time.Now() - LogRes(res, err, start - end) - - return res, err -} - -client := openai.NewClient( - option.WithMiddleware(Logger), -) -``` - -When multiple middlewares are provided as variadic arguments, the middlewares -are applied left to right. If `option.WithMiddleware` is given -multiple times, for example first in the client then the method, the -middleware in the client will run first and the middleware given in the method -will run next. - -You may also replace the default `http.Client` with -`option.WithHTTPClient(client)`. Only one http client is -accepted (this overwrites any previous client) and receives requests after any -middleware has been applied. - -## Microsoft Azure OpenAI - -To use this library with [Azure OpenAI]https://learn.microsoft.com/azure/ai-services/openai/overview), -use the option.RequestOption functions in the `azure` package. - -```go -package main - -import ( - "github.com/Azure/azure-sdk-for-go/sdk/azidentity" - "github.com/openai/openai-go" - "github.com/openai/openai-go/azure" -) - -func main() { - const azureOpenAIEndpoint = "https://.openai.azure.com" - - // The latest API versions, including previews, can be found here: - // ttps://learn.microsoft.com/en-us/azure/ai-services/openai/reference#rest-api-versionng - const azureOpenAIAPIVersion = "2024-06-01" - - tokenCredential, err := azidentity.NewDefaultAzureCredential(nil) - - if err != nil { - fmt.Printf("Failed to create the DefaultAzureCredential: %s", err) - os.Exit(1) - } - - client := openai.NewClient( - azure.WithEndpoint(azureOpenAIEndpoint, azureOpenAIAPIVersion), - - // Choose between authenticating using a TokenCredential or an API Key - azure.WithTokenCredential(tokenCredential), - // or azure.WithAPIKey(azureOpenAIAPIKey), - ) -} -``` - - -## Semantic versioning - -This package generally follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions, though certain backwards-incompatible changes may be released as minor versions: - -1. Changes to library internals which are technically public but not intended or documented for external use. _(Please open a GitHub issue to let us know if you are relying on such internals.)_ -2. Changes that we do not expect to impact the vast majority of users in practice. - -We take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience. - -We are keen for your feedback; please open an [issue](https://www.github.com/openai/openai-go/issues) with questions, bugs, or suggestions. - -## Contributing - -See [the contributing documentation](./CONTRIBUTING.md). diff --git a/vendor/github.com/openai/openai-go/SECURITY.md b/vendor/github.com/openai/openai-go/SECURITY.md deleted file mode 100644 index 4adb0c54..00000000 --- a/vendor/github.com/openai/openai-go/SECURITY.md +++ /dev/null @@ -1,29 +0,0 @@ -# Security Policy - -## Reporting Security Issues - -This SDK is generated by [Stainless Software Inc](http://stainless.com). Stainless takes security seriously, and encourages you to report any security vulnerability promptly so that appropriate action can be taken. - -To report a security issue, please contact the Stainless team at security@stainless.com. - -## Responsible Disclosure - -We appreciate the efforts of security researchers and individuals who help us maintain the security of -SDKs we generate. If you believe you have found a security vulnerability, please adhere to responsible -disclosure practices by allowing us a reasonable amount of time to investigate and address the issue -before making any information public. - -## Reporting Non-SDK Related Security Issues - -If you encounter security issues that are not directly related to SDKs but pertain to the services -or products provided by OpenAI, please follow the respective company's security reporting guidelines. - -### OpenAI Terms and Policies - -Our Security Policy can be found at [Security Policy URL](https://openai.com/policies/coordinated-vulnerability-disclosure-policy). - -Please contact disclosure@openai.com for any questions or concerns regarding the security of our services. - ---- - -Thank you for helping us keep the SDKs and systems they interact with secure. diff --git a/vendor/github.com/openai/openai-go/aliases.go b/vendor/github.com/openai/openai-go/aliases.go deleted file mode 100644 index 73b6c0cc..00000000 --- a/vendor/github.com/openai/openai-go/aliases.go +++ /dev/null @@ -1,440 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -package openai - -import ( - "github.com/openai/openai-go/internal/apierror" - "github.com/openai/openai-go/packages/param" - "github.com/openai/openai-go/shared" -) - -// aliased to make [param.APIUnion] private when embedding -type paramUnion = param.APIUnion - -// aliased to make [param.APIObject] private when embedding -type paramObj = param.APIObject - -type Error = apierror.Error - -// This is an alias to an internal type. -type ChatModel = shared.ChatModel - -// Equals "gpt-4.1" -const ChatModelGPT4_1 = shared.ChatModelGPT4_1 - -// Equals "gpt-4.1-mini" -const ChatModelGPT4_1Mini = shared.ChatModelGPT4_1Mini - -// Equals "gpt-4.1-nano" -const ChatModelGPT4_1Nano = shared.ChatModelGPT4_1Nano - -// Equals "gpt-4.1-2025-04-14" -const ChatModelGPT4_1_2025_04_14 = shared.ChatModelGPT4_1_2025_04_14 - -// Equals "gpt-4.1-mini-2025-04-14" -const ChatModelGPT4_1Mini2025_04_14 = shared.ChatModelGPT4_1Mini2025_04_14 - -// Equals "gpt-4.1-nano-2025-04-14" -const ChatModelGPT4_1Nano2025_04_14 = shared.ChatModelGPT4_1Nano2025_04_14 - -// Equals "o4-mini" -const ChatModelO4Mini = shared.ChatModelO4Mini - -// Equals "o4-mini-2025-04-16" -const ChatModelO4Mini2025_04_16 = shared.ChatModelO4Mini2025_04_16 - -// Equals "o3" -const ChatModelO3 = shared.ChatModelO3 - -// Equals "o3-2025-04-16" -const ChatModelO3_2025_04_16 = shared.ChatModelO3_2025_04_16 - -// Equals "o3-mini" -const ChatModelO3Mini = shared.ChatModelO3Mini - -// Equals "o3-mini-2025-01-31" -const ChatModelO3Mini2025_01_31 = shared.ChatModelO3Mini2025_01_31 - -// Equals "o1" -const ChatModelO1 = shared.ChatModelO1 - -// Equals "o1-2024-12-17" -const ChatModelO1_2024_12_17 = shared.ChatModelO1_2024_12_17 - -// Equals "o1-preview" -const ChatModelO1Preview = shared.ChatModelO1Preview - -// Equals "o1-preview-2024-09-12" -const ChatModelO1Preview2024_09_12 = shared.ChatModelO1Preview2024_09_12 - -// Equals "o1-mini" -const ChatModelO1Mini = shared.ChatModelO1Mini - -// Equals "o1-mini-2024-09-12" -const ChatModelO1Mini2024_09_12 = shared.ChatModelO1Mini2024_09_12 - -// Equals "gpt-4o" -const ChatModelGPT4o = shared.ChatModelGPT4o - -// Equals "gpt-4o-2024-11-20" -const ChatModelGPT4o2024_11_20 = shared.ChatModelGPT4o2024_11_20 - -// Equals "gpt-4o-2024-08-06" -const ChatModelGPT4o2024_08_06 = shared.ChatModelGPT4o2024_08_06 - -// Equals "gpt-4o-2024-05-13" -const ChatModelGPT4o2024_05_13 = shared.ChatModelGPT4o2024_05_13 - -// Equals "gpt-4o-audio-preview" -const ChatModelGPT4oAudioPreview = shared.ChatModelGPT4oAudioPreview - -// Equals "gpt-4o-audio-preview-2024-10-01" -const ChatModelGPT4oAudioPreview2024_10_01 = shared.ChatModelGPT4oAudioPreview2024_10_01 - -// Equals "gpt-4o-audio-preview-2024-12-17" -const ChatModelGPT4oAudioPreview2024_12_17 = shared.ChatModelGPT4oAudioPreview2024_12_17 - -// Equals "gpt-4o-audio-preview-2025-06-03" -const ChatModelGPT4oAudioPreview2025_06_03 = shared.ChatModelGPT4oAudioPreview2025_06_03 - -// Equals "gpt-4o-mini-audio-preview" -const ChatModelGPT4oMiniAudioPreview = shared.ChatModelGPT4oMiniAudioPreview - -// Equals "gpt-4o-mini-audio-preview-2024-12-17" -const ChatModelGPT4oMiniAudioPreview2024_12_17 = shared.ChatModelGPT4oMiniAudioPreview2024_12_17 - -// Equals "gpt-4o-search-preview" -const ChatModelGPT4oSearchPreview = shared.ChatModelGPT4oSearchPreview - -// Equals "gpt-4o-mini-search-preview" -const ChatModelGPT4oMiniSearchPreview = shared.ChatModelGPT4oMiniSearchPreview - -// Equals "gpt-4o-search-preview-2025-03-11" -const ChatModelGPT4oSearchPreview2025_03_11 = shared.ChatModelGPT4oSearchPreview2025_03_11 - -// Equals "gpt-4o-mini-search-preview-2025-03-11" -const ChatModelGPT4oMiniSearchPreview2025_03_11 = shared.ChatModelGPT4oMiniSearchPreview2025_03_11 - -// Equals "chatgpt-4o-latest" -const ChatModelChatgpt4oLatest = shared.ChatModelChatgpt4oLatest - -// Equals "codex-mini-latest" -const ChatModelCodexMiniLatest = shared.ChatModelCodexMiniLatest - -// Equals "gpt-4o-mini" -const ChatModelGPT4oMini = shared.ChatModelGPT4oMini - -// Equals "gpt-4o-mini-2024-07-18" -const ChatModelGPT4oMini2024_07_18 = shared.ChatModelGPT4oMini2024_07_18 - -// Equals "gpt-4-turbo" -const ChatModelGPT4Turbo = shared.ChatModelGPT4Turbo - -// Equals "gpt-4-turbo-2024-04-09" -const ChatModelGPT4Turbo2024_04_09 = shared.ChatModelGPT4Turbo2024_04_09 - -// Equals "gpt-4-0125-preview" -const ChatModelGPT4_0125Preview = shared.ChatModelGPT4_0125Preview - -// Equals "gpt-4-turbo-preview" -const ChatModelGPT4TurboPreview = shared.ChatModelGPT4TurboPreview - -// Equals "gpt-4-1106-preview" -const ChatModelGPT4_1106Preview = shared.ChatModelGPT4_1106Preview - -// Equals "gpt-4-vision-preview" -const ChatModelGPT4VisionPreview = shared.ChatModelGPT4VisionPreview - -// Equals "gpt-4" -const ChatModelGPT4 = shared.ChatModelGPT4 - -// Equals "gpt-4-0314" -const ChatModelGPT4_0314 = shared.ChatModelGPT4_0314 - -// Equals "gpt-4-0613" -const ChatModelGPT4_0613 = shared.ChatModelGPT4_0613 - -// Equals "gpt-4-32k" -const ChatModelGPT4_32k = shared.ChatModelGPT4_32k - -// Equals "gpt-4-32k-0314" -const ChatModelGPT4_32k0314 = shared.ChatModelGPT4_32k0314 - -// Equals "gpt-4-32k-0613" -const ChatModelGPT4_32k0613 = shared.ChatModelGPT4_32k0613 - -// Equals "gpt-3.5-turbo" -const ChatModelGPT3_5Turbo = shared.ChatModelGPT3_5Turbo - -// Equals "gpt-3.5-turbo-16k" -const ChatModelGPT3_5Turbo16k = shared.ChatModelGPT3_5Turbo16k - -// Equals "gpt-3.5-turbo-0301" -const ChatModelGPT3_5Turbo0301 = shared.ChatModelGPT3_5Turbo0301 - -// Equals "gpt-3.5-turbo-0613" -const ChatModelGPT3_5Turbo0613 = shared.ChatModelGPT3_5Turbo0613 - -// Equals "gpt-3.5-turbo-1106" -const ChatModelGPT3_5Turbo1106 = shared.ChatModelGPT3_5Turbo1106 - -// Equals "gpt-3.5-turbo-0125" -const ChatModelGPT3_5Turbo0125 = shared.ChatModelGPT3_5Turbo0125 - -// Equals "gpt-3.5-turbo-16k-0613" -const ChatModelGPT3_5Turbo16k0613 = shared.ChatModelGPT3_5Turbo16k0613 - -// A filter used to compare a specified attribute key to a given value using a -// defined comparison operation. -// -// This is an alias to an internal type. -type ComparisonFilter = shared.ComparisonFilter - -// Specifies the comparison operator: `eq`, `ne`, `gt`, `gte`, `lt`, `lte`. -// -// - `eq`: equals -// - `ne`: not equal -// - `gt`: greater than -// - `gte`: greater than or equal -// - `lt`: less than -// - `lte`: less than or equal -// -// This is an alias to an internal type. -type ComparisonFilterType = shared.ComparisonFilterType - -// Equals "eq" -const ComparisonFilterTypeEq = shared.ComparisonFilterTypeEq - -// Equals "ne" -const ComparisonFilterTypeNe = shared.ComparisonFilterTypeNe - -// Equals "gt" -const ComparisonFilterTypeGt = shared.ComparisonFilterTypeGt - -// Equals "gte" -const ComparisonFilterTypeGte = shared.ComparisonFilterTypeGte - -// Equals "lt" -const ComparisonFilterTypeLt = shared.ComparisonFilterTypeLt - -// Equals "lte" -const ComparisonFilterTypeLte = shared.ComparisonFilterTypeLte - -// The value to compare against the attribute key; supports string, number, or -// boolean types. -// -// This is an alias to an internal type. -type ComparisonFilterValueUnion = shared.ComparisonFilterValueUnion - -// A filter used to compare a specified attribute key to a given value using a -// defined comparison operation. -// -// This is an alias to an internal type. -type ComparisonFilterParam = shared.ComparisonFilterParam - -// The value to compare against the attribute key; supports string, number, or -// boolean types. -// -// This is an alias to an internal type. -type ComparisonFilterValueUnionParam = shared.ComparisonFilterValueUnionParam - -// Combine multiple filters using `and` or `or`. -// -// This is an alias to an internal type. -type CompoundFilter = shared.CompoundFilter - -// Type of operation: `and` or `or`. -// -// This is an alias to an internal type. -type CompoundFilterType = shared.CompoundFilterType - -// Equals "and" -const CompoundFilterTypeAnd = shared.CompoundFilterTypeAnd - -// Equals "or" -const CompoundFilterTypeOr = shared.CompoundFilterTypeOr - -// Combine multiple filters using `and` or `or`. -// -// This is an alias to an internal type. -type CompoundFilterParam = shared.CompoundFilterParam - -// This is an alias to an internal type. -type ErrorObject = shared.ErrorObject - -// This is an alias to an internal type. -type FunctionDefinition = shared.FunctionDefinition - -// This is an alias to an internal type. -type FunctionDefinitionParam = shared.FunctionDefinitionParam - -// The parameters the functions accepts, described as a JSON Schema object. See the -// [guide](https://platform.openai.com/docs/guides/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. -// -// This is an alias to an internal type. -type FunctionParameters = shared.FunctionParameters - -// 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, and -// querying for objects via API or the dashboard. -// -// Keys are strings with a maximum length of 64 characters. Values are strings with -// a maximum length of 512 characters. -// -// This is an alias to an internal type. -type Metadata = shared.Metadata - -// **o-series models only** -// -// Configuration options for -// [reasoning models](https://platform.openai.com/docs/guides/reasoning). -// -// This is an alias to an internal type. -type Reasoning = shared.Reasoning - -// **Deprecated:** use `summary` instead. -// -// A summary of the reasoning performed by the model. This can be useful for -// debugging and understanding the model's reasoning process. One of `auto`, -// `concise`, or `detailed`. -// -// This is an alias to an internal type. -type ReasoningGenerateSummary = shared.ReasoningGenerateSummary - -// Equals "auto" -const ReasoningGenerateSummaryAuto = shared.ReasoningGenerateSummaryAuto - -// Equals "concise" -const ReasoningGenerateSummaryConcise = shared.ReasoningGenerateSummaryConcise - -// Equals "detailed" -const ReasoningGenerateSummaryDetailed = shared.ReasoningGenerateSummaryDetailed - -// A summary of the reasoning performed by the model. This can be useful for -// debugging and understanding the model's reasoning process. One of `auto`, -// `concise`, or `detailed`. -// -// This is an alias to an internal type. -type ReasoningSummary = shared.ReasoningSummary - -// Equals "auto" -const ReasoningSummaryAuto = shared.ReasoningSummaryAuto - -// Equals "concise" -const ReasoningSummaryConcise = shared.ReasoningSummaryConcise - -// Equals "detailed" -const ReasoningSummaryDetailed = shared.ReasoningSummaryDetailed - -// **o-series models only** -// -// Configuration options for -// [reasoning models](https://platform.openai.com/docs/guides/reasoning). -// -// This is an alias to an internal type. -type ReasoningParam = shared.ReasoningParam - -// **o-series models only** -// -// Constrains effort on reasoning for -// [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently -// supported values are `low`, `medium`, and `high`. Reducing reasoning effort can -// result in faster responses and fewer tokens used on reasoning in a response. -// -// This is an alias to an internal type. -type ReasoningEffort = shared.ReasoningEffort - -// Equals "low" -const ReasoningEffortLow = shared.ReasoningEffortLow - -// Equals "medium" -const ReasoningEffortMedium = shared.ReasoningEffortMedium - -// Equals "high" -const ReasoningEffortHigh = shared.ReasoningEffortHigh - -// JSON object response format. An older method of generating JSON responses. Using -// `json_schema` is recommended for models that support it. Note that the model -// will not generate JSON without a system or user message instructing it to do so. -// -// This is an alias to an internal type. -type ResponseFormatJSONObject = shared.ResponseFormatJSONObject - -// JSON object response format. An older method of generating JSON responses. Using -// `json_schema` is recommended for models that support it. Note that the model -// will not generate JSON without a system or user message instructing it to do so. -// -// This is an alias to an internal type. -type ResponseFormatJSONObjectParam = shared.ResponseFormatJSONObjectParam - -// JSON Schema response format. Used to generate structured JSON responses. Learn -// more about -// [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs). -// -// This is an alias to an internal type. -type ResponseFormatJSONSchema = shared.ResponseFormatJSONSchema - -// Structured Outputs configuration options, including a JSON Schema. -// -// This is an alias to an internal type. -type ResponseFormatJSONSchemaJSONSchema = shared.ResponseFormatJSONSchemaJSONSchema - -// JSON Schema response format. Used to generate structured JSON responses. Learn -// more about -// [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs). -// -// This is an alias to an internal type. -type ResponseFormatJSONSchemaParam = shared.ResponseFormatJSONSchemaParam - -// Structured Outputs configuration options, including a JSON Schema. -// -// This is an alias to an internal type. -type ResponseFormatJSONSchemaJSONSchemaParam = shared.ResponseFormatJSONSchemaJSONSchemaParam - -// Default response format. Used to generate text responses. -// -// This is an alias to an internal type. -type ResponseFormatText = shared.ResponseFormatText - -// Default response format. Used to generate text responses. -// -// This is an alias to an internal type. -type ResponseFormatTextParam = shared.ResponseFormatTextParam - -// This is an alias to an internal type. -type ResponsesModel = shared.ResponsesModel - -// Equals "o1-pro" -const ResponsesModelO1Pro = shared.ResponsesModelO1Pro - -// Equals "o1-pro-2025-03-19" -const ResponsesModelO1Pro2025_03_19 = shared.ResponsesModelO1Pro2025_03_19 - -// Equals "o3-pro" -const ResponsesModelO3Pro = shared.ResponsesModelO3Pro - -// Equals "o3-pro-2025-06-10" -const ResponsesModelO3Pro2025_06_10 = shared.ResponsesModelO3Pro2025_06_10 - -// Equals "o3-deep-research" -const ResponsesModelO3DeepResearch = shared.ResponsesModelO3DeepResearch - -// Equals "o3-deep-research-2025-06-26" -const ResponsesModelO3DeepResearch2025_06_26 = shared.ResponsesModelO3DeepResearch2025_06_26 - -// Equals "o4-mini-deep-research" -const ResponsesModelO4MiniDeepResearch = shared.ResponsesModelO4MiniDeepResearch - -// Equals "o4-mini-deep-research-2025-06-26" -const ResponsesModelO4MiniDeepResearch2025_06_26 = shared.ResponsesModelO4MiniDeepResearch2025_06_26 - -// Equals "computer-use-preview" -const ResponsesModelComputerUsePreview = shared.ResponsesModelComputerUsePreview - -// Equals "computer-use-preview-2025-03-11" -const ResponsesModelComputerUsePreview2025_03_11 = shared.ResponsesModelComputerUsePreview2025_03_11 diff --git a/vendor/github.com/openai/openai-go/api.md b/vendor/github.com/openai/openai-go/api.md deleted file mode 100644 index 841a0891..00000000 --- a/vendor/github.com/openai/openai-go/api.md +++ /dev/null @@ -1,791 +0,0 @@ -# Shared Params Types - -- shared.ChatModel -- shared.ComparisonFilterParam -- shared.CompoundFilterParam -- shared.FunctionDefinitionParam -- shared.FunctionParameters -- shared.Metadata -- shared.ReasoningParam -- shared.ReasoningEffort -- shared.ResponseFormatJSONObjectParam -- shared.ResponseFormatJSONSchemaParam -- shared.ResponseFormatTextParam -- shared.ResponsesModel - -# Shared Response Types - -- shared.ChatModel -- shared.ComparisonFilter -- shared.CompoundFilter -- shared.ErrorObject -- shared.FunctionDefinition -- shared.FunctionParameters -- shared.Metadata -- shared.Reasoning -- shared.ReasoningEffort -- shared.ResponseFormatJSONObject -- shared.ResponseFormatJSONSchema -- shared.ResponseFormatText -- shared.ResponsesModel - -# Completions - -Response Types: - -- openai.Completion -- openai.CompletionChoice -- openai.CompletionUsage - -Methods: - -- client.Completions.New(ctx context.Context, body openai.CompletionNewParams) (openai.Completion, error) - -# Chat - -## Completions - -Params Types: - -- openai.ChatCompletionAssistantMessageParam -- openai.ChatCompletionAudioParam -- openai.ChatCompletionContentPartUnionParam -- openai.ChatCompletionContentPartImageParam -- openai.ChatCompletionContentPartInputAudioParam -- openai.ChatCompletionContentPartRefusalParam -- openai.ChatCompletionContentPartTextParam -- openai.ChatCompletionDeveloperMessageParam -- openai.ChatCompletionFunctionCallOptionParam -- openai.ChatCompletionFunctionMessageParam -- openai.ChatCompletionMessageParamUnion -- openai.ChatCompletionMessageToolCallParam -- openai.ChatCompletionNamedToolChoiceParam -- openai.ChatCompletionPredictionContentParam -- openai.ChatCompletionStreamOptionsParam -- openai.ChatCompletionSystemMessageParam -- openai.ChatCompletionToolParam -- openai.ChatCompletionToolChoiceOptionUnionParam -- openai.ChatCompletionToolMessageParam -- openai.ChatCompletionUserMessageParam - -Response Types: - -- openai.ChatCompletion -- openai.ChatCompletionAudio -- openai.ChatCompletionChunk -- openai.ChatCompletionContentPartImage -- openai.ChatCompletionContentPartText -- openai.ChatCompletionDeleted -- openai.ChatCompletionMessage -- openai.ChatCompletionMessageToolCall -- openai.ChatCompletionStoreMessage -- openai.ChatCompletionTokenLogprob - -Methods: - -- client.Chat.Completions.New(ctx context.Context, body openai.ChatCompletionNewParams) (openai.ChatCompletion, error) -- client.Chat.Completions.Get(ctx context.Context, completionID string) (openai.ChatCompletion, error) -- client.Chat.Completions.Update(ctx context.Context, completionID string, body openai.ChatCompletionUpdateParams) (openai.ChatCompletion, error) -- client.Chat.Completions.List(ctx context.Context, query openai.ChatCompletionListParams) (pagination.CursorPage[openai.ChatCompletion], error) -- client.Chat.Completions.Delete(ctx context.Context, completionID string) (openai.ChatCompletionDeleted, error) - -### Messages - -Methods: - -- client.Chat.Completions.Messages.List(ctx context.Context, completionID string, query openai.ChatCompletionMessageListParams) (pagination.CursorPage[openai.ChatCompletionStoreMessage], error) - -# Embeddings - -Params Types: - -- openai.EmbeddingModel - -Response Types: - -- openai.CreateEmbeddingResponse -- openai.Embedding - -Methods: - -- client.Embeddings.New(ctx context.Context, body openai.EmbeddingNewParams) (openai.CreateEmbeddingResponse, error) - -# Files - -Params Types: - -- openai.FilePurpose - -Response Types: - -- openai.FileDeleted -- openai.FileObject - -Methods: - -- client.Files.New(ctx context.Context, body openai.FileNewParams) (openai.FileObject, error) -- client.Files.Get(ctx context.Context, fileID string) (openai.FileObject, error) -- client.Files.List(ctx context.Context, query openai.FileListParams) (pagination.CursorPage[openai.FileObject], error) -- client.Files.Delete(ctx context.Context, fileID string) (openai.FileDeleted, error) -- client.Files.Content(ctx context.Context, fileID string) (http.Response, error) - -# Images - -Params Types: - -- openai.ImageModel - -Response Types: - -- openai.Image -- openai.ImageEditCompletedEvent -- openai.ImageEditPartialImageEvent -- openai.ImageEditStreamEventUnion -- openai.ImageGenCompletedEvent -- openai.ImageGenPartialImageEvent -- openai.ImageGenStreamEventUnion -- openai.ImagesResponse - -Methods: - -- client.Images.NewVariation(ctx context.Context, body openai.ImageNewVariationParams) (openai.ImagesResponse, error) -- client.Images.Edit(ctx context.Context, body openai.ImageEditParams) (openai.ImagesResponse, error) -- client.Images.Generate(ctx context.Context, body openai.ImageGenerateParams) (openai.ImagesResponse, error) - -# Audio - -Params Types: - -- openai.AudioModel -- openai.AudioResponseFormat - -## Transcriptions - -Params Types: - -- openai.TranscriptionInclude - -Response Types: - -- openai.Transcription -- openai.TranscriptionStreamEventUnion -- openai.TranscriptionTextDeltaEvent -- openai.TranscriptionTextDoneEvent - -Methods: - -- client.Audio.Transcriptions.New(ctx context.Context, body openai.AudioTranscriptionNewParams) (Transcription, error) - -## Translations - -Response Types: - -- openai.Translation - -Methods: - -- client.Audio.Translations.New(ctx context.Context, body openai.AudioTranslationNewParams) (Translation, error) - -## Speech - -Params Types: - -- openai.SpeechModel - -Methods: - -- client.Audio.Speech.New(ctx context.Context, body openai.AudioSpeechNewParams) (http.Response, error) - -# Moderations - -Params Types: - -- openai.ModerationImageURLInputParam -- openai.ModerationModel -- openai.ModerationMultiModalInputUnionParam -- openai.ModerationTextInputParam - -Response Types: - -- openai.Moderation -- openai.ModerationNewResponse - -Methods: - -- client.Moderations.New(ctx context.Context, body openai.ModerationNewParams) (openai.ModerationNewResponse, error) - -# Models - -Response Types: - -- openai.Model -- openai.ModelDeleted - -Methods: - -- client.Models.Get(ctx context.Context, model string) (openai.Model, error) -- client.Models.List(ctx context.Context) (pagination.Page[openai.Model], error) -- client.Models.Delete(ctx context.Context, model string) (openai.ModelDeleted, error) - -# FineTuning - -## Methods - -Params Types: - -- openai.DpoHyperparameters -- openai.DpoMethodParam -- openai.ReinforcementHyperparameters -- openai.ReinforcementMethodParam -- openai.SupervisedHyperparameters -- openai.SupervisedMethodParam - -Response Types: - -- openai.DpoHyperparametersResp -- openai.DpoMethod -- openai.ReinforcementHyperparametersResp -- openai.ReinforcementMethod -- openai.SupervisedHyperparametersResp -- openai.SupervisedMethod - -## Jobs - -Response Types: - -- openai.FineTuningJob -- openai.FineTuningJobEvent -- openai.FineTuningJobWandbIntegration -- openai.FineTuningJobWandbIntegrationObject - -Methods: - -- client.FineTuning.Jobs.New(ctx context.Context, body openai.FineTuningJobNewParams) (openai.FineTuningJob, error) -- client.FineTuning.Jobs.Get(ctx context.Context, fineTuningJobID string) (openai.FineTuningJob, error) -- client.FineTuning.Jobs.List(ctx context.Context, query openai.FineTuningJobListParams) (pagination.CursorPage[openai.FineTuningJob], error) -- client.FineTuning.Jobs.Cancel(ctx context.Context, fineTuningJobID string) (openai.FineTuningJob, error) -- client.FineTuning.Jobs.ListEvents(ctx context.Context, fineTuningJobID string, query openai.FineTuningJobListEventsParams) (pagination.CursorPage[openai.FineTuningJobEvent], error) -- client.FineTuning.Jobs.Pause(ctx context.Context, fineTuningJobID string) (openai.FineTuningJob, error) -- client.FineTuning.Jobs.Resume(ctx context.Context, fineTuningJobID string) (openai.FineTuningJob, error) - -### Checkpoints - -Response Types: - -- openai.FineTuningJobCheckpoint - -Methods: - -- client.FineTuning.Jobs.Checkpoints.List(ctx context.Context, fineTuningJobID string, query openai.FineTuningJobCheckpointListParams) (pagination.CursorPage[openai.FineTuningJobCheckpoint], error) - -## Checkpoints - -### Permissions - -Response Types: - -- openai.FineTuningCheckpointPermissionNewResponse -- openai.FineTuningCheckpointPermissionGetResponse -- openai.FineTuningCheckpointPermissionDeleteResponse - -Methods: - -- client.FineTuning.Checkpoints.Permissions.New(ctx context.Context, fineTunedModelCheckpoint string, body openai.FineTuningCheckpointPermissionNewParams) (pagination.Page[openai.FineTuningCheckpointPermissionNewResponse], error) -- client.FineTuning.Checkpoints.Permissions.Get(ctx context.Context, fineTunedModelCheckpoint string, query openai.FineTuningCheckpointPermissionGetParams) (openai.FineTuningCheckpointPermissionGetResponse, error) -- client.FineTuning.Checkpoints.Permissions.Delete(ctx context.Context, fineTunedModelCheckpoint string, permissionID string) (openai.FineTuningCheckpointPermissionDeleteResponse, error) - -## Alpha - -### Graders - -Response Types: - -- openai.FineTuningAlphaGraderRunResponse -- openai.FineTuningAlphaGraderValidateResponse - -Methods: - -- client.FineTuning.Alpha.Graders.Run(ctx context.Context, body openai.FineTuningAlphaGraderRunParams) (openai.FineTuningAlphaGraderRunResponse, error) -- client.FineTuning.Alpha.Graders.Validate(ctx context.Context, body openai.FineTuningAlphaGraderValidateParams) (openai.FineTuningAlphaGraderValidateResponse, error) - -# Graders - -## GraderModels - -Params Types: - -- openai.LabelModelGraderParam -- openai.MultiGraderParam -- openai.PythonGraderParam -- openai.ScoreModelGraderParam -- openai.StringCheckGraderParam -- openai.TextSimilarityGraderParam - -Response Types: - -- openai.LabelModelGrader -- openai.MultiGrader -- openai.PythonGrader -- openai.ScoreModelGrader -- openai.StringCheckGrader -- openai.TextSimilarityGrader - -# VectorStores - -Params Types: - -- openai.AutoFileChunkingStrategyParam -- openai.FileChunkingStrategyParamUnion -- openai.StaticFileChunkingStrategyParam -- openai.StaticFileChunkingStrategyObjectParam - -Response Types: - -- openai.FileChunkingStrategyUnion -- openai.OtherFileChunkingStrategyObject -- openai.StaticFileChunkingStrategy -- openai.StaticFileChunkingStrategyObject -- openai.VectorStore -- openai.VectorStoreDeleted -- openai.VectorStoreSearchResponse - -Methods: - -- client.VectorStores.New(ctx context.Context, body openai.VectorStoreNewParams) (openai.VectorStore, error) -- client.VectorStores.Get(ctx context.Context, vectorStoreID string) (openai.VectorStore, error) -- client.VectorStores.Update(ctx context.Context, vectorStoreID string, body openai.VectorStoreUpdateParams) (openai.VectorStore, error) -- client.VectorStores.List(ctx context.Context, query openai.VectorStoreListParams) (pagination.CursorPage[openai.VectorStore], error) -- client.VectorStores.Delete(ctx context.Context, vectorStoreID string) (openai.VectorStoreDeleted, error) -- client.VectorStores.Search(ctx context.Context, vectorStoreID string, body openai.VectorStoreSearchParams) (pagination.Page[openai.VectorStoreSearchResponse], error) - -## Files - -Response Types: - -- openai.VectorStoreFile -- openai.VectorStoreFileDeleted -- openai.VectorStoreFileContentResponse - -Methods: - -- client.VectorStores.Files.New(ctx context.Context, vectorStoreID string, body openai.VectorStoreFileNewParams) (openai.VectorStoreFile, error) -- client.VectorStores.Files.Get(ctx context.Context, vectorStoreID string, fileID string) (openai.VectorStoreFile, error) -- client.VectorStores.Files.Update(ctx context.Context, vectorStoreID string, fileID string, body openai.VectorStoreFileUpdateParams) (openai.VectorStoreFile, error) -- client.VectorStores.Files.List(ctx context.Context, vectorStoreID string, query openai.VectorStoreFileListParams) (pagination.CursorPage[openai.VectorStoreFile], error) -- client.VectorStores.Files.Delete(ctx context.Context, vectorStoreID string, fileID string) (openai.VectorStoreFileDeleted, error) -- client.VectorStores.Files.Content(ctx context.Context, vectorStoreID string, fileID string) (pagination.Page[openai.VectorStoreFileContentResponse], error) - -## FileBatches - -Response Types: - -- openai.VectorStoreFileBatch - -Methods: - -- client.VectorStores.FileBatches.New(ctx context.Context, vectorStoreID string, body openai.VectorStoreFileBatchNewParams) (openai.VectorStoreFileBatch, error) -- client.VectorStores.FileBatches.Get(ctx context.Context, vectorStoreID string, batchID string) (openai.VectorStoreFileBatch, error) -- client.VectorStores.FileBatches.Cancel(ctx context.Context, vectorStoreID string, batchID string) (openai.VectorStoreFileBatch, error) -- client.VectorStores.FileBatches.ListFiles(ctx context.Context, vectorStoreID string, batchID string, query openai.VectorStoreFileBatchListFilesParams) (pagination.CursorPage[openai.VectorStoreFile], error) - -# Webhooks - -Response Types: - -- webhooks.BatchCancelledWebhookEvent -- webhooks.BatchCompletedWebhookEvent -- webhooks.BatchExpiredWebhookEvent -- webhooks.BatchFailedWebhookEvent -- webhooks.EvalRunCanceledWebhookEvent -- webhooks.EvalRunFailedWebhookEvent -- webhooks.EvalRunSucceededWebhookEvent -- webhooks.FineTuningJobCancelledWebhookEvent -- webhooks.FineTuningJobFailedWebhookEvent -- webhooks.FineTuningJobSucceededWebhookEvent -- webhooks.ResponseCancelledWebhookEvent -- webhooks.ResponseCompletedWebhookEvent -- webhooks.ResponseFailedWebhookEvent -- webhooks.ResponseIncompleteWebhookEvent -- webhooks.UnwrapWebhookEventUnion - -Methods: - -- client.Webhooks.Unwrap(body []byte, headers http.Header, opts ...option.RequestOption) (*webhooks.UnwrapWebhookEventUnion, error) -- client.Webhooks.UnwrapWithTolerance(body []byte, headers http.Header, tolerance time.Duration, opts ...option.RequestOption) (*webhooks.UnwrapWebhookEventUnion, error) -- client.Webhooks.UnwrapWithToleranceAndTime(body []byte, headers http.Header, tolerance time.Duration, now time.Time, opts ...option.RequestOption) (*webhooks.UnwrapWebhookEventUnion, error) -- client.Webhooks.VerifySignature(body []byte, headers http.Header, opts ...option.RequestOption) error -- client.Webhooks.VerifySignatureWithTolerance(body []byte, headers http.Header, tolerance time.Duration, opts ...option.RequestOption) error -- client.Webhooks.VerifySignatureWithToleranceAndTime(body []byte, headers http.Header, tolerance time.Duration, now time.Time, opts ...option.RequestOption) error - -# Beta - -## Assistants - -Params Types: - -- openai.AssistantToolUnionParam -- openai.CodeInterpreterToolParam -- openai.FileSearchToolParam -- openai.FunctionToolParam - -Response Types: - -- openai.Assistant -- openai.AssistantDeleted -- openai.AssistantStreamEventUnion -- openai.AssistantToolUnion -- openai.CodeInterpreterTool -- openai.FileSearchTool -- openai.FunctionTool - -Methods: - -- client.Beta.Assistants.New(ctx context.Context, body openai.BetaAssistantNewParams) (openai.Assistant, error) -- client.Beta.Assistants.Get(ctx context.Context, assistantID string) (openai.Assistant, error) -- client.Beta.Assistants.Update(ctx context.Context, assistantID string, body openai.BetaAssistantUpdateParams) (openai.Assistant, error) -- client.Beta.Assistants.List(ctx context.Context, query openai.BetaAssistantListParams) (pagination.CursorPage[openai.Assistant], error) -- client.Beta.Assistants.Delete(ctx context.Context, assistantID string) (openai.AssistantDeleted, error) - -## Threads - -Params Types: - -- openai.AssistantResponseFormatOptionUnionParam -- openai.AssistantToolChoiceParam -- openai.AssistantToolChoiceFunctionParam -- openai.AssistantToolChoiceOptionUnionParam - -Response Types: - -- openai.AssistantResponseFormatOptionUnion -- openai.AssistantToolChoice -- openai.AssistantToolChoiceFunction -- openai.AssistantToolChoiceOptionUnion -- openai.Thread -- openai.ThreadDeleted - -Methods: - -- client.Beta.Threads.New(ctx context.Context, body openai.BetaThreadNewParams) (openai.Thread, error) -- client.Beta.Threads.Get(ctx context.Context, threadID string) (openai.Thread, error) -- client.Beta.Threads.Update(ctx context.Context, threadID string, body openai.BetaThreadUpdateParams) (openai.Thread, error) -- client.Beta.Threads.Delete(ctx context.Context, threadID string) (openai.ThreadDeleted, error) -- client.Beta.Threads.NewAndRun(ctx context.Context, body openai.BetaThreadNewAndRunParams) (openai.Run, error) - -### Runs - -Response Types: - -- openai.RequiredActionFunctionToolCall -- openai.Run -- openai.RunStatus - -Methods: - -- client.Beta.Threads.Runs.New(ctx context.Context, threadID string, params openai.BetaThreadRunNewParams) (openai.Run, error) -- client.Beta.Threads.Runs.Get(ctx context.Context, threadID string, runID string) (openai.Run, error) -- client.Beta.Threads.Runs.Update(ctx context.Context, threadID string, runID string, body openai.BetaThreadRunUpdateParams) (openai.Run, error) -- client.Beta.Threads.Runs.List(ctx context.Context, threadID string, query openai.BetaThreadRunListParams) (pagination.CursorPage[openai.Run], error) -- client.Beta.Threads.Runs.Cancel(ctx context.Context, threadID string, runID string) (openai.Run, error) -- client.Beta.Threads.Runs.SubmitToolOutputs(ctx context.Context, threadID string, runID string, body openai.BetaThreadRunSubmitToolOutputsParams) (openai.Run, error) - -#### Steps - -Params Types: - -- openai.RunStepInclude - -Response Types: - -- openai.CodeInterpreterLogs -- openai.CodeInterpreterOutputImage -- openai.CodeInterpreterToolCall -- openai.CodeInterpreterToolCallDelta -- openai.FileSearchToolCall -- openai.FileSearchToolCallDelta -- openai.FunctionToolCall -- openai.FunctionToolCallDelta -- openai.MessageCreationStepDetails -- openai.RunStep -- openai.RunStepDelta -- openai.RunStepDeltaEvent -- openai.RunStepDeltaMessageDelta -- openai.ToolCallUnion -- openai.ToolCallDeltaUnion -- openai.ToolCallDeltaObject -- openai.ToolCallsStepDetails - -Methods: - -- client.Beta.Threads.Runs.Steps.Get(ctx context.Context, threadID string, runID string, stepID string, query openai.BetaThreadRunStepGetParams) (openai.RunStep, error) -- client.Beta.Threads.Runs.Steps.List(ctx context.Context, threadID string, runID string, query openai.BetaThreadRunStepListParams) (pagination.CursorPage[openai.RunStep], error) - -### Messages - -Params Types: - -- openai.ImageFileParam -- openai.ImageFileContentBlockParam -- openai.ImageURLParam -- openai.ImageURLContentBlockParam -- openai.MessageContentPartParamUnion -- openai.TextContentBlockParam - -Response Types: - -- openai.AnnotationUnion -- openai.AnnotationDeltaUnion -- openai.FileCitationAnnotation -- openai.FileCitationDeltaAnnotation -- openai.FilePathAnnotation -- openai.FilePathDeltaAnnotation -- openai.ImageFile -- openai.ImageFileContentBlock -- openai.ImageFileDelta -- openai.ImageFileDeltaBlock -- openai.ImageURL -- openai.ImageURLContentBlock -- openai.ImageURLDelta -- openai.ImageURLDeltaBlock -- openai.Message -- openai.MessageContentUnion -- openai.MessageContentDeltaUnion -- openai.MessageDeleted -- openai.MessageDelta -- openai.MessageDeltaEvent -- openai.RefusalContentBlock -- openai.RefusalDeltaBlock -- openai.Text -- openai.TextContentBlock -- openai.TextDelta -- openai.TextDeltaBlock - -Methods: - -- client.Beta.Threads.Messages.New(ctx context.Context, threadID string, body openai.BetaThreadMessageNewParams) (openai.Message, error) -- client.Beta.Threads.Messages.Get(ctx context.Context, threadID string, messageID string) (openai.Message, error) -- client.Beta.Threads.Messages.Update(ctx context.Context, threadID string, messageID string, body openai.BetaThreadMessageUpdateParams) (openai.Message, error) -- client.Beta.Threads.Messages.List(ctx context.Context, threadID string, query openai.BetaThreadMessageListParams) (pagination.CursorPage[openai.Message], error) -- client.Beta.Threads.Messages.Delete(ctx context.Context, threadID string, messageID string) (openai.MessageDeleted, error) - -# Batches - -Response Types: - -- openai.Batch -- openai.BatchError -- openai.BatchRequestCounts - -Methods: - -- client.Batches.New(ctx context.Context, body openai.BatchNewParams) (openai.Batch, error) -- client.Batches.Get(ctx context.Context, batchID string) (openai.Batch, error) -- client.Batches.List(ctx context.Context, query openai.BatchListParams) (pagination.CursorPage[openai.Batch], error) -- client.Batches.Cancel(ctx context.Context, batchID string) (openai.Batch, error) - -# Uploads - -Response Types: - -- openai.Upload - -Methods: - -- client.Uploads.New(ctx context.Context, body openai.UploadNewParams) (openai.Upload, error) -- client.Uploads.Cancel(ctx context.Context, uploadID string) (openai.Upload, error) -- client.Uploads.Complete(ctx context.Context, uploadID string, body openai.UploadCompleteParams) (openai.Upload, error) - -## Parts - -Response Types: - -- openai.UploadPart - -Methods: - -- client.Uploads.Parts.New(ctx context.Context, uploadID string, body openai.UploadPartNewParams) (openai.UploadPart, error) - -# Responses - -Params Types: - -- responses.ComputerToolParam -- responses.EasyInputMessageParam -- responses.FileSearchToolParam -- responses.FunctionToolParam -- responses.ResponseCodeInterpreterToolCallParam -- responses.ResponseComputerToolCallParam -- responses.ResponseComputerToolCallOutputScreenshotParam -- responses.ResponseFileSearchToolCallParam -- responses.ResponseFormatTextConfigUnionParam -- responses.ResponseFormatTextJSONSchemaConfigParam -- responses.ResponseFunctionToolCallParam -- responses.ResponseFunctionWebSearchParam -- responses.ResponseIncludable -- responses.ResponseInputParam -- responses.ResponseInputContentUnionParam -- responses.ResponseInputFileParam -- responses.ResponseInputImageParam -- responses.ResponseInputItemUnionParam -- responses.ResponseInputMessageContentListParam -- responses.ResponseInputTextParam -- responses.ResponseOutputMessageParam -- responses.ResponseOutputRefusalParam -- responses.ResponseOutputTextParam -- responses.ResponsePromptParam -- responses.ResponseReasoningItemParam -- responses.ResponseTextConfigParam -- responses.ToolUnionParam -- responses.ToolChoiceFunctionParam -- responses.ToolChoiceMcpParam -- responses.ToolChoiceOptions -- responses.ToolChoiceTypesParam -- responses.WebSearchToolParam - -Response Types: - -- responses.ComputerTool -- responses.EasyInputMessage -- responses.FileSearchTool -- responses.FunctionTool -- responses.Response -- responses.ResponseAudioDeltaEvent -- responses.ResponseAudioDoneEvent -- responses.ResponseAudioTranscriptDeltaEvent -- responses.ResponseAudioTranscriptDoneEvent -- responses.ResponseCodeInterpreterCallCodeDeltaEvent -- responses.ResponseCodeInterpreterCallCodeDoneEvent -- responses.ResponseCodeInterpreterCallCompletedEvent -- responses.ResponseCodeInterpreterCallInProgressEvent -- responses.ResponseCodeInterpreterCallInterpretingEvent -- responses.ResponseCodeInterpreterToolCall -- responses.ResponseCompletedEvent -- responses.ResponseComputerToolCall -- responses.ResponseComputerToolCallOutputItem -- responses.ResponseComputerToolCallOutputScreenshot -- responses.ResponseContentPartAddedEvent -- responses.ResponseContentPartDoneEvent -- responses.ResponseCreatedEvent -- responses.ResponseError -- responses.ResponseErrorEvent -- responses.ResponseFailedEvent -- responses.ResponseFileSearchCallCompletedEvent -- responses.ResponseFileSearchCallInProgressEvent -- responses.ResponseFileSearchCallSearchingEvent -- responses.ResponseFileSearchToolCall -- responses.ResponseFormatTextConfigUnion -- responses.ResponseFormatTextJSONSchemaConfig -- responses.ResponseFunctionCallArgumentsDeltaEvent -- responses.ResponseFunctionCallArgumentsDoneEvent -- responses.ResponseFunctionToolCall -- responses.ResponseFunctionToolCallItem -- responses.ResponseFunctionToolCallOutputItem -- responses.ResponseFunctionWebSearch -- responses.ResponseImageGenCallCompletedEvent -- responses.ResponseImageGenCallGeneratingEvent -- responses.ResponseImageGenCallInProgressEvent -- responses.ResponseImageGenCallPartialImageEvent -- responses.ResponseInProgressEvent -- responses.ResponseIncompleteEvent -- responses.ResponseInputContentUnion -- responses.ResponseInputFile -- responses.ResponseInputImage -- responses.ResponseInputItemUnion -- responses.ResponseInputMessageContentList -- responses.ResponseInputMessageItem -- responses.ResponseInputText -- responses.ResponseItemUnion -- responses.ResponseMcpCallArgumentsDeltaEvent -- responses.ResponseMcpCallArgumentsDoneEvent -- responses.ResponseMcpCallCompletedEvent -- responses.ResponseMcpCallFailedEvent -- responses.ResponseMcpCallInProgressEvent -- responses.ResponseMcpListToolsCompletedEvent -- responses.ResponseMcpListToolsFailedEvent -- responses.ResponseMcpListToolsInProgressEvent -- responses.ResponseOutputItemUnion -- responses.ResponseOutputItemAddedEvent -- responses.ResponseOutputItemDoneEvent -- responses.ResponseOutputMessage -- responses.ResponseOutputRefusal -- responses.ResponseOutputText -- responses.ResponseOutputTextAnnotationAddedEvent -- responses.ResponsePrompt -- responses.ResponseQueuedEvent -- responses.ResponseReasoningItem -- responses.ResponseReasoningSummaryDeltaEvent -- responses.ResponseReasoningSummaryDoneEvent -- responses.ResponseReasoningSummaryPartAddedEvent -- responses.ResponseReasoningSummaryPartDoneEvent -- responses.ResponseReasoningSummaryTextDeltaEvent -- responses.ResponseReasoningSummaryTextDoneEvent -- responses.ResponseRefusalDeltaEvent -- responses.ResponseRefusalDoneEvent -- responses.ResponseStatus -- responses.ResponseStreamEventUnion -- responses.ResponseTextConfig -- responses.ResponseTextDeltaEvent -- responses.ResponseTextDoneEvent -- responses.ResponseUsage -- responses.ResponseWebSearchCallCompletedEvent -- responses.ResponseWebSearchCallInProgressEvent -- responses.ResponseWebSearchCallSearchingEvent -- responses.ToolUnion -- responses.ToolChoiceFunction -- responses.ToolChoiceMcp -- responses.ToolChoiceOptions -- responses.ToolChoiceTypes -- responses.WebSearchTool - -Methods: - -- client.Responses.New(ctx context.Context, body responses.ResponseNewParams) (responses.Response, error) -- client.Responses.Get(ctx context.Context, responseID string, query responses.ResponseGetParams) (responses.Response, error) -- client.Responses.Delete(ctx context.Context, responseID string) error -- client.Responses.Cancel(ctx context.Context, responseID string) (responses.Response, error) - -## InputItems - -Response Types: - -- responses.ResponseItemList - -Methods: - -- client.Responses.InputItems.List(ctx context.Context, responseID string, query responses.InputItemListParams) (pagination.CursorPage[responses.ResponseItemUnion], error) - -# Containers - -Response Types: - -- openai.ContainerNewResponse -- openai.ContainerGetResponse -- openai.ContainerListResponse - -Methods: - -- client.Containers.New(ctx context.Context, body openai.ContainerNewParams) (openai.ContainerNewResponse, error) -- client.Containers.Get(ctx context.Context, containerID string) (openai.ContainerGetResponse, error) -- client.Containers.List(ctx context.Context, query openai.ContainerListParams) (pagination.CursorPage[openai.ContainerListResponse], error) -- client.Containers.Delete(ctx context.Context, containerID string) error - -## Files - -Response Types: - -- openai.ContainerFileNewResponse -- openai.ContainerFileGetResponse -- openai.ContainerFileListResponse - -Methods: - -- client.Containers.Files.New(ctx context.Context, containerID string, body openai.ContainerFileNewParams) (openai.ContainerFileNewResponse, error) -- client.Containers.Files.Get(ctx context.Context, containerID string, fileID string) (openai.ContainerFileGetResponse, error) -- client.Containers.Files.List(ctx context.Context, containerID string, query openai.ContainerFileListParams) (pagination.CursorPage[openai.ContainerFileListResponse], error) -- client.Containers.Files.Delete(ctx context.Context, containerID string, fileID string) error - -### Content - -Methods: - -- client.Containers.Files.Content.Get(ctx context.Context, containerID string, fileID string) (http.Response, error) diff --git a/vendor/github.com/openai/openai-go/audio.go b/vendor/github.com/openai/openai-go/audio.go deleted file mode 100644 index 9cd3e19d..00000000 --- a/vendor/github.com/openai/openai-go/audio.go +++ /dev/null @@ -1,53 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -package openai - -import ( - "github.com/openai/openai-go/option" -) - -// AudioService contains methods and other services that help with interacting with -// the openai API. -// -// Note, unlike clients, this service does not read variables from the environment -// automatically. You should not instantiate this service directly, and instead use -// the [NewAudioService] method instead. -type AudioService struct { - Options []option.RequestOption - Transcriptions AudioTranscriptionService - Translations AudioTranslationService - Speech AudioSpeechService -} - -// NewAudioService generates a new service that applies the given options to each -// request. These options are applied after the parent client's options (if there -// is one), and before any request-specific options. -func NewAudioService(opts ...option.RequestOption) (r AudioService) { - r = AudioService{} - r.Options = opts - r.Transcriptions = NewAudioTranscriptionService(opts...) - r.Translations = NewAudioTranslationService(opts...) - r.Speech = NewAudioSpeechService(opts...) - return -} - -type AudioModel = string - -const ( - AudioModelWhisper1 AudioModel = "whisper-1" - AudioModelGPT4oTranscribe AudioModel = "gpt-4o-transcribe" - AudioModelGPT4oMiniTranscribe AudioModel = "gpt-4o-mini-transcribe" -) - -// The format of the output, in one of these options: `json`, `text`, `srt`, -// `verbose_json`, or `vtt`. For `gpt-4o-transcribe` and `gpt-4o-mini-transcribe`, -// the only supported format is `json`. -type AudioResponseFormat string - -const ( - AudioResponseFormatJSON AudioResponseFormat = "json" - AudioResponseFormatText AudioResponseFormat = "text" - AudioResponseFormatSRT AudioResponseFormat = "srt" - AudioResponseFormatVerboseJSON AudioResponseFormat = "verbose_json" - AudioResponseFormatVTT AudioResponseFormat = "vtt" -) diff --git a/vendor/github.com/openai/openai-go/audiospeech.go b/vendor/github.com/openai/openai-go/audiospeech.go deleted file mode 100644 index 8adc81a6..00000000 --- a/vendor/github.com/openai/openai-go/audiospeech.go +++ /dev/null @@ -1,126 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -package openai - -import ( - "context" - "net/http" - - "github.com/openai/openai-go/internal/apijson" - "github.com/openai/openai-go/internal/requestconfig" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/packages/param" -) - -// AudioSpeechService contains methods and other services that help with -// interacting with the openai API. -// -// Note, unlike clients, this service does not read variables from the environment -// automatically. You should not instantiate this service directly, and instead use -// the [NewAudioSpeechService] method instead. -type AudioSpeechService struct { - Options []option.RequestOption -} - -// NewAudioSpeechService generates a new service that applies the given options to -// each request. These options are applied after the parent client's options (if -// there is one), and before any request-specific options. -func NewAudioSpeechService(opts ...option.RequestOption) (r AudioSpeechService) { - r = AudioSpeechService{} - r.Options = opts - return -} - -// Generates audio from the input text. -func (r *AudioSpeechService) New(ctx context.Context, body AudioSpeechNewParams, opts ...option.RequestOption) (res *http.Response, err error) { - opts = append(r.Options[:], opts...) - opts = append([]option.RequestOption{option.WithHeader("Accept", "application/octet-stream")}, opts...) - path := "audio/speech" - err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...) - return -} - -type SpeechModel = string - -const ( - SpeechModelTTS1 SpeechModel = "tts-1" - SpeechModelTTS1HD SpeechModel = "tts-1-hd" - SpeechModelGPT4oMiniTTS SpeechModel = "gpt-4o-mini-tts" -) - -type AudioSpeechNewParams struct { - // The text to generate audio for. The maximum length is 4096 characters. - Input string `json:"input,required"` - // One of the available [TTS models](https://platform.openai.com/docs/models#tts): - // `tts-1`, `tts-1-hd` or `gpt-4o-mini-tts`. - Model SpeechModel `json:"model,omitzero,required"` - // The voice to use when generating the audio. Supported voices are `alloy`, `ash`, - // `ballad`, `coral`, `echo`, `fable`, `onyx`, `nova`, `sage`, `shimmer`, and - // `verse`. Previews of the voices are available in the - // [Text to speech guide](https://platform.openai.com/docs/guides/text-to-speech#voice-options). - Voice AudioSpeechNewParamsVoice `json:"voice,omitzero,required"` - // Control the voice of your generated audio with additional instructions. Does not - // work with `tts-1` or `tts-1-hd`. - Instructions param.Opt[string] `json:"instructions,omitzero"` - // The speed of the generated audio. Select a value from `0.25` to `4.0`. `1.0` is - // the default. - Speed param.Opt[float64] `json:"speed,omitzero"` - // The format to audio in. Supported formats are `mp3`, `opus`, `aac`, `flac`, - // `wav`, and `pcm`. - // - // Any of "mp3", "opus", "aac", "flac", "wav", "pcm". - ResponseFormat AudioSpeechNewParamsResponseFormat `json:"response_format,omitzero"` - // The format to stream the audio in. Supported formats are `sse` and `audio`. - // `sse` is not supported for `tts-1` or `tts-1-hd`. - // - // Any of "sse", "audio". - StreamFormat AudioSpeechNewParamsStreamFormat `json:"stream_format,omitzero"` - paramObj -} - -func (r AudioSpeechNewParams) MarshalJSON() (data []byte, err error) { - type shadow AudioSpeechNewParams - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *AudioSpeechNewParams) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The voice to use when generating the audio. Supported voices are `alloy`, `ash`, -// `ballad`, `coral`, `echo`, `fable`, `onyx`, `nova`, `sage`, `shimmer`, and -// `verse`. Previews of the voices are available in the -// [Text to speech guide](https://platform.openai.com/docs/guides/text-to-speech#voice-options). -type AudioSpeechNewParamsVoice string - -const ( - AudioSpeechNewParamsVoiceAlloy AudioSpeechNewParamsVoice = "alloy" - AudioSpeechNewParamsVoiceAsh AudioSpeechNewParamsVoice = "ash" - AudioSpeechNewParamsVoiceBallad AudioSpeechNewParamsVoice = "ballad" - AudioSpeechNewParamsVoiceCoral AudioSpeechNewParamsVoice = "coral" - AudioSpeechNewParamsVoiceEcho AudioSpeechNewParamsVoice = "echo" - AudioSpeechNewParamsVoiceSage AudioSpeechNewParamsVoice = "sage" - AudioSpeechNewParamsVoiceShimmer AudioSpeechNewParamsVoice = "shimmer" - AudioSpeechNewParamsVoiceVerse AudioSpeechNewParamsVoice = "verse" -) - -// The format to audio in. Supported formats are `mp3`, `opus`, `aac`, `flac`, -// `wav`, and `pcm`. -type AudioSpeechNewParamsResponseFormat string - -const ( - AudioSpeechNewParamsResponseFormatMP3 AudioSpeechNewParamsResponseFormat = "mp3" - AudioSpeechNewParamsResponseFormatOpus AudioSpeechNewParamsResponseFormat = "opus" - AudioSpeechNewParamsResponseFormatAAC AudioSpeechNewParamsResponseFormat = "aac" - AudioSpeechNewParamsResponseFormatFLAC AudioSpeechNewParamsResponseFormat = "flac" - AudioSpeechNewParamsResponseFormatWAV AudioSpeechNewParamsResponseFormat = "wav" - AudioSpeechNewParamsResponseFormatPCM AudioSpeechNewParamsResponseFormat = "pcm" -) - -// The format to stream the audio in. Supported formats are `sse` and `audio`. -// `sse` is not supported for `tts-1` or `tts-1-hd`. -type AudioSpeechNewParamsStreamFormat string - -const ( - AudioSpeechNewParamsStreamFormatSSE AudioSpeechNewParamsStreamFormat = "sse" - AudioSpeechNewParamsStreamFormatAudio AudioSpeechNewParamsStreamFormat = "audio" -) diff --git a/vendor/github.com/openai/openai-go/audiotranscription.go b/vendor/github.com/openai/openai-go/audiotranscription.go deleted file mode 100644 index a7a79138..00000000 --- a/vendor/github.com/openai/openai-go/audiotranscription.go +++ /dev/null @@ -1,654 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -package openai - -import ( - "bytes" - "context" - "encoding/json" - "io" - "mime/multipart" - "net/http" - - "github.com/openai/openai-go/internal/apiform" - "github.com/openai/openai-go/internal/apijson" - "github.com/openai/openai-go/internal/requestconfig" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/packages/param" - "github.com/openai/openai-go/packages/respjson" - "github.com/openai/openai-go/packages/ssestream" - "github.com/openai/openai-go/shared/constant" -) - -// AudioTranscriptionService contains methods and other services that help with -// interacting with the openai API. -// -// Note, unlike clients, this service does not read variables from the environment -// automatically. You should not instantiate this service directly, and instead use -// the [NewAudioTranscriptionService] method instead. -type AudioTranscriptionService struct { - Options []option.RequestOption -} - -// NewAudioTranscriptionService generates a new service that applies the given -// options to each request. These options are applied after the parent client's -// options (if there is one), and before any request-specific options. -func NewAudioTranscriptionService(opts ...option.RequestOption) (r AudioTranscriptionService) { - r = AudioTranscriptionService{} - r.Options = opts - return -} - -// Transcribes audio into the input language. -func (r *AudioTranscriptionService) New(ctx context.Context, body AudioTranscriptionNewParams, opts ...option.RequestOption) (res *Transcription, err error) { - opts = append(r.Options[:], opts...) - path := "audio/transcriptions" - err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...) - return -} - -// Transcribes audio into the input language. -func (r *AudioTranscriptionService) NewStreaming(ctx context.Context, body AudioTranscriptionNewParams, opts ...option.RequestOption) (stream *ssestream.Stream[TranscriptionStreamEventUnion]) { - var ( - raw *http.Response - err error - ) - opts = append(r.Options[:], opts...) - body.SetExtraFields(map[string]any{ - "stream": "true", - }) - path := "audio/transcriptions" - err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &raw, opts...) - return ssestream.NewStream[TranscriptionStreamEventUnion](ssestream.NewDecoder(raw), err) -} - -// Represents a transcription response returned by model, based on the provided -// input. -type Transcription struct { - // The transcribed text. - Text string `json:"text,required"` - // The log probabilities of the tokens in the transcription. Only returned with the - // models `gpt-4o-transcribe` and `gpt-4o-mini-transcribe` if `logprobs` is added - // to the `include` array. - Logprobs []TranscriptionLogprob `json:"logprobs"` - // Token usage statistics for the request. - Usage TranscriptionUsageUnion `json:"usage"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Text respjson.Field - Logprobs respjson.Field - Usage respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r Transcription) RawJSON() string { return r.JSON.raw } -func (r *Transcription) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type TranscriptionLogprob struct { - // The token in the transcription. - Token string `json:"token"` - // The bytes of the token. - Bytes []float64 `json:"bytes"` - // The log probability of the token. - Logprob float64 `json:"logprob"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Token respjson.Field - Bytes respjson.Field - Logprob respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r TranscriptionLogprob) RawJSON() string { return r.JSON.raw } -func (r *TranscriptionLogprob) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// TranscriptionUsageUnion contains all possible properties and values from -// [TranscriptionUsageTokens], [TranscriptionUsageDuration]. -// -// Use the [TranscriptionUsageUnion.AsAny] method to switch on the variant. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -type TranscriptionUsageUnion struct { - // This field is from variant [TranscriptionUsageTokens]. - InputTokens int64 `json:"input_tokens"` - // This field is from variant [TranscriptionUsageTokens]. - OutputTokens int64 `json:"output_tokens"` - // This field is from variant [TranscriptionUsageTokens]. - TotalTokens int64 `json:"total_tokens"` - // Any of "tokens", "duration". - Type string `json:"type"` - // This field is from variant [TranscriptionUsageTokens]. - InputTokenDetails TranscriptionUsageTokensInputTokenDetails `json:"input_token_details"` - // This field is from variant [TranscriptionUsageDuration]. - Seconds float64 `json:"seconds"` - JSON struct { - InputTokens respjson.Field - OutputTokens respjson.Field - TotalTokens respjson.Field - Type respjson.Field - InputTokenDetails respjson.Field - Seconds respjson.Field - raw string - } `json:"-"` -} - -// anyTranscriptionUsage is implemented by each variant of -// [TranscriptionUsageUnion] to add type safety for the return type of -// [TranscriptionUsageUnion.AsAny] -type anyTranscriptionUsage interface { - implTranscriptionUsageUnion() -} - -func (TranscriptionUsageTokens) implTranscriptionUsageUnion() {} -func (TranscriptionUsageDuration) implTranscriptionUsageUnion() {} - -// Use the following switch statement to find the correct variant -// -// switch variant := TranscriptionUsageUnion.AsAny().(type) { -// case openai.TranscriptionUsageTokens: -// case openai.TranscriptionUsageDuration: -// default: -// fmt.Errorf("no variant present") -// } -func (u TranscriptionUsageUnion) AsAny() anyTranscriptionUsage { - switch u.Type { - case "tokens": - return u.AsTokens() - case "duration": - return u.AsDuration() - } - return nil -} - -func (u TranscriptionUsageUnion) AsTokens() (v TranscriptionUsageTokens) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u TranscriptionUsageUnion) AsDuration() (v TranscriptionUsageDuration) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -// Returns the unmodified JSON received from the API -func (u TranscriptionUsageUnion) RawJSON() string { return u.JSON.raw } - -func (r *TranscriptionUsageUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Usage statistics for models billed by token usage. -type TranscriptionUsageTokens struct { - // Number of input tokens billed for this request. - InputTokens int64 `json:"input_tokens,required"` - // Number of output tokens generated. - OutputTokens int64 `json:"output_tokens,required"` - // Total number of tokens used (input + output). - TotalTokens int64 `json:"total_tokens,required"` - // The type of the usage object. Always `tokens` for this variant. - Type constant.Tokens `json:"type,required"` - // Details about the input tokens billed for this request. - InputTokenDetails TranscriptionUsageTokensInputTokenDetails `json:"input_token_details"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - InputTokens respjson.Field - OutputTokens respjson.Field - TotalTokens respjson.Field - Type respjson.Field - InputTokenDetails respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r TranscriptionUsageTokens) RawJSON() string { return r.JSON.raw } -func (r *TranscriptionUsageTokens) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Details about the input tokens billed for this request. -type TranscriptionUsageTokensInputTokenDetails struct { - // Number of audio tokens billed for this request. - AudioTokens int64 `json:"audio_tokens"` - // Number of text tokens billed for this request. - TextTokens int64 `json:"text_tokens"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - AudioTokens respjson.Field - TextTokens respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r TranscriptionUsageTokensInputTokenDetails) RawJSON() string { return r.JSON.raw } -func (r *TranscriptionUsageTokensInputTokenDetails) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Usage statistics for models billed by audio input duration. -type TranscriptionUsageDuration struct { - // Duration of the input audio in seconds. - Seconds float64 `json:"seconds,required"` - // The type of the usage object. Always `duration` for this variant. - Type constant.Duration `json:"type,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Seconds respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r TranscriptionUsageDuration) RawJSON() string { return r.JSON.raw } -func (r *TranscriptionUsageDuration) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type TranscriptionInclude string - -const ( - TranscriptionIncludeLogprobs TranscriptionInclude = "logprobs" -) - -// TranscriptionStreamEventUnion contains all possible properties and values from -// [TranscriptionTextDeltaEvent], [TranscriptionTextDoneEvent]. -// -// Use the [TranscriptionStreamEventUnion.AsAny] method to switch on the variant. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -type TranscriptionStreamEventUnion struct { - // This field is from variant [TranscriptionTextDeltaEvent]. - Delta string `json:"delta"` - // Any of "transcript.text.delta", "transcript.text.done". - Type string `json:"type"` - // This field is a union of [[]TranscriptionTextDeltaEventLogprob], - // [[]TranscriptionTextDoneEventLogprob] - Logprobs TranscriptionStreamEventUnionLogprobs `json:"logprobs"` - // This field is from variant [TranscriptionTextDoneEvent]. - Text string `json:"text"` - // This field is from variant [TranscriptionTextDoneEvent]. - Usage TranscriptionTextDoneEventUsage `json:"usage"` - JSON struct { - Delta respjson.Field - Type respjson.Field - Logprobs respjson.Field - Text respjson.Field - Usage respjson.Field - raw string - } `json:"-"` -} - -// anyTranscriptionStreamEvent is implemented by each variant of -// [TranscriptionStreamEventUnion] to add type safety for the return type of -// [TranscriptionStreamEventUnion.AsAny] -type anyTranscriptionStreamEvent interface { - implTranscriptionStreamEventUnion() -} - -func (TranscriptionTextDeltaEvent) implTranscriptionStreamEventUnion() {} -func (TranscriptionTextDoneEvent) implTranscriptionStreamEventUnion() {} - -// Use the following switch statement to find the correct variant -// -// switch variant := TranscriptionStreamEventUnion.AsAny().(type) { -// case openai.TranscriptionTextDeltaEvent: -// case openai.TranscriptionTextDoneEvent: -// default: -// fmt.Errorf("no variant present") -// } -func (u TranscriptionStreamEventUnion) AsAny() anyTranscriptionStreamEvent { - switch u.Type { - case "transcript.text.delta": - return u.AsTranscriptTextDelta() - case "transcript.text.done": - return u.AsTranscriptTextDone() - } - return nil -} - -func (u TranscriptionStreamEventUnion) AsTranscriptTextDelta() (v TranscriptionTextDeltaEvent) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u TranscriptionStreamEventUnion) AsTranscriptTextDone() (v TranscriptionTextDoneEvent) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -// Returns the unmodified JSON received from the API -func (u TranscriptionStreamEventUnion) RawJSON() string { return u.JSON.raw } - -func (r *TranscriptionStreamEventUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// TranscriptionStreamEventUnionLogprobs is an implicit subunion of -// [TranscriptionStreamEventUnion]. TranscriptionStreamEventUnionLogprobs provides -// convenient access to the sub-properties of the union. -// -// For type safety it is recommended to directly use a variant of the -// [TranscriptionStreamEventUnion]. -// -// If the underlying value is not a json object, one of the following properties -// will be valid: OfTranscriptionTextDeltaEventLogprobs -// OfTranscriptionTextDoneEventLogprobs] -type TranscriptionStreamEventUnionLogprobs struct { - // This field will be present if the value is a - // [[]TranscriptionTextDeltaEventLogprob] instead of an object. - OfTranscriptionTextDeltaEventLogprobs []TranscriptionTextDeltaEventLogprob `json:",inline"` - // This field will be present if the value is a - // [[]TranscriptionTextDoneEventLogprob] instead of an object. - OfTranscriptionTextDoneEventLogprobs []TranscriptionTextDoneEventLogprob `json:",inline"` - JSON struct { - OfTranscriptionTextDeltaEventLogprobs respjson.Field - OfTranscriptionTextDoneEventLogprobs respjson.Field - raw string - } `json:"-"` -} - -func (r *TranscriptionStreamEventUnionLogprobs) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Emitted when there is an additional text delta. This is also the first event -// emitted when the transcription starts. Only emitted when you -// [create a transcription](https://platform.openai.com/docs/api-reference/audio/create-transcription) -// with the `Stream` parameter set to `true`. -type TranscriptionTextDeltaEvent struct { - // The text delta that was additionally transcribed. - Delta string `json:"delta,required"` - // The type of the event. Always `transcript.text.delta`. - Type constant.TranscriptTextDelta `json:"type,required"` - // The log probabilities of the delta. Only included if you - // [create a transcription](https://platform.openai.com/docs/api-reference/audio/create-transcription) - // with the `include[]` parameter set to `logprobs`. - Logprobs []TranscriptionTextDeltaEventLogprob `json:"logprobs"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Delta respjson.Field - Type respjson.Field - Logprobs respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r TranscriptionTextDeltaEvent) RawJSON() string { return r.JSON.raw } -func (r *TranscriptionTextDeltaEvent) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type TranscriptionTextDeltaEventLogprob struct { - // The token that was used to generate the log probability. - Token string `json:"token"` - // The bytes that were used to generate the log probability. - Bytes []int64 `json:"bytes"` - // The log probability of the token. - Logprob float64 `json:"logprob"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Token respjson.Field - Bytes respjson.Field - Logprob respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r TranscriptionTextDeltaEventLogprob) RawJSON() string { return r.JSON.raw } -func (r *TranscriptionTextDeltaEventLogprob) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Emitted when the transcription is complete. Contains the complete transcription -// text. Only emitted when you -// [create a transcription](https://platform.openai.com/docs/api-reference/audio/create-transcription) -// with the `Stream` parameter set to `true`. -type TranscriptionTextDoneEvent struct { - // The text that was transcribed. - Text string `json:"text,required"` - // The type of the event. Always `transcript.text.done`. - Type constant.TranscriptTextDone `json:"type,required"` - // The log probabilities of the individual tokens in the transcription. Only - // included if you - // [create a transcription](https://platform.openai.com/docs/api-reference/audio/create-transcription) - // with the `include[]` parameter set to `logprobs`. - Logprobs []TranscriptionTextDoneEventLogprob `json:"logprobs"` - // Usage statistics for models billed by token usage. - Usage TranscriptionTextDoneEventUsage `json:"usage"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Text respjson.Field - Type respjson.Field - Logprobs respjson.Field - Usage respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r TranscriptionTextDoneEvent) RawJSON() string { return r.JSON.raw } -func (r *TranscriptionTextDoneEvent) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type TranscriptionTextDoneEventLogprob struct { - // The token that was used to generate the log probability. - Token string `json:"token"` - // The bytes that were used to generate the log probability. - Bytes []int64 `json:"bytes"` - // The log probability of the token. - Logprob float64 `json:"logprob"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Token respjson.Field - Bytes respjson.Field - Logprob respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r TranscriptionTextDoneEventLogprob) RawJSON() string { return r.JSON.raw } -func (r *TranscriptionTextDoneEventLogprob) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Usage statistics for models billed by token usage. -type TranscriptionTextDoneEventUsage struct { - // Number of input tokens billed for this request. - InputTokens int64 `json:"input_tokens,required"` - // Number of output tokens generated. - OutputTokens int64 `json:"output_tokens,required"` - // Total number of tokens used (input + output). - TotalTokens int64 `json:"total_tokens,required"` - // The type of the usage object. Always `tokens` for this variant. - Type constant.Tokens `json:"type,required"` - // Details about the input tokens billed for this request. - InputTokenDetails TranscriptionTextDoneEventUsageInputTokenDetails `json:"input_token_details"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - InputTokens respjson.Field - OutputTokens respjson.Field - TotalTokens respjson.Field - Type respjson.Field - InputTokenDetails respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r TranscriptionTextDoneEventUsage) RawJSON() string { return r.JSON.raw } -func (r *TranscriptionTextDoneEventUsage) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Details about the input tokens billed for this request. -type TranscriptionTextDoneEventUsageInputTokenDetails struct { - // Number of audio tokens billed for this request. - AudioTokens int64 `json:"audio_tokens"` - // Number of text tokens billed for this request. - TextTokens int64 `json:"text_tokens"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - AudioTokens respjson.Field - TextTokens respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r TranscriptionTextDoneEventUsageInputTokenDetails) RawJSON() string { return r.JSON.raw } -func (r *TranscriptionTextDoneEventUsageInputTokenDetails) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type AudioTranscriptionNewParams struct { - // The audio file object (not file name) to transcribe, in one of these formats: - // flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm. - File io.Reader `json:"file,omitzero,required" format:"binary"` - // ID of the model to use. The options are `gpt-4o-transcribe`, - // `gpt-4o-mini-transcribe`, and `whisper-1` (which is powered by our open source - // Whisper V2 model). - Model AudioModel `json:"model,omitzero,required"` - // 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) (e.g. `en`) - // format will improve accuracy and latency. - Language param.Opt[string] `json:"language,omitzero"` - // An optional text to guide the model's style or continue a previous audio - // segment. The - // [prompt](https://platform.openai.com/docs/guides/speech-to-text#prompting) - // should match the audio language. - Prompt param.Opt[string] `json:"prompt,omitzero"` - // 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. - Temperature param.Opt[float64] `json:"temperature,omitzero"` - // Controls how the audio is cut into chunks. When set to `"auto"`, the server - // first normalizes loudness and then uses voice activity detection (VAD) to choose - // boundaries. `server_vad` object can be provided to tweak VAD detection - // parameters manually. If unset, the audio is transcribed as a single block. - ChunkingStrategy AudioTranscriptionNewParamsChunkingStrategyUnion `json:"chunking_strategy,omitzero"` - // Additional information to include in the transcription response. `logprobs` will - // return the log probabilities of the tokens in the response to understand the - // model's confidence in the transcription. `logprobs` only works with - // response_format set to `json` and only with the models `gpt-4o-transcribe` and - // `gpt-4o-mini-transcribe`. - Include []TranscriptionInclude `json:"include,omitzero"` - // The format of the output, in one of these options: `json`, `text`, `srt`, - // `verbose_json`, or `vtt`. For `gpt-4o-transcribe` and `gpt-4o-mini-transcribe`, - // the only supported format is `json`. - // - // Any of "json", "text", "srt", "verbose_json", "vtt". - ResponseFormat AudioResponseFormat `json:"response_format,omitzero"` - // 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. - // - // Any of "word", "segment". - TimestampGranularities []string `json:"timestamp_granularities,omitzero"` - paramObj -} - -func (r AudioTranscriptionNewParams) MarshalMultipart() (data []byte, contentType string, err error) { - buf := bytes.NewBuffer(nil) - writer := multipart.NewWriter(buf) - err = apiform.MarshalRoot(r, writer) - if err == nil { - err = apiform.WriteExtras(writer, r.ExtraFields()) - } - if err != nil { - writer.Close() - return nil, "", err - } - err = writer.Close() - if err != nil { - return nil, "", err - } - return buf.Bytes(), writer.FormDataContentType(), nil -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type AudioTranscriptionNewParamsChunkingStrategyUnion struct { - // Construct this variant with constant.ValueOf[constant.Auto]() - OfAuto constant.Auto `json:",omitzero,inline"` - OfAudioTranscriptionNewsChunkingStrategyVadConfig *AudioTranscriptionNewParamsChunkingStrategyVadConfig `json:",omitzero,inline"` - paramUnion -} - -func (u AudioTranscriptionNewParamsChunkingStrategyUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfAuto, u.OfAudioTranscriptionNewsChunkingStrategyVadConfig) -} -func (u *AudioTranscriptionNewParamsChunkingStrategyUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *AudioTranscriptionNewParamsChunkingStrategyUnion) asAny() any { - if !param.IsOmitted(u.OfAuto) { - return &u.OfAuto - } else if !param.IsOmitted(u.OfAudioTranscriptionNewsChunkingStrategyVadConfig) { - return u.OfAudioTranscriptionNewsChunkingStrategyVadConfig - } - return nil -} - -// The property Type is required. -type AudioTranscriptionNewParamsChunkingStrategyVadConfig struct { - // Must be set to `server_vad` to enable manual chunking using server side VAD. - // - // Any of "server_vad". - Type string `json:"type,omitzero,required"` - // Amount of audio to include before the VAD detected speech (in milliseconds). - PrefixPaddingMs param.Opt[int64] `json:"prefix_padding_ms,omitzero"` - // Duration of silence to detect speech stop (in milliseconds). With shorter values - // the model will respond more quickly, but may jump in on short pauses from the - // user. - SilenceDurationMs param.Opt[int64] `json:"silence_duration_ms,omitzero"` - // Sensitivity threshold (0.0 to 1.0) for voice activity detection. A higher - // threshold will require louder audio to activate the model, and thus might - // perform better in noisy environments. - Threshold param.Opt[float64] `json:"threshold,omitzero"` - paramObj -} - -func (r AudioTranscriptionNewParamsChunkingStrategyVadConfig) MarshalJSON() (data []byte, err error) { - type shadow AudioTranscriptionNewParamsChunkingStrategyVadConfig - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *AudioTranscriptionNewParamsChunkingStrategyVadConfig) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -func init() { - apijson.RegisterFieldValidator[AudioTranscriptionNewParamsChunkingStrategyVadConfig]( - "type", "server_vad", - ) -} diff --git a/vendor/github.com/openai/openai-go/audiotranslation.go b/vendor/github.com/openai/openai-go/audiotranslation.go deleted file mode 100644 index aa754e94..00000000 --- a/vendor/github.com/openai/openai-go/audiotranslation.go +++ /dev/null @@ -1,117 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -package openai - -import ( - "bytes" - "context" - "io" - "mime/multipart" - "net/http" - - "github.com/openai/openai-go/internal/apiform" - "github.com/openai/openai-go/internal/apijson" - "github.com/openai/openai-go/internal/requestconfig" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/packages/param" - "github.com/openai/openai-go/packages/respjson" -) - -// AudioTranslationService contains methods and other services that help with -// interacting with the openai API. -// -// Note, unlike clients, this service does not read variables from the environment -// automatically. You should not instantiate this service directly, and instead use -// the [NewAudioTranslationService] method instead. -type AudioTranslationService struct { - Options []option.RequestOption -} - -// NewAudioTranslationService generates a new service that applies the given -// options to each request. These options are applied after the parent client's -// options (if there is one), and before any request-specific options. -func NewAudioTranslationService(opts ...option.RequestOption) (r AudioTranslationService) { - r = AudioTranslationService{} - r.Options = opts - return -} - -// Translates audio into English. -func (r *AudioTranslationService) New(ctx context.Context, body AudioTranslationNewParams, opts ...option.RequestOption) (res *Translation, err error) { - opts = append(r.Options[:], opts...) - path := "audio/translations" - err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...) - return -} - -type Translation struct { - Text string `json:"text,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Text respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r Translation) RawJSON() string { return r.JSON.raw } -func (r *Translation) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type AudioTranslationNewParams struct { - // The audio file object (not file name) translate, in one of these formats: flac, - // mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm. - File io.Reader `json:"file,omitzero,required" format:"binary"` - // ID of the model to use. Only `whisper-1` (which is powered by our open source - // Whisper V2 model) is currently available. - Model AudioModel `json:"model,omitzero,required"` - // An optional text to guide the model's style or continue a previous audio - // segment. The - // [prompt](https://platform.openai.com/docs/guides/speech-to-text#prompting) - // should be in English. - Prompt param.Opt[string] `json:"prompt,omitzero"` - // 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. - Temperature param.Opt[float64] `json:"temperature,omitzero"` - // The format of the output, in one of these options: `json`, `text`, `srt`, - // `verbose_json`, or `vtt`. - // - // Any of "json", "text", "srt", "verbose_json", "vtt". - ResponseFormat AudioTranslationNewParamsResponseFormat `json:"response_format,omitzero"` - paramObj -} - -func (r AudioTranslationNewParams) MarshalMultipart() (data []byte, contentType string, err error) { - buf := bytes.NewBuffer(nil) - writer := multipart.NewWriter(buf) - err = apiform.MarshalRoot(r, writer) - if err == nil { - err = apiform.WriteExtras(writer, r.ExtraFields()) - } - if err != nil { - writer.Close() - return nil, "", err - } - err = writer.Close() - if err != nil { - return nil, "", err - } - return buf.Bytes(), writer.FormDataContentType(), nil -} - -// The format of the output, in one of these options: `json`, `text`, `srt`, -// `verbose_json`, or `vtt`. -type AudioTranslationNewParamsResponseFormat string - -const ( - AudioTranslationNewParamsResponseFormatJSON AudioTranslationNewParamsResponseFormat = "json" - AudioTranslationNewParamsResponseFormatText AudioTranslationNewParamsResponseFormat = "text" - AudioTranslationNewParamsResponseFormatSRT AudioTranslationNewParamsResponseFormat = "srt" - AudioTranslationNewParamsResponseFormatVerboseJSON AudioTranslationNewParamsResponseFormat = "verbose_json" - AudioTranslationNewParamsResponseFormatVTT AudioTranslationNewParamsResponseFormat = "vtt" -) diff --git a/vendor/github.com/openai/openai-go/batch.go b/vendor/github.com/openai/openai-go/batch.go deleted file mode 100644 index 36e02ed3..00000000 --- a/vendor/github.com/openai/openai-go/batch.go +++ /dev/null @@ -1,343 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -package openai - -import ( - "context" - "errors" - "fmt" - "net/http" - "net/url" - - "github.com/openai/openai-go/internal/apijson" - "github.com/openai/openai-go/internal/apiquery" - "github.com/openai/openai-go/internal/requestconfig" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/packages/pagination" - "github.com/openai/openai-go/packages/param" - "github.com/openai/openai-go/packages/respjson" - "github.com/openai/openai-go/shared" - "github.com/openai/openai-go/shared/constant" -) - -// BatchService contains methods and other services that help with interacting with -// the openai API. -// -// Note, unlike clients, this service does not read variables from the environment -// automatically. You should not instantiate this service directly, and instead use -// the [NewBatchService] method instead. -type BatchService struct { - Options []option.RequestOption -} - -// NewBatchService generates a new service that applies the given options to each -// request. These options are applied after the parent client's options (if there -// is one), and before any request-specific options. -func NewBatchService(opts ...option.RequestOption) (r BatchService) { - r = BatchService{} - r.Options = opts - return -} - -// Creates and executes a batch from an uploaded file of requests -func (r *BatchService) New(ctx context.Context, body BatchNewParams, opts ...option.RequestOption) (res *Batch, err error) { - opts = append(r.Options[:], opts...) - path := "batches" - err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...) - return -} - -// Retrieves a batch. -func (r *BatchService) Get(ctx context.Context, batchID string, opts ...option.RequestOption) (res *Batch, err error) { - opts = append(r.Options[:], opts...) - if batchID == "" { - err = errors.New("missing required batch_id parameter") - return - } - path := fmt.Sprintf("batches/%s", batchID) - err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...) - return -} - -// List your organization's batches. -func (r *BatchService) List(ctx context.Context, query BatchListParams, opts ...option.RequestOption) (res *pagination.CursorPage[Batch], err error) { - var raw *http.Response - opts = append(r.Options[:], opts...) - opts = append([]option.RequestOption{option.WithResponseInto(&raw)}, opts...) - path := "batches" - cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, query, &res, opts...) - if err != nil { - return nil, err - } - err = cfg.Execute() - if err != nil { - return nil, err - } - res.SetPageConfig(cfg, raw) - return res, nil -} - -// List your organization's batches. -func (r *BatchService) ListAutoPaging(ctx context.Context, query BatchListParams, opts ...option.RequestOption) *pagination.CursorPageAutoPager[Batch] { - return pagination.NewCursorPageAutoPager(r.List(ctx, query, opts...)) -} - -// Cancels an in-progress batch. The batch will be in status `cancelling` for up to -// 10 minutes, before changing to `cancelled`, where it will have partial results -// (if any) available in the output file. -func (r *BatchService) Cancel(ctx context.Context, batchID string, opts ...option.RequestOption) (res *Batch, err error) { - opts = append(r.Options[:], opts...) - if batchID == "" { - err = errors.New("missing required batch_id parameter") - return - } - path := fmt.Sprintf("batches/%s/cancel", batchID) - err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, nil, &res, opts...) - return -} - -type Batch struct { - ID string `json:"id,required"` - // The time frame within which the batch should be processed. - CompletionWindow string `json:"completion_window,required"` - // The Unix timestamp (in seconds) for when the batch was created. - CreatedAt int64 `json:"created_at,required"` - // The OpenAI API endpoint used by the batch. - Endpoint string `json:"endpoint,required"` - // The ID of the input file for the batch. - InputFileID string `json:"input_file_id,required"` - // The object type, which is always `batch`. - Object constant.Batch `json:"object,required"` - // The current status of the batch. - // - // Any of "validating", "failed", "in_progress", "finalizing", "completed", - // "expired", "cancelling", "cancelled". - Status BatchStatus `json:"status,required"` - // The Unix timestamp (in seconds) for when the batch was cancelled. - CancelledAt int64 `json:"cancelled_at"` - // The Unix timestamp (in seconds) for when the batch started cancelling. - CancellingAt int64 `json:"cancelling_at"` - // The Unix timestamp (in seconds) for when the batch was completed. - CompletedAt int64 `json:"completed_at"` - // The ID of the file containing the outputs of requests with errors. - ErrorFileID string `json:"error_file_id"` - Errors BatchErrors `json:"errors"` - // The Unix timestamp (in seconds) for when the batch expired. - ExpiredAt int64 `json:"expired_at"` - // The Unix timestamp (in seconds) for when the batch will expire. - ExpiresAt int64 `json:"expires_at"` - // The Unix timestamp (in seconds) for when the batch failed. - FailedAt int64 `json:"failed_at"` - // The Unix timestamp (in seconds) for when the batch started finalizing. - FinalizingAt int64 `json:"finalizing_at"` - // The Unix timestamp (in seconds) for when the batch started processing. - InProgressAt int64 `json:"in_progress_at"` - // 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, and - // querying for objects via API or the dashboard. - // - // Keys are strings with a maximum length of 64 characters. Values are strings with - // a maximum length of 512 characters. - Metadata shared.Metadata `json:"metadata,nullable"` - // The ID of the file containing the outputs of successfully executed requests. - OutputFileID string `json:"output_file_id"` - // The request counts for different statuses within the batch. - RequestCounts BatchRequestCounts `json:"request_counts"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ID respjson.Field - CompletionWindow respjson.Field - CreatedAt respjson.Field - Endpoint respjson.Field - InputFileID respjson.Field - Object respjson.Field - Status respjson.Field - CancelledAt respjson.Field - CancellingAt respjson.Field - CompletedAt respjson.Field - ErrorFileID respjson.Field - Errors respjson.Field - ExpiredAt respjson.Field - ExpiresAt respjson.Field - FailedAt respjson.Field - FinalizingAt respjson.Field - InProgressAt respjson.Field - Metadata respjson.Field - OutputFileID respjson.Field - RequestCounts respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r Batch) RawJSON() string { return r.JSON.raw } -func (r *Batch) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The current status of the batch. -type BatchStatus string - -const ( - BatchStatusValidating BatchStatus = "validating" - BatchStatusFailed BatchStatus = "failed" - BatchStatusInProgress BatchStatus = "in_progress" - BatchStatusFinalizing BatchStatus = "finalizing" - BatchStatusCompleted BatchStatus = "completed" - BatchStatusExpired BatchStatus = "expired" - BatchStatusCancelling BatchStatus = "cancelling" - BatchStatusCancelled BatchStatus = "cancelled" -) - -type BatchErrors struct { - Data []BatchError `json:"data"` - // The object type, which is always `list`. - Object string `json:"object"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Data respjson.Field - Object respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r BatchErrors) RawJSON() string { return r.JSON.raw } -func (r *BatchErrors) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type BatchError struct { - // An error code identifying the error type. - Code string `json:"code"` - // The line number of the input file where the error occurred, if applicable. - Line int64 `json:"line,nullable"` - // A human-readable message providing more details about the error. - Message string `json:"message"` - // The name of the parameter that caused the error, if applicable. - Param string `json:"param,nullable"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Code respjson.Field - Line respjson.Field - Message respjson.Field - Param respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r BatchError) RawJSON() string { return r.JSON.raw } -func (r *BatchError) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The request counts for different statuses within the batch. -type BatchRequestCounts struct { - // Number of requests that have been completed successfully. - Completed int64 `json:"completed,required"` - // Number of requests that have failed. - Failed int64 `json:"failed,required"` - // Total number of requests in the batch. - Total int64 `json:"total,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Completed respjson.Field - Failed respjson.Field - Total respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r BatchRequestCounts) RawJSON() string { return r.JSON.raw } -func (r *BatchRequestCounts) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type BatchNewParams struct { - // The time frame within which the batch should be processed. Currently only `24h` - // is supported. - // - // Any of "24h". - CompletionWindow BatchNewParamsCompletionWindow `json:"completion_window,omitzero,required"` - // The endpoint to be used for all requests in the batch. Currently - // `/v1/responses`, `/v1/chat/completions`, `/v1/embeddings`, and `/v1/completions` - // are supported. Note that `/v1/embeddings` batches are also restricted to a - // maximum of 50,000 embedding inputs across all requests in the batch. - // - // Any of "/v1/responses", "/v1/chat/completions", "/v1/embeddings", - // "/v1/completions". - Endpoint BatchNewParamsEndpoint `json:"endpoint,omitzero,required"` - // The ID of an uploaded file that contains requests for the new batch. - // - // See [upload file](https://platform.openai.com/docs/api-reference/files/create) - // for how to upload a file. - // - // Your input file must be formatted as a - // [JSONL file](https://platform.openai.com/docs/api-reference/batch/request-input), - // and must be uploaded with the purpose `batch`. The file can contain up to 50,000 - // requests, and can be up to 200 MB in size. - InputFileID string `json:"input_file_id,required"` - // 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, and - // querying for objects via API or the dashboard. - // - // Keys are strings with a maximum length of 64 characters. Values are strings with - // a maximum length of 512 characters. - Metadata shared.Metadata `json:"metadata,omitzero"` - paramObj -} - -func (r BatchNewParams) MarshalJSON() (data []byte, err error) { - type shadow BatchNewParams - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BatchNewParams) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The time frame within which the batch should be processed. Currently only `24h` -// is supported. -type BatchNewParamsCompletionWindow string - -const ( - BatchNewParamsCompletionWindow24h BatchNewParamsCompletionWindow = "24h" -) - -// The endpoint to be used for all requests in the batch. Currently -// `/v1/responses`, `/v1/chat/completions`, `/v1/embeddings`, and `/v1/completions` -// are supported. Note that `/v1/embeddings` batches are also restricted to a -// maximum of 50,000 embedding inputs across all requests in the batch. -type BatchNewParamsEndpoint string - -const ( - BatchNewParamsEndpointV1Responses BatchNewParamsEndpoint = "/v1/responses" - BatchNewParamsEndpointV1ChatCompletions BatchNewParamsEndpoint = "/v1/chat/completions" - BatchNewParamsEndpointV1Embeddings BatchNewParamsEndpoint = "/v1/embeddings" - BatchNewParamsEndpointV1Completions BatchNewParamsEndpoint = "/v1/completions" -) - -type BatchListParams struct { - // 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. - After param.Opt[string] `query:"after,omitzero" json:"-"` - // A limit on the number of objects to be returned. Limit can range between 1 and - // 100, and the default is 20. - Limit param.Opt[int64] `query:"limit,omitzero" json:"-"` - paramObj -} - -// URLQuery serializes [BatchListParams]'s query parameters as `url.Values`. -func (r BatchListParams) URLQuery() (v url.Values, err error) { - return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ - ArrayFormat: apiquery.ArrayQueryFormatBrackets, - NestedFormat: apiquery.NestedQueryFormatBrackets, - }) -} diff --git a/vendor/github.com/openai/openai-go/beta.go b/vendor/github.com/openai/openai-go/beta.go deleted file mode 100644 index 79fb960a..00000000 --- a/vendor/github.com/openai/openai-go/beta.go +++ /dev/null @@ -1,31 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -package openai - -import ( - "github.com/openai/openai-go/option" -) - -// BetaService contains methods and other services that help with interacting with -// the openai API. -// -// Note, unlike clients, this service does not read variables from the environment -// automatically. You should not instantiate this service directly, and instead use -// the [NewBetaService] method instead. -type BetaService struct { - Options []option.RequestOption - Assistants BetaAssistantService - // Deprecated: The Assistants API is deprecated in favor of the Responses API - Threads BetaThreadService -} - -// NewBetaService generates a new service that applies the given options to each -// request. These options are applied after the parent client's options (if there -// is one), and before any request-specific options. -func NewBetaService(opts ...option.RequestOption) (r BetaService) { - r = BetaService{} - r.Options = opts - r.Assistants = NewBetaAssistantService(opts...) - r.Threads = NewBetaThreadService(opts...) - return -} diff --git a/vendor/github.com/openai/openai-go/betaassistant.go b/vendor/github.com/openai/openai-go/betaassistant.go deleted file mode 100644 index 69cb0fa8..00000000 --- a/vendor/github.com/openai/openai-go/betaassistant.go +++ /dev/null @@ -1,2246 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -package openai - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "net/http" - "net/url" - - "github.com/openai/openai-go/internal/apijson" - "github.com/openai/openai-go/internal/apiquery" - "github.com/openai/openai-go/internal/requestconfig" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/packages/pagination" - "github.com/openai/openai-go/packages/param" - "github.com/openai/openai-go/packages/respjson" - "github.com/openai/openai-go/shared" - "github.com/openai/openai-go/shared/constant" -) - -// BetaAssistantService contains methods and other services that help with -// interacting with the openai API. -// -// Note, unlike clients, this service does not read variables from the environment -// automatically. You should not instantiate this service directly, and instead use -// the [NewBetaAssistantService] method instead. -type BetaAssistantService struct { - Options []option.RequestOption -} - -// NewBetaAssistantService generates a new service that applies the given options -// to each request. These options are applied after the parent client's options (if -// there is one), and before any request-specific options. -func NewBetaAssistantService(opts ...option.RequestOption) (r BetaAssistantService) { - r = BetaAssistantService{} - r.Options = opts - return -} - -// Create an assistant with a model and instructions. -func (r *BetaAssistantService) New(ctx context.Context, body BetaAssistantNewParams, opts ...option.RequestOption) (res *Assistant, err error) { - opts = append(r.Options[:], opts...) - opts = append([]option.RequestOption{option.WithHeader("OpenAI-Beta", "assistants=v2")}, opts...) - path := "assistants" - err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...) - return -} - -// Retrieves an assistant. -func (r *BetaAssistantService) Get(ctx context.Context, assistantID string, opts ...option.RequestOption) (res *Assistant, err error) { - opts = append(r.Options[:], opts...) - opts = append([]option.RequestOption{option.WithHeader("OpenAI-Beta", "assistants=v2")}, opts...) - if assistantID == "" { - err = errors.New("missing required assistant_id parameter") - return - } - path := fmt.Sprintf("assistants/%s", assistantID) - err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...) - return -} - -// Modifies an assistant. -func (r *BetaAssistantService) Update(ctx context.Context, assistantID string, body BetaAssistantUpdateParams, opts ...option.RequestOption) (res *Assistant, err error) { - opts = append(r.Options[:], opts...) - opts = append([]option.RequestOption{option.WithHeader("OpenAI-Beta", "assistants=v2")}, opts...) - if assistantID == "" { - err = errors.New("missing required assistant_id parameter") - return - } - path := fmt.Sprintf("assistants/%s", assistantID) - err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...) - return -} - -// Returns a list of assistants. -func (r *BetaAssistantService) List(ctx context.Context, query BetaAssistantListParams, opts ...option.RequestOption) (res *pagination.CursorPage[Assistant], err error) { - var raw *http.Response - opts = append(r.Options[:], opts...) - opts = append([]option.RequestOption{option.WithHeader("OpenAI-Beta", "assistants=v2"), option.WithResponseInto(&raw)}, opts...) - path := "assistants" - cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, query, &res, opts...) - if err != nil { - return nil, err - } - err = cfg.Execute() - if err != nil { - return nil, err - } - res.SetPageConfig(cfg, raw) - return res, nil -} - -// Returns a list of assistants. -func (r *BetaAssistantService) ListAutoPaging(ctx context.Context, query BetaAssistantListParams, opts ...option.RequestOption) *pagination.CursorPageAutoPager[Assistant] { - return pagination.NewCursorPageAutoPager(r.List(ctx, query, opts...)) -} - -// Delete an assistant. -func (r *BetaAssistantService) Delete(ctx context.Context, assistantID string, opts ...option.RequestOption) (res *AssistantDeleted, err error) { - opts = append(r.Options[:], opts...) - opts = append([]option.RequestOption{option.WithHeader("OpenAI-Beta", "assistants=v2")}, opts...) - if assistantID == "" { - err = errors.New("missing required assistant_id parameter") - return - } - path := fmt.Sprintf("assistants/%s", assistantID) - err = requestconfig.ExecuteNewRequest(ctx, http.MethodDelete, path, nil, &res, opts...) - return -} - -// Represents an `assistant` that can call the model and use tools. -type Assistant struct { - // The identifier, which can be referenced in API endpoints. - ID string `json:"id,required"` - // The Unix timestamp (in seconds) for when the assistant was created. - CreatedAt int64 `json:"created_at,required"` - // The description of the assistant. The maximum length is 512 characters. - Description string `json:"description,required"` - // The system instructions that the assistant uses. The maximum length is 256,000 - // characters. - Instructions string `json:"instructions,required"` - // 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, and - // querying for objects via API or the dashboard. - // - // Keys are strings with a maximum length of 64 characters. Values are strings with - // a maximum length of 512 characters. - Metadata shared.Metadata `json:"metadata,required"` - // ID of the model to use. You can use the - // [List models](https://platform.openai.com/docs/api-reference/models/list) API to - // see all of your available models, or see our - // [Model overview](https://platform.openai.com/docs/models) for descriptions of - // them. - Model string `json:"model,required"` - // The name of the assistant. The maximum length is 256 characters. - Name string `json:"name,required"` - // The object type, which is always `assistant`. - Object constant.Assistant `json:"object,required"` - // 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`. - Tools []AssistantToolUnion `json:"tools,required"` - // Specifies the format that the model must output. Compatible with - // [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), - // [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), - // and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. - // - // Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured - // Outputs which ensures the model will match your supplied JSON schema. Learn more - // in the - // [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). - // - // Setting to `{ "type": "json_object" }` enables JSON mode, which ensures 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 AssistantResponseFormatOptionUnion `json:"response_format,nullable"` - // 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. - Temperature float64 `json:"temperature,nullable"` - // 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. - ToolResources AssistantToolResources `json:"tool_resources,nullable"` - // 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 `json:"top_p,nullable"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ID respjson.Field - CreatedAt respjson.Field - Description respjson.Field - Instructions respjson.Field - Metadata respjson.Field - Model respjson.Field - Name respjson.Field - Object respjson.Field - Tools respjson.Field - ResponseFormat respjson.Field - Temperature respjson.Field - ToolResources respjson.Field - TopP respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r Assistant) RawJSON() string { return r.JSON.raw } -func (r *Assistant) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// 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. -type AssistantToolResources struct { - CodeInterpreter AssistantToolResourcesCodeInterpreter `json:"code_interpreter"` - FileSearch AssistantToolResourcesFileSearch `json:"file_search"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - CodeInterpreter respjson.Field - FileSearch respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r AssistantToolResources) RawJSON() string { return r.JSON.raw } -func (r *AssistantToolResources) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type AssistantToolResourcesCodeInterpreter struct { - // A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made - // available to the `code_interpreter“ tool. There can be a maximum of 20 files - // associated with the tool. - FileIDs []string `json:"file_ids"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - FileIDs respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r AssistantToolResourcesCodeInterpreter) RawJSON() string { return r.JSON.raw } -func (r *AssistantToolResourcesCodeInterpreter) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type AssistantToolResourcesFileSearch struct { - // The ID of the - // [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) - // attached to this assistant. There can be a maximum of 1 vector store attached to - // the assistant. - VectorStoreIDs []string `json:"vector_store_ids"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - VectorStoreIDs respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r AssistantToolResourcesFileSearch) RawJSON() string { return r.JSON.raw } -func (r *AssistantToolResourcesFileSearch) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type AssistantDeleted struct { - ID string `json:"id,required"` - Deleted bool `json:"deleted,required"` - Object constant.AssistantDeleted `json:"object,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ID respjson.Field - Deleted respjson.Field - Object respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r AssistantDeleted) RawJSON() string { return r.JSON.raw } -func (r *AssistantDeleted) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// AssistantStreamEventUnion contains all possible properties and values from -// [AssistantStreamEventThreadCreated], [AssistantStreamEventThreadRunCreated], -// [AssistantStreamEventThreadRunQueued], -// [AssistantStreamEventThreadRunInProgress], -// [AssistantStreamEventThreadRunRequiresAction], -// [AssistantStreamEventThreadRunCompleted], -// [AssistantStreamEventThreadRunIncomplete], -// [AssistantStreamEventThreadRunFailed], -// [AssistantStreamEventThreadRunCancelling], -// [AssistantStreamEventThreadRunCancelled], -// [AssistantStreamEventThreadRunExpired], -// [AssistantStreamEventThreadRunStepCreated], -// [AssistantStreamEventThreadRunStepInProgress], -// [AssistantStreamEventThreadRunStepDelta], -// [AssistantStreamEventThreadRunStepCompleted], -// [AssistantStreamEventThreadRunStepFailed], -// [AssistantStreamEventThreadRunStepCancelled], -// [AssistantStreamEventThreadRunStepExpired], -// [AssistantStreamEventThreadMessageCreated], -// [AssistantStreamEventThreadMessageInProgress], -// [AssistantStreamEventThreadMessageDelta], -// [AssistantStreamEventThreadMessageCompleted], -// [AssistantStreamEventThreadMessageIncomplete], [AssistantStreamEventErrorEvent]. -// -// Use the [AssistantStreamEventUnion.AsAny] method to switch on the variant. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -type AssistantStreamEventUnion struct { - // This field is a union of [Thread], [Run], [RunStep], [RunStepDeltaEvent], - // [Message], [MessageDeltaEvent], [shared.ErrorObject] - Data AssistantStreamEventUnionData `json:"data"` - // Any of "thread.created", "thread.run.created", "thread.run.queued", - // "thread.run.in_progress", "thread.run.requires_action", "thread.run.completed", - // "thread.run.incomplete", "thread.run.failed", "thread.run.cancelling", - // "thread.run.cancelled", "thread.run.expired", "thread.run.step.created", - // "thread.run.step.in_progress", "thread.run.step.delta", - // "thread.run.step.completed", "thread.run.step.failed", - // "thread.run.step.cancelled", "thread.run.step.expired", - // "thread.message.created", "thread.message.in_progress", "thread.message.delta", - // "thread.message.completed", "thread.message.incomplete", "error". - Event string `json:"event"` - // This field is from variant [AssistantStreamEventThreadCreated]. - Enabled bool `json:"enabled"` - JSON struct { - Data respjson.Field - Event respjson.Field - Enabled respjson.Field - raw string - } `json:"-"` -} - -// anyAssistantStreamEvent is implemented by each variant of -// [AssistantStreamEventUnion] to add type safety for the return type of -// [AssistantStreamEventUnion.AsAny] -type anyAssistantStreamEvent interface { - implAssistantStreamEventUnion() -} - -func (AssistantStreamEventThreadCreated) implAssistantStreamEventUnion() {} -func (AssistantStreamEventThreadRunCreated) implAssistantStreamEventUnion() {} -func (AssistantStreamEventThreadRunQueued) implAssistantStreamEventUnion() {} -func (AssistantStreamEventThreadRunInProgress) implAssistantStreamEventUnion() {} -func (AssistantStreamEventThreadRunRequiresAction) implAssistantStreamEventUnion() {} -func (AssistantStreamEventThreadRunCompleted) implAssistantStreamEventUnion() {} -func (AssistantStreamEventThreadRunIncomplete) implAssistantStreamEventUnion() {} -func (AssistantStreamEventThreadRunFailed) implAssistantStreamEventUnion() {} -func (AssistantStreamEventThreadRunCancelling) implAssistantStreamEventUnion() {} -func (AssistantStreamEventThreadRunCancelled) implAssistantStreamEventUnion() {} -func (AssistantStreamEventThreadRunExpired) implAssistantStreamEventUnion() {} -func (AssistantStreamEventThreadRunStepCreated) implAssistantStreamEventUnion() {} -func (AssistantStreamEventThreadRunStepInProgress) implAssistantStreamEventUnion() {} -func (AssistantStreamEventThreadRunStepDelta) implAssistantStreamEventUnion() {} -func (AssistantStreamEventThreadRunStepCompleted) implAssistantStreamEventUnion() {} -func (AssistantStreamEventThreadRunStepFailed) implAssistantStreamEventUnion() {} -func (AssistantStreamEventThreadRunStepCancelled) implAssistantStreamEventUnion() {} -func (AssistantStreamEventThreadRunStepExpired) implAssistantStreamEventUnion() {} -func (AssistantStreamEventThreadMessageCreated) implAssistantStreamEventUnion() {} -func (AssistantStreamEventThreadMessageInProgress) implAssistantStreamEventUnion() {} -func (AssistantStreamEventThreadMessageDelta) implAssistantStreamEventUnion() {} -func (AssistantStreamEventThreadMessageCompleted) implAssistantStreamEventUnion() {} -func (AssistantStreamEventThreadMessageIncomplete) implAssistantStreamEventUnion() {} -func (AssistantStreamEventErrorEvent) implAssistantStreamEventUnion() {} - -// Use the following switch statement to find the correct variant -// -// switch variant := AssistantStreamEventUnion.AsAny().(type) { -// case openai.AssistantStreamEventThreadCreated: -// case openai.AssistantStreamEventThreadRunCreated: -// case openai.AssistantStreamEventThreadRunQueued: -// case openai.AssistantStreamEventThreadRunInProgress: -// case openai.AssistantStreamEventThreadRunRequiresAction: -// case openai.AssistantStreamEventThreadRunCompleted: -// case openai.AssistantStreamEventThreadRunIncomplete: -// case openai.AssistantStreamEventThreadRunFailed: -// case openai.AssistantStreamEventThreadRunCancelling: -// case openai.AssistantStreamEventThreadRunCancelled: -// case openai.AssistantStreamEventThreadRunExpired: -// case openai.AssistantStreamEventThreadRunStepCreated: -// case openai.AssistantStreamEventThreadRunStepInProgress: -// case openai.AssistantStreamEventThreadRunStepDelta: -// case openai.AssistantStreamEventThreadRunStepCompleted: -// case openai.AssistantStreamEventThreadRunStepFailed: -// case openai.AssistantStreamEventThreadRunStepCancelled: -// case openai.AssistantStreamEventThreadRunStepExpired: -// case openai.AssistantStreamEventThreadMessageCreated: -// case openai.AssistantStreamEventThreadMessageInProgress: -// case openai.AssistantStreamEventThreadMessageDelta: -// case openai.AssistantStreamEventThreadMessageCompleted: -// case openai.AssistantStreamEventThreadMessageIncomplete: -// case openai.AssistantStreamEventErrorEvent: -// default: -// fmt.Errorf("no variant present") -// } -func (u AssistantStreamEventUnion) AsAny() anyAssistantStreamEvent { - switch u.Event { - case "thread.created": - return u.AsThreadCreated() - case "thread.run.created": - return u.AsThreadRunCreated() - case "thread.run.queued": - return u.AsThreadRunQueued() - case "thread.run.in_progress": - return u.AsThreadRunInProgress() - case "thread.run.requires_action": - return u.AsThreadRunRequiresAction() - case "thread.run.completed": - return u.AsThreadRunCompleted() - case "thread.run.incomplete": - return u.AsThreadRunIncomplete() - case "thread.run.failed": - return u.AsThreadRunFailed() - case "thread.run.cancelling": - return u.AsThreadRunCancelling() - case "thread.run.cancelled": - return u.AsThreadRunCancelled() - case "thread.run.expired": - return u.AsThreadRunExpired() - case "thread.run.step.created": - return u.AsThreadRunStepCreated() - case "thread.run.step.in_progress": - return u.AsThreadRunStepInProgress() - case "thread.run.step.delta": - return u.AsThreadRunStepDelta() - case "thread.run.step.completed": - return u.AsThreadRunStepCompleted() - case "thread.run.step.failed": - return u.AsThreadRunStepFailed() - case "thread.run.step.cancelled": - return u.AsThreadRunStepCancelled() - case "thread.run.step.expired": - return u.AsThreadRunStepExpired() - case "thread.message.created": - return u.AsThreadMessageCreated() - case "thread.message.in_progress": - return u.AsThreadMessageInProgress() - case "thread.message.delta": - return u.AsThreadMessageDelta() - case "thread.message.completed": - return u.AsThreadMessageCompleted() - case "thread.message.incomplete": - return u.AsThreadMessageIncomplete() - case "error": - return u.AsErrorEvent() - } - return nil -} - -func (u AssistantStreamEventUnion) AsThreadCreated() (v AssistantStreamEventThreadCreated) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u AssistantStreamEventUnion) AsThreadRunCreated() (v AssistantStreamEventThreadRunCreated) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u AssistantStreamEventUnion) AsThreadRunQueued() (v AssistantStreamEventThreadRunQueued) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u AssistantStreamEventUnion) AsThreadRunInProgress() (v AssistantStreamEventThreadRunInProgress) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u AssistantStreamEventUnion) AsThreadRunRequiresAction() (v AssistantStreamEventThreadRunRequiresAction) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u AssistantStreamEventUnion) AsThreadRunCompleted() (v AssistantStreamEventThreadRunCompleted) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u AssistantStreamEventUnion) AsThreadRunIncomplete() (v AssistantStreamEventThreadRunIncomplete) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u AssistantStreamEventUnion) AsThreadRunFailed() (v AssistantStreamEventThreadRunFailed) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u AssistantStreamEventUnion) AsThreadRunCancelling() (v AssistantStreamEventThreadRunCancelling) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u AssistantStreamEventUnion) AsThreadRunCancelled() (v AssistantStreamEventThreadRunCancelled) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u AssistantStreamEventUnion) AsThreadRunExpired() (v AssistantStreamEventThreadRunExpired) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u AssistantStreamEventUnion) AsThreadRunStepCreated() (v AssistantStreamEventThreadRunStepCreated) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u AssistantStreamEventUnion) AsThreadRunStepInProgress() (v AssistantStreamEventThreadRunStepInProgress) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u AssistantStreamEventUnion) AsThreadRunStepDelta() (v AssistantStreamEventThreadRunStepDelta) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u AssistantStreamEventUnion) AsThreadRunStepCompleted() (v AssistantStreamEventThreadRunStepCompleted) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u AssistantStreamEventUnion) AsThreadRunStepFailed() (v AssistantStreamEventThreadRunStepFailed) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u AssistantStreamEventUnion) AsThreadRunStepCancelled() (v AssistantStreamEventThreadRunStepCancelled) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u AssistantStreamEventUnion) AsThreadRunStepExpired() (v AssistantStreamEventThreadRunStepExpired) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u AssistantStreamEventUnion) AsThreadMessageCreated() (v AssistantStreamEventThreadMessageCreated) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u AssistantStreamEventUnion) AsThreadMessageInProgress() (v AssistantStreamEventThreadMessageInProgress) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u AssistantStreamEventUnion) AsThreadMessageDelta() (v AssistantStreamEventThreadMessageDelta) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u AssistantStreamEventUnion) AsThreadMessageCompleted() (v AssistantStreamEventThreadMessageCompleted) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u AssistantStreamEventUnion) AsThreadMessageIncomplete() (v AssistantStreamEventThreadMessageIncomplete) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u AssistantStreamEventUnion) AsErrorEvent() (v AssistantStreamEventErrorEvent) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -// Returns the unmodified JSON received from the API -func (u AssistantStreamEventUnion) RawJSON() string { return u.JSON.raw } - -func (r *AssistantStreamEventUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// AssistantStreamEventUnionData is an implicit subunion of -// [AssistantStreamEventUnion]. AssistantStreamEventUnionData provides convenient -// access to the sub-properties of the union. -// -// For type safety it is recommended to directly use a variant of the -// [AssistantStreamEventUnion]. -type AssistantStreamEventUnionData struct { - ID string `json:"id"` - CreatedAt int64 `json:"created_at"` - // This field is from variant [Thread]. - Metadata shared.Metadata `json:"metadata"` - Object string `json:"object"` - // This field is from variant [Thread]. - ToolResources ThreadToolResources `json:"tool_resources"` - AssistantID string `json:"assistant_id"` - CancelledAt int64 `json:"cancelled_at"` - CompletedAt int64 `json:"completed_at"` - // This field is from variant [Run]. - ExpiresAt int64 `json:"expires_at"` - FailedAt int64 `json:"failed_at"` - // This field is a union of [RunIncompleteDetails], [MessageIncompleteDetails] - IncompleteDetails AssistantStreamEventUnionDataIncompleteDetails `json:"incomplete_details"` - // This field is from variant [Run]. - Instructions string `json:"instructions"` - // This field is a union of [RunLastError], [RunStepLastError] - LastError AssistantStreamEventUnionDataLastError `json:"last_error"` - // This field is from variant [Run]. - MaxCompletionTokens int64 `json:"max_completion_tokens"` - // This field is from variant [Run]. - MaxPromptTokens int64 `json:"max_prompt_tokens"` - // This field is from variant [Run]. - Model string `json:"model"` - // This field is from variant [Run]. - ParallelToolCalls bool `json:"parallel_tool_calls"` - // This field is from variant [Run]. - RequiredAction RunRequiredAction `json:"required_action"` - // This field is from variant [Run]. - ResponseFormat AssistantResponseFormatOptionUnion `json:"response_format"` - // This field is from variant [Run]. - StartedAt int64 `json:"started_at"` - Status string `json:"status"` - ThreadID string `json:"thread_id"` - // This field is from variant [Run]. - ToolChoice AssistantToolChoiceOptionUnion `json:"tool_choice"` - // This field is from variant [Run]. - Tools []AssistantToolUnion `json:"tools"` - // This field is from variant [Run]. - TruncationStrategy RunTruncationStrategy `json:"truncation_strategy"` - // This field is a union of [RunUsage], [RunStepUsage] - Usage AssistantStreamEventUnionDataUsage `json:"usage"` - // This field is from variant [Run]. - Temperature float64 `json:"temperature"` - // This field is from variant [Run]. - TopP float64 `json:"top_p"` - // This field is from variant [RunStep]. - ExpiredAt int64 `json:"expired_at"` - RunID string `json:"run_id"` - // This field is from variant [RunStep]. - StepDetails RunStepStepDetailsUnion `json:"step_details"` - Type string `json:"type"` - // This field is a union of [RunStepDelta], [MessageDelta] - Delta AssistantStreamEventUnionDataDelta `json:"delta"` - // This field is from variant [Message]. - Attachments []MessageAttachment `json:"attachments"` - // This field is from variant [Message]. - Content []MessageContentUnion `json:"content"` - // This field is from variant [Message]. - IncompleteAt int64 `json:"incomplete_at"` - // This field is from variant [Message]. - Role MessageRole `json:"role"` - // This field is from variant [shared.ErrorObject]. - Code string `json:"code"` - // This field is from variant [shared.ErrorObject]. - Message string `json:"message"` - // This field is from variant [shared.ErrorObject]. - Param string `json:"param"` - JSON struct { - ID respjson.Field - CreatedAt respjson.Field - Metadata respjson.Field - Object respjson.Field - ToolResources respjson.Field - AssistantID respjson.Field - CancelledAt respjson.Field - CompletedAt respjson.Field - ExpiresAt respjson.Field - FailedAt respjson.Field - IncompleteDetails respjson.Field - Instructions respjson.Field - LastError respjson.Field - MaxCompletionTokens respjson.Field - MaxPromptTokens respjson.Field - Model respjson.Field - ParallelToolCalls respjson.Field - RequiredAction respjson.Field - ResponseFormat respjson.Field - StartedAt respjson.Field - Status respjson.Field - ThreadID respjson.Field - ToolChoice respjson.Field - Tools respjson.Field - TruncationStrategy respjson.Field - Usage respjson.Field - Temperature respjson.Field - TopP respjson.Field - ExpiredAt respjson.Field - RunID respjson.Field - StepDetails respjson.Field - Type respjson.Field - Delta respjson.Field - Attachments respjson.Field - Content respjson.Field - IncompleteAt respjson.Field - Role respjson.Field - Code respjson.Field - Message respjson.Field - Param respjson.Field - raw string - } `json:"-"` -} - -func (r *AssistantStreamEventUnionData) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// AssistantStreamEventUnionDataIncompleteDetails is an implicit subunion of -// [AssistantStreamEventUnion]. AssistantStreamEventUnionDataIncompleteDetails -// provides convenient access to the sub-properties of the union. -// -// For type safety it is recommended to directly use a variant of the -// [AssistantStreamEventUnion]. -type AssistantStreamEventUnionDataIncompleteDetails struct { - Reason string `json:"reason"` - JSON struct { - Reason respjson.Field - raw string - } `json:"-"` -} - -func (r *AssistantStreamEventUnionDataIncompleteDetails) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// AssistantStreamEventUnionDataLastError is an implicit subunion of -// [AssistantStreamEventUnion]. AssistantStreamEventUnionDataLastError provides -// convenient access to the sub-properties of the union. -// -// For type safety it is recommended to directly use a variant of the -// [AssistantStreamEventUnion]. -type AssistantStreamEventUnionDataLastError struct { - Code string `json:"code"` - Message string `json:"message"` - JSON struct { - Code respjson.Field - Message respjson.Field - raw string - } `json:"-"` -} - -func (r *AssistantStreamEventUnionDataLastError) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// AssistantStreamEventUnionDataUsage is an implicit subunion of -// [AssistantStreamEventUnion]. AssistantStreamEventUnionDataUsage provides -// convenient access to the sub-properties of the union. -// -// For type safety it is recommended to directly use a variant of the -// [AssistantStreamEventUnion]. -type AssistantStreamEventUnionDataUsage struct { - CompletionTokens int64 `json:"completion_tokens"` - PromptTokens int64 `json:"prompt_tokens"` - TotalTokens int64 `json:"total_tokens"` - JSON struct { - CompletionTokens respjson.Field - PromptTokens respjson.Field - TotalTokens respjson.Field - raw string - } `json:"-"` -} - -func (r *AssistantStreamEventUnionDataUsage) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// AssistantStreamEventUnionDataDelta is an implicit subunion of -// [AssistantStreamEventUnion]. AssistantStreamEventUnionDataDelta provides -// convenient access to the sub-properties of the union. -// -// For type safety it is recommended to directly use a variant of the -// [AssistantStreamEventUnion]. -type AssistantStreamEventUnionDataDelta struct { - // This field is from variant [RunStepDelta]. - StepDetails RunStepDeltaStepDetailsUnion `json:"step_details"` - // This field is from variant [MessageDelta]. - Content []MessageContentDeltaUnion `json:"content"` - // This field is from variant [MessageDelta]. - Role MessageDeltaRole `json:"role"` - JSON struct { - StepDetails respjson.Field - Content respjson.Field - Role respjson.Field - raw string - } `json:"-"` -} - -func (r *AssistantStreamEventUnionDataDelta) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Occurs when a new -// [thread](https://platform.openai.com/docs/api-reference/threads/object) is -// created. -type AssistantStreamEventThreadCreated struct { - // Represents a thread that contains - // [messages](https://platform.openai.com/docs/api-reference/messages). - Data Thread `json:"data,required"` - Event constant.ThreadCreated `json:"event,required"` - // Whether to enable input audio transcription. - Enabled bool `json:"enabled"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Data respjson.Field - Event respjson.Field - Enabled respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r AssistantStreamEventThreadCreated) RawJSON() string { return r.JSON.raw } -func (r *AssistantStreamEventThreadCreated) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Occurs when a new -// [run](https://platform.openai.com/docs/api-reference/runs/object) is created. -type AssistantStreamEventThreadRunCreated struct { - // Represents an execution run on a - // [thread](https://platform.openai.com/docs/api-reference/threads). - Data Run `json:"data,required"` - Event constant.ThreadRunCreated `json:"event,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Data respjson.Field - Event respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r AssistantStreamEventThreadRunCreated) RawJSON() string { return r.JSON.raw } -func (r *AssistantStreamEventThreadRunCreated) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) -// moves to a `queued` status. -type AssistantStreamEventThreadRunQueued struct { - // Represents an execution run on a - // [thread](https://platform.openai.com/docs/api-reference/threads). - Data Run `json:"data,required"` - Event constant.ThreadRunQueued `json:"event,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Data respjson.Field - Event respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r AssistantStreamEventThreadRunQueued) RawJSON() string { return r.JSON.raw } -func (r *AssistantStreamEventThreadRunQueued) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) -// moves to an `in_progress` status. -type AssistantStreamEventThreadRunInProgress struct { - // Represents an execution run on a - // [thread](https://platform.openai.com/docs/api-reference/threads). - Data Run `json:"data,required"` - Event constant.ThreadRunInProgress `json:"event,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Data respjson.Field - Event respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r AssistantStreamEventThreadRunInProgress) RawJSON() string { return r.JSON.raw } -func (r *AssistantStreamEventThreadRunInProgress) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) -// moves to a `requires_action` status. -type AssistantStreamEventThreadRunRequiresAction struct { - // Represents an execution run on a - // [thread](https://platform.openai.com/docs/api-reference/threads). - Data Run `json:"data,required"` - Event constant.ThreadRunRequiresAction `json:"event,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Data respjson.Field - Event respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r AssistantStreamEventThreadRunRequiresAction) RawJSON() string { return r.JSON.raw } -func (r *AssistantStreamEventThreadRunRequiresAction) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) -// is completed. -type AssistantStreamEventThreadRunCompleted struct { - // Represents an execution run on a - // [thread](https://platform.openai.com/docs/api-reference/threads). - Data Run `json:"data,required"` - Event constant.ThreadRunCompleted `json:"event,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Data respjson.Field - Event respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r AssistantStreamEventThreadRunCompleted) RawJSON() string { return r.JSON.raw } -func (r *AssistantStreamEventThreadRunCompleted) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) -// ends with status `incomplete`. -type AssistantStreamEventThreadRunIncomplete struct { - // Represents an execution run on a - // [thread](https://platform.openai.com/docs/api-reference/threads). - Data Run `json:"data,required"` - Event constant.ThreadRunIncomplete `json:"event,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Data respjson.Field - Event respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r AssistantStreamEventThreadRunIncomplete) RawJSON() string { return r.JSON.raw } -func (r *AssistantStreamEventThreadRunIncomplete) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) -// fails. -type AssistantStreamEventThreadRunFailed struct { - // Represents an execution run on a - // [thread](https://platform.openai.com/docs/api-reference/threads). - Data Run `json:"data,required"` - Event constant.ThreadRunFailed `json:"event,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Data respjson.Field - Event respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r AssistantStreamEventThreadRunFailed) RawJSON() string { return r.JSON.raw } -func (r *AssistantStreamEventThreadRunFailed) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) -// moves to a `cancelling` status. -type AssistantStreamEventThreadRunCancelling struct { - // Represents an execution run on a - // [thread](https://platform.openai.com/docs/api-reference/threads). - Data Run `json:"data,required"` - Event constant.ThreadRunCancelling `json:"event,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Data respjson.Field - Event respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r AssistantStreamEventThreadRunCancelling) RawJSON() string { return r.JSON.raw } -func (r *AssistantStreamEventThreadRunCancelling) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) -// is cancelled. -type AssistantStreamEventThreadRunCancelled struct { - // Represents an execution run on a - // [thread](https://platform.openai.com/docs/api-reference/threads). - Data Run `json:"data,required"` - Event constant.ThreadRunCancelled `json:"event,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Data respjson.Field - Event respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r AssistantStreamEventThreadRunCancelled) RawJSON() string { return r.JSON.raw } -func (r *AssistantStreamEventThreadRunCancelled) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Occurs when a [run](https://platform.openai.com/docs/api-reference/runs/object) -// expires. -type AssistantStreamEventThreadRunExpired struct { - // Represents an execution run on a - // [thread](https://platform.openai.com/docs/api-reference/threads). - Data Run `json:"data,required"` - Event constant.ThreadRunExpired `json:"event,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Data respjson.Field - Event respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r AssistantStreamEventThreadRunExpired) RawJSON() string { return r.JSON.raw } -func (r *AssistantStreamEventThreadRunExpired) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Occurs when a -// [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) -// is created. -type AssistantStreamEventThreadRunStepCreated struct { - // Represents a step in execution of a run. - Data RunStep `json:"data,required"` - Event constant.ThreadRunStepCreated `json:"event,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Data respjson.Field - Event respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r AssistantStreamEventThreadRunStepCreated) RawJSON() string { return r.JSON.raw } -func (r *AssistantStreamEventThreadRunStepCreated) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Occurs when a -// [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) -// moves to an `in_progress` state. -type AssistantStreamEventThreadRunStepInProgress struct { - // Represents a step in execution of a run. - Data RunStep `json:"data,required"` - Event constant.ThreadRunStepInProgress `json:"event,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Data respjson.Field - Event respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r AssistantStreamEventThreadRunStepInProgress) RawJSON() string { return r.JSON.raw } -func (r *AssistantStreamEventThreadRunStepInProgress) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Occurs when parts of a -// [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) -// are being streamed. -type AssistantStreamEventThreadRunStepDelta struct { - // Represents a run step delta i.e. any changed fields on a run step during - // streaming. - Data RunStepDeltaEvent `json:"data,required"` - Event constant.ThreadRunStepDelta `json:"event,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Data respjson.Field - Event respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r AssistantStreamEventThreadRunStepDelta) RawJSON() string { return r.JSON.raw } -func (r *AssistantStreamEventThreadRunStepDelta) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Occurs when a -// [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) -// is completed. -type AssistantStreamEventThreadRunStepCompleted struct { - // Represents a step in execution of a run. - Data RunStep `json:"data,required"` - Event constant.ThreadRunStepCompleted `json:"event,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Data respjson.Field - Event respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r AssistantStreamEventThreadRunStepCompleted) RawJSON() string { return r.JSON.raw } -func (r *AssistantStreamEventThreadRunStepCompleted) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Occurs when a -// [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) -// fails. -type AssistantStreamEventThreadRunStepFailed struct { - // Represents a step in execution of a run. - Data RunStep `json:"data,required"` - Event constant.ThreadRunStepFailed `json:"event,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Data respjson.Field - Event respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r AssistantStreamEventThreadRunStepFailed) RawJSON() string { return r.JSON.raw } -func (r *AssistantStreamEventThreadRunStepFailed) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Occurs when a -// [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) -// is cancelled. -type AssistantStreamEventThreadRunStepCancelled struct { - // Represents a step in execution of a run. - Data RunStep `json:"data,required"` - Event constant.ThreadRunStepCancelled `json:"event,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Data respjson.Field - Event respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r AssistantStreamEventThreadRunStepCancelled) RawJSON() string { return r.JSON.raw } -func (r *AssistantStreamEventThreadRunStepCancelled) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Occurs when a -// [run step](https://platform.openai.com/docs/api-reference/run-steps/step-object) -// expires. -type AssistantStreamEventThreadRunStepExpired struct { - // Represents a step in execution of a run. - Data RunStep `json:"data,required"` - Event constant.ThreadRunStepExpired `json:"event,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Data respjson.Field - Event respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r AssistantStreamEventThreadRunStepExpired) RawJSON() string { return r.JSON.raw } -func (r *AssistantStreamEventThreadRunStepExpired) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Occurs when a -// [message](https://platform.openai.com/docs/api-reference/messages/object) is -// created. -type AssistantStreamEventThreadMessageCreated struct { - // Represents a message within a - // [thread](https://platform.openai.com/docs/api-reference/threads). - Data Message `json:"data,required"` - Event constant.ThreadMessageCreated `json:"event,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Data respjson.Field - Event respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r AssistantStreamEventThreadMessageCreated) RawJSON() string { return r.JSON.raw } -func (r *AssistantStreamEventThreadMessageCreated) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Occurs when a -// [message](https://platform.openai.com/docs/api-reference/messages/object) moves -// to an `in_progress` state. -type AssistantStreamEventThreadMessageInProgress struct { - // Represents a message within a - // [thread](https://platform.openai.com/docs/api-reference/threads). - Data Message `json:"data,required"` - Event constant.ThreadMessageInProgress `json:"event,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Data respjson.Field - Event respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r AssistantStreamEventThreadMessageInProgress) RawJSON() string { return r.JSON.raw } -func (r *AssistantStreamEventThreadMessageInProgress) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Occurs when parts of a -// [Message](https://platform.openai.com/docs/api-reference/messages/object) are -// being streamed. -type AssistantStreamEventThreadMessageDelta struct { - // Represents a message delta i.e. any changed fields on a message during - // streaming. - Data MessageDeltaEvent `json:"data,required"` - Event constant.ThreadMessageDelta `json:"event,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Data respjson.Field - Event respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r AssistantStreamEventThreadMessageDelta) RawJSON() string { return r.JSON.raw } -func (r *AssistantStreamEventThreadMessageDelta) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Occurs when a -// [message](https://platform.openai.com/docs/api-reference/messages/object) is -// completed. -type AssistantStreamEventThreadMessageCompleted struct { - // Represents a message within a - // [thread](https://platform.openai.com/docs/api-reference/threads). - Data Message `json:"data,required"` - Event constant.ThreadMessageCompleted `json:"event,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Data respjson.Field - Event respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r AssistantStreamEventThreadMessageCompleted) RawJSON() string { return r.JSON.raw } -func (r *AssistantStreamEventThreadMessageCompleted) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Occurs when a -// [message](https://platform.openai.com/docs/api-reference/messages/object) ends -// before it is completed. -type AssistantStreamEventThreadMessageIncomplete struct { - // Represents a message within a - // [thread](https://platform.openai.com/docs/api-reference/threads). - Data Message `json:"data,required"` - Event constant.ThreadMessageIncomplete `json:"event,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Data respjson.Field - Event respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r AssistantStreamEventThreadMessageIncomplete) RawJSON() string { return r.JSON.raw } -func (r *AssistantStreamEventThreadMessageIncomplete) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Occurs when an -// [error](https://platform.openai.com/docs/guides/error-codes#api-errors) occurs. -// This can happen due to an internal server error or a timeout. -type AssistantStreamEventErrorEvent struct { - Data shared.ErrorObject `json:"data,required"` - Event constant.Error `json:"event,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Data respjson.Field - Event respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r AssistantStreamEventErrorEvent) RawJSON() string { return r.JSON.raw } -func (r *AssistantStreamEventErrorEvent) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// AssistantToolUnion contains all possible properties and values from -// [CodeInterpreterTool], [FileSearchTool], [FunctionTool]. -// -// Use the [AssistantToolUnion.AsAny] method to switch on the variant. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -type AssistantToolUnion struct { - // Any of "code_interpreter", "file_search", "function". - Type string `json:"type"` - // This field is from variant [FileSearchTool]. - FileSearch FileSearchToolFileSearch `json:"file_search"` - // This field is from variant [FunctionTool]. - Function shared.FunctionDefinition `json:"function"` - JSON struct { - Type respjson.Field - FileSearch respjson.Field - Function respjson.Field - raw string - } `json:"-"` -} - -// anyAssistantTool is implemented by each variant of [AssistantToolUnion] to add -// type safety for the return type of [AssistantToolUnion.AsAny] -type anyAssistantTool interface { - implAssistantToolUnion() -} - -func (CodeInterpreterTool) implAssistantToolUnion() {} -func (FileSearchTool) implAssistantToolUnion() {} -func (FunctionTool) implAssistantToolUnion() {} - -// Use the following switch statement to find the correct variant -// -// switch variant := AssistantToolUnion.AsAny().(type) { -// case openai.CodeInterpreterTool: -// case openai.FileSearchTool: -// case openai.FunctionTool: -// default: -// fmt.Errorf("no variant present") -// } -func (u AssistantToolUnion) AsAny() anyAssistantTool { - switch u.Type { - case "code_interpreter": - return u.AsCodeInterpreter() - case "file_search": - return u.AsFileSearch() - case "function": - return u.AsFunction() - } - return nil -} - -func (u AssistantToolUnion) AsCodeInterpreter() (v CodeInterpreterTool) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u AssistantToolUnion) AsFileSearch() (v FileSearchTool) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u AssistantToolUnion) AsFunction() (v FunctionTool) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -// Returns the unmodified JSON received from the API -func (u AssistantToolUnion) RawJSON() string { return u.JSON.raw } - -func (r *AssistantToolUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// ToParam converts this AssistantToolUnion to a AssistantToolUnionParam. -// -// Warning: the fields of the param type will not be present. ToParam should only -// be used at the last possible moment before sending a request. Test for this with -// AssistantToolUnionParam.Overrides() -func (r AssistantToolUnion) ToParam() AssistantToolUnionParam { - return param.Override[AssistantToolUnionParam](json.RawMessage(r.RawJSON())) -} - -func AssistantToolParamOfFunction(function shared.FunctionDefinitionParam) AssistantToolUnionParam { - var variant FunctionToolParam - variant.Function = function - return AssistantToolUnionParam{OfFunction: &variant} -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type AssistantToolUnionParam struct { - OfCodeInterpreter *CodeInterpreterToolParam `json:",omitzero,inline"` - OfFileSearch *FileSearchToolParam `json:",omitzero,inline"` - OfFunction *FunctionToolParam `json:",omitzero,inline"` - paramUnion -} - -func (u AssistantToolUnionParam) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfCodeInterpreter, u.OfFileSearch, u.OfFunction) -} -func (u *AssistantToolUnionParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *AssistantToolUnionParam) asAny() any { - if !param.IsOmitted(u.OfCodeInterpreter) { - return u.OfCodeInterpreter - } else if !param.IsOmitted(u.OfFileSearch) { - return u.OfFileSearch - } else if !param.IsOmitted(u.OfFunction) { - return u.OfFunction - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u AssistantToolUnionParam) GetFileSearch() *FileSearchToolFileSearchParam { - if vt := u.OfFileSearch; vt != nil { - return &vt.FileSearch - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u AssistantToolUnionParam) GetFunction() *shared.FunctionDefinitionParam { - if vt := u.OfFunction; vt != nil { - return &vt.Function - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u AssistantToolUnionParam) GetType() *string { - if vt := u.OfCodeInterpreter; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfFileSearch; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfFunction; vt != nil { - return (*string)(&vt.Type) - } - return nil -} - -func init() { - apijson.RegisterUnion[AssistantToolUnionParam]( - "type", - apijson.Discriminator[CodeInterpreterToolParam]("code_interpreter"), - apijson.Discriminator[FileSearchToolParam]("file_search"), - apijson.Discriminator[FunctionToolParam]("function"), - ) -} - -type CodeInterpreterTool struct { - // The type of tool being defined: `code_interpreter` - Type constant.CodeInterpreter `json:"type,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r CodeInterpreterTool) RawJSON() string { return r.JSON.raw } -func (r *CodeInterpreterTool) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// ToParam converts this CodeInterpreterTool to a CodeInterpreterToolParam. -// -// Warning: the fields of the param type will not be present. ToParam should only -// be used at the last possible moment before sending a request. Test for this with -// CodeInterpreterToolParam.Overrides() -func (r CodeInterpreterTool) ToParam() CodeInterpreterToolParam { - return param.Override[CodeInterpreterToolParam](json.RawMessage(r.RawJSON())) -} - -func NewCodeInterpreterToolParam() CodeInterpreterToolParam { - return CodeInterpreterToolParam{ - Type: "code_interpreter", - } -} - -// This struct has a constant value, construct it with -// [NewCodeInterpreterToolParam]. -type CodeInterpreterToolParam struct { - // The type of tool being defined: `code_interpreter` - Type constant.CodeInterpreter `json:"type,required"` - paramObj -} - -func (r CodeInterpreterToolParam) MarshalJSON() (data []byte, err error) { - type shadow CodeInterpreterToolParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *CodeInterpreterToolParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type FileSearchTool struct { - // The type of tool being defined: `file_search` - Type constant.FileSearch `json:"type,required"` - // Overrides for the file search tool. - FileSearch FileSearchToolFileSearch `json:"file_search"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Type respjson.Field - FileSearch respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r FileSearchTool) RawJSON() string { return r.JSON.raw } -func (r *FileSearchTool) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// ToParam converts this FileSearchTool to a FileSearchToolParam. -// -// Warning: the fields of the param type will not be present. ToParam should only -// be used at the last possible moment before sending a request. Test for this with -// FileSearchToolParam.Overrides() -func (r FileSearchTool) ToParam() FileSearchToolParam { - return param.Override[FileSearchToolParam](json.RawMessage(r.RawJSON())) -} - -// Overrides for the file search tool. -type FileSearchToolFileSearch struct { - // The maximum number of results the file search tool should output. The default is - // 20 for `gpt-4*` models and 5 for `gpt-3.5-turbo`. This number should be between - // 1 and 50 inclusive. - // - // Note that the file search tool may output fewer than `max_num_results` results. - // See the - // [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) - // for more information. - MaxNumResults int64 `json:"max_num_results"` - // The ranking options for the file search. If not specified, the file search tool - // will use the `auto` ranker and a score_threshold of 0. - // - // See the - // [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) - // for more information. - RankingOptions FileSearchToolFileSearchRankingOptions `json:"ranking_options"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - MaxNumResults respjson.Field - RankingOptions respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r FileSearchToolFileSearch) RawJSON() string { return r.JSON.raw } -func (r *FileSearchToolFileSearch) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The ranking options for the file search. If not specified, the file search tool -// will use the `auto` ranker and a score_threshold of 0. -// -// See the -// [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) -// for more information. -type FileSearchToolFileSearchRankingOptions struct { - // The score threshold for the file search. All values must be a floating point - // number between 0 and 1. - ScoreThreshold float64 `json:"score_threshold,required"` - // The ranker to use for the file search. If not specified will use the `auto` - // ranker. - // - // Any of "auto", "default_2024_08_21". - Ranker string `json:"ranker"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ScoreThreshold respjson.Field - Ranker respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r FileSearchToolFileSearchRankingOptions) RawJSON() string { return r.JSON.raw } -func (r *FileSearchToolFileSearchRankingOptions) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The property Type is required. -type FileSearchToolParam struct { - // Overrides for the file search tool. - FileSearch FileSearchToolFileSearchParam `json:"file_search,omitzero"` - // The type of tool being defined: `file_search` - // - // This field can be elided, and will marshal its zero value as "file_search". - Type constant.FileSearch `json:"type,required"` - paramObj -} - -func (r FileSearchToolParam) MarshalJSON() (data []byte, err error) { - type shadow FileSearchToolParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *FileSearchToolParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Overrides for the file search tool. -type FileSearchToolFileSearchParam struct { - // The maximum number of results the file search tool should output. The default is - // 20 for `gpt-4*` models and 5 for `gpt-3.5-turbo`. This number should be between - // 1 and 50 inclusive. - // - // Note that the file search tool may output fewer than `max_num_results` results. - // See the - // [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) - // for more information. - MaxNumResults param.Opt[int64] `json:"max_num_results,omitzero"` - // The ranking options for the file search. If not specified, the file search tool - // will use the `auto` ranker and a score_threshold of 0. - // - // See the - // [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) - // for more information. - RankingOptions FileSearchToolFileSearchRankingOptionsParam `json:"ranking_options,omitzero"` - paramObj -} - -func (r FileSearchToolFileSearchParam) MarshalJSON() (data []byte, err error) { - type shadow FileSearchToolFileSearchParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *FileSearchToolFileSearchParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The ranking options for the file search. If not specified, the file search tool -// will use the `auto` ranker and a score_threshold of 0. -// -// See the -// [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) -// for more information. -// -// The property ScoreThreshold is required. -type FileSearchToolFileSearchRankingOptionsParam struct { - // The score threshold for the file search. All values must be a floating point - // number between 0 and 1. - ScoreThreshold float64 `json:"score_threshold,required"` - // The ranker to use for the file search. If not specified will use the `auto` - // ranker. - // - // Any of "auto", "default_2024_08_21". - Ranker string `json:"ranker,omitzero"` - paramObj -} - -func (r FileSearchToolFileSearchRankingOptionsParam) MarshalJSON() (data []byte, err error) { - type shadow FileSearchToolFileSearchRankingOptionsParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *FileSearchToolFileSearchRankingOptionsParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -func init() { - apijson.RegisterFieldValidator[FileSearchToolFileSearchRankingOptionsParam]( - "ranker", "auto", "default_2024_08_21", - ) -} - -type FunctionTool struct { - Function shared.FunctionDefinition `json:"function,required"` - // The type of tool being defined: `function` - Type constant.Function `json:"type,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Function respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r FunctionTool) RawJSON() string { return r.JSON.raw } -func (r *FunctionTool) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// ToParam converts this FunctionTool to a FunctionToolParam. -// -// Warning: the fields of the param type will not be present. ToParam should only -// be used at the last possible moment before sending a request. Test for this with -// FunctionToolParam.Overrides() -func (r FunctionTool) ToParam() FunctionToolParam { - return param.Override[FunctionToolParam](json.RawMessage(r.RawJSON())) -} - -// The properties Function, Type are required. -type FunctionToolParam struct { - Function shared.FunctionDefinitionParam `json:"function,omitzero,required"` - // The type of tool being defined: `function` - // - // This field can be elided, and will marshal its zero value as "function". - Type constant.Function `json:"type,required"` - paramObj -} - -func (r FunctionToolParam) MarshalJSON() (data []byte, err error) { - type shadow FunctionToolParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *FunctionToolParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type BetaAssistantNewParams struct { - // ID of the model to use. You can use the - // [List models](https://platform.openai.com/docs/api-reference/models/list) API to - // see all of your available models, or see our - // [Model overview](https://platform.openai.com/docs/models) for descriptions of - // them. - Model shared.ChatModel `json:"model,omitzero,required"` - // The description of the assistant. The maximum length is 512 characters. - Description param.Opt[string] `json:"description,omitzero"` - // The system instructions that the assistant uses. The maximum length is 256,000 - // characters. - Instructions param.Opt[string] `json:"instructions,omitzero"` - // The name of the assistant. The maximum length is 256 characters. - Name param.Opt[string] `json:"name,omitzero"` - // 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. - Temperature param.Opt[float64] `json:"temperature,omitzero"` - // 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 param.Opt[float64] `json:"top_p,omitzero"` - // 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, and - // querying for objects via API or the dashboard. - // - // Keys are strings with a maximum length of 64 characters. Values are strings with - // a maximum length of 512 characters. - Metadata shared.Metadata `json:"metadata,omitzero"` - // **o-series models only** - // - // Constrains effort on reasoning for - // [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently - // supported values are `low`, `medium`, and `high`. Reducing reasoning effort can - // result in faster responses and fewer tokens used on reasoning in a response. - // - // Any of "low", "medium", "high". - ReasoningEffort shared.ReasoningEffort `json:"reasoning_effort,omitzero"` - // 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. - ToolResources BetaAssistantNewParamsToolResources `json:"tool_resources,omitzero"` - // Specifies the format that the model must output. Compatible with - // [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), - // [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), - // and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. - // - // Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured - // Outputs which ensures the model will match your supplied JSON schema. Learn more - // in the - // [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). - // - // Setting to `{ "type": "json_object" }` enables JSON mode, which ensures 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 AssistantResponseFormatOptionUnionParam `json:"response_format,omitzero"` - // 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`. - Tools []AssistantToolUnionParam `json:"tools,omitzero"` - paramObj -} - -func (r BetaAssistantNewParams) MarshalJSON() (data []byte, err error) { - type shadow BetaAssistantNewParams - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaAssistantNewParams) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// 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. -type BetaAssistantNewParamsToolResources struct { - CodeInterpreter BetaAssistantNewParamsToolResourcesCodeInterpreter `json:"code_interpreter,omitzero"` - FileSearch BetaAssistantNewParamsToolResourcesFileSearch `json:"file_search,omitzero"` - paramObj -} - -func (r BetaAssistantNewParamsToolResources) MarshalJSON() (data []byte, err error) { - type shadow BetaAssistantNewParamsToolResources - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaAssistantNewParamsToolResources) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type BetaAssistantNewParamsToolResourcesCodeInterpreter struct { - // A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made - // available to the `code_interpreter` tool. There can be a maximum of 20 files - // associated with the tool. - FileIDs []string `json:"file_ids,omitzero"` - paramObj -} - -func (r BetaAssistantNewParamsToolResourcesCodeInterpreter) MarshalJSON() (data []byte, err error) { - type shadow BetaAssistantNewParamsToolResourcesCodeInterpreter - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaAssistantNewParamsToolResourcesCodeInterpreter) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type BetaAssistantNewParamsToolResourcesFileSearch struct { - // The - // [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) - // attached to this assistant. There can be a maximum of 1 vector store attached to - // the assistant. - VectorStoreIDs []string `json:"vector_store_ids,omitzero"` - // A helper to create a - // [vector store](https://platform.openai.com/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. - VectorStores []BetaAssistantNewParamsToolResourcesFileSearchVectorStore `json:"vector_stores,omitzero"` - paramObj -} - -func (r BetaAssistantNewParamsToolResourcesFileSearch) MarshalJSON() (data []byte, err error) { - type shadow BetaAssistantNewParamsToolResourcesFileSearch - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaAssistantNewParamsToolResourcesFileSearch) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type BetaAssistantNewParamsToolResourcesFileSearchVectorStore struct { - // 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, and - // querying for objects via API or the dashboard. - // - // Keys are strings with a maximum length of 64 characters. Values are strings with - // a maximum length of 512 characters. - Metadata shared.Metadata `json:"metadata,omitzero"` - // The chunking strategy used to chunk the file(s). If not set, will use the `auto` - // strategy. - ChunkingStrategy BetaAssistantNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyUnion `json:"chunking_strategy,omitzero"` - // A list of [file](https://platform.openai.com/docs/api-reference/files) IDs to - // add to the vector store. There can be a maximum of 10000 files in a vector - // store. - FileIDs []string `json:"file_ids,omitzero"` - paramObj -} - -func (r BetaAssistantNewParamsToolResourcesFileSearchVectorStore) MarshalJSON() (data []byte, err error) { - type shadow BetaAssistantNewParamsToolResourcesFileSearchVectorStore - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaAssistantNewParamsToolResourcesFileSearchVectorStore) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type BetaAssistantNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyUnion struct { - OfAuto *BetaAssistantNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyAuto `json:",omitzero,inline"` - OfStatic *BetaAssistantNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyStatic `json:",omitzero,inline"` - paramUnion -} - -func (u BetaAssistantNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfAuto, u.OfStatic) -} -func (u *BetaAssistantNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *BetaAssistantNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyUnion) asAny() any { - if !param.IsOmitted(u.OfAuto) { - return u.OfAuto - } else if !param.IsOmitted(u.OfStatic) { - return u.OfStatic - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u BetaAssistantNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyUnion) GetStatic() *BetaAssistantNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyStaticStatic { - if vt := u.OfStatic; vt != nil { - return &vt.Static - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u BetaAssistantNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyUnion) GetType() *string { - if vt := u.OfAuto; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfStatic; vt != nil { - return (*string)(&vt.Type) - } - return nil -} - -func init() { - apijson.RegisterUnion[BetaAssistantNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyUnion]( - "type", - apijson.Discriminator[BetaAssistantNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyAuto]("auto"), - apijson.Discriminator[BetaAssistantNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyStatic]("static"), - ) -} - -func NewBetaAssistantNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyAuto() BetaAssistantNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyAuto { - return BetaAssistantNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyAuto{ - Type: "auto", - } -} - -// The default strategy. This strategy currently uses a `max_chunk_size_tokens` of -// `800` and `chunk_overlap_tokens` of `400`. -// -// This struct has a constant value, construct it with -// [NewBetaAssistantNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyAuto]. -type BetaAssistantNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyAuto struct { - // Always `auto`. - Type constant.Auto `json:"type,required"` - paramObj -} - -func (r BetaAssistantNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyAuto) MarshalJSON() (data []byte, err error) { - type shadow BetaAssistantNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyAuto - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaAssistantNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyAuto) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The properties Static, Type are required. -type BetaAssistantNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyStatic struct { - Static BetaAssistantNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyStaticStatic `json:"static,omitzero,required"` - // Always `static`. - // - // This field can be elided, and will marshal its zero value as "static". - Type constant.Static `json:"type,required"` - paramObj -} - -func (r BetaAssistantNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyStatic) MarshalJSON() (data []byte, err error) { - type shadow BetaAssistantNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyStatic - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaAssistantNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyStatic) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The properties ChunkOverlapTokens, MaxChunkSizeTokens are required. -type BetaAssistantNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyStaticStatic struct { - // The number of tokens that overlap between chunks. The default value is `400`. - // - // Note that the overlap must not exceed half of `max_chunk_size_tokens`. - ChunkOverlapTokens int64 `json:"chunk_overlap_tokens,required"` - // The maximum number of tokens in each chunk. The default value is `800`. The - // minimum value is `100` and the maximum value is `4096`. - MaxChunkSizeTokens int64 `json:"max_chunk_size_tokens,required"` - paramObj -} - -func (r BetaAssistantNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyStaticStatic) MarshalJSON() (data []byte, err error) { - type shadow BetaAssistantNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyStaticStatic - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaAssistantNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyStaticStatic) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type BetaAssistantUpdateParams struct { - // The description of the assistant. The maximum length is 512 characters. - Description param.Opt[string] `json:"description,omitzero"` - // The system instructions that the assistant uses. The maximum length is 256,000 - // characters. - Instructions param.Opt[string] `json:"instructions,omitzero"` - // The name of the assistant. The maximum length is 256 characters. - Name param.Opt[string] `json:"name,omitzero"` - // 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. - Temperature param.Opt[float64] `json:"temperature,omitzero"` - // 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 param.Opt[float64] `json:"top_p,omitzero"` - // 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, and - // querying for objects via API or the dashboard. - // - // Keys are strings with a maximum length of 64 characters. Values are strings with - // a maximum length of 512 characters. - Metadata shared.Metadata `json:"metadata,omitzero"` - // **o-series models only** - // - // Constrains effort on reasoning for - // [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently - // supported values are `low`, `medium`, and `high`. Reducing reasoning effort can - // result in faster responses and fewer tokens used on reasoning in a response. - // - // Any of "low", "medium", "high". - ReasoningEffort shared.ReasoningEffort `json:"reasoning_effort,omitzero"` - // 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. - ToolResources BetaAssistantUpdateParamsToolResources `json:"tool_resources,omitzero"` - // ID of the model to use. You can use the - // [List models](https://platform.openai.com/docs/api-reference/models/list) API to - // see all of your available models, or see our - // [Model overview](https://platform.openai.com/docs/models) for descriptions of - // them. - Model BetaAssistantUpdateParamsModel `json:"model,omitzero"` - // Specifies the format that the model must output. Compatible with - // [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), - // [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), - // and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. - // - // Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured - // Outputs which ensures the model will match your supplied JSON schema. Learn more - // in the - // [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). - // - // Setting to `{ "type": "json_object" }` enables JSON mode, which ensures 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 AssistantResponseFormatOptionUnionParam `json:"response_format,omitzero"` - // 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`. - Tools []AssistantToolUnionParam `json:"tools,omitzero"` - paramObj -} - -func (r BetaAssistantUpdateParams) MarshalJSON() (data []byte, err error) { - type shadow BetaAssistantUpdateParams - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaAssistantUpdateParams) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// ID of the model to use. You can use the -// [List models](https://platform.openai.com/docs/api-reference/models/list) API to -// see all of your available models, or see our -// [Model overview](https://platform.openai.com/docs/models) for descriptions of -// them. -type BetaAssistantUpdateParamsModel string - -const ( - BetaAssistantUpdateParamsModelGPT4_1 BetaAssistantUpdateParamsModel = "gpt-4.1" - BetaAssistantUpdateParamsModelGPT4_1Mini BetaAssistantUpdateParamsModel = "gpt-4.1-mini" - BetaAssistantUpdateParamsModelGPT4_1Nano BetaAssistantUpdateParamsModel = "gpt-4.1-nano" - BetaAssistantUpdateParamsModelGPT4_1_2025_04_14 BetaAssistantUpdateParamsModel = "gpt-4.1-2025-04-14" - BetaAssistantUpdateParamsModelGPT4_1Mini2025_04_14 BetaAssistantUpdateParamsModel = "gpt-4.1-mini-2025-04-14" - BetaAssistantUpdateParamsModelGPT4_1Nano2025_04_14 BetaAssistantUpdateParamsModel = "gpt-4.1-nano-2025-04-14" - BetaAssistantUpdateParamsModelO3Mini BetaAssistantUpdateParamsModel = "o3-mini" - BetaAssistantUpdateParamsModelO3Mini2025_01_31 BetaAssistantUpdateParamsModel = "o3-mini-2025-01-31" - BetaAssistantUpdateParamsModelO1 BetaAssistantUpdateParamsModel = "o1" - BetaAssistantUpdateParamsModelO1_2024_12_17 BetaAssistantUpdateParamsModel = "o1-2024-12-17" - BetaAssistantUpdateParamsModelGPT4o BetaAssistantUpdateParamsModel = "gpt-4o" - BetaAssistantUpdateParamsModelGPT4o2024_11_20 BetaAssistantUpdateParamsModel = "gpt-4o-2024-11-20" - BetaAssistantUpdateParamsModelGPT4o2024_08_06 BetaAssistantUpdateParamsModel = "gpt-4o-2024-08-06" - BetaAssistantUpdateParamsModelGPT4o2024_05_13 BetaAssistantUpdateParamsModel = "gpt-4o-2024-05-13" - BetaAssistantUpdateParamsModelGPT4oMini BetaAssistantUpdateParamsModel = "gpt-4o-mini" - BetaAssistantUpdateParamsModelGPT4oMini2024_07_18 BetaAssistantUpdateParamsModel = "gpt-4o-mini-2024-07-18" - BetaAssistantUpdateParamsModelGPT4_5Preview BetaAssistantUpdateParamsModel = "gpt-4.5-preview" - BetaAssistantUpdateParamsModelGPT4_5Preview2025_02_27 BetaAssistantUpdateParamsModel = "gpt-4.5-preview-2025-02-27" - BetaAssistantUpdateParamsModelGPT4Turbo BetaAssistantUpdateParamsModel = "gpt-4-turbo" - BetaAssistantUpdateParamsModelGPT4Turbo2024_04_09 BetaAssistantUpdateParamsModel = "gpt-4-turbo-2024-04-09" - BetaAssistantUpdateParamsModelGPT4_0125Preview BetaAssistantUpdateParamsModel = "gpt-4-0125-preview" - BetaAssistantUpdateParamsModelGPT4TurboPreview BetaAssistantUpdateParamsModel = "gpt-4-turbo-preview" - BetaAssistantUpdateParamsModelGPT4_1106Preview BetaAssistantUpdateParamsModel = "gpt-4-1106-preview" - BetaAssistantUpdateParamsModelGPT4VisionPreview BetaAssistantUpdateParamsModel = "gpt-4-vision-preview" - BetaAssistantUpdateParamsModelGPT4 BetaAssistantUpdateParamsModel = "gpt-4" - BetaAssistantUpdateParamsModelGPT4_0314 BetaAssistantUpdateParamsModel = "gpt-4-0314" - BetaAssistantUpdateParamsModelGPT4_0613 BetaAssistantUpdateParamsModel = "gpt-4-0613" - BetaAssistantUpdateParamsModelGPT4_32k BetaAssistantUpdateParamsModel = "gpt-4-32k" - BetaAssistantUpdateParamsModelGPT4_32k0314 BetaAssistantUpdateParamsModel = "gpt-4-32k-0314" - BetaAssistantUpdateParamsModelGPT4_32k0613 BetaAssistantUpdateParamsModel = "gpt-4-32k-0613" - BetaAssistantUpdateParamsModelGPT3_5Turbo BetaAssistantUpdateParamsModel = "gpt-3.5-turbo" - BetaAssistantUpdateParamsModelGPT3_5Turbo16k BetaAssistantUpdateParamsModel = "gpt-3.5-turbo-16k" - BetaAssistantUpdateParamsModelGPT3_5Turbo0613 BetaAssistantUpdateParamsModel = "gpt-3.5-turbo-0613" - BetaAssistantUpdateParamsModelGPT3_5Turbo1106 BetaAssistantUpdateParamsModel = "gpt-3.5-turbo-1106" - BetaAssistantUpdateParamsModelGPT3_5Turbo0125 BetaAssistantUpdateParamsModel = "gpt-3.5-turbo-0125" - BetaAssistantUpdateParamsModelGPT3_5Turbo16k0613 BetaAssistantUpdateParamsModel = "gpt-3.5-turbo-16k-0613" -) - -// 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. -type BetaAssistantUpdateParamsToolResources struct { - CodeInterpreter BetaAssistantUpdateParamsToolResourcesCodeInterpreter `json:"code_interpreter,omitzero"` - FileSearch BetaAssistantUpdateParamsToolResourcesFileSearch `json:"file_search,omitzero"` - paramObj -} - -func (r BetaAssistantUpdateParamsToolResources) MarshalJSON() (data []byte, err error) { - type shadow BetaAssistantUpdateParamsToolResources - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaAssistantUpdateParamsToolResources) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type BetaAssistantUpdateParamsToolResourcesCodeInterpreter struct { - // Overrides the list of - // [file](https://platform.openai.com/docs/api-reference/files) IDs made available - // to the `code_interpreter` tool. There can be a maximum of 20 files associated - // with the tool. - FileIDs []string `json:"file_ids,omitzero"` - paramObj -} - -func (r BetaAssistantUpdateParamsToolResourcesCodeInterpreter) MarshalJSON() (data []byte, err error) { - type shadow BetaAssistantUpdateParamsToolResourcesCodeInterpreter - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaAssistantUpdateParamsToolResourcesCodeInterpreter) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type BetaAssistantUpdateParamsToolResourcesFileSearch struct { - // Overrides the - // [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) - // attached to this assistant. There can be a maximum of 1 vector store attached to - // the assistant. - VectorStoreIDs []string `json:"vector_store_ids,omitzero"` - paramObj -} - -func (r BetaAssistantUpdateParamsToolResourcesFileSearch) MarshalJSON() (data []byte, err error) { - type shadow BetaAssistantUpdateParamsToolResourcesFileSearch - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaAssistantUpdateParamsToolResourcesFileSearch) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type BetaAssistantListParams struct { - // 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. - After param.Opt[string] `query:"after,omitzero" json:"-"` - // A cursor for use in pagination. `before` is an object ID that defines your place - // in the list. For instance, if you make a list request and receive 100 objects, - // starting with obj_foo, your subsequent call can include before=obj_foo in order - // to fetch the previous page of the list. - Before param.Opt[string] `query:"before,omitzero" json:"-"` - // A limit on the number of objects to be returned. Limit can range between 1 and - // 100, and the default is 20. - Limit param.Opt[int64] `query:"limit,omitzero" json:"-"` - // Sort order by the `created_at` timestamp of the objects. `asc` for ascending - // order and `desc` for descending order. - // - // Any of "asc", "desc". - Order BetaAssistantListParamsOrder `query:"order,omitzero" json:"-"` - paramObj -} - -// URLQuery serializes [BetaAssistantListParams]'s query parameters as -// `url.Values`. -func (r BetaAssistantListParams) URLQuery() (v url.Values, err error) { - return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ - ArrayFormat: apiquery.ArrayQueryFormatBrackets, - NestedFormat: apiquery.NestedQueryFormatBrackets, - }) -} - -// Sort order by the `created_at` timestamp of the objects. `asc` for ascending -// order and `desc` for descending order. -type BetaAssistantListParamsOrder string - -const ( - BetaAssistantListParamsOrderAsc BetaAssistantListParamsOrder = "asc" - BetaAssistantListParamsOrderDesc BetaAssistantListParamsOrder = "desc" -) diff --git a/vendor/github.com/openai/openai-go/betathread.go b/vendor/github.com/openai/openai-go/betathread.go deleted file mode 100644 index 7e351bf3..00000000 --- a/vendor/github.com/openai/openai-go/betathread.go +++ /dev/null @@ -1,1564 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -package openai - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "net/http" - - "github.com/openai/openai-go/internal/apijson" - "github.com/openai/openai-go/internal/requestconfig" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/packages/param" - "github.com/openai/openai-go/packages/respjson" - "github.com/openai/openai-go/packages/ssestream" - "github.com/openai/openai-go/shared" - "github.com/openai/openai-go/shared/constant" -) - -// BetaThreadService contains methods and other services that help with interacting -// with the openai API. -// -// Note, unlike clients, this service does not read variables from the environment -// automatically. You should not instantiate this service directly, and instead use -// the [NewBetaThreadService] method instead. -// -// Deprecated: The Assistants API is deprecated in favor of the Responses API -type BetaThreadService struct { - Options []option.RequestOption - // Deprecated: The Assistants API is deprecated in favor of the Responses API - Runs BetaThreadRunService - // Deprecated: The Assistants API is deprecated in favor of the Responses API - Messages BetaThreadMessageService -} - -// NewBetaThreadService generates a new service that applies the given options to -// each request. These options are applied after the parent client's options (if -// there is one), and before any request-specific options. -func NewBetaThreadService(opts ...option.RequestOption) (r BetaThreadService) { - r = BetaThreadService{} - r.Options = opts - r.Runs = NewBetaThreadRunService(opts...) - r.Messages = NewBetaThreadMessageService(opts...) - return -} - -// Create a thread. -// -// Deprecated: The Assistants API is deprecated in favor of the Responses API -func (r *BetaThreadService) New(ctx context.Context, body BetaThreadNewParams, opts ...option.RequestOption) (res *Thread, err error) { - opts = append(r.Options[:], opts...) - opts = append([]option.RequestOption{option.WithHeader("OpenAI-Beta", "assistants=v2")}, opts...) - path := "threads" - err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...) - return -} - -// Retrieves a thread. -// -// Deprecated: The Assistants API is deprecated in favor of the Responses API -func (r *BetaThreadService) Get(ctx context.Context, threadID string, opts ...option.RequestOption) (res *Thread, err error) { - opts = append(r.Options[:], opts...) - opts = append([]option.RequestOption{option.WithHeader("OpenAI-Beta", "assistants=v2")}, opts...) - if threadID == "" { - err = errors.New("missing required thread_id parameter") - return - } - path := fmt.Sprintf("threads/%s", threadID) - err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...) - return -} - -// Modifies a thread. -// -// Deprecated: The Assistants API is deprecated in favor of the Responses API -func (r *BetaThreadService) Update(ctx context.Context, threadID string, body BetaThreadUpdateParams, opts ...option.RequestOption) (res *Thread, err error) { - opts = append(r.Options[:], opts...) - opts = append([]option.RequestOption{option.WithHeader("OpenAI-Beta", "assistants=v2")}, opts...) - if threadID == "" { - err = errors.New("missing required thread_id parameter") - return - } - path := fmt.Sprintf("threads/%s", threadID) - err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...) - return -} - -// Delete a thread. -// -// Deprecated: The Assistants API is deprecated in favor of the Responses API -func (r *BetaThreadService) Delete(ctx context.Context, threadID string, opts ...option.RequestOption) (res *ThreadDeleted, err error) { - opts = append(r.Options[:], opts...) - opts = append([]option.RequestOption{option.WithHeader("OpenAI-Beta", "assistants=v2")}, opts...) - if threadID == "" { - err = errors.New("missing required thread_id parameter") - return - } - path := fmt.Sprintf("threads/%s", threadID) - err = requestconfig.ExecuteNewRequest(ctx, http.MethodDelete, path, nil, &res, opts...) - return -} - -// Create a thread and run it in one request. -// -// Deprecated: The Assistants API is deprecated in favor of the Responses API -func (r *BetaThreadService) NewAndRun(ctx context.Context, body BetaThreadNewAndRunParams, opts ...option.RequestOption) (res *Run, err error) { - opts = append(r.Options[:], opts...) - opts = append([]option.RequestOption{option.WithHeader("OpenAI-Beta", "assistants=v2")}, opts...) - path := "threads/runs" - err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...) - return -} - -// Create a thread and run it in one request. -// -// Deprecated: The Assistants API is deprecated in favor of the Responses API -func (r *BetaThreadService) NewAndRunStreaming(ctx context.Context, body BetaThreadNewAndRunParams, opts ...option.RequestOption) (stream *ssestream.Stream[AssistantStreamEventUnion]) { - var ( - raw *http.Response - err error - ) - opts = append(r.Options[:], opts...) - opts = append([]option.RequestOption{option.WithHeader("OpenAI-Beta", "assistants=v2"), option.WithJSONSet("stream", true)}, opts...) - path := "threads/runs" - err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &raw, opts...) - return ssestream.NewStream[AssistantStreamEventUnion](ssestream.NewDecoder(raw), err) -} - -// AssistantResponseFormatOptionUnion contains all possible properties and values -// from [constant.Auto], [shared.ResponseFormatText], -// [shared.ResponseFormatJSONObject], [shared.ResponseFormatJSONSchema]. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -// -// If the underlying value is not a json object, one of the following properties -// will be valid: OfAuto] -type AssistantResponseFormatOptionUnion struct { - // This field will be present if the value is a [constant.Auto] instead of an - // object. - OfAuto constant.Auto `json:",inline"` - Type string `json:"type"` - // This field is from variant [shared.ResponseFormatJSONSchema]. - JSONSchema shared.ResponseFormatJSONSchemaJSONSchema `json:"json_schema"` - JSON struct { - OfAuto respjson.Field - Type respjson.Field - JSONSchema respjson.Field - raw string - } `json:"-"` -} - -func (u AssistantResponseFormatOptionUnion) AsAuto() (v constant.Auto) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u AssistantResponseFormatOptionUnion) AsText() (v shared.ResponseFormatText) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u AssistantResponseFormatOptionUnion) AsJSONObject() (v shared.ResponseFormatJSONObject) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u AssistantResponseFormatOptionUnion) AsJSONSchema() (v shared.ResponseFormatJSONSchema) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -// Returns the unmodified JSON received from the API -func (u AssistantResponseFormatOptionUnion) RawJSON() string { return u.JSON.raw } - -func (r *AssistantResponseFormatOptionUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// ToParam converts this AssistantResponseFormatOptionUnion to a -// AssistantResponseFormatOptionUnionParam. -// -// Warning: the fields of the param type will not be present. ToParam should only -// be used at the last possible moment before sending a request. Test for this with -// AssistantResponseFormatOptionUnionParam.Overrides() -func (r AssistantResponseFormatOptionUnion) ToParam() AssistantResponseFormatOptionUnionParam { - return param.Override[AssistantResponseFormatOptionUnionParam](json.RawMessage(r.RawJSON())) -} - -func AssistantResponseFormatOptionParamOfAuto() AssistantResponseFormatOptionUnionParam { - return AssistantResponseFormatOptionUnionParam{OfAuto: constant.ValueOf[constant.Auto]()} -} - -func AssistantResponseFormatOptionParamOfJSONSchema(jsonSchema shared.ResponseFormatJSONSchemaJSONSchemaParam) AssistantResponseFormatOptionUnionParam { - var variant shared.ResponseFormatJSONSchemaParam - variant.JSONSchema = jsonSchema - return AssistantResponseFormatOptionUnionParam{OfJSONSchema: &variant} -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type AssistantResponseFormatOptionUnionParam struct { - // Construct this variant with constant.ValueOf[constant.Auto]() - OfAuto constant.Auto `json:",omitzero,inline"` - OfText *shared.ResponseFormatTextParam `json:",omitzero,inline"` - OfJSONObject *shared.ResponseFormatJSONObjectParam `json:",omitzero,inline"` - OfJSONSchema *shared.ResponseFormatJSONSchemaParam `json:",omitzero,inline"` - paramUnion -} - -func (u AssistantResponseFormatOptionUnionParam) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfAuto, u.OfText, u.OfJSONObject, u.OfJSONSchema) -} -func (u *AssistantResponseFormatOptionUnionParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *AssistantResponseFormatOptionUnionParam) asAny() any { - if !param.IsOmitted(u.OfAuto) { - return &u.OfAuto - } else if !param.IsOmitted(u.OfText) { - return u.OfText - } else if !param.IsOmitted(u.OfJSONObject) { - return u.OfJSONObject - } else if !param.IsOmitted(u.OfJSONSchema) { - return u.OfJSONSchema - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u AssistantResponseFormatOptionUnionParam) GetJSONSchema() *shared.ResponseFormatJSONSchemaJSONSchemaParam { - if vt := u.OfJSONSchema; vt != nil { - return &vt.JSONSchema - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u AssistantResponseFormatOptionUnionParam) GetType() *string { - if vt := u.OfText; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfJSONObject; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfJSONSchema; vt != nil { - return (*string)(&vt.Type) - } - return nil -} - -// Specifies a tool the model should use. Use to force the model to call a specific -// tool. -type AssistantToolChoice struct { - // The type of the tool. If type is `function`, the function name must be set - // - // Any of "function", "code_interpreter", "file_search". - Type AssistantToolChoiceType `json:"type,required"` - Function AssistantToolChoiceFunction `json:"function"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Type respjson.Field - Function respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r AssistantToolChoice) RawJSON() string { return r.JSON.raw } -func (r *AssistantToolChoice) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// ToParam converts this AssistantToolChoice to a AssistantToolChoiceParam. -// -// Warning: the fields of the param type will not be present. ToParam should only -// be used at the last possible moment before sending a request. Test for this with -// AssistantToolChoiceParam.Overrides() -func (r AssistantToolChoice) ToParam() AssistantToolChoiceParam { - return param.Override[AssistantToolChoiceParam](json.RawMessage(r.RawJSON())) -} - -// The type of the tool. If type is `function`, the function name must be set -type AssistantToolChoiceType string - -const ( - AssistantToolChoiceTypeFunction AssistantToolChoiceType = "function" - AssistantToolChoiceTypeCodeInterpreter AssistantToolChoiceType = "code_interpreter" - AssistantToolChoiceTypeFileSearch AssistantToolChoiceType = "file_search" -) - -// Specifies a tool the model should use. Use to force the model to call a specific -// tool. -// -// The property Type is required. -type AssistantToolChoiceParam struct { - // The type of the tool. If type is `function`, the function name must be set - // - // Any of "function", "code_interpreter", "file_search". - Type AssistantToolChoiceType `json:"type,omitzero,required"` - Function AssistantToolChoiceFunctionParam `json:"function,omitzero"` - paramObj -} - -func (r AssistantToolChoiceParam) MarshalJSON() (data []byte, err error) { - type shadow AssistantToolChoiceParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *AssistantToolChoiceParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type AssistantToolChoiceFunction struct { - // The name of the function to call. - Name string `json:"name,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Name respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r AssistantToolChoiceFunction) RawJSON() string { return r.JSON.raw } -func (r *AssistantToolChoiceFunction) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// ToParam converts this AssistantToolChoiceFunction to a -// AssistantToolChoiceFunctionParam. -// -// Warning: the fields of the param type will not be present. ToParam should only -// be used at the last possible moment before sending a request. Test for this with -// AssistantToolChoiceFunctionParam.Overrides() -func (r AssistantToolChoiceFunction) ToParam() AssistantToolChoiceFunctionParam { - return param.Override[AssistantToolChoiceFunctionParam](json.RawMessage(r.RawJSON())) -} - -// The property Name is required. -type AssistantToolChoiceFunctionParam struct { - // The name of the function to call. - Name string `json:"name,required"` - paramObj -} - -func (r AssistantToolChoiceFunctionParam) MarshalJSON() (data []byte, err error) { - type shadow AssistantToolChoiceFunctionParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *AssistantToolChoiceFunctionParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// AssistantToolChoiceOptionUnion contains all possible properties and values from -// [string], [AssistantToolChoice]. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -// -// If the underlying value is not a json object, one of the following properties -// will be valid: OfAuto] -type AssistantToolChoiceOptionUnion struct { - // This field will be present if the value is a [string] instead of an object. - OfAuto string `json:",inline"` - // This field is from variant [AssistantToolChoice]. - Type AssistantToolChoiceType `json:"type"` - // This field is from variant [AssistantToolChoice]. - Function AssistantToolChoiceFunction `json:"function"` - JSON struct { - OfAuto respjson.Field - Type respjson.Field - Function respjson.Field - raw string - } `json:"-"` -} - -func (u AssistantToolChoiceOptionUnion) AsAuto() (v string) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u AssistantToolChoiceOptionUnion) AsAssistantToolChoice() (v AssistantToolChoice) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -// Returns the unmodified JSON received from the API -func (u AssistantToolChoiceOptionUnion) RawJSON() string { return u.JSON.raw } - -func (r *AssistantToolChoiceOptionUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// ToParam converts this AssistantToolChoiceOptionUnion to a -// AssistantToolChoiceOptionUnionParam. -// -// Warning: the fields of the param type will not be present. ToParam should only -// be used at the last possible moment before sending a request. Test for this with -// AssistantToolChoiceOptionUnionParam.Overrides() -func (r AssistantToolChoiceOptionUnion) ToParam() AssistantToolChoiceOptionUnionParam { - return param.Override[AssistantToolChoiceOptionUnionParam](json.RawMessage(r.RawJSON())) -} - -// `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. -type AssistantToolChoiceOptionAuto string - -const ( - AssistantToolChoiceOptionAutoNone AssistantToolChoiceOptionAuto = "none" - AssistantToolChoiceOptionAutoAuto AssistantToolChoiceOptionAuto = "auto" - AssistantToolChoiceOptionAutoRequired AssistantToolChoiceOptionAuto = "required" -) - -func AssistantToolChoiceOptionParamOfAssistantToolChoice(type_ AssistantToolChoiceType) AssistantToolChoiceOptionUnionParam { - var variant AssistantToolChoiceParam - variant.Type = type_ - return AssistantToolChoiceOptionUnionParam{OfAssistantToolChoice: &variant} -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type AssistantToolChoiceOptionUnionParam struct { - // Check if union is this variant with !param.IsOmitted(union.OfAuto) - OfAuto param.Opt[string] `json:",omitzero,inline"` - OfAssistantToolChoice *AssistantToolChoiceParam `json:",omitzero,inline"` - paramUnion -} - -func (u AssistantToolChoiceOptionUnionParam) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfAuto, u.OfAssistantToolChoice) -} -func (u *AssistantToolChoiceOptionUnionParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *AssistantToolChoiceOptionUnionParam) asAny() any { - if !param.IsOmitted(u.OfAuto) { - return &u.OfAuto - } else if !param.IsOmitted(u.OfAssistantToolChoice) { - return u.OfAssistantToolChoice - } - return nil -} - -// Represents a thread that contains -// [messages](https://platform.openai.com/docs/api-reference/messages). -type Thread struct { - // The identifier, which can be referenced in API endpoints. - ID string `json:"id,required"` - // The Unix timestamp (in seconds) for when the thread was created. - CreatedAt int64 `json:"created_at,required"` - // 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, and - // querying for objects via API or the dashboard. - // - // Keys are strings with a maximum length of 64 characters. Values are strings with - // a maximum length of 512 characters. - Metadata shared.Metadata `json:"metadata,required"` - // The object type, which is always `thread`. - Object constant.Thread `json:"object,required"` - // 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. - ToolResources ThreadToolResources `json:"tool_resources,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ID respjson.Field - CreatedAt respjson.Field - Metadata respjson.Field - Object respjson.Field - ToolResources respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r Thread) RawJSON() string { return r.JSON.raw } -func (r *Thread) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// 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. -type ThreadToolResources struct { - CodeInterpreter ThreadToolResourcesCodeInterpreter `json:"code_interpreter"` - FileSearch ThreadToolResourcesFileSearch `json:"file_search"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - CodeInterpreter respjson.Field - FileSearch respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ThreadToolResources) RawJSON() string { return r.JSON.raw } -func (r *ThreadToolResources) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type ThreadToolResourcesCodeInterpreter struct { - // A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made - // available to the `code_interpreter` tool. There can be a maximum of 20 files - // associated with the tool. - FileIDs []string `json:"file_ids"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - FileIDs respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ThreadToolResourcesCodeInterpreter) RawJSON() string { return r.JSON.raw } -func (r *ThreadToolResourcesCodeInterpreter) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type ThreadToolResourcesFileSearch struct { - // The - // [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) - // attached to this thread. There can be a maximum of 1 vector store attached to - // the thread. - VectorStoreIDs []string `json:"vector_store_ids"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - VectorStoreIDs respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ThreadToolResourcesFileSearch) RawJSON() string { return r.JSON.raw } -func (r *ThreadToolResourcesFileSearch) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type ThreadDeleted struct { - ID string `json:"id,required"` - Deleted bool `json:"deleted,required"` - Object constant.ThreadDeleted `json:"object,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ID respjson.Field - Deleted respjson.Field - Object respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ThreadDeleted) RawJSON() string { return r.JSON.raw } -func (r *ThreadDeleted) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type BetaThreadNewParams struct { - // 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, and - // querying for objects via API or the dashboard. - // - // Keys are strings with a maximum length of 64 characters. Values are strings with - // a maximum length of 512 characters. - Metadata shared.Metadata `json:"metadata,omitzero"` - // 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. - ToolResources BetaThreadNewParamsToolResources `json:"tool_resources,omitzero"` - // A list of [messages](https://platform.openai.com/docs/api-reference/messages) to - // start the thread with. - Messages []BetaThreadNewParamsMessage `json:"messages,omitzero"` - paramObj -} - -func (r BetaThreadNewParams) MarshalJSON() (data []byte, err error) { - type shadow BetaThreadNewParams - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaThreadNewParams) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The properties Content, Role are required. -type BetaThreadNewParamsMessage struct { - // The text contents of the message. - Content BetaThreadNewParamsMessageContentUnion `json:"content,omitzero,required"` - // 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. - // - // Any of "user", "assistant". - Role string `json:"role,omitzero,required"` - // A list of files attached to the message, and the tools they should be added to. - Attachments []BetaThreadNewParamsMessageAttachment `json:"attachments,omitzero"` - // 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, and - // querying for objects via API or the dashboard. - // - // Keys are strings with a maximum length of 64 characters. Values are strings with - // a maximum length of 512 characters. - Metadata shared.Metadata `json:"metadata,omitzero"` - paramObj -} - -func (r BetaThreadNewParamsMessage) MarshalJSON() (data []byte, err error) { - type shadow BetaThreadNewParamsMessage - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaThreadNewParamsMessage) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -func init() { - apijson.RegisterFieldValidator[BetaThreadNewParamsMessage]( - "role", "user", "assistant", - ) -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type BetaThreadNewParamsMessageContentUnion struct { - OfString param.Opt[string] `json:",omitzero,inline"` - OfArrayOfContentParts []MessageContentPartParamUnion `json:",omitzero,inline"` - paramUnion -} - -func (u BetaThreadNewParamsMessageContentUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfString, u.OfArrayOfContentParts) -} -func (u *BetaThreadNewParamsMessageContentUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *BetaThreadNewParamsMessageContentUnion) asAny() any { - if !param.IsOmitted(u.OfString) { - return &u.OfString.Value - } else if !param.IsOmitted(u.OfArrayOfContentParts) { - return &u.OfArrayOfContentParts - } - return nil -} - -type BetaThreadNewParamsMessageAttachment struct { - // The ID of the file to attach to the message. - FileID param.Opt[string] `json:"file_id,omitzero"` - // The tools to add this file to. - Tools []BetaThreadNewParamsMessageAttachmentToolUnion `json:"tools,omitzero"` - paramObj -} - -func (r BetaThreadNewParamsMessageAttachment) MarshalJSON() (data []byte, err error) { - type shadow BetaThreadNewParamsMessageAttachment - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaThreadNewParamsMessageAttachment) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type BetaThreadNewParamsMessageAttachmentToolUnion struct { - OfCodeInterpreter *CodeInterpreterToolParam `json:",omitzero,inline"` - OfFileSearch *BetaThreadNewParamsMessageAttachmentToolFileSearch `json:",omitzero,inline"` - paramUnion -} - -func (u BetaThreadNewParamsMessageAttachmentToolUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfCodeInterpreter, u.OfFileSearch) -} -func (u *BetaThreadNewParamsMessageAttachmentToolUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *BetaThreadNewParamsMessageAttachmentToolUnion) asAny() any { - if !param.IsOmitted(u.OfCodeInterpreter) { - return u.OfCodeInterpreter - } else if !param.IsOmitted(u.OfFileSearch) { - return u.OfFileSearch - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u BetaThreadNewParamsMessageAttachmentToolUnion) GetType() *string { - if vt := u.OfCodeInterpreter; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfFileSearch; vt != nil { - return (*string)(&vt.Type) - } - return nil -} - -func init() { - apijson.RegisterUnion[BetaThreadNewParamsMessageAttachmentToolUnion]( - "type", - apijson.Discriminator[CodeInterpreterToolParam]("code_interpreter"), - apijson.Discriminator[BetaThreadNewParamsMessageAttachmentToolFileSearch]("file_search"), - ) -} - -func NewBetaThreadNewParamsMessageAttachmentToolFileSearch() BetaThreadNewParamsMessageAttachmentToolFileSearch { - return BetaThreadNewParamsMessageAttachmentToolFileSearch{ - Type: "file_search", - } -} - -// This struct has a constant value, construct it with -// [NewBetaThreadNewParamsMessageAttachmentToolFileSearch]. -type BetaThreadNewParamsMessageAttachmentToolFileSearch struct { - // The type of tool being defined: `file_search` - Type constant.FileSearch `json:"type,required"` - paramObj -} - -func (r BetaThreadNewParamsMessageAttachmentToolFileSearch) MarshalJSON() (data []byte, err error) { - type shadow BetaThreadNewParamsMessageAttachmentToolFileSearch - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaThreadNewParamsMessageAttachmentToolFileSearch) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// 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. -type BetaThreadNewParamsToolResources struct { - CodeInterpreter BetaThreadNewParamsToolResourcesCodeInterpreter `json:"code_interpreter,omitzero"` - FileSearch BetaThreadNewParamsToolResourcesFileSearch `json:"file_search,omitzero"` - paramObj -} - -func (r BetaThreadNewParamsToolResources) MarshalJSON() (data []byte, err error) { - type shadow BetaThreadNewParamsToolResources - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaThreadNewParamsToolResources) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type BetaThreadNewParamsToolResourcesCodeInterpreter struct { - // A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made - // available to the `code_interpreter` tool. There can be a maximum of 20 files - // associated with the tool. - FileIDs []string `json:"file_ids,omitzero"` - paramObj -} - -func (r BetaThreadNewParamsToolResourcesCodeInterpreter) MarshalJSON() (data []byte, err error) { - type shadow BetaThreadNewParamsToolResourcesCodeInterpreter - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaThreadNewParamsToolResourcesCodeInterpreter) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type BetaThreadNewParamsToolResourcesFileSearch struct { - // The - // [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) - // attached to this thread. There can be a maximum of 1 vector store attached to - // the thread. - VectorStoreIDs []string `json:"vector_store_ids,omitzero"` - // A helper to create a - // [vector store](https://platform.openai.com/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. - VectorStores []BetaThreadNewParamsToolResourcesFileSearchVectorStore `json:"vector_stores,omitzero"` - paramObj -} - -func (r BetaThreadNewParamsToolResourcesFileSearch) MarshalJSON() (data []byte, err error) { - type shadow BetaThreadNewParamsToolResourcesFileSearch - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaThreadNewParamsToolResourcesFileSearch) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type BetaThreadNewParamsToolResourcesFileSearchVectorStore struct { - // 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, and - // querying for objects via API or the dashboard. - // - // Keys are strings with a maximum length of 64 characters. Values are strings with - // a maximum length of 512 characters. - Metadata shared.Metadata `json:"metadata,omitzero"` - // The chunking strategy used to chunk the file(s). If not set, will use the `auto` - // strategy. - ChunkingStrategy BetaThreadNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyUnion `json:"chunking_strategy,omitzero"` - // A list of [file](https://platform.openai.com/docs/api-reference/files) IDs to - // add to the vector store. There can be a maximum of 10000 files in a vector - // store. - FileIDs []string `json:"file_ids,omitzero"` - paramObj -} - -func (r BetaThreadNewParamsToolResourcesFileSearchVectorStore) MarshalJSON() (data []byte, err error) { - type shadow BetaThreadNewParamsToolResourcesFileSearchVectorStore - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaThreadNewParamsToolResourcesFileSearchVectorStore) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type BetaThreadNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyUnion struct { - OfAuto *BetaThreadNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyAuto `json:",omitzero,inline"` - OfStatic *BetaThreadNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyStatic `json:",omitzero,inline"` - paramUnion -} - -func (u BetaThreadNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfAuto, u.OfStatic) -} -func (u *BetaThreadNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *BetaThreadNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyUnion) asAny() any { - if !param.IsOmitted(u.OfAuto) { - return u.OfAuto - } else if !param.IsOmitted(u.OfStatic) { - return u.OfStatic - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u BetaThreadNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyUnion) GetStatic() *BetaThreadNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyStaticStatic { - if vt := u.OfStatic; vt != nil { - return &vt.Static - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u BetaThreadNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyUnion) GetType() *string { - if vt := u.OfAuto; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfStatic; vt != nil { - return (*string)(&vt.Type) - } - return nil -} - -func init() { - apijson.RegisterUnion[BetaThreadNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyUnion]( - "type", - apijson.Discriminator[BetaThreadNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyAuto]("auto"), - apijson.Discriminator[BetaThreadNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyStatic]("static"), - ) -} - -func NewBetaThreadNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyAuto() BetaThreadNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyAuto { - return BetaThreadNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyAuto{ - Type: "auto", - } -} - -// The default strategy. This strategy currently uses a `max_chunk_size_tokens` of -// `800` and `chunk_overlap_tokens` of `400`. -// -// This struct has a constant value, construct it with -// [NewBetaThreadNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyAuto]. -type BetaThreadNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyAuto struct { - // Always `auto`. - Type constant.Auto `json:"type,required"` - paramObj -} - -func (r BetaThreadNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyAuto) MarshalJSON() (data []byte, err error) { - type shadow BetaThreadNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyAuto - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaThreadNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyAuto) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The properties Static, Type are required. -type BetaThreadNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyStatic struct { - Static BetaThreadNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyStaticStatic `json:"static,omitzero,required"` - // Always `static`. - // - // This field can be elided, and will marshal its zero value as "static". - Type constant.Static `json:"type,required"` - paramObj -} - -func (r BetaThreadNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyStatic) MarshalJSON() (data []byte, err error) { - type shadow BetaThreadNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyStatic - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaThreadNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyStatic) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The properties ChunkOverlapTokens, MaxChunkSizeTokens are required. -type BetaThreadNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyStaticStatic struct { - // The number of tokens that overlap between chunks. The default value is `400`. - // - // Note that the overlap must not exceed half of `max_chunk_size_tokens`. - ChunkOverlapTokens int64 `json:"chunk_overlap_tokens,required"` - // The maximum number of tokens in each chunk. The default value is `800`. The - // minimum value is `100` and the maximum value is `4096`. - MaxChunkSizeTokens int64 `json:"max_chunk_size_tokens,required"` - paramObj -} - -func (r BetaThreadNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyStaticStatic) MarshalJSON() (data []byte, err error) { - type shadow BetaThreadNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyStaticStatic - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaThreadNewParamsToolResourcesFileSearchVectorStoreChunkingStrategyStaticStatic) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type BetaThreadUpdateParams struct { - // 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, and - // querying for objects via API or the dashboard. - // - // Keys are strings with a maximum length of 64 characters. Values are strings with - // a maximum length of 512 characters. - Metadata shared.Metadata `json:"metadata,omitzero"` - // 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. - ToolResources BetaThreadUpdateParamsToolResources `json:"tool_resources,omitzero"` - paramObj -} - -func (r BetaThreadUpdateParams) MarshalJSON() (data []byte, err error) { - type shadow BetaThreadUpdateParams - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaThreadUpdateParams) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// 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. -type BetaThreadUpdateParamsToolResources struct { - CodeInterpreter BetaThreadUpdateParamsToolResourcesCodeInterpreter `json:"code_interpreter,omitzero"` - FileSearch BetaThreadUpdateParamsToolResourcesFileSearch `json:"file_search,omitzero"` - paramObj -} - -func (r BetaThreadUpdateParamsToolResources) MarshalJSON() (data []byte, err error) { - type shadow BetaThreadUpdateParamsToolResources - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaThreadUpdateParamsToolResources) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type BetaThreadUpdateParamsToolResourcesCodeInterpreter struct { - // A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made - // available to the `code_interpreter` tool. There can be a maximum of 20 files - // associated with the tool. - FileIDs []string `json:"file_ids,omitzero"` - paramObj -} - -func (r BetaThreadUpdateParamsToolResourcesCodeInterpreter) MarshalJSON() (data []byte, err error) { - type shadow BetaThreadUpdateParamsToolResourcesCodeInterpreter - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaThreadUpdateParamsToolResourcesCodeInterpreter) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type BetaThreadUpdateParamsToolResourcesFileSearch struct { - // The - // [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) - // attached to this thread. There can be a maximum of 1 vector store attached to - // the thread. - VectorStoreIDs []string `json:"vector_store_ids,omitzero"` - paramObj -} - -func (r BetaThreadUpdateParamsToolResourcesFileSearch) MarshalJSON() (data []byte, err error) { - type shadow BetaThreadUpdateParamsToolResourcesFileSearch - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaThreadUpdateParamsToolResourcesFileSearch) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type BetaThreadNewAndRunParams struct { - // The ID of the - // [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to - // execute this run. - AssistantID string `json:"assistant_id,required"` - // Override the default system message of the assistant. This is useful for - // modifying the behavior on a per-run basis. - Instructions param.Opt[string] `json:"instructions,omitzero"` - // 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. - MaxCompletionTokens param.Opt[int64] `json:"max_completion_tokens,omitzero"` - // 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. - MaxPromptTokens param.Opt[int64] `json:"max_prompt_tokens,omitzero"` - // 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. - Temperature param.Opt[float64] `json:"temperature,omitzero"` - // 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 param.Opt[float64] `json:"top_p,omitzero"` - // Whether to enable - // [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) - // during tool use. - ParallelToolCalls param.Opt[bool] `json:"parallel_tool_calls,omitzero"` - // 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, and - // querying for objects via API or the dashboard. - // - // Keys are strings with a maximum length of 64 characters. Values are strings with - // a maximum length of 512 characters. - Metadata shared.Metadata `json:"metadata,omitzero"` - // The ID of the [Model](https://platform.openai.com/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. - Model shared.ChatModel `json:"model,omitzero"` - // 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. - ToolResources BetaThreadNewAndRunParamsToolResources `json:"tool_resources,omitzero"` - // Override the tools the assistant can use for this run. This is useful for - // modifying the behavior on a per-run basis. - Tools []AssistantToolUnionParam `json:"tools,omitzero"` - // Controls for how a thread will be truncated prior to the run. Use this to - // control the intial context window of the run. - TruncationStrategy BetaThreadNewAndRunParamsTruncationStrategy `json:"truncation_strategy,omitzero"` - // Specifies the format that the model must output. Compatible with - // [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), - // [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), - // and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. - // - // Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured - // Outputs which ensures the model will match your supplied JSON schema. Learn more - // in the - // [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). - // - // Setting to `{ "type": "json_object" }` enables JSON mode, which ensures 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 AssistantResponseFormatOptionUnionParam `json:"response_format,omitzero"` - // Options to create a new thread. If no thread is provided when running a request, - // an empty thread will be created. - Thread BetaThreadNewAndRunParamsThread `json:"thread,omitzero"` - // 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. - ToolChoice AssistantToolChoiceOptionUnionParam `json:"tool_choice,omitzero"` - paramObj -} - -func (r BetaThreadNewAndRunParams) MarshalJSON() (data []byte, err error) { - type shadow BetaThreadNewAndRunParams - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaThreadNewAndRunParams) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Options to create a new thread. If no thread is provided when running a request, -// an empty thread will be created. -type BetaThreadNewAndRunParamsThread struct { - // 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, and - // querying for objects via API or the dashboard. - // - // Keys are strings with a maximum length of 64 characters. Values are strings with - // a maximum length of 512 characters. - Metadata shared.Metadata `json:"metadata,omitzero"` - // 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. - ToolResources BetaThreadNewAndRunParamsThreadToolResources `json:"tool_resources,omitzero"` - // A list of [messages](https://platform.openai.com/docs/api-reference/messages) to - // start the thread with. - Messages []BetaThreadNewAndRunParamsThreadMessage `json:"messages,omitzero"` - paramObj -} - -func (r BetaThreadNewAndRunParamsThread) MarshalJSON() (data []byte, err error) { - type shadow BetaThreadNewAndRunParamsThread - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaThreadNewAndRunParamsThread) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The properties Content, Role are required. -type BetaThreadNewAndRunParamsThreadMessage struct { - // The text contents of the message. - Content BetaThreadNewAndRunParamsThreadMessageContentUnion `json:"content,omitzero,required"` - // 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. - // - // Any of "user", "assistant". - Role string `json:"role,omitzero,required"` - // A list of files attached to the message, and the tools they should be added to. - Attachments []BetaThreadNewAndRunParamsThreadMessageAttachment `json:"attachments,omitzero"` - // 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, and - // querying for objects via API or the dashboard. - // - // Keys are strings with a maximum length of 64 characters. Values are strings with - // a maximum length of 512 characters. - Metadata shared.Metadata `json:"metadata,omitzero"` - paramObj -} - -func (r BetaThreadNewAndRunParamsThreadMessage) MarshalJSON() (data []byte, err error) { - type shadow BetaThreadNewAndRunParamsThreadMessage - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaThreadNewAndRunParamsThreadMessage) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -func init() { - apijson.RegisterFieldValidator[BetaThreadNewAndRunParamsThreadMessage]( - "role", "user", "assistant", - ) -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type BetaThreadNewAndRunParamsThreadMessageContentUnion struct { - OfString param.Opt[string] `json:",omitzero,inline"` - OfArrayOfContentParts []MessageContentPartParamUnion `json:",omitzero,inline"` - paramUnion -} - -func (u BetaThreadNewAndRunParamsThreadMessageContentUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfString, u.OfArrayOfContentParts) -} -func (u *BetaThreadNewAndRunParamsThreadMessageContentUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *BetaThreadNewAndRunParamsThreadMessageContentUnion) asAny() any { - if !param.IsOmitted(u.OfString) { - return &u.OfString.Value - } else if !param.IsOmitted(u.OfArrayOfContentParts) { - return &u.OfArrayOfContentParts - } - return nil -} - -type BetaThreadNewAndRunParamsThreadMessageAttachment struct { - // The ID of the file to attach to the message. - FileID param.Opt[string] `json:"file_id,omitzero"` - // The tools to add this file to. - Tools []BetaThreadNewAndRunParamsThreadMessageAttachmentToolUnion `json:"tools,omitzero"` - paramObj -} - -func (r BetaThreadNewAndRunParamsThreadMessageAttachment) MarshalJSON() (data []byte, err error) { - type shadow BetaThreadNewAndRunParamsThreadMessageAttachment - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaThreadNewAndRunParamsThreadMessageAttachment) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type BetaThreadNewAndRunParamsThreadMessageAttachmentToolUnion struct { - OfCodeInterpreter *CodeInterpreterToolParam `json:",omitzero,inline"` - OfFileSearch *BetaThreadNewAndRunParamsThreadMessageAttachmentToolFileSearch `json:",omitzero,inline"` - paramUnion -} - -func (u BetaThreadNewAndRunParamsThreadMessageAttachmentToolUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfCodeInterpreter, u.OfFileSearch) -} -func (u *BetaThreadNewAndRunParamsThreadMessageAttachmentToolUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *BetaThreadNewAndRunParamsThreadMessageAttachmentToolUnion) asAny() any { - if !param.IsOmitted(u.OfCodeInterpreter) { - return u.OfCodeInterpreter - } else if !param.IsOmitted(u.OfFileSearch) { - return u.OfFileSearch - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u BetaThreadNewAndRunParamsThreadMessageAttachmentToolUnion) GetType() *string { - if vt := u.OfCodeInterpreter; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfFileSearch; vt != nil { - return (*string)(&vt.Type) - } - return nil -} - -func init() { - apijson.RegisterUnion[BetaThreadNewAndRunParamsThreadMessageAttachmentToolUnion]( - "type", - apijson.Discriminator[CodeInterpreterToolParam]("code_interpreter"), - apijson.Discriminator[BetaThreadNewAndRunParamsThreadMessageAttachmentToolFileSearch]("file_search"), - ) -} - -func NewBetaThreadNewAndRunParamsThreadMessageAttachmentToolFileSearch() BetaThreadNewAndRunParamsThreadMessageAttachmentToolFileSearch { - return BetaThreadNewAndRunParamsThreadMessageAttachmentToolFileSearch{ - Type: "file_search", - } -} - -// This struct has a constant value, construct it with -// [NewBetaThreadNewAndRunParamsThreadMessageAttachmentToolFileSearch]. -type BetaThreadNewAndRunParamsThreadMessageAttachmentToolFileSearch struct { - // The type of tool being defined: `file_search` - Type constant.FileSearch `json:"type,required"` - paramObj -} - -func (r BetaThreadNewAndRunParamsThreadMessageAttachmentToolFileSearch) MarshalJSON() (data []byte, err error) { - type shadow BetaThreadNewAndRunParamsThreadMessageAttachmentToolFileSearch - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaThreadNewAndRunParamsThreadMessageAttachmentToolFileSearch) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// 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. -type BetaThreadNewAndRunParamsThreadToolResources struct { - CodeInterpreter BetaThreadNewAndRunParamsThreadToolResourcesCodeInterpreter `json:"code_interpreter,omitzero"` - FileSearch BetaThreadNewAndRunParamsThreadToolResourcesFileSearch `json:"file_search,omitzero"` - paramObj -} - -func (r BetaThreadNewAndRunParamsThreadToolResources) MarshalJSON() (data []byte, err error) { - type shadow BetaThreadNewAndRunParamsThreadToolResources - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaThreadNewAndRunParamsThreadToolResources) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type BetaThreadNewAndRunParamsThreadToolResourcesCodeInterpreter struct { - // A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made - // available to the `code_interpreter` tool. There can be a maximum of 20 files - // associated with the tool. - FileIDs []string `json:"file_ids,omitzero"` - paramObj -} - -func (r BetaThreadNewAndRunParamsThreadToolResourcesCodeInterpreter) MarshalJSON() (data []byte, err error) { - type shadow BetaThreadNewAndRunParamsThreadToolResourcesCodeInterpreter - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaThreadNewAndRunParamsThreadToolResourcesCodeInterpreter) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type BetaThreadNewAndRunParamsThreadToolResourcesFileSearch struct { - // The - // [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) - // attached to this thread. There can be a maximum of 1 vector store attached to - // the thread. - VectorStoreIDs []string `json:"vector_store_ids,omitzero"` - // A helper to create a - // [vector store](https://platform.openai.com/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. - VectorStores []BetaThreadNewAndRunParamsThreadToolResourcesFileSearchVectorStore `json:"vector_stores,omitzero"` - paramObj -} - -func (r BetaThreadNewAndRunParamsThreadToolResourcesFileSearch) MarshalJSON() (data []byte, err error) { - type shadow BetaThreadNewAndRunParamsThreadToolResourcesFileSearch - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaThreadNewAndRunParamsThreadToolResourcesFileSearch) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type BetaThreadNewAndRunParamsThreadToolResourcesFileSearchVectorStore struct { - // 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, and - // querying for objects via API or the dashboard. - // - // Keys are strings with a maximum length of 64 characters. Values are strings with - // a maximum length of 512 characters. - Metadata shared.Metadata `json:"metadata,omitzero"` - // The chunking strategy used to chunk the file(s). If not set, will use the `auto` - // strategy. - ChunkingStrategy BetaThreadNewAndRunParamsThreadToolResourcesFileSearchVectorStoreChunkingStrategyUnion `json:"chunking_strategy,omitzero"` - // A list of [file](https://platform.openai.com/docs/api-reference/files) IDs to - // add to the vector store. There can be a maximum of 10000 files in a vector - // store. - FileIDs []string `json:"file_ids,omitzero"` - paramObj -} - -func (r BetaThreadNewAndRunParamsThreadToolResourcesFileSearchVectorStore) MarshalJSON() (data []byte, err error) { - type shadow BetaThreadNewAndRunParamsThreadToolResourcesFileSearchVectorStore - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaThreadNewAndRunParamsThreadToolResourcesFileSearchVectorStore) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type BetaThreadNewAndRunParamsThreadToolResourcesFileSearchVectorStoreChunkingStrategyUnion struct { - OfAuto *BetaThreadNewAndRunParamsThreadToolResourcesFileSearchVectorStoreChunkingStrategyAuto `json:",omitzero,inline"` - OfStatic *BetaThreadNewAndRunParamsThreadToolResourcesFileSearchVectorStoreChunkingStrategyStatic `json:",omitzero,inline"` - paramUnion -} - -func (u BetaThreadNewAndRunParamsThreadToolResourcesFileSearchVectorStoreChunkingStrategyUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfAuto, u.OfStatic) -} -func (u *BetaThreadNewAndRunParamsThreadToolResourcesFileSearchVectorStoreChunkingStrategyUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *BetaThreadNewAndRunParamsThreadToolResourcesFileSearchVectorStoreChunkingStrategyUnion) asAny() any { - if !param.IsOmitted(u.OfAuto) { - return u.OfAuto - } else if !param.IsOmitted(u.OfStatic) { - return u.OfStatic - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u BetaThreadNewAndRunParamsThreadToolResourcesFileSearchVectorStoreChunkingStrategyUnion) GetStatic() *BetaThreadNewAndRunParamsThreadToolResourcesFileSearchVectorStoreChunkingStrategyStaticStatic { - if vt := u.OfStatic; vt != nil { - return &vt.Static - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u BetaThreadNewAndRunParamsThreadToolResourcesFileSearchVectorStoreChunkingStrategyUnion) GetType() *string { - if vt := u.OfAuto; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfStatic; vt != nil { - return (*string)(&vt.Type) - } - return nil -} - -func init() { - apijson.RegisterUnion[BetaThreadNewAndRunParamsThreadToolResourcesFileSearchVectorStoreChunkingStrategyUnion]( - "type", - apijson.Discriminator[BetaThreadNewAndRunParamsThreadToolResourcesFileSearchVectorStoreChunkingStrategyAuto]("auto"), - apijson.Discriminator[BetaThreadNewAndRunParamsThreadToolResourcesFileSearchVectorStoreChunkingStrategyStatic]("static"), - ) -} - -func NewBetaThreadNewAndRunParamsThreadToolResourcesFileSearchVectorStoreChunkingStrategyAuto() BetaThreadNewAndRunParamsThreadToolResourcesFileSearchVectorStoreChunkingStrategyAuto { - return BetaThreadNewAndRunParamsThreadToolResourcesFileSearchVectorStoreChunkingStrategyAuto{ - Type: "auto", - } -} - -// The default strategy. This strategy currently uses a `max_chunk_size_tokens` of -// `800` and `chunk_overlap_tokens` of `400`. -// -// This struct has a constant value, construct it with -// [NewBetaThreadNewAndRunParamsThreadToolResourcesFileSearchVectorStoreChunkingStrategyAuto]. -type BetaThreadNewAndRunParamsThreadToolResourcesFileSearchVectorStoreChunkingStrategyAuto struct { - // Always `auto`. - Type constant.Auto `json:"type,required"` - paramObj -} - -func (r BetaThreadNewAndRunParamsThreadToolResourcesFileSearchVectorStoreChunkingStrategyAuto) MarshalJSON() (data []byte, err error) { - type shadow BetaThreadNewAndRunParamsThreadToolResourcesFileSearchVectorStoreChunkingStrategyAuto - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaThreadNewAndRunParamsThreadToolResourcesFileSearchVectorStoreChunkingStrategyAuto) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The properties Static, Type are required. -type BetaThreadNewAndRunParamsThreadToolResourcesFileSearchVectorStoreChunkingStrategyStatic struct { - Static BetaThreadNewAndRunParamsThreadToolResourcesFileSearchVectorStoreChunkingStrategyStaticStatic `json:"static,omitzero,required"` - // Always `static`. - // - // This field can be elided, and will marshal its zero value as "static". - Type constant.Static `json:"type,required"` - paramObj -} - -func (r BetaThreadNewAndRunParamsThreadToolResourcesFileSearchVectorStoreChunkingStrategyStatic) MarshalJSON() (data []byte, err error) { - type shadow BetaThreadNewAndRunParamsThreadToolResourcesFileSearchVectorStoreChunkingStrategyStatic - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaThreadNewAndRunParamsThreadToolResourcesFileSearchVectorStoreChunkingStrategyStatic) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The properties ChunkOverlapTokens, MaxChunkSizeTokens are required. -type BetaThreadNewAndRunParamsThreadToolResourcesFileSearchVectorStoreChunkingStrategyStaticStatic struct { - // The number of tokens that overlap between chunks. The default value is `400`. - // - // Note that the overlap must not exceed half of `max_chunk_size_tokens`. - ChunkOverlapTokens int64 `json:"chunk_overlap_tokens,required"` - // The maximum number of tokens in each chunk. The default value is `800`. The - // minimum value is `100` and the maximum value is `4096`. - MaxChunkSizeTokens int64 `json:"max_chunk_size_tokens,required"` - paramObj -} - -func (r BetaThreadNewAndRunParamsThreadToolResourcesFileSearchVectorStoreChunkingStrategyStaticStatic) MarshalJSON() (data []byte, err error) { - type shadow BetaThreadNewAndRunParamsThreadToolResourcesFileSearchVectorStoreChunkingStrategyStaticStatic - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaThreadNewAndRunParamsThreadToolResourcesFileSearchVectorStoreChunkingStrategyStaticStatic) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// 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. -type BetaThreadNewAndRunParamsToolResources struct { - CodeInterpreter BetaThreadNewAndRunParamsToolResourcesCodeInterpreter `json:"code_interpreter,omitzero"` - FileSearch BetaThreadNewAndRunParamsToolResourcesFileSearch `json:"file_search,omitzero"` - paramObj -} - -func (r BetaThreadNewAndRunParamsToolResources) MarshalJSON() (data []byte, err error) { - type shadow BetaThreadNewAndRunParamsToolResources - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaThreadNewAndRunParamsToolResources) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type BetaThreadNewAndRunParamsToolResourcesCodeInterpreter struct { - // A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made - // available to the `code_interpreter` tool. There can be a maximum of 20 files - // associated with the tool. - FileIDs []string `json:"file_ids,omitzero"` - paramObj -} - -func (r BetaThreadNewAndRunParamsToolResourcesCodeInterpreter) MarshalJSON() (data []byte, err error) { - type shadow BetaThreadNewAndRunParamsToolResourcesCodeInterpreter - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaThreadNewAndRunParamsToolResourcesCodeInterpreter) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type BetaThreadNewAndRunParamsToolResourcesFileSearch struct { - // The ID of the - // [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) - // attached to this assistant. There can be a maximum of 1 vector store attached to - // the assistant. - VectorStoreIDs []string `json:"vector_store_ids,omitzero"` - paramObj -} - -func (r BetaThreadNewAndRunParamsToolResourcesFileSearch) MarshalJSON() (data []byte, err error) { - type shadow BetaThreadNewAndRunParamsToolResourcesFileSearch - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaThreadNewAndRunParamsToolResourcesFileSearch) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Controls for how a thread will be truncated prior to the run. Use this to -// control the intial context window of the run. -// -// The property Type is required. -type BetaThreadNewAndRunParamsTruncationStrategy struct { - // 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`. - // - // Any of "auto", "last_messages". - Type string `json:"type,omitzero,required"` - // The number of most recent messages from the thread when constructing the context - // for the run. - LastMessages param.Opt[int64] `json:"last_messages,omitzero"` - paramObj -} - -func (r BetaThreadNewAndRunParamsTruncationStrategy) MarshalJSON() (data []byte, err error) { - type shadow BetaThreadNewAndRunParamsTruncationStrategy - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaThreadNewAndRunParamsTruncationStrategy) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -func init() { - apijson.RegisterFieldValidator[BetaThreadNewAndRunParamsTruncationStrategy]( - "type", "auto", "last_messages", - ) -} diff --git a/vendor/github.com/openai/openai-go/betathreadmessage.go b/vendor/github.com/openai/openai-go/betathreadmessage.go deleted file mode 100644 index 3078e0a6..00000000 --- a/vendor/github.com/openai/openai-go/betathreadmessage.go +++ /dev/null @@ -1,1712 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -package openai - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "net/http" - "net/url" - - "github.com/openai/openai-go/internal/apijson" - "github.com/openai/openai-go/internal/apiquery" - "github.com/openai/openai-go/internal/requestconfig" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/packages/pagination" - "github.com/openai/openai-go/packages/param" - "github.com/openai/openai-go/packages/respjson" - "github.com/openai/openai-go/shared" - "github.com/openai/openai-go/shared/constant" -) - -// BetaThreadMessageService contains methods and other services that help with -// interacting with the openai API. -// -// Note, unlike clients, this service does not read variables from the environment -// automatically. You should not instantiate this service directly, and instead use -// the [NewBetaThreadMessageService] method instead. -// -// Deprecated: The Assistants API is deprecated in favor of the Responses API -type BetaThreadMessageService struct { - Options []option.RequestOption -} - -// NewBetaThreadMessageService generates a new service that applies the given -// options to each request. These options are applied after the parent client's -// options (if there is one), and before any request-specific options. -func NewBetaThreadMessageService(opts ...option.RequestOption) (r BetaThreadMessageService) { - r = BetaThreadMessageService{} - r.Options = opts - return -} - -// Create a message. -// -// Deprecated: The Assistants API is deprecated in favor of the Responses API -func (r *BetaThreadMessageService) New(ctx context.Context, threadID string, body BetaThreadMessageNewParams, opts ...option.RequestOption) (res *Message, err error) { - opts = append(r.Options[:], opts...) - opts = append([]option.RequestOption{option.WithHeader("OpenAI-Beta", "assistants=v2")}, opts...) - if threadID == "" { - err = errors.New("missing required thread_id parameter") - return - } - path := fmt.Sprintf("threads/%s/messages", threadID) - err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...) - return -} - -// Retrieve a message. -// -// Deprecated: The Assistants API is deprecated in favor of the Responses API -func (r *BetaThreadMessageService) Get(ctx context.Context, threadID string, messageID string, opts ...option.RequestOption) (res *Message, err error) { - opts = append(r.Options[:], opts...) - opts = append([]option.RequestOption{option.WithHeader("OpenAI-Beta", "assistants=v2")}, opts...) - if threadID == "" { - err = errors.New("missing required thread_id parameter") - return - } - if messageID == "" { - err = errors.New("missing required message_id parameter") - return - } - path := fmt.Sprintf("threads/%s/messages/%s", threadID, messageID) - err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...) - return -} - -// Modifies a message. -// -// Deprecated: The Assistants API is deprecated in favor of the Responses API -func (r *BetaThreadMessageService) Update(ctx context.Context, threadID string, messageID string, body BetaThreadMessageUpdateParams, opts ...option.RequestOption) (res *Message, err error) { - opts = append(r.Options[:], opts...) - opts = append([]option.RequestOption{option.WithHeader("OpenAI-Beta", "assistants=v2")}, opts...) - if threadID == "" { - err = errors.New("missing required thread_id parameter") - return - } - if messageID == "" { - err = errors.New("missing required message_id parameter") - return - } - path := fmt.Sprintf("threads/%s/messages/%s", threadID, messageID) - err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...) - return -} - -// Returns a list of messages for a given thread. -// -// Deprecated: The Assistants API is deprecated in favor of the Responses API -func (r *BetaThreadMessageService) List(ctx context.Context, threadID string, query BetaThreadMessageListParams, opts ...option.RequestOption) (res *pagination.CursorPage[Message], err error) { - var raw *http.Response - opts = append(r.Options[:], opts...) - opts = append([]option.RequestOption{option.WithHeader("OpenAI-Beta", "assistants=v2"), option.WithResponseInto(&raw)}, opts...) - if threadID == "" { - err = errors.New("missing required thread_id parameter") - return - } - path := fmt.Sprintf("threads/%s/messages", threadID) - cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, query, &res, opts...) - if err != nil { - return nil, err - } - err = cfg.Execute() - if err != nil { - return nil, err - } - res.SetPageConfig(cfg, raw) - return res, nil -} - -// Returns a list of messages for a given thread. -// -// Deprecated: The Assistants API is deprecated in favor of the Responses API -func (r *BetaThreadMessageService) ListAutoPaging(ctx context.Context, threadID string, query BetaThreadMessageListParams, opts ...option.RequestOption) *pagination.CursorPageAutoPager[Message] { - return pagination.NewCursorPageAutoPager(r.List(ctx, threadID, query, opts...)) -} - -// Deletes a message. -// -// Deprecated: The Assistants API is deprecated in favor of the Responses API -func (r *BetaThreadMessageService) Delete(ctx context.Context, threadID string, messageID string, opts ...option.RequestOption) (res *MessageDeleted, err error) { - opts = append(r.Options[:], opts...) - opts = append([]option.RequestOption{option.WithHeader("OpenAI-Beta", "assistants=v2")}, opts...) - if threadID == "" { - err = errors.New("missing required thread_id parameter") - return - } - if messageID == "" { - err = errors.New("missing required message_id parameter") - return - } - path := fmt.Sprintf("threads/%s/messages/%s", threadID, messageID) - err = requestconfig.ExecuteNewRequest(ctx, http.MethodDelete, path, nil, &res, opts...) - return -} - -// AnnotationUnion contains all possible properties and values from -// [FileCitationAnnotation], [FilePathAnnotation]. -// -// Use the [AnnotationUnion.AsAny] method to switch on the variant. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -type AnnotationUnion struct { - EndIndex int64 `json:"end_index"` - // This field is from variant [FileCitationAnnotation]. - FileCitation FileCitationAnnotationFileCitation `json:"file_citation"` - StartIndex int64 `json:"start_index"` - Text string `json:"text"` - // Any of "file_citation", "file_path". - Type string `json:"type"` - // This field is from variant [FilePathAnnotation]. - FilePath FilePathAnnotationFilePath `json:"file_path"` - JSON struct { - EndIndex respjson.Field - FileCitation respjson.Field - StartIndex respjson.Field - Text respjson.Field - Type respjson.Field - FilePath respjson.Field - raw string - } `json:"-"` -} - -// anyAnnotation is implemented by each variant of [AnnotationUnion] to add type -// safety for the return type of [AnnotationUnion.AsAny] -type anyAnnotation interface { - implAnnotationUnion() -} - -func (FileCitationAnnotation) implAnnotationUnion() {} -func (FilePathAnnotation) implAnnotationUnion() {} - -// Use the following switch statement to find the correct variant -// -// switch variant := AnnotationUnion.AsAny().(type) { -// case openai.FileCitationAnnotation: -// case openai.FilePathAnnotation: -// default: -// fmt.Errorf("no variant present") -// } -func (u AnnotationUnion) AsAny() anyAnnotation { - switch u.Type { - case "file_citation": - return u.AsFileCitation() - case "file_path": - return u.AsFilePath() - } - return nil -} - -func (u AnnotationUnion) AsFileCitation() (v FileCitationAnnotation) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u AnnotationUnion) AsFilePath() (v FilePathAnnotation) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -// Returns the unmodified JSON received from the API -func (u AnnotationUnion) RawJSON() string { return u.JSON.raw } - -func (r *AnnotationUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// AnnotationDeltaUnion contains all possible properties and values from -// [FileCitationDeltaAnnotation], [FilePathDeltaAnnotation]. -// -// Use the [AnnotationDeltaUnion.AsAny] method to switch on the variant. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -type AnnotationDeltaUnion struct { - Index int64 `json:"index"` - // Any of "file_citation", "file_path". - Type string `json:"type"` - EndIndex int64 `json:"end_index"` - // This field is from variant [FileCitationDeltaAnnotation]. - FileCitation FileCitationDeltaAnnotationFileCitation `json:"file_citation"` - StartIndex int64 `json:"start_index"` - Text string `json:"text"` - // This field is from variant [FilePathDeltaAnnotation]. - FilePath FilePathDeltaAnnotationFilePath `json:"file_path"` - JSON struct { - Index respjson.Field - Type respjson.Field - EndIndex respjson.Field - FileCitation respjson.Field - StartIndex respjson.Field - Text respjson.Field - FilePath respjson.Field - raw string - } `json:"-"` -} - -// anyAnnotationDelta is implemented by each variant of [AnnotationDeltaUnion] to -// add type safety for the return type of [AnnotationDeltaUnion.AsAny] -type anyAnnotationDelta interface { - implAnnotationDeltaUnion() -} - -func (FileCitationDeltaAnnotation) implAnnotationDeltaUnion() {} -func (FilePathDeltaAnnotation) implAnnotationDeltaUnion() {} - -// Use the following switch statement to find the correct variant -// -// switch variant := AnnotationDeltaUnion.AsAny().(type) { -// case openai.FileCitationDeltaAnnotation: -// case openai.FilePathDeltaAnnotation: -// default: -// fmt.Errorf("no variant present") -// } -func (u AnnotationDeltaUnion) AsAny() anyAnnotationDelta { - switch u.Type { - case "file_citation": - return u.AsFileCitation() - case "file_path": - return u.AsFilePath() - } - return nil -} - -func (u AnnotationDeltaUnion) AsFileCitation() (v FileCitationDeltaAnnotation) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u AnnotationDeltaUnion) AsFilePath() (v FilePathDeltaAnnotation) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -// Returns the unmodified JSON received from the API -func (u AnnotationDeltaUnion) RawJSON() string { return u.JSON.raw } - -func (r *AnnotationDeltaUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// 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. -type FileCitationAnnotation struct { - EndIndex int64 `json:"end_index,required"` - FileCitation FileCitationAnnotationFileCitation `json:"file_citation,required"` - StartIndex int64 `json:"start_index,required"` - // The text in the message content that needs to be replaced. - Text string `json:"text,required"` - // Always `file_citation`. - Type constant.FileCitation `json:"type,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - EndIndex respjson.Field - FileCitation respjson.Field - StartIndex respjson.Field - Text respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r FileCitationAnnotation) RawJSON() string { return r.JSON.raw } -func (r *FileCitationAnnotation) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type FileCitationAnnotationFileCitation struct { - // The ID of the specific File the citation is from. - FileID string `json:"file_id,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - FileID respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r FileCitationAnnotationFileCitation) RawJSON() string { return r.JSON.raw } -func (r *FileCitationAnnotationFileCitation) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// 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. -type FileCitationDeltaAnnotation struct { - // The index of the annotation in the text content part. - Index int64 `json:"index,required"` - // Always `file_citation`. - Type constant.FileCitation `json:"type,required"` - EndIndex int64 `json:"end_index"` - FileCitation FileCitationDeltaAnnotationFileCitation `json:"file_citation"` - StartIndex int64 `json:"start_index"` - // The text in the message content that needs to be replaced. - Text string `json:"text"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Index respjson.Field - Type respjson.Field - EndIndex respjson.Field - FileCitation respjson.Field - StartIndex respjson.Field - Text respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r FileCitationDeltaAnnotation) RawJSON() string { return r.JSON.raw } -func (r *FileCitationDeltaAnnotation) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type FileCitationDeltaAnnotationFileCitation struct { - // The ID of the specific File the citation is from. - FileID string `json:"file_id"` - // The specific quote in the file. - Quote string `json:"quote"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - FileID respjson.Field - Quote respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r FileCitationDeltaAnnotationFileCitation) RawJSON() string { return r.JSON.raw } -func (r *FileCitationDeltaAnnotationFileCitation) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// A URL for the file that's generated when the assistant used the -// `code_interpreter` tool to generate a file. -type FilePathAnnotation struct { - EndIndex int64 `json:"end_index,required"` - FilePath FilePathAnnotationFilePath `json:"file_path,required"` - StartIndex int64 `json:"start_index,required"` - // The text in the message content that needs to be replaced. - Text string `json:"text,required"` - // Always `file_path`. - Type constant.FilePath `json:"type,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - EndIndex respjson.Field - FilePath respjson.Field - StartIndex respjson.Field - Text respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r FilePathAnnotation) RawJSON() string { return r.JSON.raw } -func (r *FilePathAnnotation) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type FilePathAnnotationFilePath struct { - // The ID of the file that was generated. - FileID string `json:"file_id,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - FileID respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r FilePathAnnotationFilePath) RawJSON() string { return r.JSON.raw } -func (r *FilePathAnnotationFilePath) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// A URL for the file that's generated when the assistant used the -// `code_interpreter` tool to generate a file. -type FilePathDeltaAnnotation struct { - // The index of the annotation in the text content part. - Index int64 `json:"index,required"` - // Always `file_path`. - Type constant.FilePath `json:"type,required"` - EndIndex int64 `json:"end_index"` - FilePath FilePathDeltaAnnotationFilePath `json:"file_path"` - StartIndex int64 `json:"start_index"` - // The text in the message content that needs to be replaced. - Text string `json:"text"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Index respjson.Field - Type respjson.Field - EndIndex respjson.Field - FilePath respjson.Field - StartIndex respjson.Field - Text respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r FilePathDeltaAnnotation) RawJSON() string { return r.JSON.raw } -func (r *FilePathDeltaAnnotation) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type FilePathDeltaAnnotationFilePath struct { - // The ID of the file that was generated. - FileID string `json:"file_id"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - FileID respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r FilePathDeltaAnnotationFilePath) RawJSON() string { return r.JSON.raw } -func (r *FilePathDeltaAnnotationFilePath) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type ImageFile struct { - // The [File](https://platform.openai.com/docs/api-reference/files) ID of the image - // in the message content. Set `purpose="vision"` when uploading the File if you - // need to later display the file content. - FileID string `json:"file_id,required"` - // Specifies the detail level of the image if specified by the user. `low` uses - // fewer tokens, you can opt in to high resolution using `high`. - // - // Any of "auto", "low", "high". - Detail ImageFileDetail `json:"detail"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - FileID respjson.Field - Detail respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ImageFile) RawJSON() string { return r.JSON.raw } -func (r *ImageFile) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// ToParam converts this ImageFile to a ImageFileParam. -// -// Warning: the fields of the param type will not be present. ToParam should only -// be used at the last possible moment before sending a request. Test for this with -// ImageFileParam.Overrides() -func (r ImageFile) ToParam() ImageFileParam { - return param.Override[ImageFileParam](json.RawMessage(r.RawJSON())) -} - -// Specifies the detail level of the image if specified by the user. `low` uses -// fewer tokens, you can opt in to high resolution using `high`. -type ImageFileDetail string - -const ( - ImageFileDetailAuto ImageFileDetail = "auto" - ImageFileDetailLow ImageFileDetail = "low" - ImageFileDetailHigh ImageFileDetail = "high" -) - -// The property FileID is required. -type ImageFileParam struct { - // The [File](https://platform.openai.com/docs/api-reference/files) ID of the image - // in the message content. Set `purpose="vision"` when uploading the File if you - // need to later display the file content. - FileID string `json:"file_id,required"` - // Specifies the detail level of the image if specified by the user. `low` uses - // fewer tokens, you can opt in to high resolution using `high`. - // - // Any of "auto", "low", "high". - Detail ImageFileDetail `json:"detail,omitzero"` - paramObj -} - -func (r ImageFileParam) MarshalJSON() (data []byte, err error) { - type shadow ImageFileParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ImageFileParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// References an image [File](https://platform.openai.com/docs/api-reference/files) -// in the content of a message. -type ImageFileContentBlock struct { - ImageFile ImageFile `json:"image_file,required"` - // Always `image_file`. - Type constant.ImageFile `json:"type,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ImageFile respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ImageFileContentBlock) RawJSON() string { return r.JSON.raw } -func (r *ImageFileContentBlock) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// ToParam converts this ImageFileContentBlock to a ImageFileContentBlockParam. -// -// Warning: the fields of the param type will not be present. ToParam should only -// be used at the last possible moment before sending a request. Test for this with -// ImageFileContentBlockParam.Overrides() -func (r ImageFileContentBlock) ToParam() ImageFileContentBlockParam { - return param.Override[ImageFileContentBlockParam](json.RawMessage(r.RawJSON())) -} - -// References an image [File](https://platform.openai.com/docs/api-reference/files) -// in the content of a message. -// -// The properties ImageFile, Type are required. -type ImageFileContentBlockParam struct { - ImageFile ImageFileParam `json:"image_file,omitzero,required"` - // Always `image_file`. - // - // This field can be elided, and will marshal its zero value as "image_file". - Type constant.ImageFile `json:"type,required"` - paramObj -} - -func (r ImageFileContentBlockParam) MarshalJSON() (data []byte, err error) { - type shadow ImageFileContentBlockParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ImageFileContentBlockParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type ImageFileDelta struct { - // Specifies the detail level of the image if specified by the user. `low` uses - // fewer tokens, you can opt in to high resolution using `high`. - // - // Any of "auto", "low", "high". - Detail ImageFileDeltaDetail `json:"detail"` - // The [File](https://platform.openai.com/docs/api-reference/files) ID of the image - // in the message content. Set `purpose="vision"` when uploading the File if you - // need to later display the file content. - FileID string `json:"file_id"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Detail respjson.Field - FileID respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ImageFileDelta) RawJSON() string { return r.JSON.raw } -func (r *ImageFileDelta) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Specifies the detail level of the image if specified by the user. `low` uses -// fewer tokens, you can opt in to high resolution using `high`. -type ImageFileDeltaDetail string - -const ( - ImageFileDeltaDetailAuto ImageFileDeltaDetail = "auto" - ImageFileDeltaDetailLow ImageFileDeltaDetail = "low" - ImageFileDeltaDetailHigh ImageFileDeltaDetail = "high" -) - -// References an image [File](https://platform.openai.com/docs/api-reference/files) -// in the content of a message. -type ImageFileDeltaBlock struct { - // The index of the content part in the message. - Index int64 `json:"index,required"` - // Always `image_file`. - Type constant.ImageFile `json:"type,required"` - ImageFile ImageFileDelta `json:"image_file"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Index respjson.Field - Type respjson.Field - ImageFile respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ImageFileDeltaBlock) RawJSON() string { return r.JSON.raw } -func (r *ImageFileDeltaBlock) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type ImageURL struct { - // The external URL of the image, must be a supported image types: jpeg, jpg, png, - // gif, webp. - URL string `json:"url,required" format:"uri"` - // Specifies the detail level of the image. `low` uses fewer tokens, you can opt in - // to high resolution using `high`. Default value is `auto` - // - // Any of "auto", "low", "high". - Detail ImageURLDetail `json:"detail"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - URL respjson.Field - Detail respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ImageURL) RawJSON() string { return r.JSON.raw } -func (r *ImageURL) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// ToParam converts this ImageURL to a ImageURLParam. -// -// Warning: the fields of the param type will not be present. ToParam should only -// be used at the last possible moment before sending a request. Test for this with -// ImageURLParam.Overrides() -func (r ImageURL) ToParam() ImageURLParam { - return param.Override[ImageURLParam](json.RawMessage(r.RawJSON())) -} - -// Specifies the detail level of the image. `low` uses fewer tokens, you can opt in -// to high resolution using `high`. Default value is `auto` -type ImageURLDetail string - -const ( - ImageURLDetailAuto ImageURLDetail = "auto" - ImageURLDetailLow ImageURLDetail = "low" - ImageURLDetailHigh ImageURLDetail = "high" -) - -// The property URL is required. -type ImageURLParam struct { - // The external URL of the image, must be a supported image types: jpeg, jpg, png, - // gif, webp. - URL string `json:"url,required" format:"uri"` - // Specifies the detail level of the image. `low` uses fewer tokens, you can opt in - // to high resolution using `high`. Default value is `auto` - // - // Any of "auto", "low", "high". - Detail ImageURLDetail `json:"detail,omitzero"` - paramObj -} - -func (r ImageURLParam) MarshalJSON() (data []byte, err error) { - type shadow ImageURLParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ImageURLParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// References an image URL in the content of a message. -type ImageURLContentBlock struct { - ImageURL ImageURL `json:"image_url,required"` - // The type of the content part. - Type constant.ImageURL `json:"type,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ImageURL respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ImageURLContentBlock) RawJSON() string { return r.JSON.raw } -func (r *ImageURLContentBlock) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// ToParam converts this ImageURLContentBlock to a ImageURLContentBlockParam. -// -// Warning: the fields of the param type will not be present. ToParam should only -// be used at the last possible moment before sending a request. Test for this with -// ImageURLContentBlockParam.Overrides() -func (r ImageURLContentBlock) ToParam() ImageURLContentBlockParam { - return param.Override[ImageURLContentBlockParam](json.RawMessage(r.RawJSON())) -} - -// References an image URL in the content of a message. -// -// The properties ImageURL, Type are required. -type ImageURLContentBlockParam struct { - ImageURL ImageURLParam `json:"image_url,omitzero,required"` - // The type of the content part. - // - // This field can be elided, and will marshal its zero value as "image_url". - Type constant.ImageURL `json:"type,required"` - paramObj -} - -func (r ImageURLContentBlockParam) MarshalJSON() (data []byte, err error) { - type shadow ImageURLContentBlockParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ImageURLContentBlockParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type ImageURLDelta struct { - // Specifies the detail level of the image. `low` uses fewer tokens, you can opt in - // to high resolution using `high`. - // - // Any of "auto", "low", "high". - Detail ImageURLDeltaDetail `json:"detail"` - // The URL of the image, must be a supported image types: jpeg, jpg, png, gif, - // webp. - URL string `json:"url"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Detail respjson.Field - URL respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ImageURLDelta) RawJSON() string { return r.JSON.raw } -func (r *ImageURLDelta) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Specifies the detail level of the image. `low` uses fewer tokens, you can opt in -// to high resolution using `high`. -type ImageURLDeltaDetail string - -const ( - ImageURLDeltaDetailAuto ImageURLDeltaDetail = "auto" - ImageURLDeltaDetailLow ImageURLDeltaDetail = "low" - ImageURLDeltaDetailHigh ImageURLDeltaDetail = "high" -) - -// References an image URL in the content of a message. -type ImageURLDeltaBlock struct { - // The index of the content part in the message. - Index int64 `json:"index,required"` - // Always `image_url`. - Type constant.ImageURL `json:"type,required"` - ImageURL ImageURLDelta `json:"image_url"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Index respjson.Field - Type respjson.Field - ImageURL respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ImageURLDeltaBlock) RawJSON() string { return r.JSON.raw } -func (r *ImageURLDeltaBlock) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Represents a message within a -// [thread](https://platform.openai.com/docs/api-reference/threads). -type Message struct { - // The identifier, which can be referenced in API endpoints. - ID string `json:"id,required"` - // If applicable, the ID of the - // [assistant](https://platform.openai.com/docs/api-reference/assistants) that - // authored this message. - AssistantID string `json:"assistant_id,required"` - // A list of files attached to the message, and the tools they were added to. - Attachments []MessageAttachment `json:"attachments,required"` - // The Unix timestamp (in seconds) for when the message was completed. - CompletedAt int64 `json:"completed_at,required"` - // The content of the message in array of text and/or images. - Content []MessageContentUnion `json:"content,required"` - // The Unix timestamp (in seconds) for when the message was created. - CreatedAt int64 `json:"created_at,required"` - // The Unix timestamp (in seconds) for when the message was marked as incomplete. - IncompleteAt int64 `json:"incomplete_at,required"` - // On an incomplete message, details about why the message is incomplete. - IncompleteDetails MessageIncompleteDetails `json:"incomplete_details,required"` - // 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, and - // querying for objects via API or the dashboard. - // - // Keys are strings with a maximum length of 64 characters. Values are strings with - // a maximum length of 512 characters. - Metadata shared.Metadata `json:"metadata,required"` - // The object type, which is always `thread.message`. - Object constant.ThreadMessage `json:"object,required"` - // The entity that produced the message. One of `user` or `assistant`. - // - // Any of "user", "assistant". - Role MessageRole `json:"role,required"` - // The ID of the [run](https://platform.openai.com/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. - RunID string `json:"run_id,required"` - // The status of the message, which can be either `in_progress`, `incomplete`, or - // `completed`. - // - // Any of "in_progress", "incomplete", "completed". - Status MessageStatus `json:"status,required"` - // The [thread](https://platform.openai.com/docs/api-reference/threads) ID that - // this message belongs to. - ThreadID string `json:"thread_id,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ID respjson.Field - AssistantID respjson.Field - Attachments respjson.Field - CompletedAt respjson.Field - Content respjson.Field - CreatedAt respjson.Field - IncompleteAt respjson.Field - IncompleteDetails respjson.Field - Metadata respjson.Field - Object respjson.Field - Role respjson.Field - RunID respjson.Field - Status respjson.Field - ThreadID respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r Message) RawJSON() string { return r.JSON.raw } -func (r *Message) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type MessageAttachment struct { - // The ID of the file to attach to the message. - FileID string `json:"file_id"` - // The tools to add this file to. - Tools []MessageAttachmentToolUnion `json:"tools"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - FileID respjson.Field - Tools respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r MessageAttachment) RawJSON() string { return r.JSON.raw } -func (r *MessageAttachment) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// MessageAttachmentToolUnion contains all possible properties and values from -// [CodeInterpreterTool], [MessageAttachmentToolFileSearchTool]. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -type MessageAttachmentToolUnion struct { - Type string `json:"type"` - JSON struct { - Type respjson.Field - raw string - } `json:"-"` -} - -func (u MessageAttachmentToolUnion) AsCodeInterpreterTool() (v CodeInterpreterTool) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u MessageAttachmentToolUnion) AsFileSearchTool() (v MessageAttachmentToolFileSearchTool) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -// Returns the unmodified JSON received from the API -func (u MessageAttachmentToolUnion) RawJSON() string { return u.JSON.raw } - -func (r *MessageAttachmentToolUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type MessageAttachmentToolFileSearchTool struct { - // The type of tool being defined: `file_search` - Type constant.FileSearch `json:"type,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r MessageAttachmentToolFileSearchTool) RawJSON() string { return r.JSON.raw } -func (r *MessageAttachmentToolFileSearchTool) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// On an incomplete message, details about why the message is incomplete. -type MessageIncompleteDetails struct { - // The reason the message is incomplete. - // - // Any of "content_filter", "max_tokens", "run_cancelled", "run_expired", - // "run_failed". - Reason string `json:"reason,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Reason respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r MessageIncompleteDetails) RawJSON() string { return r.JSON.raw } -func (r *MessageIncompleteDetails) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The entity that produced the message. One of `user` or `assistant`. -type MessageRole string - -const ( - MessageRoleUser MessageRole = "user" - MessageRoleAssistant MessageRole = "assistant" -) - -// The status of the message, which can be either `in_progress`, `incomplete`, or -// `completed`. -type MessageStatus string - -const ( - MessageStatusInProgress MessageStatus = "in_progress" - MessageStatusIncomplete MessageStatus = "incomplete" - MessageStatusCompleted MessageStatus = "completed" -) - -// MessageContentUnion contains all possible properties and values from -// [ImageFileContentBlock], [ImageURLContentBlock], [TextContentBlock], -// [RefusalContentBlock]. -// -// Use the [MessageContentUnion.AsAny] method to switch on the variant. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -type MessageContentUnion struct { - // This field is from variant [ImageFileContentBlock]. - ImageFile ImageFile `json:"image_file"` - // Any of "image_file", "image_url", "text", "refusal". - Type string `json:"type"` - // This field is from variant [ImageURLContentBlock]. - ImageURL ImageURL `json:"image_url"` - // This field is from variant [TextContentBlock]. - Text Text `json:"text"` - // This field is from variant [RefusalContentBlock]. - Refusal string `json:"refusal"` - JSON struct { - ImageFile respjson.Field - Type respjson.Field - ImageURL respjson.Field - Text respjson.Field - Refusal respjson.Field - raw string - } `json:"-"` -} - -// anyMessageContent is implemented by each variant of [MessageContentUnion] to add -// type safety for the return type of [MessageContentUnion.AsAny] -type anyMessageContent interface { - implMessageContentUnion() -} - -func (ImageFileContentBlock) implMessageContentUnion() {} -func (ImageURLContentBlock) implMessageContentUnion() {} -func (TextContentBlock) implMessageContentUnion() {} -func (RefusalContentBlock) implMessageContentUnion() {} - -// Use the following switch statement to find the correct variant -// -// switch variant := MessageContentUnion.AsAny().(type) { -// case openai.ImageFileContentBlock: -// case openai.ImageURLContentBlock: -// case openai.TextContentBlock: -// case openai.RefusalContentBlock: -// default: -// fmt.Errorf("no variant present") -// } -func (u MessageContentUnion) AsAny() anyMessageContent { - switch u.Type { - case "image_file": - return u.AsImageFile() - case "image_url": - return u.AsImageURL() - case "text": - return u.AsText() - case "refusal": - return u.AsRefusal() - } - return nil -} - -func (u MessageContentUnion) AsImageFile() (v ImageFileContentBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u MessageContentUnion) AsImageURL() (v ImageURLContentBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u MessageContentUnion) AsText() (v TextContentBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u MessageContentUnion) AsRefusal() (v RefusalContentBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -// Returns the unmodified JSON received from the API -func (u MessageContentUnion) RawJSON() string { return u.JSON.raw } - -func (r *MessageContentUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// MessageContentDeltaUnion contains all possible properties and values from -// [ImageFileDeltaBlock], [TextDeltaBlock], [RefusalDeltaBlock], -// [ImageURLDeltaBlock]. -// -// Use the [MessageContentDeltaUnion.AsAny] method to switch on the variant. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -type MessageContentDeltaUnion struct { - Index int64 `json:"index"` - // Any of "image_file", "text", "refusal", "image_url". - Type string `json:"type"` - // This field is from variant [ImageFileDeltaBlock]. - ImageFile ImageFileDelta `json:"image_file"` - // This field is from variant [TextDeltaBlock]. - Text TextDelta `json:"text"` - // This field is from variant [RefusalDeltaBlock]. - Refusal string `json:"refusal"` - // This field is from variant [ImageURLDeltaBlock]. - ImageURL ImageURLDelta `json:"image_url"` - JSON struct { - Index respjson.Field - Type respjson.Field - ImageFile respjson.Field - Text respjson.Field - Refusal respjson.Field - ImageURL respjson.Field - raw string - } `json:"-"` -} - -// anyMessageContentDelta is implemented by each variant of -// [MessageContentDeltaUnion] to add type safety for the return type of -// [MessageContentDeltaUnion.AsAny] -type anyMessageContentDelta interface { - implMessageContentDeltaUnion() -} - -func (ImageFileDeltaBlock) implMessageContentDeltaUnion() {} -func (TextDeltaBlock) implMessageContentDeltaUnion() {} -func (RefusalDeltaBlock) implMessageContentDeltaUnion() {} -func (ImageURLDeltaBlock) implMessageContentDeltaUnion() {} - -// Use the following switch statement to find the correct variant -// -// switch variant := MessageContentDeltaUnion.AsAny().(type) { -// case openai.ImageFileDeltaBlock: -// case openai.TextDeltaBlock: -// case openai.RefusalDeltaBlock: -// case openai.ImageURLDeltaBlock: -// default: -// fmt.Errorf("no variant present") -// } -func (u MessageContentDeltaUnion) AsAny() anyMessageContentDelta { - switch u.Type { - case "image_file": - return u.AsImageFile() - case "text": - return u.AsText() - case "refusal": - return u.AsRefusal() - case "image_url": - return u.AsImageURL() - } - return nil -} - -func (u MessageContentDeltaUnion) AsImageFile() (v ImageFileDeltaBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u MessageContentDeltaUnion) AsText() (v TextDeltaBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u MessageContentDeltaUnion) AsRefusal() (v RefusalDeltaBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u MessageContentDeltaUnion) AsImageURL() (v ImageURLDeltaBlock) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -// Returns the unmodified JSON received from the API -func (u MessageContentDeltaUnion) RawJSON() string { return u.JSON.raw } - -func (r *MessageContentDeltaUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -func MessageContentPartParamOfImageFile(imageFile ImageFileParam) MessageContentPartParamUnion { - var variant ImageFileContentBlockParam - variant.ImageFile = imageFile - return MessageContentPartParamUnion{OfImageFile: &variant} -} - -func MessageContentPartParamOfImageURL(imageURL ImageURLParam) MessageContentPartParamUnion { - var variant ImageURLContentBlockParam - variant.ImageURL = imageURL - return MessageContentPartParamUnion{OfImageURL: &variant} -} - -func MessageContentPartParamOfText(text string) MessageContentPartParamUnion { - var variant TextContentBlockParam - variant.Text = text - return MessageContentPartParamUnion{OfText: &variant} -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type MessageContentPartParamUnion struct { - OfImageFile *ImageFileContentBlockParam `json:",omitzero,inline"` - OfImageURL *ImageURLContentBlockParam `json:",omitzero,inline"` - OfText *TextContentBlockParam `json:",omitzero,inline"` - paramUnion -} - -func (u MessageContentPartParamUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfImageFile, u.OfImageURL, u.OfText) -} -func (u *MessageContentPartParamUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *MessageContentPartParamUnion) asAny() any { - if !param.IsOmitted(u.OfImageFile) { - return u.OfImageFile - } else if !param.IsOmitted(u.OfImageURL) { - return u.OfImageURL - } else if !param.IsOmitted(u.OfText) { - return u.OfText - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u MessageContentPartParamUnion) GetImageFile() *ImageFileParam { - if vt := u.OfImageFile; vt != nil { - return &vt.ImageFile - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u MessageContentPartParamUnion) GetImageURL() *ImageURLParam { - if vt := u.OfImageURL; vt != nil { - return &vt.ImageURL - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u MessageContentPartParamUnion) GetText() *string { - if vt := u.OfText; vt != nil { - return &vt.Text - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u MessageContentPartParamUnion) GetType() *string { - if vt := u.OfImageFile; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfImageURL; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfText; vt != nil { - return (*string)(&vt.Type) - } - return nil -} - -func init() { - apijson.RegisterUnion[MessageContentPartParamUnion]( - "type", - apijson.Discriminator[ImageFileContentBlockParam]("image_file"), - apijson.Discriminator[ImageURLContentBlockParam]("image_url"), - apijson.Discriminator[TextContentBlockParam]("text"), - ) -} - -type MessageDeleted struct { - ID string `json:"id,required"` - Deleted bool `json:"deleted,required"` - Object constant.ThreadMessageDeleted `json:"object,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ID respjson.Field - Deleted respjson.Field - Object respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r MessageDeleted) RawJSON() string { return r.JSON.raw } -func (r *MessageDeleted) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The delta containing the fields that have changed on the Message. -type MessageDelta struct { - // The content of the message in array of text and/or images. - Content []MessageContentDeltaUnion `json:"content"` - // The entity that produced the message. One of `user` or `assistant`. - // - // Any of "user", "assistant". - Role MessageDeltaRole `json:"role"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Content respjson.Field - Role respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r MessageDelta) RawJSON() string { return r.JSON.raw } -func (r *MessageDelta) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The entity that produced the message. One of `user` or `assistant`. -type MessageDeltaRole string - -const ( - MessageDeltaRoleUser MessageDeltaRole = "user" - MessageDeltaRoleAssistant MessageDeltaRole = "assistant" -) - -// Represents a message delta i.e. any changed fields on a message during -// streaming. -type MessageDeltaEvent struct { - // The identifier of the message, which can be referenced in API endpoints. - ID string `json:"id,required"` - // The delta containing the fields that have changed on the Message. - Delta MessageDelta `json:"delta,required"` - // The object type, which is always `thread.message.delta`. - Object constant.ThreadMessageDelta `json:"object,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ID respjson.Field - Delta respjson.Field - Object respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r MessageDeltaEvent) RawJSON() string { return r.JSON.raw } -func (r *MessageDeltaEvent) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The refusal content generated by the assistant. -type RefusalContentBlock struct { - Refusal string `json:"refusal,required"` - // Always `refusal`. - Type constant.Refusal `json:"type,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Refusal respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r RefusalContentBlock) RawJSON() string { return r.JSON.raw } -func (r *RefusalContentBlock) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The refusal content that is part of a message. -type RefusalDeltaBlock struct { - // The index of the refusal part in the message. - Index int64 `json:"index,required"` - // Always `refusal`. - Type constant.Refusal `json:"type,required"` - Refusal string `json:"refusal"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Index respjson.Field - Type respjson.Field - Refusal respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r RefusalDeltaBlock) RawJSON() string { return r.JSON.raw } -func (r *RefusalDeltaBlock) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type Text struct { - Annotations []AnnotationUnion `json:"annotations,required"` - // The data that makes up the text. - Value string `json:"value,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Annotations respjson.Field - Value respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r Text) RawJSON() string { return r.JSON.raw } -func (r *Text) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The text content that is part of a message. -type TextContentBlock struct { - Text Text `json:"text,required"` - // Always `text`. - Type constant.Text `json:"type,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Text respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r TextContentBlock) RawJSON() string { return r.JSON.raw } -func (r *TextContentBlock) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The text content that is part of a message. -// -// The properties Text, Type are required. -type TextContentBlockParam struct { - // Text content to be sent to the model - Text string `json:"text,required"` - // Always `text`. - // - // This field can be elided, and will marshal its zero value as "text". - Type constant.Text `json:"type,required"` - paramObj -} - -func (r TextContentBlockParam) MarshalJSON() (data []byte, err error) { - type shadow TextContentBlockParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *TextContentBlockParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type TextDelta struct { - Annotations []AnnotationDeltaUnion `json:"annotations"` - // The data that makes up the text. - Value string `json:"value"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Annotations respjson.Field - Value respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r TextDelta) RawJSON() string { return r.JSON.raw } -func (r *TextDelta) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The text content that is part of a message. -type TextDeltaBlock struct { - // The index of the content part in the message. - Index int64 `json:"index,required"` - // Always `text`. - Type constant.Text `json:"type,required"` - Text TextDelta `json:"text"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Index respjson.Field - Type respjson.Field - Text respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r TextDeltaBlock) RawJSON() string { return r.JSON.raw } -func (r *TextDeltaBlock) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type BetaThreadMessageNewParams struct { - // The text contents of the message. - Content BetaThreadMessageNewParamsContentUnion `json:"content,omitzero,required"` - // 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. - // - // Any of "user", "assistant". - Role BetaThreadMessageNewParamsRole `json:"role,omitzero,required"` - // A list of files attached to the message, and the tools they should be added to. - Attachments []BetaThreadMessageNewParamsAttachment `json:"attachments,omitzero"` - // 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, and - // querying for objects via API or the dashboard. - // - // Keys are strings with a maximum length of 64 characters. Values are strings with - // a maximum length of 512 characters. - Metadata shared.Metadata `json:"metadata,omitzero"` - paramObj -} - -func (r BetaThreadMessageNewParams) MarshalJSON() (data []byte, err error) { - type shadow BetaThreadMessageNewParams - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaThreadMessageNewParams) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type BetaThreadMessageNewParamsContentUnion struct { - OfString param.Opt[string] `json:",omitzero,inline"` - OfArrayOfContentParts []MessageContentPartParamUnion `json:",omitzero,inline"` - paramUnion -} - -func (u BetaThreadMessageNewParamsContentUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfString, u.OfArrayOfContentParts) -} -func (u *BetaThreadMessageNewParamsContentUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *BetaThreadMessageNewParamsContentUnion) asAny() any { - if !param.IsOmitted(u.OfString) { - return &u.OfString.Value - } else if !param.IsOmitted(u.OfArrayOfContentParts) { - return &u.OfArrayOfContentParts - } - return nil -} - -// 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. -type BetaThreadMessageNewParamsRole string - -const ( - BetaThreadMessageNewParamsRoleUser BetaThreadMessageNewParamsRole = "user" - BetaThreadMessageNewParamsRoleAssistant BetaThreadMessageNewParamsRole = "assistant" -) - -type BetaThreadMessageNewParamsAttachment struct { - // The ID of the file to attach to the message. - FileID param.Opt[string] `json:"file_id,omitzero"` - // The tools to add this file to. - Tools []BetaThreadMessageNewParamsAttachmentToolUnion `json:"tools,omitzero"` - paramObj -} - -func (r BetaThreadMessageNewParamsAttachment) MarshalJSON() (data []byte, err error) { - type shadow BetaThreadMessageNewParamsAttachment - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaThreadMessageNewParamsAttachment) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type BetaThreadMessageNewParamsAttachmentToolUnion struct { - OfCodeInterpreter *CodeInterpreterToolParam `json:",omitzero,inline"` - OfFileSearch *BetaThreadMessageNewParamsAttachmentToolFileSearch `json:",omitzero,inline"` - paramUnion -} - -func (u BetaThreadMessageNewParamsAttachmentToolUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfCodeInterpreter, u.OfFileSearch) -} -func (u *BetaThreadMessageNewParamsAttachmentToolUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *BetaThreadMessageNewParamsAttachmentToolUnion) asAny() any { - if !param.IsOmitted(u.OfCodeInterpreter) { - return u.OfCodeInterpreter - } else if !param.IsOmitted(u.OfFileSearch) { - return u.OfFileSearch - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u BetaThreadMessageNewParamsAttachmentToolUnion) GetType() *string { - if vt := u.OfCodeInterpreter; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfFileSearch; vt != nil { - return (*string)(&vt.Type) - } - return nil -} - -func init() { - apijson.RegisterUnion[BetaThreadMessageNewParamsAttachmentToolUnion]( - "type", - apijson.Discriminator[CodeInterpreterToolParam]("code_interpreter"), - apijson.Discriminator[BetaThreadMessageNewParamsAttachmentToolFileSearch]("file_search"), - ) -} - -func NewBetaThreadMessageNewParamsAttachmentToolFileSearch() BetaThreadMessageNewParamsAttachmentToolFileSearch { - return BetaThreadMessageNewParamsAttachmentToolFileSearch{ - Type: "file_search", - } -} - -// This struct has a constant value, construct it with -// [NewBetaThreadMessageNewParamsAttachmentToolFileSearch]. -type BetaThreadMessageNewParamsAttachmentToolFileSearch struct { - // The type of tool being defined: `file_search` - Type constant.FileSearch `json:"type,required"` - paramObj -} - -func (r BetaThreadMessageNewParamsAttachmentToolFileSearch) MarshalJSON() (data []byte, err error) { - type shadow BetaThreadMessageNewParamsAttachmentToolFileSearch - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaThreadMessageNewParamsAttachmentToolFileSearch) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type BetaThreadMessageUpdateParams struct { - // 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, and - // querying for objects via API or the dashboard. - // - // Keys are strings with a maximum length of 64 characters. Values are strings with - // a maximum length of 512 characters. - Metadata shared.Metadata `json:"metadata,omitzero"` - paramObj -} - -func (r BetaThreadMessageUpdateParams) MarshalJSON() (data []byte, err error) { - type shadow BetaThreadMessageUpdateParams - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaThreadMessageUpdateParams) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type BetaThreadMessageListParams struct { - // 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. - After param.Opt[string] `query:"after,omitzero" json:"-"` - // A cursor for use in pagination. `before` is an object ID that defines your place - // in the list. For instance, if you make a list request and receive 100 objects, - // starting with obj_foo, your subsequent call can include before=obj_foo in order - // to fetch the previous page of the list. - Before param.Opt[string] `query:"before,omitzero" json:"-"` - // A limit on the number of objects to be returned. Limit can range between 1 and - // 100, and the default is 20. - Limit param.Opt[int64] `query:"limit,omitzero" json:"-"` - // Filter messages by the run ID that generated them. - RunID param.Opt[string] `query:"run_id,omitzero" json:"-"` - // Sort order by the `created_at` timestamp of the objects. `asc` for ascending - // order and `desc` for descending order. - // - // Any of "asc", "desc". - Order BetaThreadMessageListParamsOrder `query:"order,omitzero" json:"-"` - paramObj -} - -// URLQuery serializes [BetaThreadMessageListParams]'s query parameters as -// `url.Values`. -func (r BetaThreadMessageListParams) URLQuery() (v url.Values, err error) { - return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ - ArrayFormat: apiquery.ArrayQueryFormatBrackets, - NestedFormat: apiquery.NestedQueryFormatBrackets, - }) -} - -// Sort order by the `created_at` timestamp of the objects. `asc` for ascending -// order and `desc` for descending order. -type BetaThreadMessageListParamsOrder string - -const ( - BetaThreadMessageListParamsOrderAsc BetaThreadMessageListParamsOrder = "asc" - BetaThreadMessageListParamsOrderDesc BetaThreadMessageListParamsOrder = "desc" -) diff --git a/vendor/github.com/openai/openai-go/betathreadrun.go b/vendor/github.com/openai/openai-go/betathreadrun.go deleted file mode 100644 index 7d7e1166..00000000 --- a/vendor/github.com/openai/openai-go/betathreadrun.go +++ /dev/null @@ -1,960 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -package openai - -import ( - "context" - "errors" - "fmt" - "net/http" - "net/url" - - "github.com/openai/openai-go/internal/apijson" - "github.com/openai/openai-go/internal/apiquery" - "github.com/openai/openai-go/internal/requestconfig" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/packages/pagination" - "github.com/openai/openai-go/packages/param" - "github.com/openai/openai-go/packages/respjson" - "github.com/openai/openai-go/packages/ssestream" - "github.com/openai/openai-go/shared" - "github.com/openai/openai-go/shared/constant" -) - -// BetaThreadRunService contains methods and other services that help with -// interacting with the openai API. -// -// Note, unlike clients, this service does not read variables from the environment -// automatically. You should not instantiate this service directly, and instead use -// the [NewBetaThreadRunService] method instead. -// -// Deprecated: The Assistants API is deprecated in favor of the Responses API -type BetaThreadRunService struct { - Options []option.RequestOption - // Deprecated: The Assistants API is deprecated in favor of the Responses API - Steps BetaThreadRunStepService -} - -// NewBetaThreadRunService generates a new service that applies the given options -// to each request. These options are applied after the parent client's options (if -// there is one), and before any request-specific options. -func NewBetaThreadRunService(opts ...option.RequestOption) (r BetaThreadRunService) { - r = BetaThreadRunService{} - r.Options = opts - r.Steps = NewBetaThreadRunStepService(opts...) - return -} - -// Create a run. -// -// Deprecated: The Assistants API is deprecated in favor of the Responses API -func (r *BetaThreadRunService) New(ctx context.Context, threadID string, params BetaThreadRunNewParams, opts ...option.RequestOption) (res *Run, err error) { - opts = append(r.Options[:], opts...) - opts = append([]option.RequestOption{option.WithHeader("OpenAI-Beta", "assistants=v2")}, opts...) - if threadID == "" { - err = errors.New("missing required thread_id parameter") - return - } - path := fmt.Sprintf("threads/%s/runs", threadID) - err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, params, &res, opts...) - return -} - -// Create a run. -// -// Deprecated: The Assistants API is deprecated in favor of the Responses API -func (r *BetaThreadRunService) NewStreaming(ctx context.Context, threadID string, params BetaThreadRunNewParams, opts ...option.RequestOption) (stream *ssestream.Stream[AssistantStreamEventUnion]) { - var ( - raw *http.Response - err error - ) - opts = append(r.Options[:], opts...) - opts = append([]option.RequestOption{option.WithHeader("OpenAI-Beta", "assistants=v2"), option.WithJSONSet("stream", true)}, opts...) - if threadID == "" { - err = errors.New("missing required thread_id parameter") - return - } - path := fmt.Sprintf("threads/%s/runs", threadID) - err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, params, &raw, opts...) - return ssestream.NewStream[AssistantStreamEventUnion](ssestream.NewDecoder(raw), err) -} - -// Retrieves a run. -// -// Deprecated: The Assistants API is deprecated in favor of the Responses API -func (r *BetaThreadRunService) Get(ctx context.Context, threadID string, runID string, opts ...option.RequestOption) (res *Run, err error) { - opts = append(r.Options[:], opts...) - opts = append([]option.RequestOption{option.WithHeader("OpenAI-Beta", "assistants=v2")}, opts...) - if threadID == "" { - err = errors.New("missing required thread_id parameter") - return - } - if runID == "" { - err = errors.New("missing required run_id parameter") - return - } - path := fmt.Sprintf("threads/%s/runs/%s", threadID, runID) - err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...) - return -} - -// Modifies a run. -// -// Deprecated: The Assistants API is deprecated in favor of the Responses API -func (r *BetaThreadRunService) Update(ctx context.Context, threadID string, runID string, body BetaThreadRunUpdateParams, opts ...option.RequestOption) (res *Run, err error) { - opts = append(r.Options[:], opts...) - opts = append([]option.RequestOption{option.WithHeader("OpenAI-Beta", "assistants=v2")}, opts...) - if threadID == "" { - err = errors.New("missing required thread_id parameter") - return - } - if runID == "" { - err = errors.New("missing required run_id parameter") - return - } - path := fmt.Sprintf("threads/%s/runs/%s", threadID, runID) - err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...) - return -} - -// Returns a list of runs belonging to a thread. -// -// Deprecated: The Assistants API is deprecated in favor of the Responses API -func (r *BetaThreadRunService) List(ctx context.Context, threadID string, query BetaThreadRunListParams, opts ...option.RequestOption) (res *pagination.CursorPage[Run], err error) { - var raw *http.Response - opts = append(r.Options[:], opts...) - opts = append([]option.RequestOption{option.WithHeader("OpenAI-Beta", "assistants=v2"), option.WithResponseInto(&raw)}, opts...) - if threadID == "" { - err = errors.New("missing required thread_id parameter") - return - } - path := fmt.Sprintf("threads/%s/runs", threadID) - cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, query, &res, opts...) - if err != nil { - return nil, err - } - err = cfg.Execute() - if err != nil { - return nil, err - } - res.SetPageConfig(cfg, raw) - return res, nil -} - -// Returns a list of runs belonging to a thread. -// -// Deprecated: The Assistants API is deprecated in favor of the Responses API -func (r *BetaThreadRunService) ListAutoPaging(ctx context.Context, threadID string, query BetaThreadRunListParams, opts ...option.RequestOption) *pagination.CursorPageAutoPager[Run] { - return pagination.NewCursorPageAutoPager(r.List(ctx, threadID, query, opts...)) -} - -// Cancels a run that is `in_progress`. -// -// Deprecated: The Assistants API is deprecated in favor of the Responses API -func (r *BetaThreadRunService) Cancel(ctx context.Context, threadID string, runID string, opts ...option.RequestOption) (res *Run, err error) { - opts = append(r.Options[:], opts...) - opts = append([]option.RequestOption{option.WithHeader("OpenAI-Beta", "assistants=v2")}, opts...) - if threadID == "" { - err = errors.New("missing required thread_id parameter") - return - } - if runID == "" { - err = errors.New("missing required run_id parameter") - return - } - path := fmt.Sprintf("threads/%s/runs/%s/cancel", threadID, runID) - err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, nil, &res, opts...) - return -} - -// 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. -// -// Deprecated: The Assistants API is deprecated in favor of the Responses API -func (r *BetaThreadRunService) SubmitToolOutputs(ctx context.Context, threadID string, runID string, body BetaThreadRunSubmitToolOutputsParams, opts ...option.RequestOption) (res *Run, err error) { - opts = append(r.Options[:], opts...) - opts = append([]option.RequestOption{option.WithHeader("OpenAI-Beta", "assistants=v2")}, opts...) - if threadID == "" { - err = errors.New("missing required thread_id parameter") - return - } - if runID == "" { - err = errors.New("missing required run_id parameter") - return - } - path := fmt.Sprintf("threads/%s/runs/%s/submit_tool_outputs", threadID, runID) - err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...) - return -} - -// 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. -// -// Deprecated: The Assistants API is deprecated in favor of the Responses API -func (r *BetaThreadRunService) SubmitToolOutputsStreaming(ctx context.Context, threadID string, runID string, body BetaThreadRunSubmitToolOutputsParams, opts ...option.RequestOption) (stream *ssestream.Stream[AssistantStreamEventUnion]) { - var ( - raw *http.Response - err error - ) - opts = append(r.Options[:], opts...) - opts = append([]option.RequestOption{option.WithHeader("OpenAI-Beta", "assistants=v2"), option.WithJSONSet("stream", true)}, opts...) - if threadID == "" { - err = errors.New("missing required thread_id parameter") - return - } - if runID == "" { - err = errors.New("missing required run_id parameter") - return - } - path := fmt.Sprintf("threads/%s/runs/%s/submit_tool_outputs", threadID, runID) - err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &raw, opts...) - return ssestream.NewStream[AssistantStreamEventUnion](ssestream.NewDecoder(raw), err) -} - -// Tool call objects -type RequiredActionFunctionToolCall struct { - // 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](https://platform.openai.com/docs/api-reference/runs/submitToolOutputs) - // endpoint. - ID string `json:"id,required"` - // The function definition. - Function RequiredActionFunctionToolCallFunction `json:"function,required"` - // The type of tool call the output is required for. For now, this is always - // `function`. - Type constant.Function `json:"type,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ID respjson.Field - Function respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r RequiredActionFunctionToolCall) RawJSON() string { return r.JSON.raw } -func (r *RequiredActionFunctionToolCall) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The function definition. -type RequiredActionFunctionToolCallFunction struct { - // The arguments that the model expects you to pass to the function. - Arguments string `json:"arguments,required"` - // The name of the function. - Name string `json:"name,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Arguments respjson.Field - Name respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r RequiredActionFunctionToolCallFunction) RawJSON() string { return r.JSON.raw } -func (r *RequiredActionFunctionToolCallFunction) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Represents an execution run on a -// [thread](https://platform.openai.com/docs/api-reference/threads). -type Run struct { - // The identifier, which can be referenced in API endpoints. - ID string `json:"id,required"` - // The ID of the - // [assistant](https://platform.openai.com/docs/api-reference/assistants) used for - // execution of this run. - AssistantID string `json:"assistant_id,required"` - // The Unix timestamp (in seconds) for when the run was cancelled. - CancelledAt int64 `json:"cancelled_at,required"` - // The Unix timestamp (in seconds) for when the run was completed. - CompletedAt int64 `json:"completed_at,required"` - // The Unix timestamp (in seconds) for when the run was created. - CreatedAt int64 `json:"created_at,required"` - // The Unix timestamp (in seconds) for when the run will expire. - ExpiresAt int64 `json:"expires_at,required"` - // The Unix timestamp (in seconds) for when the run failed. - FailedAt int64 `json:"failed_at,required"` - // Details on why the run is incomplete. Will be `null` if the run is not - // incomplete. - IncompleteDetails RunIncompleteDetails `json:"incomplete_details,required"` - // The instructions that the - // [assistant](https://platform.openai.com/docs/api-reference/assistants) used for - // this run. - Instructions string `json:"instructions,required"` - // The last error associated with this run. Will be `null` if there are no errors. - LastError RunLastError `json:"last_error,required"` - // The maximum number of completion tokens specified to have been used over the - // course of the run. - MaxCompletionTokens int64 `json:"max_completion_tokens,required"` - // The maximum number of prompt tokens specified to have been used over the course - // of the run. - MaxPromptTokens int64 `json:"max_prompt_tokens,required"` - // 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, and - // querying for objects via API or the dashboard. - // - // Keys are strings with a maximum length of 64 characters. Values are strings with - // a maximum length of 512 characters. - Metadata shared.Metadata `json:"metadata,required"` - // The model that the - // [assistant](https://platform.openai.com/docs/api-reference/assistants) used for - // this run. - Model string `json:"model,required"` - // The object type, which is always `thread.run`. - Object constant.ThreadRun `json:"object,required"` - // Whether to enable - // [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) - // during tool use. - ParallelToolCalls bool `json:"parallel_tool_calls,required"` - // Details on the action required to continue the run. Will be `null` if no action - // is required. - RequiredAction RunRequiredAction `json:"required_action,required"` - // Specifies the format that the model must output. Compatible with - // [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), - // [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), - // and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. - // - // Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured - // Outputs which ensures the model will match your supplied JSON schema. Learn more - // in the - // [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). - // - // Setting to `{ "type": "json_object" }` enables JSON mode, which ensures 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 AssistantResponseFormatOptionUnion `json:"response_format,required"` - // The Unix timestamp (in seconds) for when the run was started. - StartedAt int64 `json:"started_at,required"` - // The status of the run, which can be either `queued`, `in_progress`, - // `requires_action`, `cancelling`, `cancelled`, `failed`, `completed`, - // `incomplete`, or `expired`. - // - // Any of "queued", "in_progress", "requires_action", "cancelling", "cancelled", - // "failed", "completed", "incomplete", "expired". - Status RunStatus `json:"status,required"` - // The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) - // that was executed on as a part of this run. - ThreadID string `json:"thread_id,required"` - // 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. - ToolChoice AssistantToolChoiceOptionUnion `json:"tool_choice,required"` - // The list of tools that the - // [assistant](https://platform.openai.com/docs/api-reference/assistants) used for - // this run. - Tools []AssistantToolUnion `json:"tools,required"` - // Controls for how a thread will be truncated prior to the run. Use this to - // control the intial context window of the run. - TruncationStrategy RunTruncationStrategy `json:"truncation_strategy,required"` - // 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.). - Usage RunUsage `json:"usage,required"` - // The sampling temperature used for this run. If not set, defaults to 1. - Temperature float64 `json:"temperature,nullable"` - // The nucleus sampling value used for this run. If not set, defaults to 1. - TopP float64 `json:"top_p,nullable"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ID respjson.Field - AssistantID respjson.Field - CancelledAt respjson.Field - CompletedAt respjson.Field - CreatedAt respjson.Field - ExpiresAt respjson.Field - FailedAt respjson.Field - IncompleteDetails respjson.Field - Instructions respjson.Field - LastError respjson.Field - MaxCompletionTokens respjson.Field - MaxPromptTokens respjson.Field - Metadata respjson.Field - Model respjson.Field - Object respjson.Field - ParallelToolCalls respjson.Field - RequiredAction respjson.Field - ResponseFormat respjson.Field - StartedAt respjson.Field - Status respjson.Field - ThreadID respjson.Field - ToolChoice respjson.Field - Tools respjson.Field - TruncationStrategy respjson.Field - Usage respjson.Field - Temperature respjson.Field - TopP respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r Run) RawJSON() string { return r.JSON.raw } -func (r *Run) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Details on why the run is incomplete. Will be `null` if the run is not -// incomplete. -type RunIncompleteDetails struct { - // The reason why the run is incomplete. This will point to which specific token - // limit was reached over the course of the run. - // - // Any of "max_completion_tokens", "max_prompt_tokens". - Reason string `json:"reason"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Reason respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r RunIncompleteDetails) RawJSON() string { return r.JSON.raw } -func (r *RunIncompleteDetails) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The last error associated with this run. Will be `null` if there are no errors. -type RunLastError struct { - // One of `server_error`, `rate_limit_exceeded`, or `invalid_prompt`. - // - // Any of "server_error", "rate_limit_exceeded", "invalid_prompt". - Code string `json:"code,required"` - // A human-readable description of the error. - Message string `json:"message,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Code respjson.Field - Message respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r RunLastError) RawJSON() string { return r.JSON.raw } -func (r *RunLastError) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Details on the action required to continue the run. Will be `null` if no action -// is required. -type RunRequiredAction struct { - // Details on the tool outputs needed for this run to continue. - SubmitToolOutputs RunRequiredActionSubmitToolOutputs `json:"submit_tool_outputs,required"` - // For now, this is always `submit_tool_outputs`. - Type constant.SubmitToolOutputs `json:"type,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - SubmitToolOutputs respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r RunRequiredAction) RawJSON() string { return r.JSON.raw } -func (r *RunRequiredAction) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Details on the tool outputs needed for this run to continue. -type RunRequiredActionSubmitToolOutputs struct { - // A list of the relevant tool calls. - ToolCalls []RequiredActionFunctionToolCall `json:"tool_calls,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ToolCalls respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r RunRequiredActionSubmitToolOutputs) RawJSON() string { return r.JSON.raw } -func (r *RunRequiredActionSubmitToolOutputs) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Controls for how a thread will be truncated prior to the run. Use this to -// control the intial context window of the run. -type RunTruncationStrategy struct { - // 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`. - // - // Any of "auto", "last_messages". - Type string `json:"type,required"` - // The number of most recent messages from the thread when constructing the context - // for the run. - LastMessages int64 `json:"last_messages,nullable"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Type respjson.Field - LastMessages respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r RunTruncationStrategy) RawJSON() string { return r.JSON.raw } -func (r *RunTruncationStrategy) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// 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.). -type RunUsage struct { - // Number of completion tokens used over the course of the run. - CompletionTokens int64 `json:"completion_tokens,required"` - // Number of prompt tokens used over the course of the run. - PromptTokens int64 `json:"prompt_tokens,required"` - // Total number of tokens used (prompt + completion). - TotalTokens int64 `json:"total_tokens,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - CompletionTokens respjson.Field - PromptTokens respjson.Field - TotalTokens respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r RunUsage) RawJSON() string { return r.JSON.raw } -func (r *RunUsage) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The status of the run, which can be either `queued`, `in_progress`, -// `requires_action`, `cancelling`, `cancelled`, `failed`, `completed`, -// `incomplete`, or `expired`. -type RunStatus string - -const ( - RunStatusQueued RunStatus = "queued" - RunStatusInProgress RunStatus = "in_progress" - RunStatusRequiresAction RunStatus = "requires_action" - RunStatusCancelling RunStatus = "cancelling" - RunStatusCancelled RunStatus = "cancelled" - RunStatusFailed RunStatus = "failed" - RunStatusCompleted RunStatus = "completed" - RunStatusIncomplete RunStatus = "incomplete" - RunStatusExpired RunStatus = "expired" -) - -type BetaThreadRunNewParams struct { - // The ID of the - // [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to - // execute this run. - AssistantID string `json:"assistant_id,required"` - // 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. - AdditionalInstructions param.Opt[string] `json:"additional_instructions,omitzero"` - // Overrides the - // [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant) - // of the assistant. This is useful for modifying the behavior on a per-run basis. - Instructions param.Opt[string] `json:"instructions,omitzero"` - // 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. - MaxCompletionTokens param.Opt[int64] `json:"max_completion_tokens,omitzero"` - // 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. - MaxPromptTokens param.Opt[int64] `json:"max_prompt_tokens,omitzero"` - // 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. - Temperature param.Opt[float64] `json:"temperature,omitzero"` - // 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 param.Opt[float64] `json:"top_p,omitzero"` - // Whether to enable - // [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) - // during tool use. - ParallelToolCalls param.Opt[bool] `json:"parallel_tool_calls,omitzero"` - // Adds additional messages to the thread before creating the run. - AdditionalMessages []BetaThreadRunNewParamsAdditionalMessage `json:"additional_messages,omitzero"` - // 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, and - // querying for objects via API or the dashboard. - // - // Keys are strings with a maximum length of 64 characters. Values are strings with - // a maximum length of 512 characters. - Metadata shared.Metadata `json:"metadata,omitzero"` - // The ID of the [Model](https://platform.openai.com/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. - Model shared.ChatModel `json:"model,omitzero"` - // **o-series models only** - // - // Constrains effort on reasoning for - // [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently - // supported values are `low`, `medium`, and `high`. Reducing reasoning effort can - // result in faster responses and fewer tokens used on reasoning in a response. - // - // Any of "low", "medium", "high". - ReasoningEffort shared.ReasoningEffort `json:"reasoning_effort,omitzero"` - // Override the tools the assistant can use for this run. This is useful for - // modifying the behavior on a per-run basis. - Tools []AssistantToolUnionParam `json:"tools,omitzero"` - // Controls for how a thread will be truncated prior to the run. Use this to - // control the intial context window of the run. - TruncationStrategy BetaThreadRunNewParamsTruncationStrategy `json:"truncation_strategy,omitzero"` - // A list of additional fields to include in the response. Currently the only - // supported value is `step_details.tool_calls[*].file_search.results[*].content` - // to fetch the file search result content. - // - // See the - // [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) - // for more information. - Include []RunStepInclude `query:"include,omitzero" json:"-"` - // Specifies the format that the model must output. Compatible with - // [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), - // [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), - // and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. - // - // Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured - // Outputs which ensures the model will match your supplied JSON schema. Learn more - // in the - // [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). - // - // Setting to `{ "type": "json_object" }` enables JSON mode, which ensures 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 AssistantResponseFormatOptionUnionParam `json:"response_format,omitzero"` - // 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. - ToolChoice AssistantToolChoiceOptionUnionParam `json:"tool_choice,omitzero"` - paramObj -} - -func (r BetaThreadRunNewParams) MarshalJSON() (data []byte, err error) { - type shadow BetaThreadRunNewParams - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaThreadRunNewParams) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// URLQuery serializes [BetaThreadRunNewParams]'s query parameters as `url.Values`. -func (r BetaThreadRunNewParams) URLQuery() (v url.Values, err error) { - return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ - ArrayFormat: apiquery.ArrayQueryFormatBrackets, - NestedFormat: apiquery.NestedQueryFormatBrackets, - }) -} - -// The properties Content, Role are required. -type BetaThreadRunNewParamsAdditionalMessage struct { - // The text contents of the message. - Content BetaThreadRunNewParamsAdditionalMessageContentUnion `json:"content,omitzero,required"` - // 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. - // - // Any of "user", "assistant". - Role string `json:"role,omitzero,required"` - // A list of files attached to the message, and the tools they should be added to. - Attachments []BetaThreadRunNewParamsAdditionalMessageAttachment `json:"attachments,omitzero"` - // 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, and - // querying for objects via API or the dashboard. - // - // Keys are strings with a maximum length of 64 characters. Values are strings with - // a maximum length of 512 characters. - Metadata shared.Metadata `json:"metadata,omitzero"` - paramObj -} - -func (r BetaThreadRunNewParamsAdditionalMessage) MarshalJSON() (data []byte, err error) { - type shadow BetaThreadRunNewParamsAdditionalMessage - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaThreadRunNewParamsAdditionalMessage) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -func init() { - apijson.RegisterFieldValidator[BetaThreadRunNewParamsAdditionalMessage]( - "role", "user", "assistant", - ) -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type BetaThreadRunNewParamsAdditionalMessageContentUnion struct { - OfString param.Opt[string] `json:",omitzero,inline"` - OfArrayOfContentParts []MessageContentPartParamUnion `json:",omitzero,inline"` - paramUnion -} - -func (u BetaThreadRunNewParamsAdditionalMessageContentUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfString, u.OfArrayOfContentParts) -} -func (u *BetaThreadRunNewParamsAdditionalMessageContentUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *BetaThreadRunNewParamsAdditionalMessageContentUnion) asAny() any { - if !param.IsOmitted(u.OfString) { - return &u.OfString.Value - } else if !param.IsOmitted(u.OfArrayOfContentParts) { - return &u.OfArrayOfContentParts - } - return nil -} - -type BetaThreadRunNewParamsAdditionalMessageAttachment struct { - // The ID of the file to attach to the message. - FileID param.Opt[string] `json:"file_id,omitzero"` - // The tools to add this file to. - Tools []BetaThreadRunNewParamsAdditionalMessageAttachmentToolUnion `json:"tools,omitzero"` - paramObj -} - -func (r BetaThreadRunNewParamsAdditionalMessageAttachment) MarshalJSON() (data []byte, err error) { - type shadow BetaThreadRunNewParamsAdditionalMessageAttachment - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaThreadRunNewParamsAdditionalMessageAttachment) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type BetaThreadRunNewParamsAdditionalMessageAttachmentToolUnion struct { - OfCodeInterpreter *CodeInterpreterToolParam `json:",omitzero,inline"` - OfFileSearch *BetaThreadRunNewParamsAdditionalMessageAttachmentToolFileSearch `json:",omitzero,inline"` - paramUnion -} - -func (u BetaThreadRunNewParamsAdditionalMessageAttachmentToolUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfCodeInterpreter, u.OfFileSearch) -} -func (u *BetaThreadRunNewParamsAdditionalMessageAttachmentToolUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *BetaThreadRunNewParamsAdditionalMessageAttachmentToolUnion) asAny() any { - if !param.IsOmitted(u.OfCodeInterpreter) { - return u.OfCodeInterpreter - } else if !param.IsOmitted(u.OfFileSearch) { - return u.OfFileSearch - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u BetaThreadRunNewParamsAdditionalMessageAttachmentToolUnion) GetType() *string { - if vt := u.OfCodeInterpreter; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfFileSearch; vt != nil { - return (*string)(&vt.Type) - } - return nil -} - -func init() { - apijson.RegisterUnion[BetaThreadRunNewParamsAdditionalMessageAttachmentToolUnion]( - "type", - apijson.Discriminator[CodeInterpreterToolParam]("code_interpreter"), - apijson.Discriminator[BetaThreadRunNewParamsAdditionalMessageAttachmentToolFileSearch]("file_search"), - ) -} - -func NewBetaThreadRunNewParamsAdditionalMessageAttachmentToolFileSearch() BetaThreadRunNewParamsAdditionalMessageAttachmentToolFileSearch { - return BetaThreadRunNewParamsAdditionalMessageAttachmentToolFileSearch{ - Type: "file_search", - } -} - -// This struct has a constant value, construct it with -// [NewBetaThreadRunNewParamsAdditionalMessageAttachmentToolFileSearch]. -type BetaThreadRunNewParamsAdditionalMessageAttachmentToolFileSearch struct { - // The type of tool being defined: `file_search` - Type constant.FileSearch `json:"type,required"` - paramObj -} - -func (r BetaThreadRunNewParamsAdditionalMessageAttachmentToolFileSearch) MarshalJSON() (data []byte, err error) { - type shadow BetaThreadRunNewParamsAdditionalMessageAttachmentToolFileSearch - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaThreadRunNewParamsAdditionalMessageAttachmentToolFileSearch) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Controls for how a thread will be truncated prior to the run. Use this to -// control the intial context window of the run. -// -// The property Type is required. -type BetaThreadRunNewParamsTruncationStrategy struct { - // 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`. - // - // Any of "auto", "last_messages". - Type string `json:"type,omitzero,required"` - // The number of most recent messages from the thread when constructing the context - // for the run. - LastMessages param.Opt[int64] `json:"last_messages,omitzero"` - paramObj -} - -func (r BetaThreadRunNewParamsTruncationStrategy) MarshalJSON() (data []byte, err error) { - type shadow BetaThreadRunNewParamsTruncationStrategy - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaThreadRunNewParamsTruncationStrategy) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -func init() { - apijson.RegisterFieldValidator[BetaThreadRunNewParamsTruncationStrategy]( - "type", "auto", "last_messages", - ) -} - -type BetaThreadRunUpdateParams struct { - // 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, and - // querying for objects via API or the dashboard. - // - // Keys are strings with a maximum length of 64 characters. Values are strings with - // a maximum length of 512 characters. - Metadata shared.Metadata `json:"metadata,omitzero"` - paramObj -} - -func (r BetaThreadRunUpdateParams) MarshalJSON() (data []byte, err error) { - type shadow BetaThreadRunUpdateParams - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaThreadRunUpdateParams) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type BetaThreadRunListParams struct { - // 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. - After param.Opt[string] `query:"after,omitzero" json:"-"` - // A cursor for use in pagination. `before` is an object ID that defines your place - // in the list. For instance, if you make a list request and receive 100 objects, - // starting with obj_foo, your subsequent call can include before=obj_foo in order - // to fetch the previous page of the list. - Before param.Opt[string] `query:"before,omitzero" json:"-"` - // A limit on the number of objects to be returned. Limit can range between 1 and - // 100, and the default is 20. - Limit param.Opt[int64] `query:"limit,omitzero" json:"-"` - // Sort order by the `created_at` timestamp of the objects. `asc` for ascending - // order and `desc` for descending order. - // - // Any of "asc", "desc". - Order BetaThreadRunListParamsOrder `query:"order,omitzero" json:"-"` - paramObj -} - -// URLQuery serializes [BetaThreadRunListParams]'s query parameters as -// `url.Values`. -func (r BetaThreadRunListParams) URLQuery() (v url.Values, err error) { - return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ - ArrayFormat: apiquery.ArrayQueryFormatBrackets, - NestedFormat: apiquery.NestedQueryFormatBrackets, - }) -} - -// Sort order by the `created_at` timestamp of the objects. `asc` for ascending -// order and `desc` for descending order. -type BetaThreadRunListParamsOrder string - -const ( - BetaThreadRunListParamsOrderAsc BetaThreadRunListParamsOrder = "asc" - BetaThreadRunListParamsOrderDesc BetaThreadRunListParamsOrder = "desc" -) - -type BetaThreadRunSubmitToolOutputsParams struct { - // A list of tools for which the outputs are being submitted. - ToolOutputs []BetaThreadRunSubmitToolOutputsParamsToolOutput `json:"tool_outputs,omitzero,required"` - paramObj -} - -func (r BetaThreadRunSubmitToolOutputsParams) MarshalJSON() (data []byte, err error) { - type shadow BetaThreadRunSubmitToolOutputsParams - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaThreadRunSubmitToolOutputsParams) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type BetaThreadRunSubmitToolOutputsParamsToolOutput struct { - // The output of the tool call to be submitted to continue the run. - Output param.Opt[string] `json:"output,omitzero"` - // The ID of the tool call in the `required_action` object within the run object - // the output is being submitted for. - ToolCallID param.Opt[string] `json:"tool_call_id,omitzero"` - paramObj -} - -func (r BetaThreadRunSubmitToolOutputsParamsToolOutput) MarshalJSON() (data []byte, err error) { - type shadow BetaThreadRunSubmitToolOutputsParamsToolOutput - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *BetaThreadRunSubmitToolOutputsParamsToolOutput) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} diff --git a/vendor/github.com/openai/openai-go/betathreadrunstep.go b/vendor/github.com/openai/openai-go/betathreadrunstep.go deleted file mode 100644 index 1ae783e5..00000000 --- a/vendor/github.com/openai/openai-go/betathreadrunstep.go +++ /dev/null @@ -1,1393 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -package openai - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "net/http" - "net/url" - - "github.com/openai/openai-go/internal/apijson" - "github.com/openai/openai-go/internal/apiquery" - "github.com/openai/openai-go/internal/requestconfig" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/packages/pagination" - "github.com/openai/openai-go/packages/param" - "github.com/openai/openai-go/packages/respjson" - "github.com/openai/openai-go/shared" - "github.com/openai/openai-go/shared/constant" -) - -// BetaThreadRunStepService contains methods and other services that help with -// interacting with the openai API. -// -// Note, unlike clients, this service does not read variables from the environment -// automatically. You should not instantiate this service directly, and instead use -// the [NewBetaThreadRunStepService] method instead. -// -// Deprecated: The Assistants API is deprecated in favor of the Responses API -type BetaThreadRunStepService struct { - Options []option.RequestOption -} - -// NewBetaThreadRunStepService generates a new service that applies the given -// options to each request. These options are applied after the parent client's -// options (if there is one), and before any request-specific options. -func NewBetaThreadRunStepService(opts ...option.RequestOption) (r BetaThreadRunStepService) { - r = BetaThreadRunStepService{} - r.Options = opts - return -} - -// Retrieves a run step. -// -// Deprecated: The Assistants API is deprecated in favor of the Responses API -func (r *BetaThreadRunStepService) Get(ctx context.Context, threadID string, runID string, stepID string, query BetaThreadRunStepGetParams, opts ...option.RequestOption) (res *RunStep, err error) { - opts = append(r.Options[:], opts...) - opts = append([]option.RequestOption{option.WithHeader("OpenAI-Beta", "assistants=v2")}, opts...) - if threadID == "" { - err = errors.New("missing required thread_id parameter") - return - } - if runID == "" { - err = errors.New("missing required run_id parameter") - return - } - if stepID == "" { - err = errors.New("missing required step_id parameter") - return - } - path := fmt.Sprintf("threads/%s/runs/%s/steps/%s", threadID, runID, stepID) - err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, query, &res, opts...) - return -} - -// Returns a list of run steps belonging to a run. -// -// Deprecated: The Assistants API is deprecated in favor of the Responses API -func (r *BetaThreadRunStepService) List(ctx context.Context, threadID string, runID string, query BetaThreadRunStepListParams, opts ...option.RequestOption) (res *pagination.CursorPage[RunStep], err error) { - var raw *http.Response - opts = append(r.Options[:], opts...) - opts = append([]option.RequestOption{option.WithHeader("OpenAI-Beta", "assistants=v2"), option.WithResponseInto(&raw)}, opts...) - if threadID == "" { - err = errors.New("missing required thread_id parameter") - return - } - if runID == "" { - err = errors.New("missing required run_id parameter") - return - } - path := fmt.Sprintf("threads/%s/runs/%s/steps", threadID, runID) - cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, query, &res, opts...) - if err != nil { - return nil, err - } - err = cfg.Execute() - if err != nil { - return nil, err - } - res.SetPageConfig(cfg, raw) - return res, nil -} - -// Returns a list of run steps belonging to a run. -// -// Deprecated: The Assistants API is deprecated in favor of the Responses API -func (r *BetaThreadRunStepService) ListAutoPaging(ctx context.Context, threadID string, runID string, query BetaThreadRunStepListParams, opts ...option.RequestOption) *pagination.CursorPageAutoPager[RunStep] { - return pagination.NewCursorPageAutoPager(r.List(ctx, threadID, runID, query, opts...)) -} - -// Text output from the Code Interpreter tool call as part of a run step. -type CodeInterpreterLogs struct { - // The index of the output in the outputs array. - Index int64 `json:"index,required"` - // Always `logs`. - Type constant.Logs `json:"type,required"` - // The text output from the Code Interpreter tool call. - Logs string `json:"logs"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Index respjson.Field - Type respjson.Field - Logs respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r CodeInterpreterLogs) RawJSON() string { return r.JSON.raw } -func (r *CodeInterpreterLogs) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type CodeInterpreterOutputImage struct { - // The index of the output in the outputs array. - Index int64 `json:"index,required"` - // Always `image`. - Type constant.Image `json:"type,required"` - Image CodeInterpreterOutputImageImage `json:"image"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Index respjson.Field - Type respjson.Field - Image respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r CodeInterpreterOutputImage) RawJSON() string { return r.JSON.raw } -func (r *CodeInterpreterOutputImage) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type CodeInterpreterOutputImageImage struct { - // The [file](https://platform.openai.com/docs/api-reference/files) ID of the - // image. - FileID string `json:"file_id"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - FileID respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r CodeInterpreterOutputImageImage) RawJSON() string { return r.JSON.raw } -func (r *CodeInterpreterOutputImageImage) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Details of the Code Interpreter tool call the run step was involved in. -type CodeInterpreterToolCall struct { - // The ID of the tool call. - ID string `json:"id,required"` - // The Code Interpreter tool call definition. - CodeInterpreter CodeInterpreterToolCallCodeInterpreter `json:"code_interpreter,required"` - // The type of tool call. This is always going to be `code_interpreter` for this - // type of tool call. - Type constant.CodeInterpreter `json:"type,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ID respjson.Field - CodeInterpreter respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r CodeInterpreterToolCall) RawJSON() string { return r.JSON.raw } -func (r *CodeInterpreterToolCall) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The Code Interpreter tool call definition. -type CodeInterpreterToolCallCodeInterpreter struct { - // The input to the Code Interpreter tool call. - Input string `json:"input,required"` - // 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. - Outputs []CodeInterpreterToolCallCodeInterpreterOutputUnion `json:"outputs,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Input respjson.Field - Outputs respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r CodeInterpreterToolCallCodeInterpreter) RawJSON() string { return r.JSON.raw } -func (r *CodeInterpreterToolCallCodeInterpreter) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// CodeInterpreterToolCallCodeInterpreterOutputUnion contains all possible -// properties and values from [CodeInterpreterToolCallCodeInterpreterOutputLogs], -// [CodeInterpreterToolCallCodeInterpreterOutputImage]. -// -// Use the [CodeInterpreterToolCallCodeInterpreterOutputUnion.AsAny] method to -// switch on the variant. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -type CodeInterpreterToolCallCodeInterpreterOutputUnion struct { - // This field is from variant [CodeInterpreterToolCallCodeInterpreterOutputLogs]. - Logs string `json:"logs"` - // Any of "logs", "image". - Type string `json:"type"` - // This field is from variant [CodeInterpreterToolCallCodeInterpreterOutputImage]. - Image CodeInterpreterToolCallCodeInterpreterOutputImageImage `json:"image"` - JSON struct { - Logs respjson.Field - Type respjson.Field - Image respjson.Field - raw string - } `json:"-"` -} - -// anyCodeInterpreterToolCallCodeInterpreterOutput is implemented by each variant -// of [CodeInterpreterToolCallCodeInterpreterOutputUnion] to add type safety for -// the return type of [CodeInterpreterToolCallCodeInterpreterOutputUnion.AsAny] -type anyCodeInterpreterToolCallCodeInterpreterOutput interface { - implCodeInterpreterToolCallCodeInterpreterOutputUnion() -} - -func (CodeInterpreterToolCallCodeInterpreterOutputLogs) implCodeInterpreterToolCallCodeInterpreterOutputUnion() { -} -func (CodeInterpreterToolCallCodeInterpreterOutputImage) implCodeInterpreterToolCallCodeInterpreterOutputUnion() { -} - -// Use the following switch statement to find the correct variant -// -// switch variant := CodeInterpreterToolCallCodeInterpreterOutputUnion.AsAny().(type) { -// case openai.CodeInterpreterToolCallCodeInterpreterOutputLogs: -// case openai.CodeInterpreterToolCallCodeInterpreterOutputImage: -// default: -// fmt.Errorf("no variant present") -// } -func (u CodeInterpreterToolCallCodeInterpreterOutputUnion) AsAny() anyCodeInterpreterToolCallCodeInterpreterOutput { - switch u.Type { - case "logs": - return u.AsLogs() - case "image": - return u.AsImage() - } - return nil -} - -func (u CodeInterpreterToolCallCodeInterpreterOutputUnion) AsLogs() (v CodeInterpreterToolCallCodeInterpreterOutputLogs) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u CodeInterpreterToolCallCodeInterpreterOutputUnion) AsImage() (v CodeInterpreterToolCallCodeInterpreterOutputImage) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -// Returns the unmodified JSON received from the API -func (u CodeInterpreterToolCallCodeInterpreterOutputUnion) RawJSON() string { return u.JSON.raw } - -func (r *CodeInterpreterToolCallCodeInterpreterOutputUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Text output from the Code Interpreter tool call as part of a run step. -type CodeInterpreterToolCallCodeInterpreterOutputLogs struct { - // The text output from the Code Interpreter tool call. - Logs string `json:"logs,required"` - // Always `logs`. - Type constant.Logs `json:"type,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Logs respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r CodeInterpreterToolCallCodeInterpreterOutputLogs) RawJSON() string { return r.JSON.raw } -func (r *CodeInterpreterToolCallCodeInterpreterOutputLogs) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type CodeInterpreterToolCallCodeInterpreterOutputImage struct { - Image CodeInterpreterToolCallCodeInterpreterOutputImageImage `json:"image,required"` - // Always `image`. - Type constant.Image `json:"type,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Image respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r CodeInterpreterToolCallCodeInterpreterOutputImage) RawJSON() string { return r.JSON.raw } -func (r *CodeInterpreterToolCallCodeInterpreterOutputImage) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type CodeInterpreterToolCallCodeInterpreterOutputImageImage struct { - // The [file](https://platform.openai.com/docs/api-reference/files) ID of the - // image. - FileID string `json:"file_id,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - FileID respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r CodeInterpreterToolCallCodeInterpreterOutputImageImage) RawJSON() string { return r.JSON.raw } -func (r *CodeInterpreterToolCallCodeInterpreterOutputImageImage) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Details of the Code Interpreter tool call the run step was involved in. -type CodeInterpreterToolCallDelta struct { - // The index of the tool call in the tool calls array. - Index int64 `json:"index,required"` - // The type of tool call. This is always going to be `code_interpreter` for this - // type of tool call. - Type constant.CodeInterpreter `json:"type,required"` - // The ID of the tool call. - ID string `json:"id"` - // The Code Interpreter tool call definition. - CodeInterpreter CodeInterpreterToolCallDeltaCodeInterpreter `json:"code_interpreter"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Index respjson.Field - Type respjson.Field - ID respjson.Field - CodeInterpreter respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r CodeInterpreterToolCallDelta) RawJSON() string { return r.JSON.raw } -func (r *CodeInterpreterToolCallDelta) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The Code Interpreter tool call definition. -type CodeInterpreterToolCallDeltaCodeInterpreter struct { - // The input to the Code Interpreter tool call. - Input string `json:"input"` - // 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. - Outputs []CodeInterpreterToolCallDeltaCodeInterpreterOutputUnion `json:"outputs"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Input respjson.Field - Outputs respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r CodeInterpreterToolCallDeltaCodeInterpreter) RawJSON() string { return r.JSON.raw } -func (r *CodeInterpreterToolCallDeltaCodeInterpreter) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// CodeInterpreterToolCallDeltaCodeInterpreterOutputUnion contains all possible -// properties and values from [CodeInterpreterLogs], [CodeInterpreterOutputImage]. -// -// Use the [CodeInterpreterToolCallDeltaCodeInterpreterOutputUnion.AsAny] method to -// switch on the variant. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -type CodeInterpreterToolCallDeltaCodeInterpreterOutputUnion struct { - Index int64 `json:"index"` - // Any of "logs", "image". - Type string `json:"type"` - // This field is from variant [CodeInterpreterLogs]. - Logs string `json:"logs"` - // This field is from variant [CodeInterpreterOutputImage]. - Image CodeInterpreterOutputImageImage `json:"image"` - JSON struct { - Index respjson.Field - Type respjson.Field - Logs respjson.Field - Image respjson.Field - raw string - } `json:"-"` -} - -// anyCodeInterpreterToolCallDeltaCodeInterpreterOutput is implemented by each -// variant of [CodeInterpreterToolCallDeltaCodeInterpreterOutputUnion] to add type -// safety for the return type of -// [CodeInterpreterToolCallDeltaCodeInterpreterOutputUnion.AsAny] -type anyCodeInterpreterToolCallDeltaCodeInterpreterOutput interface { - implCodeInterpreterToolCallDeltaCodeInterpreterOutputUnion() -} - -func (CodeInterpreterLogs) implCodeInterpreterToolCallDeltaCodeInterpreterOutputUnion() {} -func (CodeInterpreterOutputImage) implCodeInterpreterToolCallDeltaCodeInterpreterOutputUnion() {} - -// Use the following switch statement to find the correct variant -// -// switch variant := CodeInterpreterToolCallDeltaCodeInterpreterOutputUnion.AsAny().(type) { -// case openai.CodeInterpreterLogs: -// case openai.CodeInterpreterOutputImage: -// default: -// fmt.Errorf("no variant present") -// } -func (u CodeInterpreterToolCallDeltaCodeInterpreterOutputUnion) AsAny() anyCodeInterpreterToolCallDeltaCodeInterpreterOutput { - switch u.Type { - case "logs": - return u.AsLogs() - case "image": - return u.AsImage() - } - return nil -} - -func (u CodeInterpreterToolCallDeltaCodeInterpreterOutputUnion) AsLogs() (v CodeInterpreterLogs) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u CodeInterpreterToolCallDeltaCodeInterpreterOutputUnion) AsImage() (v CodeInterpreterOutputImage) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -// Returns the unmodified JSON received from the API -func (u CodeInterpreterToolCallDeltaCodeInterpreterOutputUnion) RawJSON() string { return u.JSON.raw } - -func (r *CodeInterpreterToolCallDeltaCodeInterpreterOutputUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type FileSearchToolCall struct { - // The ID of the tool call object. - ID string `json:"id,required"` - // For now, this is always going to be an empty object. - FileSearch FileSearchToolCallFileSearch `json:"file_search,required"` - // The type of tool call. This is always going to be `file_search` for this type of - // tool call. - Type constant.FileSearch `json:"type,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ID respjson.Field - FileSearch respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r FileSearchToolCall) RawJSON() string { return r.JSON.raw } -func (r *FileSearchToolCall) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// For now, this is always going to be an empty object. -type FileSearchToolCallFileSearch struct { - // The ranking options for the file search. - RankingOptions FileSearchToolCallFileSearchRankingOptions `json:"ranking_options"` - // The results of the file search. - Results []FileSearchToolCallFileSearchResult `json:"results"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - RankingOptions respjson.Field - Results respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r FileSearchToolCallFileSearch) RawJSON() string { return r.JSON.raw } -func (r *FileSearchToolCallFileSearch) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The ranking options for the file search. -type FileSearchToolCallFileSearchRankingOptions struct { - // The ranker to use for the file search. If not specified will use the `auto` - // ranker. - // - // Any of "auto", "default_2024_08_21". - Ranker string `json:"ranker,required"` - // The score threshold for the file search. All values must be a floating point - // number between 0 and 1. - ScoreThreshold float64 `json:"score_threshold,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Ranker respjson.Field - ScoreThreshold respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r FileSearchToolCallFileSearchRankingOptions) RawJSON() string { return r.JSON.raw } -func (r *FileSearchToolCallFileSearchRankingOptions) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// A result instance of the file search. -type FileSearchToolCallFileSearchResult struct { - // The ID of the file that result was found in. - FileID string `json:"file_id,required"` - // The name of the file that result was found in. - FileName string `json:"file_name,required"` - // The score of the result. All values must be a floating point number between 0 - // and 1. - Score float64 `json:"score,required"` - // The content of the result that was found. The content is only included if - // requested via the include query parameter. - Content []FileSearchToolCallFileSearchResultContent `json:"content"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - FileID respjson.Field - FileName respjson.Field - Score respjson.Field - Content respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r FileSearchToolCallFileSearchResult) RawJSON() string { return r.JSON.raw } -func (r *FileSearchToolCallFileSearchResult) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type FileSearchToolCallFileSearchResultContent struct { - // The text content of the file. - Text string `json:"text"` - // The type of the content. - // - // Any of "text". - Type string `json:"type"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Text respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r FileSearchToolCallFileSearchResultContent) RawJSON() string { return r.JSON.raw } -func (r *FileSearchToolCallFileSearchResultContent) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type FileSearchToolCallDelta struct { - // For now, this is always going to be an empty object. - FileSearch any `json:"file_search,required"` - // The index of the tool call in the tool calls array. - Index int64 `json:"index,required"` - // The type of tool call. This is always going to be `file_search` for this type of - // tool call. - Type constant.FileSearch `json:"type,required"` - // The ID of the tool call object. - ID string `json:"id"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - FileSearch respjson.Field - Index respjson.Field - Type respjson.Field - ID respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r FileSearchToolCallDelta) RawJSON() string { return r.JSON.raw } -func (r *FileSearchToolCallDelta) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type FunctionToolCall struct { - // The ID of the tool call object. - ID string `json:"id,required"` - // The definition of the function that was called. - Function FunctionToolCallFunction `json:"function,required"` - // The type of tool call. This is always going to be `function` for this type of - // tool call. - Type constant.Function `json:"type,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ID respjson.Field - Function respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r FunctionToolCall) RawJSON() string { return r.JSON.raw } -func (r *FunctionToolCall) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The definition of the function that was called. -type FunctionToolCallFunction struct { - // The arguments passed to the function. - Arguments string `json:"arguments,required"` - // The name of the function. - Name string `json:"name,required"` - // The output of the function. This will be `null` if the outputs have not been - // [submitted](https://platform.openai.com/docs/api-reference/runs/submitToolOutputs) - // yet. - Output string `json:"output,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Arguments respjson.Field - Name respjson.Field - Output respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r FunctionToolCallFunction) RawJSON() string { return r.JSON.raw } -func (r *FunctionToolCallFunction) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type FunctionToolCallDelta struct { - // The index of the tool call in the tool calls array. - Index int64 `json:"index,required"` - // The type of tool call. This is always going to be `function` for this type of - // tool call. - Type constant.Function `json:"type,required"` - // The ID of the tool call object. - ID string `json:"id"` - // The definition of the function that was called. - Function FunctionToolCallDeltaFunction `json:"function"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Index respjson.Field - Type respjson.Field - ID respjson.Field - Function respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r FunctionToolCallDelta) RawJSON() string { return r.JSON.raw } -func (r *FunctionToolCallDelta) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The definition of the function that was called. -type FunctionToolCallDeltaFunction struct { - // The arguments passed to the function. - Arguments string `json:"arguments"` - // The name of the function. - Name string `json:"name"` - // The output of the function. This will be `null` if the outputs have not been - // [submitted](https://platform.openai.com/docs/api-reference/runs/submitToolOutputs) - // yet. - Output string `json:"output,nullable"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Arguments respjson.Field - Name respjson.Field - Output respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r FunctionToolCallDeltaFunction) RawJSON() string { return r.JSON.raw } -func (r *FunctionToolCallDeltaFunction) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Details of the message creation by the run step. -type MessageCreationStepDetails struct { - MessageCreation MessageCreationStepDetailsMessageCreation `json:"message_creation,required"` - // Always `message_creation`. - Type constant.MessageCreation `json:"type,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - MessageCreation respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r MessageCreationStepDetails) RawJSON() string { return r.JSON.raw } -func (r *MessageCreationStepDetails) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type MessageCreationStepDetailsMessageCreation struct { - // The ID of the message that was created by this run step. - MessageID string `json:"message_id,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - MessageID respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r MessageCreationStepDetailsMessageCreation) RawJSON() string { return r.JSON.raw } -func (r *MessageCreationStepDetailsMessageCreation) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Represents a step in execution of a run. -type RunStep struct { - // The identifier of the run step, which can be referenced in API endpoints. - ID string `json:"id,required"` - // The ID of the - // [assistant](https://platform.openai.com/docs/api-reference/assistants) - // associated with the run step. - AssistantID string `json:"assistant_id,required"` - // The Unix timestamp (in seconds) for when the run step was cancelled. - CancelledAt int64 `json:"cancelled_at,required"` - // The Unix timestamp (in seconds) for when the run step completed. - CompletedAt int64 `json:"completed_at,required"` - // The Unix timestamp (in seconds) for when the run step was created. - CreatedAt int64 `json:"created_at,required"` - // The Unix timestamp (in seconds) for when the run step expired. A step is - // considered expired if the parent run is expired. - ExpiredAt int64 `json:"expired_at,required"` - // The Unix timestamp (in seconds) for when the run step failed. - FailedAt int64 `json:"failed_at,required"` - // The last error associated with this run step. Will be `null` if there are no - // errors. - LastError RunStepLastError `json:"last_error,required"` - // 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, and - // querying for objects via API or the dashboard. - // - // Keys are strings with a maximum length of 64 characters. Values are strings with - // a maximum length of 512 characters. - Metadata shared.Metadata `json:"metadata,required"` - // The object type, which is always `thread.run.step`. - Object constant.ThreadRunStep `json:"object,required"` - // The ID of the [run](https://platform.openai.com/docs/api-reference/runs) that - // this run step is a part of. - RunID string `json:"run_id,required"` - // The status of the run step, which can be either `in_progress`, `cancelled`, - // `failed`, `completed`, or `expired`. - // - // Any of "in_progress", "cancelled", "failed", "completed", "expired". - Status RunStepStatus `json:"status,required"` - // The details of the run step. - StepDetails RunStepStepDetailsUnion `json:"step_details,required"` - // The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) - // that was run. - ThreadID string `json:"thread_id,required"` - // The type of run step, which can be either `message_creation` or `tool_calls`. - // - // Any of "message_creation", "tool_calls". - Type RunStepType `json:"type,required"` - // Usage statistics related to the run step. This value will be `null` while the - // run step's status is `in_progress`. - Usage RunStepUsage `json:"usage,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ID respjson.Field - AssistantID respjson.Field - CancelledAt respjson.Field - CompletedAt respjson.Field - CreatedAt respjson.Field - ExpiredAt respjson.Field - FailedAt respjson.Field - LastError respjson.Field - Metadata respjson.Field - Object respjson.Field - RunID respjson.Field - Status respjson.Field - StepDetails respjson.Field - ThreadID respjson.Field - Type respjson.Field - Usage respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r RunStep) RawJSON() string { return r.JSON.raw } -func (r *RunStep) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The last error associated with this run step. Will be `null` if there are no -// errors. -type RunStepLastError struct { - // One of `server_error` or `rate_limit_exceeded`. - // - // Any of "server_error", "rate_limit_exceeded". - Code string `json:"code,required"` - // A human-readable description of the error. - Message string `json:"message,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Code respjson.Field - Message respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r RunStepLastError) RawJSON() string { return r.JSON.raw } -func (r *RunStepLastError) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The status of the run step, which can be either `in_progress`, `cancelled`, -// `failed`, `completed`, or `expired`. -type RunStepStatus string - -const ( - RunStepStatusInProgress RunStepStatus = "in_progress" - RunStepStatusCancelled RunStepStatus = "cancelled" - RunStepStatusFailed RunStepStatus = "failed" - RunStepStatusCompleted RunStepStatus = "completed" - RunStepStatusExpired RunStepStatus = "expired" -) - -// RunStepStepDetailsUnion contains all possible properties and values from -// [MessageCreationStepDetails], [ToolCallsStepDetails]. -// -// Use the [RunStepStepDetailsUnion.AsAny] method to switch on the variant. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -type RunStepStepDetailsUnion struct { - // This field is from variant [MessageCreationStepDetails]. - MessageCreation MessageCreationStepDetailsMessageCreation `json:"message_creation"` - // Any of "message_creation", "tool_calls". - Type string `json:"type"` - // This field is from variant [ToolCallsStepDetails]. - ToolCalls []ToolCallUnion `json:"tool_calls"` - JSON struct { - MessageCreation respjson.Field - Type respjson.Field - ToolCalls respjson.Field - raw string - } `json:"-"` -} - -// anyRunStepStepDetails is implemented by each variant of -// [RunStepStepDetailsUnion] to add type safety for the return type of -// [RunStepStepDetailsUnion.AsAny] -type anyRunStepStepDetails interface { - implRunStepStepDetailsUnion() -} - -func (MessageCreationStepDetails) implRunStepStepDetailsUnion() {} -func (ToolCallsStepDetails) implRunStepStepDetailsUnion() {} - -// Use the following switch statement to find the correct variant -// -// switch variant := RunStepStepDetailsUnion.AsAny().(type) { -// case openai.MessageCreationStepDetails: -// case openai.ToolCallsStepDetails: -// default: -// fmt.Errorf("no variant present") -// } -func (u RunStepStepDetailsUnion) AsAny() anyRunStepStepDetails { - switch u.Type { - case "message_creation": - return u.AsMessageCreation() - case "tool_calls": - return u.AsToolCalls() - } - return nil -} - -func (u RunStepStepDetailsUnion) AsMessageCreation() (v MessageCreationStepDetails) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u RunStepStepDetailsUnion) AsToolCalls() (v ToolCallsStepDetails) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -// Returns the unmodified JSON received from the API -func (u RunStepStepDetailsUnion) RawJSON() string { return u.JSON.raw } - -func (r *RunStepStepDetailsUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The type of run step, which can be either `message_creation` or `tool_calls`. -type RunStepType string - -const ( - RunStepTypeMessageCreation RunStepType = "message_creation" - RunStepTypeToolCalls RunStepType = "tool_calls" -) - -// Usage statistics related to the run step. This value will be `null` while the -// run step's status is `in_progress`. -type RunStepUsage struct { - // Number of completion tokens used over the course of the run step. - CompletionTokens int64 `json:"completion_tokens,required"` - // Number of prompt tokens used over the course of the run step. - PromptTokens int64 `json:"prompt_tokens,required"` - // Total number of tokens used (prompt + completion). - TotalTokens int64 `json:"total_tokens,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - CompletionTokens respjson.Field - PromptTokens respjson.Field - TotalTokens respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r RunStepUsage) RawJSON() string { return r.JSON.raw } -func (r *RunStepUsage) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The delta containing the fields that have changed on the run step. -type RunStepDelta struct { - // The details of the run step. - StepDetails RunStepDeltaStepDetailsUnion `json:"step_details"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - StepDetails respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r RunStepDelta) RawJSON() string { return r.JSON.raw } -func (r *RunStepDelta) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// RunStepDeltaStepDetailsUnion contains all possible properties and values from -// [RunStepDeltaMessageDelta], [ToolCallDeltaObject]. -// -// Use the [RunStepDeltaStepDetailsUnion.AsAny] method to switch on the variant. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -type RunStepDeltaStepDetailsUnion struct { - // Any of "message_creation", "tool_calls". - Type string `json:"type"` - // This field is from variant [RunStepDeltaMessageDelta]. - MessageCreation RunStepDeltaMessageDeltaMessageCreation `json:"message_creation"` - // This field is from variant [ToolCallDeltaObject]. - ToolCalls []ToolCallDeltaUnion `json:"tool_calls"` - JSON struct { - Type respjson.Field - MessageCreation respjson.Field - ToolCalls respjson.Field - raw string - } `json:"-"` -} - -// anyRunStepDeltaStepDetails is implemented by each variant of -// [RunStepDeltaStepDetailsUnion] to add type safety for the return type of -// [RunStepDeltaStepDetailsUnion.AsAny] -type anyRunStepDeltaStepDetails interface { - implRunStepDeltaStepDetailsUnion() -} - -func (RunStepDeltaMessageDelta) implRunStepDeltaStepDetailsUnion() {} -func (ToolCallDeltaObject) implRunStepDeltaStepDetailsUnion() {} - -// Use the following switch statement to find the correct variant -// -// switch variant := RunStepDeltaStepDetailsUnion.AsAny().(type) { -// case openai.RunStepDeltaMessageDelta: -// case openai.ToolCallDeltaObject: -// default: -// fmt.Errorf("no variant present") -// } -func (u RunStepDeltaStepDetailsUnion) AsAny() anyRunStepDeltaStepDetails { - switch u.Type { - case "message_creation": - return u.AsMessageCreation() - case "tool_calls": - return u.AsToolCalls() - } - return nil -} - -func (u RunStepDeltaStepDetailsUnion) AsMessageCreation() (v RunStepDeltaMessageDelta) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u RunStepDeltaStepDetailsUnion) AsToolCalls() (v ToolCallDeltaObject) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -// Returns the unmodified JSON received from the API -func (u RunStepDeltaStepDetailsUnion) RawJSON() string { return u.JSON.raw } - -func (r *RunStepDeltaStepDetailsUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Represents a run step delta i.e. any changed fields on a run step during -// streaming. -type RunStepDeltaEvent struct { - // The identifier of the run step, which can be referenced in API endpoints. - ID string `json:"id,required"` - // The delta containing the fields that have changed on the run step. - Delta RunStepDelta `json:"delta,required"` - // The object type, which is always `thread.run.step.delta`. - Object constant.ThreadRunStepDelta `json:"object,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ID respjson.Field - Delta respjson.Field - Object respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r RunStepDeltaEvent) RawJSON() string { return r.JSON.raw } -func (r *RunStepDeltaEvent) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Details of the message creation by the run step. -type RunStepDeltaMessageDelta struct { - // Always `message_creation`. - Type constant.MessageCreation `json:"type,required"` - MessageCreation RunStepDeltaMessageDeltaMessageCreation `json:"message_creation"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Type respjson.Field - MessageCreation respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r RunStepDeltaMessageDelta) RawJSON() string { return r.JSON.raw } -func (r *RunStepDeltaMessageDelta) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type RunStepDeltaMessageDeltaMessageCreation struct { - // The ID of the message that was created by this run step. - MessageID string `json:"message_id"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - MessageID respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r RunStepDeltaMessageDeltaMessageCreation) RawJSON() string { return r.JSON.raw } -func (r *RunStepDeltaMessageDeltaMessageCreation) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type RunStepInclude string - -const ( - RunStepIncludeStepDetailsToolCallsFileSearchResultsContent RunStepInclude = "step_details.tool_calls[*].file_search.results[*].content" -) - -// ToolCallUnion contains all possible properties and values from -// [CodeInterpreterToolCall], [FileSearchToolCall], [FunctionToolCall]. -// -// Use the [ToolCallUnion.AsAny] method to switch on the variant. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -type ToolCallUnion struct { - ID string `json:"id"` - // This field is from variant [CodeInterpreterToolCall]. - CodeInterpreter CodeInterpreterToolCallCodeInterpreter `json:"code_interpreter"` - // Any of "code_interpreter", "file_search", "function". - Type string `json:"type"` - // This field is from variant [FileSearchToolCall]. - FileSearch FileSearchToolCallFileSearch `json:"file_search"` - // This field is from variant [FunctionToolCall]. - Function FunctionToolCallFunction `json:"function"` - JSON struct { - ID respjson.Field - CodeInterpreter respjson.Field - Type respjson.Field - FileSearch respjson.Field - Function respjson.Field - raw string - } `json:"-"` -} - -// anyToolCall is implemented by each variant of [ToolCallUnion] to add type safety -// for the return type of [ToolCallUnion.AsAny] -type anyToolCall interface { - implToolCallUnion() -} - -func (CodeInterpreterToolCall) implToolCallUnion() {} -func (FileSearchToolCall) implToolCallUnion() {} -func (FunctionToolCall) implToolCallUnion() {} - -// Use the following switch statement to find the correct variant -// -// switch variant := ToolCallUnion.AsAny().(type) { -// case openai.CodeInterpreterToolCall: -// case openai.FileSearchToolCall: -// case openai.FunctionToolCall: -// default: -// fmt.Errorf("no variant present") -// } -func (u ToolCallUnion) AsAny() anyToolCall { - switch u.Type { - case "code_interpreter": - return u.AsCodeInterpreter() - case "file_search": - return u.AsFileSearch() - case "function": - return u.AsFunction() - } - return nil -} - -func (u ToolCallUnion) AsCodeInterpreter() (v CodeInterpreterToolCall) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u ToolCallUnion) AsFileSearch() (v FileSearchToolCall) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u ToolCallUnion) AsFunction() (v FunctionToolCall) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -// Returns the unmodified JSON received from the API -func (u ToolCallUnion) RawJSON() string { return u.JSON.raw } - -func (r *ToolCallUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// ToolCallDeltaUnion contains all possible properties and values from -// [CodeInterpreterToolCallDelta], [FileSearchToolCallDelta], -// [FunctionToolCallDelta]. -// -// Use the [ToolCallDeltaUnion.AsAny] method to switch on the variant. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -type ToolCallDeltaUnion struct { - Index int64 `json:"index"` - // Any of "code_interpreter", "file_search", "function". - Type string `json:"type"` - ID string `json:"id"` - // This field is from variant [CodeInterpreterToolCallDelta]. - CodeInterpreter CodeInterpreterToolCallDeltaCodeInterpreter `json:"code_interpreter"` - // This field is from variant [FileSearchToolCallDelta]. - FileSearch any `json:"file_search"` - // This field is from variant [FunctionToolCallDelta]. - Function FunctionToolCallDeltaFunction `json:"function"` - JSON struct { - Index respjson.Field - Type respjson.Field - ID respjson.Field - CodeInterpreter respjson.Field - FileSearch respjson.Field - Function respjson.Field - raw string - } `json:"-"` -} - -// anyToolCallDelta is implemented by each variant of [ToolCallDeltaUnion] to add -// type safety for the return type of [ToolCallDeltaUnion.AsAny] -type anyToolCallDelta interface { - implToolCallDeltaUnion() -} - -func (CodeInterpreterToolCallDelta) implToolCallDeltaUnion() {} -func (FileSearchToolCallDelta) implToolCallDeltaUnion() {} -func (FunctionToolCallDelta) implToolCallDeltaUnion() {} - -// Use the following switch statement to find the correct variant -// -// switch variant := ToolCallDeltaUnion.AsAny().(type) { -// case openai.CodeInterpreterToolCallDelta: -// case openai.FileSearchToolCallDelta: -// case openai.FunctionToolCallDelta: -// default: -// fmt.Errorf("no variant present") -// } -func (u ToolCallDeltaUnion) AsAny() anyToolCallDelta { - switch u.Type { - case "code_interpreter": - return u.AsCodeInterpreter() - case "file_search": - return u.AsFileSearch() - case "function": - return u.AsFunction() - } - return nil -} - -func (u ToolCallDeltaUnion) AsCodeInterpreter() (v CodeInterpreterToolCallDelta) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u ToolCallDeltaUnion) AsFileSearch() (v FileSearchToolCallDelta) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u ToolCallDeltaUnion) AsFunction() (v FunctionToolCallDelta) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -// Returns the unmodified JSON received from the API -func (u ToolCallDeltaUnion) RawJSON() string { return u.JSON.raw } - -func (r *ToolCallDeltaUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Details of the tool call. -type ToolCallDeltaObject struct { - // Always `tool_calls`. - Type constant.ToolCalls `json:"type,required"` - // 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`. - ToolCalls []ToolCallDeltaUnion `json:"tool_calls"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Type respjson.Field - ToolCalls respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ToolCallDeltaObject) RawJSON() string { return r.JSON.raw } -func (r *ToolCallDeltaObject) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Details of the tool call. -type ToolCallsStepDetails struct { - // 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`. - ToolCalls []ToolCallUnion `json:"tool_calls,required"` - // Always `tool_calls`. - Type constant.ToolCalls `json:"type,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ToolCalls respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ToolCallsStepDetails) RawJSON() string { return r.JSON.raw } -func (r *ToolCallsStepDetails) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type BetaThreadRunStepGetParams struct { - // A list of additional fields to include in the response. Currently the only - // supported value is `step_details.tool_calls[*].file_search.results[*].content` - // to fetch the file search result content. - // - // See the - // [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) - // for more information. - Include []RunStepInclude `query:"include,omitzero" json:"-"` - paramObj -} - -// URLQuery serializes [BetaThreadRunStepGetParams]'s query parameters as -// `url.Values`. -func (r BetaThreadRunStepGetParams) URLQuery() (v url.Values, err error) { - return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ - ArrayFormat: apiquery.ArrayQueryFormatBrackets, - NestedFormat: apiquery.NestedQueryFormatBrackets, - }) -} - -type BetaThreadRunStepListParams struct { - // 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. - After param.Opt[string] `query:"after,omitzero" json:"-"` - // A cursor for use in pagination. `before` is an object ID that defines your place - // in the list. For instance, if you make a list request and receive 100 objects, - // starting with obj_foo, your subsequent call can include before=obj_foo in order - // to fetch the previous page of the list. - Before param.Opt[string] `query:"before,omitzero" json:"-"` - // A limit on the number of objects to be returned. Limit can range between 1 and - // 100, and the default is 20. - Limit param.Opt[int64] `query:"limit,omitzero" json:"-"` - // A list of additional fields to include in the response. Currently the only - // supported value is `step_details.tool_calls[*].file_search.results[*].content` - // to fetch the file search result content. - // - // See the - // [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) - // for more information. - Include []RunStepInclude `query:"include,omitzero" json:"-"` - // Sort order by the `created_at` timestamp of the objects. `asc` for ascending - // order and `desc` for descending order. - // - // Any of "asc", "desc". - Order BetaThreadRunStepListParamsOrder `query:"order,omitzero" json:"-"` - paramObj -} - -// URLQuery serializes [BetaThreadRunStepListParams]'s query parameters as -// `url.Values`. -func (r BetaThreadRunStepListParams) URLQuery() (v url.Values, err error) { - return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ - ArrayFormat: apiquery.ArrayQueryFormatBrackets, - NestedFormat: apiquery.NestedQueryFormatBrackets, - }) -} - -// Sort order by the `created_at` timestamp of the objects. `asc` for ascending -// order and `desc` for descending order. -type BetaThreadRunStepListParamsOrder string - -const ( - BetaThreadRunStepListParamsOrderAsc BetaThreadRunStepListParamsOrder = "asc" - BetaThreadRunStepListParamsOrderDesc BetaThreadRunStepListParamsOrder = "desc" -) diff --git a/vendor/github.com/openai/openai-go/chat.go b/vendor/github.com/openai/openai-go/chat.go deleted file mode 100644 index f579dc3c..00000000 --- a/vendor/github.com/openai/openai-go/chat.go +++ /dev/null @@ -1,28 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -package openai - -import ( - "github.com/openai/openai-go/option" -) - -// ChatService contains methods and other services that help with interacting with -// the openai API. -// -// Note, unlike clients, this service does not read variables from the environment -// automatically. You should not instantiate this service directly, and instead use -// the [NewChatService] method instead. -type ChatService struct { - Options []option.RequestOption - Completions ChatCompletionService -} - -// NewChatService generates a new service that applies the given options to each -// request. These options are applied after the parent client's options (if there -// is one), and before any request-specific options. -func NewChatService(opts ...option.RequestOption) (r ChatService) { - r = ChatService{} - r.Options = opts - r.Completions = NewChatCompletionService(opts...) - return -} diff --git a/vendor/github.com/openai/openai-go/chatcompletion.go b/vendor/github.com/openai/openai-go/chatcompletion.go deleted file mode 100644 index 4ebf54b5..00000000 --- a/vendor/github.com/openai/openai-go/chatcompletion.go +++ /dev/null @@ -1,2738 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -package openai - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "net/http" - "net/url" - - "github.com/openai/openai-go/internal/apijson" - "github.com/openai/openai-go/internal/apiquery" - "github.com/openai/openai-go/internal/requestconfig" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/packages/pagination" - "github.com/openai/openai-go/packages/param" - "github.com/openai/openai-go/packages/respjson" - "github.com/openai/openai-go/packages/ssestream" - "github.com/openai/openai-go/shared" - "github.com/openai/openai-go/shared/constant" -) - -// ChatCompletionService contains methods and other services that help with -// interacting with the openai API. -// -// Note, unlike clients, this service does not read variables from the environment -// automatically. You should not instantiate this service directly, and instead use -// the [NewChatCompletionService] method instead. -type ChatCompletionService struct { - Options []option.RequestOption - Messages ChatCompletionMessageService -} - -// NewChatCompletionService generates a new service that applies the given options -// to each request. These options are applied after the parent client's options (if -// there is one), and before any request-specific options. -func NewChatCompletionService(opts ...option.RequestOption) (r ChatCompletionService) { - r = ChatCompletionService{} - r.Options = opts - r.Messages = NewChatCompletionMessageService(opts...) - return -} - -// **Starting a new project?** We recommend trying -// [Responses](https://platform.openai.com/docs/api-reference/responses) to take -// advantage of the latest OpenAI platform features. Compare -// [Chat Completions with Responses](https://platform.openai.com/docs/guides/responses-vs-chat-completions?api-mode=responses). -// -// --- -// -// Creates a model response for the given chat conversation. Learn more in the -// [text generation](https://platform.openai.com/docs/guides/text-generation), -// [vision](https://platform.openai.com/docs/guides/vision), and -// [audio](https://platform.openai.com/docs/guides/audio) guides. -// -// Parameter support can differ depending on the model used to generate the -// response, particularly for newer reasoning models. Parameters that are only -// supported for reasoning models are noted below. For the current state of -// unsupported parameters in reasoning models, -// [refer to the reasoning guide](https://platform.openai.com/docs/guides/reasoning). -func (r *ChatCompletionService) New(ctx context.Context, body ChatCompletionNewParams, opts ...option.RequestOption) (res *ChatCompletion, err error) { - opts = append(r.Options[:], opts...) - path := "chat/completions" - err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...) - return -} - -// **Starting a new project?** We recommend trying -// [Responses](https://platform.openai.com/docs/api-reference/responses) to take -// advantage of the latest OpenAI platform features. Compare -// [Chat Completions with Responses](https://platform.openai.com/docs/guides/responses-vs-chat-completions?api-mode=responses). -// -// --- -// -// Creates a model response for the given chat conversation. Learn more in the -// [text generation](https://platform.openai.com/docs/guides/text-generation), -// [vision](https://platform.openai.com/docs/guides/vision), and -// [audio](https://platform.openai.com/docs/guides/audio) guides. -// -// Parameter support can differ depending on the model used to generate the -// response, particularly for newer reasoning models. Parameters that are only -// supported for reasoning models are noted below. For the current state of -// unsupported parameters in reasoning models, -// [refer to the reasoning guide](https://platform.openai.com/docs/guides/reasoning). -func (r *ChatCompletionService) NewStreaming(ctx context.Context, body ChatCompletionNewParams, opts ...option.RequestOption) (stream *ssestream.Stream[ChatCompletionChunk]) { - var ( - raw *http.Response - err error - ) - opts = append(r.Options[:], opts...) - opts = append([]option.RequestOption{option.WithJSONSet("stream", true)}, opts...) - path := "chat/completions" - err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &raw, opts...) - return ssestream.NewStream[ChatCompletionChunk](ssestream.NewDecoder(raw), err) -} - -// Get a stored chat completion. Only Chat Completions that have been created with -// the `store` parameter set to `true` will be returned. -func (r *ChatCompletionService) Get(ctx context.Context, completionID string, opts ...option.RequestOption) (res *ChatCompletion, err error) { - opts = append(r.Options[:], opts...) - if completionID == "" { - err = errors.New("missing required completion_id parameter") - return - } - path := fmt.Sprintf("chat/completions/%s", completionID) - err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...) - return -} - -// Modify a stored chat completion. Only Chat Completions that have been created -// with the `store` parameter set to `true` can be modified. Currently, the only -// supported modification is to update the `metadata` field. -func (r *ChatCompletionService) Update(ctx context.Context, completionID string, body ChatCompletionUpdateParams, opts ...option.RequestOption) (res *ChatCompletion, err error) { - opts = append(r.Options[:], opts...) - if completionID == "" { - err = errors.New("missing required completion_id parameter") - return - } - path := fmt.Sprintf("chat/completions/%s", completionID) - err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...) - return -} - -// List stored Chat Completions. Only Chat Completions that have been stored with -// the `store` parameter set to `true` will be returned. -func (r *ChatCompletionService) List(ctx context.Context, query ChatCompletionListParams, opts ...option.RequestOption) (res *pagination.CursorPage[ChatCompletion], err error) { - var raw *http.Response - opts = append(r.Options[:], opts...) - opts = append([]option.RequestOption{option.WithResponseInto(&raw)}, opts...) - path := "chat/completions" - cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, query, &res, opts...) - if err != nil { - return nil, err - } - err = cfg.Execute() - if err != nil { - return nil, err - } - res.SetPageConfig(cfg, raw) - return res, nil -} - -// List stored Chat Completions. Only Chat Completions that have been stored with -// the `store` parameter set to `true` will be returned. -func (r *ChatCompletionService) ListAutoPaging(ctx context.Context, query ChatCompletionListParams, opts ...option.RequestOption) *pagination.CursorPageAutoPager[ChatCompletion] { - return pagination.NewCursorPageAutoPager(r.List(ctx, query, opts...)) -} - -// Delete a stored chat completion. Only Chat Completions that have been created -// with the `store` parameter set to `true` can be deleted. -func (r *ChatCompletionService) Delete(ctx context.Context, completionID string, opts ...option.RequestOption) (res *ChatCompletionDeleted, err error) { - opts = append(r.Options[:], opts...) - if completionID == "" { - err = errors.New("missing required completion_id parameter") - return - } - path := fmt.Sprintf("chat/completions/%s", completionID) - err = requestconfig.ExecuteNewRequest(ctx, http.MethodDelete, path, nil, &res, opts...) - return -} - -// Represents a chat completion response returned by model, based on the provided -// input. -type ChatCompletion struct { - // A unique identifier for the chat completion. - ID string `json:"id,required"` - // A list of chat completion choices. Can be more than one if `n` is greater - // than 1. - Choices []ChatCompletionChoice `json:"choices,required"` - // The Unix timestamp (in seconds) of when the chat completion was created. - Created int64 `json:"created,required"` - // The model used for the chat completion. - Model string `json:"model,required"` - // The object type, which is always `chat.completion`. - Object constant.ChatCompletion `json:"object,required"` - // Specifies the processing type used for serving the request. - // - // - If set to 'auto', then the request will be processed with the service tier - // configured in the Project settings. Unless otherwise configured, the Project - // will use 'default'. - // - If set to 'default', then the request will be processed with the standard - // pricing and performance for the selected model. - // - If set to '[flex](https://platform.openai.com/docs/guides/flex-processing)' or - // 'priority', then the request will be processed with the corresponding service - // tier. [Contact sales](https://openai.com/contact-sales) to learn more about - // Priority processing. - // - When not set, the default behavior is 'auto'. - // - // When the `service_tier` parameter is set, the response body will include the - // `service_tier` value based on the processing mode actually used to serve the - // request. This response value may be different from the value set in the - // parameter. - // - // Any of "auto", "default", "flex", "scale", "priority". - ServiceTier ChatCompletionServiceTier `json:"service_tier,nullable"` - // 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"` - // Usage statistics for the completion request. - Usage CompletionUsage `json:"usage"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ID respjson.Field - Choices respjson.Field - Created respjson.Field - Model respjson.Field - Object respjson.Field - ServiceTier respjson.Field - SystemFingerprint respjson.Field - Usage respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ChatCompletion) RawJSON() string { return r.JSON.raw } -func (r *ChatCompletion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type ChatCompletionChoice 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. - // - // Any of "stop", "length", "tool_calls", "content_filter", "function_call". - FinishReason string `json:"finish_reason,required"` - // The index of the choice in the list of choices. - Index int64 `json:"index,required"` - // Log probability information for the choice. - Logprobs ChatCompletionChoiceLogprobs `json:"logprobs,required"` - // A chat completion message generated by the model. - Message ChatCompletionMessage `json:"message,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - FinishReason respjson.Field - Index respjson.Field - Logprobs respjson.Field - Message respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ChatCompletionChoice) RawJSON() string { return r.JSON.raw } -func (r *ChatCompletionChoice) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Log probability information for the choice. -type ChatCompletionChoiceLogprobs struct { - // A list of message content tokens with log probability information. - Content []ChatCompletionTokenLogprob `json:"content,required"` - // A list of message refusal tokens with log probability information. - Refusal []ChatCompletionTokenLogprob `json:"refusal,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Content respjson.Field - Refusal respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ChatCompletionChoiceLogprobs) RawJSON() string { return r.JSON.raw } -func (r *ChatCompletionChoiceLogprobs) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Specifies the processing type used for serving the request. -// -// - If set to 'auto', then the request will be processed with the service tier -// configured in the Project settings. Unless otherwise configured, the Project -// will use 'default'. -// - If set to 'default', then the request will be processed with the standard -// pricing and performance for the selected model. -// - If set to '[flex](https://platform.openai.com/docs/guides/flex-processing)' or -// 'priority', then the request will be processed with the corresponding service -// tier. [Contact sales](https://openai.com/contact-sales) to learn more about -// Priority processing. -// - When not set, the default behavior is 'auto'. -// -// When the `service_tier` parameter is set, the response body will include the -// `service_tier` value based on the processing mode actually used to serve the -// request. This response value may be different from the value set in the -// parameter. -type ChatCompletionServiceTier string - -const ( - ChatCompletionServiceTierAuto ChatCompletionServiceTier = "auto" - ChatCompletionServiceTierDefault ChatCompletionServiceTier = "default" - ChatCompletionServiceTierFlex ChatCompletionServiceTier = "flex" - ChatCompletionServiceTierScale ChatCompletionServiceTier = "scale" - ChatCompletionServiceTierPriority ChatCompletionServiceTier = "priority" -) - -// Messages sent by the model in response to user messages. -// -// The property Role is required. -type ChatCompletionAssistantMessageParam struct { - // The refusal message by the assistant. - Refusal param.Opt[string] `json:"refusal,omitzero"` - // An optional name for the participant. Provides the model information to - // differentiate between participants of the same role. - Name param.Opt[string] `json:"name,omitzero"` - // Data about a previous audio response from the model. - // [Learn more](https://platform.openai.com/docs/guides/audio). - Audio ChatCompletionAssistantMessageParamAudio `json:"audio,omitzero"` - // The contents of the assistant message. Required unless `tool_calls` or - // `function_call` is specified. - Content ChatCompletionAssistantMessageParamContentUnion `json:"content,omitzero"` - // Deprecated and replaced by `tool_calls`. The name and arguments of a function - // that should be called, as generated by the model. - // - // Deprecated: deprecated - FunctionCall ChatCompletionAssistantMessageParamFunctionCall `json:"function_call,omitzero"` - // The tool calls generated by the model, such as function calls. - ToolCalls []ChatCompletionMessageToolCallParam `json:"tool_calls,omitzero"` - // The role of the messages author, in this case `assistant`. - // - // This field can be elided, and will marshal its zero value as "assistant". - Role constant.Assistant `json:"role,required"` - paramObj -} - -func (r ChatCompletionAssistantMessageParam) MarshalJSON() (data []byte, err error) { - type shadow ChatCompletionAssistantMessageParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ChatCompletionAssistantMessageParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Data about a previous audio response from the model. -// [Learn more](https://platform.openai.com/docs/guides/audio). -// -// The property ID is required. -type ChatCompletionAssistantMessageParamAudio struct { - // Unique identifier for a previous audio response from the model. - ID string `json:"id,required"` - paramObj -} - -func (r ChatCompletionAssistantMessageParamAudio) MarshalJSON() (data []byte, err error) { - type shadow ChatCompletionAssistantMessageParamAudio - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ChatCompletionAssistantMessageParamAudio) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type ChatCompletionAssistantMessageParamContentUnion struct { - OfString param.Opt[string] `json:",omitzero,inline"` - OfArrayOfContentParts []ChatCompletionAssistantMessageParamContentArrayOfContentPartUnion `json:",omitzero,inline"` - paramUnion -} - -func (u ChatCompletionAssistantMessageParamContentUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfString, u.OfArrayOfContentParts) -} -func (u *ChatCompletionAssistantMessageParamContentUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *ChatCompletionAssistantMessageParamContentUnion) asAny() any { - if !param.IsOmitted(u.OfString) { - return &u.OfString.Value - } else if !param.IsOmitted(u.OfArrayOfContentParts) { - return &u.OfArrayOfContentParts - } - return nil -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type ChatCompletionAssistantMessageParamContentArrayOfContentPartUnion struct { - OfText *ChatCompletionContentPartTextParam `json:",omitzero,inline"` - OfRefusal *ChatCompletionContentPartRefusalParam `json:",omitzero,inline"` - paramUnion -} - -func (u ChatCompletionAssistantMessageParamContentArrayOfContentPartUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfText, u.OfRefusal) -} -func (u *ChatCompletionAssistantMessageParamContentArrayOfContentPartUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *ChatCompletionAssistantMessageParamContentArrayOfContentPartUnion) asAny() any { - if !param.IsOmitted(u.OfText) { - return u.OfText - } else if !param.IsOmitted(u.OfRefusal) { - return u.OfRefusal - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u ChatCompletionAssistantMessageParamContentArrayOfContentPartUnion) GetText() *string { - if vt := u.OfText; vt != nil { - return &vt.Text - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u ChatCompletionAssistantMessageParamContentArrayOfContentPartUnion) GetRefusal() *string { - if vt := u.OfRefusal; vt != nil { - return &vt.Refusal - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u ChatCompletionAssistantMessageParamContentArrayOfContentPartUnion) GetType() *string { - if vt := u.OfText; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfRefusal; vt != nil { - return (*string)(&vt.Type) - } - return nil -} - -func init() { - apijson.RegisterUnion[ChatCompletionAssistantMessageParamContentArrayOfContentPartUnion]( - "type", - apijson.Discriminator[ChatCompletionContentPartTextParam]("text"), - apijson.Discriminator[ChatCompletionContentPartRefusalParam]("refusal"), - ) -} - -// Deprecated and replaced by `tool_calls`. The name and arguments of a function -// that should be called, as generated by the model. -// -// Deprecated: deprecated -// -// The properties Arguments, Name are required. -type ChatCompletionAssistantMessageParamFunctionCall 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,required"` - // The name of the function to call. - Name string `json:"name,required"` - paramObj -} - -func (r ChatCompletionAssistantMessageParamFunctionCall) MarshalJSON() (data []byte, err error) { - type shadow ChatCompletionAssistantMessageParamFunctionCall - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ChatCompletionAssistantMessageParamFunctionCall) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// If the audio output modality is requested, this object contains data about the -// audio response from the model. -// [Learn more](https://platform.openai.com/docs/guides/audio). -type ChatCompletionAudio struct { - // Unique identifier for this audio response. - ID string `json:"id,required"` - // Base64 encoded audio bytes generated by the model, in the format specified in - // the request. - Data string `json:"data,required"` - // The Unix timestamp (in seconds) for when this audio response will no longer be - // accessible on the server for use in multi-turn conversations. - ExpiresAt int64 `json:"expires_at,required"` - // Transcript of the audio generated by the model. - Transcript string `json:"transcript,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ID respjson.Field - Data respjson.Field - ExpiresAt respjson.Field - Transcript respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ChatCompletionAudio) RawJSON() string { return r.JSON.raw } -func (r *ChatCompletionAudio) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Parameters for audio output. Required when audio output is requested with -// `modalities: ["audio"]`. -// [Learn more](https://platform.openai.com/docs/guides/audio). -// -// The properties Format, Voice are required. -type ChatCompletionAudioParam struct { - // Specifies the output audio format. Must be one of `wav`, `mp3`, `flac`, `opus`, - // or `pcm16`. - // - // Any of "wav", "aac", "mp3", "flac", "opus", "pcm16". - Format ChatCompletionAudioParamFormat `json:"format,omitzero,required"` - // The voice the model uses to respond. Supported voices are `alloy`, `ash`, - // `ballad`, `coral`, `echo`, `fable`, `nova`, `onyx`, `sage`, and `shimmer`. - Voice ChatCompletionAudioParamVoice `json:"voice,omitzero,required"` - paramObj -} - -func (r ChatCompletionAudioParam) MarshalJSON() (data []byte, err error) { - type shadow ChatCompletionAudioParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ChatCompletionAudioParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Specifies the output audio format. Must be one of `wav`, `mp3`, `flac`, `opus`, -// or `pcm16`. -type ChatCompletionAudioParamFormat string - -const ( - ChatCompletionAudioParamFormatWAV ChatCompletionAudioParamFormat = "wav" - ChatCompletionAudioParamFormatAAC ChatCompletionAudioParamFormat = "aac" - ChatCompletionAudioParamFormatMP3 ChatCompletionAudioParamFormat = "mp3" - ChatCompletionAudioParamFormatFLAC ChatCompletionAudioParamFormat = "flac" - ChatCompletionAudioParamFormatOpus ChatCompletionAudioParamFormat = "opus" - ChatCompletionAudioParamFormatPcm16 ChatCompletionAudioParamFormat = "pcm16" -) - -// The voice the model uses to respond. Supported voices are `alloy`, `ash`, -// `ballad`, `coral`, `echo`, `fable`, `nova`, `onyx`, `sage`, and `shimmer`. -type ChatCompletionAudioParamVoice string - -const ( - ChatCompletionAudioParamVoiceAlloy ChatCompletionAudioParamVoice = "alloy" - ChatCompletionAudioParamVoiceAsh ChatCompletionAudioParamVoice = "ash" - ChatCompletionAudioParamVoiceBallad ChatCompletionAudioParamVoice = "ballad" - ChatCompletionAudioParamVoiceCoral ChatCompletionAudioParamVoice = "coral" - ChatCompletionAudioParamVoiceEcho ChatCompletionAudioParamVoice = "echo" - ChatCompletionAudioParamVoiceSage ChatCompletionAudioParamVoice = "sage" - ChatCompletionAudioParamVoiceShimmer ChatCompletionAudioParamVoice = "shimmer" - ChatCompletionAudioParamVoiceVerse ChatCompletionAudioParamVoice = "verse" -) - -// Represents a streamed chunk of a chat completion response returned by the model, -// based on the provided input. -// [Learn more](https://platform.openai.com/docs/guides/streaming-responses). -type ChatCompletionChunk struct { - // A unique identifier for the chat completion. Each chunk has the same ID. - ID string `json:"id,required"` - // 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}`. - Choices []ChatCompletionChunkChoice `json:"choices,required"` - // The Unix timestamp (in seconds) of when the chat completion was created. Each - // chunk has the same timestamp. - Created int64 `json:"created,required"` - // The model to generate the completion. - Model string `json:"model,required"` - // The object type, which is always `chat.completion.chunk`. - Object constant.ChatCompletionChunk `json:"object,required"` - // Specifies the processing type used for serving the request. - // - // - If set to 'auto', then the request will be processed with the service tier - // configured in the Project settings. Unless otherwise configured, the Project - // will use 'default'. - // - If set to 'default', then the request will be processed with the standard - // pricing and performance for the selected model. - // - If set to '[flex](https://platform.openai.com/docs/guides/flex-processing)' or - // 'priority', then the request will be processed with the corresponding service - // tier. [Contact sales](https://openai.com/contact-sales) to learn more about - // Priority processing. - // - When not set, the default behavior is 'auto'. - // - // When the `service_tier` parameter is set, the response body will include the - // `service_tier` value based on the processing mode actually used to serve the - // request. This response value may be different from the value set in the - // parameter. - // - // Any of "auto", "default", "flex", "scale", "priority". - ServiceTier ChatCompletionChunkServiceTier `json:"service_tier,nullable"` - // 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"` - // 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. - // - // **NOTE:** If the stream is interrupted or cancelled, you may not receive the - // final usage chunk which contains the total token usage for the request. - Usage CompletionUsage `json:"usage,nullable"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ID respjson.Field - Choices respjson.Field - Created respjson.Field - Model respjson.Field - Object respjson.Field - ServiceTier respjson.Field - SystemFingerprint respjson.Field - Usage respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ChatCompletionChunk) RawJSON() string { return r.JSON.raw } -func (r *ChatCompletionChunk) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type ChatCompletionChunkChoice struct { - // A chat completion delta generated by streamed model responses. - Delta ChatCompletionChunkChoiceDelta `json:"delta,required"` - // 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. - // - // Any of "stop", "length", "tool_calls", "content_filter", "function_call". - FinishReason string `json:"finish_reason,required"` - // The index of the choice in the list of choices. - Index int64 `json:"index,required"` - // Log probability information for the choice. - Logprobs ChatCompletionChunkChoiceLogprobs `json:"logprobs,nullable"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Delta respjson.Field - FinishReason respjson.Field - Index respjson.Field - Logprobs respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ChatCompletionChunkChoice) RawJSON() string { return r.JSON.raw } -func (r *ChatCompletionChunkChoice) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// A chat completion delta generated by streamed model responses. -type ChatCompletionChunkChoiceDelta struct { - // The contents of the chunk message. - Content string `json:"content,nullable"` - // Deprecated and replaced by `tool_calls`. The name and arguments of a function - // that should be called, as generated by the model. - // - // Deprecated: deprecated - FunctionCall ChatCompletionChunkChoiceDeltaFunctionCall `json:"function_call"` - // The refusal message generated by the model. - Refusal string `json:"refusal,nullable"` - // The role of the author of this message. - // - // Any of "developer", "system", "user", "assistant", "tool". - Role string `json:"role"` - ToolCalls []ChatCompletionChunkChoiceDeltaToolCall `json:"tool_calls"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Content respjson.Field - FunctionCall respjson.Field - Refusal respjson.Field - Role respjson.Field - ToolCalls respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ChatCompletionChunkChoiceDelta) RawJSON() string { return r.JSON.raw } -func (r *ChatCompletionChunkChoiceDelta) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Deprecated and replaced by `tool_calls`. The name and arguments of a function -// that should be called, as generated by the model. -// -// Deprecated: deprecated -type ChatCompletionChunkChoiceDeltaFunctionCall 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"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Arguments respjson.Field - Name respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ChatCompletionChunkChoiceDeltaFunctionCall) RawJSON() string { return r.JSON.raw } -func (r *ChatCompletionChunkChoiceDeltaFunctionCall) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type ChatCompletionChunkChoiceDeltaToolCall struct { - Index int64 `json:"index,required"` - // The ID of the tool call. - ID string `json:"id"` - Function ChatCompletionChunkChoiceDeltaToolCallFunction `json:"function"` - // The type of the tool. Currently, only `function` is supported. - // - // Any of "function". - Type string `json:"type"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Index respjson.Field - ID respjson.Field - Function respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ChatCompletionChunkChoiceDeltaToolCall) RawJSON() string { return r.JSON.raw } -func (r *ChatCompletionChunkChoiceDeltaToolCall) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type ChatCompletionChunkChoiceDeltaToolCallFunction 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"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Arguments respjson.Field - Name respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ChatCompletionChunkChoiceDeltaToolCallFunction) RawJSON() string { return r.JSON.raw } -func (r *ChatCompletionChunkChoiceDeltaToolCallFunction) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Log probability information for the choice. -type ChatCompletionChunkChoiceLogprobs struct { - // A list of message content tokens with log probability information. - Content []ChatCompletionTokenLogprob `json:"content,required"` - // A list of message refusal tokens with log probability information. - Refusal []ChatCompletionTokenLogprob `json:"refusal,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Content respjson.Field - Refusal respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ChatCompletionChunkChoiceLogprobs) RawJSON() string { return r.JSON.raw } -func (r *ChatCompletionChunkChoiceLogprobs) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Specifies the processing type used for serving the request. -// -// - If set to 'auto', then the request will be processed with the service tier -// configured in the Project settings. Unless otherwise configured, the Project -// will use 'default'. -// - If set to 'default', then the request will be processed with the standard -// pricing and performance for the selected model. -// - If set to '[flex](https://platform.openai.com/docs/guides/flex-processing)' or -// 'priority', then the request will be processed with the corresponding service -// tier. [Contact sales](https://openai.com/contact-sales) to learn more about -// Priority processing. -// - When not set, the default behavior is 'auto'. -// -// When the `service_tier` parameter is set, the response body will include the -// `service_tier` value based on the processing mode actually used to serve the -// request. This response value may be different from the value set in the -// parameter. -type ChatCompletionChunkServiceTier string - -const ( - ChatCompletionChunkServiceTierAuto ChatCompletionChunkServiceTier = "auto" - ChatCompletionChunkServiceTierDefault ChatCompletionChunkServiceTier = "default" - ChatCompletionChunkServiceTierFlex ChatCompletionChunkServiceTier = "flex" - ChatCompletionChunkServiceTierScale ChatCompletionChunkServiceTier = "scale" - ChatCompletionChunkServiceTierPriority ChatCompletionChunkServiceTier = "priority" -) - -func TextContentPart(text string) ChatCompletionContentPartUnionParam { - var variant ChatCompletionContentPartTextParam - variant.Text = text - return ChatCompletionContentPartUnionParam{OfText: &variant} -} - -func ImageContentPart(imageURL ChatCompletionContentPartImageImageURLParam) ChatCompletionContentPartUnionParam { - var variant ChatCompletionContentPartImageParam - variant.ImageURL = imageURL - return ChatCompletionContentPartUnionParam{OfImageURL: &variant} -} - -func InputAudioContentPart(inputAudio ChatCompletionContentPartInputAudioInputAudioParam) ChatCompletionContentPartUnionParam { - var variant ChatCompletionContentPartInputAudioParam - variant.InputAudio = inputAudio - return ChatCompletionContentPartUnionParam{OfInputAudio: &variant} -} - -func FileContentPart(file ChatCompletionContentPartFileFileParam) ChatCompletionContentPartUnionParam { - var variant ChatCompletionContentPartFileParam - variant.File = file - return ChatCompletionContentPartUnionParam{OfFile: &variant} -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type ChatCompletionContentPartUnionParam struct { - OfText *ChatCompletionContentPartTextParam `json:",omitzero,inline"` - OfImageURL *ChatCompletionContentPartImageParam `json:",omitzero,inline"` - OfInputAudio *ChatCompletionContentPartInputAudioParam `json:",omitzero,inline"` - OfFile *ChatCompletionContentPartFileParam `json:",omitzero,inline"` - paramUnion -} - -func (u ChatCompletionContentPartUnionParam) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfText, u.OfImageURL, u.OfInputAudio, u.OfFile) -} -func (u *ChatCompletionContentPartUnionParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *ChatCompletionContentPartUnionParam) asAny() any { - if !param.IsOmitted(u.OfText) { - return u.OfText - } else if !param.IsOmitted(u.OfImageURL) { - return u.OfImageURL - } else if !param.IsOmitted(u.OfInputAudio) { - return u.OfInputAudio - } else if !param.IsOmitted(u.OfFile) { - return u.OfFile - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u ChatCompletionContentPartUnionParam) GetText() *string { - if vt := u.OfText; vt != nil { - return &vt.Text - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u ChatCompletionContentPartUnionParam) GetImageURL() *ChatCompletionContentPartImageImageURLParam { - if vt := u.OfImageURL; vt != nil { - return &vt.ImageURL - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u ChatCompletionContentPartUnionParam) GetInputAudio() *ChatCompletionContentPartInputAudioInputAudioParam { - if vt := u.OfInputAudio; vt != nil { - return &vt.InputAudio - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u ChatCompletionContentPartUnionParam) GetFile() *ChatCompletionContentPartFileFileParam { - if vt := u.OfFile; vt != nil { - return &vt.File - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u ChatCompletionContentPartUnionParam) GetType() *string { - if vt := u.OfText; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfImageURL; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfInputAudio; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfFile; vt != nil { - return (*string)(&vt.Type) - } - return nil -} - -func init() { - apijson.RegisterUnion[ChatCompletionContentPartUnionParam]( - "type", - apijson.Discriminator[ChatCompletionContentPartTextParam]("text"), - apijson.Discriminator[ChatCompletionContentPartImageParam]("image_url"), - apijson.Discriminator[ChatCompletionContentPartInputAudioParam]("input_audio"), - apijson.Discriminator[ChatCompletionContentPartFileParam]("file"), - ) -} - -// Learn about [file inputs](https://platform.openai.com/docs/guides/text) for text -// generation. -// -// The properties File, Type are required. -type ChatCompletionContentPartFileParam struct { - File ChatCompletionContentPartFileFileParam `json:"file,omitzero,required"` - // The type of the content part. Always `file`. - // - // This field can be elided, and will marshal its zero value as "file". - Type constant.File `json:"type,required"` - paramObj -} - -func (r ChatCompletionContentPartFileParam) MarshalJSON() (data []byte, err error) { - type shadow ChatCompletionContentPartFileParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ChatCompletionContentPartFileParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type ChatCompletionContentPartFileFileParam struct { - // The base64 encoded file data, used when passing the file to the model as a - // string. - FileData param.Opt[string] `json:"file_data,omitzero"` - // The ID of an uploaded file to use as input. - FileID param.Opt[string] `json:"file_id,omitzero"` - // The name of the file, used when passing the file to the model as a string. - Filename param.Opt[string] `json:"filename,omitzero"` - paramObj -} - -func (r ChatCompletionContentPartFileFileParam) MarshalJSON() (data []byte, err error) { - type shadow ChatCompletionContentPartFileFileParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ChatCompletionContentPartFileFileParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Learn about [image inputs](https://platform.openai.com/docs/guides/vision). -type ChatCompletionContentPartImage struct { - ImageURL ChatCompletionContentPartImageImageURL `json:"image_url,required"` - // The type of the content part. - Type constant.ImageURL `json:"type,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ImageURL respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ChatCompletionContentPartImage) RawJSON() string { return r.JSON.raw } -func (r *ChatCompletionContentPartImage) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// ToParam converts this ChatCompletionContentPartImage to a -// ChatCompletionContentPartImageParam. -// -// Warning: the fields of the param type will not be present. ToParam should only -// be used at the last possible moment before sending a request. Test for this with -// ChatCompletionContentPartImageParam.Overrides() -func (r ChatCompletionContentPartImage) ToParam() ChatCompletionContentPartImageParam { - return param.Override[ChatCompletionContentPartImageParam](json.RawMessage(r.RawJSON())) -} - -type ChatCompletionContentPartImageImageURL struct { - // Either a URL of the image or the base64 encoded image data. - URL string `json:"url,required" format:"uri"` - // Specifies the detail level of the image. Learn more in the - // [Vision guide](https://platform.openai.com/docs/guides/vision#low-or-high-fidelity-image-understanding). - // - // Any of "auto", "low", "high". - Detail string `json:"detail"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - URL respjson.Field - Detail respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ChatCompletionContentPartImageImageURL) RawJSON() string { return r.JSON.raw } -func (r *ChatCompletionContentPartImageImageURL) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Learn about [image inputs](https://platform.openai.com/docs/guides/vision). -// -// The properties ImageURL, Type are required. -type ChatCompletionContentPartImageParam struct { - ImageURL ChatCompletionContentPartImageImageURLParam `json:"image_url,omitzero,required"` - // The type of the content part. - // - // This field can be elided, and will marshal its zero value as "image_url". - Type constant.ImageURL `json:"type,required"` - paramObj -} - -func (r ChatCompletionContentPartImageParam) MarshalJSON() (data []byte, err error) { - type shadow ChatCompletionContentPartImageParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ChatCompletionContentPartImageParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The property URL is required. -type ChatCompletionContentPartImageImageURLParam struct { - // Either a URL of the image or the base64 encoded image data. - URL string `json:"url,required" format:"uri"` - // Specifies the detail level of the image. Learn more in the - // [Vision guide](https://platform.openai.com/docs/guides/vision#low-or-high-fidelity-image-understanding). - // - // Any of "auto", "low", "high". - Detail string `json:"detail,omitzero"` - paramObj -} - -func (r ChatCompletionContentPartImageImageURLParam) MarshalJSON() (data []byte, err error) { - type shadow ChatCompletionContentPartImageImageURLParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ChatCompletionContentPartImageImageURLParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -func init() { - apijson.RegisterFieldValidator[ChatCompletionContentPartImageImageURLParam]( - "detail", "auto", "low", "high", - ) -} - -// Learn about [audio inputs](https://platform.openai.com/docs/guides/audio). -// -// The properties InputAudio, Type are required. -type ChatCompletionContentPartInputAudioParam struct { - InputAudio ChatCompletionContentPartInputAudioInputAudioParam `json:"input_audio,omitzero,required"` - // The type of the content part. Always `input_audio`. - // - // This field can be elided, and will marshal its zero value as "input_audio". - Type constant.InputAudio `json:"type,required"` - paramObj -} - -func (r ChatCompletionContentPartInputAudioParam) MarshalJSON() (data []byte, err error) { - type shadow ChatCompletionContentPartInputAudioParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ChatCompletionContentPartInputAudioParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The properties Data, Format are required. -type ChatCompletionContentPartInputAudioInputAudioParam struct { - // Base64 encoded audio data. - Data string `json:"data,required"` - // The format of the encoded audio data. Currently supports "wav" and "mp3". - // - // Any of "wav", "mp3". - Format string `json:"format,omitzero,required"` - paramObj -} - -func (r ChatCompletionContentPartInputAudioInputAudioParam) MarshalJSON() (data []byte, err error) { - type shadow ChatCompletionContentPartInputAudioInputAudioParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ChatCompletionContentPartInputAudioInputAudioParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -func init() { - apijson.RegisterFieldValidator[ChatCompletionContentPartInputAudioInputAudioParam]( - "format", "wav", "mp3", - ) -} - -// The properties Refusal, Type are required. -type ChatCompletionContentPartRefusalParam struct { - // The refusal message generated by the model. - Refusal string `json:"refusal,required"` - // The type of the content part. - // - // This field can be elided, and will marshal its zero value as "refusal". - Type constant.Refusal `json:"type,required"` - paramObj -} - -func (r ChatCompletionContentPartRefusalParam) MarshalJSON() (data []byte, err error) { - type shadow ChatCompletionContentPartRefusalParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ChatCompletionContentPartRefusalParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Learn about -// [text inputs](https://platform.openai.com/docs/guides/text-generation). -type ChatCompletionContentPartText struct { - // The text content. - Text string `json:"text,required"` - // The type of the content part. - Type constant.Text `json:"type,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Text respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ChatCompletionContentPartText) RawJSON() string { return r.JSON.raw } -func (r *ChatCompletionContentPartText) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// ToParam converts this ChatCompletionContentPartText to a -// ChatCompletionContentPartTextParam. -// -// Warning: the fields of the param type will not be present. ToParam should only -// be used at the last possible moment before sending a request. Test for this with -// ChatCompletionContentPartTextParam.Overrides() -func (r ChatCompletionContentPartText) ToParam() ChatCompletionContentPartTextParam { - return param.Override[ChatCompletionContentPartTextParam](json.RawMessage(r.RawJSON())) -} - -// Learn about -// [text inputs](https://platform.openai.com/docs/guides/text-generation). -// -// The properties Text, Type are required. -type ChatCompletionContentPartTextParam struct { - // The text content. - Text string `json:"text,required"` - // The type of the content part. - // - // This field can be elided, and will marshal its zero value as "text". - Type constant.Text `json:"type,required"` - paramObj -} - -func (r ChatCompletionContentPartTextParam) MarshalJSON() (data []byte, err error) { - type shadow ChatCompletionContentPartTextParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ChatCompletionContentPartTextParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type ChatCompletionDeleted struct { - // The ID of the chat completion that was deleted. - ID string `json:"id,required"` - // Whether the chat completion was deleted. - Deleted bool `json:"deleted,required"` - // The type of object being deleted. - Object constant.ChatCompletionDeleted `json:"object,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ID respjson.Field - Deleted respjson.Field - Object respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ChatCompletionDeleted) RawJSON() string { return r.JSON.raw } -func (r *ChatCompletionDeleted) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Developer-provided instructions that the model should follow, regardless of -// messages sent by the user. With o1 models and newer, `developer` messages -// replace the previous `system` messages. -// -// The properties Content, Role are required. -type ChatCompletionDeveloperMessageParam struct { - // The contents of the developer message. - Content ChatCompletionDeveloperMessageParamContentUnion `json:"content,omitzero,required"` - // An optional name for the participant. Provides the model information to - // differentiate between participants of the same role. - Name param.Opt[string] `json:"name,omitzero"` - // The role of the messages author, in this case `developer`. - // - // This field can be elided, and will marshal its zero value as "developer". - Role constant.Developer `json:"role,required"` - paramObj -} - -func (r ChatCompletionDeveloperMessageParam) MarshalJSON() (data []byte, err error) { - type shadow ChatCompletionDeveloperMessageParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ChatCompletionDeveloperMessageParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type ChatCompletionDeveloperMessageParamContentUnion struct { - OfString param.Opt[string] `json:",omitzero,inline"` - OfArrayOfContentParts []ChatCompletionContentPartTextParam `json:",omitzero,inline"` - paramUnion -} - -func (u ChatCompletionDeveloperMessageParamContentUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfString, u.OfArrayOfContentParts) -} -func (u *ChatCompletionDeveloperMessageParamContentUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *ChatCompletionDeveloperMessageParamContentUnion) asAny() any { - if !param.IsOmitted(u.OfString) { - return &u.OfString.Value - } else if !param.IsOmitted(u.OfArrayOfContentParts) { - return &u.OfArrayOfContentParts - } - return nil -} - -// Specifying a particular function via `{"name": "my_function"}` forces the model -// to call that function. -// -// The property Name is required. -type ChatCompletionFunctionCallOptionParam struct { - // The name of the function to call. - Name string `json:"name,required"` - paramObj -} - -func (r ChatCompletionFunctionCallOptionParam) MarshalJSON() (data []byte, err error) { - type shadow ChatCompletionFunctionCallOptionParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ChatCompletionFunctionCallOptionParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Deprecated: deprecated -// -// The properties Content, Name, Role are required. -type ChatCompletionFunctionMessageParam struct { - // The contents of the function message. - Content param.Opt[string] `json:"content,omitzero,required"` - // The name of the function to call. - Name string `json:"name,required"` - // The role of the messages author, in this case `function`. - // - // This field can be elided, and will marshal its zero value as "function". - Role constant.Function `json:"role,required"` - paramObj -} - -func (r ChatCompletionFunctionMessageParam) MarshalJSON() (data []byte, err error) { - type shadow ChatCompletionFunctionMessageParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ChatCompletionFunctionMessageParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// A chat completion message generated by the model. -type ChatCompletionMessage struct { - // The contents of the message. - Content string `json:"content,required"` - // The refusal message generated by the model. - Refusal string `json:"refusal,required"` - // The role of the author of this message. - Role constant.Assistant `json:"role,required"` - // Annotations for the message, when applicable, as when using the - // [web search tool](https://platform.openai.com/docs/guides/tools-web-search?api-mode=chat). - Annotations []ChatCompletionMessageAnnotation `json:"annotations"` - // If the audio output modality is requested, this object contains data about the - // audio response from the model. - // [Learn more](https://platform.openai.com/docs/guides/audio). - Audio ChatCompletionAudio `json:"audio,nullable"` - // Deprecated and replaced by `tool_calls`. The name and arguments of a function - // that should be called, as generated by the model. - // - // Deprecated: deprecated - FunctionCall ChatCompletionMessageFunctionCall `json:"function_call"` - // The tool calls generated by the model, such as function calls. - ToolCalls []ChatCompletionMessageToolCall `json:"tool_calls"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Content respjson.Field - Refusal respjson.Field - Role respjson.Field - Annotations respjson.Field - Audio respjson.Field - FunctionCall respjson.Field - ToolCalls respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ChatCompletionMessage) RawJSON() string { return r.JSON.raw } -func (r *ChatCompletionMessage) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -func (r ChatCompletionMessage) ToParam() ChatCompletionMessageParamUnion { - asst := r.ToAssistantMessageParam() - return ChatCompletionMessageParamUnion{OfAssistant: &asst} -} - -func (r ChatCompletionMessage) ToAssistantMessageParam() ChatCompletionAssistantMessageParam { - var p ChatCompletionAssistantMessageParam - - // It is important to not rely on the JSON metadata property - // here, it may be unset if the receiver was generated via a - // [ChatCompletionAccumulator]. - // - // Explicit null is intentionally elided from the response. - if r.Content != "" { - p.Content.OfString = String(r.Content) - } - if r.Refusal != "" { - p.Refusal = String(r.Refusal) - } - - p.Audio.ID = r.Audio.ID - p.Role = r.Role - p.FunctionCall.Arguments = r.FunctionCall.Arguments - p.FunctionCall.Name = r.FunctionCall.Name - - if len(r.ToolCalls) > 0 { - p.ToolCalls = make([]ChatCompletionMessageToolCallParam, len(r.ToolCalls)) - for i, v := range r.ToolCalls { - p.ToolCalls[i].ID = v.ID - p.ToolCalls[i].Function.Arguments = v.Function.Arguments - p.ToolCalls[i].Function.Name = v.Function.Name - } - } - return p -} - -// A URL citation when using web search. -type ChatCompletionMessageAnnotation struct { - // The type of the URL citation. Always `url_citation`. - Type constant.URLCitation `json:"type,required"` - // A URL citation when using web search. - URLCitation ChatCompletionMessageAnnotationURLCitation `json:"url_citation,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Type respjson.Field - URLCitation respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ChatCompletionMessageAnnotation) RawJSON() string { return r.JSON.raw } -func (r *ChatCompletionMessageAnnotation) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// A URL citation when using web search. -type ChatCompletionMessageAnnotationURLCitation struct { - // The index of the last character of the URL citation in the message. - EndIndex int64 `json:"end_index,required"` - // The index of the first character of the URL citation in the message. - StartIndex int64 `json:"start_index,required"` - // The title of the web resource. - Title string `json:"title,required"` - // The URL of the web resource. - URL string `json:"url,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - EndIndex respjson.Field - StartIndex respjson.Field - Title respjson.Field - URL respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ChatCompletionMessageAnnotationURLCitation) RawJSON() string { return r.JSON.raw } -func (r *ChatCompletionMessageAnnotationURLCitation) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Deprecated and replaced by `tool_calls`. The name and arguments of a function -// that should be called, as generated by the model. -// -// Deprecated: deprecated -type ChatCompletionMessageFunctionCall 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,required"` - // The name of the function to call. - Name string `json:"name,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Arguments respjson.Field - Name respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ChatCompletionMessageFunctionCall) RawJSON() string { return r.JSON.raw } -func (r *ChatCompletionMessageFunctionCall) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -func AssistantMessage[T string | []ChatCompletionAssistantMessageParamContentArrayOfContentPartUnion](content T) ChatCompletionMessageParamUnion { - var assistant ChatCompletionAssistantMessageParam - switch v := any(content).(type) { - case string: - assistant.Content.OfString = param.NewOpt(v) - case []ChatCompletionAssistantMessageParamContentArrayOfContentPartUnion: - assistant.Content.OfArrayOfContentParts = v - } - return ChatCompletionMessageParamUnion{OfAssistant: &assistant} -} - -func DeveloperMessage[T string | []ChatCompletionContentPartTextParam](content T) ChatCompletionMessageParamUnion { - var developer ChatCompletionDeveloperMessageParam - switch v := any(content).(type) { - case string: - developer.Content.OfString = param.NewOpt(v) - case []ChatCompletionContentPartTextParam: - developer.Content.OfArrayOfContentParts = v - } - return ChatCompletionMessageParamUnion{OfDeveloper: &developer} -} - -func SystemMessage[T string | []ChatCompletionContentPartTextParam](content T) ChatCompletionMessageParamUnion { - var system ChatCompletionSystemMessageParam - switch v := any(content).(type) { - case string: - system.Content.OfString = param.NewOpt(v) - case []ChatCompletionContentPartTextParam: - system.Content.OfArrayOfContentParts = v - } - return ChatCompletionMessageParamUnion{OfSystem: &system} -} - -func UserMessage[T string | []ChatCompletionContentPartUnionParam](content T) ChatCompletionMessageParamUnion { - var user ChatCompletionUserMessageParam - switch v := any(content).(type) { - case string: - user.Content.OfString = param.NewOpt(v) - case []ChatCompletionContentPartUnionParam: - user.Content.OfArrayOfContentParts = v - } - return ChatCompletionMessageParamUnion{OfUser: &user} -} - -func ChatCompletionMessageParamOfAssistant[ - T string | []ChatCompletionAssistantMessageParamContentArrayOfContentPartUnion, -](content T) ChatCompletionMessageParamUnion { - var assistant ChatCompletionAssistantMessageParam - switch v := any(content).(type) { - case string: - assistant.Content.OfString = param.NewOpt(v) - case []ChatCompletionAssistantMessageParamContentArrayOfContentPartUnion: - assistant.Content.OfArrayOfContentParts = v - } - return ChatCompletionMessageParamUnion{OfAssistant: &assistant} -} - -func ToolMessage[T string | []ChatCompletionContentPartTextParam](content T, toolCallID string) ChatCompletionMessageParamUnion { - var tool ChatCompletionToolMessageParam - switch v := any(content).(type) { - case string: - tool.Content.OfString = param.NewOpt(v) - case []ChatCompletionContentPartTextParam: - tool.Content.OfArrayOfContentParts = v - } - tool.ToolCallID = toolCallID - return ChatCompletionMessageParamUnion{OfTool: &tool} -} - -func ChatCompletionMessageParamOfFunction(content string, name string) ChatCompletionMessageParamUnion { - var function ChatCompletionFunctionMessageParam - function.Content = param.NewOpt(content) - function.Name = name - return ChatCompletionMessageParamUnion{OfFunction: &function} -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type ChatCompletionMessageParamUnion struct { - OfDeveloper *ChatCompletionDeveloperMessageParam `json:",omitzero,inline"` - OfSystem *ChatCompletionSystemMessageParam `json:",omitzero,inline"` - OfUser *ChatCompletionUserMessageParam `json:",omitzero,inline"` - OfAssistant *ChatCompletionAssistantMessageParam `json:",omitzero,inline"` - OfTool *ChatCompletionToolMessageParam `json:",omitzero,inline"` - OfFunction *ChatCompletionFunctionMessageParam `json:",omitzero,inline"` - paramUnion -} - -func (u ChatCompletionMessageParamUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfDeveloper, - u.OfSystem, - u.OfUser, - u.OfAssistant, - u.OfTool, - u.OfFunction) -} -func (u *ChatCompletionMessageParamUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *ChatCompletionMessageParamUnion) asAny() any { - if !param.IsOmitted(u.OfDeveloper) { - return u.OfDeveloper - } else if !param.IsOmitted(u.OfSystem) { - return u.OfSystem - } else if !param.IsOmitted(u.OfUser) { - return u.OfUser - } else if !param.IsOmitted(u.OfAssistant) { - return u.OfAssistant - } else if !param.IsOmitted(u.OfTool) { - return u.OfTool - } else if !param.IsOmitted(u.OfFunction) { - return u.OfFunction - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u ChatCompletionMessageParamUnion) GetAudio() *ChatCompletionAssistantMessageParamAudio { - if vt := u.OfAssistant; vt != nil { - return &vt.Audio - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u ChatCompletionMessageParamUnion) GetFunctionCall() *ChatCompletionAssistantMessageParamFunctionCall { - if vt := u.OfAssistant; vt != nil { - return &vt.FunctionCall - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u ChatCompletionMessageParamUnion) GetRefusal() *string { - if vt := u.OfAssistant; vt != nil && vt.Refusal.Valid() { - return &vt.Refusal.Value - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u ChatCompletionMessageParamUnion) GetToolCalls() []ChatCompletionMessageToolCallParam { - if vt := u.OfAssistant; vt != nil { - return vt.ToolCalls - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u ChatCompletionMessageParamUnion) GetToolCallID() *string { - if vt := u.OfTool; vt != nil { - return &vt.ToolCallID - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u ChatCompletionMessageParamUnion) GetRole() *string { - if vt := u.OfDeveloper; vt != nil { - return (*string)(&vt.Role) - } else if vt := u.OfSystem; vt != nil { - return (*string)(&vt.Role) - } else if vt := u.OfUser; vt != nil { - return (*string)(&vt.Role) - } else if vt := u.OfAssistant; vt != nil { - return (*string)(&vt.Role) - } else if vt := u.OfTool; vt != nil { - return (*string)(&vt.Role) - } else if vt := u.OfFunction; vt != nil { - return (*string)(&vt.Role) - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u ChatCompletionMessageParamUnion) GetName() *string { - if vt := u.OfDeveloper; vt != nil && vt.Name.Valid() { - return &vt.Name.Value - } else if vt := u.OfSystem; vt != nil && vt.Name.Valid() { - return &vt.Name.Value - } else if vt := u.OfUser; vt != nil && vt.Name.Valid() { - return &vt.Name.Value - } else if vt := u.OfAssistant; vt != nil && vt.Name.Valid() { - return &vt.Name.Value - } else if vt := u.OfFunction; vt != nil { - return (*string)(&vt.Name) - } - return nil -} - -// Returns a subunion which exports methods to access subproperties -// -// Or use AsAny() to get the underlying value -func (u ChatCompletionMessageParamUnion) GetContent() (res chatCompletionMessageParamUnionContent) { - if vt := u.OfDeveloper; vt != nil { - res.any = vt.Content.asAny() - } else if vt := u.OfSystem; vt != nil { - res.any = vt.Content.asAny() - } else if vt := u.OfUser; vt != nil { - res.any = vt.Content.asAny() - } else if vt := u.OfAssistant; vt != nil { - res.any = vt.Content.asAny() - } else if vt := u.OfTool; vt != nil { - res.any = vt.Content.asAny() - } else if vt := u.OfFunction; vt != nil && vt.Content.Valid() { - res.any = &vt.Content.Value - } - return -} - -// Can have the runtime types [*string], [_[]ChatCompletionContentPartTextParam], -// [_[]ChatCompletionContentPartUnionParam], -// [\*[]ChatCompletionAssistantMessageParamContentArrayOfContentPartUnion] -type chatCompletionMessageParamUnionContent struct{ any } - -// Use the following switch statement to get the type of the union: -// -// switch u.AsAny().(type) { -// case *string: -// case *[]openai.ChatCompletionContentPartTextParam: -// case *[]openai.ChatCompletionContentPartUnionParam: -// case *[]openai.ChatCompletionAssistantMessageParamContentArrayOfContentPartUnion: -// default: -// fmt.Errorf("not present") -// } -func (u chatCompletionMessageParamUnionContent) AsAny() any { return u.any } - -func init() { - apijson.RegisterUnion[ChatCompletionMessageParamUnion]( - "role", - apijson.Discriminator[ChatCompletionDeveloperMessageParam]("developer"), - apijson.Discriminator[ChatCompletionSystemMessageParam]("system"), - apijson.Discriminator[ChatCompletionUserMessageParam]("user"), - apijson.Discriminator[ChatCompletionAssistantMessageParam]("assistant"), - apijson.Discriminator[ChatCompletionToolMessageParam]("tool"), - apijson.Discriminator[ChatCompletionFunctionMessageParam]("function"), - ) -} - -type ChatCompletionMessageToolCall struct { - // The ID of the tool call. - ID string `json:"id,required"` - // The function that the model called. - Function ChatCompletionMessageToolCallFunction `json:"function,required"` - // The type of the tool. Currently, only `function` is supported. - Type constant.Function `json:"type,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ID respjson.Field - Function respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ChatCompletionMessageToolCall) RawJSON() string { return r.JSON.raw } -func (r *ChatCompletionMessageToolCall) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// ToParam converts this ChatCompletionMessageToolCall to a -// ChatCompletionMessageToolCallParam. -// -// Warning: the fields of the param type will not be present. ToParam should only -// be used at the last possible moment before sending a request. Test for this with -// ChatCompletionMessageToolCallParam.Overrides() -func (r ChatCompletionMessageToolCall) ToParam() ChatCompletionMessageToolCallParam { - return param.Override[ChatCompletionMessageToolCallParam](json.RawMessage(r.RawJSON())) -} - -// The function that the model called. -type ChatCompletionMessageToolCallFunction 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,required"` - // The name of the function to call. - Name string `json:"name,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Arguments respjson.Field - Name respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ChatCompletionMessageToolCallFunction) RawJSON() string { return r.JSON.raw } -func (r *ChatCompletionMessageToolCallFunction) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The properties ID, Function, Type are required. -type ChatCompletionMessageToolCallParam struct { - // The ID of the tool call. - ID string `json:"id,required"` - // The function that the model called. - Function ChatCompletionMessageToolCallFunctionParam `json:"function,omitzero,required"` - // The type of the tool. Currently, only `function` is supported. - // - // This field can be elided, and will marshal its zero value as "function". - Type constant.Function `json:"type,required"` - paramObj -} - -func (r ChatCompletionMessageToolCallParam) MarshalJSON() (data []byte, err error) { - type shadow ChatCompletionMessageToolCallParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ChatCompletionMessageToolCallParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The function that the model called. -// -// The properties Arguments, Name are required. -type ChatCompletionMessageToolCallFunctionParam 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,required"` - // The name of the function to call. - Name string `json:"name,required"` - paramObj -} - -func (r ChatCompletionMessageToolCallFunctionParam) MarshalJSON() (data []byte, err error) { - type shadow ChatCompletionMessageToolCallFunctionParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ChatCompletionMessageToolCallFunctionParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Specifies a tool the model should use. Use to force the model to call a specific -// function. -// -// The properties Function, Type are required. -type ChatCompletionNamedToolChoiceParam struct { - Function ChatCompletionNamedToolChoiceFunctionParam `json:"function,omitzero,required"` - // The type of the tool. Currently, only `function` is supported. - // - // This field can be elided, and will marshal its zero value as "function". - Type constant.Function `json:"type,required"` - paramObj -} - -func (r ChatCompletionNamedToolChoiceParam) MarshalJSON() (data []byte, err error) { - type shadow ChatCompletionNamedToolChoiceParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ChatCompletionNamedToolChoiceParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The property Name is required. -type ChatCompletionNamedToolChoiceFunctionParam struct { - // The name of the function to call. - Name string `json:"name,required"` - paramObj -} - -func (r ChatCompletionNamedToolChoiceFunctionParam) MarshalJSON() (data []byte, err error) { - type shadow ChatCompletionNamedToolChoiceFunctionParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ChatCompletionNamedToolChoiceFunctionParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Static predicted output content, such as the content of a text file that is -// being regenerated. -// -// The properties Content, Type are required. -type ChatCompletionPredictionContentParam struct { - // The content that should be matched when generating a model response. If - // generated tokens would match this content, the entire model response can be - // returned much more quickly. - Content ChatCompletionPredictionContentContentUnionParam `json:"content,omitzero,required"` - // The type of the predicted content you want to provide. This type is currently - // always `content`. - // - // This field can be elided, and will marshal its zero value as "content". - Type constant.Content `json:"type,required"` - paramObj -} - -func (r ChatCompletionPredictionContentParam) MarshalJSON() (data []byte, err error) { - type shadow ChatCompletionPredictionContentParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ChatCompletionPredictionContentParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type ChatCompletionPredictionContentContentUnionParam struct { - OfString param.Opt[string] `json:",omitzero,inline"` - OfArrayOfContentParts []ChatCompletionContentPartTextParam `json:",omitzero,inline"` - paramUnion -} - -func (u ChatCompletionPredictionContentContentUnionParam) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfString, u.OfArrayOfContentParts) -} -func (u *ChatCompletionPredictionContentContentUnionParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *ChatCompletionPredictionContentContentUnionParam) asAny() any { - if !param.IsOmitted(u.OfString) { - return &u.OfString.Value - } else if !param.IsOmitted(u.OfArrayOfContentParts) { - return &u.OfArrayOfContentParts - } - return nil -} - -// A chat completion message generated by the model. -type ChatCompletionStoreMessage struct { - // The identifier of the chat message. - ID string `json:"id,required"` - // If a content parts array was provided, this is an array of `text` and - // `image_url` parts. Otherwise, null. - ContentParts []ChatCompletionStoreMessageContentPartUnion `json:"content_parts,nullable"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ID respjson.Field - ContentParts respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` - ChatCompletionMessage -} - -// Returns the unmodified JSON received from the API -func (r ChatCompletionStoreMessage) RawJSON() string { return r.JSON.raw } -func (r *ChatCompletionStoreMessage) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// ChatCompletionStoreMessageContentPartUnion contains all possible properties and -// values from [ChatCompletionContentPartText], [ChatCompletionContentPartImage]. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -type ChatCompletionStoreMessageContentPartUnion struct { - // This field is from variant [ChatCompletionContentPartText]. - Text string `json:"text"` - Type string `json:"type"` - // This field is from variant [ChatCompletionContentPartImage]. - ImageURL ChatCompletionContentPartImageImageURL `json:"image_url"` - JSON struct { - Text respjson.Field - Type respjson.Field - ImageURL respjson.Field - raw string - } `json:"-"` -} - -func (u ChatCompletionStoreMessageContentPartUnion) AsTextContentPart() (v ChatCompletionContentPartText) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u ChatCompletionStoreMessageContentPartUnion) AsImageContentPart() (v ChatCompletionContentPartImage) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -// Returns the unmodified JSON received from the API -func (u ChatCompletionStoreMessageContentPartUnion) RawJSON() string { return u.JSON.raw } - -func (r *ChatCompletionStoreMessageContentPartUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Options for streaming response. Only set this when you set `stream: true`. -type ChatCompletionStreamOptionsParam 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. - // **NOTE:** If the stream is interrupted, you may not receive the final usage - // chunk which contains the total token usage for the request. - IncludeUsage param.Opt[bool] `json:"include_usage,omitzero"` - paramObj -} - -func (r ChatCompletionStreamOptionsParam) MarshalJSON() (data []byte, err error) { - type shadow ChatCompletionStreamOptionsParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ChatCompletionStreamOptionsParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Developer-provided instructions that the model should follow, regardless of -// messages sent by the user. With o1 models and newer, use `developer` messages -// for this purpose instead. -// -// The properties Content, Role are required. -type ChatCompletionSystemMessageParam struct { - // The contents of the system message. - Content ChatCompletionSystemMessageParamContentUnion `json:"content,omitzero,required"` - // An optional name for the participant. Provides the model information to - // differentiate between participants of the same role. - Name param.Opt[string] `json:"name,omitzero"` - // The role of the messages author, in this case `system`. - // - // This field can be elided, and will marshal its zero value as "system". - Role constant.System `json:"role,required"` - paramObj -} - -func (r ChatCompletionSystemMessageParam) MarshalJSON() (data []byte, err error) { - type shadow ChatCompletionSystemMessageParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ChatCompletionSystemMessageParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type ChatCompletionSystemMessageParamContentUnion struct { - OfString param.Opt[string] `json:",omitzero,inline"` - OfArrayOfContentParts []ChatCompletionContentPartTextParam `json:",omitzero,inline"` - paramUnion -} - -func (u ChatCompletionSystemMessageParamContentUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfString, u.OfArrayOfContentParts) -} -func (u *ChatCompletionSystemMessageParamContentUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *ChatCompletionSystemMessageParamContentUnion) asAny() any { - if !param.IsOmitted(u.OfString) { - return &u.OfString.Value - } else if !param.IsOmitted(u.OfArrayOfContentParts) { - return &u.OfArrayOfContentParts - } - return nil -} - -type ChatCompletionTokenLogprob struct { - // The token. - Token string `json:"token,required"` - // 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,required"` - // 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,required"` - // 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 []ChatCompletionTokenLogprobTopLogprob `json:"top_logprobs,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Token respjson.Field - Bytes respjson.Field - Logprob respjson.Field - TopLogprobs respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ChatCompletionTokenLogprob) RawJSON() string { return r.JSON.raw } -func (r *ChatCompletionTokenLogprob) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type ChatCompletionTokenLogprobTopLogprob struct { - // The token. - Token string `json:"token,required"` - // 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,required"` - // 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,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Token respjson.Field - Bytes respjson.Field - Logprob respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ChatCompletionTokenLogprobTopLogprob) RawJSON() string { return r.JSON.raw } -func (r *ChatCompletionTokenLogprobTopLogprob) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The properties Function, Type are required. -type ChatCompletionToolParam struct { - Function shared.FunctionDefinitionParam `json:"function,omitzero,required"` - // The type of the tool. Currently, only `function` is supported. - // - // This field can be elided, and will marshal its zero value as "function". - Type constant.Function `json:"type,required"` - paramObj -} - -func (r ChatCompletionToolParam) MarshalJSON() (data []byte, err error) { - type shadow ChatCompletionToolParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ChatCompletionToolParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -func ChatCompletionToolChoiceOptionParamOfChatCompletionNamedToolChoice(function ChatCompletionNamedToolChoiceFunctionParam) ChatCompletionToolChoiceOptionUnionParam { - var variant ChatCompletionNamedToolChoiceParam - variant.Function = function - return ChatCompletionToolChoiceOptionUnionParam{OfChatCompletionNamedToolChoice: &variant} -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type ChatCompletionToolChoiceOptionUnionParam struct { - // Check if union is this variant with !param.IsOmitted(union.OfAuto) - OfAuto param.Opt[string] `json:",omitzero,inline"` - OfChatCompletionNamedToolChoice *ChatCompletionNamedToolChoiceParam `json:",omitzero,inline"` - paramUnion -} - -func (u ChatCompletionToolChoiceOptionUnionParam) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfAuto, u.OfChatCompletionNamedToolChoice) -} -func (u *ChatCompletionToolChoiceOptionUnionParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *ChatCompletionToolChoiceOptionUnionParam) asAny() any { - if !param.IsOmitted(u.OfAuto) { - return &u.OfAuto - } else if !param.IsOmitted(u.OfChatCompletionNamedToolChoice) { - return u.OfChatCompletionNamedToolChoice - } - return nil -} - -// `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 ChatCompletionToolChoiceOptionAuto string - -const ( - ChatCompletionToolChoiceOptionAutoNone ChatCompletionToolChoiceOptionAuto = "none" - ChatCompletionToolChoiceOptionAutoAuto ChatCompletionToolChoiceOptionAuto = "auto" - ChatCompletionToolChoiceOptionAutoRequired ChatCompletionToolChoiceOptionAuto = "required" -) - -// The properties Content, Role, ToolCallID are required. -type ChatCompletionToolMessageParam struct { - // The contents of the tool message. - Content ChatCompletionToolMessageParamContentUnion `json:"content,omitzero,required"` - // Tool call that this message is responding to. - ToolCallID string `json:"tool_call_id,required"` - // The role of the messages author, in this case `tool`. - // - // This field can be elided, and will marshal its zero value as "tool". - Role constant.Tool `json:"role,required"` - paramObj -} - -func (r ChatCompletionToolMessageParam) MarshalJSON() (data []byte, err error) { - type shadow ChatCompletionToolMessageParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ChatCompletionToolMessageParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type ChatCompletionToolMessageParamContentUnion struct { - OfString param.Opt[string] `json:",omitzero,inline"` - OfArrayOfContentParts []ChatCompletionContentPartTextParam `json:",omitzero,inline"` - paramUnion -} - -func (u ChatCompletionToolMessageParamContentUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfString, u.OfArrayOfContentParts) -} -func (u *ChatCompletionToolMessageParamContentUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *ChatCompletionToolMessageParamContentUnion) asAny() any { - if !param.IsOmitted(u.OfString) { - return &u.OfString.Value - } else if !param.IsOmitted(u.OfArrayOfContentParts) { - return &u.OfArrayOfContentParts - } - return nil -} - -// Messages sent by an end user, containing prompts or additional context -// information. -// -// The properties Content, Role are required. -type ChatCompletionUserMessageParam struct { - // The contents of the user message. - Content ChatCompletionUserMessageParamContentUnion `json:"content,omitzero,required"` - // An optional name for the participant. Provides the model information to - // differentiate between participants of the same role. - Name param.Opt[string] `json:"name,omitzero"` - // The role of the messages author, in this case `user`. - // - // This field can be elided, and will marshal its zero value as "user". - Role constant.User `json:"role,required"` - paramObj -} - -func (r ChatCompletionUserMessageParam) MarshalJSON() (data []byte, err error) { - type shadow ChatCompletionUserMessageParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ChatCompletionUserMessageParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type ChatCompletionUserMessageParamContentUnion struct { - OfString param.Opt[string] `json:",omitzero,inline"` - OfArrayOfContentParts []ChatCompletionContentPartUnionParam `json:",omitzero,inline"` - paramUnion -} - -func (u ChatCompletionUserMessageParamContentUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfString, u.OfArrayOfContentParts) -} -func (u *ChatCompletionUserMessageParamContentUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *ChatCompletionUserMessageParamContentUnion) asAny() any { - if !param.IsOmitted(u.OfString) { - return &u.OfString.Value - } else if !param.IsOmitted(u.OfArrayOfContentParts) { - return &u.OfArrayOfContentParts - } - return nil -} - -type ChatCompletionNewParams struct { - // A list of messages comprising the conversation so far. Depending on the - // [model](https://platform.openai.com/docs/models) you use, different message - // types (modalities) are supported, like - // [text](https://platform.openai.com/docs/guides/text-generation), - // [images](https://platform.openai.com/docs/guides/vision), and - // [audio](https://platform.openai.com/docs/guides/audio). - Messages []ChatCompletionMessageParamUnion `json:"messages,omitzero,required"` - // Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI offers a - // wide range of models with different capabilities, performance characteristics, - // and price points. Refer to the - // [model guide](https://platform.openai.com/docs/models) to browse and compare - // available models. - Model shared.ChatModel `json:"model,omitzero,required"` - // 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. - FrequencyPenalty param.Opt[float64] `json:"frequency_penalty,omitzero"` - // 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 param.Opt[bool] `json:"logprobs,omitzero"` - // An upper bound for the number of tokens that can be generated for a completion, - // including visible output tokens and - // [reasoning tokens](https://platform.openai.com/docs/guides/reasoning). - MaxCompletionTokens param.Opt[int64] `json:"max_completion_tokens,omitzero"` - // The maximum number of [tokens](/tokenizer) that can be generated in the chat - // completion. This value can be used to control - // [costs](https://openai.com/api/pricing/) for text generated via API. - // - // This value is now deprecated in favor of `max_completion_tokens`, and is not - // compatible with - // [o-series models](https://platform.openai.com/docs/guides/reasoning). - MaxTokens param.Opt[int64] `json:"max_tokens,omitzero"` - // 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 param.Opt[int64] `json:"n,omitzero"` - // 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. - PresencePenalty param.Opt[float64] `json:"presence_penalty,omitzero"` - // 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 param.Opt[int64] `json:"seed,omitzero"` - // Whether or not to store the output of this chat completion request for use in - // our [model distillation](https://platform.openai.com/docs/guides/distillation) - // or [evals](https://platform.openai.com/docs/guides/evals) products. - // - // Supports text and image inputs. Note: image inputs over 10MB will be dropped. - Store param.Opt[bool] `json:"store,omitzero"` - // 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 param.Opt[float64] `json:"temperature,omitzero"` - // 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 param.Opt[int64] `json:"top_logprobs,omitzero"` - // 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 param.Opt[float64] `json:"top_p,omitzero"` - // Whether to enable - // [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) - // during tool use. - ParallelToolCalls param.Opt[bool] `json:"parallel_tool_calls,omitzero"` - // Used by OpenAI to cache responses for similar requests to optimize your cache - // hit rates. Replaces the `user` field. - // [Learn more](https://platform.openai.com/docs/guides/prompt-caching). - PromptCacheKey param.Opt[string] `json:"prompt_cache_key,omitzero"` - // A stable identifier used to help detect users of your application that may be - // violating OpenAI's usage policies. The IDs should be a string that uniquely - // identifies each user. We recommend hashing their username or email address, in - // order to avoid sending us any identifying information. - // [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#safety-identifiers). - SafetyIdentifier param.Opt[string] `json:"safety_identifier,omitzero"` - // This field is being replaced by `safety_identifier` and `prompt_cache_key`. Use - // `prompt_cache_key` instead to maintain caching optimizations. A stable - // identifier for your end-users. Used to boost cache hit rates by better bucketing - // similar requests and to help OpenAI detect and prevent abuse. - // [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#safety-identifiers). - User param.Opt[string] `json:"user,omitzero"` - // Parameters for audio output. Required when audio output is requested with - // `modalities: ["audio"]`. - // [Learn more](https://platform.openai.com/docs/guides/audio). - Audio ChatCompletionAudioParam `json:"audio,omitzero"` - // 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,omitzero"` - // 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, and - // querying for objects via API or the dashboard. - // - // Keys are strings with a maximum length of 64 characters. Values are strings with - // a maximum length of 512 characters. - Metadata shared.Metadata `json:"metadata,omitzero"` - // Output types that you would like the model to generate. Most models are capable - // of generating text, which is the default: - // - // `["text"]` - // - // The `gpt-4o-audio-preview` model can also be used to - // [generate audio](https://platform.openai.com/docs/guides/audio). To request that - // this model generate both text and audio responses, you can use: - // - // `["text", "audio"]` - // - // Any of "text", "audio". - Modalities []string `json:"modalities,omitzero"` - // **o-series models only** - // - // Constrains effort on reasoning for - // [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently - // supported values are `low`, `medium`, and `high`. Reducing reasoning effort can - // result in faster responses and fewer tokens used on reasoning in a response. - // - // Any of "low", "medium", "high". - ReasoningEffort shared.ReasoningEffort `json:"reasoning_effort,omitzero"` - // Specifies the processing type used for serving the request. - // - // - If set to 'auto', then the request will be processed with the service tier - // configured in the Project settings. Unless otherwise configured, the Project - // will use 'default'. - // - If set to 'default', then the request will be processed with the standard - // pricing and performance for the selected model. - // - If set to '[flex](https://platform.openai.com/docs/guides/flex-processing)' or - // 'priority', then the request will be processed with the corresponding service - // tier. [Contact sales](https://openai.com/contact-sales) to learn more about - // Priority processing. - // - When not set, the default behavior is 'auto'. - // - // When the `service_tier` parameter is set, the response body will include the - // `service_tier` value based on the processing mode actually used to serve the - // request. This response value may be different from the value set in the - // parameter. - // - // Any of "auto", "default", "flex", "scale", "priority". - ServiceTier ChatCompletionNewParamsServiceTier `json:"service_tier,omitzero"` - // Not supported with latest reasoning models `o3` and `o4-mini`. - // - // Up to 4 sequences where the API will stop generating further tokens. The - // returned text will not contain the stop sequence. - Stop ChatCompletionNewParamsStopUnion `json:"stop,omitzero"` - // Options for streaming response. Only set this when you set `stream: true`. - StreamOptions ChatCompletionStreamOptionsParam `json:"stream_options,omitzero"` - // 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. - FunctionCall ChatCompletionNewParamsFunctionCallUnion `json:"function_call,omitzero"` - // Deprecated in favor of `tools`. - // - // A list of functions the model may generate JSON inputs for. - Functions []ChatCompletionNewParamsFunction `json:"functions,omitzero"` - // Static predicted output content, such as the content of a text file that is - // being regenerated. - Prediction ChatCompletionPredictionContentParam `json:"prediction,omitzero"` - // An object specifying the format that the model must output. - // - // Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured - // Outputs which ensures the model will match your supplied JSON schema. Learn more - // in the - // [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). - // - // Setting to `{ "type": "json_object" }` enables the older JSON mode, which - // ensures the message the model generates is valid JSON. Using `json_schema` is - // preferred for models that support it. - ResponseFormat ChatCompletionNewParamsResponseFormatUnion `json:"response_format,omitzero"` - // 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 ChatCompletionToolChoiceOptionUnionParam `json:"tool_choice,omitzero"` - // 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 []ChatCompletionToolParam `json:"tools,omitzero"` - // This tool searches the web for relevant results to use in a response. Learn more - // about the - // [web search tool](https://platform.openai.com/docs/guides/tools-web-search?api-mode=chat). - WebSearchOptions ChatCompletionNewParamsWebSearchOptions `json:"web_search_options,omitzero"` - paramObj -} - -func (r ChatCompletionNewParams) MarshalJSON() (data []byte, err error) { - type shadow ChatCompletionNewParams - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ChatCompletionNewParams) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type ChatCompletionNewParamsFunctionCallUnion struct { - // Check if union is this variant with !param.IsOmitted(union.OfFunctionCallMode) - OfFunctionCallMode param.Opt[string] `json:",omitzero,inline"` - OfFunctionCallOption *ChatCompletionFunctionCallOptionParam `json:",omitzero,inline"` - paramUnion -} - -func (u ChatCompletionNewParamsFunctionCallUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfFunctionCallMode, u.OfFunctionCallOption) -} -func (u *ChatCompletionNewParamsFunctionCallUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *ChatCompletionNewParamsFunctionCallUnion) asAny() any { - if !param.IsOmitted(u.OfFunctionCallMode) { - return &u.OfFunctionCallMode - } else if !param.IsOmitted(u.OfFunctionCallOption) { - return u.OfFunctionCallOption - } - return nil -} - -// `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 ChatCompletionNewParamsFunctionCallFunctionCallMode string - -const ( - ChatCompletionNewParamsFunctionCallFunctionCallModeNone ChatCompletionNewParamsFunctionCallFunctionCallMode = "none" - ChatCompletionNewParamsFunctionCallFunctionCallModeAuto ChatCompletionNewParamsFunctionCallFunctionCallMode = "auto" -) - -// Deprecated: deprecated -// -// The property Name is required. -type ChatCompletionNewParamsFunction struct { - // 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,required"` - // A description of what the function does, used by the model to choose when and - // how to call the function. - Description param.Opt[string] `json:"description,omitzero"` - // The parameters the functions accepts, described as a JSON Schema object. See the - // [guide](https://platform.openai.com/docs/guides/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 shared.FunctionParameters `json:"parameters,omitzero"` - paramObj -} - -func (r ChatCompletionNewParamsFunction) MarshalJSON() (data []byte, err error) { - type shadow ChatCompletionNewParamsFunction - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ChatCompletionNewParamsFunction) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type ChatCompletionNewParamsResponseFormatUnion struct { - OfText *shared.ResponseFormatTextParam `json:",omitzero,inline"` - OfJSONSchema *shared.ResponseFormatJSONSchemaParam `json:",omitzero,inline"` - OfJSONObject *shared.ResponseFormatJSONObjectParam `json:",omitzero,inline"` - paramUnion -} - -func (u ChatCompletionNewParamsResponseFormatUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfText, u.OfJSONSchema, u.OfJSONObject) -} -func (u *ChatCompletionNewParamsResponseFormatUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *ChatCompletionNewParamsResponseFormatUnion) asAny() any { - if !param.IsOmitted(u.OfText) { - return u.OfText - } else if !param.IsOmitted(u.OfJSONSchema) { - return u.OfJSONSchema - } else if !param.IsOmitted(u.OfJSONObject) { - return u.OfJSONObject - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u ChatCompletionNewParamsResponseFormatUnion) GetJSONSchema() *shared.ResponseFormatJSONSchemaJSONSchemaParam { - if vt := u.OfJSONSchema; vt != nil { - return &vt.JSONSchema - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u ChatCompletionNewParamsResponseFormatUnion) GetType() *string { - if vt := u.OfText; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfJSONSchema; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfJSONObject; vt != nil { - return (*string)(&vt.Type) - } - return nil -} - -// Specifies the processing type used for serving the request. -// -// - If set to 'auto', then the request will be processed with the service tier -// configured in the Project settings. Unless otherwise configured, the Project -// will use 'default'. -// - If set to 'default', then the request will be processed with the standard -// pricing and performance for the selected model. -// - If set to '[flex](https://platform.openai.com/docs/guides/flex-processing)' or -// 'priority', then the request will be processed with the corresponding service -// tier. [Contact sales](https://openai.com/contact-sales) to learn more about -// Priority processing. -// - When not set, the default behavior is 'auto'. -// -// When the `service_tier` parameter is set, the response body will include the -// `service_tier` value based on the processing mode actually used to serve the -// request. This response value may be different from the value set in the -// parameter. -type ChatCompletionNewParamsServiceTier string - -const ( - ChatCompletionNewParamsServiceTierAuto ChatCompletionNewParamsServiceTier = "auto" - ChatCompletionNewParamsServiceTierDefault ChatCompletionNewParamsServiceTier = "default" - ChatCompletionNewParamsServiceTierFlex ChatCompletionNewParamsServiceTier = "flex" - ChatCompletionNewParamsServiceTierScale ChatCompletionNewParamsServiceTier = "scale" - ChatCompletionNewParamsServiceTierPriority ChatCompletionNewParamsServiceTier = "priority" -) - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type ChatCompletionNewParamsStopUnion struct { - OfString param.Opt[string] `json:",omitzero,inline"` - OfStringArray []string `json:",omitzero,inline"` - paramUnion -} - -func (u ChatCompletionNewParamsStopUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfString, u.OfStringArray) -} -func (u *ChatCompletionNewParamsStopUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *ChatCompletionNewParamsStopUnion) asAny() any { - if !param.IsOmitted(u.OfString) { - return &u.OfString.Value - } else if !param.IsOmitted(u.OfStringArray) { - return &u.OfStringArray - } - return nil -} - -// This tool searches the web for relevant results to use in a response. Learn more -// about the -// [web search tool](https://platform.openai.com/docs/guides/tools-web-search?api-mode=chat). -type ChatCompletionNewParamsWebSearchOptions struct { - // Approximate location parameters for the search. - UserLocation ChatCompletionNewParamsWebSearchOptionsUserLocation `json:"user_location,omitzero"` - // High level guidance for the amount of context window space to use for the - // search. One of `low`, `medium`, or `high`. `medium` is the default. - // - // Any of "low", "medium", "high". - SearchContextSize string `json:"search_context_size,omitzero"` - paramObj -} - -func (r ChatCompletionNewParamsWebSearchOptions) MarshalJSON() (data []byte, err error) { - type shadow ChatCompletionNewParamsWebSearchOptions - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ChatCompletionNewParamsWebSearchOptions) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -func init() { - apijson.RegisterFieldValidator[ChatCompletionNewParamsWebSearchOptions]( - "search_context_size", "low", "medium", "high", - ) -} - -// Approximate location parameters for the search. -// -// The properties Approximate, Type are required. -type ChatCompletionNewParamsWebSearchOptionsUserLocation struct { - // Approximate location parameters for the search. - Approximate ChatCompletionNewParamsWebSearchOptionsUserLocationApproximate `json:"approximate,omitzero,required"` - // The type of location approximation. Always `approximate`. - // - // This field can be elided, and will marshal its zero value as "approximate". - Type constant.Approximate `json:"type,required"` - paramObj -} - -func (r ChatCompletionNewParamsWebSearchOptionsUserLocation) MarshalJSON() (data []byte, err error) { - type shadow ChatCompletionNewParamsWebSearchOptionsUserLocation - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ChatCompletionNewParamsWebSearchOptionsUserLocation) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Approximate location parameters for the search. -type ChatCompletionNewParamsWebSearchOptionsUserLocationApproximate struct { - // Free text input for the city of the user, e.g. `San Francisco`. - City param.Opt[string] `json:"city,omitzero"` - // The two-letter [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1) of - // the user, e.g. `US`. - Country param.Opt[string] `json:"country,omitzero"` - // Free text input for the region of the user, e.g. `California`. - Region param.Opt[string] `json:"region,omitzero"` - // The [IANA timezone](https://timeapi.io/documentation/iana-timezones) of the - // user, e.g. `America/Los_Angeles`. - Timezone param.Opt[string] `json:"timezone,omitzero"` - paramObj -} - -func (r ChatCompletionNewParamsWebSearchOptionsUserLocationApproximate) MarshalJSON() (data []byte, err error) { - type shadow ChatCompletionNewParamsWebSearchOptionsUserLocationApproximate - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ChatCompletionNewParamsWebSearchOptionsUserLocationApproximate) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type ChatCompletionUpdateParams struct { - // 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, and - // querying for objects via API or the dashboard. - // - // Keys are strings with a maximum length of 64 characters. Values are strings with - // a maximum length of 512 characters. - Metadata shared.Metadata `json:"metadata,omitzero,required"` - paramObj -} - -func (r ChatCompletionUpdateParams) MarshalJSON() (data []byte, err error) { - type shadow ChatCompletionUpdateParams - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ChatCompletionUpdateParams) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type ChatCompletionListParams struct { - // Identifier for the last chat completion from the previous pagination request. - After param.Opt[string] `query:"after,omitzero" json:"-"` - // Number of Chat Completions to retrieve. - Limit param.Opt[int64] `query:"limit,omitzero" json:"-"` - // The model used to generate the Chat Completions. - Model param.Opt[string] `query:"model,omitzero" json:"-"` - // A list of metadata keys to filter the Chat Completions by. Example: - // - // `metadata[key1]=value1&metadata[key2]=value2` - Metadata shared.Metadata `query:"metadata,omitzero" json:"-"` - // Sort order for Chat Completions by timestamp. Use `asc` for ascending order or - // `desc` for descending order. Defaults to `asc`. - // - // Any of "asc", "desc". - Order ChatCompletionListParamsOrder `query:"order,omitzero" json:"-"` - paramObj -} - -// URLQuery serializes [ChatCompletionListParams]'s query parameters as -// `url.Values`. -func (r ChatCompletionListParams) URLQuery() (v url.Values, err error) { - return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ - ArrayFormat: apiquery.ArrayQueryFormatBrackets, - NestedFormat: apiquery.NestedQueryFormatBrackets, - }) -} - -// Sort order for Chat Completions by timestamp. Use `asc` for ascending order or -// `desc` for descending order. Defaults to `asc`. -type ChatCompletionListParamsOrder string - -const ( - ChatCompletionListParamsOrderAsc ChatCompletionListParamsOrder = "asc" - ChatCompletionListParamsOrderDesc ChatCompletionListParamsOrder = "desc" -) diff --git a/vendor/github.com/openai/openai-go/chatcompletionmessage.go b/vendor/github.com/openai/openai-go/chatcompletionmessage.go deleted file mode 100644 index 4b44d416..00000000 --- a/vendor/github.com/openai/openai-go/chatcompletionmessage.go +++ /dev/null @@ -1,96 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -package openai - -import ( - "context" - "errors" - "fmt" - "net/http" - "net/url" - - "github.com/openai/openai-go/internal/apiquery" - "github.com/openai/openai-go/internal/requestconfig" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/packages/pagination" - "github.com/openai/openai-go/packages/param" -) - -// ChatCompletionMessageService contains methods and other services that help with -// interacting with the openai API. -// -// Note, unlike clients, this service does not read variables from the environment -// automatically. You should not instantiate this service directly, and instead use -// the [NewChatCompletionMessageService] method instead. -type ChatCompletionMessageService struct { - Options []option.RequestOption -} - -// NewChatCompletionMessageService generates a new service that applies the given -// options to each request. These options are applied after the parent client's -// options (if there is one), and before any request-specific options. -func NewChatCompletionMessageService(opts ...option.RequestOption) (r ChatCompletionMessageService) { - r = ChatCompletionMessageService{} - r.Options = opts - return -} - -// Get the messages in a stored chat completion. Only Chat Completions that have -// been created with the `store` parameter set to `true` will be returned. -func (r *ChatCompletionMessageService) List(ctx context.Context, completionID string, query ChatCompletionMessageListParams, opts ...option.RequestOption) (res *pagination.CursorPage[ChatCompletionStoreMessage], err error) { - var raw *http.Response - opts = append(r.Options[:], opts...) - opts = append([]option.RequestOption{option.WithResponseInto(&raw)}, opts...) - if completionID == "" { - err = errors.New("missing required completion_id parameter") - return - } - path := fmt.Sprintf("chat/completions/%s/messages", completionID) - cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, query, &res, opts...) - if err != nil { - return nil, err - } - err = cfg.Execute() - if err != nil { - return nil, err - } - res.SetPageConfig(cfg, raw) - return res, nil -} - -// Get the messages in a stored chat completion. Only Chat Completions that have -// been created with the `store` parameter set to `true` will be returned. -func (r *ChatCompletionMessageService) ListAutoPaging(ctx context.Context, completionID string, query ChatCompletionMessageListParams, opts ...option.RequestOption) *pagination.CursorPageAutoPager[ChatCompletionStoreMessage] { - return pagination.NewCursorPageAutoPager(r.List(ctx, completionID, query, opts...)) -} - -type ChatCompletionMessageListParams struct { - // Identifier for the last message from the previous pagination request. - After param.Opt[string] `query:"after,omitzero" json:"-"` - // Number of messages to retrieve. - Limit param.Opt[int64] `query:"limit,omitzero" json:"-"` - // Sort order for messages by timestamp. Use `asc` for ascending order or `desc` - // for descending order. Defaults to `asc`. - // - // Any of "asc", "desc". - Order ChatCompletionMessageListParamsOrder `query:"order,omitzero" json:"-"` - paramObj -} - -// URLQuery serializes [ChatCompletionMessageListParams]'s query parameters as -// `url.Values`. -func (r ChatCompletionMessageListParams) URLQuery() (v url.Values, err error) { - return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ - ArrayFormat: apiquery.ArrayQueryFormatBrackets, - NestedFormat: apiquery.NestedQueryFormatBrackets, - }) -} - -// Sort order for messages by timestamp. Use `asc` for ascending order or `desc` -// for descending order. Defaults to `asc`. -type ChatCompletionMessageListParamsOrder string - -const ( - ChatCompletionMessageListParamsOrderAsc ChatCompletionMessageListParamsOrder = "asc" - ChatCompletionMessageListParamsOrderDesc ChatCompletionMessageListParamsOrder = "desc" -) diff --git a/vendor/github.com/openai/openai-go/client.go b/vendor/github.com/openai/openai-go/client.go deleted file mode 100644 index 3d78d86b..00000000 --- a/vendor/github.com/openai/openai-go/client.go +++ /dev/null @@ -1,161 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -package openai - -import ( - "context" - "net/http" - "os" - - "github.com/openai/openai-go/internal/requestconfig" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/responses" - "github.com/openai/openai-go/webhooks" -) - -// Client creates a struct with services and top level methods that help with -// interacting with the openai API. You should not instantiate this client -// directly, and instead use the [NewClient] method instead. -type Client struct { - Options []option.RequestOption - Completions CompletionService - Chat ChatService - Embeddings EmbeddingService - Files FileService - Images ImageService - Audio AudioService - Moderations ModerationService - Models ModelService - FineTuning FineTuningService - Graders GraderService - VectorStores VectorStoreService - Webhooks webhooks.WebhookService - Beta BetaService - Batches BatchService - Uploads UploadService - Responses responses.ResponseService - Containers ContainerService -} - -// DefaultClientOptions read from the environment (OPENAI_API_KEY, OPENAI_ORG_ID, -// OPENAI_PROJECT_ID, OPENAI_WEBHOOK_SECRET, OPENAI_BASE_URL). This should be used -// to initialize new clients. -func DefaultClientOptions() []option.RequestOption { - defaults := []option.RequestOption{option.WithEnvironmentProduction()} - if o, ok := os.LookupEnv("OPENAI_BASE_URL"); ok { - defaults = append(defaults, option.WithBaseURL(o)) - } - if o, ok := os.LookupEnv("OPENAI_API_KEY"); ok { - defaults = append(defaults, option.WithAPIKey(o)) - } - if o, ok := os.LookupEnv("OPENAI_ORG_ID"); ok { - defaults = append(defaults, option.WithOrganization(o)) - } - if o, ok := os.LookupEnv("OPENAI_PROJECT_ID"); ok { - defaults = append(defaults, option.WithProject(o)) - } - if o, ok := os.LookupEnv("OPENAI_WEBHOOK_SECRET"); ok { - defaults = append(defaults, option.WithWebhookSecret(o)) - } - return defaults -} - -// NewClient generates a new client with the default option read from the -// environment (OPENAI_API_KEY, OPENAI_ORG_ID, OPENAI_PROJECT_ID, -// OPENAI_WEBHOOK_SECRET, OPENAI_BASE_URL). The option passed in as arguments are -// applied after these default arguments, and all option will be passed down to the -// services and requests that this client makes. -func NewClient(opts ...option.RequestOption) (r Client) { - opts = append(DefaultClientOptions(), opts...) - - r = Client{Options: opts} - - r.Completions = NewCompletionService(opts...) - r.Chat = NewChatService(opts...) - r.Embeddings = NewEmbeddingService(opts...) - r.Files = NewFileService(opts...) - r.Images = NewImageService(opts...) - r.Audio = NewAudioService(opts...) - r.Moderations = NewModerationService(opts...) - r.Models = NewModelService(opts...) - r.FineTuning = NewFineTuningService(opts...) - r.Graders = NewGraderService(opts...) - r.VectorStores = NewVectorStoreService(opts...) - r.Webhooks = webhooks.NewWebhookService(opts...) - r.Beta = NewBetaService(opts...) - r.Batches = NewBatchService(opts...) - r.Uploads = NewUploadService(opts...) - r.Responses = responses.NewResponseService(opts...) - r.Containers = NewContainerService(opts...) - - return -} - -// Execute makes a request with the given context, method, URL, request params, -// response, and request options. This is useful for hitting undocumented endpoints -// while retaining the base URL, auth, retries, and other options from the client. -// -// If a byte slice or an [io.Reader] is supplied to params, it will be used as-is -// for the request body. -// -// The params is by default serialized into the body using [encoding/json]. If your -// type implements a MarshalJSON function, it will be used instead to serialize the -// request. If a URLQuery method is implemented, the returned [url.Values] will be -// used as query strings to the url. -// -// If your params struct uses [param.Field], you must provide either [MarshalJSON], -// [URLQuery], and/or [MarshalForm] functions. It is undefined behavior to use a -// struct uses [param.Field] without specifying how it is serialized. -// -// Any "…Params" object defined in this library can be used as the request -// argument. Note that 'path' arguments will not be forwarded into the url. -// -// The response body will be deserialized into the res variable, depending on its -// type: -// -// - A pointer to a [*http.Response] is populated by the raw response. -// - A pointer to a byte array will be populated with the contents of the request -// body. -// - A pointer to any other type uses this library's default JSON decoding, which -// respects UnmarshalJSON if it is defined on the type. -// - A nil value will not read the response body. -// -// For even greater flexibility, see [option.WithResponseInto] and -// [option.WithResponseBodyInto]. -func (r *Client) Execute(ctx context.Context, method string, path string, params any, res any, opts ...option.RequestOption) error { - opts = append(r.Options, opts...) - return requestconfig.ExecuteNewRequest(ctx, method, path, params, res, opts...) -} - -// Get makes a GET request with the given URL, params, and optionally deserializes -// to a response. See [Execute] documentation on the params and response. -func (r *Client) Get(ctx context.Context, path string, params any, res any, opts ...option.RequestOption) error { - return r.Execute(ctx, http.MethodGet, path, params, res, opts...) -} - -// Post makes a POST request with the given URL, params, and optionally -// deserializes to a response. See [Execute] documentation on the params and -// response. -func (r *Client) Post(ctx context.Context, path string, params any, res any, opts ...option.RequestOption) error { - return r.Execute(ctx, http.MethodPost, path, params, res, opts...) -} - -// Put makes a PUT request with the given URL, params, and optionally deserializes -// to a response. See [Execute] documentation on the params and response. -func (r *Client) Put(ctx context.Context, path string, params any, res any, opts ...option.RequestOption) error { - return r.Execute(ctx, http.MethodPut, path, params, res, opts...) -} - -// Patch makes a PATCH request with the given URL, params, and optionally -// deserializes to a response. See [Execute] documentation on the params and -// response. -func (r *Client) Patch(ctx context.Context, path string, params any, res any, opts ...option.RequestOption) error { - return r.Execute(ctx, http.MethodPatch, path, params, res, opts...) -} - -// Delete makes a DELETE request with the given URL, params, and optionally -// deserializes to a response. See [Execute] documentation on the params and -// response. -func (r *Client) Delete(ctx context.Context, path string, params any, res any, opts ...option.RequestOption) error { - return r.Execute(ctx, http.MethodDelete, path, params, res, opts...) -} diff --git a/vendor/github.com/openai/openai-go/completion.go b/vendor/github.com/openai/openai-go/completion.go deleted file mode 100644 index 72b2c510..00000000 --- a/vendor/github.com/openai/openai-go/completion.go +++ /dev/null @@ -1,426 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -package openai - -import ( - "context" - "net/http" - - "github.com/openai/openai-go/internal/apijson" - "github.com/openai/openai-go/internal/requestconfig" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/packages/param" - "github.com/openai/openai-go/packages/respjson" - "github.com/openai/openai-go/packages/ssestream" - "github.com/openai/openai-go/shared/constant" -) - -// CompletionService contains methods and other services that help with interacting -// with the openai API. -// -// Note, unlike clients, this service does not read variables from the environment -// automatically. You should not instantiate this service directly, and instead use -// the [NewCompletionService] method instead. -type CompletionService struct { - Options []option.RequestOption -} - -// NewCompletionService generates a new service that applies the given options to -// each request. These options are applied after the parent client's options (if -// there is one), and before any request-specific options. -func NewCompletionService(opts ...option.RequestOption) (r CompletionService) { - r = CompletionService{} - r.Options = opts - return -} - -// Creates a completion for the provided prompt and parameters. -func (r *CompletionService) New(ctx context.Context, body CompletionNewParams, opts ...option.RequestOption) (res *Completion, err error) { - opts = append(r.Options[:], opts...) - path := "completions" - err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...) - return -} - -// Creates a completion for the provided prompt and parameters. -func (r *CompletionService) NewStreaming(ctx context.Context, body CompletionNewParams, opts ...option.RequestOption) (stream *ssestream.Stream[Completion]) { - var ( - raw *http.Response - err error - ) - opts = append(r.Options[:], opts...) - opts = append([]option.RequestOption{option.WithJSONSet("stream", true)}, opts...) - path := "completions" - err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &raw, opts...) - return ssestream.NewStream[Completion](ssestream.NewDecoder(raw), err) -} - -// Represents a completion response from the API. Note: both the streamed and -// non-streamed response objects share the same shape (unlike the chat endpoint). -type Completion struct { - // A unique identifier for the completion. - ID string `json:"id,required"` - // The list of completion choices the model generated for the input prompt. - Choices []CompletionChoice `json:"choices,required"` - // The Unix timestamp (in seconds) of when the completion was created. - Created int64 `json:"created,required"` - // The model used for completion. - Model string `json:"model,required"` - // The object type, which is always "text_completion" - Object constant.TextCompletion `json:"object,required"` - // 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"` - // Usage statistics for the completion request. - Usage CompletionUsage `json:"usage"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ID respjson.Field - Choices respjson.Field - Created respjson.Field - Model respjson.Field - Object respjson.Field - SystemFingerprint respjson.Field - Usage respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r Completion) RawJSON() string { return r.JSON.raw } -func (r *Completion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type CompletionChoice 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, or `content_filter` if - // content was omitted due to a flag from our content filters. - // - // Any of "stop", "length", "content_filter". - FinishReason CompletionChoiceFinishReason `json:"finish_reason,required"` - Index int64 `json:"index,required"` - Logprobs CompletionChoiceLogprobs `json:"logprobs,required"` - Text string `json:"text,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - FinishReason respjson.Field - Index respjson.Field - Logprobs respjson.Field - Text respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r CompletionChoice) RawJSON() string { return r.JSON.raw } -func (r *CompletionChoice) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// 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. -type CompletionChoiceFinishReason string - -const ( - CompletionChoiceFinishReasonStop CompletionChoiceFinishReason = "stop" - CompletionChoiceFinishReasonLength CompletionChoiceFinishReason = "length" - CompletionChoiceFinishReasonContentFilter CompletionChoiceFinishReason = "content_filter" -) - -type CompletionChoiceLogprobs struct { - TextOffset []int64 `json:"text_offset"` - TokenLogprobs []float64 `json:"token_logprobs"` - Tokens []string `json:"tokens"` - TopLogprobs []map[string]float64 `json:"top_logprobs"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - TextOffset respjson.Field - TokenLogprobs respjson.Field - Tokens respjson.Field - TopLogprobs respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r CompletionChoiceLogprobs) RawJSON() string { return r.JSON.raw } -func (r *CompletionChoiceLogprobs) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Usage statistics for the completion request. -type CompletionUsage struct { - // Number of tokens in the generated completion. - CompletionTokens int64 `json:"completion_tokens,required"` - // Number of tokens in the prompt. - PromptTokens int64 `json:"prompt_tokens,required"` - // Total number of tokens used in the request (prompt + completion). - TotalTokens int64 `json:"total_tokens,required"` - // Breakdown of tokens used in a completion. - CompletionTokensDetails CompletionUsageCompletionTokensDetails `json:"completion_tokens_details"` - // Breakdown of tokens used in the prompt. - PromptTokensDetails CompletionUsagePromptTokensDetails `json:"prompt_tokens_details"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - CompletionTokens respjson.Field - PromptTokens respjson.Field - TotalTokens respjson.Field - CompletionTokensDetails respjson.Field - PromptTokensDetails respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r CompletionUsage) RawJSON() string { return r.JSON.raw } -func (r *CompletionUsage) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Breakdown of tokens used in a completion. -type CompletionUsageCompletionTokensDetails struct { - // When using Predicted Outputs, the number of tokens in the prediction that - // appeared in the completion. - AcceptedPredictionTokens int64 `json:"accepted_prediction_tokens"` - // Audio input tokens generated by the model. - AudioTokens int64 `json:"audio_tokens"` - // Tokens generated by the model for reasoning. - ReasoningTokens int64 `json:"reasoning_tokens"` - // When using Predicted Outputs, the number of tokens in the prediction that did - // not appear in the completion. However, like reasoning tokens, these tokens are - // still counted in the total completion tokens for purposes of billing, output, - // and context window limits. - RejectedPredictionTokens int64 `json:"rejected_prediction_tokens"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - AcceptedPredictionTokens respjson.Field - AudioTokens respjson.Field - ReasoningTokens respjson.Field - RejectedPredictionTokens respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r CompletionUsageCompletionTokensDetails) RawJSON() string { return r.JSON.raw } -func (r *CompletionUsageCompletionTokensDetails) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Breakdown of tokens used in the prompt. -type CompletionUsagePromptTokensDetails struct { - // Audio input tokens present in the prompt. - AudioTokens int64 `json:"audio_tokens"` - // Cached tokens present in the prompt. - CachedTokens int64 `json:"cached_tokens"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - AudioTokens respjson.Field - CachedTokens respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r CompletionUsagePromptTokensDetails) RawJSON() string { return r.JSON.raw } -func (r *CompletionUsagePromptTokensDetails) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type CompletionNewParams struct { - // 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. - Prompt CompletionNewParamsPromptUnion `json:"prompt,omitzero,required"` - // ID of the model to use. You can use the - // [List models](https://platform.openai.com/docs/api-reference/models/list) API to - // see all of your available models, or see our - // [Model overview](https://platform.openai.com/docs/models) for descriptions of - // them. - Model CompletionNewParamsModel `json:"model,omitzero,required"` - // 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`. - BestOf param.Opt[int64] `json:"best_of,omitzero"` - // Echo back the prompt in addition to the completion - Echo param.Opt[bool] `json:"echo,omitzero"` - // 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.](https://platform.openai.com/docs/guides/text-generation) - FrequencyPenalty param.Opt[float64] `json:"frequency_penalty,omitzero"` - // 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. - Logprobs param.Opt[int64] `json:"logprobs,omitzero"` - // 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. - MaxTokens param.Opt[int64] `json:"max_tokens,omitzero"` - // 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`. - N param.Opt[int64] `json:"n,omitzero"` - // 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.](https://platform.openai.com/docs/guides/text-generation) - PresencePenalty param.Opt[float64] `json:"presence_penalty,omitzero"` - // 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 param.Opt[int64] `json:"seed,omitzero"` - // The suffix that comes after a completion of inserted text. - // - // This parameter is only supported for `gpt-3.5-turbo-instruct`. - Suffix param.Opt[string] `json:"suffix,omitzero"` - // 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 param.Opt[float64] `json:"temperature,omitzero"` - // 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 param.Opt[float64] `json:"top_p,omitzero"` - // A unique identifier representing your end-user, which can help OpenAI to monitor - // and detect abuse. - // [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). - User param.Opt[string] `json:"user,omitzero"` - // 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. - LogitBias map[string]int64 `json:"logit_bias,omitzero"` - // Not supported with latest reasoning models `o3` and `o4-mini`. - // - // Up to 4 sequences where the API will stop generating further tokens. The - // returned text will not contain the stop sequence. - Stop CompletionNewParamsStopUnion `json:"stop,omitzero"` - // Options for streaming response. Only set this when you set `stream: true`. - StreamOptions ChatCompletionStreamOptionsParam `json:"stream_options,omitzero"` - paramObj -} - -func (r CompletionNewParams) MarshalJSON() (data []byte, err error) { - type shadow CompletionNewParams - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *CompletionNewParams) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// ID of the model to use. You can use the -// [List models](https://platform.openai.com/docs/api-reference/models/list) API to -// see all of your available models, or see our -// [Model overview](https://platform.openai.com/docs/models) for descriptions of -// them. -type CompletionNewParamsModel string - -const ( - CompletionNewParamsModelGPT3_5TurboInstruct CompletionNewParamsModel = "gpt-3.5-turbo-instruct" - CompletionNewParamsModelDavinci002 CompletionNewParamsModel = "davinci-002" - CompletionNewParamsModelBabbage002 CompletionNewParamsModel = "babbage-002" -) - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type CompletionNewParamsPromptUnion struct { - OfString param.Opt[string] `json:",omitzero,inline"` - OfArrayOfStrings []string `json:",omitzero,inline"` - OfArrayOfTokens []int64 `json:",omitzero,inline"` - OfArrayOfTokenArrays [][]int64 `json:",omitzero,inline"` - paramUnion -} - -func (u CompletionNewParamsPromptUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfString, u.OfArrayOfStrings, u.OfArrayOfTokens, u.OfArrayOfTokenArrays) -} -func (u *CompletionNewParamsPromptUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *CompletionNewParamsPromptUnion) asAny() any { - if !param.IsOmitted(u.OfString) { - return &u.OfString.Value - } else if !param.IsOmitted(u.OfArrayOfStrings) { - return &u.OfArrayOfStrings - } else if !param.IsOmitted(u.OfArrayOfTokens) { - return &u.OfArrayOfTokens - } else if !param.IsOmitted(u.OfArrayOfTokenArrays) { - return &u.OfArrayOfTokenArrays - } - return nil -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type CompletionNewParamsStopUnion struct { - OfString param.Opt[string] `json:",omitzero,inline"` - OfStringArray []string `json:",omitzero,inline"` - paramUnion -} - -func (u CompletionNewParamsStopUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfString, u.OfStringArray) -} -func (u *CompletionNewParamsStopUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *CompletionNewParamsStopUnion) asAny() any { - if !param.IsOmitted(u.OfString) { - return &u.OfString.Value - } else if !param.IsOmitted(u.OfStringArray) { - return &u.OfStringArray - } - return nil -} diff --git a/vendor/github.com/openai/openai-go/container.go b/vendor/github.com/openai/openai-go/container.go deleted file mode 100644 index 357bb988..00000000 --- a/vendor/github.com/openai/openai-go/container.go +++ /dev/null @@ -1,352 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -package openai - -import ( - "context" - "errors" - "fmt" - "net/http" - "net/url" - - "github.com/openai/openai-go/internal/apijson" - "github.com/openai/openai-go/internal/apiquery" - "github.com/openai/openai-go/internal/requestconfig" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/packages/pagination" - "github.com/openai/openai-go/packages/param" - "github.com/openai/openai-go/packages/respjson" -) - -// ContainerService contains methods and other services that help with interacting -// with the openai API. -// -// Note, unlike clients, this service does not read variables from the environment -// automatically. You should not instantiate this service directly, and instead use -// the [NewContainerService] method instead. -type ContainerService struct { - Options []option.RequestOption - Files ContainerFileService -} - -// NewContainerService generates a new service that applies the given options to -// each request. These options are applied after the parent client's options (if -// there is one), and before any request-specific options. -func NewContainerService(opts ...option.RequestOption) (r ContainerService) { - r = ContainerService{} - r.Options = opts - r.Files = NewContainerFileService(opts...) - return -} - -// Create Container -func (r *ContainerService) New(ctx context.Context, body ContainerNewParams, opts ...option.RequestOption) (res *ContainerNewResponse, err error) { - opts = append(r.Options[:], opts...) - path := "containers" - err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...) - return -} - -// Retrieve Container -func (r *ContainerService) Get(ctx context.Context, containerID string, opts ...option.RequestOption) (res *ContainerGetResponse, err error) { - opts = append(r.Options[:], opts...) - if containerID == "" { - err = errors.New("missing required container_id parameter") - return - } - path := fmt.Sprintf("containers/%s", containerID) - err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...) - return -} - -// List Containers -func (r *ContainerService) List(ctx context.Context, query ContainerListParams, opts ...option.RequestOption) (res *pagination.CursorPage[ContainerListResponse], err error) { - var raw *http.Response - opts = append(r.Options[:], opts...) - opts = append([]option.RequestOption{option.WithResponseInto(&raw)}, opts...) - path := "containers" - cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, query, &res, opts...) - if err != nil { - return nil, err - } - err = cfg.Execute() - if err != nil { - return nil, err - } - res.SetPageConfig(cfg, raw) - return res, nil -} - -// List Containers -func (r *ContainerService) ListAutoPaging(ctx context.Context, query ContainerListParams, opts ...option.RequestOption) *pagination.CursorPageAutoPager[ContainerListResponse] { - return pagination.NewCursorPageAutoPager(r.List(ctx, query, opts...)) -} - -// Delete Container -func (r *ContainerService) Delete(ctx context.Context, containerID string, opts ...option.RequestOption) (err error) { - opts = append(r.Options[:], opts...) - opts = append([]option.RequestOption{option.WithHeader("Accept", "")}, opts...) - if containerID == "" { - err = errors.New("missing required container_id parameter") - return - } - path := fmt.Sprintf("containers/%s", containerID) - err = requestconfig.ExecuteNewRequest(ctx, http.MethodDelete, path, nil, nil, opts...) - return -} - -type ContainerNewResponse struct { - // Unique identifier for the container. - ID string `json:"id,required"` - // Unix timestamp (in seconds) when the container was created. - CreatedAt int64 `json:"created_at,required"` - // Name of the container. - Name string `json:"name,required"` - // The type of this object. - Object string `json:"object,required"` - // Status of the container (e.g., active, deleted). - Status string `json:"status,required"` - // The container will expire after this time period. The anchor is the reference - // point for the expiration. The minutes is the number of minutes after the anchor - // before the container expires. - ExpiresAfter ContainerNewResponseExpiresAfter `json:"expires_after"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ID respjson.Field - CreatedAt respjson.Field - Name respjson.Field - Object respjson.Field - Status respjson.Field - ExpiresAfter respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ContainerNewResponse) RawJSON() string { return r.JSON.raw } -func (r *ContainerNewResponse) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The container will expire after this time period. The anchor is the reference -// point for the expiration. The minutes is the number of minutes after the anchor -// before the container expires. -type ContainerNewResponseExpiresAfter struct { - // The reference point for the expiration. - // - // Any of "last_active_at". - Anchor string `json:"anchor"` - // The number of minutes after the anchor before the container expires. - Minutes int64 `json:"minutes"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Anchor respjson.Field - Minutes respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ContainerNewResponseExpiresAfter) RawJSON() string { return r.JSON.raw } -func (r *ContainerNewResponseExpiresAfter) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type ContainerGetResponse struct { - // Unique identifier for the container. - ID string `json:"id,required"` - // Unix timestamp (in seconds) when the container was created. - CreatedAt int64 `json:"created_at,required"` - // Name of the container. - Name string `json:"name,required"` - // The type of this object. - Object string `json:"object,required"` - // Status of the container (e.g., active, deleted). - Status string `json:"status,required"` - // The container will expire after this time period. The anchor is the reference - // point for the expiration. The minutes is the number of minutes after the anchor - // before the container expires. - ExpiresAfter ContainerGetResponseExpiresAfter `json:"expires_after"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ID respjson.Field - CreatedAt respjson.Field - Name respjson.Field - Object respjson.Field - Status respjson.Field - ExpiresAfter respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ContainerGetResponse) RawJSON() string { return r.JSON.raw } -func (r *ContainerGetResponse) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The container will expire after this time period. The anchor is the reference -// point for the expiration. The minutes is the number of minutes after the anchor -// before the container expires. -type ContainerGetResponseExpiresAfter struct { - // The reference point for the expiration. - // - // Any of "last_active_at". - Anchor string `json:"anchor"` - // The number of minutes after the anchor before the container expires. - Minutes int64 `json:"minutes"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Anchor respjson.Field - Minutes respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ContainerGetResponseExpiresAfter) RawJSON() string { return r.JSON.raw } -func (r *ContainerGetResponseExpiresAfter) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type ContainerListResponse struct { - // Unique identifier for the container. - ID string `json:"id,required"` - // Unix timestamp (in seconds) when the container was created. - CreatedAt int64 `json:"created_at,required"` - // Name of the container. - Name string `json:"name,required"` - // The type of this object. - Object string `json:"object,required"` - // Status of the container (e.g., active, deleted). - Status string `json:"status,required"` - // The container will expire after this time period. The anchor is the reference - // point for the expiration. The minutes is the number of minutes after the anchor - // before the container expires. - ExpiresAfter ContainerListResponseExpiresAfter `json:"expires_after"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ID respjson.Field - CreatedAt respjson.Field - Name respjson.Field - Object respjson.Field - Status respjson.Field - ExpiresAfter respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ContainerListResponse) RawJSON() string { return r.JSON.raw } -func (r *ContainerListResponse) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The container will expire after this time period. The anchor is the reference -// point for the expiration. The minutes is the number of minutes after the anchor -// before the container expires. -type ContainerListResponseExpiresAfter struct { - // The reference point for the expiration. - // - // Any of "last_active_at". - Anchor string `json:"anchor"` - // The number of minutes after the anchor before the container expires. - Minutes int64 `json:"minutes"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Anchor respjson.Field - Minutes respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ContainerListResponseExpiresAfter) RawJSON() string { return r.JSON.raw } -func (r *ContainerListResponseExpiresAfter) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type ContainerNewParams struct { - // Name of the container to create. - Name string `json:"name,required"` - // Container expiration time in seconds relative to the 'anchor' time. - ExpiresAfter ContainerNewParamsExpiresAfter `json:"expires_after,omitzero"` - // IDs of files to copy to the container. - FileIDs []string `json:"file_ids,omitzero"` - paramObj -} - -func (r ContainerNewParams) MarshalJSON() (data []byte, err error) { - type shadow ContainerNewParams - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ContainerNewParams) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Container expiration time in seconds relative to the 'anchor' time. -// -// The properties Anchor, Minutes are required. -type ContainerNewParamsExpiresAfter struct { - // Time anchor for the expiration time. Currently only 'last_active_at' is - // supported. - // - // Any of "last_active_at". - Anchor string `json:"anchor,omitzero,required"` - Minutes int64 `json:"minutes,required"` - paramObj -} - -func (r ContainerNewParamsExpiresAfter) MarshalJSON() (data []byte, err error) { - type shadow ContainerNewParamsExpiresAfter - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ContainerNewParamsExpiresAfter) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -func init() { - apijson.RegisterFieldValidator[ContainerNewParamsExpiresAfter]( - "anchor", "last_active_at", - ) -} - -type ContainerListParams struct { - // 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. - After param.Opt[string] `query:"after,omitzero" json:"-"` - // A limit on the number of objects to be returned. Limit can range between 1 and - // 100, and the default is 20. - Limit param.Opt[int64] `query:"limit,omitzero" json:"-"` - // Sort order by the `created_at` timestamp of the objects. `asc` for ascending - // order and `desc` for descending order. - // - // Any of "asc", "desc". - Order ContainerListParamsOrder `query:"order,omitzero" json:"-"` - paramObj -} - -// URLQuery serializes [ContainerListParams]'s query parameters as `url.Values`. -func (r ContainerListParams) URLQuery() (v url.Values, err error) { - return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ - ArrayFormat: apiquery.ArrayQueryFormatBrackets, - NestedFormat: apiquery.NestedQueryFormatBrackets, - }) -} - -// Sort order by the `created_at` timestamp of the objects. `asc` for ascending -// order and `desc` for descending order. -type ContainerListParamsOrder string - -const ( - ContainerListParamsOrderAsc ContainerListParamsOrder = "asc" - ContainerListParamsOrderDesc ContainerListParamsOrder = "desc" -) diff --git a/vendor/github.com/openai/openai-go/containerfile.go b/vendor/github.com/openai/openai-go/containerfile.go deleted file mode 100644 index bd50b529..00000000 --- a/vendor/github.com/openai/openai-go/containerfile.go +++ /dev/null @@ -1,286 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -package openai - -import ( - "bytes" - "context" - "errors" - "fmt" - "io" - "mime/multipart" - "net/http" - "net/url" - - "github.com/openai/openai-go/internal/apiform" - "github.com/openai/openai-go/internal/apijson" - "github.com/openai/openai-go/internal/apiquery" - "github.com/openai/openai-go/internal/requestconfig" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/packages/pagination" - "github.com/openai/openai-go/packages/param" - "github.com/openai/openai-go/packages/respjson" - "github.com/openai/openai-go/shared/constant" -) - -// ContainerFileService contains methods and other services that help with -// interacting with the openai API. -// -// Note, unlike clients, this service does not read variables from the environment -// automatically. You should not instantiate this service directly, and instead use -// the [NewContainerFileService] method instead. -type ContainerFileService struct { - Options []option.RequestOption - Content ContainerFileContentService -} - -// NewContainerFileService generates a new service that applies the given options -// to each request. These options are applied after the parent client's options (if -// there is one), and before any request-specific options. -func NewContainerFileService(opts ...option.RequestOption) (r ContainerFileService) { - r = ContainerFileService{} - r.Options = opts - r.Content = NewContainerFileContentService(opts...) - return -} - -// Create a Container File -// -// You can send either a multipart/form-data request with the raw file content, or -// a JSON request with a file ID. -func (r *ContainerFileService) New(ctx context.Context, containerID string, body ContainerFileNewParams, opts ...option.RequestOption) (res *ContainerFileNewResponse, err error) { - opts = append(r.Options[:], opts...) - if containerID == "" { - err = errors.New("missing required container_id parameter") - return - } - path := fmt.Sprintf("containers/%s/files", containerID) - err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...) - return -} - -// Retrieve Container File -func (r *ContainerFileService) Get(ctx context.Context, containerID string, fileID string, opts ...option.RequestOption) (res *ContainerFileGetResponse, err error) { - opts = append(r.Options[:], opts...) - if containerID == "" { - err = errors.New("missing required container_id parameter") - return - } - if fileID == "" { - err = errors.New("missing required file_id parameter") - return - } - path := fmt.Sprintf("containers/%s/files/%s", containerID, fileID) - err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...) - return -} - -// List Container files -func (r *ContainerFileService) List(ctx context.Context, containerID string, query ContainerFileListParams, opts ...option.RequestOption) (res *pagination.CursorPage[ContainerFileListResponse], err error) { - var raw *http.Response - opts = append(r.Options[:], opts...) - opts = append([]option.RequestOption{option.WithResponseInto(&raw)}, opts...) - if containerID == "" { - err = errors.New("missing required container_id parameter") - return - } - path := fmt.Sprintf("containers/%s/files", containerID) - cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, query, &res, opts...) - if err != nil { - return nil, err - } - err = cfg.Execute() - if err != nil { - return nil, err - } - res.SetPageConfig(cfg, raw) - return res, nil -} - -// List Container files -func (r *ContainerFileService) ListAutoPaging(ctx context.Context, containerID string, query ContainerFileListParams, opts ...option.RequestOption) *pagination.CursorPageAutoPager[ContainerFileListResponse] { - return pagination.NewCursorPageAutoPager(r.List(ctx, containerID, query, opts...)) -} - -// Delete Container File -func (r *ContainerFileService) Delete(ctx context.Context, containerID string, fileID string, opts ...option.RequestOption) (err error) { - opts = append(r.Options[:], opts...) - opts = append([]option.RequestOption{option.WithHeader("Accept", "")}, opts...) - if containerID == "" { - err = errors.New("missing required container_id parameter") - return - } - if fileID == "" { - err = errors.New("missing required file_id parameter") - return - } - path := fmt.Sprintf("containers/%s/files/%s", containerID, fileID) - err = requestconfig.ExecuteNewRequest(ctx, http.MethodDelete, path, nil, nil, opts...) - return -} - -type ContainerFileNewResponse struct { - // Unique identifier for the file. - ID string `json:"id,required"` - // Size of the file in bytes. - Bytes int64 `json:"bytes,required"` - // The container this file belongs to. - ContainerID string `json:"container_id,required"` - // Unix timestamp (in seconds) when the file was created. - CreatedAt int64 `json:"created_at,required"` - // The type of this object (`container.file`). - Object constant.ContainerFile `json:"object,required"` - // Path of the file in the container. - Path string `json:"path,required"` - // Source of the file (e.g., `user`, `assistant`). - Source string `json:"source,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ID respjson.Field - Bytes respjson.Field - ContainerID respjson.Field - CreatedAt respjson.Field - Object respjson.Field - Path respjson.Field - Source respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ContainerFileNewResponse) RawJSON() string { return r.JSON.raw } -func (r *ContainerFileNewResponse) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type ContainerFileGetResponse struct { - // Unique identifier for the file. - ID string `json:"id,required"` - // Size of the file in bytes. - Bytes int64 `json:"bytes,required"` - // The container this file belongs to. - ContainerID string `json:"container_id,required"` - // Unix timestamp (in seconds) when the file was created. - CreatedAt int64 `json:"created_at,required"` - // The type of this object (`container.file`). - Object constant.ContainerFile `json:"object,required"` - // Path of the file in the container. - Path string `json:"path,required"` - // Source of the file (e.g., `user`, `assistant`). - Source string `json:"source,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ID respjson.Field - Bytes respjson.Field - ContainerID respjson.Field - CreatedAt respjson.Field - Object respjson.Field - Path respjson.Field - Source respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ContainerFileGetResponse) RawJSON() string { return r.JSON.raw } -func (r *ContainerFileGetResponse) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type ContainerFileListResponse struct { - // Unique identifier for the file. - ID string `json:"id,required"` - // Size of the file in bytes. - Bytes int64 `json:"bytes,required"` - // The container this file belongs to. - ContainerID string `json:"container_id,required"` - // Unix timestamp (in seconds) when the file was created. - CreatedAt int64 `json:"created_at,required"` - // The type of this object (`container.file`). - Object constant.ContainerFile `json:"object,required"` - // Path of the file in the container. - Path string `json:"path,required"` - // Source of the file (e.g., `user`, `assistant`). - Source string `json:"source,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ID respjson.Field - Bytes respjson.Field - ContainerID respjson.Field - CreatedAt respjson.Field - Object respjson.Field - Path respjson.Field - Source respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ContainerFileListResponse) RawJSON() string { return r.JSON.raw } -func (r *ContainerFileListResponse) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type ContainerFileNewParams struct { - // Name of the file to create. - FileID param.Opt[string] `json:"file_id,omitzero"` - // The File object (not file name) to be uploaded. - File io.Reader `json:"file,omitzero" format:"binary"` - paramObj -} - -func (r ContainerFileNewParams) MarshalMultipart() (data []byte, contentType string, err error) { - buf := bytes.NewBuffer(nil) - writer := multipart.NewWriter(buf) - err = apiform.MarshalRoot(r, writer) - if err == nil { - err = apiform.WriteExtras(writer, r.ExtraFields()) - } - if err != nil { - writer.Close() - return nil, "", err - } - err = writer.Close() - if err != nil { - return nil, "", err - } - return buf.Bytes(), writer.FormDataContentType(), nil -} - -type ContainerFileListParams struct { - // 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. - After param.Opt[string] `query:"after,omitzero" json:"-"` - // A limit on the number of objects to be returned. Limit can range between 1 and - // 100, and the default is 20. - Limit param.Opt[int64] `query:"limit,omitzero" json:"-"` - // Sort order by the `created_at` timestamp of the objects. `asc` for ascending - // order and `desc` for descending order. - // - // Any of "asc", "desc". - Order ContainerFileListParamsOrder `query:"order,omitzero" json:"-"` - paramObj -} - -// URLQuery serializes [ContainerFileListParams]'s query parameters as -// `url.Values`. -func (r ContainerFileListParams) URLQuery() (v url.Values, err error) { - return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ - ArrayFormat: apiquery.ArrayQueryFormatBrackets, - NestedFormat: apiquery.NestedQueryFormatBrackets, - }) -} - -// Sort order by the `created_at` timestamp of the objects. `asc` for ascending -// order and `desc` for descending order. -type ContainerFileListParamsOrder string - -const ( - ContainerFileListParamsOrderAsc ContainerFileListParamsOrder = "asc" - ContainerFileListParamsOrderDesc ContainerFileListParamsOrder = "desc" -) diff --git a/vendor/github.com/openai/openai-go/containerfilecontent.go b/vendor/github.com/openai/openai-go/containerfilecontent.go deleted file mode 100644 index 0fb0fa9f..00000000 --- a/vendor/github.com/openai/openai-go/containerfilecontent.go +++ /dev/null @@ -1,49 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -package openai - -import ( - "context" - "errors" - "fmt" - "net/http" - - "github.com/openai/openai-go/internal/requestconfig" - "github.com/openai/openai-go/option" -) - -// ContainerFileContentService contains methods and other services that help with -// interacting with the openai API. -// -// Note, unlike clients, this service does not read variables from the environment -// automatically. You should not instantiate this service directly, and instead use -// the [NewContainerFileContentService] method instead. -type ContainerFileContentService struct { - Options []option.RequestOption -} - -// NewContainerFileContentService generates a new service that applies the given -// options to each request. These options are applied after the parent client's -// options (if there is one), and before any request-specific options. -func NewContainerFileContentService(opts ...option.RequestOption) (r ContainerFileContentService) { - r = ContainerFileContentService{} - r.Options = opts - return -} - -// Retrieve Container File Content -func (r *ContainerFileContentService) Get(ctx context.Context, containerID string, fileID string, opts ...option.RequestOption) (res *http.Response, err error) { - opts = append(r.Options[:], opts...) - opts = append([]option.RequestOption{option.WithHeader("Accept", "application/binary")}, opts...) - if containerID == "" { - err = errors.New("missing required container_id parameter") - return - } - if fileID == "" { - err = errors.New("missing required file_id parameter") - return - } - path := fmt.Sprintf("containers/%s/files/%s/content", containerID, fileID) - err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...) - return -} diff --git a/vendor/github.com/openai/openai-go/embedding.go b/vendor/github.com/openai/openai-go/embedding.go deleted file mode 100644 index f7650f55..00000000 --- a/vendor/github.com/openai/openai-go/embedding.go +++ /dev/null @@ -1,203 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -package openai - -import ( - "context" - "net/http" - - "github.com/openai/openai-go/internal/apijson" - "github.com/openai/openai-go/internal/requestconfig" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/packages/param" - "github.com/openai/openai-go/packages/respjson" - "github.com/openai/openai-go/shared/constant" -) - -// EmbeddingService contains methods and other services that help with interacting -// with the openai API. -// -// Note, unlike clients, this service does not read variables from the environment -// automatically. You should not instantiate this service directly, and instead use -// the [NewEmbeddingService] method instead. -type EmbeddingService struct { - Options []option.RequestOption -} - -// NewEmbeddingService generates a new service that applies the given options to -// each request. These options are applied after the parent client's options (if -// there is one), and before any request-specific options. -func NewEmbeddingService(opts ...option.RequestOption) (r EmbeddingService) { - r = EmbeddingService{} - r.Options = opts - return -} - -// Creates an embedding vector representing the input text. -func (r *EmbeddingService) New(ctx context.Context, body EmbeddingNewParams, opts ...option.RequestOption) (res *CreateEmbeddingResponse, err error) { - opts = append(r.Options[:], opts...) - path := "embeddings" - err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...) - return -} - -type CreateEmbeddingResponse struct { - // The list of embeddings generated by the model. - Data []Embedding `json:"data,required"` - // The name of the model used to generate the embedding. - Model string `json:"model,required"` - // The object type, which is always "list". - Object constant.List `json:"object,required"` - // The usage information for the request. - Usage CreateEmbeddingResponseUsage `json:"usage,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Data respjson.Field - Model respjson.Field - Object respjson.Field - Usage respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r CreateEmbeddingResponse) RawJSON() string { return r.JSON.raw } -func (r *CreateEmbeddingResponse) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The usage information for the request. -type CreateEmbeddingResponseUsage struct { - // The number of tokens used by the prompt. - PromptTokens int64 `json:"prompt_tokens,required"` - // The total number of tokens used by the request. - TotalTokens int64 `json:"total_tokens,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - PromptTokens respjson.Field - TotalTokens respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r CreateEmbeddingResponseUsage) RawJSON() string { return r.JSON.raw } -func (r *CreateEmbeddingResponseUsage) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Represents an embedding vector returned by embedding endpoint. -type Embedding struct { - // The embedding vector, which is a list of floats. The length of vector depends on - // the model as listed in the - // [embedding guide](https://platform.openai.com/docs/guides/embeddings). - Embedding []float64 `json:"embedding,required"` - // The index of the embedding in the list of embeddings. - Index int64 `json:"index,required"` - // The object type, which is always "embedding". - Object constant.Embedding `json:"object,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Embedding respjson.Field - Index respjson.Field - Object respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r Embedding) RawJSON() string { return r.JSON.raw } -func (r *Embedding) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type EmbeddingModel = string - -const ( - EmbeddingModelTextEmbeddingAda002 EmbeddingModel = "text-embedding-ada-002" - EmbeddingModelTextEmbedding3Small EmbeddingModel = "text-embedding-3-small" - EmbeddingModelTextEmbedding3Large EmbeddingModel = "text-embedding-3-large" -) - -type EmbeddingNewParams struct { - // 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 - // all embedding models), 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. In addition to the per-input token limit, all embedding - // models enforce a maximum of 300,000 tokens summed across all inputs in a single - // request. - Input EmbeddingNewParamsInputUnion `json:"input,omitzero,required"` - // ID of the model to use. You can use the - // [List models](https://platform.openai.com/docs/api-reference/models/list) API to - // see all of your available models, or see our - // [Model overview](https://platform.openai.com/docs/models) for descriptions of - // them. - Model EmbeddingModel `json:"model,omitzero,required"` - // The number of dimensions the resulting output embeddings should have. Only - // supported in `text-embedding-3` and later models. - Dimensions param.Opt[int64] `json:"dimensions,omitzero"` - // A unique identifier representing your end-user, which can help OpenAI to monitor - // and detect abuse. - // [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). - User param.Opt[string] `json:"user,omitzero"` - // The format to return the embeddings in. Can be either `float` or - // [`base64`](https://pypi.org/project/pybase64/). - // - // Any of "float", "base64". - EncodingFormat EmbeddingNewParamsEncodingFormat `json:"encoding_format,omitzero"` - paramObj -} - -func (r EmbeddingNewParams) MarshalJSON() (data []byte, err error) { - type shadow EmbeddingNewParams - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *EmbeddingNewParams) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type EmbeddingNewParamsInputUnion struct { - OfString param.Opt[string] `json:",omitzero,inline"` - OfArrayOfStrings []string `json:",omitzero,inline"` - OfArrayOfTokens []int64 `json:",omitzero,inline"` - OfArrayOfTokenArrays [][]int64 `json:",omitzero,inline"` - paramUnion -} - -func (u EmbeddingNewParamsInputUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfString, u.OfArrayOfStrings, u.OfArrayOfTokens, u.OfArrayOfTokenArrays) -} -func (u *EmbeddingNewParamsInputUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *EmbeddingNewParamsInputUnion) asAny() any { - if !param.IsOmitted(u.OfString) { - return &u.OfString.Value - } else if !param.IsOmitted(u.OfArrayOfStrings) { - return &u.OfArrayOfStrings - } else if !param.IsOmitted(u.OfArrayOfTokens) { - return &u.OfArrayOfTokens - } else if !param.IsOmitted(u.OfArrayOfTokenArrays) { - return &u.OfArrayOfTokenArrays - } - return nil -} - -// The format to return the embeddings in. Can be either `float` or -// [`base64`](https://pypi.org/project/pybase64/). -type EmbeddingNewParamsEncodingFormat string - -const ( - EmbeddingNewParamsEncodingFormatFloat EmbeddingNewParamsEncodingFormat = "float" - EmbeddingNewParamsEncodingFormatBase64 EmbeddingNewParamsEncodingFormat = "base64" -) diff --git a/vendor/github.com/openai/openai-go/field.go b/vendor/github.com/openai/openai-go/field.go deleted file mode 100644 index affd8998..00000000 --- a/vendor/github.com/openai/openai-go/field.go +++ /dev/null @@ -1,45 +0,0 @@ -package openai - -import ( - "github.com/openai/openai-go/packages/param" - "io" - "time" -) - -func String(s string) param.Opt[string] { return param.NewOpt(s) } -func Int(i int64) param.Opt[int64] { return param.NewOpt(i) } -func Bool(b bool) param.Opt[bool] { return param.NewOpt(b) } -func Float(f float64) param.Opt[float64] { return param.NewOpt(f) } -func Time(t time.Time) param.Opt[time.Time] { return param.NewOpt(t) } - -func Opt[T comparable](v T) param.Opt[T] { return param.NewOpt(v) } -func Ptr[T any](v T) *T { return &v } - -func IntPtr(v int64) *int64 { return &v } -func BoolPtr(v bool) *bool { return &v } -func FloatPtr(v float64) *float64 { return &v } -func StringPtr(v string) *string { return &v } -func TimePtr(v time.Time) *time.Time { return &v } - -func File(rdr io.Reader, filename string, contentType string) file { - return file{rdr, filename, contentType} -} - -type file struct { - io.Reader - name string - contentType string -} - -func (f file) Filename() string { - if f.name != "" { - return f.name - } else if named, ok := f.Reader.(interface{ Name() string }); ok { - return named.Name() - } - return "" -} - -func (f file) ContentType() string { - return f.contentType -} diff --git a/vendor/github.com/openai/openai-go/file.go b/vendor/github.com/openai/openai-go/file.go deleted file mode 100644 index 7aa70565..00000000 --- a/vendor/github.com/openai/openai-go/file.go +++ /dev/null @@ -1,314 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -package openai - -import ( - "bytes" - "context" - "errors" - "fmt" - "io" - "mime/multipart" - "net/http" - "net/url" - - "github.com/openai/openai-go/internal/apiform" - "github.com/openai/openai-go/internal/apijson" - "github.com/openai/openai-go/internal/apiquery" - "github.com/openai/openai-go/internal/requestconfig" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/packages/pagination" - "github.com/openai/openai-go/packages/param" - "github.com/openai/openai-go/packages/respjson" - "github.com/openai/openai-go/shared/constant" -) - -// FileService contains methods and other services that help with interacting with -// the openai API. -// -// Note, unlike clients, this service does not read variables from the environment -// automatically. You should not instantiate this service directly, and instead use -// the [NewFileService] method instead. -type FileService struct { - Options []option.RequestOption -} - -// NewFileService generates a new service that applies the given options to each -// request. These options are applied after the parent client's options (if there -// is one), and before any request-specific options. -func NewFileService(opts ...option.RequestOption) (r FileService) { - r = FileService{} - r.Options = opts - return -} - -// Upload a file that can be used across various endpoints. Individual files can be -// up to 512 MB, and the size of all files uploaded by one organization can be up -// to 100 GB. -// -// The Assistants API supports files up to 2 million tokens and of specific file -// types. See the -// [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) for -// details. -// -// The Fine-tuning API only supports `.jsonl` files. The input also has certain -// required formats for fine-tuning -// [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input) or -// [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input) -// models. -// -// The Batch API only supports `.jsonl` files up to 200 MB in size. The input also -// has a specific required -// [format](https://platform.openai.com/docs/api-reference/batch/request-input). -// -// Please [contact us](https://help.openai.com/) if you need to increase these -// storage limits. -func (r *FileService) New(ctx context.Context, body FileNewParams, opts ...option.RequestOption) (res *FileObject, err error) { - opts = append(r.Options[:], opts...) - path := "files" - err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...) - return -} - -// Returns information about a specific file. -func (r *FileService) Get(ctx context.Context, fileID string, opts ...option.RequestOption) (res *FileObject, err error) { - opts = append(r.Options[:], opts...) - if fileID == "" { - err = errors.New("missing required file_id parameter") - return - } - path := fmt.Sprintf("files/%s", fileID) - err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...) - return -} - -// Returns a list of files. -func (r *FileService) List(ctx context.Context, query FileListParams, opts ...option.RequestOption) (res *pagination.CursorPage[FileObject], err error) { - var raw *http.Response - opts = append(r.Options[:], opts...) - opts = append([]option.RequestOption{option.WithResponseInto(&raw)}, opts...) - path := "files" - cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, query, &res, opts...) - if err != nil { - return nil, err - } - err = cfg.Execute() - if err != nil { - return nil, err - } - res.SetPageConfig(cfg, raw) - return res, nil -} - -// Returns a list of files. -func (r *FileService) ListAutoPaging(ctx context.Context, query FileListParams, opts ...option.RequestOption) *pagination.CursorPageAutoPager[FileObject] { - return pagination.NewCursorPageAutoPager(r.List(ctx, query, opts...)) -} - -// Delete a file. -func (r *FileService) Delete(ctx context.Context, fileID string, opts ...option.RequestOption) (res *FileDeleted, err error) { - opts = append(r.Options[:], opts...) - if fileID == "" { - err = errors.New("missing required file_id parameter") - return - } - path := fmt.Sprintf("files/%s", fileID) - err = requestconfig.ExecuteNewRequest(ctx, http.MethodDelete, path, nil, &res, opts...) - return -} - -// Returns the contents of the specified file. -func (r *FileService) Content(ctx context.Context, fileID string, opts ...option.RequestOption) (res *http.Response, err error) { - opts = append(r.Options[:], opts...) - opts = append([]option.RequestOption{option.WithHeader("Accept", "application/binary")}, opts...) - if fileID == "" { - err = errors.New("missing required file_id parameter") - return - } - path := fmt.Sprintf("files/%s/content", fileID) - err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...) - return -} - -type FileDeleted struct { - ID string `json:"id,required"` - Deleted bool `json:"deleted,required"` - Object constant.File `json:"object,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ID respjson.Field - Deleted respjson.Field - Object respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r FileDeleted) RawJSON() string { return r.JSON.raw } -func (r *FileDeleted) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The `File` object represents a document that has been uploaded to OpenAI. -type FileObject struct { - // The file identifier, which can be referenced in the API endpoints. - ID string `json:"id,required"` - // The size of the file, in bytes. - Bytes int64 `json:"bytes,required"` - // The Unix timestamp (in seconds) for when the file was created. - CreatedAt int64 `json:"created_at,required"` - // The name of the file. - Filename string `json:"filename,required"` - // The object type, which is always `file`. - Object constant.File `json:"object,required"` - // The intended purpose of the file. Supported values are `assistants`, - // `assistants_output`, `batch`, `batch_output`, `fine-tune`, `fine-tune-results`, - // `vision`, and `user_data`. - // - // Any of "assistants", "assistants_output", "batch", "batch_output", "fine-tune", - // "fine-tune-results", "vision", "user_data". - Purpose FileObjectPurpose `json:"purpose,required"` - // Deprecated. The current status of the file, which can be either `uploaded`, - // `processed`, or `error`. - // - // Any of "uploaded", "processed", "error". - // - // Deprecated: deprecated - Status FileObjectStatus `json:"status,required"` - // The Unix timestamp (in seconds) for when the file will expire. - ExpiresAt int64 `json:"expires_at"` - // Deprecated. For details on why a fine-tuning training file failed validation, - // see the `error` field on `fine_tuning.job`. - // - // Deprecated: deprecated - StatusDetails string `json:"status_details"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ID respjson.Field - Bytes respjson.Field - CreatedAt respjson.Field - Filename respjson.Field - Object respjson.Field - Purpose respjson.Field - Status respjson.Field - ExpiresAt respjson.Field - StatusDetails respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r FileObject) RawJSON() string { return r.JSON.raw } -func (r *FileObject) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The intended purpose of the file. Supported values are `assistants`, -// `assistants_output`, `batch`, `batch_output`, `fine-tune`, `fine-tune-results`, -// `vision`, and `user_data`. -type FileObjectPurpose string - -const ( - FileObjectPurposeAssistants FileObjectPurpose = "assistants" - FileObjectPurposeAssistantsOutput FileObjectPurpose = "assistants_output" - FileObjectPurposeBatch FileObjectPurpose = "batch" - FileObjectPurposeBatchOutput FileObjectPurpose = "batch_output" - FileObjectPurposeFineTune FileObjectPurpose = "fine-tune" - FileObjectPurposeFineTuneResults FileObjectPurpose = "fine-tune-results" - FileObjectPurposeVision FileObjectPurpose = "vision" - FileObjectPurposeUserData FileObjectPurpose = "user_data" -) - -// Deprecated. The current status of the file, which can be either `uploaded`, -// `processed`, or `error`. -type FileObjectStatus string - -const ( - FileObjectStatusUploaded FileObjectStatus = "uploaded" - FileObjectStatusProcessed FileObjectStatus = "processed" - FileObjectStatusError FileObjectStatus = "error" -) - -// The intended purpose of the uploaded file. One of: - `assistants`: Used in the -// Assistants API - `batch`: Used in the Batch API - `fine-tune`: Used for -// fine-tuning - `vision`: Images used for vision fine-tuning - `user_data`: -// Flexible file type for any purpose - `evals`: Used for eval data sets -type FilePurpose string - -const ( - FilePurposeAssistants FilePurpose = "assistants" - FilePurposeBatch FilePurpose = "batch" - FilePurposeFineTune FilePurpose = "fine-tune" - FilePurposeVision FilePurpose = "vision" - FilePurposeUserData FilePurpose = "user_data" - FilePurposeEvals FilePurpose = "evals" -) - -type FileNewParams struct { - // The File object (not file name) to be uploaded. - File io.Reader `json:"file,omitzero,required" format:"binary"` - // The intended purpose of the uploaded file. One of: - `assistants`: Used in the - // Assistants API - `batch`: Used in the Batch API - `fine-tune`: Used for - // fine-tuning - `vision`: Images used for vision fine-tuning - `user_data`: - // Flexible file type for any purpose - `evals`: Used for eval data sets - // - // Any of "assistants", "batch", "fine-tune", "vision", "user_data", "evals". - Purpose FilePurpose `json:"purpose,omitzero,required"` - paramObj -} - -func (r FileNewParams) MarshalMultipart() (data []byte, contentType string, err error) { - buf := bytes.NewBuffer(nil) - writer := multipart.NewWriter(buf) - err = apiform.MarshalRoot(r, writer) - if err == nil { - err = apiform.WriteExtras(writer, r.ExtraFields()) - } - if err != nil { - writer.Close() - return nil, "", err - } - err = writer.Close() - if err != nil { - return nil, "", err - } - return buf.Bytes(), writer.FormDataContentType(), nil -} - -type FileListParams struct { - // 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. - After param.Opt[string] `query:"after,omitzero" json:"-"` - // A limit on the number of objects to be returned. Limit can range between 1 and - // 10,000, and the default is 10,000. - Limit param.Opt[int64] `query:"limit,omitzero" json:"-"` - // Only return files with the given purpose. - Purpose param.Opt[string] `query:"purpose,omitzero" json:"-"` - // Sort order by the `created_at` timestamp of the objects. `asc` for ascending - // order and `desc` for descending order. - // - // Any of "asc", "desc". - Order FileListParamsOrder `query:"order,omitzero" json:"-"` - paramObj -} - -// URLQuery serializes [FileListParams]'s query parameters as `url.Values`. -func (r FileListParams) URLQuery() (v url.Values, err error) { - return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ - ArrayFormat: apiquery.ArrayQueryFormatBrackets, - NestedFormat: apiquery.NestedQueryFormatBrackets, - }) -} - -// Sort order by the `created_at` timestamp of the objects. `asc` for ascending -// order and `desc` for descending order. -type FileListParamsOrder string - -const ( - FileListParamsOrderAsc FileListParamsOrder = "asc" - FileListParamsOrderDesc FileListParamsOrder = "desc" -) diff --git a/vendor/github.com/openai/openai-go/finetuning.go b/vendor/github.com/openai/openai-go/finetuning.go deleted file mode 100644 index 3de51c13..00000000 --- a/vendor/github.com/openai/openai-go/finetuning.go +++ /dev/null @@ -1,34 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -package openai - -import ( - "github.com/openai/openai-go/option" -) - -// FineTuningService contains methods and other services that help with interacting -// with the openai API. -// -// Note, unlike clients, this service does not read variables from the environment -// automatically. You should not instantiate this service directly, and instead use -// the [NewFineTuningService] method instead. -type FineTuningService struct { - Options []option.RequestOption - Methods FineTuningMethodService - Jobs FineTuningJobService - Checkpoints FineTuningCheckpointService - Alpha FineTuningAlphaService -} - -// NewFineTuningService generates a new service that applies the given options to -// each request. These options are applied after the parent client's options (if -// there is one), and before any request-specific options. -func NewFineTuningService(opts ...option.RequestOption) (r FineTuningService) { - r = FineTuningService{} - r.Options = opts - r.Methods = NewFineTuningMethodService(opts...) - r.Jobs = NewFineTuningJobService(opts...) - r.Checkpoints = NewFineTuningCheckpointService(opts...) - r.Alpha = NewFineTuningAlphaService(opts...) - return -} diff --git a/vendor/github.com/openai/openai-go/finetuningalpha.go b/vendor/github.com/openai/openai-go/finetuningalpha.go deleted file mode 100644 index 986a178f..00000000 --- a/vendor/github.com/openai/openai-go/finetuningalpha.go +++ /dev/null @@ -1,28 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -package openai - -import ( - "github.com/openai/openai-go/option" -) - -// FineTuningAlphaService contains methods and other services that help with -// interacting with the openai API. -// -// Note, unlike clients, this service does not read variables from the environment -// automatically. You should not instantiate this service directly, and instead use -// the [NewFineTuningAlphaService] method instead. -type FineTuningAlphaService struct { - Options []option.RequestOption - Graders FineTuningAlphaGraderService -} - -// NewFineTuningAlphaService generates a new service that applies the given options -// to each request. These options are applied after the parent client's options (if -// there is one), and before any request-specific options. -func NewFineTuningAlphaService(opts ...option.RequestOption) (r FineTuningAlphaService) { - r = FineTuningAlphaService{} - r.Options = opts - r.Graders = NewFineTuningAlphaGraderService(opts...) - return -} diff --git a/vendor/github.com/openai/openai-go/finetuningalphagrader.go b/vendor/github.com/openai/openai-go/finetuningalphagrader.go deleted file mode 100644 index 49205832..00000000 --- a/vendor/github.com/openai/openai-go/finetuningalphagrader.go +++ /dev/null @@ -1,672 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -package openai - -import ( - "context" - "encoding/json" - "net/http" - - "github.com/openai/openai-go/internal/apijson" - "github.com/openai/openai-go/internal/requestconfig" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/packages/param" - "github.com/openai/openai-go/packages/respjson" -) - -// FineTuningAlphaGraderService contains methods and other services that help with -// interacting with the openai API. -// -// Note, unlike clients, this service does not read variables from the environment -// automatically. You should not instantiate this service directly, and instead use -// the [NewFineTuningAlphaGraderService] method instead. -type FineTuningAlphaGraderService struct { - Options []option.RequestOption -} - -// NewFineTuningAlphaGraderService generates a new service that applies the given -// options to each request. These options are applied after the parent client's -// options (if there is one), and before any request-specific options. -func NewFineTuningAlphaGraderService(opts ...option.RequestOption) (r FineTuningAlphaGraderService) { - r = FineTuningAlphaGraderService{} - r.Options = opts - return -} - -// Run a grader. -func (r *FineTuningAlphaGraderService) Run(ctx context.Context, body FineTuningAlphaGraderRunParams, opts ...option.RequestOption) (res *FineTuningAlphaGraderRunResponse, err error) { - opts = append(r.Options[:], opts...) - path := "fine_tuning/alpha/graders/run" - err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...) - return -} - -// Validate a grader. -func (r *FineTuningAlphaGraderService) Validate(ctx context.Context, body FineTuningAlphaGraderValidateParams, opts ...option.RequestOption) (res *FineTuningAlphaGraderValidateResponse, err error) { - opts = append(r.Options[:], opts...) - path := "fine_tuning/alpha/graders/validate" - err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...) - return -} - -type FineTuningAlphaGraderRunResponse struct { - Metadata FineTuningAlphaGraderRunResponseMetadata `json:"metadata,required"` - ModelGraderTokenUsagePerModel map[string]any `json:"model_grader_token_usage_per_model,required"` - Reward float64 `json:"reward,required"` - SubRewards map[string]any `json:"sub_rewards,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Metadata respjson.Field - ModelGraderTokenUsagePerModel respjson.Field - Reward respjson.Field - SubRewards respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r FineTuningAlphaGraderRunResponse) RawJSON() string { return r.JSON.raw } -func (r *FineTuningAlphaGraderRunResponse) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type FineTuningAlphaGraderRunResponseMetadata struct { - Errors FineTuningAlphaGraderRunResponseMetadataErrors `json:"errors,required"` - ExecutionTime float64 `json:"execution_time,required"` - Name string `json:"name,required"` - SampledModelName string `json:"sampled_model_name,required"` - Scores map[string]any `json:"scores,required"` - TokenUsage int64 `json:"token_usage,required"` - Type string `json:"type,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Errors respjson.Field - ExecutionTime respjson.Field - Name respjson.Field - SampledModelName respjson.Field - Scores respjson.Field - TokenUsage respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r FineTuningAlphaGraderRunResponseMetadata) RawJSON() string { return r.JSON.raw } -func (r *FineTuningAlphaGraderRunResponseMetadata) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type FineTuningAlphaGraderRunResponseMetadataErrors struct { - FormulaParseError bool `json:"formula_parse_error,required"` - InvalidVariableError bool `json:"invalid_variable_error,required"` - ModelGraderParseError bool `json:"model_grader_parse_error,required"` - ModelGraderRefusalError bool `json:"model_grader_refusal_error,required"` - ModelGraderServerError bool `json:"model_grader_server_error,required"` - ModelGraderServerErrorDetails string `json:"model_grader_server_error_details,required"` - OtherError bool `json:"other_error,required"` - PythonGraderRuntimeError bool `json:"python_grader_runtime_error,required"` - PythonGraderRuntimeErrorDetails string `json:"python_grader_runtime_error_details,required"` - PythonGraderServerError bool `json:"python_grader_server_error,required"` - PythonGraderServerErrorType string `json:"python_grader_server_error_type,required"` - SampleParseError bool `json:"sample_parse_error,required"` - TruncatedObservationError bool `json:"truncated_observation_error,required"` - UnresponsiveRewardError bool `json:"unresponsive_reward_error,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - FormulaParseError respjson.Field - InvalidVariableError respjson.Field - ModelGraderParseError respjson.Field - ModelGraderRefusalError respjson.Field - ModelGraderServerError respjson.Field - ModelGraderServerErrorDetails respjson.Field - OtherError respjson.Field - PythonGraderRuntimeError respjson.Field - PythonGraderRuntimeErrorDetails respjson.Field - PythonGraderServerError respjson.Field - PythonGraderServerErrorType respjson.Field - SampleParseError respjson.Field - TruncatedObservationError respjson.Field - UnresponsiveRewardError respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r FineTuningAlphaGraderRunResponseMetadataErrors) RawJSON() string { return r.JSON.raw } -func (r *FineTuningAlphaGraderRunResponseMetadataErrors) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type FineTuningAlphaGraderValidateResponse struct { - // The grader used for the fine-tuning job. - Grader FineTuningAlphaGraderValidateResponseGraderUnion `json:"grader"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Grader respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r FineTuningAlphaGraderValidateResponse) RawJSON() string { return r.JSON.raw } -func (r *FineTuningAlphaGraderValidateResponse) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// FineTuningAlphaGraderValidateResponseGraderUnion contains all possible -// properties and values from [StringCheckGrader], [TextSimilarityGrader], -// [PythonGrader], [ScoreModelGrader], [MultiGrader]. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -type FineTuningAlphaGraderValidateResponseGraderUnion struct { - // This field is a union of [string], [string], [[]ScoreModelGraderInput] - Input FineTuningAlphaGraderValidateResponseGraderUnionInput `json:"input"` - Name string `json:"name"` - // This field is from variant [StringCheckGrader]. - Operation StringCheckGraderOperation `json:"operation"` - Reference string `json:"reference"` - Type string `json:"type"` - // This field is from variant [TextSimilarityGrader]. - EvaluationMetric TextSimilarityGraderEvaluationMetric `json:"evaluation_metric"` - // This field is from variant [PythonGrader]. - Source string `json:"source"` - // This field is from variant [PythonGrader]. - ImageTag string `json:"image_tag"` - // This field is from variant [ScoreModelGrader]. - Model string `json:"model"` - // This field is from variant [ScoreModelGrader]. - Range []float64 `json:"range"` - // This field is from variant [ScoreModelGrader]. - SamplingParams any `json:"sampling_params"` - // This field is from variant [MultiGrader]. - CalculateOutput string `json:"calculate_output"` - // This field is from variant [MultiGrader]. - Graders MultiGraderGradersUnion `json:"graders"` - JSON struct { - Input respjson.Field - Name respjson.Field - Operation respjson.Field - Reference respjson.Field - Type respjson.Field - EvaluationMetric respjson.Field - Source respjson.Field - ImageTag respjson.Field - Model respjson.Field - Range respjson.Field - SamplingParams respjson.Field - CalculateOutput respjson.Field - Graders respjson.Field - raw string - } `json:"-"` -} - -func (u FineTuningAlphaGraderValidateResponseGraderUnion) AsStringCheckGrader() (v StringCheckGrader) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u FineTuningAlphaGraderValidateResponseGraderUnion) AsTextSimilarityGrader() (v TextSimilarityGrader) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u FineTuningAlphaGraderValidateResponseGraderUnion) AsPythonGrader() (v PythonGrader) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u FineTuningAlphaGraderValidateResponseGraderUnion) AsScoreModelGrader() (v ScoreModelGrader) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u FineTuningAlphaGraderValidateResponseGraderUnion) AsMultiGrader() (v MultiGrader) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -// Returns the unmodified JSON received from the API -func (u FineTuningAlphaGraderValidateResponseGraderUnion) RawJSON() string { return u.JSON.raw } - -func (r *FineTuningAlphaGraderValidateResponseGraderUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// FineTuningAlphaGraderValidateResponseGraderUnionInput is an implicit subunion of -// [FineTuningAlphaGraderValidateResponseGraderUnion]. -// FineTuningAlphaGraderValidateResponseGraderUnionInput provides convenient access -// to the sub-properties of the union. -// -// For type safety it is recommended to directly use a variant of the -// [FineTuningAlphaGraderValidateResponseGraderUnion]. -// -// If the underlying value is not a json object, one of the following properties -// will be valid: OfString OfScoreModelGraderInputArray] -type FineTuningAlphaGraderValidateResponseGraderUnionInput struct { - // This field will be present if the value is a [string] instead of an object. - OfString string `json:",inline"` - // This field will be present if the value is a [[]ScoreModelGraderInput] instead - // of an object. - OfScoreModelGraderInputArray []ScoreModelGraderInput `json:",inline"` - JSON struct { - OfString respjson.Field - OfScoreModelGraderInputArray respjson.Field - raw string - } `json:"-"` -} - -func (r *FineTuningAlphaGraderValidateResponseGraderUnionInput) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type FineTuningAlphaGraderRunParams struct { - // The grader used for the fine-tuning job. - Grader FineTuningAlphaGraderRunParamsGraderUnion `json:"grader,omitzero,required"` - // The model sample to be evaluated. This value will be used to populate the - // `sample` namespace. See - // [the guide](https://platform.openai.com/docs/guides/graders) for more details. - // The `output_json` variable will be populated if the model sample is a valid JSON - // string. - ModelSample string `json:"model_sample,required"` - // The dataset item provided to the grader. This will be used to populate the - // `item` namespace. See - // [the guide](https://platform.openai.com/docs/guides/graders) for more details. - Item any `json:"item,omitzero"` - paramObj -} - -func (r FineTuningAlphaGraderRunParams) MarshalJSON() (data []byte, err error) { - type shadow FineTuningAlphaGraderRunParams - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *FineTuningAlphaGraderRunParams) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type FineTuningAlphaGraderRunParamsGraderUnion struct { - OfStringCheck *StringCheckGraderParam `json:",omitzero,inline"` - OfTextSimilarity *TextSimilarityGraderParam `json:",omitzero,inline"` - OfPython *PythonGraderParam `json:",omitzero,inline"` - OfScoreModel *ScoreModelGraderParam `json:",omitzero,inline"` - OfMulti *MultiGraderParam `json:",omitzero,inline"` - paramUnion -} - -func (u FineTuningAlphaGraderRunParamsGraderUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfStringCheck, - u.OfTextSimilarity, - u.OfPython, - u.OfScoreModel, - u.OfMulti) -} -func (u *FineTuningAlphaGraderRunParamsGraderUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *FineTuningAlphaGraderRunParamsGraderUnion) asAny() any { - if !param.IsOmitted(u.OfStringCheck) { - return u.OfStringCheck - } else if !param.IsOmitted(u.OfTextSimilarity) { - return u.OfTextSimilarity - } else if !param.IsOmitted(u.OfPython) { - return u.OfPython - } else if !param.IsOmitted(u.OfScoreModel) { - return u.OfScoreModel - } else if !param.IsOmitted(u.OfMulti) { - return u.OfMulti - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u FineTuningAlphaGraderRunParamsGraderUnion) GetOperation() *string { - if vt := u.OfStringCheck; vt != nil { - return (*string)(&vt.Operation) - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u FineTuningAlphaGraderRunParamsGraderUnion) GetEvaluationMetric() *string { - if vt := u.OfTextSimilarity; vt != nil { - return (*string)(&vt.EvaluationMetric) - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u FineTuningAlphaGraderRunParamsGraderUnion) GetSource() *string { - if vt := u.OfPython; vt != nil { - return &vt.Source - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u FineTuningAlphaGraderRunParamsGraderUnion) GetImageTag() *string { - if vt := u.OfPython; vt != nil && vt.ImageTag.Valid() { - return &vt.ImageTag.Value - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u FineTuningAlphaGraderRunParamsGraderUnion) GetModel() *string { - if vt := u.OfScoreModel; vt != nil { - return &vt.Model - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u FineTuningAlphaGraderRunParamsGraderUnion) GetRange() []float64 { - if vt := u.OfScoreModel; vt != nil { - return vt.Range - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u FineTuningAlphaGraderRunParamsGraderUnion) GetSamplingParams() *any { - if vt := u.OfScoreModel; vt != nil { - return &vt.SamplingParams - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u FineTuningAlphaGraderRunParamsGraderUnion) GetCalculateOutput() *string { - if vt := u.OfMulti; vt != nil { - return &vt.CalculateOutput - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u FineTuningAlphaGraderRunParamsGraderUnion) GetGraders() *MultiGraderGradersUnionParam { - if vt := u.OfMulti; vt != nil { - return &vt.Graders - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u FineTuningAlphaGraderRunParamsGraderUnion) GetName() *string { - if vt := u.OfStringCheck; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfTextSimilarity; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfPython; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfScoreModel; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfMulti; vt != nil { - return (*string)(&vt.Name) - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u FineTuningAlphaGraderRunParamsGraderUnion) GetReference() *string { - if vt := u.OfStringCheck; vt != nil { - return (*string)(&vt.Reference) - } else if vt := u.OfTextSimilarity; vt != nil { - return (*string)(&vt.Reference) - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u FineTuningAlphaGraderRunParamsGraderUnion) GetType() *string { - if vt := u.OfStringCheck; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfTextSimilarity; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfPython; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfScoreModel; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfMulti; vt != nil { - return (*string)(&vt.Type) - } - return nil -} - -// Returns a subunion which exports methods to access subproperties -// -// Or use AsAny() to get the underlying value -func (u FineTuningAlphaGraderRunParamsGraderUnion) GetInput() (res fineTuningAlphaGraderRunParamsGraderUnionInput) { - if vt := u.OfStringCheck; vt != nil { - res.any = &vt.Input - } else if vt := u.OfTextSimilarity; vt != nil { - res.any = &vt.Input - } else if vt := u.OfScoreModel; vt != nil { - res.any = &vt.Input - } - return -} - -// Can have the runtime types [*string], [\*[]ScoreModelGraderInputParam] -type fineTuningAlphaGraderRunParamsGraderUnionInput struct{ any } - -// Use the following switch statement to get the type of the union: -// -// switch u.AsAny().(type) { -// case *string: -// case *[]openai.ScoreModelGraderInputParam: -// default: -// fmt.Errorf("not present") -// } -func (u fineTuningAlphaGraderRunParamsGraderUnionInput) AsAny() any { return u.any } - -func init() { - apijson.RegisterUnion[FineTuningAlphaGraderRunParamsGraderUnion]( - "type", - apijson.Discriminator[StringCheckGraderParam]("string_check"), - apijson.Discriminator[TextSimilarityGraderParam]("text_similarity"), - apijson.Discriminator[PythonGraderParam]("python"), - apijson.Discriminator[ScoreModelGraderParam]("score_model"), - apijson.Discriminator[MultiGraderParam]("multi"), - ) -} - -type FineTuningAlphaGraderValidateParams struct { - // The grader used for the fine-tuning job. - Grader FineTuningAlphaGraderValidateParamsGraderUnion `json:"grader,omitzero,required"` - paramObj -} - -func (r FineTuningAlphaGraderValidateParams) MarshalJSON() (data []byte, err error) { - type shadow FineTuningAlphaGraderValidateParams - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *FineTuningAlphaGraderValidateParams) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type FineTuningAlphaGraderValidateParamsGraderUnion struct { - OfStringCheckGrader *StringCheckGraderParam `json:",omitzero,inline"` - OfTextSimilarityGrader *TextSimilarityGraderParam `json:",omitzero,inline"` - OfPythonGrader *PythonGraderParam `json:",omitzero,inline"` - OfScoreModelGrader *ScoreModelGraderParam `json:",omitzero,inline"` - OfMultiGrader *MultiGraderParam `json:",omitzero,inline"` - paramUnion -} - -func (u FineTuningAlphaGraderValidateParamsGraderUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfStringCheckGrader, - u.OfTextSimilarityGrader, - u.OfPythonGrader, - u.OfScoreModelGrader, - u.OfMultiGrader) -} -func (u *FineTuningAlphaGraderValidateParamsGraderUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *FineTuningAlphaGraderValidateParamsGraderUnion) asAny() any { - if !param.IsOmitted(u.OfStringCheckGrader) { - return u.OfStringCheckGrader - } else if !param.IsOmitted(u.OfTextSimilarityGrader) { - return u.OfTextSimilarityGrader - } else if !param.IsOmitted(u.OfPythonGrader) { - return u.OfPythonGrader - } else if !param.IsOmitted(u.OfScoreModelGrader) { - return u.OfScoreModelGrader - } else if !param.IsOmitted(u.OfMultiGrader) { - return u.OfMultiGrader - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u FineTuningAlphaGraderValidateParamsGraderUnion) GetOperation() *string { - if vt := u.OfStringCheckGrader; vt != nil { - return (*string)(&vt.Operation) - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u FineTuningAlphaGraderValidateParamsGraderUnion) GetEvaluationMetric() *string { - if vt := u.OfTextSimilarityGrader; vt != nil { - return (*string)(&vt.EvaluationMetric) - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u FineTuningAlphaGraderValidateParamsGraderUnion) GetSource() *string { - if vt := u.OfPythonGrader; vt != nil { - return &vt.Source - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u FineTuningAlphaGraderValidateParamsGraderUnion) GetImageTag() *string { - if vt := u.OfPythonGrader; vt != nil && vt.ImageTag.Valid() { - return &vt.ImageTag.Value - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u FineTuningAlphaGraderValidateParamsGraderUnion) GetModel() *string { - if vt := u.OfScoreModelGrader; vt != nil { - return &vt.Model - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u FineTuningAlphaGraderValidateParamsGraderUnion) GetRange() []float64 { - if vt := u.OfScoreModelGrader; vt != nil { - return vt.Range - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u FineTuningAlphaGraderValidateParamsGraderUnion) GetSamplingParams() *any { - if vt := u.OfScoreModelGrader; vt != nil { - return &vt.SamplingParams - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u FineTuningAlphaGraderValidateParamsGraderUnion) GetCalculateOutput() *string { - if vt := u.OfMultiGrader; vt != nil { - return &vt.CalculateOutput - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u FineTuningAlphaGraderValidateParamsGraderUnion) GetGraders() *MultiGraderGradersUnionParam { - if vt := u.OfMultiGrader; vt != nil { - return &vt.Graders - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u FineTuningAlphaGraderValidateParamsGraderUnion) GetName() *string { - if vt := u.OfStringCheckGrader; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfTextSimilarityGrader; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfPythonGrader; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfScoreModelGrader; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfMultiGrader; vt != nil { - return (*string)(&vt.Name) - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u FineTuningAlphaGraderValidateParamsGraderUnion) GetReference() *string { - if vt := u.OfStringCheckGrader; vt != nil { - return (*string)(&vt.Reference) - } else if vt := u.OfTextSimilarityGrader; vt != nil { - return (*string)(&vt.Reference) - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u FineTuningAlphaGraderValidateParamsGraderUnion) GetType() *string { - if vt := u.OfStringCheckGrader; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfTextSimilarityGrader; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfPythonGrader; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfScoreModelGrader; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfMultiGrader; vt != nil { - return (*string)(&vt.Type) - } - return nil -} - -// Returns a subunion which exports methods to access subproperties -// -// Or use AsAny() to get the underlying value -func (u FineTuningAlphaGraderValidateParamsGraderUnion) GetInput() (res fineTuningAlphaGraderValidateParamsGraderUnionInput) { - if vt := u.OfStringCheckGrader; vt != nil { - res.any = &vt.Input - } else if vt := u.OfTextSimilarityGrader; vt != nil { - res.any = &vt.Input - } else if vt := u.OfScoreModelGrader; vt != nil { - res.any = &vt.Input - } - return -} - -// Can have the runtime types [*string], [\*[]ScoreModelGraderInputParam] -type fineTuningAlphaGraderValidateParamsGraderUnionInput struct{ any } - -// Use the following switch statement to get the type of the union: -// -// switch u.AsAny().(type) { -// case *string: -// case *[]openai.ScoreModelGraderInputParam: -// default: -// fmt.Errorf("not present") -// } -func (u fineTuningAlphaGraderValidateParamsGraderUnionInput) AsAny() any { return u.any } diff --git a/vendor/github.com/openai/openai-go/finetuningcheckpoint.go b/vendor/github.com/openai/openai-go/finetuningcheckpoint.go deleted file mode 100644 index 11a485e7..00000000 --- a/vendor/github.com/openai/openai-go/finetuningcheckpoint.go +++ /dev/null @@ -1,28 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -package openai - -import ( - "github.com/openai/openai-go/option" -) - -// FineTuningCheckpointService contains methods and other services that help with -// interacting with the openai API. -// -// Note, unlike clients, this service does not read variables from the environment -// automatically. You should not instantiate this service directly, and instead use -// the [NewFineTuningCheckpointService] method instead. -type FineTuningCheckpointService struct { - Options []option.RequestOption - Permissions FineTuningCheckpointPermissionService -} - -// NewFineTuningCheckpointService generates a new service that applies the given -// options to each request. These options are applied after the parent client's -// options (if there is one), and before any request-specific options. -func NewFineTuningCheckpointService(opts ...option.RequestOption) (r FineTuningCheckpointService) { - r = FineTuningCheckpointService{} - r.Options = opts - r.Permissions = NewFineTuningCheckpointPermissionService(opts...) - return -} diff --git a/vendor/github.com/openai/openai-go/finetuningcheckpointpermission.go b/vendor/github.com/openai/openai-go/finetuningcheckpointpermission.go deleted file mode 100644 index 27992919..00000000 --- a/vendor/github.com/openai/openai-go/finetuningcheckpointpermission.go +++ /dev/null @@ -1,254 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -package openai - -import ( - "context" - "errors" - "fmt" - "net/http" - "net/url" - - "github.com/openai/openai-go/internal/apijson" - "github.com/openai/openai-go/internal/apiquery" - "github.com/openai/openai-go/internal/requestconfig" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/packages/pagination" - "github.com/openai/openai-go/packages/param" - "github.com/openai/openai-go/packages/respjson" - "github.com/openai/openai-go/shared/constant" -) - -// FineTuningCheckpointPermissionService contains methods and other services that -// help with interacting with the openai API. -// -// Note, unlike clients, this service does not read variables from the environment -// automatically. You should not instantiate this service directly, and instead use -// the [NewFineTuningCheckpointPermissionService] method instead. -type FineTuningCheckpointPermissionService struct { - Options []option.RequestOption -} - -// NewFineTuningCheckpointPermissionService generates a new service that applies -// the given options to each request. These options are applied after the parent -// client's options (if there is one), and before any request-specific options. -func NewFineTuningCheckpointPermissionService(opts ...option.RequestOption) (r FineTuningCheckpointPermissionService) { - r = FineTuningCheckpointPermissionService{} - r.Options = opts - return -} - -// **NOTE:** Calling this endpoint requires an [admin API key](../admin-api-keys). -// -// This enables organization owners to share fine-tuned models with other projects -// in their organization. -func (r *FineTuningCheckpointPermissionService) New(ctx context.Context, fineTunedModelCheckpoint string, body FineTuningCheckpointPermissionNewParams, opts ...option.RequestOption) (res *pagination.Page[FineTuningCheckpointPermissionNewResponse], err error) { - var raw *http.Response - opts = append(r.Options[:], opts...) - opts = append([]option.RequestOption{option.WithResponseInto(&raw)}, opts...) - if fineTunedModelCheckpoint == "" { - err = errors.New("missing required fine_tuned_model_checkpoint parameter") - return - } - path := fmt.Sprintf("fine_tuning/checkpoints/%s/permissions", fineTunedModelCheckpoint) - cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodPost, path, body, &res, opts...) - if err != nil { - return nil, err - } - err = cfg.Execute() - if err != nil { - return nil, err - } - res.SetPageConfig(cfg, raw) - return res, nil -} - -// **NOTE:** Calling this endpoint requires an [admin API key](../admin-api-keys). -// -// This enables organization owners to share fine-tuned models with other projects -// in their organization. -func (r *FineTuningCheckpointPermissionService) NewAutoPaging(ctx context.Context, fineTunedModelCheckpoint string, body FineTuningCheckpointPermissionNewParams, opts ...option.RequestOption) *pagination.PageAutoPager[FineTuningCheckpointPermissionNewResponse] { - return pagination.NewPageAutoPager(r.New(ctx, fineTunedModelCheckpoint, body, opts...)) -} - -// **NOTE:** This endpoint requires an [admin API key](../admin-api-keys). -// -// Organization owners can use this endpoint to view all permissions for a -// fine-tuned model checkpoint. -func (r *FineTuningCheckpointPermissionService) Get(ctx context.Context, fineTunedModelCheckpoint string, query FineTuningCheckpointPermissionGetParams, opts ...option.RequestOption) (res *FineTuningCheckpointPermissionGetResponse, err error) { - opts = append(r.Options[:], opts...) - if fineTunedModelCheckpoint == "" { - err = errors.New("missing required fine_tuned_model_checkpoint parameter") - return - } - path := fmt.Sprintf("fine_tuning/checkpoints/%s/permissions", fineTunedModelCheckpoint) - err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, query, &res, opts...) - return -} - -// **NOTE:** This endpoint requires an [admin API key](../admin-api-keys). -// -// Organization owners can use this endpoint to delete a permission for a -// fine-tuned model checkpoint. -func (r *FineTuningCheckpointPermissionService) Delete(ctx context.Context, fineTunedModelCheckpoint string, permissionID string, opts ...option.RequestOption) (res *FineTuningCheckpointPermissionDeleteResponse, err error) { - opts = append(r.Options[:], opts...) - if fineTunedModelCheckpoint == "" { - err = errors.New("missing required fine_tuned_model_checkpoint parameter") - return - } - if permissionID == "" { - err = errors.New("missing required permission_id parameter") - return - } - path := fmt.Sprintf("fine_tuning/checkpoints/%s/permissions/%s", fineTunedModelCheckpoint, permissionID) - err = requestconfig.ExecuteNewRequest(ctx, http.MethodDelete, path, nil, &res, opts...) - return -} - -// The `checkpoint.permission` object represents a permission for a fine-tuned -// model checkpoint. -type FineTuningCheckpointPermissionNewResponse struct { - // The permission identifier, which can be referenced in the API endpoints. - ID string `json:"id,required"` - // The Unix timestamp (in seconds) for when the permission was created. - CreatedAt int64 `json:"created_at,required"` - // The object type, which is always "checkpoint.permission". - Object constant.CheckpointPermission `json:"object,required"` - // The project identifier that the permission is for. - ProjectID string `json:"project_id,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ID respjson.Field - CreatedAt respjson.Field - Object respjson.Field - ProjectID respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r FineTuningCheckpointPermissionNewResponse) RawJSON() string { return r.JSON.raw } -func (r *FineTuningCheckpointPermissionNewResponse) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type FineTuningCheckpointPermissionGetResponse struct { - Data []FineTuningCheckpointPermissionGetResponseData `json:"data,required"` - HasMore bool `json:"has_more,required"` - Object constant.List `json:"object,required"` - FirstID string `json:"first_id,nullable"` - LastID string `json:"last_id,nullable"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Data respjson.Field - HasMore respjson.Field - Object respjson.Field - FirstID respjson.Field - LastID respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r FineTuningCheckpointPermissionGetResponse) RawJSON() string { return r.JSON.raw } -func (r *FineTuningCheckpointPermissionGetResponse) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The `checkpoint.permission` object represents a permission for a fine-tuned -// model checkpoint. -type FineTuningCheckpointPermissionGetResponseData struct { - // The permission identifier, which can be referenced in the API endpoints. - ID string `json:"id,required"` - // The Unix timestamp (in seconds) for when the permission was created. - CreatedAt int64 `json:"created_at,required"` - // The object type, which is always "checkpoint.permission". - Object constant.CheckpointPermission `json:"object,required"` - // The project identifier that the permission is for. - ProjectID string `json:"project_id,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ID respjson.Field - CreatedAt respjson.Field - Object respjson.Field - ProjectID respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r FineTuningCheckpointPermissionGetResponseData) RawJSON() string { return r.JSON.raw } -func (r *FineTuningCheckpointPermissionGetResponseData) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type FineTuningCheckpointPermissionDeleteResponse struct { - // The ID of the fine-tuned model checkpoint permission that was deleted. - ID string `json:"id,required"` - // Whether the fine-tuned model checkpoint permission was successfully deleted. - Deleted bool `json:"deleted,required"` - // The object type, which is always "checkpoint.permission". - Object constant.CheckpointPermission `json:"object,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ID respjson.Field - Deleted respjson.Field - Object respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r FineTuningCheckpointPermissionDeleteResponse) RawJSON() string { return r.JSON.raw } -func (r *FineTuningCheckpointPermissionDeleteResponse) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type FineTuningCheckpointPermissionNewParams struct { - // The project identifiers to grant access to. - ProjectIDs []string `json:"project_ids,omitzero,required"` - paramObj -} - -func (r FineTuningCheckpointPermissionNewParams) MarshalJSON() (data []byte, err error) { - type shadow FineTuningCheckpointPermissionNewParams - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *FineTuningCheckpointPermissionNewParams) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type FineTuningCheckpointPermissionGetParams struct { - // Identifier for the last permission ID from the previous pagination request. - After param.Opt[string] `query:"after,omitzero" json:"-"` - // Number of permissions to retrieve. - Limit param.Opt[int64] `query:"limit,omitzero" json:"-"` - // The ID of the project to get permissions for. - ProjectID param.Opt[string] `query:"project_id,omitzero" json:"-"` - // The order in which to retrieve permissions. - // - // Any of "ascending", "descending". - Order FineTuningCheckpointPermissionGetParamsOrder `query:"order,omitzero" json:"-"` - paramObj -} - -// URLQuery serializes [FineTuningCheckpointPermissionGetParams]'s query parameters -// as `url.Values`. -func (r FineTuningCheckpointPermissionGetParams) URLQuery() (v url.Values, err error) { - return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ - ArrayFormat: apiquery.ArrayQueryFormatBrackets, - NestedFormat: apiquery.NestedQueryFormatBrackets, - }) -} - -// The order in which to retrieve permissions. -type FineTuningCheckpointPermissionGetParamsOrder string - -const ( - FineTuningCheckpointPermissionGetParamsOrderAscending FineTuningCheckpointPermissionGetParamsOrder = "ascending" - FineTuningCheckpointPermissionGetParamsOrderDescending FineTuningCheckpointPermissionGetParamsOrder = "descending" -) diff --git a/vendor/github.com/openai/openai-go/finetuningjob.go b/vendor/github.com/openai/openai-go/finetuningjob.go deleted file mode 100644 index 5776f03c..00000000 --- a/vendor/github.com/openai/openai-go/finetuningjob.go +++ /dev/null @@ -1,880 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -package openai - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "net/http" - "net/url" - - "github.com/openai/openai-go/internal/apijson" - "github.com/openai/openai-go/internal/apiquery" - "github.com/openai/openai-go/internal/requestconfig" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/packages/pagination" - "github.com/openai/openai-go/packages/param" - "github.com/openai/openai-go/packages/respjson" - "github.com/openai/openai-go/shared" - "github.com/openai/openai-go/shared/constant" -) - -// FineTuningJobService contains methods and other services that help with -// interacting with the openai API. -// -// Note, unlike clients, this service does not read variables from the environment -// automatically. You should not instantiate this service directly, and instead use -// the [NewFineTuningJobService] method instead. -type FineTuningJobService struct { - Options []option.RequestOption - Checkpoints FineTuningJobCheckpointService -} - -// NewFineTuningJobService generates a new service that applies the given options -// to each request. These options are applied after the parent client's options (if -// there is one), and before any request-specific options. -func NewFineTuningJobService(opts ...option.RequestOption) (r FineTuningJobService) { - r = FineTuningJobService{} - r.Options = opts - r.Checkpoints = NewFineTuningJobCheckpointService(opts...) - return -} - -// Creates a fine-tuning job which begins the process of creating a new model from -// a given dataset. -// -// Response includes details of the enqueued job including job status and the name -// of the fine-tuned models once complete. -// -// [Learn more about fine-tuning](https://platform.openai.com/docs/guides/model-optimization) -func (r *FineTuningJobService) New(ctx context.Context, body FineTuningJobNewParams, opts ...option.RequestOption) (res *FineTuningJob, err error) { - opts = append(r.Options[:], opts...) - path := "fine_tuning/jobs" - err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...) - return -} - -// Get info about a fine-tuning job. -// -// [Learn more about fine-tuning](https://platform.openai.com/docs/guides/model-optimization) -func (r *FineTuningJobService) Get(ctx context.Context, fineTuningJobID string, opts ...option.RequestOption) (res *FineTuningJob, err error) { - opts = append(r.Options[:], opts...) - if fineTuningJobID == "" { - err = errors.New("missing required fine_tuning_job_id parameter") - return - } - path := fmt.Sprintf("fine_tuning/jobs/%s", fineTuningJobID) - err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...) - return -} - -// List your organization's fine-tuning jobs -func (r *FineTuningJobService) List(ctx context.Context, query FineTuningJobListParams, opts ...option.RequestOption) (res *pagination.CursorPage[FineTuningJob], err error) { - var raw *http.Response - opts = append(r.Options[:], opts...) - opts = append([]option.RequestOption{option.WithResponseInto(&raw)}, opts...) - path := "fine_tuning/jobs" - cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, query, &res, opts...) - if err != nil { - return nil, err - } - err = cfg.Execute() - if err != nil { - return nil, err - } - res.SetPageConfig(cfg, raw) - return res, nil -} - -// List your organization's fine-tuning jobs -func (r *FineTuningJobService) ListAutoPaging(ctx context.Context, query FineTuningJobListParams, opts ...option.RequestOption) *pagination.CursorPageAutoPager[FineTuningJob] { - return pagination.NewCursorPageAutoPager(r.List(ctx, query, opts...)) -} - -// Immediately cancel a fine-tune job. -func (r *FineTuningJobService) Cancel(ctx context.Context, fineTuningJobID string, opts ...option.RequestOption) (res *FineTuningJob, err error) { - opts = append(r.Options[:], opts...) - if fineTuningJobID == "" { - err = errors.New("missing required fine_tuning_job_id parameter") - return - } - path := fmt.Sprintf("fine_tuning/jobs/%s/cancel", fineTuningJobID) - err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, nil, &res, opts...) - return -} - -// Get status updates for a fine-tuning job. -func (r *FineTuningJobService) ListEvents(ctx context.Context, fineTuningJobID string, query FineTuningJobListEventsParams, opts ...option.RequestOption) (res *pagination.CursorPage[FineTuningJobEvent], err error) { - var raw *http.Response - opts = append(r.Options[:], opts...) - opts = append([]option.RequestOption{option.WithResponseInto(&raw)}, opts...) - if fineTuningJobID == "" { - err = errors.New("missing required fine_tuning_job_id parameter") - return - } - path := fmt.Sprintf("fine_tuning/jobs/%s/events", fineTuningJobID) - cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, query, &res, opts...) - if err != nil { - return nil, err - } - err = cfg.Execute() - if err != nil { - return nil, err - } - res.SetPageConfig(cfg, raw) - return res, nil -} - -// Get status updates for a fine-tuning job. -func (r *FineTuningJobService) ListEventsAutoPaging(ctx context.Context, fineTuningJobID string, query FineTuningJobListEventsParams, opts ...option.RequestOption) *pagination.CursorPageAutoPager[FineTuningJobEvent] { - return pagination.NewCursorPageAutoPager(r.ListEvents(ctx, fineTuningJobID, query, opts...)) -} - -// Pause a fine-tune job. -func (r *FineTuningJobService) Pause(ctx context.Context, fineTuningJobID string, opts ...option.RequestOption) (res *FineTuningJob, err error) { - opts = append(r.Options[:], opts...) - if fineTuningJobID == "" { - err = errors.New("missing required fine_tuning_job_id parameter") - return - } - path := fmt.Sprintf("fine_tuning/jobs/%s/pause", fineTuningJobID) - err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, nil, &res, opts...) - return -} - -// Resume a fine-tune job. -func (r *FineTuningJobService) Resume(ctx context.Context, fineTuningJobID string, opts ...option.RequestOption) (res *FineTuningJob, err error) { - opts = append(r.Options[:], opts...) - if fineTuningJobID == "" { - err = errors.New("missing required fine_tuning_job_id parameter") - return - } - path := fmt.Sprintf("fine_tuning/jobs/%s/resume", fineTuningJobID) - err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, nil, &res, opts...) - return -} - -// The `fine_tuning.job` object represents a fine-tuning job that has been created -// through the API. -type FineTuningJob struct { - // The object identifier, which can be referenced in the API endpoints. - ID string `json:"id,required"` - // The Unix timestamp (in seconds) for when the fine-tuning job was created. - CreatedAt int64 `json:"created_at,required"` - // For fine-tuning jobs that have `failed`, this will contain more information on - // the cause of the failure. - Error FineTuningJobError `json:"error,required"` - // The name of the fine-tuned model that is being created. The value will be null - // if the fine-tuning job is still running. - FineTunedModel string `json:"fine_tuned_model,required"` - // 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. - FinishedAt int64 `json:"finished_at,required"` - // The hyperparameters used for the fine-tuning job. This value will only be - // returned when running `supervised` jobs. - Hyperparameters FineTuningJobHyperparameters `json:"hyperparameters,required"` - // The base model that is being fine-tuned. - Model string `json:"model,required"` - // The object type, which is always "fine_tuning.job". - Object constant.FineTuningJob `json:"object,required"` - // The organization that owns the fine-tuning job. - OrganizationID string `json:"organization_id,required"` - // The compiled results file ID(s) for the fine-tuning job. You can retrieve the - // results with the - // [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents). - ResultFiles []string `json:"result_files,required"` - // The seed used for the fine-tuning job. - Seed int64 `json:"seed,required"` - // The current status of the fine-tuning job, which can be either - // `validating_files`, `queued`, `running`, `succeeded`, `failed`, or `cancelled`. - // - // Any of "validating_files", "queued", "running", "succeeded", "failed", - // "cancelled". - Status FineTuningJobStatus `json:"status,required"` - // 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. - TrainedTokens int64 `json:"trained_tokens,required"` - // The file ID used for training. You can retrieve the training data with the - // [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents). - TrainingFile string `json:"training_file,required"` - // The file ID used for validation. You can retrieve the validation results with - // the - // [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents). - ValidationFile string `json:"validation_file,required"` - // 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. - EstimatedFinish int64 `json:"estimated_finish,nullable"` - // A list of integrations to enable for this fine-tuning job. - Integrations []FineTuningJobWandbIntegrationObject `json:"integrations,nullable"` - // 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, and - // querying for objects via API or the dashboard. - // - // Keys are strings with a maximum length of 64 characters. Values are strings with - // a maximum length of 512 characters. - Metadata shared.Metadata `json:"metadata,nullable"` - // The method used for fine-tuning. - Method FineTuningJobMethod `json:"method"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ID respjson.Field - CreatedAt respjson.Field - Error respjson.Field - FineTunedModel respjson.Field - FinishedAt respjson.Field - Hyperparameters respjson.Field - Model respjson.Field - Object respjson.Field - OrganizationID respjson.Field - ResultFiles respjson.Field - Seed respjson.Field - Status respjson.Field - TrainedTokens respjson.Field - TrainingFile respjson.Field - ValidationFile respjson.Field - EstimatedFinish respjson.Field - Integrations respjson.Field - Metadata respjson.Field - Method respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r FineTuningJob) RawJSON() string { return r.JSON.raw } -func (r *FineTuningJob) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// For fine-tuning jobs that have `failed`, this will contain more information on -// the cause of the failure. -type FineTuningJobError struct { - // A machine-readable error code. - Code string `json:"code,required"` - // A human-readable error message. - Message string `json:"message,required"` - // The parameter that was invalid, usually `training_file` or `validation_file`. - // This field will be null if the failure was not parameter-specific. - Param string `json:"param,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Code respjson.Field - Message respjson.Field - Param respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r FineTuningJobError) RawJSON() string { return r.JSON.raw } -func (r *FineTuningJobError) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The hyperparameters used for the fine-tuning job. This value will only be -// returned when running `supervised` jobs. -type FineTuningJobHyperparameters struct { - // Number of examples in each batch. A larger batch size means that model - // parameters are updated less frequently, but with lower variance. - BatchSize FineTuningJobHyperparametersBatchSizeUnion `json:"batch_size,nullable"` - // Scaling factor for the learning rate. A smaller learning rate may be useful to - // avoid overfitting. - LearningRateMultiplier FineTuningJobHyperparametersLearningRateMultiplierUnion `json:"learning_rate_multiplier"` - // The number of epochs to train the model for. An epoch refers to one full cycle - // through the training dataset. - NEpochs FineTuningJobHyperparametersNEpochsUnion `json:"n_epochs"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - BatchSize respjson.Field - LearningRateMultiplier respjson.Field - NEpochs respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r FineTuningJobHyperparameters) RawJSON() string { return r.JSON.raw } -func (r *FineTuningJobHyperparameters) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// FineTuningJobHyperparametersBatchSizeUnion contains all possible properties and -// values from [constant.Auto], [int64]. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -// -// If the underlying value is not a json object, one of the following properties -// will be valid: OfAuto OfInt] -type FineTuningJobHyperparametersBatchSizeUnion struct { - // This field will be present if the value is a [constant.Auto] instead of an - // object. - OfAuto constant.Auto `json:",inline"` - // This field will be present if the value is a [int64] instead of an object. - OfInt int64 `json:",inline"` - JSON struct { - OfAuto respjson.Field - OfInt respjson.Field - raw string - } `json:"-"` -} - -func (u FineTuningJobHyperparametersBatchSizeUnion) AsAuto() (v constant.Auto) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u FineTuningJobHyperparametersBatchSizeUnion) AsInt() (v int64) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -// Returns the unmodified JSON received from the API -func (u FineTuningJobHyperparametersBatchSizeUnion) RawJSON() string { return u.JSON.raw } - -func (r *FineTuningJobHyperparametersBatchSizeUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// FineTuningJobHyperparametersLearningRateMultiplierUnion contains all possible -// properties and values from [constant.Auto], [float64]. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -// -// If the underlying value is not a json object, one of the following properties -// will be valid: OfAuto OfFloat] -type FineTuningJobHyperparametersLearningRateMultiplierUnion struct { - // This field will be present if the value is a [constant.Auto] instead of an - // object. - OfAuto constant.Auto `json:",inline"` - // This field will be present if the value is a [float64] instead of an object. - OfFloat float64 `json:",inline"` - JSON struct { - OfAuto respjson.Field - OfFloat respjson.Field - raw string - } `json:"-"` -} - -func (u FineTuningJobHyperparametersLearningRateMultiplierUnion) AsAuto() (v constant.Auto) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u FineTuningJobHyperparametersLearningRateMultiplierUnion) AsFloat() (v float64) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -// Returns the unmodified JSON received from the API -func (u FineTuningJobHyperparametersLearningRateMultiplierUnion) RawJSON() string { return u.JSON.raw } - -func (r *FineTuningJobHyperparametersLearningRateMultiplierUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// FineTuningJobHyperparametersNEpochsUnion contains all possible properties and -// values from [constant.Auto], [int64]. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -// -// If the underlying value is not a json object, one of the following properties -// will be valid: OfAuto OfInt] -type FineTuningJobHyperparametersNEpochsUnion struct { - // This field will be present if the value is a [constant.Auto] instead of an - // object. - OfAuto constant.Auto `json:",inline"` - // This field will be present if the value is a [int64] instead of an object. - OfInt int64 `json:",inline"` - JSON struct { - OfAuto respjson.Field - OfInt respjson.Field - raw string - } `json:"-"` -} - -func (u FineTuningJobHyperparametersNEpochsUnion) AsAuto() (v constant.Auto) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u FineTuningJobHyperparametersNEpochsUnion) AsInt() (v int64) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -// Returns the unmodified JSON received from the API -func (u FineTuningJobHyperparametersNEpochsUnion) RawJSON() string { return u.JSON.raw } - -func (r *FineTuningJobHyperparametersNEpochsUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The current status of the fine-tuning job, which can be either -// `validating_files`, `queued`, `running`, `succeeded`, `failed`, or `cancelled`. -type FineTuningJobStatus string - -const ( - FineTuningJobStatusValidatingFiles FineTuningJobStatus = "validating_files" - FineTuningJobStatusQueued FineTuningJobStatus = "queued" - FineTuningJobStatusRunning FineTuningJobStatus = "running" - FineTuningJobStatusSucceeded FineTuningJobStatus = "succeeded" - FineTuningJobStatusFailed FineTuningJobStatus = "failed" - FineTuningJobStatusCancelled FineTuningJobStatus = "cancelled" -) - -// The method used for fine-tuning. -type FineTuningJobMethod struct { - // The type of method. Is either `supervised`, `dpo`, or `reinforcement`. - // - // Any of "supervised", "dpo", "reinforcement". - Type string `json:"type,required"` - // Configuration for the DPO fine-tuning method. - Dpo DpoMethod `json:"dpo"` - // Configuration for the reinforcement fine-tuning method. - Reinforcement ReinforcementMethod `json:"reinforcement"` - // Configuration for the supervised fine-tuning method. - Supervised SupervisedMethod `json:"supervised"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Type respjson.Field - Dpo respjson.Field - Reinforcement respjson.Field - Supervised respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r FineTuningJobMethod) RawJSON() string { return r.JSON.raw } -func (r *FineTuningJobMethod) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Fine-tuning job event object -type FineTuningJobEvent struct { - // The object identifier. - ID string `json:"id,required"` - // The Unix timestamp (in seconds) for when the fine-tuning job was created. - CreatedAt int64 `json:"created_at,required"` - // The log level of the event. - // - // Any of "info", "warn", "error". - Level FineTuningJobEventLevel `json:"level,required"` - // The message of the event. - Message string `json:"message,required"` - // The object type, which is always "fine_tuning.job.event". - Object constant.FineTuningJobEvent `json:"object,required"` - // The data associated with the event. - Data any `json:"data"` - // The type of event. - // - // Any of "message", "metrics". - Type FineTuningJobEventType `json:"type"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ID respjson.Field - CreatedAt respjson.Field - Level respjson.Field - Message respjson.Field - Object respjson.Field - Data respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r FineTuningJobEvent) RawJSON() string { return r.JSON.raw } -func (r *FineTuningJobEvent) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The log level of the event. -type FineTuningJobEventLevel string - -const ( - FineTuningJobEventLevelInfo FineTuningJobEventLevel = "info" - FineTuningJobEventLevelWarn FineTuningJobEventLevel = "warn" - FineTuningJobEventLevelError FineTuningJobEventLevel = "error" -) - -// The type of event. -type FineTuningJobEventType string - -const ( - FineTuningJobEventTypeMessage FineTuningJobEventType = "message" - FineTuningJobEventTypeMetrics FineTuningJobEventType = "metrics" -) - -// 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. -type FineTuningJobWandbIntegration struct { - // The name of the project that the new run will be created under. - Project string `json:"project,required"` - // 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. - Entity string `json:"entity,nullable"` - // A display name to set for the run. If not set, we will use the Job ID as the - // name. - Name string `json:"name,nullable"` - // 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}". - Tags []string `json:"tags"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Project respjson.Field - Entity respjson.Field - Name respjson.Field - Tags respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r FineTuningJobWandbIntegration) RawJSON() string { return r.JSON.raw } -func (r *FineTuningJobWandbIntegration) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type FineTuningJobWandbIntegrationObject struct { - // The type of the integration being enabled for the fine-tuning job - Type constant.Wandb `json:"type,required"` - // 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. - Wandb FineTuningJobWandbIntegration `json:"wandb,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Type respjson.Field - Wandb respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r FineTuningJobWandbIntegrationObject) RawJSON() string { return r.JSON.raw } -func (r *FineTuningJobWandbIntegrationObject) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type FineTuningJobNewParams struct { - // The name of the model to fine-tune. You can select one of the - // [supported models](https://platform.openai.com/docs/guides/fine-tuning#which-models-can-be-fine-tuned). - Model FineTuningJobNewParamsModel `json:"model,omitzero,required"` - // The ID of an uploaded file that contains training data. - // - // See [upload file](https://platform.openai.com/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`. - // - // The contents of the file should differ depending on if the model uses the - // [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input), - // [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input) - // format, or if the fine-tuning method uses the - // [preference](https://platform.openai.com/docs/api-reference/fine-tuning/preference-input) - // format. - // - // See the - // [fine-tuning guide](https://platform.openai.com/docs/guides/model-optimization) - // for more details. - TrainingFile string `json:"training_file,required"` - // 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. - Seed param.Opt[int64] `json:"seed,omitzero"` - // A string of up to 64 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-4o-mini:openai:custom-model-name:7p4lURel`. - Suffix param.Opt[string] `json:"suffix,omitzero"` - // 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](https://platform.openai.com/docs/guides/model-optimization) - // for more details. - ValidationFile param.Opt[string] `json:"validation_file,omitzero"` - // A list of integrations to enable for your fine-tuning job. - Integrations []FineTuningJobNewParamsIntegration `json:"integrations,omitzero"` - // 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, and - // querying for objects via API or the dashboard. - // - // Keys are strings with a maximum length of 64 characters. Values are strings with - // a maximum length of 512 characters. - Metadata shared.Metadata `json:"metadata,omitzero"` - // The hyperparameters used for the fine-tuning job. This value is now deprecated - // in favor of `method`, and should be passed in under the `method` parameter. - Hyperparameters FineTuningJobNewParamsHyperparameters `json:"hyperparameters,omitzero"` - // The method used for fine-tuning. - Method FineTuningJobNewParamsMethod `json:"method,omitzero"` - paramObj -} - -func (r FineTuningJobNewParams) MarshalJSON() (data []byte, err error) { - type shadow FineTuningJobNewParams - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *FineTuningJobNewParams) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The name of the model to fine-tune. You can select one of the -// [supported models](https://platform.openai.com/docs/guides/fine-tuning#which-models-can-be-fine-tuned). -type FineTuningJobNewParamsModel string - -const ( - FineTuningJobNewParamsModelBabbage002 FineTuningJobNewParamsModel = "babbage-002" - FineTuningJobNewParamsModelDavinci002 FineTuningJobNewParamsModel = "davinci-002" - FineTuningJobNewParamsModelGPT3_5Turbo FineTuningJobNewParamsModel = "gpt-3.5-turbo" - FineTuningJobNewParamsModelGPT4oMini FineTuningJobNewParamsModel = "gpt-4o-mini" -) - -// The hyperparameters used for the fine-tuning job. This value is now deprecated -// in favor of `method`, and should be passed in under the `method` parameter. -// -// Deprecated: deprecated -type FineTuningJobNewParamsHyperparameters struct { - // Number of examples in each batch. A larger batch size means that model - // parameters are updated less frequently, but with lower variance. - BatchSize FineTuningJobNewParamsHyperparametersBatchSizeUnion `json:"batch_size,omitzero"` - // Scaling factor for the learning rate. A smaller learning rate may be useful to - // avoid overfitting. - LearningRateMultiplier FineTuningJobNewParamsHyperparametersLearningRateMultiplierUnion `json:"learning_rate_multiplier,omitzero"` - // The number of epochs to train the model for. An epoch refers to one full cycle - // through the training dataset. - NEpochs FineTuningJobNewParamsHyperparametersNEpochsUnion `json:"n_epochs,omitzero"` - paramObj -} - -func (r FineTuningJobNewParamsHyperparameters) MarshalJSON() (data []byte, err error) { - type shadow FineTuningJobNewParamsHyperparameters - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *FineTuningJobNewParamsHyperparameters) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type FineTuningJobNewParamsHyperparametersBatchSizeUnion struct { - // Construct this variant with constant.ValueOf[constant.Auto]() - OfAuto constant.Auto `json:",omitzero,inline"` - OfInt param.Opt[int64] `json:",omitzero,inline"` - paramUnion -} - -func (u FineTuningJobNewParamsHyperparametersBatchSizeUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfAuto, u.OfInt) -} -func (u *FineTuningJobNewParamsHyperparametersBatchSizeUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *FineTuningJobNewParamsHyperparametersBatchSizeUnion) asAny() any { - if !param.IsOmitted(u.OfAuto) { - return &u.OfAuto - } else if !param.IsOmitted(u.OfInt) { - return &u.OfInt.Value - } - return nil -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type FineTuningJobNewParamsHyperparametersLearningRateMultiplierUnion struct { - // Construct this variant with constant.ValueOf[constant.Auto]() - OfAuto constant.Auto `json:",omitzero,inline"` - OfFloat param.Opt[float64] `json:",omitzero,inline"` - paramUnion -} - -func (u FineTuningJobNewParamsHyperparametersLearningRateMultiplierUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfAuto, u.OfFloat) -} -func (u *FineTuningJobNewParamsHyperparametersLearningRateMultiplierUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *FineTuningJobNewParamsHyperparametersLearningRateMultiplierUnion) asAny() any { - if !param.IsOmitted(u.OfAuto) { - return &u.OfAuto - } else if !param.IsOmitted(u.OfFloat) { - return &u.OfFloat.Value - } - return nil -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type FineTuningJobNewParamsHyperparametersNEpochsUnion struct { - // Construct this variant with constant.ValueOf[constant.Auto]() - OfAuto constant.Auto `json:",omitzero,inline"` - OfInt param.Opt[int64] `json:",omitzero,inline"` - paramUnion -} - -func (u FineTuningJobNewParamsHyperparametersNEpochsUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfAuto, u.OfInt) -} -func (u *FineTuningJobNewParamsHyperparametersNEpochsUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *FineTuningJobNewParamsHyperparametersNEpochsUnion) asAny() any { - if !param.IsOmitted(u.OfAuto) { - return &u.OfAuto - } else if !param.IsOmitted(u.OfInt) { - return &u.OfInt.Value - } - return nil -} - -// The properties Type, Wandb are required. -type FineTuningJobNewParamsIntegration struct { - // 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. - Wandb FineTuningJobNewParamsIntegrationWandb `json:"wandb,omitzero,required"` - // The type of integration to enable. Currently, only "wandb" (Weights and Biases) - // is supported. - // - // This field can be elided, and will marshal its zero value as "wandb". - Type constant.Wandb `json:"type,required"` - paramObj -} - -func (r FineTuningJobNewParamsIntegration) MarshalJSON() (data []byte, err error) { - type shadow FineTuningJobNewParamsIntegration - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *FineTuningJobNewParamsIntegration) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// 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. -// -// The property Project is required. -type FineTuningJobNewParamsIntegrationWandb struct { - // The name of the project that the new run will be created under. - Project string `json:"project,required"` - // 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. - Entity param.Opt[string] `json:"entity,omitzero"` - // A display name to set for the run. If not set, we will use the Job ID as the - // name. - Name param.Opt[string] `json:"name,omitzero"` - // 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}". - Tags []string `json:"tags,omitzero"` - paramObj -} - -func (r FineTuningJobNewParamsIntegrationWandb) MarshalJSON() (data []byte, err error) { - type shadow FineTuningJobNewParamsIntegrationWandb - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *FineTuningJobNewParamsIntegrationWandb) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The method used for fine-tuning. -// -// The property Type is required. -type FineTuningJobNewParamsMethod struct { - // The type of method. Is either `supervised`, `dpo`, or `reinforcement`. - // - // Any of "supervised", "dpo", "reinforcement". - Type string `json:"type,omitzero,required"` - // Configuration for the DPO fine-tuning method. - Dpo DpoMethodParam `json:"dpo,omitzero"` - // Configuration for the reinforcement fine-tuning method. - Reinforcement ReinforcementMethodParam `json:"reinforcement,omitzero"` - // Configuration for the supervised fine-tuning method. - Supervised SupervisedMethodParam `json:"supervised,omitzero"` - paramObj -} - -func (r FineTuningJobNewParamsMethod) MarshalJSON() (data []byte, err error) { - type shadow FineTuningJobNewParamsMethod - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *FineTuningJobNewParamsMethod) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -func init() { - apijson.RegisterFieldValidator[FineTuningJobNewParamsMethod]( - "type", "supervised", "dpo", "reinforcement", - ) -} - -type FineTuningJobListParams struct { - // Identifier for the last job from the previous pagination request. - After param.Opt[string] `query:"after,omitzero" json:"-"` - // Number of fine-tuning jobs to retrieve. - Limit param.Opt[int64] `query:"limit,omitzero" json:"-"` - // Optional metadata filter. To filter, use the syntax `metadata[k]=v`. - // Alternatively, set `metadata=null` to indicate no metadata. - Metadata map[string]string `query:"metadata,omitzero" json:"-"` - paramObj -} - -// URLQuery serializes [FineTuningJobListParams]'s query parameters as -// `url.Values`. -func (r FineTuningJobListParams) URLQuery() (v url.Values, err error) { - return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ - ArrayFormat: apiquery.ArrayQueryFormatBrackets, - NestedFormat: apiquery.NestedQueryFormatBrackets, - }) -} - -type FineTuningJobListEventsParams struct { - // Identifier for the last event from the previous pagination request. - After param.Opt[string] `query:"after,omitzero" json:"-"` - // Number of events to retrieve. - Limit param.Opt[int64] `query:"limit,omitzero" json:"-"` - paramObj -} - -// URLQuery serializes [FineTuningJobListEventsParams]'s query parameters as -// `url.Values`. -func (r FineTuningJobListEventsParams) URLQuery() (v url.Values, err error) { - return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ - ArrayFormat: apiquery.ArrayQueryFormatBrackets, - NestedFormat: apiquery.NestedQueryFormatBrackets, - }) -} diff --git a/vendor/github.com/openai/openai-go/finetuningjobcheckpoint.go b/vendor/github.com/openai/openai-go/finetuningjobcheckpoint.go deleted file mode 100644 index 69ef75da..00000000 --- a/vendor/github.com/openai/openai-go/finetuningjobcheckpoint.go +++ /dev/null @@ -1,149 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -package openai - -import ( - "context" - "errors" - "fmt" - "net/http" - "net/url" - - "github.com/openai/openai-go/internal/apijson" - "github.com/openai/openai-go/internal/apiquery" - "github.com/openai/openai-go/internal/requestconfig" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/packages/pagination" - "github.com/openai/openai-go/packages/param" - "github.com/openai/openai-go/packages/respjson" - "github.com/openai/openai-go/shared/constant" -) - -// FineTuningJobCheckpointService contains methods and other services that help -// with interacting with the openai API. -// -// Note, unlike clients, this service does not read variables from the environment -// automatically. You should not instantiate this service directly, and instead use -// the [NewFineTuningJobCheckpointService] method instead. -type FineTuningJobCheckpointService struct { - Options []option.RequestOption -} - -// NewFineTuningJobCheckpointService generates a new service that applies the given -// options to each request. These options are applied after the parent client's -// options (if there is one), and before any request-specific options. -func NewFineTuningJobCheckpointService(opts ...option.RequestOption) (r FineTuningJobCheckpointService) { - r = FineTuningJobCheckpointService{} - r.Options = opts - return -} - -// List checkpoints for a fine-tuning job. -func (r *FineTuningJobCheckpointService) List(ctx context.Context, fineTuningJobID string, query FineTuningJobCheckpointListParams, opts ...option.RequestOption) (res *pagination.CursorPage[FineTuningJobCheckpoint], err error) { - var raw *http.Response - opts = append(r.Options[:], opts...) - opts = append([]option.RequestOption{option.WithResponseInto(&raw)}, opts...) - if fineTuningJobID == "" { - err = errors.New("missing required fine_tuning_job_id parameter") - return - } - path := fmt.Sprintf("fine_tuning/jobs/%s/checkpoints", fineTuningJobID) - cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, query, &res, opts...) - if err != nil { - return nil, err - } - err = cfg.Execute() - if err != nil { - return nil, err - } - res.SetPageConfig(cfg, raw) - return res, nil -} - -// List checkpoints for a fine-tuning job. -func (r *FineTuningJobCheckpointService) ListAutoPaging(ctx context.Context, fineTuningJobID string, query FineTuningJobCheckpointListParams, opts ...option.RequestOption) *pagination.CursorPageAutoPager[FineTuningJobCheckpoint] { - return pagination.NewCursorPageAutoPager(r.List(ctx, fineTuningJobID, query, opts...)) -} - -// The `fine_tuning.job.checkpoint` object represents a model checkpoint for a -// fine-tuning job that is ready to use. -type FineTuningJobCheckpoint struct { - // The checkpoint identifier, which can be referenced in the API endpoints. - ID string `json:"id,required"` - // The Unix timestamp (in seconds) for when the checkpoint was created. - CreatedAt int64 `json:"created_at,required"` - // The name of the fine-tuned checkpoint model that is created. - FineTunedModelCheckpoint string `json:"fine_tuned_model_checkpoint,required"` - // The name of the fine-tuning job that this checkpoint was created from. - FineTuningJobID string `json:"fine_tuning_job_id,required"` - // Metrics at the step number during the fine-tuning job. - Metrics FineTuningJobCheckpointMetrics `json:"metrics,required"` - // The object type, which is always "fine_tuning.job.checkpoint". - Object constant.FineTuningJobCheckpoint `json:"object,required"` - // The step number that the checkpoint was created at. - StepNumber int64 `json:"step_number,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ID respjson.Field - CreatedAt respjson.Field - FineTunedModelCheckpoint respjson.Field - FineTuningJobID respjson.Field - Metrics respjson.Field - Object respjson.Field - StepNumber respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r FineTuningJobCheckpoint) RawJSON() string { return r.JSON.raw } -func (r *FineTuningJobCheckpoint) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Metrics at the step number during the fine-tuning job. -type FineTuningJobCheckpointMetrics struct { - FullValidLoss float64 `json:"full_valid_loss"` - FullValidMeanTokenAccuracy float64 `json:"full_valid_mean_token_accuracy"` - Step float64 `json:"step"` - TrainLoss float64 `json:"train_loss"` - TrainMeanTokenAccuracy float64 `json:"train_mean_token_accuracy"` - ValidLoss float64 `json:"valid_loss"` - ValidMeanTokenAccuracy float64 `json:"valid_mean_token_accuracy"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - FullValidLoss respjson.Field - FullValidMeanTokenAccuracy respjson.Field - Step respjson.Field - TrainLoss respjson.Field - TrainMeanTokenAccuracy respjson.Field - ValidLoss respjson.Field - ValidMeanTokenAccuracy respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r FineTuningJobCheckpointMetrics) RawJSON() string { return r.JSON.raw } -func (r *FineTuningJobCheckpointMetrics) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type FineTuningJobCheckpointListParams struct { - // Identifier for the last checkpoint ID from the previous pagination request. - After param.Opt[string] `query:"after,omitzero" json:"-"` - // Number of checkpoints to retrieve. - Limit param.Opt[int64] `query:"limit,omitzero" json:"-"` - paramObj -} - -// URLQuery serializes [FineTuningJobCheckpointListParams]'s query parameters as -// `url.Values`. -func (r FineTuningJobCheckpointListParams) URLQuery() (v url.Values, err error) { - return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{ - ArrayFormat: apiquery.ArrayQueryFormatBrackets, - NestedFormat: apiquery.NestedQueryFormatBrackets, - }) -} diff --git a/vendor/github.com/openai/openai-go/finetuningmethod.go b/vendor/github.com/openai/openai-go/finetuningmethod.go deleted file mode 100644 index b315a9dc..00000000 --- a/vendor/github.com/openai/openai-go/finetuningmethod.go +++ /dev/null @@ -1,1487 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -package openai - -import ( - "encoding/json" - - "github.com/openai/openai-go/internal/apijson" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/packages/param" - "github.com/openai/openai-go/packages/respjson" - "github.com/openai/openai-go/shared/constant" -) - -// FineTuningMethodService contains methods and other services that help with -// interacting with the openai API. -// -// Note, unlike clients, this service does not read variables from the environment -// automatically. You should not instantiate this service directly, and instead use -// the [NewFineTuningMethodService] method instead. -type FineTuningMethodService struct { - Options []option.RequestOption -} - -// NewFineTuningMethodService generates a new service that applies the given -// options to each request. These options are applied after the parent client's -// options (if there is one), and before any request-specific options. -func NewFineTuningMethodService(opts ...option.RequestOption) (r FineTuningMethodService) { - r = FineTuningMethodService{} - r.Options = opts - return -} - -// The hyperparameters used for the DPO fine-tuning job. -type DpoHyperparametersResp struct { - // Number of examples in each batch. A larger batch size means that model - // parameters are updated less frequently, but with lower variance. - BatchSize DpoHyperparametersBatchSizeUnionResp `json:"batch_size"` - // The beta value for the DPO method. A higher beta value will increase the weight - // of the penalty between the policy and reference model. - Beta DpoHyperparametersBetaUnionResp `json:"beta"` - // Scaling factor for the learning rate. A smaller learning rate may be useful to - // avoid overfitting. - LearningRateMultiplier DpoHyperparametersLearningRateMultiplierUnionResp `json:"learning_rate_multiplier"` - // The number of epochs to train the model for. An epoch refers to one full cycle - // through the training dataset. - NEpochs DpoHyperparametersNEpochsUnionResp `json:"n_epochs"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - BatchSize respjson.Field - Beta respjson.Field - LearningRateMultiplier respjson.Field - NEpochs respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r DpoHyperparametersResp) RawJSON() string { return r.JSON.raw } -func (r *DpoHyperparametersResp) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// ToParam converts this DpoHyperparametersResp to a DpoHyperparameters. -// -// Warning: the fields of the param type will not be present. ToParam should only -// be used at the last possible moment before sending a request. Test for this with -// DpoHyperparameters.Overrides() -func (r DpoHyperparametersResp) ToParam() DpoHyperparameters { - return param.Override[DpoHyperparameters](json.RawMessage(r.RawJSON())) -} - -// DpoHyperparametersBatchSizeUnionResp contains all possible properties and values -// from [constant.Auto], [int64]. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -// -// If the underlying value is not a json object, one of the following properties -// will be valid: OfAuto OfInt] -type DpoHyperparametersBatchSizeUnionResp struct { - // This field will be present if the value is a [constant.Auto] instead of an - // object. - OfAuto constant.Auto `json:",inline"` - // This field will be present if the value is a [int64] instead of an object. - OfInt int64 `json:",inline"` - JSON struct { - OfAuto respjson.Field - OfInt respjson.Field - raw string - } `json:"-"` -} - -func (u DpoHyperparametersBatchSizeUnionResp) AsAuto() (v constant.Auto) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u DpoHyperparametersBatchSizeUnionResp) AsInt() (v int64) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -// Returns the unmodified JSON received from the API -func (u DpoHyperparametersBatchSizeUnionResp) RawJSON() string { return u.JSON.raw } - -func (r *DpoHyperparametersBatchSizeUnionResp) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// DpoHyperparametersBetaUnionResp contains all possible properties and values from -// [constant.Auto], [float64]. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -// -// If the underlying value is not a json object, one of the following properties -// will be valid: OfAuto OfFloat] -type DpoHyperparametersBetaUnionResp struct { - // This field will be present if the value is a [constant.Auto] instead of an - // object. - OfAuto constant.Auto `json:",inline"` - // This field will be present if the value is a [float64] instead of an object. - OfFloat float64 `json:",inline"` - JSON struct { - OfAuto respjson.Field - OfFloat respjson.Field - raw string - } `json:"-"` -} - -func (u DpoHyperparametersBetaUnionResp) AsAuto() (v constant.Auto) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u DpoHyperparametersBetaUnionResp) AsFloat() (v float64) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -// Returns the unmodified JSON received from the API -func (u DpoHyperparametersBetaUnionResp) RawJSON() string { return u.JSON.raw } - -func (r *DpoHyperparametersBetaUnionResp) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// DpoHyperparametersLearningRateMultiplierUnionResp contains all possible -// properties and values from [constant.Auto], [float64]. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -// -// If the underlying value is not a json object, one of the following properties -// will be valid: OfAuto OfFloat] -type DpoHyperparametersLearningRateMultiplierUnionResp struct { - // This field will be present if the value is a [constant.Auto] instead of an - // object. - OfAuto constant.Auto `json:",inline"` - // This field will be present if the value is a [float64] instead of an object. - OfFloat float64 `json:",inline"` - JSON struct { - OfAuto respjson.Field - OfFloat respjson.Field - raw string - } `json:"-"` -} - -func (u DpoHyperparametersLearningRateMultiplierUnionResp) AsAuto() (v constant.Auto) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u DpoHyperparametersLearningRateMultiplierUnionResp) AsFloat() (v float64) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -// Returns the unmodified JSON received from the API -func (u DpoHyperparametersLearningRateMultiplierUnionResp) RawJSON() string { return u.JSON.raw } - -func (r *DpoHyperparametersLearningRateMultiplierUnionResp) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// DpoHyperparametersNEpochsUnionResp contains all possible properties and values -// from [constant.Auto], [int64]. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -// -// If the underlying value is not a json object, one of the following properties -// will be valid: OfAuto OfInt] -type DpoHyperparametersNEpochsUnionResp struct { - // This field will be present if the value is a [constant.Auto] instead of an - // object. - OfAuto constant.Auto `json:",inline"` - // This field will be present if the value is a [int64] instead of an object. - OfInt int64 `json:",inline"` - JSON struct { - OfAuto respjson.Field - OfInt respjson.Field - raw string - } `json:"-"` -} - -func (u DpoHyperparametersNEpochsUnionResp) AsAuto() (v constant.Auto) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u DpoHyperparametersNEpochsUnionResp) AsInt() (v int64) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -// Returns the unmodified JSON received from the API -func (u DpoHyperparametersNEpochsUnionResp) RawJSON() string { return u.JSON.raw } - -func (r *DpoHyperparametersNEpochsUnionResp) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The hyperparameters used for the DPO fine-tuning job. -type DpoHyperparameters struct { - // Number of examples in each batch. A larger batch size means that model - // parameters are updated less frequently, but with lower variance. - BatchSize DpoHyperparametersBatchSizeUnion `json:"batch_size,omitzero"` - // The beta value for the DPO method. A higher beta value will increase the weight - // of the penalty between the policy and reference model. - Beta DpoHyperparametersBetaUnion `json:"beta,omitzero"` - // Scaling factor for the learning rate. A smaller learning rate may be useful to - // avoid overfitting. - LearningRateMultiplier DpoHyperparametersLearningRateMultiplierUnion `json:"learning_rate_multiplier,omitzero"` - // The number of epochs to train the model for. An epoch refers to one full cycle - // through the training dataset. - NEpochs DpoHyperparametersNEpochsUnion `json:"n_epochs,omitzero"` - paramObj -} - -func (r DpoHyperparameters) MarshalJSON() (data []byte, err error) { - type shadow DpoHyperparameters - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *DpoHyperparameters) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type DpoHyperparametersBatchSizeUnion struct { - // Construct this variant with constant.ValueOf[constant.Auto]() - OfAuto constant.Auto `json:",omitzero,inline"` - OfInt param.Opt[int64] `json:",omitzero,inline"` - paramUnion -} - -func (u DpoHyperparametersBatchSizeUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfAuto, u.OfInt) -} -func (u *DpoHyperparametersBatchSizeUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *DpoHyperparametersBatchSizeUnion) asAny() any { - if !param.IsOmitted(u.OfAuto) { - return &u.OfAuto - } else if !param.IsOmitted(u.OfInt) { - return &u.OfInt.Value - } - return nil -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type DpoHyperparametersBetaUnion struct { - // Construct this variant with constant.ValueOf[constant.Auto]() - OfAuto constant.Auto `json:",omitzero,inline"` - OfFloat param.Opt[float64] `json:",omitzero,inline"` - paramUnion -} - -func (u DpoHyperparametersBetaUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfAuto, u.OfFloat) -} -func (u *DpoHyperparametersBetaUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *DpoHyperparametersBetaUnion) asAny() any { - if !param.IsOmitted(u.OfAuto) { - return &u.OfAuto - } else if !param.IsOmitted(u.OfFloat) { - return &u.OfFloat.Value - } - return nil -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type DpoHyperparametersLearningRateMultiplierUnion struct { - // Construct this variant with constant.ValueOf[constant.Auto]() - OfAuto constant.Auto `json:",omitzero,inline"` - OfFloat param.Opt[float64] `json:",omitzero,inline"` - paramUnion -} - -func (u DpoHyperparametersLearningRateMultiplierUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfAuto, u.OfFloat) -} -func (u *DpoHyperparametersLearningRateMultiplierUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *DpoHyperparametersLearningRateMultiplierUnion) asAny() any { - if !param.IsOmitted(u.OfAuto) { - return &u.OfAuto - } else if !param.IsOmitted(u.OfFloat) { - return &u.OfFloat.Value - } - return nil -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type DpoHyperparametersNEpochsUnion struct { - // Construct this variant with constant.ValueOf[constant.Auto]() - OfAuto constant.Auto `json:",omitzero,inline"` - OfInt param.Opt[int64] `json:",omitzero,inline"` - paramUnion -} - -func (u DpoHyperparametersNEpochsUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfAuto, u.OfInt) -} -func (u *DpoHyperparametersNEpochsUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *DpoHyperparametersNEpochsUnion) asAny() any { - if !param.IsOmitted(u.OfAuto) { - return &u.OfAuto - } else if !param.IsOmitted(u.OfInt) { - return &u.OfInt.Value - } - return nil -} - -// Configuration for the DPO fine-tuning method. -type DpoMethod struct { - // The hyperparameters used for the DPO fine-tuning job. - Hyperparameters DpoHyperparametersResp `json:"hyperparameters"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Hyperparameters respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r DpoMethod) RawJSON() string { return r.JSON.raw } -func (r *DpoMethod) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// ToParam converts this DpoMethod to a DpoMethodParam. -// -// Warning: the fields of the param type will not be present. ToParam should only -// be used at the last possible moment before sending a request. Test for this with -// DpoMethodParam.Overrides() -func (r DpoMethod) ToParam() DpoMethodParam { - return param.Override[DpoMethodParam](json.RawMessage(r.RawJSON())) -} - -// Configuration for the DPO fine-tuning method. -type DpoMethodParam struct { - // The hyperparameters used for the DPO fine-tuning job. - Hyperparameters DpoHyperparameters `json:"hyperparameters,omitzero"` - paramObj -} - -func (r DpoMethodParam) MarshalJSON() (data []byte, err error) { - type shadow DpoMethodParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *DpoMethodParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The hyperparameters used for the reinforcement fine-tuning job. -type ReinforcementHyperparametersResp struct { - // Number of examples in each batch. A larger batch size means that model - // parameters are updated less frequently, but with lower variance. - BatchSize ReinforcementHyperparametersBatchSizeUnionResp `json:"batch_size"` - // Multiplier on amount of compute used for exploring search space during training. - ComputeMultiplier ReinforcementHyperparametersComputeMultiplierUnionResp `json:"compute_multiplier"` - // The number of training steps between evaluation runs. - EvalInterval ReinforcementHyperparametersEvalIntervalUnionResp `json:"eval_interval"` - // Number of evaluation samples to generate per training step. - EvalSamples ReinforcementHyperparametersEvalSamplesUnionResp `json:"eval_samples"` - // Scaling factor for the learning rate. A smaller learning rate may be useful to - // avoid overfitting. - LearningRateMultiplier ReinforcementHyperparametersLearningRateMultiplierUnionResp `json:"learning_rate_multiplier"` - // The number of epochs to train the model for. An epoch refers to one full cycle - // through the training dataset. - NEpochs ReinforcementHyperparametersNEpochsUnionResp `json:"n_epochs"` - // Level of reasoning effort. - // - // Any of "default", "low", "medium", "high". - ReasoningEffort ReinforcementHyperparametersReasoningEffort `json:"reasoning_effort"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - BatchSize respjson.Field - ComputeMultiplier respjson.Field - EvalInterval respjson.Field - EvalSamples respjson.Field - LearningRateMultiplier respjson.Field - NEpochs respjson.Field - ReasoningEffort respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ReinforcementHyperparametersResp) RawJSON() string { return r.JSON.raw } -func (r *ReinforcementHyperparametersResp) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// ToParam converts this ReinforcementHyperparametersResp to a -// ReinforcementHyperparameters. -// -// Warning: the fields of the param type will not be present. ToParam should only -// be used at the last possible moment before sending a request. Test for this with -// ReinforcementHyperparameters.Overrides() -func (r ReinforcementHyperparametersResp) ToParam() ReinforcementHyperparameters { - return param.Override[ReinforcementHyperparameters](json.RawMessage(r.RawJSON())) -} - -// ReinforcementHyperparametersBatchSizeUnionResp contains all possible properties -// and values from [constant.Auto], [int64]. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -// -// If the underlying value is not a json object, one of the following properties -// will be valid: OfAuto OfInt] -type ReinforcementHyperparametersBatchSizeUnionResp struct { - // This field will be present if the value is a [constant.Auto] instead of an - // object. - OfAuto constant.Auto `json:",inline"` - // This field will be present if the value is a [int64] instead of an object. - OfInt int64 `json:",inline"` - JSON struct { - OfAuto respjson.Field - OfInt respjson.Field - raw string - } `json:"-"` -} - -func (u ReinforcementHyperparametersBatchSizeUnionResp) AsAuto() (v constant.Auto) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u ReinforcementHyperparametersBatchSizeUnionResp) AsInt() (v int64) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -// Returns the unmodified JSON received from the API -func (u ReinforcementHyperparametersBatchSizeUnionResp) RawJSON() string { return u.JSON.raw } - -func (r *ReinforcementHyperparametersBatchSizeUnionResp) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// ReinforcementHyperparametersComputeMultiplierUnionResp contains all possible -// properties and values from [constant.Auto], [float64]. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -// -// If the underlying value is not a json object, one of the following properties -// will be valid: OfAuto OfFloat] -type ReinforcementHyperparametersComputeMultiplierUnionResp struct { - // This field will be present if the value is a [constant.Auto] instead of an - // object. - OfAuto constant.Auto `json:",inline"` - // This field will be present if the value is a [float64] instead of an object. - OfFloat float64 `json:",inline"` - JSON struct { - OfAuto respjson.Field - OfFloat respjson.Field - raw string - } `json:"-"` -} - -func (u ReinforcementHyperparametersComputeMultiplierUnionResp) AsAuto() (v constant.Auto) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u ReinforcementHyperparametersComputeMultiplierUnionResp) AsFloat() (v float64) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -// Returns the unmodified JSON received from the API -func (u ReinforcementHyperparametersComputeMultiplierUnionResp) RawJSON() string { return u.JSON.raw } - -func (r *ReinforcementHyperparametersComputeMultiplierUnionResp) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// ReinforcementHyperparametersEvalIntervalUnionResp contains all possible -// properties and values from [constant.Auto], [int64]. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -// -// If the underlying value is not a json object, one of the following properties -// will be valid: OfAuto OfInt] -type ReinforcementHyperparametersEvalIntervalUnionResp struct { - // This field will be present if the value is a [constant.Auto] instead of an - // object. - OfAuto constant.Auto `json:",inline"` - // This field will be present if the value is a [int64] instead of an object. - OfInt int64 `json:",inline"` - JSON struct { - OfAuto respjson.Field - OfInt respjson.Field - raw string - } `json:"-"` -} - -func (u ReinforcementHyperparametersEvalIntervalUnionResp) AsAuto() (v constant.Auto) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u ReinforcementHyperparametersEvalIntervalUnionResp) AsInt() (v int64) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -// Returns the unmodified JSON received from the API -func (u ReinforcementHyperparametersEvalIntervalUnionResp) RawJSON() string { return u.JSON.raw } - -func (r *ReinforcementHyperparametersEvalIntervalUnionResp) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// ReinforcementHyperparametersEvalSamplesUnionResp contains all possible -// properties and values from [constant.Auto], [int64]. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -// -// If the underlying value is not a json object, one of the following properties -// will be valid: OfAuto OfInt] -type ReinforcementHyperparametersEvalSamplesUnionResp struct { - // This field will be present if the value is a [constant.Auto] instead of an - // object. - OfAuto constant.Auto `json:",inline"` - // This field will be present if the value is a [int64] instead of an object. - OfInt int64 `json:",inline"` - JSON struct { - OfAuto respjson.Field - OfInt respjson.Field - raw string - } `json:"-"` -} - -func (u ReinforcementHyperparametersEvalSamplesUnionResp) AsAuto() (v constant.Auto) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u ReinforcementHyperparametersEvalSamplesUnionResp) AsInt() (v int64) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -// Returns the unmodified JSON received from the API -func (u ReinforcementHyperparametersEvalSamplesUnionResp) RawJSON() string { return u.JSON.raw } - -func (r *ReinforcementHyperparametersEvalSamplesUnionResp) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// ReinforcementHyperparametersLearningRateMultiplierUnionResp contains all -// possible properties and values from [constant.Auto], [float64]. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -// -// If the underlying value is not a json object, one of the following properties -// will be valid: OfAuto OfFloat] -type ReinforcementHyperparametersLearningRateMultiplierUnionResp struct { - // This field will be present if the value is a [constant.Auto] instead of an - // object. - OfAuto constant.Auto `json:",inline"` - // This field will be present if the value is a [float64] instead of an object. - OfFloat float64 `json:",inline"` - JSON struct { - OfAuto respjson.Field - OfFloat respjson.Field - raw string - } `json:"-"` -} - -func (u ReinforcementHyperparametersLearningRateMultiplierUnionResp) AsAuto() (v constant.Auto) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u ReinforcementHyperparametersLearningRateMultiplierUnionResp) AsFloat() (v float64) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -// Returns the unmodified JSON received from the API -func (u ReinforcementHyperparametersLearningRateMultiplierUnionResp) RawJSON() string { - return u.JSON.raw -} - -func (r *ReinforcementHyperparametersLearningRateMultiplierUnionResp) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// ReinforcementHyperparametersNEpochsUnionResp contains all possible properties -// and values from [constant.Auto], [int64]. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -// -// If the underlying value is not a json object, one of the following properties -// will be valid: OfAuto OfInt] -type ReinforcementHyperparametersNEpochsUnionResp struct { - // This field will be present if the value is a [constant.Auto] instead of an - // object. - OfAuto constant.Auto `json:",inline"` - // This field will be present if the value is a [int64] instead of an object. - OfInt int64 `json:",inline"` - JSON struct { - OfAuto respjson.Field - OfInt respjson.Field - raw string - } `json:"-"` -} - -func (u ReinforcementHyperparametersNEpochsUnionResp) AsAuto() (v constant.Auto) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u ReinforcementHyperparametersNEpochsUnionResp) AsInt() (v int64) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -// Returns the unmodified JSON received from the API -func (u ReinforcementHyperparametersNEpochsUnionResp) RawJSON() string { return u.JSON.raw } - -func (r *ReinforcementHyperparametersNEpochsUnionResp) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Level of reasoning effort. -type ReinforcementHyperparametersReasoningEffort string - -const ( - ReinforcementHyperparametersReasoningEffortDefault ReinforcementHyperparametersReasoningEffort = "default" - ReinforcementHyperparametersReasoningEffortLow ReinforcementHyperparametersReasoningEffort = "low" - ReinforcementHyperparametersReasoningEffortMedium ReinforcementHyperparametersReasoningEffort = "medium" - ReinforcementHyperparametersReasoningEffortHigh ReinforcementHyperparametersReasoningEffort = "high" -) - -// The hyperparameters used for the reinforcement fine-tuning job. -type ReinforcementHyperparameters struct { - // Number of examples in each batch. A larger batch size means that model - // parameters are updated less frequently, but with lower variance. - BatchSize ReinforcementHyperparametersBatchSizeUnion `json:"batch_size,omitzero"` - // Multiplier on amount of compute used for exploring search space during training. - ComputeMultiplier ReinforcementHyperparametersComputeMultiplierUnion `json:"compute_multiplier,omitzero"` - // The number of training steps between evaluation runs. - EvalInterval ReinforcementHyperparametersEvalIntervalUnion `json:"eval_interval,omitzero"` - // Number of evaluation samples to generate per training step. - EvalSamples ReinforcementHyperparametersEvalSamplesUnion `json:"eval_samples,omitzero"` - // Scaling factor for the learning rate. A smaller learning rate may be useful to - // avoid overfitting. - LearningRateMultiplier ReinforcementHyperparametersLearningRateMultiplierUnion `json:"learning_rate_multiplier,omitzero"` - // The number of epochs to train the model for. An epoch refers to one full cycle - // through the training dataset. - NEpochs ReinforcementHyperparametersNEpochsUnion `json:"n_epochs,omitzero"` - // Level of reasoning effort. - // - // Any of "default", "low", "medium", "high". - ReasoningEffort ReinforcementHyperparametersReasoningEffort `json:"reasoning_effort,omitzero"` - paramObj -} - -func (r ReinforcementHyperparameters) MarshalJSON() (data []byte, err error) { - type shadow ReinforcementHyperparameters - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ReinforcementHyperparameters) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type ReinforcementHyperparametersBatchSizeUnion struct { - // Construct this variant with constant.ValueOf[constant.Auto]() - OfAuto constant.Auto `json:",omitzero,inline"` - OfInt param.Opt[int64] `json:",omitzero,inline"` - paramUnion -} - -func (u ReinforcementHyperparametersBatchSizeUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfAuto, u.OfInt) -} -func (u *ReinforcementHyperparametersBatchSizeUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *ReinforcementHyperparametersBatchSizeUnion) asAny() any { - if !param.IsOmitted(u.OfAuto) { - return &u.OfAuto - } else if !param.IsOmitted(u.OfInt) { - return &u.OfInt.Value - } - return nil -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type ReinforcementHyperparametersComputeMultiplierUnion struct { - // Construct this variant with constant.ValueOf[constant.Auto]() - OfAuto constant.Auto `json:",omitzero,inline"` - OfFloat param.Opt[float64] `json:",omitzero,inline"` - paramUnion -} - -func (u ReinforcementHyperparametersComputeMultiplierUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfAuto, u.OfFloat) -} -func (u *ReinforcementHyperparametersComputeMultiplierUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *ReinforcementHyperparametersComputeMultiplierUnion) asAny() any { - if !param.IsOmitted(u.OfAuto) { - return &u.OfAuto - } else if !param.IsOmitted(u.OfFloat) { - return &u.OfFloat.Value - } - return nil -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type ReinforcementHyperparametersEvalIntervalUnion struct { - // Construct this variant with constant.ValueOf[constant.Auto]() - OfAuto constant.Auto `json:",omitzero,inline"` - OfInt param.Opt[int64] `json:",omitzero,inline"` - paramUnion -} - -func (u ReinforcementHyperparametersEvalIntervalUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfAuto, u.OfInt) -} -func (u *ReinforcementHyperparametersEvalIntervalUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *ReinforcementHyperparametersEvalIntervalUnion) asAny() any { - if !param.IsOmitted(u.OfAuto) { - return &u.OfAuto - } else if !param.IsOmitted(u.OfInt) { - return &u.OfInt.Value - } - return nil -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type ReinforcementHyperparametersEvalSamplesUnion struct { - // Construct this variant with constant.ValueOf[constant.Auto]() - OfAuto constant.Auto `json:",omitzero,inline"` - OfInt param.Opt[int64] `json:",omitzero,inline"` - paramUnion -} - -func (u ReinforcementHyperparametersEvalSamplesUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfAuto, u.OfInt) -} -func (u *ReinforcementHyperparametersEvalSamplesUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *ReinforcementHyperparametersEvalSamplesUnion) asAny() any { - if !param.IsOmitted(u.OfAuto) { - return &u.OfAuto - } else if !param.IsOmitted(u.OfInt) { - return &u.OfInt.Value - } - return nil -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type ReinforcementHyperparametersLearningRateMultiplierUnion struct { - // Construct this variant with constant.ValueOf[constant.Auto]() - OfAuto constant.Auto `json:",omitzero,inline"` - OfFloat param.Opt[float64] `json:",omitzero,inline"` - paramUnion -} - -func (u ReinforcementHyperparametersLearningRateMultiplierUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfAuto, u.OfFloat) -} -func (u *ReinforcementHyperparametersLearningRateMultiplierUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *ReinforcementHyperparametersLearningRateMultiplierUnion) asAny() any { - if !param.IsOmitted(u.OfAuto) { - return &u.OfAuto - } else if !param.IsOmitted(u.OfFloat) { - return &u.OfFloat.Value - } - return nil -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type ReinforcementHyperparametersNEpochsUnion struct { - // Construct this variant with constant.ValueOf[constant.Auto]() - OfAuto constant.Auto `json:",omitzero,inline"` - OfInt param.Opt[int64] `json:",omitzero,inline"` - paramUnion -} - -func (u ReinforcementHyperparametersNEpochsUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfAuto, u.OfInt) -} -func (u *ReinforcementHyperparametersNEpochsUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *ReinforcementHyperparametersNEpochsUnion) asAny() any { - if !param.IsOmitted(u.OfAuto) { - return &u.OfAuto - } else if !param.IsOmitted(u.OfInt) { - return &u.OfInt.Value - } - return nil -} - -// Configuration for the reinforcement fine-tuning method. -type ReinforcementMethod struct { - // The grader used for the fine-tuning job. - Grader ReinforcementMethodGraderUnion `json:"grader,required"` - // The hyperparameters used for the reinforcement fine-tuning job. - Hyperparameters ReinforcementHyperparametersResp `json:"hyperparameters"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Grader respjson.Field - Hyperparameters respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ReinforcementMethod) RawJSON() string { return r.JSON.raw } -func (r *ReinforcementMethod) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// ToParam converts this ReinforcementMethod to a ReinforcementMethodParam. -// -// Warning: the fields of the param type will not be present. ToParam should only -// be used at the last possible moment before sending a request. Test for this with -// ReinforcementMethodParam.Overrides() -func (r ReinforcementMethod) ToParam() ReinforcementMethodParam { - return param.Override[ReinforcementMethodParam](json.RawMessage(r.RawJSON())) -} - -// ReinforcementMethodGraderUnion contains all possible properties and values from -// [StringCheckGrader], [TextSimilarityGrader], [PythonGrader], [ScoreModelGrader], -// [MultiGrader]. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -type ReinforcementMethodGraderUnion struct { - // This field is a union of [string], [string], [[]ScoreModelGraderInput] - Input ReinforcementMethodGraderUnionInput `json:"input"` - Name string `json:"name"` - // This field is from variant [StringCheckGrader]. - Operation StringCheckGraderOperation `json:"operation"` - Reference string `json:"reference"` - Type string `json:"type"` - // This field is from variant [TextSimilarityGrader]. - EvaluationMetric TextSimilarityGraderEvaluationMetric `json:"evaluation_metric"` - // This field is from variant [PythonGrader]. - Source string `json:"source"` - // This field is from variant [PythonGrader]. - ImageTag string `json:"image_tag"` - // This field is from variant [ScoreModelGrader]. - Model string `json:"model"` - // This field is from variant [ScoreModelGrader]. - Range []float64 `json:"range"` - // This field is from variant [ScoreModelGrader]. - SamplingParams any `json:"sampling_params"` - // This field is from variant [MultiGrader]. - CalculateOutput string `json:"calculate_output"` - // This field is from variant [MultiGrader]. - Graders MultiGraderGradersUnion `json:"graders"` - JSON struct { - Input respjson.Field - Name respjson.Field - Operation respjson.Field - Reference respjson.Field - Type respjson.Field - EvaluationMetric respjson.Field - Source respjson.Field - ImageTag respjson.Field - Model respjson.Field - Range respjson.Field - SamplingParams respjson.Field - CalculateOutput respjson.Field - Graders respjson.Field - raw string - } `json:"-"` -} - -func (u ReinforcementMethodGraderUnion) AsStringCheckGrader() (v StringCheckGrader) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u ReinforcementMethodGraderUnion) AsTextSimilarityGrader() (v TextSimilarityGrader) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u ReinforcementMethodGraderUnion) AsPythonGrader() (v PythonGrader) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u ReinforcementMethodGraderUnion) AsScoreModelGrader() (v ScoreModelGrader) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u ReinforcementMethodGraderUnion) AsMultiGrader() (v MultiGrader) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -// Returns the unmodified JSON received from the API -func (u ReinforcementMethodGraderUnion) RawJSON() string { return u.JSON.raw } - -func (r *ReinforcementMethodGraderUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// ReinforcementMethodGraderUnionInput is an implicit subunion of -// [ReinforcementMethodGraderUnion]. ReinforcementMethodGraderUnionInput provides -// convenient access to the sub-properties of the union. -// -// For type safety it is recommended to directly use a variant of the -// [ReinforcementMethodGraderUnion]. -// -// If the underlying value is not a json object, one of the following properties -// will be valid: OfString OfScoreModelGraderInputArray] -type ReinforcementMethodGraderUnionInput struct { - // This field will be present if the value is a [string] instead of an object. - OfString string `json:",inline"` - // This field will be present if the value is a [[]ScoreModelGraderInput] instead - // of an object. - OfScoreModelGraderInputArray []ScoreModelGraderInput `json:",inline"` - JSON struct { - OfString respjson.Field - OfScoreModelGraderInputArray respjson.Field - raw string - } `json:"-"` -} - -func (r *ReinforcementMethodGraderUnionInput) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Configuration for the reinforcement fine-tuning method. -// -// The property Grader is required. -type ReinforcementMethodParam struct { - // The grader used for the fine-tuning job. - Grader ReinforcementMethodGraderUnionParam `json:"grader,omitzero,required"` - // The hyperparameters used for the reinforcement fine-tuning job. - Hyperparameters ReinforcementHyperparameters `json:"hyperparameters,omitzero"` - paramObj -} - -func (r ReinforcementMethodParam) MarshalJSON() (data []byte, err error) { - type shadow ReinforcementMethodParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ReinforcementMethodParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type ReinforcementMethodGraderUnionParam struct { - OfStringCheckGrader *StringCheckGraderParam `json:",omitzero,inline"` - OfTextSimilarityGrader *TextSimilarityGraderParam `json:",omitzero,inline"` - OfPythonGrader *PythonGraderParam `json:",omitzero,inline"` - OfScoreModelGrader *ScoreModelGraderParam `json:",omitzero,inline"` - OfMultiGrader *MultiGraderParam `json:",omitzero,inline"` - paramUnion -} - -func (u ReinforcementMethodGraderUnionParam) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfStringCheckGrader, - u.OfTextSimilarityGrader, - u.OfPythonGrader, - u.OfScoreModelGrader, - u.OfMultiGrader) -} -func (u *ReinforcementMethodGraderUnionParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *ReinforcementMethodGraderUnionParam) asAny() any { - if !param.IsOmitted(u.OfStringCheckGrader) { - return u.OfStringCheckGrader - } else if !param.IsOmitted(u.OfTextSimilarityGrader) { - return u.OfTextSimilarityGrader - } else if !param.IsOmitted(u.OfPythonGrader) { - return u.OfPythonGrader - } else if !param.IsOmitted(u.OfScoreModelGrader) { - return u.OfScoreModelGrader - } else if !param.IsOmitted(u.OfMultiGrader) { - return u.OfMultiGrader - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u ReinforcementMethodGraderUnionParam) GetOperation() *string { - if vt := u.OfStringCheckGrader; vt != nil { - return (*string)(&vt.Operation) - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u ReinforcementMethodGraderUnionParam) GetEvaluationMetric() *string { - if vt := u.OfTextSimilarityGrader; vt != nil { - return (*string)(&vt.EvaluationMetric) - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u ReinforcementMethodGraderUnionParam) GetSource() *string { - if vt := u.OfPythonGrader; vt != nil { - return &vt.Source - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u ReinforcementMethodGraderUnionParam) GetImageTag() *string { - if vt := u.OfPythonGrader; vt != nil && vt.ImageTag.Valid() { - return &vt.ImageTag.Value - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u ReinforcementMethodGraderUnionParam) GetModel() *string { - if vt := u.OfScoreModelGrader; vt != nil { - return &vt.Model - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u ReinforcementMethodGraderUnionParam) GetRange() []float64 { - if vt := u.OfScoreModelGrader; vt != nil { - return vt.Range - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u ReinforcementMethodGraderUnionParam) GetSamplingParams() *any { - if vt := u.OfScoreModelGrader; vt != nil { - return &vt.SamplingParams - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u ReinforcementMethodGraderUnionParam) GetCalculateOutput() *string { - if vt := u.OfMultiGrader; vt != nil { - return &vt.CalculateOutput - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u ReinforcementMethodGraderUnionParam) GetGraders() *MultiGraderGradersUnionParam { - if vt := u.OfMultiGrader; vt != nil { - return &vt.Graders - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u ReinforcementMethodGraderUnionParam) GetName() *string { - if vt := u.OfStringCheckGrader; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfTextSimilarityGrader; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfPythonGrader; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfScoreModelGrader; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfMultiGrader; vt != nil { - return (*string)(&vt.Name) - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u ReinforcementMethodGraderUnionParam) GetReference() *string { - if vt := u.OfStringCheckGrader; vt != nil { - return (*string)(&vt.Reference) - } else if vt := u.OfTextSimilarityGrader; vt != nil { - return (*string)(&vt.Reference) - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u ReinforcementMethodGraderUnionParam) GetType() *string { - if vt := u.OfStringCheckGrader; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfTextSimilarityGrader; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfPythonGrader; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfScoreModelGrader; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfMultiGrader; vt != nil { - return (*string)(&vt.Type) - } - return nil -} - -// Returns a subunion which exports methods to access subproperties -// -// Or use AsAny() to get the underlying value -func (u ReinforcementMethodGraderUnionParam) GetInput() (res reinforcementMethodGraderUnionParamInput) { - if vt := u.OfStringCheckGrader; vt != nil { - res.any = &vt.Input - } else if vt := u.OfTextSimilarityGrader; vt != nil { - res.any = &vt.Input - } else if vt := u.OfScoreModelGrader; vt != nil { - res.any = &vt.Input - } - return -} - -// Can have the runtime types [*string], [\*[]ScoreModelGraderInputParam] -type reinforcementMethodGraderUnionParamInput struct{ any } - -// Use the following switch statement to get the type of the union: -// -// switch u.AsAny().(type) { -// case *string: -// case *[]openai.ScoreModelGraderInputParam: -// default: -// fmt.Errorf("not present") -// } -func (u reinforcementMethodGraderUnionParamInput) AsAny() any { return u.any } - -// The hyperparameters used for the fine-tuning job. -type SupervisedHyperparametersResp struct { - // Number of examples in each batch. A larger batch size means that model - // parameters are updated less frequently, but with lower variance. - BatchSize SupervisedHyperparametersBatchSizeUnionResp `json:"batch_size"` - // Scaling factor for the learning rate. A smaller learning rate may be useful to - // avoid overfitting. - LearningRateMultiplier SupervisedHyperparametersLearningRateMultiplierUnionResp `json:"learning_rate_multiplier"` - // The number of epochs to train the model for. An epoch refers to one full cycle - // through the training dataset. - NEpochs SupervisedHyperparametersNEpochsUnionResp `json:"n_epochs"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - BatchSize respjson.Field - LearningRateMultiplier respjson.Field - NEpochs respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r SupervisedHyperparametersResp) RawJSON() string { return r.JSON.raw } -func (r *SupervisedHyperparametersResp) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// ToParam converts this SupervisedHyperparametersResp to a -// SupervisedHyperparameters. -// -// Warning: the fields of the param type will not be present. ToParam should only -// be used at the last possible moment before sending a request. Test for this with -// SupervisedHyperparameters.Overrides() -func (r SupervisedHyperparametersResp) ToParam() SupervisedHyperparameters { - return param.Override[SupervisedHyperparameters](json.RawMessage(r.RawJSON())) -} - -// SupervisedHyperparametersBatchSizeUnionResp contains all possible properties and -// values from [constant.Auto], [int64]. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -// -// If the underlying value is not a json object, one of the following properties -// will be valid: OfAuto OfInt] -type SupervisedHyperparametersBatchSizeUnionResp struct { - // This field will be present if the value is a [constant.Auto] instead of an - // object. - OfAuto constant.Auto `json:",inline"` - // This field will be present if the value is a [int64] instead of an object. - OfInt int64 `json:",inline"` - JSON struct { - OfAuto respjson.Field - OfInt respjson.Field - raw string - } `json:"-"` -} - -func (u SupervisedHyperparametersBatchSizeUnionResp) AsAuto() (v constant.Auto) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u SupervisedHyperparametersBatchSizeUnionResp) AsInt() (v int64) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -// Returns the unmodified JSON received from the API -func (u SupervisedHyperparametersBatchSizeUnionResp) RawJSON() string { return u.JSON.raw } - -func (r *SupervisedHyperparametersBatchSizeUnionResp) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// SupervisedHyperparametersLearningRateMultiplierUnionResp contains all possible -// properties and values from [constant.Auto], [float64]. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -// -// If the underlying value is not a json object, one of the following properties -// will be valid: OfAuto OfFloat] -type SupervisedHyperparametersLearningRateMultiplierUnionResp struct { - // This field will be present if the value is a [constant.Auto] instead of an - // object. - OfAuto constant.Auto `json:",inline"` - // This field will be present if the value is a [float64] instead of an object. - OfFloat float64 `json:",inline"` - JSON struct { - OfAuto respjson.Field - OfFloat respjson.Field - raw string - } `json:"-"` -} - -func (u SupervisedHyperparametersLearningRateMultiplierUnionResp) AsAuto() (v constant.Auto) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u SupervisedHyperparametersLearningRateMultiplierUnionResp) AsFloat() (v float64) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -// Returns the unmodified JSON received from the API -func (u SupervisedHyperparametersLearningRateMultiplierUnionResp) RawJSON() string { return u.JSON.raw } - -func (r *SupervisedHyperparametersLearningRateMultiplierUnionResp) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// SupervisedHyperparametersNEpochsUnionResp contains all possible properties and -// values from [constant.Auto], [int64]. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -// -// If the underlying value is not a json object, one of the following properties -// will be valid: OfAuto OfInt] -type SupervisedHyperparametersNEpochsUnionResp struct { - // This field will be present if the value is a [constant.Auto] instead of an - // object. - OfAuto constant.Auto `json:",inline"` - // This field will be present if the value is a [int64] instead of an object. - OfInt int64 `json:",inline"` - JSON struct { - OfAuto respjson.Field - OfInt respjson.Field - raw string - } `json:"-"` -} - -func (u SupervisedHyperparametersNEpochsUnionResp) AsAuto() (v constant.Auto) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u SupervisedHyperparametersNEpochsUnionResp) AsInt() (v int64) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -// Returns the unmodified JSON received from the API -func (u SupervisedHyperparametersNEpochsUnionResp) RawJSON() string { return u.JSON.raw } - -func (r *SupervisedHyperparametersNEpochsUnionResp) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The hyperparameters used for the fine-tuning job. -type SupervisedHyperparameters struct { - // Number of examples in each batch. A larger batch size means that model - // parameters are updated less frequently, but with lower variance. - BatchSize SupervisedHyperparametersBatchSizeUnion `json:"batch_size,omitzero"` - // Scaling factor for the learning rate. A smaller learning rate may be useful to - // avoid overfitting. - LearningRateMultiplier SupervisedHyperparametersLearningRateMultiplierUnion `json:"learning_rate_multiplier,omitzero"` - // The number of epochs to train the model for. An epoch refers to one full cycle - // through the training dataset. - NEpochs SupervisedHyperparametersNEpochsUnion `json:"n_epochs,omitzero"` - paramObj -} - -func (r SupervisedHyperparameters) MarshalJSON() (data []byte, err error) { - type shadow SupervisedHyperparameters - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *SupervisedHyperparameters) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type SupervisedHyperparametersBatchSizeUnion struct { - // Construct this variant with constant.ValueOf[constant.Auto]() - OfAuto constant.Auto `json:",omitzero,inline"` - OfInt param.Opt[int64] `json:",omitzero,inline"` - paramUnion -} - -func (u SupervisedHyperparametersBatchSizeUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfAuto, u.OfInt) -} -func (u *SupervisedHyperparametersBatchSizeUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *SupervisedHyperparametersBatchSizeUnion) asAny() any { - if !param.IsOmitted(u.OfAuto) { - return &u.OfAuto - } else if !param.IsOmitted(u.OfInt) { - return &u.OfInt.Value - } - return nil -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type SupervisedHyperparametersLearningRateMultiplierUnion struct { - // Construct this variant with constant.ValueOf[constant.Auto]() - OfAuto constant.Auto `json:",omitzero,inline"` - OfFloat param.Opt[float64] `json:",omitzero,inline"` - paramUnion -} - -func (u SupervisedHyperparametersLearningRateMultiplierUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfAuto, u.OfFloat) -} -func (u *SupervisedHyperparametersLearningRateMultiplierUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *SupervisedHyperparametersLearningRateMultiplierUnion) asAny() any { - if !param.IsOmitted(u.OfAuto) { - return &u.OfAuto - } else if !param.IsOmitted(u.OfFloat) { - return &u.OfFloat.Value - } - return nil -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type SupervisedHyperparametersNEpochsUnion struct { - // Construct this variant with constant.ValueOf[constant.Auto]() - OfAuto constant.Auto `json:",omitzero,inline"` - OfInt param.Opt[int64] `json:",omitzero,inline"` - paramUnion -} - -func (u SupervisedHyperparametersNEpochsUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfAuto, u.OfInt) -} -func (u *SupervisedHyperparametersNEpochsUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *SupervisedHyperparametersNEpochsUnion) asAny() any { - if !param.IsOmitted(u.OfAuto) { - return &u.OfAuto - } else if !param.IsOmitted(u.OfInt) { - return &u.OfInt.Value - } - return nil -} - -// Configuration for the supervised fine-tuning method. -type SupervisedMethod struct { - // The hyperparameters used for the fine-tuning job. - Hyperparameters SupervisedHyperparametersResp `json:"hyperparameters"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Hyperparameters respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r SupervisedMethod) RawJSON() string { return r.JSON.raw } -func (r *SupervisedMethod) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// ToParam converts this SupervisedMethod to a SupervisedMethodParam. -// -// Warning: the fields of the param type will not be present. ToParam should only -// be used at the last possible moment before sending a request. Test for this with -// SupervisedMethodParam.Overrides() -func (r SupervisedMethod) ToParam() SupervisedMethodParam { - return param.Override[SupervisedMethodParam](json.RawMessage(r.RawJSON())) -} - -// Configuration for the supervised fine-tuning method. -type SupervisedMethodParam struct { - // The hyperparameters used for the fine-tuning job. - Hyperparameters SupervisedHyperparameters `json:"hyperparameters,omitzero"` - paramObj -} - -func (r SupervisedMethodParam) MarshalJSON() (data []byte, err error) { - type shadow SupervisedMethodParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *SupervisedMethodParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} diff --git a/vendor/github.com/openai/openai-go/grader.go b/vendor/github.com/openai/openai-go/grader.go deleted file mode 100644 index 0a12b450..00000000 --- a/vendor/github.com/openai/openai-go/grader.go +++ /dev/null @@ -1,28 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -package openai - -import ( - "github.com/openai/openai-go/option" -) - -// GraderService contains methods and other services that help with interacting -// with the openai API. -// -// Note, unlike clients, this service does not read variables from the environment -// automatically. You should not instantiate this service directly, and instead use -// the [NewGraderService] method instead. -type GraderService struct { - Options []option.RequestOption - GraderModels GraderGraderModelService -} - -// NewGraderService generates a new service that applies the given options to each -// request. These options are applied after the parent client's options (if there -// is one), and before any request-specific options. -func NewGraderService(opts ...option.RequestOption) (r GraderService) { - r = GraderService{} - r.Options = opts - r.GraderModels = NewGraderGraderModelService(opts...) - return -} diff --git a/vendor/github.com/openai/openai-go/gradergradermodel.go b/vendor/github.com/openai/openai-go/gradergradermodel.go deleted file mode 100644 index 27236a69..00000000 --- a/vendor/github.com/openai/openai-go/gradergradermodel.go +++ /dev/null @@ -1,1373 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -package openai - -import ( - "encoding/json" - - "github.com/openai/openai-go/internal/apijson" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/packages/param" - "github.com/openai/openai-go/packages/respjson" - "github.com/openai/openai-go/responses" - "github.com/openai/openai-go/shared/constant" -) - -// GraderGraderModelService contains methods and other services that help with -// interacting with the openai API. -// -// Note, unlike clients, this service does not read variables from the environment -// automatically. You should not instantiate this service directly, and instead use -// the [NewGraderGraderModelService] method instead. -type GraderGraderModelService struct { - Options []option.RequestOption -} - -// NewGraderGraderModelService generates a new service that applies the given -// options to each request. These options are applied after the parent client's -// options (if there is one), and before any request-specific options. -func NewGraderGraderModelService(opts ...option.RequestOption) (r GraderGraderModelService) { - r = GraderGraderModelService{} - r.Options = opts - return -} - -// A LabelModelGrader object which uses a model to assign labels to each item in -// the evaluation. -type LabelModelGrader struct { - Input []LabelModelGraderInput `json:"input,required"` - // The labels to assign to each item in the evaluation. - Labels []string `json:"labels,required"` - // The model to use for the evaluation. Must support structured outputs. - Model string `json:"model,required"` - // The name of the grader. - Name string `json:"name,required"` - // The labels that indicate a passing result. Must be a subset of labels. - PassingLabels []string `json:"passing_labels,required"` - // The object type, which is always `label_model`. - Type constant.LabelModel `json:"type,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Input respjson.Field - Labels respjson.Field - Model respjson.Field - Name respjson.Field - PassingLabels respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r LabelModelGrader) RawJSON() string { return r.JSON.raw } -func (r *LabelModelGrader) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// ToParam converts this LabelModelGrader to a LabelModelGraderParam. -// -// Warning: the fields of the param type will not be present. ToParam should only -// be used at the last possible moment before sending a request. Test for this with -// LabelModelGraderParam.Overrides() -func (r LabelModelGrader) ToParam() LabelModelGraderParam { - return param.Override[LabelModelGraderParam](json.RawMessage(r.RawJSON())) -} - -// A message input to the model with a role indicating instruction following -// hierarchy. Instructions given with the `developer` or `system` role take -// precedence over instructions given with the `user` role. Messages with the -// `assistant` role are presumed to have been generated by the model in previous -// interactions. -type LabelModelGraderInput struct { - // Inputs to the model - can contain template strings. - Content LabelModelGraderInputContentUnion `json:"content,required"` - // The role of the message input. One of `user`, `assistant`, `system`, or - // `developer`. - // - // Any of "user", "assistant", "system", "developer". - Role string `json:"role,required"` - // The type of the message input. Always `message`. - // - // Any of "message". - Type string `json:"type"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Content respjson.Field - Role respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r LabelModelGraderInput) RawJSON() string { return r.JSON.raw } -func (r *LabelModelGraderInput) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// LabelModelGraderInputContentUnion contains all possible properties and values -// from [string], [responses.ResponseInputText], -// [LabelModelGraderInputContentOutputText], -// [LabelModelGraderInputContentInputImage], [[]any]. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -// -// If the underlying value is not a json object, one of the following properties -// will be valid: OfString OfAnArrayOfInputTextAndInputImage] -type LabelModelGraderInputContentUnion struct { - // This field will be present if the value is a [string] instead of an object. - OfString string `json:",inline"` - // This field will be present if the value is a [[]any] instead of an object. - OfAnArrayOfInputTextAndInputImage []any `json:",inline"` - Text string `json:"text"` - Type string `json:"type"` - // This field is from variant [LabelModelGraderInputContentInputImage]. - ImageURL string `json:"image_url"` - // This field is from variant [LabelModelGraderInputContentInputImage]. - Detail string `json:"detail"` - JSON struct { - OfString respjson.Field - OfAnArrayOfInputTextAndInputImage respjson.Field - Text respjson.Field - Type respjson.Field - ImageURL respjson.Field - Detail respjson.Field - raw string - } `json:"-"` -} - -func (u LabelModelGraderInputContentUnion) AsString() (v string) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u LabelModelGraderInputContentUnion) AsInputText() (v responses.ResponseInputText) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u LabelModelGraderInputContentUnion) AsOutputText() (v LabelModelGraderInputContentOutputText) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u LabelModelGraderInputContentUnion) AsInputImage() (v LabelModelGraderInputContentInputImage) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u LabelModelGraderInputContentUnion) AsAnArrayOfInputTextAndInputImage() (v []any) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -// Returns the unmodified JSON received from the API -func (u LabelModelGraderInputContentUnion) RawJSON() string { return u.JSON.raw } - -func (r *LabelModelGraderInputContentUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// A text output from the model. -type LabelModelGraderInputContentOutputText struct { - // The text output from the model. - Text string `json:"text,required"` - // The type of the output text. Always `output_text`. - Type constant.OutputText `json:"type,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Text respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r LabelModelGraderInputContentOutputText) RawJSON() string { return r.JSON.raw } -func (r *LabelModelGraderInputContentOutputText) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// An image input to the model. -type LabelModelGraderInputContentInputImage struct { - // The URL of the image input. - ImageURL string `json:"image_url,required"` - // The type of the image input. Always `input_image`. - Type constant.InputImage `json:"type,required"` - // The detail level of the image to be sent to the model. One of `high`, `low`, or - // `auto`. Defaults to `auto`. - Detail string `json:"detail"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ImageURL respjson.Field - Type respjson.Field - Detail respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r LabelModelGraderInputContentInputImage) RawJSON() string { return r.JSON.raw } -func (r *LabelModelGraderInputContentInputImage) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// A LabelModelGrader object which uses a model to assign labels to each item in -// the evaluation. -// -// The properties Input, Labels, Model, Name, PassingLabels, Type are required. -type LabelModelGraderParam struct { - Input []LabelModelGraderInputParam `json:"input,omitzero,required"` - // The labels to assign to each item in the evaluation. - Labels []string `json:"labels,omitzero,required"` - // The model to use for the evaluation. Must support structured outputs. - Model string `json:"model,required"` - // The name of the grader. - Name string `json:"name,required"` - // The labels that indicate a passing result. Must be a subset of labels. - PassingLabels []string `json:"passing_labels,omitzero,required"` - // The object type, which is always `label_model`. - // - // This field can be elided, and will marshal its zero value as "label_model". - Type constant.LabelModel `json:"type,required"` - paramObj -} - -func (r LabelModelGraderParam) MarshalJSON() (data []byte, err error) { - type shadow LabelModelGraderParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *LabelModelGraderParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// A message input to the model with a role indicating instruction following -// hierarchy. Instructions given with the `developer` or `system` role take -// precedence over instructions given with the `user` role. Messages with the -// `assistant` role are presumed to have been generated by the model in previous -// interactions. -// -// The properties Content, Role are required. -type LabelModelGraderInputParam struct { - // Inputs to the model - can contain template strings. - Content LabelModelGraderInputContentUnionParam `json:"content,omitzero,required"` - // The role of the message input. One of `user`, `assistant`, `system`, or - // `developer`. - // - // Any of "user", "assistant", "system", "developer". - Role string `json:"role,omitzero,required"` - // The type of the message input. Always `message`. - // - // Any of "message". - Type string `json:"type,omitzero"` - paramObj -} - -func (r LabelModelGraderInputParam) MarshalJSON() (data []byte, err error) { - type shadow LabelModelGraderInputParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *LabelModelGraderInputParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -func init() { - apijson.RegisterFieldValidator[LabelModelGraderInputParam]( - "role", "user", "assistant", "system", "developer", - ) - apijson.RegisterFieldValidator[LabelModelGraderInputParam]( - "type", "message", - ) -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type LabelModelGraderInputContentUnionParam struct { - OfString param.Opt[string] `json:",omitzero,inline"` - OfInputText *responses.ResponseInputTextParam `json:",omitzero,inline"` - OfOutputText *LabelModelGraderInputContentOutputTextParam `json:",omitzero,inline"` - OfInputImage *LabelModelGraderInputContentInputImageParam `json:",omitzero,inline"` - OfAnArrayOfInputTextAndInputImage []any `json:",omitzero,inline"` - paramUnion -} - -func (u LabelModelGraderInputContentUnionParam) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfString, - u.OfInputText, - u.OfOutputText, - u.OfInputImage, - u.OfAnArrayOfInputTextAndInputImage) -} -func (u *LabelModelGraderInputContentUnionParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *LabelModelGraderInputContentUnionParam) asAny() any { - if !param.IsOmitted(u.OfString) { - return &u.OfString.Value - } else if !param.IsOmitted(u.OfInputText) { - return u.OfInputText - } else if !param.IsOmitted(u.OfOutputText) { - return u.OfOutputText - } else if !param.IsOmitted(u.OfInputImage) { - return u.OfInputImage - } else if !param.IsOmitted(u.OfAnArrayOfInputTextAndInputImage) { - return &u.OfAnArrayOfInputTextAndInputImage - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u LabelModelGraderInputContentUnionParam) GetImageURL() *string { - if vt := u.OfInputImage; vt != nil { - return &vt.ImageURL - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u LabelModelGraderInputContentUnionParam) GetDetail() *string { - if vt := u.OfInputImage; vt != nil && vt.Detail.Valid() { - return &vt.Detail.Value - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u LabelModelGraderInputContentUnionParam) GetText() *string { - if vt := u.OfInputText; vt != nil { - return (*string)(&vt.Text) - } else if vt := u.OfOutputText; vt != nil { - return (*string)(&vt.Text) - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u LabelModelGraderInputContentUnionParam) GetType() *string { - if vt := u.OfInputText; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfOutputText; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfInputImage; vt != nil { - return (*string)(&vt.Type) - } - return nil -} - -// A text output from the model. -// -// The properties Text, Type are required. -type LabelModelGraderInputContentOutputTextParam struct { - // The text output from the model. - Text string `json:"text,required"` - // The type of the output text. Always `output_text`. - // - // This field can be elided, and will marshal its zero value as "output_text". - Type constant.OutputText `json:"type,required"` - paramObj -} - -func (r LabelModelGraderInputContentOutputTextParam) MarshalJSON() (data []byte, err error) { - type shadow LabelModelGraderInputContentOutputTextParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *LabelModelGraderInputContentOutputTextParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// An image input to the model. -// -// The properties ImageURL, Type are required. -type LabelModelGraderInputContentInputImageParam struct { - // The URL of the image input. - ImageURL string `json:"image_url,required"` - // The detail level of the image to be sent to the model. One of `high`, `low`, or - // `auto`. Defaults to `auto`. - Detail param.Opt[string] `json:"detail,omitzero"` - // The type of the image input. Always `input_image`. - // - // This field can be elided, and will marshal its zero value as "input_image". - Type constant.InputImage `json:"type,required"` - paramObj -} - -func (r LabelModelGraderInputContentInputImageParam) MarshalJSON() (data []byte, err error) { - type shadow LabelModelGraderInputContentInputImageParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *LabelModelGraderInputContentInputImageParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// A MultiGrader object combines the output of multiple graders to produce a single -// score. -type MultiGrader struct { - // A formula to calculate the output based on grader results. - CalculateOutput string `json:"calculate_output,required"` - // A StringCheckGrader object that performs a string comparison between input and - // reference using a specified operation. - Graders MultiGraderGradersUnion `json:"graders,required"` - // The name of the grader. - Name string `json:"name,required"` - // The object type, which is always `multi`. - Type constant.Multi `json:"type,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - CalculateOutput respjson.Field - Graders respjson.Field - Name respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r MultiGrader) RawJSON() string { return r.JSON.raw } -func (r *MultiGrader) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// ToParam converts this MultiGrader to a MultiGraderParam. -// -// Warning: the fields of the param type will not be present. ToParam should only -// be used at the last possible moment before sending a request. Test for this with -// MultiGraderParam.Overrides() -func (r MultiGrader) ToParam() MultiGraderParam { - return param.Override[MultiGraderParam](json.RawMessage(r.RawJSON())) -} - -// MultiGraderGradersUnion contains all possible properties and values from -// [StringCheckGrader], [TextSimilarityGrader], [PythonGrader], [ScoreModelGrader], -// [LabelModelGrader]. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -type MultiGraderGradersUnion struct { - // This field is a union of [string], [string], [[]ScoreModelGraderInput], - // [[]LabelModelGraderInput] - Input MultiGraderGradersUnionInput `json:"input"` - Name string `json:"name"` - // This field is from variant [StringCheckGrader]. - Operation StringCheckGraderOperation `json:"operation"` - Reference string `json:"reference"` - Type string `json:"type"` - // This field is from variant [TextSimilarityGrader]. - EvaluationMetric TextSimilarityGraderEvaluationMetric `json:"evaluation_metric"` - // This field is from variant [PythonGrader]. - Source string `json:"source"` - // This field is from variant [PythonGrader]. - ImageTag string `json:"image_tag"` - Model string `json:"model"` - // This field is from variant [ScoreModelGrader]. - Range []float64 `json:"range"` - // This field is from variant [ScoreModelGrader]. - SamplingParams any `json:"sampling_params"` - // This field is from variant [LabelModelGrader]. - Labels []string `json:"labels"` - // This field is from variant [LabelModelGrader]. - PassingLabels []string `json:"passing_labels"` - JSON struct { - Input respjson.Field - Name respjson.Field - Operation respjson.Field - Reference respjson.Field - Type respjson.Field - EvaluationMetric respjson.Field - Source respjson.Field - ImageTag respjson.Field - Model respjson.Field - Range respjson.Field - SamplingParams respjson.Field - Labels respjson.Field - PassingLabels respjson.Field - raw string - } `json:"-"` -} - -func (u MultiGraderGradersUnion) AsStringCheckGrader() (v StringCheckGrader) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u MultiGraderGradersUnion) AsTextSimilarityGrader() (v TextSimilarityGrader) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u MultiGraderGradersUnion) AsPythonGrader() (v PythonGrader) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u MultiGraderGradersUnion) AsScoreModelGrader() (v ScoreModelGrader) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u MultiGraderGradersUnion) AsLabelModelGrader() (v LabelModelGrader) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -// Returns the unmodified JSON received from the API -func (u MultiGraderGradersUnion) RawJSON() string { return u.JSON.raw } - -func (r *MultiGraderGradersUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// MultiGraderGradersUnionInput is an implicit subunion of -// [MultiGraderGradersUnion]. MultiGraderGradersUnionInput provides convenient -// access to the sub-properties of the union. -// -// For type safety it is recommended to directly use a variant of the -// [MultiGraderGradersUnion]. -// -// If the underlying value is not a json object, one of the following properties -// will be valid: OfString OfScoreModelGraderInputArray -// OfLabelModelGraderInputArray] -type MultiGraderGradersUnionInput struct { - // This field will be present if the value is a [string] instead of an object. - OfString string `json:",inline"` - // This field will be present if the value is a [[]ScoreModelGraderInput] instead - // of an object. - OfScoreModelGraderInputArray []ScoreModelGraderInput `json:",inline"` - // This field will be present if the value is a [[]LabelModelGraderInput] instead - // of an object. - OfLabelModelGraderInputArray []LabelModelGraderInput `json:",inline"` - JSON struct { - OfString respjson.Field - OfScoreModelGraderInputArray respjson.Field - OfLabelModelGraderInputArray respjson.Field - raw string - } `json:"-"` -} - -func (r *MultiGraderGradersUnionInput) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// A MultiGrader object combines the output of multiple graders to produce a single -// score. -// -// The properties CalculateOutput, Graders, Name, Type are required. -type MultiGraderParam struct { - // A formula to calculate the output based on grader results. - CalculateOutput string `json:"calculate_output,required"` - // A StringCheckGrader object that performs a string comparison between input and - // reference using a specified operation. - Graders MultiGraderGradersUnionParam `json:"graders,omitzero,required"` - // The name of the grader. - Name string `json:"name,required"` - // The object type, which is always `multi`. - // - // This field can be elided, and will marshal its zero value as "multi". - Type constant.Multi `json:"type,required"` - paramObj -} - -func (r MultiGraderParam) MarshalJSON() (data []byte, err error) { - type shadow MultiGraderParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *MultiGraderParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type MultiGraderGradersUnionParam struct { - OfStringCheckGrader *StringCheckGraderParam `json:",omitzero,inline"` - OfTextSimilarityGrader *TextSimilarityGraderParam `json:",omitzero,inline"` - OfPythonGrader *PythonGraderParam `json:",omitzero,inline"` - OfScoreModelGrader *ScoreModelGraderParam `json:",omitzero,inline"` - OfLabelModelGrader *LabelModelGraderParam `json:",omitzero,inline"` - paramUnion -} - -func (u MultiGraderGradersUnionParam) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfStringCheckGrader, - u.OfTextSimilarityGrader, - u.OfPythonGrader, - u.OfScoreModelGrader, - u.OfLabelModelGrader) -} -func (u *MultiGraderGradersUnionParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *MultiGraderGradersUnionParam) asAny() any { - if !param.IsOmitted(u.OfStringCheckGrader) { - return u.OfStringCheckGrader - } else if !param.IsOmitted(u.OfTextSimilarityGrader) { - return u.OfTextSimilarityGrader - } else if !param.IsOmitted(u.OfPythonGrader) { - return u.OfPythonGrader - } else if !param.IsOmitted(u.OfScoreModelGrader) { - return u.OfScoreModelGrader - } else if !param.IsOmitted(u.OfLabelModelGrader) { - return u.OfLabelModelGrader - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u MultiGraderGradersUnionParam) GetOperation() *string { - if vt := u.OfStringCheckGrader; vt != nil { - return (*string)(&vt.Operation) - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u MultiGraderGradersUnionParam) GetEvaluationMetric() *string { - if vt := u.OfTextSimilarityGrader; vt != nil { - return (*string)(&vt.EvaluationMetric) - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u MultiGraderGradersUnionParam) GetSource() *string { - if vt := u.OfPythonGrader; vt != nil { - return &vt.Source - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u MultiGraderGradersUnionParam) GetImageTag() *string { - if vt := u.OfPythonGrader; vt != nil && vt.ImageTag.Valid() { - return &vt.ImageTag.Value - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u MultiGraderGradersUnionParam) GetRange() []float64 { - if vt := u.OfScoreModelGrader; vt != nil { - return vt.Range - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u MultiGraderGradersUnionParam) GetSamplingParams() *any { - if vt := u.OfScoreModelGrader; vt != nil { - return &vt.SamplingParams - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u MultiGraderGradersUnionParam) GetLabels() []string { - if vt := u.OfLabelModelGrader; vt != nil { - return vt.Labels - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u MultiGraderGradersUnionParam) GetPassingLabels() []string { - if vt := u.OfLabelModelGrader; vt != nil { - return vt.PassingLabels - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u MultiGraderGradersUnionParam) GetName() *string { - if vt := u.OfStringCheckGrader; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfTextSimilarityGrader; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfPythonGrader; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfScoreModelGrader; vt != nil { - return (*string)(&vt.Name) - } else if vt := u.OfLabelModelGrader; vt != nil { - return (*string)(&vt.Name) - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u MultiGraderGradersUnionParam) GetReference() *string { - if vt := u.OfStringCheckGrader; vt != nil { - return (*string)(&vt.Reference) - } else if vt := u.OfTextSimilarityGrader; vt != nil { - return (*string)(&vt.Reference) - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u MultiGraderGradersUnionParam) GetType() *string { - if vt := u.OfStringCheckGrader; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfTextSimilarityGrader; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfPythonGrader; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfScoreModelGrader; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfLabelModelGrader; vt != nil { - return (*string)(&vt.Type) - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u MultiGraderGradersUnionParam) GetModel() *string { - if vt := u.OfScoreModelGrader; vt != nil { - return (*string)(&vt.Model) - } else if vt := u.OfLabelModelGrader; vt != nil { - return (*string)(&vt.Model) - } - return nil -} - -// Returns a subunion which exports methods to access subproperties -// -// Or use AsAny() to get the underlying value -func (u MultiGraderGradersUnionParam) GetInput() (res multiGraderGradersUnionParamInput) { - if vt := u.OfStringCheckGrader; vt != nil { - res.any = &vt.Input - } else if vt := u.OfTextSimilarityGrader; vt != nil { - res.any = &vt.Input - } else if vt := u.OfScoreModelGrader; vt != nil { - res.any = &vt.Input - } else if vt := u.OfLabelModelGrader; vt != nil { - res.any = &vt.Input - } - return -} - -// Can have the runtime types [*string], [_[]ScoreModelGraderInputParam], -// [_[]LabelModelGraderInputParam] -type multiGraderGradersUnionParamInput struct{ any } - -// Use the following switch statement to get the type of the union: -// -// switch u.AsAny().(type) { -// case *string: -// case *[]openai.ScoreModelGraderInputParam: -// case *[]openai.LabelModelGraderInputParam: -// default: -// fmt.Errorf("not present") -// } -func (u multiGraderGradersUnionParamInput) AsAny() any { return u.any } - -// A PythonGrader object that runs a python script on the input. -type PythonGrader struct { - // The name of the grader. - Name string `json:"name,required"` - // The source code of the python script. - Source string `json:"source,required"` - // The object type, which is always `python`. - Type constant.Python `json:"type,required"` - // The image tag to use for the python script. - ImageTag string `json:"image_tag"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Name respjson.Field - Source respjson.Field - Type respjson.Field - ImageTag respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r PythonGrader) RawJSON() string { return r.JSON.raw } -func (r *PythonGrader) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// ToParam converts this PythonGrader to a PythonGraderParam. -// -// Warning: the fields of the param type will not be present. ToParam should only -// be used at the last possible moment before sending a request. Test for this with -// PythonGraderParam.Overrides() -func (r PythonGrader) ToParam() PythonGraderParam { - return param.Override[PythonGraderParam](json.RawMessage(r.RawJSON())) -} - -// A PythonGrader object that runs a python script on the input. -// -// The properties Name, Source, Type are required. -type PythonGraderParam struct { - // The name of the grader. - Name string `json:"name,required"` - // The source code of the python script. - Source string `json:"source,required"` - // The image tag to use for the python script. - ImageTag param.Opt[string] `json:"image_tag,omitzero"` - // The object type, which is always `python`. - // - // This field can be elided, and will marshal its zero value as "python". - Type constant.Python `json:"type,required"` - paramObj -} - -func (r PythonGraderParam) MarshalJSON() (data []byte, err error) { - type shadow PythonGraderParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *PythonGraderParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// A ScoreModelGrader object that uses a model to assign a score to the input. -type ScoreModelGrader struct { - // The input text. This may include template strings. - Input []ScoreModelGraderInput `json:"input,required"` - // The model to use for the evaluation. - Model string `json:"model,required"` - // The name of the grader. - Name string `json:"name,required"` - // The object type, which is always `score_model`. - Type constant.ScoreModel `json:"type,required"` - // The range of the score. Defaults to `[0, 1]`. - Range []float64 `json:"range"` - // The sampling parameters for the model. - SamplingParams any `json:"sampling_params"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Input respjson.Field - Model respjson.Field - Name respjson.Field - Type respjson.Field - Range respjson.Field - SamplingParams respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ScoreModelGrader) RawJSON() string { return r.JSON.raw } -func (r *ScoreModelGrader) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// ToParam converts this ScoreModelGrader to a ScoreModelGraderParam. -// -// Warning: the fields of the param type will not be present. ToParam should only -// be used at the last possible moment before sending a request. Test for this with -// ScoreModelGraderParam.Overrides() -func (r ScoreModelGrader) ToParam() ScoreModelGraderParam { - return param.Override[ScoreModelGraderParam](json.RawMessage(r.RawJSON())) -} - -// A message input to the model with a role indicating instruction following -// hierarchy. Instructions given with the `developer` or `system` role take -// precedence over instructions given with the `user` role. Messages with the -// `assistant` role are presumed to have been generated by the model in previous -// interactions. -type ScoreModelGraderInput struct { - // Inputs to the model - can contain template strings. - Content ScoreModelGraderInputContentUnion `json:"content,required"` - // The role of the message input. One of `user`, `assistant`, `system`, or - // `developer`. - // - // Any of "user", "assistant", "system", "developer". - Role string `json:"role,required"` - // The type of the message input. Always `message`. - // - // Any of "message". - Type string `json:"type"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Content respjson.Field - Role respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ScoreModelGraderInput) RawJSON() string { return r.JSON.raw } -func (r *ScoreModelGraderInput) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// ScoreModelGraderInputContentUnion contains all possible properties and values -// from [string], [responses.ResponseInputText], -// [ScoreModelGraderInputContentOutputText], -// [ScoreModelGraderInputContentInputImage], [[]any]. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -// -// If the underlying value is not a json object, one of the following properties -// will be valid: OfString OfAnArrayOfInputTextAndInputImage] -type ScoreModelGraderInputContentUnion struct { - // This field will be present if the value is a [string] instead of an object. - OfString string `json:",inline"` - // This field will be present if the value is a [[]any] instead of an object. - OfAnArrayOfInputTextAndInputImage []any `json:",inline"` - Text string `json:"text"` - Type string `json:"type"` - // This field is from variant [ScoreModelGraderInputContentInputImage]. - ImageURL string `json:"image_url"` - // This field is from variant [ScoreModelGraderInputContentInputImage]. - Detail string `json:"detail"` - JSON struct { - OfString respjson.Field - OfAnArrayOfInputTextAndInputImage respjson.Field - Text respjson.Field - Type respjson.Field - ImageURL respjson.Field - Detail respjson.Field - raw string - } `json:"-"` -} - -func (u ScoreModelGraderInputContentUnion) AsString() (v string) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u ScoreModelGraderInputContentUnion) AsInputText() (v responses.ResponseInputText) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u ScoreModelGraderInputContentUnion) AsOutputText() (v ScoreModelGraderInputContentOutputText) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u ScoreModelGraderInputContentUnion) AsInputImage() (v ScoreModelGraderInputContentInputImage) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u ScoreModelGraderInputContentUnion) AsAnArrayOfInputTextAndInputImage() (v []any) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -// Returns the unmodified JSON received from the API -func (u ScoreModelGraderInputContentUnion) RawJSON() string { return u.JSON.raw } - -func (r *ScoreModelGraderInputContentUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// A text output from the model. -type ScoreModelGraderInputContentOutputText struct { - // The text output from the model. - Text string `json:"text,required"` - // The type of the output text. Always `output_text`. - Type constant.OutputText `json:"type,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Text respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ScoreModelGraderInputContentOutputText) RawJSON() string { return r.JSON.raw } -func (r *ScoreModelGraderInputContentOutputText) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// An image input to the model. -type ScoreModelGraderInputContentInputImage struct { - // The URL of the image input. - ImageURL string `json:"image_url,required"` - // The type of the image input. Always `input_image`. - Type constant.InputImage `json:"type,required"` - // The detail level of the image to be sent to the model. One of `high`, `low`, or - // `auto`. Defaults to `auto`. - Detail string `json:"detail"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ImageURL respjson.Field - Type respjson.Field - Detail respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ScoreModelGraderInputContentInputImage) RawJSON() string { return r.JSON.raw } -func (r *ScoreModelGraderInputContentInputImage) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// A ScoreModelGrader object that uses a model to assign a score to the input. -// -// The properties Input, Model, Name, Type are required. -type ScoreModelGraderParam struct { - // The input text. This may include template strings. - Input []ScoreModelGraderInputParam `json:"input,omitzero,required"` - // The model to use for the evaluation. - Model string `json:"model,required"` - // The name of the grader. - Name string `json:"name,required"` - // The range of the score. Defaults to `[0, 1]`. - Range []float64 `json:"range,omitzero"` - // The sampling parameters for the model. - SamplingParams any `json:"sampling_params,omitzero"` - // The object type, which is always `score_model`. - // - // This field can be elided, and will marshal its zero value as "score_model". - Type constant.ScoreModel `json:"type,required"` - paramObj -} - -func (r ScoreModelGraderParam) MarshalJSON() (data []byte, err error) { - type shadow ScoreModelGraderParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ScoreModelGraderParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// A message input to the model with a role indicating instruction following -// hierarchy. Instructions given with the `developer` or `system` role take -// precedence over instructions given with the `user` role. Messages with the -// `assistant` role are presumed to have been generated by the model in previous -// interactions. -// -// The properties Content, Role are required. -type ScoreModelGraderInputParam struct { - // Inputs to the model - can contain template strings. - Content ScoreModelGraderInputContentUnionParam `json:"content,omitzero,required"` - // The role of the message input. One of `user`, `assistant`, `system`, or - // `developer`. - // - // Any of "user", "assistant", "system", "developer". - Role string `json:"role,omitzero,required"` - // The type of the message input. Always `message`. - // - // Any of "message". - Type string `json:"type,omitzero"` - paramObj -} - -func (r ScoreModelGraderInputParam) MarshalJSON() (data []byte, err error) { - type shadow ScoreModelGraderInputParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ScoreModelGraderInputParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -func init() { - apijson.RegisterFieldValidator[ScoreModelGraderInputParam]( - "role", "user", "assistant", "system", "developer", - ) - apijson.RegisterFieldValidator[ScoreModelGraderInputParam]( - "type", "message", - ) -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type ScoreModelGraderInputContentUnionParam struct { - OfString param.Opt[string] `json:",omitzero,inline"` - OfInputText *responses.ResponseInputTextParam `json:",omitzero,inline"` - OfOutputText *ScoreModelGraderInputContentOutputTextParam `json:",omitzero,inline"` - OfInputImage *ScoreModelGraderInputContentInputImageParam `json:",omitzero,inline"` - OfAnArrayOfInputTextAndInputImage []any `json:",omitzero,inline"` - paramUnion -} - -func (u ScoreModelGraderInputContentUnionParam) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfString, - u.OfInputText, - u.OfOutputText, - u.OfInputImage, - u.OfAnArrayOfInputTextAndInputImage) -} -func (u *ScoreModelGraderInputContentUnionParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *ScoreModelGraderInputContentUnionParam) asAny() any { - if !param.IsOmitted(u.OfString) { - return &u.OfString.Value - } else if !param.IsOmitted(u.OfInputText) { - return u.OfInputText - } else if !param.IsOmitted(u.OfOutputText) { - return u.OfOutputText - } else if !param.IsOmitted(u.OfInputImage) { - return u.OfInputImage - } else if !param.IsOmitted(u.OfAnArrayOfInputTextAndInputImage) { - return &u.OfAnArrayOfInputTextAndInputImage - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u ScoreModelGraderInputContentUnionParam) GetImageURL() *string { - if vt := u.OfInputImage; vt != nil { - return &vt.ImageURL - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u ScoreModelGraderInputContentUnionParam) GetDetail() *string { - if vt := u.OfInputImage; vt != nil && vt.Detail.Valid() { - return &vt.Detail.Value - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u ScoreModelGraderInputContentUnionParam) GetText() *string { - if vt := u.OfInputText; vt != nil { - return (*string)(&vt.Text) - } else if vt := u.OfOutputText; vt != nil { - return (*string)(&vt.Text) - } - return nil -} - -// Returns a pointer to the underlying variant's property, if present. -func (u ScoreModelGraderInputContentUnionParam) GetType() *string { - if vt := u.OfInputText; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfOutputText; vt != nil { - return (*string)(&vt.Type) - } else if vt := u.OfInputImage; vt != nil { - return (*string)(&vt.Type) - } - return nil -} - -// A text output from the model. -// -// The properties Text, Type are required. -type ScoreModelGraderInputContentOutputTextParam struct { - // The text output from the model. - Text string `json:"text,required"` - // The type of the output text. Always `output_text`. - // - // This field can be elided, and will marshal its zero value as "output_text". - Type constant.OutputText `json:"type,required"` - paramObj -} - -func (r ScoreModelGraderInputContentOutputTextParam) MarshalJSON() (data []byte, err error) { - type shadow ScoreModelGraderInputContentOutputTextParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ScoreModelGraderInputContentOutputTextParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// An image input to the model. -// -// The properties ImageURL, Type are required. -type ScoreModelGraderInputContentInputImageParam struct { - // The URL of the image input. - ImageURL string `json:"image_url,required"` - // The detail level of the image to be sent to the model. One of `high`, `low`, or - // `auto`. Defaults to `auto`. - Detail param.Opt[string] `json:"detail,omitzero"` - // The type of the image input. Always `input_image`. - // - // This field can be elided, and will marshal its zero value as "input_image". - Type constant.InputImage `json:"type,required"` - paramObj -} - -func (r ScoreModelGraderInputContentInputImageParam) MarshalJSON() (data []byte, err error) { - type shadow ScoreModelGraderInputContentInputImageParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ScoreModelGraderInputContentInputImageParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// A StringCheckGrader object that performs a string comparison between input and -// reference using a specified operation. -type StringCheckGrader struct { - // The input text. This may include template strings. - Input string `json:"input,required"` - // The name of the grader. - Name string `json:"name,required"` - // The string check operation to perform. One of `eq`, `ne`, `like`, or `ilike`. - // - // Any of "eq", "ne", "like", "ilike". - Operation StringCheckGraderOperation `json:"operation,required"` - // The reference text. This may include template strings. - Reference string `json:"reference,required"` - // The object type, which is always `string_check`. - Type constant.StringCheck `json:"type,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Input respjson.Field - Name respjson.Field - Operation respjson.Field - Reference respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r StringCheckGrader) RawJSON() string { return r.JSON.raw } -func (r *StringCheckGrader) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// ToParam converts this StringCheckGrader to a StringCheckGraderParam. -// -// Warning: the fields of the param type will not be present. ToParam should only -// be used at the last possible moment before sending a request. Test for this with -// StringCheckGraderParam.Overrides() -func (r StringCheckGrader) ToParam() StringCheckGraderParam { - return param.Override[StringCheckGraderParam](json.RawMessage(r.RawJSON())) -} - -// The string check operation to perform. One of `eq`, `ne`, `like`, or `ilike`. -type StringCheckGraderOperation string - -const ( - StringCheckGraderOperationEq StringCheckGraderOperation = "eq" - StringCheckGraderOperationNe StringCheckGraderOperation = "ne" - StringCheckGraderOperationLike StringCheckGraderOperation = "like" - StringCheckGraderOperationIlike StringCheckGraderOperation = "ilike" -) - -// A StringCheckGrader object that performs a string comparison between input and -// reference using a specified operation. -// -// The properties Input, Name, Operation, Reference, Type are required. -type StringCheckGraderParam struct { - // The input text. This may include template strings. - Input string `json:"input,required"` - // The name of the grader. - Name string `json:"name,required"` - // The string check operation to perform. One of `eq`, `ne`, `like`, or `ilike`. - // - // Any of "eq", "ne", "like", "ilike". - Operation StringCheckGraderOperation `json:"operation,omitzero,required"` - // The reference text. This may include template strings. - Reference string `json:"reference,required"` - // The object type, which is always `string_check`. - // - // This field can be elided, and will marshal its zero value as "string_check". - Type constant.StringCheck `json:"type,required"` - paramObj -} - -func (r StringCheckGraderParam) MarshalJSON() (data []byte, err error) { - type shadow StringCheckGraderParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *StringCheckGraderParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// A TextSimilarityGrader object which grades text based on similarity metrics. -type TextSimilarityGrader struct { - // The evaluation metric to use. One of `fuzzy_match`, `bleu`, `gleu`, `meteor`, - // `rouge_1`, `rouge_2`, `rouge_3`, `rouge_4`, `rouge_5`, or `rouge_l`. - // - // Any of "fuzzy_match", "bleu", "gleu", "meteor", "rouge_1", "rouge_2", "rouge_3", - // "rouge_4", "rouge_5", "rouge_l". - EvaluationMetric TextSimilarityGraderEvaluationMetric `json:"evaluation_metric,required"` - // The text being graded. - Input string `json:"input,required"` - // The name of the grader. - Name string `json:"name,required"` - // The text being graded against. - Reference string `json:"reference,required"` - // The type of grader. - Type constant.TextSimilarity `json:"type,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - EvaluationMetric respjson.Field - Input respjson.Field - Name respjson.Field - Reference respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r TextSimilarityGrader) RawJSON() string { return r.JSON.raw } -func (r *TextSimilarityGrader) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// ToParam converts this TextSimilarityGrader to a TextSimilarityGraderParam. -// -// Warning: the fields of the param type will not be present. ToParam should only -// be used at the last possible moment before sending a request. Test for this with -// TextSimilarityGraderParam.Overrides() -func (r TextSimilarityGrader) ToParam() TextSimilarityGraderParam { - return param.Override[TextSimilarityGraderParam](json.RawMessage(r.RawJSON())) -} - -// The evaluation metric to use. One of `fuzzy_match`, `bleu`, `gleu`, `meteor`, -// `rouge_1`, `rouge_2`, `rouge_3`, `rouge_4`, `rouge_5`, or `rouge_l`. -type TextSimilarityGraderEvaluationMetric string - -const ( - TextSimilarityGraderEvaluationMetricFuzzyMatch TextSimilarityGraderEvaluationMetric = "fuzzy_match" - TextSimilarityGraderEvaluationMetricBleu TextSimilarityGraderEvaluationMetric = "bleu" - TextSimilarityGraderEvaluationMetricGleu TextSimilarityGraderEvaluationMetric = "gleu" - TextSimilarityGraderEvaluationMetricMeteor TextSimilarityGraderEvaluationMetric = "meteor" - TextSimilarityGraderEvaluationMetricRouge1 TextSimilarityGraderEvaluationMetric = "rouge_1" - TextSimilarityGraderEvaluationMetricRouge2 TextSimilarityGraderEvaluationMetric = "rouge_2" - TextSimilarityGraderEvaluationMetricRouge3 TextSimilarityGraderEvaluationMetric = "rouge_3" - TextSimilarityGraderEvaluationMetricRouge4 TextSimilarityGraderEvaluationMetric = "rouge_4" - TextSimilarityGraderEvaluationMetricRouge5 TextSimilarityGraderEvaluationMetric = "rouge_5" - TextSimilarityGraderEvaluationMetricRougeL TextSimilarityGraderEvaluationMetric = "rouge_l" -) - -// A TextSimilarityGrader object which grades text based on similarity metrics. -// -// The properties EvaluationMetric, Input, Name, Reference, Type are required. -type TextSimilarityGraderParam struct { - // The evaluation metric to use. One of `fuzzy_match`, `bleu`, `gleu`, `meteor`, - // `rouge_1`, `rouge_2`, `rouge_3`, `rouge_4`, `rouge_5`, or `rouge_l`. - // - // Any of "fuzzy_match", "bleu", "gleu", "meteor", "rouge_1", "rouge_2", "rouge_3", - // "rouge_4", "rouge_5", "rouge_l". - EvaluationMetric TextSimilarityGraderEvaluationMetric `json:"evaluation_metric,omitzero,required"` - // The text being graded. - Input string `json:"input,required"` - // The name of the grader. - Name string `json:"name,required"` - // The text being graded against. - Reference string `json:"reference,required"` - // The type of grader. - // - // This field can be elided, and will marshal its zero value as "text_similarity". - Type constant.TextSimilarity `json:"type,required"` - paramObj -} - -func (r TextSimilarityGraderParam) MarshalJSON() (data []byte, err error) { - type shadow TextSimilarityGraderParam - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *TextSimilarityGraderParam) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} diff --git a/vendor/github.com/openai/openai-go/image.go b/vendor/github.com/openai/openai-go/image.go deleted file mode 100644 index 63f7b2ee..00000000 --- a/vendor/github.com/openai/openai-go/image.go +++ /dev/null @@ -1,1300 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -package openai - -import ( - "bytes" - "context" - "encoding/json" - "io" - "mime/multipart" - "net/http" - - "github.com/openai/openai-go/internal/apiform" - "github.com/openai/openai-go/internal/apijson" - "github.com/openai/openai-go/internal/requestconfig" - "github.com/openai/openai-go/option" - "github.com/openai/openai-go/packages/param" - "github.com/openai/openai-go/packages/respjson" - "github.com/openai/openai-go/packages/ssestream" - "github.com/openai/openai-go/shared/constant" -) - -// ImageService contains methods and other services that help with interacting with -// the openai API. -// -// Note, unlike clients, this service does not read variables from the environment -// automatically. You should not instantiate this service directly, and instead use -// the [NewImageService] method instead. -type ImageService struct { - Options []option.RequestOption -} - -// NewImageService generates a new service that applies the given options to each -// request. These options are applied after the parent client's options (if there -// is one), and before any request-specific options. -func NewImageService(opts ...option.RequestOption) (r ImageService) { - r = ImageService{} - r.Options = opts - return -} - -// Creates a variation of a given image. This endpoint only supports `dall-e-2`. -func (r *ImageService) NewVariation(ctx context.Context, body ImageNewVariationParams, opts ...option.RequestOption) (res *ImagesResponse, err error) { - opts = append(r.Options[:], opts...) - path := "images/variations" - err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...) - return -} - -// Creates an edited or extended image given one or more source images and a -// prompt. This endpoint only supports `gpt-image-1` and `dall-e-2`. -func (r *ImageService) Edit(ctx context.Context, body ImageEditParams, opts ...option.RequestOption) (res *ImagesResponse, err error) { - opts = append(r.Options[:], opts...) - path := "images/edits" - err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...) - return -} - -// Creates an edited or extended image given one or more source images and a -// prompt. This endpoint only supports `gpt-image-1` and `dall-e-2`. -func (r *ImageService) EditStreaming(ctx context.Context, body ImageEditParams, opts ...option.RequestOption) (stream *ssestream.Stream[ImageEditStreamEventUnion]) { - var ( - raw *http.Response - err error - ) - opts = append(r.Options[:], opts...) - body.SetExtraFields(map[string]any{ - "stream": "true", - }) - path := "images/edits" - err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &raw, opts...) - return ssestream.NewStream[ImageEditStreamEventUnion](ssestream.NewDecoder(raw), err) -} - -// Creates an image given a prompt. -// [Learn more](https://platform.openai.com/docs/guides/images). -func (r *ImageService) Generate(ctx context.Context, body ImageGenerateParams, opts ...option.RequestOption) (res *ImagesResponse, err error) { - opts = append(r.Options[:], opts...) - path := "images/generations" - err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...) - return -} - -// Creates an image given a prompt. -// [Learn more](https://platform.openai.com/docs/guides/images). -func (r *ImageService) GenerateStreaming(ctx context.Context, body ImageGenerateParams, opts ...option.RequestOption) (stream *ssestream.Stream[ImageGenStreamEventUnion]) { - var ( - raw *http.Response - err error - ) - opts = append(r.Options[:], opts...) - opts = append([]option.RequestOption{option.WithJSONSet("stream", true)}, opts...) - path := "images/generations" - err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &raw, opts...) - return ssestream.NewStream[ImageGenStreamEventUnion](ssestream.NewDecoder(raw), err) -} - -// Represents the content or the URL of an image generated by the OpenAI API. -type Image struct { - // The base64-encoded JSON of the generated image. Default value for `gpt-image-1`, - // and only present if `response_format` is set to `b64_json` for `dall-e-2` and - // `dall-e-3`. - B64JSON string `json:"b64_json"` - // For `dall-e-3` only, the revised prompt that was used to generate the image. - RevisedPrompt string `json:"revised_prompt"` - // When using `dall-e-2` or `dall-e-3`, the URL of the generated image if - // `response_format` is set to `url` (default value). Unsupported for - // `gpt-image-1`. - URL string `json:"url"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - B64JSON respjson.Field - RevisedPrompt respjson.Field - URL respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r Image) RawJSON() string { return r.JSON.raw } -func (r *Image) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Emitted when image editing has completed and the final image is available. -type ImageEditCompletedEvent struct { - // Base64-encoded final edited image data, suitable for rendering as an image. - B64JSON string `json:"b64_json,required"` - // The background setting for the edited image. - // - // Any of "transparent", "opaque", "auto". - Background ImageEditCompletedEventBackground `json:"background,required"` - // The Unix timestamp when the event was created. - CreatedAt int64 `json:"created_at,required"` - // The output format for the edited image. - // - // Any of "png", "webp", "jpeg". - OutputFormat ImageEditCompletedEventOutputFormat `json:"output_format,required"` - // The quality setting for the edited image. - // - // Any of "low", "medium", "high", "auto". - Quality ImageEditCompletedEventQuality `json:"quality,required"` - // The size of the edited image. - // - // Any of "1024x1024", "1024x1536", "1536x1024", "auto". - Size ImageEditCompletedEventSize `json:"size,required"` - // The type of the event. Always `image_edit.completed`. - Type constant.ImageEditCompleted `json:"type,required"` - // For `gpt-image-1` only, the token usage information for the image generation. - Usage ImageEditCompletedEventUsage `json:"usage,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - B64JSON respjson.Field - Background respjson.Field - CreatedAt respjson.Field - OutputFormat respjson.Field - Quality respjson.Field - Size respjson.Field - Type respjson.Field - Usage respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ImageEditCompletedEvent) RawJSON() string { return r.JSON.raw } -func (r *ImageEditCompletedEvent) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The background setting for the edited image. -type ImageEditCompletedEventBackground string - -const ( - ImageEditCompletedEventBackgroundTransparent ImageEditCompletedEventBackground = "transparent" - ImageEditCompletedEventBackgroundOpaque ImageEditCompletedEventBackground = "opaque" - ImageEditCompletedEventBackgroundAuto ImageEditCompletedEventBackground = "auto" -) - -// The output format for the edited image. -type ImageEditCompletedEventOutputFormat string - -const ( - ImageEditCompletedEventOutputFormatPNG ImageEditCompletedEventOutputFormat = "png" - ImageEditCompletedEventOutputFormatWebP ImageEditCompletedEventOutputFormat = "webp" - ImageEditCompletedEventOutputFormatJPEG ImageEditCompletedEventOutputFormat = "jpeg" -) - -// The quality setting for the edited image. -type ImageEditCompletedEventQuality string - -const ( - ImageEditCompletedEventQualityLow ImageEditCompletedEventQuality = "low" - ImageEditCompletedEventQualityMedium ImageEditCompletedEventQuality = "medium" - ImageEditCompletedEventQualityHigh ImageEditCompletedEventQuality = "high" - ImageEditCompletedEventQualityAuto ImageEditCompletedEventQuality = "auto" -) - -// The size of the edited image. -type ImageEditCompletedEventSize string - -const ( - ImageEditCompletedEventSize1024x1024 ImageEditCompletedEventSize = "1024x1024" - ImageEditCompletedEventSize1024x1536 ImageEditCompletedEventSize = "1024x1536" - ImageEditCompletedEventSize1536x1024 ImageEditCompletedEventSize = "1536x1024" - ImageEditCompletedEventSizeAuto ImageEditCompletedEventSize = "auto" -) - -// For `gpt-image-1` only, the token usage information for the image generation. -type ImageEditCompletedEventUsage struct { - // The number of tokens (images and text) in the input prompt. - InputTokens int64 `json:"input_tokens,required"` - // The input tokens detailed information for the image generation. - InputTokensDetails ImageEditCompletedEventUsageInputTokensDetails `json:"input_tokens_details,required"` - // The number of image tokens in the output image. - OutputTokens int64 `json:"output_tokens,required"` - // The total number of tokens (images and text) used for the image generation. - TotalTokens int64 `json:"total_tokens,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - InputTokens respjson.Field - InputTokensDetails respjson.Field - OutputTokens respjson.Field - TotalTokens respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ImageEditCompletedEventUsage) RawJSON() string { return r.JSON.raw } -func (r *ImageEditCompletedEventUsage) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The input tokens detailed information for the image generation. -type ImageEditCompletedEventUsageInputTokensDetails struct { - // The number of image tokens in the input prompt. - ImageTokens int64 `json:"image_tokens,required"` - // The number of text tokens in the input prompt. - TextTokens int64 `json:"text_tokens,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ImageTokens respjson.Field - TextTokens respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ImageEditCompletedEventUsageInputTokensDetails) RawJSON() string { return r.JSON.raw } -func (r *ImageEditCompletedEventUsageInputTokensDetails) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Emitted when a partial image is available during image editing streaming. -type ImageEditPartialImageEvent struct { - // Base64-encoded partial image data, suitable for rendering as an image. - B64JSON string `json:"b64_json,required"` - // The background setting for the requested edited image. - // - // Any of "transparent", "opaque", "auto". - Background ImageEditPartialImageEventBackground `json:"background,required"` - // The Unix timestamp when the event was created. - CreatedAt int64 `json:"created_at,required"` - // The output format for the requested edited image. - // - // Any of "png", "webp", "jpeg". - OutputFormat ImageEditPartialImageEventOutputFormat `json:"output_format,required"` - // 0-based index for the partial image (streaming). - PartialImageIndex int64 `json:"partial_image_index,required"` - // The quality setting for the requested edited image. - // - // Any of "low", "medium", "high", "auto". - Quality ImageEditPartialImageEventQuality `json:"quality,required"` - // The size of the requested edited image. - // - // Any of "1024x1024", "1024x1536", "1536x1024", "auto". - Size ImageEditPartialImageEventSize `json:"size,required"` - // The type of the event. Always `image_edit.partial_image`. - Type constant.ImageEditPartialImage `json:"type,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - B64JSON respjson.Field - Background respjson.Field - CreatedAt respjson.Field - OutputFormat respjson.Field - PartialImageIndex respjson.Field - Quality respjson.Field - Size respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ImageEditPartialImageEvent) RawJSON() string { return r.JSON.raw } -func (r *ImageEditPartialImageEvent) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The background setting for the requested edited image. -type ImageEditPartialImageEventBackground string - -const ( - ImageEditPartialImageEventBackgroundTransparent ImageEditPartialImageEventBackground = "transparent" - ImageEditPartialImageEventBackgroundOpaque ImageEditPartialImageEventBackground = "opaque" - ImageEditPartialImageEventBackgroundAuto ImageEditPartialImageEventBackground = "auto" -) - -// The output format for the requested edited image. -type ImageEditPartialImageEventOutputFormat string - -const ( - ImageEditPartialImageEventOutputFormatPNG ImageEditPartialImageEventOutputFormat = "png" - ImageEditPartialImageEventOutputFormatWebP ImageEditPartialImageEventOutputFormat = "webp" - ImageEditPartialImageEventOutputFormatJPEG ImageEditPartialImageEventOutputFormat = "jpeg" -) - -// The quality setting for the requested edited image. -type ImageEditPartialImageEventQuality string - -const ( - ImageEditPartialImageEventQualityLow ImageEditPartialImageEventQuality = "low" - ImageEditPartialImageEventQualityMedium ImageEditPartialImageEventQuality = "medium" - ImageEditPartialImageEventQualityHigh ImageEditPartialImageEventQuality = "high" - ImageEditPartialImageEventQualityAuto ImageEditPartialImageEventQuality = "auto" -) - -// The size of the requested edited image. -type ImageEditPartialImageEventSize string - -const ( - ImageEditPartialImageEventSize1024x1024 ImageEditPartialImageEventSize = "1024x1024" - ImageEditPartialImageEventSize1024x1536 ImageEditPartialImageEventSize = "1024x1536" - ImageEditPartialImageEventSize1536x1024 ImageEditPartialImageEventSize = "1536x1024" - ImageEditPartialImageEventSizeAuto ImageEditPartialImageEventSize = "auto" -) - -// ImageEditStreamEventUnion contains all possible properties and values from -// [ImageEditPartialImageEvent], [ImageEditCompletedEvent]. -// -// Use the [ImageEditStreamEventUnion.AsAny] method to switch on the variant. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -type ImageEditStreamEventUnion struct { - B64JSON string `json:"b64_json"` - Background string `json:"background"` - CreatedAt int64 `json:"created_at"` - OutputFormat string `json:"output_format"` - // This field is from variant [ImageEditPartialImageEvent]. - PartialImageIndex int64 `json:"partial_image_index"` - Quality string `json:"quality"` - Size string `json:"size"` - // Any of "image_edit.partial_image", "image_edit.completed". - Type string `json:"type"` - // This field is from variant [ImageEditCompletedEvent]. - Usage ImageEditCompletedEventUsage `json:"usage"` - JSON struct { - B64JSON respjson.Field - Background respjson.Field - CreatedAt respjson.Field - OutputFormat respjson.Field - PartialImageIndex respjson.Field - Quality respjson.Field - Size respjson.Field - Type respjson.Field - Usage respjson.Field - raw string - } `json:"-"` -} - -// anyImageEditStreamEvent is implemented by each variant of -// [ImageEditStreamEventUnion] to add type safety for the return type of -// [ImageEditStreamEventUnion.AsAny] -type anyImageEditStreamEvent interface { - implImageEditStreamEventUnion() -} - -func (ImageEditPartialImageEvent) implImageEditStreamEventUnion() {} -func (ImageEditCompletedEvent) implImageEditStreamEventUnion() {} - -// Use the following switch statement to find the correct variant -// -// switch variant := ImageEditStreamEventUnion.AsAny().(type) { -// case openai.ImageEditPartialImageEvent: -// case openai.ImageEditCompletedEvent: -// default: -// fmt.Errorf("no variant present") -// } -func (u ImageEditStreamEventUnion) AsAny() anyImageEditStreamEvent { - switch u.Type { - case "image_edit.partial_image": - return u.AsImageEditPartialImage() - case "image_edit.completed": - return u.AsImageEditCompleted() - } - return nil -} - -func (u ImageEditStreamEventUnion) AsImageEditPartialImage() (v ImageEditPartialImageEvent) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u ImageEditStreamEventUnion) AsImageEditCompleted() (v ImageEditCompletedEvent) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -// Returns the unmodified JSON received from the API -func (u ImageEditStreamEventUnion) RawJSON() string { return u.JSON.raw } - -func (r *ImageEditStreamEventUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Emitted when image generation has completed and the final image is available. -type ImageGenCompletedEvent struct { - // Base64-encoded image data, suitable for rendering as an image. - B64JSON string `json:"b64_json,required"` - // The background setting for the generated image. - // - // Any of "transparent", "opaque", "auto". - Background ImageGenCompletedEventBackground `json:"background,required"` - // The Unix timestamp when the event was created. - CreatedAt int64 `json:"created_at,required"` - // The output format for the generated image. - // - // Any of "png", "webp", "jpeg". - OutputFormat ImageGenCompletedEventOutputFormat `json:"output_format,required"` - // The quality setting for the generated image. - // - // Any of "low", "medium", "high", "auto". - Quality ImageGenCompletedEventQuality `json:"quality,required"` - // The size of the generated image. - // - // Any of "1024x1024", "1024x1536", "1536x1024", "auto". - Size ImageGenCompletedEventSize `json:"size,required"` - // The type of the event. Always `image_generation.completed`. - Type constant.ImageGenerationCompleted `json:"type,required"` - // For `gpt-image-1` only, the token usage information for the image generation. - Usage ImageGenCompletedEventUsage `json:"usage,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - B64JSON respjson.Field - Background respjson.Field - CreatedAt respjson.Field - OutputFormat respjson.Field - Quality respjson.Field - Size respjson.Field - Type respjson.Field - Usage respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ImageGenCompletedEvent) RawJSON() string { return r.JSON.raw } -func (r *ImageGenCompletedEvent) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The background setting for the generated image. -type ImageGenCompletedEventBackground string - -const ( - ImageGenCompletedEventBackgroundTransparent ImageGenCompletedEventBackground = "transparent" - ImageGenCompletedEventBackgroundOpaque ImageGenCompletedEventBackground = "opaque" - ImageGenCompletedEventBackgroundAuto ImageGenCompletedEventBackground = "auto" -) - -// The output format for the generated image. -type ImageGenCompletedEventOutputFormat string - -const ( - ImageGenCompletedEventOutputFormatPNG ImageGenCompletedEventOutputFormat = "png" - ImageGenCompletedEventOutputFormatWebP ImageGenCompletedEventOutputFormat = "webp" - ImageGenCompletedEventOutputFormatJPEG ImageGenCompletedEventOutputFormat = "jpeg" -) - -// The quality setting for the generated image. -type ImageGenCompletedEventQuality string - -const ( - ImageGenCompletedEventQualityLow ImageGenCompletedEventQuality = "low" - ImageGenCompletedEventQualityMedium ImageGenCompletedEventQuality = "medium" - ImageGenCompletedEventQualityHigh ImageGenCompletedEventQuality = "high" - ImageGenCompletedEventQualityAuto ImageGenCompletedEventQuality = "auto" -) - -// The size of the generated image. -type ImageGenCompletedEventSize string - -const ( - ImageGenCompletedEventSize1024x1024 ImageGenCompletedEventSize = "1024x1024" - ImageGenCompletedEventSize1024x1536 ImageGenCompletedEventSize = "1024x1536" - ImageGenCompletedEventSize1536x1024 ImageGenCompletedEventSize = "1536x1024" - ImageGenCompletedEventSizeAuto ImageGenCompletedEventSize = "auto" -) - -// For `gpt-image-1` only, the token usage information for the image generation. -type ImageGenCompletedEventUsage struct { - // The number of tokens (images and text) in the input prompt. - InputTokens int64 `json:"input_tokens,required"` - // The input tokens detailed information for the image generation. - InputTokensDetails ImageGenCompletedEventUsageInputTokensDetails `json:"input_tokens_details,required"` - // The number of image tokens in the output image. - OutputTokens int64 `json:"output_tokens,required"` - // The total number of tokens (images and text) used for the image generation. - TotalTokens int64 `json:"total_tokens,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - InputTokens respjson.Field - InputTokensDetails respjson.Field - OutputTokens respjson.Field - TotalTokens respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ImageGenCompletedEventUsage) RawJSON() string { return r.JSON.raw } -func (r *ImageGenCompletedEventUsage) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The input tokens detailed information for the image generation. -type ImageGenCompletedEventUsageInputTokensDetails struct { - // The number of image tokens in the input prompt. - ImageTokens int64 `json:"image_tokens,required"` - // The number of text tokens in the input prompt. - TextTokens int64 `json:"text_tokens,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ImageTokens respjson.Field - TextTokens respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ImageGenCompletedEventUsageInputTokensDetails) RawJSON() string { return r.JSON.raw } -func (r *ImageGenCompletedEventUsageInputTokensDetails) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Emitted when a partial image is available during image generation streaming. -type ImageGenPartialImageEvent struct { - // Base64-encoded partial image data, suitable for rendering as an image. - B64JSON string `json:"b64_json,required"` - // The background setting for the requested image. - // - // Any of "transparent", "opaque", "auto". - Background ImageGenPartialImageEventBackground `json:"background,required"` - // The Unix timestamp when the event was created. - CreatedAt int64 `json:"created_at,required"` - // The output format for the requested image. - // - // Any of "png", "webp", "jpeg". - OutputFormat ImageGenPartialImageEventOutputFormat `json:"output_format,required"` - // 0-based index for the partial image (streaming). - PartialImageIndex int64 `json:"partial_image_index,required"` - // The quality setting for the requested image. - // - // Any of "low", "medium", "high", "auto". - Quality ImageGenPartialImageEventQuality `json:"quality,required"` - // The size of the requested image. - // - // Any of "1024x1024", "1024x1536", "1536x1024", "auto". - Size ImageGenPartialImageEventSize `json:"size,required"` - // The type of the event. Always `image_generation.partial_image`. - Type constant.ImageGenerationPartialImage `json:"type,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - B64JSON respjson.Field - Background respjson.Field - CreatedAt respjson.Field - OutputFormat respjson.Field - PartialImageIndex respjson.Field - Quality respjson.Field - Size respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ImageGenPartialImageEvent) RawJSON() string { return r.JSON.raw } -func (r *ImageGenPartialImageEvent) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The background setting for the requested image. -type ImageGenPartialImageEventBackground string - -const ( - ImageGenPartialImageEventBackgroundTransparent ImageGenPartialImageEventBackground = "transparent" - ImageGenPartialImageEventBackgroundOpaque ImageGenPartialImageEventBackground = "opaque" - ImageGenPartialImageEventBackgroundAuto ImageGenPartialImageEventBackground = "auto" -) - -// The output format for the requested image. -type ImageGenPartialImageEventOutputFormat string - -const ( - ImageGenPartialImageEventOutputFormatPNG ImageGenPartialImageEventOutputFormat = "png" - ImageGenPartialImageEventOutputFormatWebP ImageGenPartialImageEventOutputFormat = "webp" - ImageGenPartialImageEventOutputFormatJPEG ImageGenPartialImageEventOutputFormat = "jpeg" -) - -// The quality setting for the requested image. -type ImageGenPartialImageEventQuality string - -const ( - ImageGenPartialImageEventQualityLow ImageGenPartialImageEventQuality = "low" - ImageGenPartialImageEventQualityMedium ImageGenPartialImageEventQuality = "medium" - ImageGenPartialImageEventQualityHigh ImageGenPartialImageEventQuality = "high" - ImageGenPartialImageEventQualityAuto ImageGenPartialImageEventQuality = "auto" -) - -// The size of the requested image. -type ImageGenPartialImageEventSize string - -const ( - ImageGenPartialImageEventSize1024x1024 ImageGenPartialImageEventSize = "1024x1024" - ImageGenPartialImageEventSize1024x1536 ImageGenPartialImageEventSize = "1024x1536" - ImageGenPartialImageEventSize1536x1024 ImageGenPartialImageEventSize = "1536x1024" - ImageGenPartialImageEventSizeAuto ImageGenPartialImageEventSize = "auto" -) - -// ImageGenStreamEventUnion contains all possible properties and values from -// [ImageGenPartialImageEvent], [ImageGenCompletedEvent]. -// -// Use the [ImageGenStreamEventUnion.AsAny] method to switch on the variant. -// -// Use the methods beginning with 'As' to cast the union to one of its variants. -type ImageGenStreamEventUnion struct { - B64JSON string `json:"b64_json"` - Background string `json:"background"` - CreatedAt int64 `json:"created_at"` - OutputFormat string `json:"output_format"` - // This field is from variant [ImageGenPartialImageEvent]. - PartialImageIndex int64 `json:"partial_image_index"` - Quality string `json:"quality"` - Size string `json:"size"` - // Any of "image_generation.partial_image", "image_generation.completed". - Type string `json:"type"` - // This field is from variant [ImageGenCompletedEvent]. - Usage ImageGenCompletedEventUsage `json:"usage"` - JSON struct { - B64JSON respjson.Field - Background respjson.Field - CreatedAt respjson.Field - OutputFormat respjson.Field - PartialImageIndex respjson.Field - Quality respjson.Field - Size respjson.Field - Type respjson.Field - Usage respjson.Field - raw string - } `json:"-"` -} - -// anyImageGenStreamEvent is implemented by each variant of -// [ImageGenStreamEventUnion] to add type safety for the return type of -// [ImageGenStreamEventUnion.AsAny] -type anyImageGenStreamEvent interface { - implImageGenStreamEventUnion() -} - -func (ImageGenPartialImageEvent) implImageGenStreamEventUnion() {} -func (ImageGenCompletedEvent) implImageGenStreamEventUnion() {} - -// Use the following switch statement to find the correct variant -// -// switch variant := ImageGenStreamEventUnion.AsAny().(type) { -// case openai.ImageGenPartialImageEvent: -// case openai.ImageGenCompletedEvent: -// default: -// fmt.Errorf("no variant present") -// } -func (u ImageGenStreamEventUnion) AsAny() anyImageGenStreamEvent { - switch u.Type { - case "image_generation.partial_image": - return u.AsImageGenerationPartialImage() - case "image_generation.completed": - return u.AsImageGenerationCompleted() - } - return nil -} - -func (u ImageGenStreamEventUnion) AsImageGenerationPartialImage() (v ImageGenPartialImageEvent) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -func (u ImageGenStreamEventUnion) AsImageGenerationCompleted() (v ImageGenCompletedEvent) { - apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v) - return -} - -// Returns the unmodified JSON received from the API -func (u ImageGenStreamEventUnion) RawJSON() string { return u.JSON.raw } - -func (r *ImageGenStreamEventUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type ImageModel = string - -const ( - ImageModelDallE2 ImageModel = "dall-e-2" - ImageModelDallE3 ImageModel = "dall-e-3" - ImageModelGPTImage1 ImageModel = "gpt-image-1" -) - -// The response from the image generation endpoint. -type ImagesResponse struct { - // The Unix timestamp (in seconds) of when the image was created. - Created int64 `json:"created,required"` - // The background parameter used for the image generation. Either `transparent` or - // `opaque`. - // - // Any of "transparent", "opaque". - Background ImagesResponseBackground `json:"background"` - // The list of generated images. - Data []Image `json:"data"` - // The output format of the image generation. Either `png`, `webp`, or `jpeg`. - // - // Any of "png", "webp", "jpeg". - OutputFormat ImagesResponseOutputFormat `json:"output_format"` - // The quality of the image generated. Either `low`, `medium`, or `high`. - // - // Any of "low", "medium", "high". - Quality ImagesResponseQuality `json:"quality"` - // The size of the image generated. Either `1024x1024`, `1024x1536`, or - // `1536x1024`. - // - // Any of "1024x1024", "1024x1536", "1536x1024". - Size ImagesResponseSize `json:"size"` - // For `gpt-image-1` only, the token usage information for the image generation. - Usage ImagesResponseUsage `json:"usage"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Created respjson.Field - Background respjson.Field - Data respjson.Field - OutputFormat respjson.Field - Quality respjson.Field - Size respjson.Field - Usage respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ImagesResponse) RawJSON() string { return r.JSON.raw } -func (r *ImagesResponse) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The background parameter used for the image generation. Either `transparent` or -// `opaque`. -type ImagesResponseBackground string - -const ( - ImagesResponseBackgroundTransparent ImagesResponseBackground = "transparent" - ImagesResponseBackgroundOpaque ImagesResponseBackground = "opaque" -) - -// The output format of the image generation. Either `png`, `webp`, or `jpeg`. -type ImagesResponseOutputFormat string - -const ( - ImagesResponseOutputFormatPNG ImagesResponseOutputFormat = "png" - ImagesResponseOutputFormatWebP ImagesResponseOutputFormat = "webp" - ImagesResponseOutputFormatJPEG ImagesResponseOutputFormat = "jpeg" -) - -// The quality of the image generated. Either `low`, `medium`, or `high`. -type ImagesResponseQuality string - -const ( - ImagesResponseQualityLow ImagesResponseQuality = "low" - ImagesResponseQualityMedium ImagesResponseQuality = "medium" - ImagesResponseQualityHigh ImagesResponseQuality = "high" -) - -// The size of the image generated. Either `1024x1024`, `1024x1536`, or -// `1536x1024`. -type ImagesResponseSize string - -const ( - ImagesResponseSize1024x1024 ImagesResponseSize = "1024x1024" - ImagesResponseSize1024x1536 ImagesResponseSize = "1024x1536" - ImagesResponseSize1536x1024 ImagesResponseSize = "1536x1024" -) - -// For `gpt-image-1` only, the token usage information for the image generation. -type ImagesResponseUsage struct { - // The number of tokens (images and text) in the input prompt. - InputTokens int64 `json:"input_tokens,required"` - // The input tokens detailed information for the image generation. - InputTokensDetails ImagesResponseUsageInputTokensDetails `json:"input_tokens_details,required"` - // The number of output tokens generated by the model. - OutputTokens int64 `json:"output_tokens,required"` - // The total number of tokens (images and text) used for the image generation. - TotalTokens int64 `json:"total_tokens,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - InputTokens respjson.Field - InputTokensDetails respjson.Field - OutputTokens respjson.Field - TotalTokens respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ImagesResponseUsage) RawJSON() string { return r.JSON.raw } -func (r *ImagesResponseUsage) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// The input tokens detailed information for the image generation. -type ImagesResponseUsageInputTokensDetails struct { - // The number of image tokens in the input prompt. - ImageTokens int64 `json:"image_tokens,required"` - // The number of text tokens in the input prompt. - TextTokens int64 `json:"text_tokens,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - ImageTokens respjson.Field - TextTokens respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` -} - -// Returns the unmodified JSON received from the API -func (r ImagesResponseUsageInputTokensDetails) RawJSON() string { return r.JSON.raw } -func (r *ImagesResponseUsageInputTokensDetails) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -type ImageNewVariationParams struct { - // The image to use as the basis for the variation(s). Must be a valid PNG file, - // less than 4MB, and square. - Image io.Reader `json:"image,omitzero,required" format:"binary"` - // The number of images to generate. Must be between 1 and 10. - N param.Opt[int64] `json:"n,omitzero"` - // A unique identifier representing your end-user, which can help OpenAI to monitor - // and detect abuse. - // [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). - User param.Opt[string] `json:"user,omitzero"` - // The model to use for image generation. Only `dall-e-2` is supported at this - // time. - Model ImageModel `json:"model,omitzero"` - // 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. - // - // Any of "url", "b64_json". - ResponseFormat ImageNewVariationParamsResponseFormat `json:"response_format,omitzero"` - // The size of the generated images. Must be one of `256x256`, `512x512`, or - // `1024x1024`. - // - // Any of "256x256", "512x512", "1024x1024". - Size ImageNewVariationParamsSize `json:"size,omitzero"` - paramObj -} - -func (r ImageNewVariationParams) MarshalMultipart() (data []byte, contentType string, err error) { - buf := bytes.NewBuffer(nil) - writer := multipart.NewWriter(buf) - err = apiform.MarshalRoot(r, writer) - if err == nil { - err = apiform.WriteExtras(writer, r.ExtraFields()) - } - if err != nil { - writer.Close() - return nil, "", err - } - err = writer.Close() - if err != nil { - return nil, "", err - } - return buf.Bytes(), writer.FormDataContentType(), nil -} - -// 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. -type ImageNewVariationParamsResponseFormat string - -const ( - ImageNewVariationParamsResponseFormatURL ImageNewVariationParamsResponseFormat = "url" - ImageNewVariationParamsResponseFormatB64JSON ImageNewVariationParamsResponseFormat = "b64_json" -) - -// The size of the generated images. Must be one of `256x256`, `512x512`, or -// `1024x1024`. -type ImageNewVariationParamsSize string - -const ( - ImageNewVariationParamsSize256x256 ImageNewVariationParamsSize = "256x256" - ImageNewVariationParamsSize512x512 ImageNewVariationParamsSize = "512x512" - ImageNewVariationParamsSize1024x1024 ImageNewVariationParamsSize = "1024x1024" -) - -type ImageEditParams struct { - // The image(s) to edit. Must be a supported image file or an array of images. - // - // For `gpt-image-1`, each image should be a `png`, `webp`, or `jpg` file less than - // 50MB. You can provide up to 16 images. - // - // For `dall-e-2`, you can only provide one image, and it should be a square `png` - // file less than 4MB. - Image ImageEditParamsImageUnion `json:"image,omitzero,required" format:"binary"` - // A text description of the desired image(s). The maximum length is 1000 - // characters for `dall-e-2`, and 32000 characters for `gpt-image-1`. - Prompt string `json:"prompt,required"` - // The number of images to generate. Must be between 1 and 10. - N param.Opt[int64] `json:"n,omitzero"` - // The compression level (0-100%) for the generated images. This parameter is only - // supported for `gpt-image-1` with the `webp` or `jpeg` output formats, and - // defaults to 100. - OutputCompression param.Opt[int64] `json:"output_compression,omitzero"` - // The number of partial images to generate. This parameter is used for streaming - // responses that return partial images. Value must be between 0 and 3. When set to - // 0, the response will be a single image sent in one streaming event. - // - // Note that the final image may be sent before the full number of partial images - // are generated if the full image is generated more quickly. - PartialImages param.Opt[int64] `json:"partial_images,omitzero"` - // A unique identifier representing your end-user, which can help OpenAI to monitor - // and detect abuse. - // [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). - User param.Opt[string] `json:"user,omitzero"` - // Allows to set transparency for the background of the generated image(s). This - // parameter is only supported for `gpt-image-1`. Must be one of `transparent`, - // `opaque` or `auto` (default value). When `auto` is used, the model will - // automatically determine the best background for the image. - // - // If `transparent`, the output format needs to support transparency, so it should - // be set to either `png` (default value) or `webp`. - // - // Any of "transparent", "opaque", "auto". - Background ImageEditParamsBackground `json:"background,omitzero"` - // Control how much effort the model will exert to match the style and features, - // especially facial features, of input images. This parameter is only supported - // for `gpt-image-1`. Supports `high` and `low`. Defaults to `low`. - // - // Any of "high", "low". - InputFidelity ImageEditParamsInputFidelity `json:"input_fidelity,omitzero"` - // The model to use for image generation. Only `dall-e-2` and `gpt-image-1` are - // supported. Defaults to `dall-e-2` unless a parameter specific to `gpt-image-1` - // is used. - Model ImageModel `json:"model,omitzero"` - // The format in which the generated images are returned. This parameter is only - // supported for `gpt-image-1`. Must be one of `png`, `jpeg`, or `webp`. The - // default value is `png`. - // - // Any of "png", "jpeg", "webp". - OutputFormat ImageEditParamsOutputFormat `json:"output_format,omitzero"` - // The quality of the image that will be generated. `high`, `medium` and `low` are - // only supported for `gpt-image-1`. `dall-e-2` only supports `standard` quality. - // Defaults to `auto`. - // - // Any of "standard", "low", "medium", "high", "auto". - Quality ImageEditParamsQuality `json:"quality,omitzero"` - // 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. This parameter is only supported for `dall-e-2`, as `gpt-image-1` - // will always return base64-encoded images. - // - // Any of "url", "b64_json". - ResponseFormat ImageEditParamsResponseFormat `json:"response_format,omitzero"` - // The size of the generated images. Must be one of `1024x1024`, `1536x1024` - // (landscape), `1024x1536` (portrait), or `auto` (default value) for - // `gpt-image-1`, and one of `256x256`, `512x512`, or `1024x1024` for `dall-e-2`. - // - // Any of "256x256", "512x512", "1024x1024", "1536x1024", "1024x1536", "auto". - Size ImageEditParamsSize `json:"size,omitzero"` - // An additional image whose fully transparent areas (e.g. where alpha is zero) - // indicate where `image` should be edited. If there are multiple images provided, - // the mask will be applied on the first image. Must be a valid PNG file, less than - // 4MB, and have the same dimensions as `image`. - Mask io.Reader `json:"mask,omitzero" format:"binary"` - paramObj -} - -func (r ImageEditParams) MarshalMultipart() (data []byte, contentType string, err error) { - buf := bytes.NewBuffer(nil) - writer := multipart.NewWriter(buf) - err = apiform.MarshalRoot(r, writer) - if err == nil { - err = apiform.WriteExtras(writer, r.ExtraFields()) - } - if err != nil { - writer.Close() - return nil, "", err - } - err = writer.Close() - if err != nil { - return nil, "", err - } - return buf.Bytes(), writer.FormDataContentType(), nil -} - -// Only one field can be non-zero. -// -// Use [param.IsOmitted] to confirm if a field is set. -type ImageEditParamsImageUnion struct { - OfFile io.Reader `json:",omitzero,inline"` - OfFileArray []io.Reader `json:",omitzero,inline"` - paramUnion -} - -func (u ImageEditParamsImageUnion) MarshalJSON() ([]byte, error) { - return param.MarshalUnion(u, u.OfFile, u.OfFileArray) -} -func (u *ImageEditParamsImageUnion) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, u) -} - -func (u *ImageEditParamsImageUnion) asAny() any { - if !param.IsOmitted(u.OfFile) { - return &u.OfFile - } else if !param.IsOmitted(u.OfFileArray) { - return &u.OfFileArray - } - return nil -} - -// Allows to set transparency for the background of the generated image(s). This -// parameter is only supported for `gpt-image-1`. Must be one of `transparent`, -// `opaque` or `auto` (default value). When `auto` is used, the model will -// automatically determine the best background for the image. -// -// If `transparent`, the output format needs to support transparency, so it should -// be set to either `png` (default value) or `webp`. -type ImageEditParamsBackground string - -const ( - ImageEditParamsBackgroundTransparent ImageEditParamsBackground = "transparent" - ImageEditParamsBackgroundOpaque ImageEditParamsBackground = "opaque" - ImageEditParamsBackgroundAuto ImageEditParamsBackground = "auto" -) - -// Control how much effort the model will exert to match the style and features, -// especially facial features, of input images. This parameter is only supported -// for `gpt-image-1`. Supports `high` and `low`. Defaults to `low`. -type ImageEditParamsInputFidelity string - -const ( - ImageEditParamsInputFidelityHigh ImageEditParamsInputFidelity = "high" - ImageEditParamsInputFidelityLow ImageEditParamsInputFidelity = "low" -) - -// The format in which the generated images are returned. This parameter is only -// supported for `gpt-image-1`. Must be one of `png`, `jpeg`, or `webp`. The -// default value is `png`. -type ImageEditParamsOutputFormat string - -const ( - ImageEditParamsOutputFormatPNG ImageEditParamsOutputFormat = "png" - ImageEditParamsOutputFormatJPEG ImageEditParamsOutputFormat = "jpeg" - ImageEditParamsOutputFormatWebP ImageEditParamsOutputFormat = "webp" -) - -// The quality of the image that will be generated. `high`, `medium` and `low` are -// only supported for `gpt-image-1`. `dall-e-2` only supports `standard` quality. -// Defaults to `auto`. -type ImageEditParamsQuality string - -const ( - ImageEditParamsQualityStandard ImageEditParamsQuality = "standard" - ImageEditParamsQualityLow ImageEditParamsQuality = "low" - ImageEditParamsQualityMedium ImageEditParamsQuality = "medium" - ImageEditParamsQualityHigh ImageEditParamsQuality = "high" - ImageEditParamsQualityAuto ImageEditParamsQuality = "auto" -) - -// 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. This parameter is only supported for `dall-e-2`, as `gpt-image-1` -// will always return base64-encoded images. -type ImageEditParamsResponseFormat string - -const ( - ImageEditParamsResponseFormatURL ImageEditParamsResponseFormat = "url" - ImageEditParamsResponseFormatB64JSON ImageEditParamsResponseFormat = "b64_json" -) - -// The size of the generated images. Must be one of `1024x1024`, `1536x1024` -// (landscape), `1024x1536` (portrait), or `auto` (default value) for -// `gpt-image-1`, and one of `256x256`, `512x512`, or `1024x1024` for `dall-e-2`. -type ImageEditParamsSize string - -const ( - ImageEditParamsSize256x256 ImageEditParamsSize = "256x256" - ImageEditParamsSize512x512 ImageEditParamsSize = "512x512" - ImageEditParamsSize1024x1024 ImageEditParamsSize = "1024x1024" - ImageEditParamsSize1536x1024 ImageEditParamsSize = "1536x1024" - ImageEditParamsSize1024x1536 ImageEditParamsSize = "1024x1536" - ImageEditParamsSizeAuto ImageEditParamsSize = "auto" -) - -type ImageGenerateParams struct { - // A text description of the desired image(s). The maximum length is 32000 - // characters for `gpt-image-1`, 1000 characters for `dall-e-2` and 4000 characters - // for `dall-e-3`. - Prompt string `json:"prompt,required"` - // The number of images to generate. Must be between 1 and 10. For `dall-e-3`, only - // `n=1` is supported. - N param.Opt[int64] `json:"n,omitzero"` - // The compression level (0-100%) for the generated images. This parameter is only - // supported for `gpt-image-1` with the `webp` or `jpeg` output formats, and - // defaults to 100. - OutputCompression param.Opt[int64] `json:"output_compression,omitzero"` - // The number of partial images to generate. This parameter is used for streaming - // responses that return partial images. Value must be between 0 and 3. When set to - // 0, the response will be a single image sent in one streaming event. - // - // Note that the final image may be sent before the full number of partial images - // are generated if the full image is generated more quickly. - PartialImages param.Opt[int64] `json:"partial_images,omitzero"` - // A unique identifier representing your end-user, which can help OpenAI to monitor - // and detect abuse. - // [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). - User param.Opt[string] `json:"user,omitzero"` - // Allows to set transparency for the background of the generated image(s). This - // parameter is only supported for `gpt-image-1`. Must be one of `transparent`, - // `opaque` or `auto` (default value). When `auto` is used, the model will - // automatically determine the best background for the image. - // - // If `transparent`, the output format needs to support transparency, so it should - // be set to either `png` (default value) or `webp`. - // - // Any of "transparent", "opaque", "auto". - Background ImageGenerateParamsBackground `json:"background,omitzero"` - // The model to use for image generation. One of `dall-e-2`, `dall-e-3`, or - // `gpt-image-1`. Defaults to `dall-e-2` unless a parameter specific to - // `gpt-image-1` is used. - Model ImageModel `json:"model,omitzero"` - // Control the content-moderation level for images generated by `gpt-image-1`. Must - // be either `low` for less restrictive filtering or `auto` (default value). - // - // Any of "low", "auto". - Moderation ImageGenerateParamsModeration `json:"moderation,omitzero"` - // The format in which the generated images are returned. This parameter is only - // supported for `gpt-image-1`. Must be one of `png`, `jpeg`, or `webp`. - // - // Any of "png", "jpeg", "webp". - OutputFormat ImageGenerateParamsOutputFormat `json:"output_format,omitzero"` - // The quality of the image that will be generated. - // - // - `auto` (default value) will automatically select the best quality for the - // given model. - // - `high`, `medium` and `low` are supported for `gpt-image-1`. - // - `hd` and `standard` are supported for `dall-e-3`. - // - `standard` is the only option for `dall-e-2`. - // - // Any of "standard", "hd", "low", "medium", "high", "auto". - Quality ImageGenerateParamsQuality `json:"quality,omitzero"` - // The format in which generated images with `dall-e-2` and `dall-e-3` are - // returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes - // after the image has been generated. This parameter isn't supported for - // `gpt-image-1` which will always return base64-encoded images. - // - // Any of "url", "b64_json". - ResponseFormat ImageGenerateParamsResponseFormat `json:"response_format,omitzero"` - // The size of the generated images. Must be one of `1024x1024`, `1536x1024` - // (landscape), `1024x1536` (portrait), or `auto` (default value) for - // `gpt-image-1`, one of `256x256`, `512x512`, or `1024x1024` for `dall-e-2`, and - // one of `1024x1024`, `1792x1024`, or `1024x1792` for `dall-e-3`. - // - // Any of "auto", "1024x1024", "1536x1024", "1024x1536", "256x256", "512x512", - // "1792x1024", "1024x1792". - Size ImageGenerateParamsSize `json:"size,omitzero"` - // The style of the generated images. This parameter is only supported for - // `dall-e-3`. 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. - // - // Any of "vivid", "natural". - Style ImageGenerateParamsStyle `json:"style,omitzero"` - paramObj -} - -func (r ImageGenerateParams) MarshalJSON() (data []byte, err error) { - type shadow ImageGenerateParams - return param.MarshalObject(r, (*shadow)(&r)) -} -func (r *ImageGenerateParams) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -// Allows to set transparency for the background of the generated image(s). This -// parameter is only supported for `gpt-image-1`. Must be one of `transparent`, -// `opaque` or `auto` (default value). When `auto` is used, the model will -// automatically determine the best background for the image. -// -// If `transparent`, the output format needs to support transparency, so it should -// be set to either `png` (default value) or `webp`. -type ImageGenerateParamsBackground string - -const ( - ImageGenerateParamsBackgroundTransparent ImageGenerateParamsBackground = "transparent" - ImageGenerateParamsBackgroundOpaque ImageGenerateParamsBackground = "opaque" - ImageGenerateParamsBackgroundAuto ImageGenerateParamsBackground = "auto" -) - -// Control the content-moderation level for images generated by `gpt-image-1`. Must -// be either `low` for less restrictive filtering or `auto` (default value). -type ImageGenerateParamsModeration string - -const ( - ImageGenerateParamsModerationLow ImageGenerateParamsModeration = "low" - ImageGenerateParamsModerationAuto ImageGenerateParamsModeration = "auto" -) - -// The format in which the generated images are returned. This parameter is only -// supported for `gpt-image-1`. Must be one of `png`, `jpeg`, or `webp`. -type ImageGenerateParamsOutputFormat string - -const ( - ImageGenerateParamsOutputFormatPNG ImageGenerateParamsOutputFormat = "png" - ImageGenerateParamsOutputFormatJPEG ImageGenerateParamsOutputFormat = "jpeg" - ImageGenerateParamsOutputFormatWebP ImageGenerateParamsOutputFormat = "webp" -) - -// The quality of the image that will be generated. -// -// - `auto` (default value) will automatically select the best quality for the -// given model. -// - `high`, `medium` and `low` are supported for `gpt-image-1`. -// - `hd` and `standard` are supported for `dall-e-3`. -// - `standard` is the only option for `dall-e-2`. -type ImageGenerateParamsQuality string - -const ( - ImageGenerateParamsQualityStandard ImageGenerateParamsQuality = "standard" - ImageGenerateParamsQualityHD ImageGenerateParamsQuality = "hd" - ImageGenerateParamsQualityLow ImageGenerateParamsQuality = "low" - ImageGenerateParamsQualityMedium ImageGenerateParamsQuality = "medium" - ImageGenerateParamsQualityHigh ImageGenerateParamsQuality = "high" - ImageGenerateParamsQualityAuto ImageGenerateParamsQuality = "auto" -) - -// The format in which generated images with `dall-e-2` and `dall-e-3` are -// returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes -// after the image has been generated. This parameter isn't supported for -// `gpt-image-1` which will always return base64-encoded images. -type ImageGenerateParamsResponseFormat string - -const ( - ImageGenerateParamsResponseFormatURL ImageGenerateParamsResponseFormat = "url" - ImageGenerateParamsResponseFormatB64JSON ImageGenerateParamsResponseFormat = "b64_json" -) - -// The size of the generated images. Must be one of `1024x1024`, `1536x1024` -// (landscape), `1024x1536` (portrait), or `auto` (default value) for -// `gpt-image-1`, one of `256x256`, `512x512`, or `1024x1024` for `dall-e-2`, and -// one of `1024x1024`, `1792x1024`, or `1024x1792` for `dall-e-3`. -type ImageGenerateParamsSize string - -const ( - ImageGenerateParamsSizeAuto ImageGenerateParamsSize = "auto" - ImageGenerateParamsSize1024x1024 ImageGenerateParamsSize = "1024x1024" - ImageGenerateParamsSize1536x1024 ImageGenerateParamsSize = "1536x1024" - ImageGenerateParamsSize1024x1536 ImageGenerateParamsSize = "1024x1536" - ImageGenerateParamsSize256x256 ImageGenerateParamsSize = "256x256" - ImageGenerateParamsSize512x512 ImageGenerateParamsSize = "512x512" - ImageGenerateParamsSize1792x1024 ImageGenerateParamsSize = "1792x1024" - ImageGenerateParamsSize1024x1792 ImageGenerateParamsSize = "1024x1792" -) - -// The style of the generated images. This parameter is only supported for -// `dall-e-3`. 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. -type ImageGenerateParamsStyle string - -const ( - ImageGenerateParamsStyleVivid ImageGenerateParamsStyle = "vivid" - ImageGenerateParamsStyleNatural ImageGenerateParamsStyle = "natural" -) diff --git a/vendor/github.com/openai/openai-go/internal/apierror/apierror.go b/vendor/github.com/openai/openai-go/internal/apierror/apierror.go deleted file mode 100644 index 1b3b9e03..00000000 --- a/vendor/github.com/openai/openai-go/internal/apierror/apierror.go +++ /dev/null @@ -1,58 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -package apierror - -import ( - "fmt" - "net/http" - "net/http/httputil" - - "github.com/openai/openai-go/internal/apijson" - "github.com/openai/openai-go/packages/respjson" -) - -// Error represents an error that originates from the API, i.e. when a request is -// made and the API returns a response with a HTTP status code. Other errors are -// not wrapped by this SDK. -type Error struct { - Code string `json:"code,required"` - Message string `json:"message,required"` - Param string `json:"param,required"` - Type string `json:"type,required"` - // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. - JSON struct { - Code respjson.Field - Message respjson.Field - Param respjson.Field - Type respjson.Field - ExtraFields map[string]respjson.Field - raw string - } `json:"-"` - StatusCode int - Request *http.Request - Response *http.Response -} - -// Returns the unmodified JSON received from the API -func (r Error) RawJSON() string { return r.JSON.raw } -func (r *Error) UnmarshalJSON(data []byte) error { - return apijson.UnmarshalRoot(data, r) -} - -func (r *Error) Error() string { - // Attempt to re-populate the response body - return fmt.Sprintf("%s %q: %d %s %s", r.Request.Method, r.Request.URL, r.Response.StatusCode, http.StatusText(r.Response.StatusCode), r.JSON.raw) -} - -func (r *Error) DumpRequest(body bool) []byte { - if r.Request.GetBody != nil { - r.Request.Body, _ = r.Request.GetBody() - } - out, _ := httputil.DumpRequestOut(r.Request, body) - return out -} - -func (r *Error) DumpResponse(body bool) []byte { - out, _ := httputil.DumpResponse(r.Response, body) - return out -} diff --git a/vendor/github.com/openai/openai-go/internal/apiform/encoder.go b/vendor/github.com/openai/openai-go/internal/apiform/encoder.go deleted file mode 100644 index f1bd1649..00000000 --- a/vendor/github.com/openai/openai-go/internal/apiform/encoder.go +++ /dev/null @@ -1,465 +0,0 @@ -package apiform - -import ( - "fmt" - "io" - "mime/multipart" - "net/textproto" - "path" - "reflect" - "sort" - "strconv" - "strings" - "sync" - "time" - - "github.com/openai/openai-go/packages/param" -) - -var encoders sync.Map // map[encoderEntry]encoderFunc - -func Marshal(value any, writer *multipart.Writer) error { - e := &encoder{ - dateFormat: time.RFC3339, - arrayFmt: "brackets", - } - return e.marshal(value, writer) -} - -func MarshalRoot(value any, writer *multipart.Writer) error { - e := &encoder{ - root: true, - dateFormat: time.RFC3339, - arrayFmt: "brackets", - } - return e.marshal(value, writer) -} - -func MarshalWithSettings(value any, writer *multipart.Writer, arrayFormat string) error { - e := &encoder{ - arrayFmt: arrayFormat, - dateFormat: time.RFC3339, - } - return e.marshal(value, writer) -} - -type encoder struct { - arrayFmt string - dateFormat string - root bool -} - -type encoderFunc func(key string, value reflect.Value, writer *multipart.Writer) error - -type encoderField struct { - tag parsedStructTag - fn encoderFunc - idx []int -} - -type encoderEntry struct { - reflect.Type - dateFormat string - root bool -} - -func (e *encoder) marshal(value any, writer *multipart.Writer) error { - val := reflect.ValueOf(value) - if !val.IsValid() { - return nil - } - typ := val.Type() - enc := e.typeEncoder(typ) - return enc("", val, writer) -} - -func (e *encoder) typeEncoder(t reflect.Type) encoderFunc { - entry := encoderEntry{ - Type: t, - dateFormat: e.dateFormat, - root: e.root, - } - - if fi, ok := encoders.Load(entry); ok { - return fi.(encoderFunc) - } - - // To deal with recursive types, populate the map with an - // indirect func before we build it. This type waits on the - // real func (f) to be ready and then calls it. This indirect - // func is only used for recursive types. - var ( - wg sync.WaitGroup - f encoderFunc - ) - wg.Add(1) - fi, loaded := encoders.LoadOrStore(entry, encoderFunc(func(key string, v reflect.Value, writer *multipart.Writer) error { - wg.Wait() - return f(key, v, writer) - })) - if loaded { - return fi.(encoderFunc) - } - - // Compute the real encoder and replace the indirect func with it. - f = e.newTypeEncoder(t) - wg.Done() - encoders.Store(entry, f) - return f -} - -func (e *encoder) newTypeEncoder(t reflect.Type) encoderFunc { - if t.ConvertibleTo(reflect.TypeOf(time.Time{})) { - return e.newTimeTypeEncoder() - } - if t.Implements(reflect.TypeOf((*io.Reader)(nil)).Elem()) { - return e.newReaderTypeEncoder() - } - e.root = false - switch t.Kind() { - case reflect.Pointer: - inner := t.Elem() - - innerEncoder := e.typeEncoder(inner) - return func(key string, v reflect.Value, writer *multipart.Writer) error { - if !v.IsValid() || v.IsNil() { - return nil - } - return innerEncoder(key, v.Elem(), writer) - } - case reflect.Struct: - return e.newStructTypeEncoder(t) - case reflect.Slice, reflect.Array: - return e.newArrayTypeEncoder(t) - case reflect.Map: - return e.newMapEncoder(t) - case reflect.Interface: - return e.newInterfaceEncoder() - default: - return e.newPrimitiveTypeEncoder(t) - } -} - -func (e *encoder) newPrimitiveTypeEncoder(t reflect.Type) encoderFunc { - switch t.Kind() { - // Note that we could use `gjson` to encode these types but it would complicate our - // code more and this current code shouldn't cause any issues - case reflect.String: - return func(key string, v reflect.Value, writer *multipart.Writer) error { - return writer.WriteField(key, v.String()) - } - case reflect.Bool: - return func(key string, v reflect.Value, writer *multipart.Writer) error { - if v.Bool() { - return writer.WriteField(key, "true") - } - return writer.WriteField(key, "false") - } - case reflect.Int, reflect.Int16, reflect.Int32, reflect.Int64: - return func(key string, v reflect.Value, writer *multipart.Writer) error { - return writer.WriteField(key, strconv.FormatInt(v.Int(), 10)) - } - case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64: - return func(key string, v reflect.Value, writer *multipart.Writer) error { - return writer.WriteField(key, strconv.FormatUint(v.Uint(), 10)) - } - case reflect.Float32: - return func(key string, v reflect.Value, writer *multipart.Writer) error { - return writer.WriteField(key, strconv.FormatFloat(v.Float(), 'f', -1, 32)) - } - case reflect.Float64: - return func(key string, v reflect.Value, writer *multipart.Writer) error { - return writer.WriteField(key, strconv.FormatFloat(v.Float(), 'f', -1, 64)) - } - default: - return func(key string, v reflect.Value, writer *multipart.Writer) error { - return fmt.Errorf("unknown type received at primitive encoder: %s", t.String()) - } - } -} - -func arrayKeyEncoder(arrayFmt string) func(string, int) string { - var keyFn func(string, int) string - switch arrayFmt { - case "comma", "repeat": - keyFn = func(k string, _ int) string { return k } - case "brackets": - keyFn = func(key string, _ int) string { return key + "[]" } - case "indices:dots": - keyFn = func(k string, i int) string { - if k == "" { - return strconv.Itoa(i) - } - return k + "." + strconv.Itoa(i) - } - case "indices:brackets": - keyFn = func(k string, i int) string { - if k == "" { - return strconv.Itoa(i) - } - return k + "[" + strconv.Itoa(i) + "]" - } - } - return keyFn -} - -func (e *encoder) newArrayTypeEncoder(t reflect.Type) encoderFunc { - itemEncoder := e.typeEncoder(t.Elem()) - keyFn := arrayKeyEncoder(e.arrayFmt) - return func(key string, v reflect.Value, writer *multipart.Writer) error { - if keyFn == nil { - return fmt.Errorf("apiform: unsupported array format") - } - for i := 0; i < v.Len(); i++ { - err := itemEncoder(keyFn(key, i), v.Index(i), writer) - if err != nil { - return err - } - } - return nil - } -} - -func (e *encoder) newStructTypeEncoder(t reflect.Type) encoderFunc { - if t.Implements(reflect.TypeOf((*param.Optional)(nil)).Elem()) { - return e.newRichFieldTypeEncoder(t) - } - - for i := 0; i < t.NumField(); i++ { - if t.Field(i).Type == paramUnionType && t.Field(i).Anonymous { - return e.newStructUnionTypeEncoder(t) - } - } - - encoderFields := []encoderField{} - extraEncoder := (*encoderField)(nil) - - // This helper allows us to recursively collect field encoders into a flat - // array. The parameter `index` keeps track of the access patterns necessary - // to get to some field. - var collectEncoderFields func(r reflect.Type, index []int) - collectEncoderFields = func(r reflect.Type, index []int) { - for i := 0; i < r.NumField(); i++ { - idx := append(index, i) - field := t.FieldByIndex(idx) - if !field.IsExported() { - continue - } - // If this is an embedded struct, traverse one level deeper to extract - // the field and get their encoders as well. - if field.Anonymous { - collectEncoderFields(field.Type, idx) - continue - } - // If json tag is not present, then we skip, which is intentionally - // different behavior from the stdlib. - ptag, ok := parseFormStructTag(field) - if !ok { - continue - } - // We only want to support unexported field if they're tagged with - // `extras` because that field shouldn't be part of the public API. We - // also want to only keep the top level extras - if ptag.extras && len(index) == 0 { - extraEncoder = &encoderField{ptag, e.typeEncoder(field.Type.Elem()), idx} - continue - } - if ptag.name == "-" || ptag.name == "" { - continue - } - - dateFormat, ok := parseFormatStructTag(field) - oldFormat := e.dateFormat - if ok { - switch dateFormat { - case "date-time": - e.dateFormat = time.RFC3339 - case "date": - e.dateFormat = "2006-01-02" - } - } - - var encoderFn encoderFunc - if ptag.omitzero { - typeEncoderFn := e.typeEncoder(field.Type) - encoderFn = func(key string, value reflect.Value, writer *multipart.Writer) error { - if value.IsZero() { - return nil - } - return typeEncoderFn(key, value, writer) - } - } else { - encoderFn = e.typeEncoder(field.Type) - } - encoderFields = append(encoderFields, encoderField{ptag, encoderFn, idx}) - e.dateFormat = oldFormat - } - } - collectEncoderFields(t, []int{}) - - // Ensure deterministic output by sorting by lexicographic order - sort.Slice(encoderFields, func(i, j int) bool { - return encoderFields[i].tag.name < encoderFields[j].tag.name - }) - - return func(key string, value reflect.Value, writer *multipart.Writer) error { - if key != "" { - key = key + "." - } - - for _, ef := range encoderFields { - field := value.FieldByIndex(ef.idx) - err := ef.fn(key+ef.tag.name, field, writer) - if err != nil { - return err - } - } - - if extraEncoder != nil { - err := e.encodeMapEntries(key, value.FieldByIndex(extraEncoder.idx), writer) - if err != nil { - return err - } - } - - return nil - } -} - -var paramUnionType = reflect.TypeOf((*param.APIUnion)(nil)).Elem() - -func (e *encoder) newStructUnionTypeEncoder(t reflect.Type) encoderFunc { - var fieldEncoders []encoderFunc - for i := 0; i < t.NumField(); i++ { - field := t.Field(i) - if field.Type == paramUnionType && field.Anonymous { - fieldEncoders = append(fieldEncoders, nil) - continue - } - fieldEncoders = append(fieldEncoders, e.typeEncoder(field.Type)) - } - - return func(key string, value reflect.Value, writer *multipart.Writer) error { - for i := 0; i < t.NumField(); i++ { - if value.Field(i).Type() == paramUnionType { - continue - } - if !value.Field(i).IsZero() { - return fieldEncoders[i](key, value.Field(i), writer) - } - } - return fmt.Errorf("apiform: union %s has no field set", t.String()) - } -} - -func (e *encoder) newTimeTypeEncoder() encoderFunc { - format := e.dateFormat - return func(key string, value reflect.Value, writer *multipart.Writer) error { - return writer.WriteField(key, value.Convert(reflect.TypeOf(time.Time{})).Interface().(time.Time).Format(format)) - } -} - -func (e encoder) newInterfaceEncoder() encoderFunc { - return func(key string, value reflect.Value, writer *multipart.Writer) error { - value = value.Elem() - if !value.IsValid() { - return nil - } - return e.typeEncoder(value.Type())(key, value, writer) - } -} - -var quoteEscaper = strings.NewReplacer("\\", "\\\\", `"`, "\\\"") - -func escapeQuotes(s string) string { - return quoteEscaper.Replace(s) -} - -func (e *encoder) newReaderTypeEncoder() encoderFunc { - return func(key string, value reflect.Value, writer *multipart.Writer) error { - reader, ok := value.Convert(reflect.TypeOf((*io.Reader)(nil)).Elem()).Interface().(io.Reader) - if !ok { - return nil - } - filename := "anonymous_file" - contentType := "application/octet-stream" - if named, ok := reader.(interface{ Filename() string }); ok { - filename = named.Filename() - } else if named, ok := reader.(interface{ Name() string }); ok { - filename = path.Base(named.Name()) - } - if typed, ok := reader.(interface{ ContentType() string }); ok { - contentType = typed.ContentType() - } - - // Below is taken almost 1-for-1 from [multipart.CreateFormFile] - h := make(textproto.MIMEHeader) - h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="%s"; filename="%s"`, escapeQuotes(key), escapeQuotes(filename))) - h.Set("Content-Type", contentType) - filewriter, err := writer.CreatePart(h) - if err != nil { - return err - } - _, err = io.Copy(filewriter, reader) - return err - } -} - -// Given a []byte of json (may either be an empty object or an object that already contains entries) -// encode all of the entries in the map to the json byte array. -func (e *encoder) encodeMapEntries(key string, v reflect.Value, writer *multipart.Writer) error { - type mapPair struct { - key string - value reflect.Value - } - - if key != "" { - key = key + "." - } - - pairs := []mapPair{} - - iter := v.MapRange() - for iter.Next() { - if iter.Key().Type().Kind() == reflect.String { - pairs = append(pairs, mapPair{key: iter.Key().String(), value: iter.Value()}) - } else { - return fmt.Errorf("cannot encode a map with a non string key") - } - } - - // Ensure deterministic output - sort.Slice(pairs, func(i, j int) bool { - return pairs[i].key < pairs[j].key - }) - - elementEncoder := e.typeEncoder(v.Type().Elem()) - for _, p := range pairs { - err := elementEncoder(key+string(p.key), p.value, writer) - if err != nil { - return err - } - } - - return nil -} - -func (e *encoder) newMapEncoder(_ reflect.Type) encoderFunc { - return func(key string, value reflect.Value, writer *multipart.Writer) error { - return e.encodeMapEntries(key, value, writer) - } -} - -func WriteExtras(writer *multipart.Writer, extras map[string]any) (err error) { - for k, v := range extras { - str, ok := v.(string) - if !ok { - break - } - err = writer.WriteField(k, str) - if err != nil { - break - } - } - return -} diff --git a/vendor/github.com/openai/openai-go/internal/apiform/form.go b/vendor/github.com/openai/openai-go/internal/apiform/form.go deleted file mode 100644 index 5445116e..00000000 --- a/vendor/github.com/openai/openai-go/internal/apiform/form.go +++ /dev/null @@ -1,5 +0,0 @@ -package apiform - -type Marshaler interface { - MarshalMultipart() ([]byte, string, error) -} diff --git a/vendor/github.com/openai/openai-go/internal/apiform/richparam.go b/vendor/github.com/openai/openai-go/internal/apiform/richparam.go deleted file mode 100644 index 690a87b7..00000000 --- a/vendor/github.com/openai/openai-go/internal/apiform/richparam.go +++ /dev/null @@ -1,20 +0,0 @@ -package apiform - -import ( - "github.com/openai/openai-go/packages/param" - "mime/multipart" - "reflect" -) - -func (e *encoder) newRichFieldTypeEncoder(t reflect.Type) encoderFunc { - f, _ := t.FieldByName("Value") - enc := e.newPrimitiveTypeEncoder(f.Type) - return func(key string, value reflect.Value, writer *multipart.Writer) error { - if opt, ok := value.Interface().(param.Optional); ok && opt.Valid() { - return enc(key, value.FieldByIndex(f.Index), writer) - } else if ok && param.IsNull(opt) { - return writer.WriteField(key, "null") - } - return nil - } -} diff --git a/vendor/github.com/openai/openai-go/internal/apiform/tag.go b/vendor/github.com/openai/openai-go/internal/apiform/tag.go deleted file mode 100644 index 736fc1ea..00000000 --- a/vendor/github.com/openai/openai-go/internal/apiform/tag.go +++ /dev/null @@ -1,51 +0,0 @@ -package apiform - -import ( - "reflect" - "strings" -) - -const jsonStructTag = "json" -const formStructTag = "form" -const formatStructTag = "format" - -type parsedStructTag struct { - name string - required bool - extras bool - metadata bool - omitzero bool -} - -func parseFormStructTag(field reflect.StructField) (tag parsedStructTag, ok bool) { - raw, ok := field.Tag.Lookup(formStructTag) - if !ok { - raw, ok = field.Tag.Lookup(jsonStructTag) - } - if !ok { - return - } - parts := strings.Split(raw, ",") - if len(parts) == 0 { - return tag, false - } - tag.name = parts[0] - for _, part := range parts[1:] { - switch part { - case "required": - tag.required = true - case "extras": - tag.extras = true - case "metadata": - tag.metadata = true - case "omitzero": - tag.omitzero = true - } - } - return -} - -func parseFormatStructTag(field reflect.StructField) (format string, ok bool) { - format, ok = field.Tag.Lookup(formatStructTag) - return -} diff --git a/vendor/github.com/openai/openai-go/internal/apijson/decoder.go b/vendor/github.com/openai/openai-go/internal/apijson/decoder.go deleted file mode 100644 index b3f1bf7a..00000000 --- a/vendor/github.com/openai/openai-go/internal/apijson/decoder.go +++ /dev/null @@ -1,691 +0,0 @@ -// The deserialization algorithm from apijson may be subject to improvements -// between minor versions, particularly with respect to calling [json.Unmarshal] -// into param unions. - -package apijson - -import ( - "encoding/json" - "fmt" - "github.com/openai/openai-go/packages/param" - "reflect" - "strconv" - "sync" - "time" - "unsafe" - - "github.com/tidwall/gjson" -) - -// decoders is a synchronized map with roughly the following type: -// map[reflect.Type]decoderFunc -var decoders sync.Map - -// Unmarshal is similar to [encoding/json.Unmarshal] and parses the JSON-encoded -// data and stores it in the given pointer. -func Unmarshal(raw []byte, to any) error { - d := &decoderBuilder{dateFormat: time.RFC3339} - return d.unmarshal(raw, to) -} - -// UnmarshalRoot is like Unmarshal, but doesn't try to call MarshalJSON on the -// root element. Useful if a struct's UnmarshalJSON is overrode to use the -// behavior of this encoder versus the standard library. -func UnmarshalRoot(raw []byte, to any) error { - d := &decoderBuilder{dateFormat: time.RFC3339, root: true} - return d.unmarshal(raw, to) -} - -// decoderBuilder contains the 'compile-time' state of the decoder. -type decoderBuilder struct { - // Whether or not this is the first element and called by [UnmarshalRoot], see - // the documentation there to see why this is necessary. - root bool - // The dateFormat (a format string for [time.Format]) which is chosen by the - // last struct tag that was seen. - dateFormat string -} - -// decoderState contains the 'run-time' state of the decoder. -type decoderState struct { - strict bool - exactness exactness - validator *validationEntry -} - -// Exactness refers to how close to the type the result was if deserialization -// was successful. This is useful in deserializing unions, where you want to try -// each entry, first with strict, then with looser validation, without actually -// having to do a lot of redundant work by marshalling twice (or maybe even more -// times). -type exactness int8 - -const ( - // Some values had to fudged a bit, for example by converting a string to an - // int, or an enum with extra values. - loose exactness = iota - // There are some extra arguments, but other wise it matches the union. - extras - // Exactly right. - exact -) - -type decoderFunc func(node gjson.Result, value reflect.Value, state *decoderState) error - -type decoderField struct { - tag parsedStructTag - fn decoderFunc - idx []int - goname string -} - -type decoderEntry struct { - reflect.Type - dateFormat string - root bool -} - -func (d *decoderBuilder) unmarshal(raw []byte, to any) error { - value := reflect.ValueOf(to).Elem() - result := gjson.ParseBytes(raw) - if !value.IsValid() { - return fmt.Errorf("apijson: cannot marshal into invalid value") - } - return d.typeDecoder(value.Type())(result, value, &decoderState{strict: false, exactness: exact}) -} - -// unmarshalWithExactness is used for internal testing purposes. -func (d *decoderBuilder) unmarshalWithExactness(raw []byte, to any) (exactness, error) { - value := reflect.ValueOf(to).Elem() - result := gjson.ParseBytes(raw) - if !value.IsValid() { - return 0, fmt.Errorf("apijson: cannot marshal into invalid value") - } - state := decoderState{strict: false, exactness: exact} - err := d.typeDecoder(value.Type())(result, value, &state) - return state.exactness, err -} - -func (d *decoderBuilder) typeDecoder(t reflect.Type) decoderFunc { - entry := decoderEntry{ - Type: t, - dateFormat: d.dateFormat, - root: d.root, - } - - if fi, ok := decoders.Load(entry); ok { - return fi.(decoderFunc) - } - - // To deal with recursive types, populate the map with an - // indirect func before we build it. This type waits on the - // real func (f) to be ready and then calls it. This indirect - // func is only used for recursive types. - var ( - wg sync.WaitGroup - f decoderFunc - ) - wg.Add(1) - fi, loaded := decoders.LoadOrStore(entry, decoderFunc(func(node gjson.Result, v reflect.Value, state *decoderState) error { - wg.Wait() - return f(node, v, state) - })) - if loaded { - return fi.(decoderFunc) - } - - // Compute the real decoder and replace the indirect func with it. - f = d.newTypeDecoder(t) - wg.Done() - decoders.Store(entry, f) - return f -} - -// validatedTypeDecoder wraps the type decoder with a validator. This is helpful -// for ensuring that enum fields are correct. -func (d *decoderBuilder) validatedTypeDecoder(t reflect.Type, entry *validationEntry) decoderFunc { - dec := d.typeDecoder(t) - if entry == nil { - return dec - } - - // Thread the current validation entry through the decoder, - // but clean up in time for the next field. - return func(node gjson.Result, v reflect.Value, state *decoderState) error { - state.validator = entry - err := dec(node, v, state) - state.validator = nil - return err - } -} - -func indirectUnmarshalerDecoder(n gjson.Result, v reflect.Value, state *decoderState) error { - return v.Addr().Interface().(json.Unmarshaler).UnmarshalJSON([]byte(n.Raw)) -} - -func unmarshalerDecoder(n gjson.Result, v reflect.Value, state *decoderState) error { - if v.Kind() == reflect.Pointer && v.CanSet() { - v.Set(reflect.New(v.Type().Elem())) - } - return v.Interface().(json.Unmarshaler).UnmarshalJSON([]byte(n.Raw)) -} - -func (d *decoderBuilder) newTypeDecoder(t reflect.Type) decoderFunc { - if t.ConvertibleTo(reflect.TypeOf(time.Time{})) { - return d.newTimeTypeDecoder(t) - } - - if t.Implements(reflect.TypeOf((*param.Optional)(nil)).Elem()) { - return d.newOptTypeDecoder(t) - } - - if !d.root && t.Implements(reflect.TypeOf((*json.Unmarshaler)(nil)).Elem()) { - return unmarshalerDecoder - } - if !d.root && reflect.PointerTo(t).Implements(reflect.TypeOf((*json.Unmarshaler)(nil)).Elem()) { - if _, ok := unionVariants[t]; !ok { - return indirectUnmarshalerDecoder - } - } - d.root = false - - if _, ok := unionRegistry[t]; ok { - if isStructUnion(t) { - return d.newStructUnionDecoder(t) - } - return d.newUnionDecoder(t) - } - - switch t.Kind() { - case reflect.Pointer: - inner := t.Elem() - innerDecoder := d.typeDecoder(inner) - - return func(n gjson.Result, v reflect.Value, state *decoderState) error { - if !v.IsValid() { - return fmt.Errorf("apijson: unexpected invalid reflection value %+#v", v) - } - - newValue := reflect.New(inner).Elem() - err := innerDecoder(n, newValue, state) - if err != nil { - return err - } - - v.Set(newValue.Addr()) - return nil - } - case reflect.Struct: - if isStructUnion(t) { - return d.newStructUnionDecoder(t) - } - return d.newStructTypeDecoder(t) - case reflect.Array: - fallthrough - case reflect.Slice: - return d.newArrayTypeDecoder(t) - case reflect.Map: - return d.newMapDecoder(t) - case reflect.Interface: - return func(node gjson.Result, value reflect.Value, state *decoderState) error { - if !value.IsValid() { - return fmt.Errorf("apijson: unexpected invalid value %+#v", value) - } - if node.Value() != nil && value.CanSet() { - value.Set(reflect.ValueOf(node.Value())) - } - return nil - } - default: - return d.newPrimitiveTypeDecoder(t) - } -} - -func (d *decoderBuilder) newMapDecoder(t reflect.Type) decoderFunc { - keyType := t.Key() - itemType := t.Elem() - itemDecoder := d.typeDecoder(itemType) - - return func(node gjson.Result, value reflect.Value, state *decoderState) (err error) { - mapValue := reflect.MakeMapWithSize(t, len(node.Map())) - - node.ForEach(func(key, value gjson.Result) bool { - // It's fine for us to just use `ValueOf` here because the key types will - // always be primitive types so we don't need to decode it using the standard pattern - keyValue := reflect.ValueOf(key.Value()) - if !keyValue.IsValid() { - if err == nil { - err = fmt.Errorf("apijson: received invalid key type %v", keyValue.String()) - } - return false - } - if keyValue.Type() != keyType { - if err == nil { - err = fmt.Errorf("apijson: expected key type %v but got %v", keyType, keyValue.Type()) - } - return false - } - - itemValue := reflect.New(itemType).Elem() - itemerr := itemDecoder(value, itemValue, state) - if itemerr != nil { - if err == nil { - err = itemerr - } - return false - } - - mapValue.SetMapIndex(keyValue, itemValue) - return true - }) - - if err != nil { - return err - } - value.Set(mapValue) - return nil - } -} - -func (d *decoderBuilder) newArrayTypeDecoder(t reflect.Type) decoderFunc { - itemDecoder := d.typeDecoder(t.Elem()) - - return func(node gjson.Result, value reflect.Value, state *decoderState) (err error) { - if !node.IsArray() { - return fmt.Errorf("apijson: could not deserialize to an array") - } - - arrayNode := node.Array() - - arrayValue := reflect.MakeSlice(reflect.SliceOf(t.Elem()), len(arrayNode), len(arrayNode)) - for i, itemNode := range arrayNode { - err = itemDecoder(itemNode, arrayValue.Index(i), state) - if err != nil { - return err - } - } - - value.Set(arrayValue) - return nil - } -} - -func (d *decoderBuilder) newStructTypeDecoder(t reflect.Type) decoderFunc { - // map of json field name to struct field decoders - decoderFields := map[string]decoderField{} - anonymousDecoders := []decoderField{} - extraDecoder := (*decoderField)(nil) - var inlineDecoders []decoderField - - validationEntries := validationRegistry[t] - - for i := 0; i < t.NumField(); i++ { - idx := []int{i} - field := t.FieldByIndex(idx) - if !field.IsExported() { - continue - } - - var validator *validationEntry - for _, entry := range validationEntries { - if entry.field.Offset == field.Offset { - validator = &entry - break - } - } - - // If this is an embedded struct, traverse one level deeper to extract - // the fields and get their encoders as well. - if field.Anonymous { - anonymousDecoders = append(anonymousDecoders, decoderField{ - fn: d.typeDecoder(field.Type), - idx: idx[:], - }) - continue - } - // If json tag is not present, then we skip, which is intentionally - // different behavior from the stdlib. - ptag, ok := parseJSONStructTag(field) - if !ok { - continue - } - // We only want to support unexported fields if they're tagged with - // `extras` because that field shouldn't be part of the public API. - if ptag.extras { - extraDecoder = &decoderField{ptag, d.typeDecoder(field.Type.Elem()), idx, field.Name} - continue - } - if ptag.inline { - df := decoderField{ptag, d.typeDecoder(field.Type), idx, field.Name} - inlineDecoders = append(inlineDecoders, df) - continue - } - if ptag.metadata { - continue - } - - oldFormat := d.dateFormat - dateFormat, ok := parseFormatStructTag(field) - if ok { - switch dateFormat { - case "date-time": - d.dateFormat = time.RFC3339 - case "date": - d.dateFormat = "2006-01-02" - } - } - - decoderFields[ptag.name] = decoderField{ - ptag, - d.validatedTypeDecoder(field.Type, validator), - idx, field.Name, - } - - d.dateFormat = oldFormat - } - - return func(node gjson.Result, value reflect.Value, state *decoderState) (err error) { - if field := value.FieldByName("JSON"); field.IsValid() { - if raw := field.FieldByName("raw"); raw.IsValid() { - setUnexportedField(raw, node.Raw) - } - } - - for _, decoder := range anonymousDecoders { - // ignore errors - decoder.fn(node, value.FieldByIndex(decoder.idx), state) - } - - for _, inlineDecoder := range inlineDecoders { - var meta Field - dest := value.FieldByIndex(inlineDecoder.idx) - isValid := false - if dest.IsValid() && node.Type != gjson.Null { - inlineState := decoderState{exactness: state.exactness, strict: true} - err = inlineDecoder.fn(node, dest, &inlineState) - if err == nil { - isValid = true - } - } - - if node.Type == gjson.Null { - meta = Field{ - raw: node.Raw, - status: null, - } - } else if !isValid { - // If an inline decoder fails, unset the field and move on. - if dest.IsValid() { - dest.SetZero() - } - continue - } else if isValid { - meta = Field{ - raw: node.Raw, - status: valid, - } - } - setMetadataSubField(value, inlineDecoder.idx, inlineDecoder.goname, meta) - } - - typedExtraType := reflect.Type(nil) - typedExtraFields := reflect.Value{} - if extraDecoder != nil { - typedExtraType = value.FieldByIndex(extraDecoder.idx).Type() - typedExtraFields = reflect.MakeMap(typedExtraType) - } - untypedExtraFields := map[string]Field{} - - for fieldName, itemNode := range node.Map() { - df, explicit := decoderFields[fieldName] - var ( - dest reflect.Value - fn decoderFunc - meta Field - ) - if explicit { - fn = df.fn - dest = value.FieldByIndex(df.idx) - } - if !explicit && extraDecoder != nil { - dest = reflect.New(typedExtraType.Elem()).Elem() - fn = extraDecoder.fn - } - - isValid := false - if dest.IsValid() && itemNode.Type != gjson.Null { - err = fn(itemNode, dest, state) - if err == nil { - isValid = true - } - } - - // Handle null [param.Opt] - if itemNode.Type == gjson.Null && dest.IsValid() && dest.Type().Implements(reflect.TypeOf((*param.Optional)(nil)).Elem()) { - dest.Addr().Interface().(json.Unmarshaler).UnmarshalJSON([]byte(itemNode.Raw)) - continue - } - - if itemNode.Type == gjson.Null { - meta = Field{ - raw: itemNode.Raw, - status: null, - } - } else if !isValid { - meta = Field{ - raw: itemNode.Raw, - status: invalid, - } - } else if isValid { - meta = Field{ - raw: itemNode.Raw, - status: valid, - } - } - - if explicit { - setMetadataSubField(value, df.idx, df.goname, meta) - } - if !explicit { - untypedExtraFields[fieldName] = meta - } - if !explicit && extraDecoder != nil { - typedExtraFields.SetMapIndex(reflect.ValueOf(fieldName), dest) - } - } - - if extraDecoder != nil && typedExtraFields.Len() > 0 { - value.FieldByIndex(extraDecoder.idx).Set(typedExtraFields) - } - - // Set exactness to 'extras' if there are untyped, extra fields. - if len(untypedExtraFields) > 0 && state.exactness > extras { - state.exactness = extras - } - - if len(untypedExtraFields) > 0 { - setMetadataExtraFields(value, []int{-1}, "ExtraFields", untypedExtraFields) - } - return nil - } -} - -func (d *decoderBuilder) newPrimitiveTypeDecoder(t reflect.Type) decoderFunc { - switch t.Kind() { - case reflect.String: - return func(n gjson.Result, v reflect.Value, state *decoderState) error { - v.SetString(n.String()) - if guardStrict(state, n.Type != gjson.String) { - return fmt.Errorf("apijson: failed to parse string strictly") - } - // Everything that is not an object can be loosely stringified. - if n.Type == gjson.JSON { - return fmt.Errorf("apijson: failed to parse string") - } - - state.validateString(v) - - if guardUnknown(state, v) { - return fmt.Errorf("apijson: failed string enum validation") - } - return nil - } - case reflect.Bool: - return func(n gjson.Result, v reflect.Value, state *decoderState) error { - v.SetBool(n.Bool()) - if guardStrict(state, n.Type != gjson.True && n.Type != gjson.False) { - return fmt.Errorf("apijson: failed to parse bool strictly") - } - // Numbers and strings that are either 'true' or 'false' can be loosely - // deserialized as bool. - if n.Type == gjson.String && (n.Raw != "true" && n.Raw != "false") || n.Type == gjson.JSON { - return fmt.Errorf("apijson: failed to parse bool") - } - - state.validateBool(v) - - if guardUnknown(state, v) { - return fmt.Errorf("apijson: failed bool enum validation") - } - return nil - } - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return func(n gjson.Result, v reflect.Value, state *decoderState) error { - v.SetInt(n.Int()) - if guardStrict(state, n.Type != gjson.Number || n.Num != float64(int(n.Num))) { - return fmt.Errorf("apijson: failed to parse int strictly") - } - // Numbers, booleans, and strings that maybe look like numbers can be - // loosely deserialized as numbers. - if n.Type == gjson.JSON || (n.Type == gjson.String && !canParseAsNumber(n.Str)) { - return fmt.Errorf("apijson: failed to parse int") - } - - state.validateInt(v) - - if guardUnknown(state, v) { - return fmt.Errorf("apijson: failed int enum validation") - } - return nil - } - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - return func(n gjson.Result, v reflect.Value, state *decoderState) error { - v.SetUint(n.Uint()) - if guardStrict(state, n.Type != gjson.Number || n.Num != float64(int(n.Num)) || n.Num < 0) { - return fmt.Errorf("apijson: failed to parse uint strictly") - } - // Numbers, booleans, and strings that maybe look like numbers can be - // loosely deserialized as uint. - if n.Type == gjson.JSON || (n.Type == gjson.String && !canParseAsNumber(n.Str)) { - return fmt.Errorf("apijson: failed to parse uint") - } - if guardUnknown(state, v) { - return fmt.Errorf("apijson: failed uint enum validation") - } - return nil - } - case reflect.Float32, reflect.Float64: - return func(n gjson.Result, v reflect.Value, state *decoderState) error { - v.SetFloat(n.Float()) - if guardStrict(state, n.Type != gjson.Number) { - return fmt.Errorf("apijson: failed to parse float strictly") - } - // Numbers, booleans, and strings that maybe look like numbers can be - // loosely deserialized as floats. - if n.Type == gjson.JSON || (n.Type == gjson.String && !canParseAsNumber(n.Str)) { - return fmt.Errorf("apijson: failed to parse float") - } - if guardUnknown(state, v) { - return fmt.Errorf("apijson: failed float enum validation") - } - return nil - } - default: - return func(node gjson.Result, v reflect.Value, state *decoderState) error { - return fmt.Errorf("unknown type received at primitive decoder: %s", t.String()) - } - } -} - -func (d *decoderBuilder) newOptTypeDecoder(t reflect.Type) decoderFunc { - for t.Kind() == reflect.Pointer { - t = t.Elem() - } - valueField, _ := t.FieldByName("Value") - return func(n gjson.Result, v reflect.Value, state *decoderState) error { - state.validateOptKind(n, valueField.Type) - return v.Addr().Interface().(json.Unmarshaler).UnmarshalJSON([]byte(n.Raw)) - } -} - -func (d *decoderBuilder) newTimeTypeDecoder(t reflect.Type) decoderFunc { - format := d.dateFormat - return func(n gjson.Result, v reflect.Value, state *decoderState) error { - parsed, err := time.Parse(format, n.Str) - if err == nil { - v.Set(reflect.ValueOf(parsed).Convert(t)) - return nil - } - - if guardStrict(state, true) { - return err - } - - layouts := []string{ - "2006-01-02", - "2006-01-02T15:04:05Z07:00", - "2006-01-02T15:04:05Z0700", - "2006-01-02T15:04:05", - "2006-01-02 15:04:05Z07:00", - "2006-01-02 15:04:05Z0700", - "2006-01-02 15:04:05", - } - - for _, layout := range layouts { - parsed, err := time.Parse(layout, n.Str) - if err == nil { - v.Set(reflect.ValueOf(parsed).Convert(t)) - return nil - } - } - - return fmt.Errorf("unable to leniently parse date-time string: %s", n.Str) - } -} - -func setUnexportedField(field reflect.Value, value any) { - reflect.NewAt(field.Type(), unsafe.Pointer(field.UnsafeAddr())).Elem().Set(reflect.ValueOf(value)) -} - -func guardStrict(state *decoderState, cond bool) bool { - if !cond { - return false - } - - if state.strict { - return true - } - - state.exactness = loose - return false -} - -func canParseAsNumber(str string) bool { - _, err := strconv.ParseFloat(str, 64) - return err == nil -} - -var stringType = reflect.TypeOf(string("")) - -func guardUnknown(state *decoderState, v reflect.Value) bool { - if have, ok := v.Interface().(interface{ IsKnown() bool }); guardStrict(state, ok && !have.IsKnown()) { - return true - } - - constantString, ok := v.Interface().(interface{ Default() string }) - named := v.Type() != stringType - if guardStrict(state, ok && named && v.Equal(reflect.ValueOf(constantString.Default()))) { - return true - } - return false -} diff --git a/vendor/github.com/openai/openai-go/internal/apijson/encoder.go b/vendor/github.com/openai/openai-go/internal/apijson/encoder.go deleted file mode 100644 index 8358a2f0..00000000 --- a/vendor/github.com/openai/openai-go/internal/apijson/encoder.go +++ /dev/null @@ -1,392 +0,0 @@ -package apijson - -import ( - "bytes" - "encoding/json" - "fmt" - "reflect" - "sort" - "strconv" - "strings" - "sync" - "time" - - "github.com/tidwall/sjson" -) - -var encoders sync.Map // map[encoderEntry]encoderFunc - -func Marshal(value any) ([]byte, error) { - e := &encoder{dateFormat: time.RFC3339} - return e.marshal(value) -} - -func MarshalRoot(value any) ([]byte, error) { - e := &encoder{root: true, dateFormat: time.RFC3339} - return e.marshal(value) -} - -type encoder struct { - dateFormat string - root bool -} - -type encoderFunc func(value reflect.Value) ([]byte, error) - -type encoderField struct { - tag parsedStructTag - fn encoderFunc - idx []int -} - -type encoderEntry struct { - reflect.Type - dateFormat string - root bool -} - -func (e *encoder) marshal(value any) ([]byte, error) { - val := reflect.ValueOf(value) - if !val.IsValid() { - return nil, nil - } - typ := val.Type() - enc := e.typeEncoder(typ) - return enc(val) -} - -func (e *encoder) typeEncoder(t reflect.Type) encoderFunc { - entry := encoderEntry{ - Type: t, - dateFormat: e.dateFormat, - root: e.root, - } - - if fi, ok := encoders.Load(entry); ok { - return fi.(encoderFunc) - } - - // To deal with recursive types, populate the map with an - // indirect func before we build it. This type waits on the - // real func (f) to be ready and then calls it. This indirect - // func is only used for recursive types. - var ( - wg sync.WaitGroup - f encoderFunc - ) - wg.Add(1) - fi, loaded := encoders.LoadOrStore(entry, encoderFunc(func(v reflect.Value) ([]byte, error) { - wg.Wait() - return f(v) - })) - if loaded { - return fi.(encoderFunc) - } - - // Compute the real encoder and replace the indirect func with it. - f = e.newTypeEncoder(t) - wg.Done() - encoders.Store(entry, f) - return f -} - -func marshalerEncoder(v reflect.Value) ([]byte, error) { - return v.Interface().(json.Marshaler).MarshalJSON() -} - -func indirectMarshalerEncoder(v reflect.Value) ([]byte, error) { - return v.Addr().Interface().(json.Marshaler).MarshalJSON() -} - -func (e *encoder) newTypeEncoder(t reflect.Type) encoderFunc { - if t.ConvertibleTo(reflect.TypeOf(time.Time{})) { - return e.newTimeTypeEncoder() - } - if !e.root && t.Implements(reflect.TypeOf((*json.Marshaler)(nil)).Elem()) { - return marshalerEncoder - } - if !e.root && reflect.PointerTo(t).Implements(reflect.TypeOf((*json.Marshaler)(nil)).Elem()) { - return indirectMarshalerEncoder - } - e.root = false - switch t.Kind() { - case reflect.Pointer: - inner := t.Elem() - - innerEncoder := e.typeEncoder(inner) - return func(v reflect.Value) ([]byte, error) { - if !v.IsValid() || v.IsNil() { - return nil, nil - } - return innerEncoder(v.Elem()) - } - case reflect.Struct: - return e.newStructTypeEncoder(t) - case reflect.Array: - fallthrough - case reflect.Slice: - return e.newArrayTypeEncoder(t) - case reflect.Map: - return e.newMapEncoder(t) - case reflect.Interface: - return e.newInterfaceEncoder() - default: - return e.newPrimitiveTypeEncoder(t) - } -} - -func (e *encoder) newPrimitiveTypeEncoder(t reflect.Type) encoderFunc { - switch t.Kind() { - // Note that we could use `gjson` to encode these types but it would complicate our - // code more and this current code shouldn't cause any issues - case reflect.String: - return func(v reflect.Value) ([]byte, error) { - return json.Marshal(v.Interface()) - } - case reflect.Bool: - return func(v reflect.Value) ([]byte, error) { - if v.Bool() { - return []byte("true"), nil - } - return []byte("false"), nil - } - case reflect.Int, reflect.Int16, reflect.Int32, reflect.Int64: - return func(v reflect.Value) ([]byte, error) { - return []byte(strconv.FormatInt(v.Int(), 10)), nil - } - case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64: - return func(v reflect.Value) ([]byte, error) { - return []byte(strconv.FormatUint(v.Uint(), 10)), nil - } - case reflect.Float32: - return func(v reflect.Value) ([]byte, error) { - return []byte(strconv.FormatFloat(v.Float(), 'f', -1, 32)), nil - } - case reflect.Float64: - return func(v reflect.Value) ([]byte, error) { - return []byte(strconv.FormatFloat(v.Float(), 'f', -1, 64)), nil - } - default: - return func(v reflect.Value) ([]byte, error) { - return nil, fmt.Errorf("unknown type received at primitive encoder: %s", t.String()) - } - } -} - -func (e *encoder) newArrayTypeEncoder(t reflect.Type) encoderFunc { - itemEncoder := e.typeEncoder(t.Elem()) - - return func(value reflect.Value) ([]byte, error) { - json := []byte("[]") - for i := 0; i < value.Len(); i++ { - var value, err = itemEncoder(value.Index(i)) - if err != nil { - return nil, err - } - if value == nil { - // Assume that empty items should be inserted as `null` so that the output array - // will be the same length as the input array - value = []byte("null") - } - - json, err = sjson.SetRawBytes(json, "-1", value) - if err != nil { - return nil, err - } - } - - return json, nil - } -} - -func (e *encoder) newStructTypeEncoder(t reflect.Type) encoderFunc { - encoderFields := []encoderField{} - extraEncoder := (*encoderField)(nil) - - // This helper allows us to recursively collect field encoders into a flat - // array. The parameter `index` keeps track of the access patterns necessary - // to get to some field. - var collectEncoderFields func(r reflect.Type, index []int) - collectEncoderFields = func(r reflect.Type, index []int) { - for i := 0; i < r.NumField(); i++ { - idx := append(index, i) - field := t.FieldByIndex(idx) - if !field.IsExported() { - continue - } - // If this is an embedded struct, traverse one level deeper to extract - // the field and get their encoders as well. - if field.Anonymous { - collectEncoderFields(field.Type, idx) - continue - } - // If json tag is not present, then we skip, which is intentionally - // different behavior from the stdlib. - ptag, ok := parseJSONStructTag(field) - if !ok { - continue - } - // We only want to support unexported field if they're tagged with - // `extras` because that field shouldn't be part of the public API. We - // also want to only keep the top level extras - if ptag.extras && len(index) == 0 { - extraEncoder = &encoderField{ptag, e.typeEncoder(field.Type.Elem()), idx} - continue - } - if ptag.name == "-" { - continue - } - - dateFormat, ok := parseFormatStructTag(field) - oldFormat := e.dateFormat - if ok { - switch dateFormat { - case "date-time": - e.dateFormat = time.RFC3339 - case "date": - e.dateFormat = "2006-01-02" - } - } - encoderFields = append(encoderFields, encoderField{ptag, e.typeEncoder(field.Type), idx}) - e.dateFormat = oldFormat - } - } - collectEncoderFields(t, []int{}) - - // Ensure deterministic output by sorting by lexicographic order - sort.Slice(encoderFields, func(i, j int) bool { - return encoderFields[i].tag.name < encoderFields[j].tag.name - }) - - return func(value reflect.Value) (json []byte, err error) { - json = []byte("{}") - - for _, ef := range encoderFields { - field := value.FieldByIndex(ef.idx) - encoded, err := ef.fn(field) - if err != nil { - return nil, err - } - if encoded == nil { - continue - } - json, err = sjson.SetRawBytes(json, ef.tag.name, encoded) - if err != nil { - return nil, err - } - } - - if extraEncoder != nil { - json, err = e.encodeMapEntries(json, value.FieldByIndex(extraEncoder.idx)) - if err != nil { - return nil, err - } - } - return - } -} - -func (e *encoder) newFieldTypeEncoder(t reflect.Type) encoderFunc { - f, _ := t.FieldByName("Value") - enc := e.typeEncoder(f.Type) - - return func(value reflect.Value) (json []byte, err error) { - present := value.FieldByName("Present") - if !present.Bool() { - return nil, nil - } - null := value.FieldByName("Null") - if null.Bool() { - return []byte("null"), nil - } - raw := value.FieldByName("Raw") - if !raw.IsNil() { - return e.typeEncoder(raw.Type())(raw) - } - return enc(value.FieldByName("Value")) - } -} - -func (e *encoder) newTimeTypeEncoder() encoderFunc { - format := e.dateFormat - return func(value reflect.Value) (json []byte, err error) { - return []byte(`"` + value.Convert(reflect.TypeOf(time.Time{})).Interface().(time.Time).Format(format) + `"`), nil - } -} - -func (e encoder) newInterfaceEncoder() encoderFunc { - return func(value reflect.Value) ([]byte, error) { - value = value.Elem() - if !value.IsValid() { - return nil, nil - } - return e.typeEncoder(value.Type())(value) - } -} - -// Given a []byte of json (may either be an empty object or an object that already contains entries) -// encode all of the entries in the map to the json byte array. -func (e *encoder) encodeMapEntries(json []byte, v reflect.Value) ([]byte, error) { - type mapPair struct { - key []byte - value reflect.Value - } - - pairs := []mapPair{} - keyEncoder := e.typeEncoder(v.Type().Key()) - - iter := v.MapRange() - for iter.Next() { - var encodedKeyString string - if iter.Key().Type().Kind() == reflect.String { - encodedKeyString = iter.Key().String() - } else { - var err error - encodedKeyBytes, err := keyEncoder(iter.Key()) - if err != nil { - return nil, err - } - encodedKeyString = string(encodedKeyBytes) - } - encodedKey := []byte(sjsonReplacer.Replace(encodedKeyString)) - pairs = append(pairs, mapPair{key: encodedKey, value: iter.Value()}) - } - - // Ensure deterministic output - sort.Slice(pairs, func(i, j int) bool { - return bytes.Compare(pairs[i].key, pairs[j].key) < 0 - }) - - elementEncoder := e.typeEncoder(v.Type().Elem()) - for _, p := range pairs { - encodedValue, err := elementEncoder(p.value) - if err != nil { - return nil, err - } - if len(encodedValue) == 0 { - continue - } - json, err = sjson.SetRawBytes(json, string(p.key), encodedValue) - if err != nil { - return nil, err - } - } - - return json, nil -} - -func (e *encoder) newMapEncoder(_ reflect.Type) encoderFunc { - return func(value reflect.Value) ([]byte, error) { - json := []byte("{}") - var err error - json, err = e.encodeMapEntries(json, value) - if err != nil { - return nil, err - } - return json, nil - } -} - -// If we want to set a literal key value into JSON using sjson, we need to make sure it doesn't have -// special characters that sjson interprets as a path. -var sjsonReplacer *strings.Replacer = strings.NewReplacer(".", "\\.", ":", "\\:", "*", "\\*") diff --git a/vendor/github.com/openai/openai-go/internal/apijson/enum.go b/vendor/github.com/openai/openai-go/internal/apijson/enum.go deleted file mode 100644 index 18b218a8..00000000 --- a/vendor/github.com/openai/openai-go/internal/apijson/enum.go +++ /dev/null @@ -1,145 +0,0 @@ -package apijson - -import ( - "fmt" - "reflect" - "slices" - "sync" - - "github.com/tidwall/gjson" -) - -/********************/ -/* Validating Enums */ -/********************/ - -type validationEntry struct { - field reflect.StructField - required bool - legalValues struct { - strings []string - // 1 represents true, 0 represents false, -1 represents either - bools int - ints []int64 - } -} - -type validatorFunc func(reflect.Value) exactness - -var validators sync.Map -var validationRegistry = map[reflect.Type][]validationEntry{} - -func RegisterFieldValidator[T any, V string | bool | int](fieldName string, values ...V) { - var t T - parentType := reflect.TypeOf(t) - - if _, ok := validationRegistry[parentType]; !ok { - validationRegistry[parentType] = []validationEntry{} - } - - // The following checks run at initialization time, - // it is impossible for them to panic if any tests pass. - if parentType.Kind() != reflect.Struct { - panic(fmt.Sprintf("apijson: cannot initialize validator for non-struct %s", parentType.String())) - } - - var field reflect.StructField - found := false - for i := 0; i < parentType.NumField(); i++ { - ptag, ok := parseJSONStructTag(parentType.Field(i)) - if ok && ptag.name == fieldName { - field = parentType.Field(i) - found = true - break - } - } - - if !found { - panic(fmt.Sprintf("apijson: cannot find field %s in struct %s", fieldName, parentType.String())) - } - - newEntry := validationEntry{field: field} - newEntry.legalValues.bools = -1 // default to either - - switch values := any(values).(type) { - case []string: - newEntry.legalValues.strings = values - case []int: - newEntry.legalValues.ints = make([]int64, len(values)) - for i, value := range values { - newEntry.legalValues.ints[i] = int64(value) - } - case []bool: - for i, value := range values { - var next int - if value { - next = 1 - } - if i > 0 && newEntry.legalValues.bools != next { - newEntry.legalValues.bools = -1 // accept either - break - } - newEntry.legalValues.bools = next - } - } - - // Store the information necessary to create a validator, so that we can use it - // lazily create the validator function when did. - validationRegistry[parentType] = append(validationRegistry[parentType], newEntry) -} - -func (state *decoderState) validateString(v reflect.Value) { - if state.validator == nil { - return - } - if !slices.Contains(state.validator.legalValues.strings, v.String()) { - state.exactness = loose - } -} - -func (state *decoderState) validateInt(v reflect.Value) { - if state.validator == nil { - return - } - if !slices.Contains(state.validator.legalValues.ints, v.Int()) { - state.exactness = loose - } -} - -func (state *decoderState) validateBool(v reflect.Value) { - if state.validator == nil { - return - } - b := v.Bool() - if state.validator.legalValues.bools == 1 && b == false { - state.exactness = loose - } else if state.validator.legalValues.bools == 0 && b == true { - state.exactness = loose - } -} - -func (state *decoderState) validateOptKind(node gjson.Result, t reflect.Type) { - switch node.Type { - case gjson.JSON: - state.exactness = loose - case gjson.Null: - return - case gjson.False, gjson.True: - if t.Kind() != reflect.Bool { - state.exactness = loose - } - case gjson.Number: - switch t.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, - reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, - reflect.Float32, reflect.Float64: - return - default: - state.exactness = loose - } - case gjson.String: - if t.Kind() != reflect.String { - state.exactness = loose - } - } -} diff --git a/vendor/github.com/openai/openai-go/internal/apijson/field.go b/vendor/github.com/openai/openai-go/internal/apijson/field.go deleted file mode 100644 index 854d6dd7..00000000 --- a/vendor/github.com/openai/openai-go/internal/apijson/field.go +++ /dev/null @@ -1,23 +0,0 @@ -package apijson - -type status uint8 - -const ( - missing status = iota - null - invalid - valid -) - -type Field struct { - raw string - status status -} - -// Returns true if the field is explicitly `null` _or_ if it is not present at all (ie, missing). -// To check if the field's key is present in the JSON with an explicit null value, -// you must check `f.IsNull() && !f.IsMissing()`. -func (j Field) IsNull() bool { return j.status <= null } -func (j Field) IsMissing() bool { return j.status == missing } -func (j Field) IsInvalid() bool { return j.status == invalid } -func (j Field) Raw() string { return j.raw } diff --git a/vendor/github.com/openai/openai-go/internal/apijson/port.go b/vendor/github.com/openai/openai-go/internal/apijson/port.go deleted file mode 100644 index b40013c1..00000000 --- a/vendor/github.com/openai/openai-go/internal/apijson/port.go +++ /dev/null @@ -1,120 +0,0 @@ -package apijson - -import ( - "fmt" - "reflect" -) - -// Port copies over values from one struct to another struct. -func Port(from any, to any) error { - toVal := reflect.ValueOf(to) - fromVal := reflect.ValueOf(from) - - if toVal.Kind() != reflect.Ptr || toVal.IsNil() { - return fmt.Errorf("destination must be a non-nil pointer") - } - - for toVal.Kind() == reflect.Ptr { - toVal = toVal.Elem() - } - toType := toVal.Type() - - for fromVal.Kind() == reflect.Ptr { - fromVal = fromVal.Elem() - } - fromType := fromVal.Type() - - if toType.Kind() != reflect.Struct { - return fmt.Errorf("destination must be a non-nil pointer to a struct (%v %v)", toType, toType.Kind()) - } - - values := map[string]reflect.Value{} - fields := map[string]reflect.Value{} - - fromJSON := fromVal.FieldByName("JSON") - toJSON := toVal.FieldByName("JSON") - - // Iterate through the fields of v and load all the "normal" fields in the struct to the map of - // string to reflect.Value, as well as their raw .JSON.Foo counterpart indicated by j. - var getFields func(t reflect.Type, v reflect.Value) - getFields = func(t reflect.Type, v reflect.Value) { - j := v.FieldByName("JSON") - - // Recurse into anonymous fields first, since the fields on the object should win over the fields in the - // embedded object. - for i := 0; i < t.NumField(); i++ { - field := t.Field(i) - if field.Anonymous { - getFields(field.Type, v.Field(i)) - continue - } - } - - for i := 0; i < t.NumField(); i++ { - field := t.Field(i) - ptag, ok := parseJSONStructTag(field) - if !ok || ptag.name == "-" || ptag.name == "" { - continue - } - values[ptag.name] = v.Field(i) - if j.IsValid() { - fields[ptag.name] = j.FieldByName(field.Name) - } - } - } - getFields(fromType, fromVal) - - // Use the values from the previous step to populate the 'to' struct. - for i := 0; i < toType.NumField(); i++ { - field := toType.Field(i) - ptag, ok := parseJSONStructTag(field) - if !ok { - continue - } - if ptag.name == "-" { - continue - } - if value, ok := values[ptag.name]; ok { - delete(values, ptag.name) - if field.Type.Kind() == reflect.Interface { - toVal.Field(i).Set(value) - } else { - switch value.Kind() { - case reflect.String: - toVal.Field(i).SetString(value.String()) - case reflect.Bool: - toVal.Field(i).SetBool(value.Bool()) - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - toVal.Field(i).SetInt(value.Int()) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - toVal.Field(i).SetUint(value.Uint()) - case reflect.Float32, reflect.Float64: - toVal.Field(i).SetFloat(value.Float()) - default: - toVal.Field(i).Set(value) - } - } - } - - if fromJSONField, ok := fields[ptag.name]; ok { - if toJSONField := toJSON.FieldByName(field.Name); toJSONField.IsValid() { - toJSONField.Set(fromJSONField) - } - } - } - - // Finally, copy over the .JSON.raw and .JSON.ExtraFields - if toJSON.IsValid() { - if raw := toJSON.FieldByName("raw"); raw.IsValid() { - setUnexportedField(raw, fromJSON.Interface().(interface{ RawJSON() string }).RawJSON()) - } - - if toExtraFields := toJSON.FieldByName("ExtraFields"); toExtraFields.IsValid() { - if fromExtraFields := fromJSON.FieldByName("ExtraFields"); fromExtraFields.IsValid() { - setUnexportedField(toExtraFields, fromExtraFields.Interface()) - } - } - } - - return nil -} diff --git a/vendor/github.com/openai/openai-go/internal/apijson/registry.go b/vendor/github.com/openai/openai-go/internal/apijson/registry.go deleted file mode 100644 index 2a249827..00000000 --- a/vendor/github.com/openai/openai-go/internal/apijson/registry.go +++ /dev/null @@ -1,51 +0,0 @@ -package apijson - -import ( - "reflect" - - "github.com/tidwall/gjson" -) - -type UnionVariant struct { - TypeFilter gjson.Type - DiscriminatorValue any - Type reflect.Type -} - -var unionRegistry = map[reflect.Type]unionEntry{} -var unionVariants = map[reflect.Type]any{} - -type unionEntry struct { - discriminatorKey string - variants []UnionVariant -} - -func Discriminator[T any](value any) UnionVariant { - var zero T - return UnionVariant{ - TypeFilter: gjson.JSON, - DiscriminatorValue: value, - Type: reflect.TypeOf(zero), - } -} - -func RegisterUnion[T any](discriminator string, variants ...UnionVariant) { - typ := reflect.TypeOf((*T)(nil)).Elem() - unionRegistry[typ] = unionEntry{ - discriminatorKey: discriminator, - variants: variants, - } - for _, variant := range variants { - unionVariants[variant.Type] = typ - } -} - -// Useful to wrap a union type to force it to use [apijson.UnmarshalJSON] since you cannot define an -// UnmarshalJSON function on the interface itself. -type UnionUnmarshaler[T any] struct { - Value T -} - -func (c *UnionUnmarshaler[T]) UnmarshalJSON(buf []byte) error { - return UnmarshalRoot(buf, &c.Value) -} diff --git a/vendor/github.com/openai/openai-go/internal/apijson/subfield.go b/vendor/github.com/openai/openai-go/internal/apijson/subfield.go deleted file mode 100644 index 782d3a78..00000000 --- a/vendor/github.com/openai/openai-go/internal/apijson/subfield.go +++ /dev/null @@ -1,67 +0,0 @@ -package apijson - -import ( - "github.com/openai/openai-go/packages/respjson" - "reflect" -) - -func getSubField(root reflect.Value, index []int, name string) reflect.Value { - strct := root.FieldByIndex(index[:len(index)-1]) - if !strct.IsValid() { - panic("couldn't find encapsulating struct for field " + name) - } - meta := strct.FieldByName("JSON") - if !meta.IsValid() { - return reflect.Value{} - } - field := meta.FieldByName(name) - if !field.IsValid() { - return reflect.Value{} - } - return field -} - -func setMetadataSubField(root reflect.Value, index []int, name string, meta Field) { - target := getSubField(root, index, name) - if !target.IsValid() { - return - } - - if target.Type() == reflect.TypeOf(meta) { - target.Set(reflect.ValueOf(meta)) - } else if respMeta := meta.toRespField(); target.Type() == reflect.TypeOf(respMeta) { - target.Set(reflect.ValueOf(respMeta)) - } -} - -func setMetadataExtraFields(root reflect.Value, index []int, name string, metaExtras map[string]Field) { - target := getSubField(root, index, name) - if !target.IsValid() { - return - } - - if target.Type() == reflect.TypeOf(metaExtras) { - target.Set(reflect.ValueOf(metaExtras)) - return - } - - newMap := make(map[string]respjson.Field, len(metaExtras)) - if target.Type() == reflect.TypeOf(newMap) { - for k, v := range metaExtras { - newMap[k] = v.toRespField() - } - target.Set(reflect.ValueOf(newMap)) - } -} - -func (f Field) toRespField() respjson.Field { - if f.IsMissing() { - return respjson.Field{} - } else if f.IsNull() { - return respjson.NewField("null") - } else if f.IsInvalid() { - return respjson.NewInvalidField(f.raw) - } else { - return respjson.NewField(f.raw) - } -} diff --git a/vendor/github.com/openai/openai-go/internal/apijson/tag.go b/vendor/github.com/openai/openai-go/internal/apijson/tag.go deleted file mode 100644 index 812fb3ca..00000000 --- a/vendor/github.com/openai/openai-go/internal/apijson/tag.go +++ /dev/null @@ -1,47 +0,0 @@ -package apijson - -import ( - "reflect" - "strings" -) - -const jsonStructTag = "json" -const formatStructTag = "format" - -type parsedStructTag struct { - name string - required bool - extras bool - metadata bool - inline bool -} - -func parseJSONStructTag(field reflect.StructField) (tag parsedStructTag, ok bool) { - raw, ok := field.Tag.Lookup(jsonStructTag) - if !ok { - return - } - parts := strings.Split(raw, ",") - if len(parts) == 0 { - return tag, false - } - tag.name = parts[0] - for _, part := range parts[1:] { - switch part { - case "required": - tag.required = true - case "extras": - tag.extras = true - case "metadata": - tag.metadata = true - case "inline": - tag.inline = true - } - } - return -} - -func parseFormatStructTag(field reflect.StructField) (format string, ok bool) { - format, ok = field.Tag.Lookup(formatStructTag) - return -} diff --git a/vendor/github.com/openai/openai-go/internal/apijson/union.go b/vendor/github.com/openai/openai-go/internal/apijson/union.go deleted file mode 100644 index 2f23de43..00000000 --- a/vendor/github.com/openai/openai-go/internal/apijson/union.go +++ /dev/null @@ -1,202 +0,0 @@ -package apijson - -import ( - "errors" - "github.com/openai/openai-go/packages/param" - "reflect" - - "github.com/tidwall/gjson" -) - -var apiUnionType = reflect.TypeOf(param.APIUnion{}) - -func isStructUnion(t reflect.Type) bool { - if t.Kind() != reflect.Struct { - return false - } - for i := 0; i < t.NumField(); i++ { - if t.Field(i).Type == apiUnionType && t.Field(i).Anonymous { - return true - } - } - return false -} - -func RegisterDiscriminatedUnion[T any](key string, mappings map[string]reflect.Type) { - var t T - entry := unionEntry{ - discriminatorKey: key, - variants: []UnionVariant{}, - } - for k, typ := range mappings { - entry.variants = append(entry.variants, UnionVariant{ - DiscriminatorValue: k, - Type: typ, - }) - } - unionRegistry[reflect.TypeOf(t)] = entry -} - -func (d *decoderBuilder) newStructUnionDecoder(t reflect.Type) decoderFunc { - type variantDecoder struct { - decoder decoderFunc - field reflect.StructField - discriminatorValue any - } - - variants := []variantDecoder{} - for i := 0; i < t.NumField(); i++ { - field := t.Field(i) - - if field.Anonymous && field.Type == apiUnionType { - continue - } - - decoder := d.typeDecoder(field.Type) - variants = append(variants, variantDecoder{ - decoder: decoder, - field: field, - }) - } - - unionEntry, discriminated := unionRegistry[t] - for _, unionVariant := range unionEntry.variants { - for i := 0; i < len(variants); i++ { - variant := &variants[i] - if variant.field.Type.Elem() == unionVariant.Type { - variant.discriminatorValue = unionVariant.DiscriminatorValue - break - } - } - } - - return func(n gjson.Result, v reflect.Value, state *decoderState) error { - if discriminated && n.Type == gjson.JSON && len(unionEntry.discriminatorKey) != 0 { - discriminator := n.Get(unionEntry.discriminatorKey).Value() - for _, variant := range variants { - if discriminator == variant.discriminatorValue { - inner := v.FieldByIndex(variant.field.Index) - return variant.decoder(n, inner, state) - } - } - return errors.New("apijson: was not able to find discriminated union variant") - } - - // Set bestExactness to worse than loose - bestExactness := loose - 1 - bestVariant := -1 - for i, variant := range variants { - // Pointers are used to discern JSON object variants from value variants - if n.Type != gjson.JSON && variant.field.Type.Kind() == reflect.Ptr { - continue - } - - sub := decoderState{strict: state.strict, exactness: exact} - inner := v.FieldByIndex(variant.field.Index) - err := variant.decoder(n, inner, &sub) - if err != nil { - continue - } - if sub.exactness == exact { - bestExactness = exact - bestVariant = i - break - } - if sub.exactness > bestExactness { - bestExactness = sub.exactness - bestVariant = i - } - } - - if bestExactness < loose { - return errors.New("apijson: was not able to coerce type as union") - } - - if guardStrict(state, bestExactness != exact) { - return errors.New("apijson: was not able to coerce type as union strictly") - } - - for i := 0; i < len(variants); i++ { - if i == bestVariant { - continue - } - v.FieldByIndex(variants[i].field.Index).SetZero() - } - - return nil - } -} - -// newUnionDecoder returns a decoderFunc that deserializes into a union using an -// algorithm roughly similar to Pydantic's [smart algorithm]. -// -// Conceptually this is equivalent to choosing the best schema based on how 'exact' -// the deserialization is for each of the schemas. -// -// If there is a tie in the level of exactness, then the tie is broken -// left-to-right. -// -// [smart algorithm]: https://docs.pydantic.dev/latest/concepts/unions/#smart-mode -func (d *decoderBuilder) newUnionDecoder(t reflect.Type) decoderFunc { - unionEntry, ok := unionRegistry[t] - if !ok { - panic("apijson: couldn't find union of type " + t.String() + " in union registry") - } - decoders := []decoderFunc{} - for _, variant := range unionEntry.variants { - decoder := d.typeDecoder(variant.Type) - decoders = append(decoders, decoder) - } - return func(n gjson.Result, v reflect.Value, state *decoderState) error { - // If there is a discriminator match, circumvent the exactness logic entirely - for idx, variant := range unionEntry.variants { - decoder := decoders[idx] - if variant.TypeFilter != n.Type { - continue - } - - if len(unionEntry.discriminatorKey) != 0 { - discriminatorValue := n.Get(unionEntry.discriminatorKey).Value() - if discriminatorValue == variant.DiscriminatorValue { - inner := reflect.New(variant.Type).Elem() - err := decoder(n, inner, state) - v.Set(inner) - return err - } - } - } - - // Set bestExactness to worse than loose - bestExactness := loose - 1 - for idx, variant := range unionEntry.variants { - decoder := decoders[idx] - if variant.TypeFilter != n.Type { - continue - } - sub := decoderState{strict: state.strict, exactness: exact} - inner := reflect.New(variant.Type).Elem() - err := decoder(n, inner, &sub) - if err != nil { - continue - } - if sub.exactness == exact { - v.Set(inner) - return nil - } - if sub.exactness > bestExactness { - v.Set(inner) - bestExactness = sub.exactness - } - } - - if bestExactness < loose { - return errors.New("apijson: was not able to coerce type as union") - } - - if guardStrict(state, bestExactness != exact) { - return errors.New("apijson: was not able to coerce type as union strictly") - } - - return nil - } -} diff --git a/vendor/github.com/openai/openai-go/internal/apiquery/encoder.go b/vendor/github.com/openai/openai-go/internal/apiquery/encoder.go deleted file mode 100644 index 94bc40c3..00000000 --- a/vendor/github.com/openai/openai-go/internal/apiquery/encoder.go +++ /dev/null @@ -1,415 +0,0 @@ -package apiquery - -import ( - "encoding/json" - "fmt" - "reflect" - "strconv" - "strings" - "sync" - "time" - - "github.com/openai/openai-go/packages/param" -) - -var encoders sync.Map // map[reflect.Type]encoderFunc - -type encoder struct { - dateFormat string - root bool - settings QuerySettings -} - -type encoderFunc func(key string, value reflect.Value) ([]Pair, error) - -type encoderField struct { - tag parsedStructTag - fn encoderFunc - idx []int -} - -type encoderEntry struct { - reflect.Type - dateFormat string - root bool - settings QuerySettings -} - -type Pair struct { - key string - value string -} - -func (e *encoder) typeEncoder(t reflect.Type) encoderFunc { - entry := encoderEntry{ - Type: t, - dateFormat: e.dateFormat, - root: e.root, - settings: e.settings, - } - - if fi, ok := encoders.Load(entry); ok { - return fi.(encoderFunc) - } - - // To deal with recursive types, populate the map with an - // indirect func before we build it. This type waits on the - // real func (f) to be ready and then calls it. This indirect - // func is only used for recursive types. - var ( - wg sync.WaitGroup - f encoderFunc - ) - wg.Add(1) - fi, loaded := encoders.LoadOrStore(entry, encoderFunc(func(key string, v reflect.Value) ([]Pair, error) { - wg.Wait() - return f(key, v) - })) - if loaded { - return fi.(encoderFunc) - } - - // Compute the real encoder and replace the indirect func with it. - f = e.newTypeEncoder(t) - wg.Done() - encoders.Store(entry, f) - return f -} - -func marshalerEncoder(key string, value reflect.Value) ([]Pair, error) { - s, err := value.Interface().(json.Marshaler).MarshalJSON() - if err != nil { - return nil, fmt.Errorf("apiquery: json fallback marshal error %s", err) - } - return []Pair{{key, string(s)}}, nil -} - -func (e *encoder) newTypeEncoder(t reflect.Type) encoderFunc { - if t.ConvertibleTo(reflect.TypeOf(time.Time{})) { - return e.newTimeTypeEncoder(t) - } - - if t.Implements(reflect.TypeOf((*param.Optional)(nil)).Elem()) { - return e.newRichFieldTypeEncoder(t) - } - - if !e.root && t.Implements(reflect.TypeOf((*json.Marshaler)(nil)).Elem()) { - return marshalerEncoder - } - - e.root = false - switch t.Kind() { - case reflect.Pointer: - encoder := e.typeEncoder(t.Elem()) - return func(key string, value reflect.Value) (pairs []Pair, err error) { - if !value.IsValid() || value.IsNil() { - return - } - return encoder(key, value.Elem()) - } - case reflect.Struct: - return e.newStructTypeEncoder(t) - case reflect.Array: - fallthrough - case reflect.Slice: - return e.newArrayTypeEncoder(t) - case reflect.Map: - return e.newMapEncoder(t) - case reflect.Interface: - return e.newInterfaceEncoder() - default: - return e.newPrimitiveTypeEncoder(t) - } -} - -func (e *encoder) newStructTypeEncoder(t reflect.Type) encoderFunc { - if t.Implements(reflect.TypeOf((*param.Optional)(nil)).Elem()) { - return e.newRichFieldTypeEncoder(t) - } - - for i := 0; i < t.NumField(); i++ { - if t.Field(i).Type == paramUnionType && t.Field(i).Anonymous { - return e.newStructUnionTypeEncoder(t) - } - } - - encoderFields := []encoderField{} - - // This helper allows us to recursively collect field encoders into a flat - // array. The parameter `index` keeps track of the access patterns necessary - // to get to some field. - var collectEncoderFields func(r reflect.Type, index []int) - collectEncoderFields = func(r reflect.Type, index []int) { - for i := 0; i < r.NumField(); i++ { - idx := append(index, i) - field := t.FieldByIndex(idx) - if !field.IsExported() { - continue - } - // If this is an embedded struct, traverse one level deeper to extract - // the field and get their encoders as well. - if field.Anonymous { - collectEncoderFields(field.Type, idx) - continue - } - // If query tag is not present, then we skip, which is intentionally - // different behavior from the stdlib. - ptag, ok := parseQueryStructTag(field) - if !ok { - continue - } - - if (ptag.name == "-" || ptag.name == "") && !ptag.inline { - continue - } - - dateFormat, ok := parseFormatStructTag(field) - oldFormat := e.dateFormat - if ok { - switch dateFormat { - case "date-time": - e.dateFormat = time.RFC3339 - case "date": - e.dateFormat = "2006-01-02" - } - } - var encoderFn encoderFunc - if ptag.omitzero { - typeEncoderFn := e.typeEncoder(field.Type) - encoderFn = func(key string, value reflect.Value) ([]Pair, error) { - if value.IsZero() { - return nil, nil - } - return typeEncoderFn(key, value) - } - } else { - encoderFn = e.typeEncoder(field.Type) - } - encoderFields = append(encoderFields, encoderField{ptag, encoderFn, idx}) - e.dateFormat = oldFormat - } - } - collectEncoderFields(t, []int{}) - - return func(key string, value reflect.Value) (pairs []Pair, err error) { - for _, ef := range encoderFields { - var subkey string = e.renderKeyPath(key, ef.tag.name) - if ef.tag.inline { - subkey = key - } - - field := value.FieldByIndex(ef.idx) - subpairs, suberr := ef.fn(subkey, field) - if suberr != nil { - err = suberr - } - pairs = append(pairs, subpairs...) - } - return - } -} - -var paramUnionType = reflect.TypeOf((*param.APIUnion)(nil)).Elem() - -func (e *encoder) newStructUnionTypeEncoder(t reflect.Type) encoderFunc { - var fieldEncoders []encoderFunc - for i := 0; i < t.NumField(); i++ { - field := t.Field(i) - if field.Type == paramUnionType && field.Anonymous { - fieldEncoders = append(fieldEncoders, nil) - continue - } - fieldEncoders = append(fieldEncoders, e.typeEncoder(field.Type)) - } - - return func(key string, value reflect.Value) (pairs []Pair, err error) { - for i := 0; i < t.NumField(); i++ { - if value.Field(i).Type() == paramUnionType { - continue - } - if !value.Field(i).IsZero() { - return fieldEncoders[i](key, value.Field(i)) - } - } - return nil, fmt.Errorf("apiquery: union %s has no field set", t.String()) - } -} - -func (e *encoder) newMapEncoder(t reflect.Type) encoderFunc { - keyEncoder := e.typeEncoder(t.Key()) - elementEncoder := e.typeEncoder(t.Elem()) - return func(key string, value reflect.Value) (pairs []Pair, err error) { - iter := value.MapRange() - for iter.Next() { - encodedKey, err := keyEncoder("", iter.Key()) - if err != nil { - return nil, err - } - if len(encodedKey) != 1 { - return nil, fmt.Errorf("apiquery: unexpected number of parts for encoded map key, map may contain non-primitive") - } - subkey := encodedKey[0].value - keyPath := e.renderKeyPath(key, subkey) - subpairs, suberr := elementEncoder(keyPath, iter.Value()) - if suberr != nil { - err = suberr - } - pairs = append(pairs, subpairs...) - } - return - } -} - -func (e *encoder) renderKeyPath(key string, subkey string) string { - if len(key) == 0 { - return subkey - } - if e.settings.NestedFormat == NestedQueryFormatDots { - return fmt.Sprintf("%s.%s", key, subkey) - } - return fmt.Sprintf("%s[%s]", key, subkey) -} - -func (e *encoder) newArrayTypeEncoder(t reflect.Type) encoderFunc { - switch e.settings.ArrayFormat { - case ArrayQueryFormatComma: - innerEncoder := e.typeEncoder(t.Elem()) - return func(key string, v reflect.Value) ([]Pair, error) { - elements := []string{} - for i := 0; i < v.Len(); i++ { - innerPairs, err := innerEncoder("", v.Index(i)) - if err != nil { - return nil, err - } - for _, pair := range innerPairs { - elements = append(elements, pair.value) - } - } - if len(elements) == 0 { - return []Pair{}, nil - } - return []Pair{{key, strings.Join(elements, ",")}}, nil - } - case ArrayQueryFormatRepeat: - innerEncoder := e.typeEncoder(t.Elem()) - return func(key string, value reflect.Value) (pairs []Pair, err error) { - for i := 0; i < value.Len(); i++ { - subpairs, suberr := innerEncoder(key, value.Index(i)) - if suberr != nil { - err = suberr - } - pairs = append(pairs, subpairs...) - } - return - } - case ArrayQueryFormatIndices: - panic("The array indices format is not supported yet") - case ArrayQueryFormatBrackets: - innerEncoder := e.typeEncoder(t.Elem()) - return func(key string, value reflect.Value) (pairs []Pair, err error) { - pairs = []Pair{} - for i := 0; i < value.Len(); i++ { - subpairs, suberr := innerEncoder(key+"[]", value.Index(i)) - if suberr != nil { - err = suberr - } - pairs = append(pairs, subpairs...) - } - return - } - default: - panic(fmt.Sprintf("Unknown ArrayFormat value: %d", e.settings.ArrayFormat)) - } -} - -func (e *encoder) newPrimitiveTypeEncoder(t reflect.Type) encoderFunc { - switch t.Kind() { - case reflect.Pointer: - inner := t.Elem() - - innerEncoder := e.newPrimitiveTypeEncoder(inner) - return func(key string, v reflect.Value) ([]Pair, error) { - if !v.IsValid() || v.IsNil() { - return nil, nil - } - return innerEncoder(key, v.Elem()) - } - case reflect.String: - return func(key string, v reflect.Value) ([]Pair, error) { - return []Pair{{key, v.String()}}, nil - } - case reflect.Bool: - return func(key string, v reflect.Value) ([]Pair, error) { - if v.Bool() { - return []Pair{{key, "true"}}, nil - } - return []Pair{{key, "false"}}, nil - } - case reflect.Int, reflect.Int16, reflect.Int32, reflect.Int64: - return func(key string, v reflect.Value) ([]Pair, error) { - return []Pair{{key, strconv.FormatInt(v.Int(), 10)}}, nil - } - case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64: - return func(key string, v reflect.Value) ([]Pair, error) { - return []Pair{{key, strconv.FormatUint(v.Uint(), 10)}}, nil - } - case reflect.Float32, reflect.Float64: - return func(key string, v reflect.Value) ([]Pair, error) { - return []Pair{{key, strconv.FormatFloat(v.Float(), 'f', -1, 64)}}, nil - } - case reflect.Complex64, reflect.Complex128: - bitSize := 64 - if t.Kind() == reflect.Complex128 { - bitSize = 128 - } - return func(key string, v reflect.Value) ([]Pair, error) { - return []Pair{{key, strconv.FormatComplex(v.Complex(), 'f', -1, bitSize)}}, nil - } - default: - return func(key string, v reflect.Value) ([]Pair, error) { - return nil, nil - } - } -} - -func (e *encoder) newFieldTypeEncoder(t reflect.Type) encoderFunc { - f, _ := t.FieldByName("Value") - enc := e.typeEncoder(f.Type) - - return func(key string, value reflect.Value) ([]Pair, error) { - present := value.FieldByName("Present") - if !present.Bool() { - return nil, nil - } - null := value.FieldByName("Null") - if null.Bool() { - return nil, fmt.Errorf("apiquery: field cannot be null") - } - raw := value.FieldByName("Raw") - if !raw.IsNil() { - return e.typeEncoder(raw.Type())(key, raw) - } - return enc(key, value.FieldByName("Value")) - } -} - -func (e *encoder) newTimeTypeEncoder(_ reflect.Type) encoderFunc { - format := e.dateFormat - return func(key string, value reflect.Value) ([]Pair, error) { - return []Pair{{ - key, - value.Convert(reflect.TypeOf(time.Time{})).Interface().(time.Time).Format(format), - }}, nil - } -} - -func (e encoder) newInterfaceEncoder() encoderFunc { - return func(key string, value reflect.Value) ([]Pair, error) { - value = value.Elem() - if !value.IsValid() { - return nil, nil - } - return e.typeEncoder(value.Type())(key, value) - } - -} diff --git a/vendor/github.com/openai/openai-go/internal/apiquery/query.go b/vendor/github.com/openai/openai-go/internal/apiquery/query.go deleted file mode 100644 index 0f379fa3..00000000 --- a/vendor/github.com/openai/openai-go/internal/apiquery/query.go +++ /dev/null @@ -1,55 +0,0 @@ -package apiquery - -import ( - "net/url" - "reflect" - "time" -) - -func MarshalWithSettings(value any, settings QuerySettings) (url.Values, error) { - e := encoder{time.RFC3339, true, settings} - kv := url.Values{} - val := reflect.ValueOf(value) - if !val.IsValid() { - return nil, nil - } - typ := val.Type() - - pairs, err := e.typeEncoder(typ)("", val) - if err != nil { - return nil, err - } - for _, pair := range pairs { - kv.Add(pair.key, pair.value) - } - return kv, nil -} - -func Marshal(value any) (url.Values, error) { - return MarshalWithSettings(value, QuerySettings{}) -} - -type Queryer interface { - URLQuery() (url.Values, error) -} - -type QuerySettings struct { - NestedFormat NestedQueryFormat - ArrayFormat ArrayQueryFormat -} - -type NestedQueryFormat int - -const ( - NestedQueryFormatBrackets NestedQueryFormat = iota - NestedQueryFormatDots -) - -type ArrayQueryFormat int - -const ( - ArrayQueryFormatComma ArrayQueryFormat = iota - ArrayQueryFormatRepeat - ArrayQueryFormatIndices - ArrayQueryFormatBrackets -) diff --git a/vendor/github.com/openai/openai-go/internal/apiquery/richparam.go b/vendor/github.com/openai/openai-go/internal/apiquery/richparam.go deleted file mode 100644 index b1636e9a..00000000 --- a/vendor/github.com/openai/openai-go/internal/apiquery/richparam.go +++ /dev/null @@ -1,20 +0,0 @@ -package apiquery - -import ( - "reflect" - - "github.com/openai/openai-go/packages/param" -) - -func (e *encoder) newRichFieldTypeEncoder(t reflect.Type) encoderFunc { - f, _ := t.FieldByName("Value") - enc := e.typeEncoder(f.Type) - return func(key string, value reflect.Value) ([]Pair, error) { - if opt, ok := value.Interface().(param.Optional); ok && opt.Valid() { - return enc(key, value.FieldByIndex(f.Index)) - } else if ok && param.IsNull(opt) { - return []Pair{{key, "null"}}, nil - } - return nil, nil - } -} diff --git a/vendor/github.com/openai/openai-go/internal/apiquery/tag.go b/vendor/github.com/openai/openai-go/internal/apiquery/tag.go deleted file mode 100644 index 772c40e1..00000000 --- a/vendor/github.com/openai/openai-go/internal/apiquery/tag.go +++ /dev/null @@ -1,44 +0,0 @@ -package apiquery - -import ( - "reflect" - "strings" -) - -const queryStructTag = "query" -const formatStructTag = "format" - -type parsedStructTag struct { - name string - omitempty bool - omitzero bool - inline bool -} - -func parseQueryStructTag(field reflect.StructField) (tag parsedStructTag, ok bool) { - raw, ok := field.Tag.Lookup(queryStructTag) - if !ok { - return - } - parts := strings.Split(raw, ",") - if len(parts) == 0 { - return tag, false - } - tag.name = parts[0] - for _, part := range parts[1:] { - switch part { - case "omitzero": - tag.omitzero = true - case "omitempty": - tag.omitempty = true - case "inline": - tag.inline = true - } - } - return -} - -func parseFormatStructTag(field reflect.StructField) (format string, ok bool) { - format, ok = field.Tag.Lookup(formatStructTag) - return -} diff --git a/vendor/github.com/openai/openai-go/internal/encoding/json/decode.go b/vendor/github.com/openai/openai-go/internal/encoding/json/decode.go deleted file mode 100644 index 93214331..00000000 --- a/vendor/github.com/openai/openai-go/internal/encoding/json/decode.go +++ /dev/null @@ -1,1324 +0,0 @@ -// Vendored from Go 1.24.0-pre-release -// To find alterations, check package shims, and comments beginning in SHIM(). -// -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Represents JSON data structure using native Go types: booleans, floats, -// strings, arrays, and maps. - -package json - -import ( - "encoding" - "encoding/base64" - "fmt" - "github.com/openai/openai-go/internal/encoding/json/shims" - "reflect" - "strconv" - "strings" - "unicode" - "unicode/utf16" - "unicode/utf8" - _ "unsafe" // for linkname -) - -// Unmarshal parses the JSON-encoded data and stores the result -// in the value pointed to by v. If v is nil or not a pointer, -// Unmarshal returns an [InvalidUnmarshalError]. -// -// Unmarshal uses the inverse of the encodings that -// [Marshal] uses, allocating maps, slices, and pointers as necessary, -// with the following additional rules: -// -// To unmarshal JSON into a pointer, Unmarshal first handles the case of -// the JSON being the JSON literal null. In that case, Unmarshal sets -// the pointer to nil. Otherwise, Unmarshal unmarshals the JSON into -// the value pointed at by the pointer. If the pointer is nil, Unmarshal -// allocates a new value for it to point to. -// -// To unmarshal JSON into a value implementing [Unmarshaler], -// Unmarshal calls that value's [Unmarshaler.UnmarshalJSON] method, including -// when the input is a JSON null. -// Otherwise, if the value implements [encoding.TextUnmarshaler] -// and the input is a JSON quoted string, Unmarshal calls -// [encoding.TextUnmarshaler.UnmarshalText] with the unquoted form of the string. -// -// To unmarshal JSON into a struct, Unmarshal matches incoming object -// keys to the keys used by [Marshal] (either the struct field name or its tag), -// preferring an exact match but also accepting a case-insensitive match. By -// default, object keys which don't have a corresponding struct field are -// ignored (see [Decoder.DisallowUnknownFields] for an alternative). -// -// To unmarshal JSON into an interface value, -// Unmarshal stores one of these in the interface value: -// -// - bool, for JSON booleans -// - float64, for JSON numbers -// - string, for JSON strings -// - []any, for JSON arrays -// - map[string]any, for JSON objects -// - nil for JSON null -// -// To unmarshal a JSON array into a slice, Unmarshal resets the slice length -// to zero and then appends each element to the slice. -// As a special case, to unmarshal an empty JSON array into a slice, -// Unmarshal replaces the slice with a new empty slice. -// -// To unmarshal a JSON array into a Go array, Unmarshal decodes -// JSON array elements into corresponding Go array elements. -// If the Go array is smaller than the JSON array, -// the additional JSON array elements are discarded. -// If the JSON array is smaller than the Go array, -// the additional Go array elements are set to zero values. -// -// To unmarshal a JSON object into a map, Unmarshal first establishes a map to -// use. If the map is nil, Unmarshal allocates a new map. Otherwise Unmarshal -// reuses the existing map, keeping existing entries. Unmarshal then stores -// key-value pairs from the JSON object into the map. The map's key type must -// either be any string type, an integer, or implement [encoding.TextUnmarshaler]. -// -// If the JSON-encoded data contain a syntax error, Unmarshal returns a [SyntaxError]. -// -// If a JSON value is not appropriate for a given target type, -// or if a JSON number overflows the target type, Unmarshal -// skips that field and completes the unmarshaling as best it can. -// If no more serious errors are encountered, Unmarshal returns -// an [UnmarshalTypeError] describing the earliest such error. In any -// case, it's not guaranteed that all the remaining fields following -// the problematic one will be unmarshaled into the target object. -// -// The JSON null value unmarshals into an interface, map, pointer, or slice -// by setting that Go value to nil. Because null is often used in JSON to mean -// “not present,” unmarshaling a JSON null into any other Go type has no effect -// on the value and produces no error. -// -// When unmarshaling quoted strings, invalid UTF-8 or -// invalid UTF-16 surrogate pairs are not treated as an error. -// Instead, they are replaced by the Unicode replacement -// character U+FFFD. -func Unmarshal(data []byte, v any) error { - // Check for well-formedness. - // Avoids filling out half a data structure - // before discovering a JSON syntax error. - var d decodeState - err := checkValid(data, &d.scan) - if err != nil { - return err - } - - d.init(data) - return d.unmarshal(v) -} - -// Unmarshaler is the interface implemented by types -// that can unmarshal a JSON description of themselves. -// The input can be assumed to be a valid encoding of -// a JSON value. UnmarshalJSON must copy the JSON data -// if it wishes to retain the data after returning. -// -// By convention, to approximate the behavior of [Unmarshal] itself, -// Unmarshalers implement UnmarshalJSON([]byte("null")) as a no-op. -type Unmarshaler interface { - UnmarshalJSON([]byte) error -} - -// An UnmarshalTypeError describes a JSON value that was -// not appropriate for a value of a specific Go type. -type UnmarshalTypeError struct { - Value string // description of JSON value - "bool", "array", "number -5" - Type reflect.Type // type of Go value it could not be assigned to - Offset int64 // error occurred after reading Offset bytes - Struct string // name of the struct type containing the field - Field string // the full path from root node to the field, include embedded struct -} - -func (e *UnmarshalTypeError) Error() string { - if e.Struct != "" || e.Field != "" { - return "json: cannot unmarshal " + e.Value + " into Go struct field " + e.Struct + "." + e.Field + " of type " + e.Type.String() - } - return "json: cannot unmarshal " + e.Value + " into Go value of type " + e.Type.String() -} - -// An UnmarshalFieldError describes a JSON object key that -// led to an unexported (and therefore unwritable) struct field. -// -// Deprecated: No longer used; kept for compatibility. -type UnmarshalFieldError struct { - Key string - Type reflect.Type - Field reflect.StructField -} - -func (e *UnmarshalFieldError) Error() string { - return "json: cannot unmarshal object key " + strconv.Quote(e.Key) + " into unexported field " + e.Field.Name + " of type " + e.Type.String() -} - -// An InvalidUnmarshalError describes an invalid argument passed to [Unmarshal]. -// (The argument to [Unmarshal] must be a non-nil pointer.) -type InvalidUnmarshalError struct { - Type reflect.Type -} - -func (e *InvalidUnmarshalError) Error() string { - if e.Type == nil { - return "json: Unmarshal(nil)" - } - - if e.Type.Kind() != reflect.Pointer { - return "json: Unmarshal(non-pointer " + e.Type.String() + ")" - } - return "json: Unmarshal(nil " + e.Type.String() + ")" -} - -func (d *decodeState) unmarshal(v any) error { - rv := reflect.ValueOf(v) - if rv.Kind() != reflect.Pointer || rv.IsNil() { - return &InvalidUnmarshalError{reflect.TypeOf(v)} - } - - d.scan.reset() - d.scanWhile(scanSkipSpace) - // We decode rv not rv.Elem because the Unmarshaler interface - // test must be applied at the top level of the value. - err := d.value(rv) - if err != nil { - return d.addErrorContext(err) - } - return d.savedError -} - -// A Number represents a JSON number literal. -type Number string - -// String returns the literal text of the number. -func (n Number) String() string { return string(n) } - -// Float64 returns the number as a float64. -func (n Number) Float64() (float64, error) { - return strconv.ParseFloat(string(n), 64) -} - -// Int64 returns the number as an int64. -func (n Number) Int64() (int64, error) { - return strconv.ParseInt(string(n), 10, 64) -} - -// An errorContext provides context for type errors during decoding. -type errorContext struct { - Struct reflect.Type - FieldStack []string -} - -// decodeState represents the state while decoding a JSON value. -type decodeState struct { - data []byte - off int // next read offset in data - opcode int // last read result - scan scanner - errorContext *errorContext - savedError error - useNumber bool - disallowUnknownFields bool -} - -// readIndex returns the position of the last byte read. -func (d *decodeState) readIndex() int { - return d.off - 1 -} - -// phasePanicMsg is used as a panic message when we end up with something that -// shouldn't happen. It can indicate a bug in the JSON decoder, or that -// something is editing the data slice while the decoder executes. -const phasePanicMsg = "JSON decoder out of sync - data changing underfoot?" - -func (d *decodeState) init(data []byte) *decodeState { - d.data = data - d.off = 0 - d.savedError = nil - if d.errorContext != nil { - d.errorContext.Struct = nil - // Reuse the allocated space for the FieldStack slice. - d.errorContext.FieldStack = d.errorContext.FieldStack[:0] - } - return d -} - -// saveError saves the first err it is called with, -// for reporting at the end of the unmarshal. -func (d *decodeState) saveError(err error) { - if d.savedError == nil { - d.savedError = d.addErrorContext(err) - } -} - -// addErrorContext returns a new error enhanced with information from d.errorContext -func (d *decodeState) addErrorContext(err error) error { - if d.errorContext != nil && (d.errorContext.Struct != nil || len(d.errorContext.FieldStack) > 0) { - switch err := err.(type) { - case *UnmarshalTypeError: - err.Struct = d.errorContext.Struct.Name() - fieldStack := d.errorContext.FieldStack - if err.Field != "" { - fieldStack = append(fieldStack, err.Field) - } - err.Field = strings.Join(fieldStack, ".") - } - } - return err -} - -// skip scans to the end of what was started. -func (d *decodeState) skip() { - s, data, i := &d.scan, d.data, d.off - depth := len(s.parseState) - for { - op := s.step(s, data[i]) - i++ - if len(s.parseState) < depth { - d.off = i - d.opcode = op - return - } - } -} - -// scanNext processes the byte at d.data[d.off]. -func (d *decodeState) scanNext() { - if d.off < len(d.data) { - d.opcode = d.scan.step(&d.scan, d.data[d.off]) - d.off++ - } else { - d.opcode = d.scan.eof() - d.off = len(d.data) + 1 // mark processed EOF with len+1 - } -} - -// scanWhile processes bytes in d.data[d.off:] until it -// receives a scan code not equal to op. -func (d *decodeState) scanWhile(op int) { - s, data, i := &d.scan, d.data, d.off - for i < len(data) { - newOp := s.step(s, data[i]) - i++ - if newOp != op { - d.opcode = newOp - d.off = i - return - } - } - - d.off = len(data) + 1 // mark processed EOF with len+1 - d.opcode = d.scan.eof() -} - -// rescanLiteral is similar to scanWhile(scanContinue), but it specialises the -// common case where we're decoding a literal. The decoder scans the input -// twice, once for syntax errors and to check the length of the value, and the -// second to perform the decoding. -// -// Only in the second step do we use decodeState to tokenize literals, so we -// know there aren't any syntax errors. We can take advantage of that knowledge, -// and scan a literal's bytes much more quickly. -func (d *decodeState) rescanLiteral() { - data, i := d.data, d.off -Switch: - switch data[i-1] { - case '"': // string - for ; i < len(data); i++ { - switch data[i] { - case '\\': - i++ // escaped char - case '"': - i++ // tokenize the closing quote too - break Switch - } - } - case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-': // number - for ; i < len(data); i++ { - switch data[i] { - case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - '.', 'e', 'E', '+', '-': - default: - break Switch - } - } - case 't': // true - i += len("rue") - case 'f': // false - i += len("alse") - case 'n': // null - i += len("ull") - } - if i < len(data) { - d.opcode = stateEndValue(&d.scan, data[i]) - } else { - d.opcode = scanEnd - } - d.off = i + 1 -} - -// value consumes a JSON value from d.data[d.off-1:], decoding into v, and -// reads the following byte ahead. If v is invalid, the value is discarded. -// The first byte of the value has been read already. -func (d *decodeState) value(v reflect.Value) error { - switch d.opcode { - default: - panic(phasePanicMsg) - - case scanBeginArray: - if v.IsValid() { - if err := d.array(v); err != nil { - return err - } - } else { - d.skip() - } - d.scanNext() - - case scanBeginObject: - if v.IsValid() { - if err := d.object(v); err != nil { - return err - } - } else { - d.skip() - } - d.scanNext() - - case scanBeginLiteral: - // All bytes inside literal return scanContinue op code. - start := d.readIndex() - d.rescanLiteral() - - if v.IsValid() { - if err := d.literalStore(d.data[start:d.readIndex()], v, false); err != nil { - return err - } - } - } - return nil -} - -type unquotedValue struct{} - -// valueQuoted is like value but decodes a -// quoted string literal or literal null into an interface value. -// If it finds anything other than a quoted string literal or null, -// valueQuoted returns unquotedValue{}. -func (d *decodeState) valueQuoted() any { - switch d.opcode { - default: - panic(phasePanicMsg) - - case scanBeginArray, scanBeginObject: - d.skip() - d.scanNext() - - case scanBeginLiteral: - v := d.literalInterface() - switch v.(type) { - case nil, string: - return v - } - } - return unquotedValue{} -} - -// indirect walks down v allocating pointers as needed, -// until it gets to a non-pointer. -// If it encounters an Unmarshaler, indirect stops and returns that. -// If decodingNull is true, indirect stops at the first settable pointer so it -// can be set to nil. -func indirect(v reflect.Value, decodingNull bool) (Unmarshaler, encoding.TextUnmarshaler, reflect.Value) { - // Issue #24153 indicates that it is generally not a guaranteed property - // that you may round-trip a reflect.Value by calling Value.Addr().Elem() - // and expect the value to still be settable for values derived from - // unexported embedded struct fields. - // - // The logic below effectively does this when it first addresses the value - // (to satisfy possible pointer methods) and continues to dereference - // subsequent pointers as necessary. - // - // After the first round-trip, we set v back to the original value to - // preserve the original RW flags contained in reflect.Value. - v0 := v - haveAddr := false - - // If v is a named type and is addressable, - // start with its address, so that if the type has pointer methods, - // we find them. - if v.Kind() != reflect.Pointer && v.Type().Name() != "" && v.CanAddr() { - haveAddr = true - v = v.Addr() - } - for { - // Load value from interface, but only if the result will be - // usefully addressable. - if v.Kind() == reflect.Interface && !v.IsNil() { - e := v.Elem() - if e.Kind() == reflect.Pointer && !e.IsNil() && (!decodingNull || e.Elem().Kind() == reflect.Pointer) { - haveAddr = false - v = e - continue - } - } - - if v.Kind() != reflect.Pointer { - break - } - - if decodingNull && v.CanSet() { - break - } - - // Prevent infinite loop if v is an interface pointing to its own address: - // var v any - // v = &v - if v.Elem().Kind() == reflect.Interface && v.Elem().Elem().Equal(v) { - v = v.Elem() - break - } - if v.IsNil() { - v.Set(reflect.New(v.Type().Elem())) - } - if v.Type().NumMethod() > 0 && v.CanInterface() { - if u, ok := v.Interface().(Unmarshaler); ok { - return u, nil, reflect.Value{} - } - if !decodingNull { - if u, ok := v.Interface().(encoding.TextUnmarshaler); ok { - return nil, u, reflect.Value{} - } - } - } - - if haveAddr { - v = v0 // restore original value after round-trip Value.Addr().Elem() - haveAddr = false - } else { - v = v.Elem() - } - } - return nil, nil, v -} - -// array consumes an array from d.data[d.off-1:], decoding into v. -// The first byte of the array ('[') has been read already. -func (d *decodeState) array(v reflect.Value) error { - // Check for unmarshaler. - u, ut, pv := indirect(v, false) - if u != nil { - start := d.readIndex() - d.skip() - return u.UnmarshalJSON(d.data[start:d.off]) - } - if ut != nil { - d.saveError(&UnmarshalTypeError{Value: "array", Type: v.Type(), Offset: int64(d.off)}) - d.skip() - return nil - } - v = pv - - // Check type of target. - switch v.Kind() { - case reflect.Interface: - if v.NumMethod() == 0 { - // Decoding into nil interface? Switch to non-reflect code. - ai := d.arrayInterface() - v.Set(reflect.ValueOf(ai)) - return nil - } - // Otherwise it's invalid. - fallthrough - default: - d.saveError(&UnmarshalTypeError{Value: "array", Type: v.Type(), Offset: int64(d.off)}) - d.skip() - return nil - case reflect.Array, reflect.Slice: - break - } - - i := 0 - for { - // Look ahead for ] - can only happen on first iteration. - d.scanWhile(scanSkipSpace) - if d.opcode == scanEndArray { - break - } - - // Expand slice length, growing the slice if necessary. - if v.Kind() == reflect.Slice { - if i >= v.Cap() { - v.Grow(1) - } - if i >= v.Len() { - v.SetLen(i + 1) - } - } - - if i < v.Len() { - // Decode into element. - if err := d.value(v.Index(i)); err != nil { - return err - } - } else { - // Ran out of fixed array: skip. - if err := d.value(reflect.Value{}); err != nil { - return err - } - } - i++ - - // Next token must be , or ]. - if d.opcode == scanSkipSpace { - d.scanWhile(scanSkipSpace) - } - if d.opcode == scanEndArray { - break - } - if d.opcode != scanArrayValue { - panic(phasePanicMsg) - } - } - - if i < v.Len() { - if v.Kind() == reflect.Array { - for ; i < v.Len(); i++ { - v.Index(i).SetZero() // zero remainder of array - } - } else { - v.SetLen(i) // truncate the slice - } - } - if i == 0 && v.Kind() == reflect.Slice { - v.Set(reflect.MakeSlice(v.Type(), 0, 0)) - } - return nil -} - -var nullLiteral = []byte("null") - -// SHIM(reflect): reflect.TypeFor[T]() reflect.T -var textUnmarshalerType = shims.TypeFor[encoding.TextUnmarshaler]() - -// object consumes an object from d.data[d.off-1:], decoding into v. -// The first byte ('{') of the object has been read already. -func (d *decodeState) object(v reflect.Value) error { - // Check for unmarshaler. - u, ut, pv := indirect(v, false) - if u != nil { - start := d.readIndex() - d.skip() - return u.UnmarshalJSON(d.data[start:d.off]) - } - if ut != nil { - d.saveError(&UnmarshalTypeError{Value: "object", Type: v.Type(), Offset: int64(d.off)}) - d.skip() - return nil - } - v = pv - t := v.Type() - - // Decoding into nil interface? Switch to non-reflect code. - if v.Kind() == reflect.Interface && v.NumMethod() == 0 { - oi := d.objectInterface() - v.Set(reflect.ValueOf(oi)) - return nil - } - - var fields structFields - - // Check type of target: - // struct or - // map[T1]T2 where T1 is string, an integer type, - // or an encoding.TextUnmarshaler - switch v.Kind() { - case reflect.Map: - // Map key must either have string kind, have an integer kind, - // or be an encoding.TextUnmarshaler. - switch t.Key().Kind() { - case reflect.String, - reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, - reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - default: - if !reflect.PointerTo(t.Key()).Implements(textUnmarshalerType) { - d.saveError(&UnmarshalTypeError{Value: "object", Type: t, Offset: int64(d.off)}) - d.skip() - return nil - } - } - if v.IsNil() { - v.Set(reflect.MakeMap(t)) - } - case reflect.Struct: - fields = cachedTypeFields(t) - // ok - default: - d.saveError(&UnmarshalTypeError{Value: "object", Type: t, Offset: int64(d.off)}) - d.skip() - return nil - } - - var mapElem reflect.Value - var origErrorContext errorContext - if d.errorContext != nil { - origErrorContext = *d.errorContext - } - - for { - // Read opening " of string key or closing }. - d.scanWhile(scanSkipSpace) - if d.opcode == scanEndObject { - // closing } - can only happen on first iteration. - break - } - if d.opcode != scanBeginLiteral { - panic(phasePanicMsg) - } - - // Read key. - start := d.readIndex() - d.rescanLiteral() - item := d.data[start:d.readIndex()] - key, ok := unquoteBytes(item) - if !ok { - panic(phasePanicMsg) - } - - // Figure out field corresponding to key. - var subv reflect.Value - destring := false // whether the value is wrapped in a string to be decoded first - - if v.Kind() == reflect.Map { - elemType := t.Elem() - if !mapElem.IsValid() { - mapElem = reflect.New(elemType).Elem() - } else { - mapElem.SetZero() - } - subv = mapElem - } else { - f := fields.byExactName[string(key)] - if f == nil { - f = fields.byFoldedName[string(foldName(key))] - } - if f != nil { - subv = v - destring = f.quoted - if d.errorContext == nil { - d.errorContext = new(errorContext) - } - for i, ind := range f.index { - if subv.Kind() == reflect.Pointer { - if subv.IsNil() { - // If a struct embeds a pointer to an unexported type, - // it is not possible to set a newly allocated value - // since the field is unexported. - // - // See https://golang.org/issue/21357 - if !subv.CanSet() { - d.saveError(fmt.Errorf("json: cannot set embedded pointer to unexported struct: %v", subv.Type().Elem())) - // Invalidate subv to ensure d.value(subv) skips over - // the JSON value without assigning it to subv. - subv = reflect.Value{} - destring = false - break - } - subv.Set(reflect.New(subv.Type().Elem())) - } - subv = subv.Elem() - } - if i < len(f.index)-1 { - d.errorContext.FieldStack = append( - d.errorContext.FieldStack, - subv.Type().Field(ind).Name, - ) - } - subv = subv.Field(ind) - } - d.errorContext.Struct = t - d.errorContext.FieldStack = append(d.errorContext.FieldStack, f.name) - } else if d.disallowUnknownFields { - d.saveError(fmt.Errorf("json: unknown field %q", key)) - } - } - - // Read : before value. - if d.opcode == scanSkipSpace { - d.scanWhile(scanSkipSpace) - } - if d.opcode != scanObjectKey { - panic(phasePanicMsg) - } - d.scanWhile(scanSkipSpace) - - if destring { - switch qv := d.valueQuoted().(type) { - case nil: - if err := d.literalStore(nullLiteral, subv, false); err != nil { - return err - } - case string: - if err := d.literalStore([]byte(qv), subv, true); err != nil { - return err - } - default: - d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal unquoted value into %v", subv.Type())) - } - } else { - if err := d.value(subv); err != nil { - return err - } - } - - // Write value back to map; - // if using struct, subv points into struct already. - if v.Kind() == reflect.Map { - kt := t.Key() - var kv reflect.Value - if reflect.PointerTo(kt).Implements(textUnmarshalerType) { - kv = reflect.New(kt) - if err := d.literalStore(item, kv, true); err != nil { - return err - } - kv = kv.Elem() - } else { - switch kt.Kind() { - case reflect.String: - kv = reflect.New(kt).Elem() - kv.SetString(string(key)) - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - s := string(key) - n, err := strconv.ParseInt(s, 10, 64) - // SHIM(reflect): reflect.Type.OverflowInt(int64) bool - okt := shims.OverflowableType{Type: kt} - if err != nil || okt.OverflowInt(n) { - d.saveError(&UnmarshalTypeError{Value: "number " + s, Type: kt, Offset: int64(start + 1)}) - break - } - kv = reflect.New(kt).Elem() - kv.SetInt(n) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - s := string(key) - n, err := strconv.ParseUint(s, 10, 64) - // SHIM(reflect): reflect.Type.OverflowUint(uint64) bool - okt := shims.OverflowableType{Type: kt} - if err != nil || okt.OverflowUint(n) { - d.saveError(&UnmarshalTypeError{Value: "number " + s, Type: kt, Offset: int64(start + 1)}) - break - } - kv = reflect.New(kt).Elem() - kv.SetUint(n) - default: - panic("json: Unexpected key type") // should never occur - } - } - if kv.IsValid() { - v.SetMapIndex(kv, subv) - } - } - - // Next token must be , or }. - if d.opcode == scanSkipSpace { - d.scanWhile(scanSkipSpace) - } - if d.errorContext != nil { - // Reset errorContext to its original state. - // Keep the same underlying array for FieldStack, to reuse the - // space and avoid unnecessary allocs. - d.errorContext.FieldStack = d.errorContext.FieldStack[:len(origErrorContext.FieldStack)] - d.errorContext.Struct = origErrorContext.Struct - } - if d.opcode == scanEndObject { - break - } - if d.opcode != scanObjectValue { - panic(phasePanicMsg) - } - } - return nil -} - -// convertNumber converts the number literal s to a float64 or a Number -// depending on the setting of d.useNumber. -func (d *decodeState) convertNumber(s string) (any, error) { - if d.useNumber { - return Number(s), nil - } - f, err := strconv.ParseFloat(s, 64) - if err != nil { - // SHIM(reflect): reflect.TypeFor[T]() reflect.Type - return nil, &UnmarshalTypeError{Value: "number " + s, Type: shims.TypeFor[float64](), Offset: int64(d.off)} - } - return f, nil -} - -// SHIM(reflect): TypeFor[T]() reflect.Type -var numberType = shims.TypeFor[Number]() - -// literalStore decodes a literal stored in item into v. -// -// fromQuoted indicates whether this literal came from unwrapping a -// string from the ",string" struct tag option. this is used only to -// produce more helpful error messages. -func (d *decodeState) literalStore(item []byte, v reflect.Value, fromQuoted bool) error { - // Check for unmarshaler. - if len(item) == 0 { - // Empty string given. - d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())) - return nil - } - isNull := item[0] == 'n' // null - u, ut, pv := indirect(v, isNull) - if u != nil { - return u.UnmarshalJSON(item) - } - if ut != nil { - if item[0] != '"' { - if fromQuoted { - d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())) - return nil - } - val := "number" - switch item[0] { - case 'n': - val = "null" - case 't', 'f': - val = "bool" - } - d.saveError(&UnmarshalTypeError{Value: val, Type: v.Type(), Offset: int64(d.readIndex())}) - return nil - } - s, ok := unquoteBytes(item) - if !ok { - if fromQuoted { - return fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type()) - } - panic(phasePanicMsg) - } - return ut.UnmarshalText(s) - } - - v = pv - - switch c := item[0]; c { - case 'n': // null - // The main parser checks that only true and false can reach here, - // but if this was a quoted string input, it could be anything. - if fromQuoted && string(item) != "null" { - d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())) - break - } - switch v.Kind() { - case reflect.Interface, reflect.Pointer, reflect.Map, reflect.Slice: - v.SetZero() - // otherwise, ignore null for primitives/string - } - case 't', 'f': // true, false - value := item[0] == 't' - // The main parser checks that only true and false can reach here, - // but if this was a quoted string input, it could be anything. - if fromQuoted && string(item) != "true" && string(item) != "false" { - d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())) - break - } - switch v.Kind() { - default: - if fromQuoted { - d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())) - } else { - d.saveError(&UnmarshalTypeError{Value: "bool", Type: v.Type(), Offset: int64(d.readIndex())}) - } - case reflect.Bool: - v.SetBool(value) - case reflect.Interface: - if v.NumMethod() == 0 { - v.Set(reflect.ValueOf(value)) - } else { - d.saveError(&UnmarshalTypeError{Value: "bool", Type: v.Type(), Offset: int64(d.readIndex())}) - } - } - - case '"': // string - s, ok := unquoteBytes(item) - if !ok { - if fromQuoted { - return fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type()) - } - panic(phasePanicMsg) - } - switch v.Kind() { - default: - d.saveError(&UnmarshalTypeError{Value: "string", Type: v.Type(), Offset: int64(d.readIndex())}) - case reflect.Slice: - if v.Type().Elem().Kind() != reflect.Uint8 { - d.saveError(&UnmarshalTypeError{Value: "string", Type: v.Type(), Offset: int64(d.readIndex())}) - break - } - b := make([]byte, base64.StdEncoding.DecodedLen(len(s))) - n, err := base64.StdEncoding.Decode(b, s) - if err != nil { - d.saveError(err) - break - } - v.SetBytes(b[:n]) - case reflect.String: - t := string(s) - if v.Type() == numberType && !isValidNumber(t) { - return fmt.Errorf("json: invalid number literal, trying to unmarshal %q into Number", item) - } - v.SetString(t) - case reflect.Interface: - if v.NumMethod() == 0 { - v.Set(reflect.ValueOf(string(s))) - } else { - d.saveError(&UnmarshalTypeError{Value: "string", Type: v.Type(), Offset: int64(d.readIndex())}) - } - } - - default: // number - if c != '-' && (c < '0' || c > '9') { - if fromQuoted { - return fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type()) - } - panic(phasePanicMsg) - } - switch v.Kind() { - default: - if v.Kind() == reflect.String && v.Type() == numberType { - // s must be a valid number, because it's - // already been tokenized. - v.SetString(string(item)) - break - } - if fromQuoted { - return fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type()) - } - d.saveError(&UnmarshalTypeError{Value: "number", Type: v.Type(), Offset: int64(d.readIndex())}) - case reflect.Interface: - n, err := d.convertNumber(string(item)) - if err != nil { - d.saveError(err) - break - } - if v.NumMethod() != 0 { - d.saveError(&UnmarshalTypeError{Value: "number", Type: v.Type(), Offset: int64(d.readIndex())}) - break - } - v.Set(reflect.ValueOf(n)) - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - n, err := strconv.ParseInt(string(item), 10, 64) - if err != nil || v.OverflowInt(n) { - d.saveError(&UnmarshalTypeError{Value: "number " + string(item), Type: v.Type(), Offset: int64(d.readIndex())}) - break - } - v.SetInt(n) - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - n, err := strconv.ParseUint(string(item), 10, 64) - if err != nil || v.OverflowUint(n) { - d.saveError(&UnmarshalTypeError{Value: "number " + string(item), Type: v.Type(), Offset: int64(d.readIndex())}) - break - } - v.SetUint(n) - - case reflect.Float32, reflect.Float64: - n, err := strconv.ParseFloat(string(item), v.Type().Bits()) - if err != nil || v.OverflowFloat(n) { - d.saveError(&UnmarshalTypeError{Value: "number " + string(item), Type: v.Type(), Offset: int64(d.readIndex())}) - break - } - v.SetFloat(n) - } - } - return nil -} - -// The xxxInterface routines build up a value to be stored -// in an empty interface. They are not strictly necessary, -// but they avoid the weight of reflection in this common case. - -// valueInterface is like value but returns any. -func (d *decodeState) valueInterface() (val any) { - switch d.opcode { - default: - panic(phasePanicMsg) - case scanBeginArray: - val = d.arrayInterface() - d.scanNext() - case scanBeginObject: - val = d.objectInterface() - d.scanNext() - case scanBeginLiteral: - val = d.literalInterface() - } - return -} - -// arrayInterface is like array but returns []any. -func (d *decodeState) arrayInterface() []any { - var v = make([]any, 0) - for { - // Look ahead for ] - can only happen on first iteration. - d.scanWhile(scanSkipSpace) - if d.opcode == scanEndArray { - break - } - - v = append(v, d.valueInterface()) - - // Next token must be , or ]. - if d.opcode == scanSkipSpace { - d.scanWhile(scanSkipSpace) - } - if d.opcode == scanEndArray { - break - } - if d.opcode != scanArrayValue { - panic(phasePanicMsg) - } - } - return v -} - -// objectInterface is like object but returns map[string]any. -func (d *decodeState) objectInterface() map[string]any { - m := make(map[string]any) - for { - // Read opening " of string key or closing }. - d.scanWhile(scanSkipSpace) - if d.opcode == scanEndObject { - // closing } - can only happen on first iteration. - break - } - if d.opcode != scanBeginLiteral { - panic(phasePanicMsg) - } - - // Read string key. - start := d.readIndex() - d.rescanLiteral() - item := d.data[start:d.readIndex()] - key, ok := unquote(item) - if !ok { - panic(phasePanicMsg) - } - - // Read : before value. - if d.opcode == scanSkipSpace { - d.scanWhile(scanSkipSpace) - } - if d.opcode != scanObjectKey { - panic(phasePanicMsg) - } - d.scanWhile(scanSkipSpace) - - // Read value. - m[key] = d.valueInterface() - - // Next token must be , or }. - if d.opcode == scanSkipSpace { - d.scanWhile(scanSkipSpace) - } - if d.opcode == scanEndObject { - break - } - if d.opcode != scanObjectValue { - panic(phasePanicMsg) - } - } - return m -} - -// literalInterface consumes and returns a literal from d.data[d.off-1:] and -// it reads the following byte ahead. The first byte of the literal has been -// read already (that's how the caller knows it's a literal). -func (d *decodeState) literalInterface() any { - // All bytes inside literal return scanContinue op code. - start := d.readIndex() - d.rescanLiteral() - - item := d.data[start:d.readIndex()] - - switch c := item[0]; c { - case 'n': // null - return nil - - case 't', 'f': // true, false - return c == 't' - - case '"': // string - s, ok := unquote(item) - if !ok { - panic(phasePanicMsg) - } - return s - - default: // number - if c != '-' && (c < '0' || c > '9') { - panic(phasePanicMsg) - } - n, err := d.convertNumber(string(item)) - if err != nil { - d.saveError(err) - } - return n - } -} - -// getu4 decodes \uXXXX from the beginning of s, returning the hex value, -// or it returns -1. -func getu4(s []byte) rune { - if len(s) < 6 || s[0] != '\\' || s[1] != 'u' { - return -1 - } - var r rune - for _, c := range s[2:6] { - switch { - case '0' <= c && c <= '9': - c = c - '0' - case 'a' <= c && c <= 'f': - c = c - 'a' + 10 - case 'A' <= c && c <= 'F': - c = c - 'A' + 10 - default: - return -1 - } - r = r*16 + rune(c) - } - return r -} - -// unquote converts a quoted JSON string literal s into an actual string t. -// The rules are different than for Go, so cannot use strconv.Unquote. -func unquote(s []byte) (t string, ok bool) { - s, ok = unquoteBytes(s) - t = string(s) - return -} - -// unquoteBytes should be an internal detail, -// but widely used packages access it using linkname. -// Notable members of the hall of shame include: -// - github.com/bytedance/sonic -// -// Do not remove or change the type signature. -// See go.dev/issue/67401. -// -//go:linkname unquoteBytes -func unquoteBytes(s []byte) (t []byte, ok bool) { - if len(s) < 2 || s[0] != '"' || s[len(s)-1] != '"' { - return - } - s = s[1 : len(s)-1] - - // Check for unusual characters. If there are none, - // then no unquoting is needed, so return a slice of the - // original bytes. - r := 0 - for r < len(s) { - c := s[r] - if c == '\\' || c == '"' || c < ' ' { - break - } - if c < utf8.RuneSelf { - r++ - continue - } - rr, size := utf8.DecodeRune(s[r:]) - if rr == utf8.RuneError && size == 1 { - break - } - r += size - } - if r == len(s) { - return s, true - } - - b := make([]byte, len(s)+2*utf8.UTFMax) - w := copy(b, s[0:r]) - for r < len(s) { - // Out of room? Can only happen if s is full of - // malformed UTF-8 and we're replacing each - // byte with RuneError. - if w >= len(b)-2*utf8.UTFMax { - nb := make([]byte, (len(b)+utf8.UTFMax)*2) - copy(nb, b[0:w]) - b = nb - } - switch c := s[r]; { - case c == '\\': - r++ - if r >= len(s) { - return - } - switch s[r] { - default: - return - case '"', '\\', '/', '\'': - b[w] = s[r] - r++ - w++ - case 'b': - b[w] = '\b' - r++ - w++ - case 'f': - b[w] = '\f' - r++ - w++ - case 'n': - b[w] = '\n' - r++ - w++ - case 'r': - b[w] = '\r' - r++ - w++ - case 't': - b[w] = '\t' - r++ - w++ - case 'u': - r-- - rr := getu4(s[r:]) - if rr < 0 { - return - } - r += 6 - if utf16.IsSurrogate(rr) { - rr1 := getu4(s[r:]) - if dec := utf16.DecodeRune(rr, rr1); dec != unicode.ReplacementChar { - // A valid pair; consume. - r += 6 - w += utf8.EncodeRune(b[w:], dec) - break - } - // Invalid surrogate; fall back to replacement rune. - rr = unicode.ReplacementChar - } - w += utf8.EncodeRune(b[w:], rr) - } - - // Quote, control characters are invalid. - case c == '"', c < ' ': - return - - // ASCII - case c < utf8.RuneSelf: - b[w] = c - r++ - w++ - - // Coerce to well-formed UTF-8. - default: - rr, size := utf8.DecodeRune(s[r:]) - r += size - w += utf8.EncodeRune(b[w:], rr) - } - } - return b[0:w], true -} diff --git a/vendor/github.com/openai/openai-go/internal/encoding/json/encode.go b/vendor/github.com/openai/openai-go/internal/encoding/json/encode.go deleted file mode 100644 index d5471325..00000000 --- a/vendor/github.com/openai/openai-go/internal/encoding/json/encode.go +++ /dev/null @@ -1,1391 +0,0 @@ -// Vendored from Go 1.24.0-pre-release -// To find alterations, check package shims, and comments beginning in SHIM(). -// -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package json implements encoding and decoding of JSON as defined in -// RFC 7159. The mapping between JSON and Go values is described -// in the documentation for the Marshal and Unmarshal functions. -// -// See "JSON and Go" for an introduction to this package: -// https://golang.org/doc/articles/json_and_go.html -package json - -import ( - "bytes" - "cmp" - "encoding" - "encoding/base64" - "fmt" - "github.com/openai/openai-go/internal/encoding/json/sentinel" - "github.com/openai/openai-go/internal/encoding/json/shims" - "math" - "reflect" - "slices" - "strconv" - "strings" - "sync" - "unicode" - "unicode/utf8" - _ "unsafe" // for linkname -) - -// Marshal returns the JSON encoding of v. -// -// Marshal traverses the value v recursively. -// If an encountered value implements [Marshaler] -// and is not a nil pointer, Marshal calls [Marshaler.MarshalJSON] -// to produce JSON. If no [Marshaler.MarshalJSON] method is present but the -// value implements [encoding.TextMarshaler] instead, Marshal calls -// [encoding.TextMarshaler.MarshalText] and encodes the result as a JSON string. -// The nil pointer exception is not strictly necessary -// but mimics a similar, necessary exception in the behavior of -// [Unmarshaler.UnmarshalJSON]. -// -// Otherwise, Marshal uses the following type-dependent default encodings: -// -// Boolean values encode as JSON booleans. -// -// Floating point, integer, and [Number] values encode as JSON numbers. -// NaN and +/-Inf values will return an [UnsupportedValueError]. -// -// String values encode as JSON strings coerced to valid UTF-8, -// replacing invalid bytes with the Unicode replacement rune. -// So that the JSON will be safe to embed inside HTML