feat: decommission nomos agent runtime (plan §5)
Replace nomos with dsh (DeepSeek Harness) as the agent runtime per
plans/2026-08-16-dsh-as-agent-replace-nomos.md section 5.
Deleted:
- cmd/nomos/ (agent loop, :8092 chat gateway, task tools, eval runner)
- nomos/ (SOUL.md, config.yaml, skills/)
- internal/nomos/{session,messagequeue,retrycap,turngate,assent}/
- compose/nomos/ Dockerfile + docker-compose nomos service
- httpapi /agent reverse-proxy mount (NOMOS_PROXY_URL)
- evals/*.yaml (nomos golden-conversation manifests)
- compose/caddy/Caddyfile.oikos nomos.hubris.network block + /agent path
- .golangci.yml nomos-isolation rules
- go.mod openai-go dependency (go mod tidy)
Kept:
- internal/adapters/postgres assent-window logic (governance port)
- OIKOS_NOMOS_AGENT_SLUG config (MCP agent entity attribution)
- Full REST API, MCP tools, policy, scheduler, secrets
Cleaned: deploy.sh image prune, verify-phase6.sh checks,
seed-secrets.sh key source, README/CONTRIBUTING/AGENTS.md docs.
Build, vet, test, compose config all pass.
This commit is contained in:
@@ -12,22 +12,18 @@ linters:
|
|||||||
- revive
|
- revive
|
||||||
settings:
|
settings:
|
||||||
depguard:
|
depguard:
|
||||||
# ADR 0016 dependency rules. Rules only constrain files that exist:
|
# ADR 0016 dependency rules. The nomos packages (and their bans) were
|
||||||
# internal/core is live since Phase 0 (domain moved); internal/nomos
|
# removed with the nomos decommission — the agent runtime is dsh, an
|
||||||
# and its bans activate in Phase 8; full audit at Phase 9.
|
# external MCP client.
|
||||||
rules:
|
rules:
|
||||||
core-no-agent-tech:
|
core-no-agent-tech:
|
||||||
files:
|
files:
|
||||||
- "**/internal/core/**"
|
- "**/internal/core/**"
|
||||||
deny:
|
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
|
- 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/**
|
- 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
|
- pkg: github.com/modelcontextprotocol/go-sdk
|
||||||
desc: core never links MCP packages — mcpserver is a driving adapter
|
desc: core never links MCP packages — mcpserver is a driving adapter
|
||||||
- pkg: github.com/modelcontextprotocol/go-sdk/**
|
- pkg: github.com/modelcontextprotocol/go-sdk/**
|
||||||
@@ -44,18 +40,6 @@ linters:
|
|||||||
desc: core must not import composition roots
|
desc: core must not import composition roots
|
||||||
- pkg: github.com/dtoro/oikos/cmd/**
|
- pkg: github.com/dtoro/oikos/cmd/**
|
||||||
desc: core must not import composition roots
|
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:
|
errcheck:
|
||||||
# Allow unchecked errors on common Close/Flush patterns (deferred cleanup)
|
# Allow unchecked errors on common Close/Flush patterns (deferred cleanup)
|
||||||
exclude-functions:
|
exclude-functions:
|
||||||
|
|||||||
@@ -3,10 +3,9 @@
|
|||||||
# Lives in dtoro/caddy-conf repo; auto-deploys to caddy (LXC 121). THIS COPY
|
# 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.
|
# 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
|
# The SPA lives in its own repo (dtoro/oikos-web) and deploys as its own
|
||||||
# by its own container (compose/web/Dockerfile, docker-compose.yml's `web`
|
# compose project publishing mac-mini:8091 — see the docker-compose.yml
|
||||||
# service, mac-mini:8091) rather than as static files read off local disk —
|
# comment. Every API/MCP route requires
|
||||||
# see that service's comment for why. Every API/MCP/agent route now requires
|
|
||||||
# a bearer token in all cases (api's dev-open bypass was removed) —
|
# 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
|
# non-browser clients (Wails, curl, a future mobile client) can't complete
|
||||||
# Authentik's browser-session login, so those routes bypass `import
|
# Authentik's browser-session login, so those routes bypass `import
|
||||||
@@ -26,11 +25,10 @@ oikos.hubris.network {
|
|||||||
reverse_proxy 192.168.178.182:8090
|
reverse_proxy 192.168.178.182:8090
|
||||||
}
|
}
|
||||||
# Bearer-token clients — api's combinedAuth (internal/httpapi/server.go)
|
# Bearer-token clients — api's combinedAuth (internal/httpapi/server.go)
|
||||||
# is the real gate for all three; Authentik would just reject non-browser
|
# is the real gate; Authentik would just reject non-browser callers
|
||||||
# callers before they ever get there. /agent/* now goes through api's own
|
# before they ever get there, so /api/v1/* and /mcp bypass `import
|
||||||
# (auth'd) proxy mount rather than straight to nomos:8092, so it's
|
# authentik` and rely on api's own combinedAuth.
|
||||||
# covered by the same check as /api/v1/* and /mcp.
|
@api path /api/v1/* /mcp
|
||||||
@api path /api/v1/* /mcp /agent/*
|
|
||||||
handle @api {
|
handle @api {
|
||||||
reverse_proxy 192.168.178.182:8090
|
reverse_proxy 192.168.178.182:8090
|
||||||
}
|
}
|
||||||
@@ -50,10 +48,7 @@ mcp.hubris.network {
|
|||||||
reverse_proxy 192.168.178.182:8090
|
reverse_proxy 192.168.178.182:8090
|
||||||
}
|
}
|
||||||
|
|
||||||
# Nomos's own gateway (workstation access) — still has NO auth of its own
|
# nomos.hubris.network (the retired nomos gateway, :8092) was removed with
|
||||||
# (C1, plans/2026-07-11-nomos-agent-code-review.md, still open). Anyone who
|
# the nomos decommission — plans/2026-08-16-dsh-as-agent-replace-nomos.md
|
||||||
# can reach this host can talk to nomos directly, bypassing api entirely.
|
# section 5. The agent runtime is dsh (external MCP client, no inbound
|
||||||
# Not fixed by the client/server split — tracked separately.
|
# gateway). Remember to mirror this removal in dtoro/caddy-conf.
|
||||||
nomos.hubris.network {
|
|
||||||
reverse_proxy 192.168.178.182:8092
|
|
||||||
}
|
|
||||||
|
|||||||
5
go.mod
5
go.mod
@@ -13,7 +13,6 @@ require (
|
|||||||
github.com/jackc/pgx/v5 v5.10.0
|
github.com/jackc/pgx/v5 v5.10.0
|
||||||
github.com/modelcontextprotocol/go-sdk v1.6.1
|
github.com/modelcontextprotocol/go-sdk v1.6.1
|
||||||
github.com/oapi-codegen/runtime v1.4.2
|
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/crypto v0.53.0
|
||||||
golang.org/x/sync v0.21.0
|
golang.org/x/sync v0.21.0
|
||||||
golang.org/x/sys v0.46.0
|
golang.org/x/sys v0.46.0
|
||||||
@@ -65,10 +64,6 @@ require (
|
|||||||
github.com/segmentio/asm v1.1.3 // indirect
|
github.com/segmentio/asm v1.1.3 // indirect
|
||||||
github.com/segmentio/encoding v0.5.4 // indirect
|
github.com/segmentio/encoding v0.5.4 // indirect
|
||||||
github.com/sony/gobreaker v0.5.0 // 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/yosida95/uritemplate/v3 v3.0.2 // indirect
|
||||||
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect
|
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect
|
||||||
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
||||||
|
|||||||
12
go.sum
12
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/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 h1:06svmvOHOVBqF81+sY2EUScvUI/iS/vl2VIeUUxZQwg=
|
||||||
github.com/oasdiff/yaml3 v0.0.13/go.mod h1:y5+oSEHCPT/DGrS++Wc/479ERge0zTFxaF8PbGKcg2o=
|
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 h1:0HJ0AgpLydp/DtvYrF2d4str2BjXOVAeNbuW7E07g94=
|
||||||
github.com/oracle/oci-go-sdk/v65 v65.95.2/go.mod h1:u6XRPsw9tPziBh76K7GrrRXPa8P8W3BQeqJ6ZZt9VLA=
|
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=
|
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.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 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
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 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
|
||||||
github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
|
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=
|
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 h1:ilQV1hzziu+LLM3zUTJ0trRztfwgjqKnBWNtSRkbmwM=
|
||||||
|
|||||||
@@ -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 <uuid> 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")
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -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))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -320,18 +320,23 @@ Each plugin:
|
|||||||
- `evals/*.yaml` — nomos golden-conversation manifests (their only runner was
|
- `evals/*.yaml` — nomos golden-conversation manifests (their only runner was
|
||||||
`cmd/nomos/eval`; dsh evals live at `packages/oikos/evals` in the harness
|
`cmd/nomos/eval`; dsh evals live at `packages/oikos/evals` in the harness
|
||||||
workspace)
|
workspace)
|
||||||
- Script/doc cleanup: deploy.sh image list, verify-phase6.sh gateway checks,
|
- Script/doc cleanup: deploy.sh image list (+ one-time oikos-nomos image
|
||||||
seed-secrets.sh OpenRouter key source (host env now), README/CONTRIBUTING/
|
prune), verify-phase6.sh gateway checks, seed-secrets.sh OpenRouter key
|
||||||
AGENTS.md/operator-facing comments
|
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
|
**Already gone before this pass:** `compose/web/` (SPA extracted to
|
||||||
dtoro/oikos-web), `desktop/` (Wails wrapper, deleted with the SPA split).
|
dtoro/oikos-web), `desktop/` (Wails wrapper, deleted with the SPA split).
|
||||||
|
|
||||||
**Kept (per the stays list):**
|
**Kept (per the stays list):**
|
||||||
- `internal/nomos/assent/` — chat-assent/typed-confirmation parsing; the
|
- ~~`internal/nomos/assent/`~~ — deleted after review: zero importers
|
||||||
assent *window* logic lives in `internal/adapters/postgres`
|
remained once cmd/nomos was gone (the assent *window* logic lives in
|
||||||
(governance.go/approvals.go) behind the governance port and is shared by
|
`internal/adapters/postgres` — governance.go/approvals.go — behind the
|
||||||
the dsh consent flow
|
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/httpapi/` REST API, `internal/mcp/` (67+ tools),
|
||||||
`internal/policy/`, `internal/scheduler/`, `internal/secrets/`
|
`internal/policy/`, `internal/scheduler/`, `internal/secrets/`
|
||||||
- `OIKOS_NOMOS_AGENT_SLUG` config + compose env — resolves the seeded
|
- `OIKOS_NOMOS_AGENT_SLUG` config + compose env — resolves the seeded
|
||||||
|
|||||||
@@ -247,6 +247,13 @@ if [ -n "$OIKOS_VERSION" ]; then
|
|||||||
done
|
done
|
||||||
fi
|
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 ──────────────────────────────────────────────────
|
# ── 7. Health check wait ──────────────────────────────────────────────────
|
||||||
echo "[7/8] health check"
|
echo "[7/8] health check"
|
||||||
healthy=0
|
healthy=0
|
||||||
|
|||||||
4
vendor/github.com/openai/openai-go/.gitignore
generated
vendored
4
vendor/github.com/openai/openai-go/.gitignore
generated
vendored
@@ -1,4 +0,0 @@
|
|||||||
.prism.log
|
|
||||||
codegen.log
|
|
||||||
Brewfile.lock.json
|
|
||||||
.idea/
|
|
||||||
3
vendor/github.com/openai/openai-go/.release-please-manifest.json
generated
vendored
3
vendor/github.com/openai/openai-go/.release-please-manifest.json
generated
vendored
@@ -1,3 +0,0 @@
|
|||||||
{
|
|
||||||
".": "1.12.0"
|
|
||||||
}
|
|
||||||
4
vendor/github.com/openai/openai-go/.stats.yml
generated
vendored
4
vendor/github.com/openai/openai-go/.stats.yml
generated
vendored
@@ -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
|
|
||||||
1
vendor/github.com/openai/openai-go/Brewfile
generated
vendored
1
vendor/github.com/openai/openai-go/Brewfile
generated
vendored
@@ -1 +0,0 @@
|
|||||||
brew "go"
|
|
||||||
473
vendor/github.com/openai/openai-go/CHANGELOG.md
generated
vendored
473
vendor/github.com/openai/openai-go/CHANGELOG.md
generated
vendored
@@ -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))
|
|
||||||
66
vendor/github.com/openai/openai-go/CONTRIBUTING.md
generated
vendored
66
vendor/github.com/openai/openai-go/CONTRIBUTING.md
generated
vendored
@@ -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/<your-example>/main.go
|
|
||||||
|
|
||||||
package main
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
// ...
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
```sh
|
|
||||||
$ go run ./examples/<your-example>
|
|
||||||
```
|
|
||||||
|
|
||||||
## 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
|
|
||||||
```
|
|
||||||
201
vendor/github.com/openai/openai-go/LICENSE
generated
vendored
201
vendor/github.com/openai/openai-go/LICENSE
generated
vendored
@@ -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.
|
|
||||||
284
vendor/github.com/openai/openai-go/MIGRATION.md
generated
vendored
284
vendor/github.com/openai/openai-go/MIGRATION.md
generated
vendored
@@ -1,284 +0,0 @@
|
|||||||
# OpenAI Go Migration Guide
|
|
||||||
|
|
||||||
<a href="https://pkg.go.dev/github.com/openai/openai-go"><img src="https://pkg.go.dev/badge/github.com/openai/openai-go.svg" alt="Go Reference"></a>
|
|
||||||
|
|
||||||
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 <code>\`json:"...,omitzero"\`</code> 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 <code>\`json:"age,required"\`</code> 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"`
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
<table>
|
|
||||||
<tr>
|
|
||||||
<th>Previous</th>
|
|
||||||
<th>New</th>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td>
|
|
||||||
|
|
||||||
```go
|
|
||||||
_ = FooParams{
|
|
||||||
Name: openai.String("Jerry")
|
|
||||||
}
|
|
||||||
`{"name": "Jerry"}` // (after serialization)
|
|
||||||
```
|
|
||||||
|
|
||||||
</td>
|
|
||||||
<td>
|
|
||||||
|
|
||||||
```go
|
|
||||||
_ = FooParams{
|
|
||||||
Name: openai.String("Jerry")
|
|
||||||
}
|
|
||||||
`{"name": "Jerry", "age": 0}` // <== Notice the age field
|
|
||||||
```
|
|
||||||
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
</table>
|
|
||||||
|
|
||||||
The required field `"age"` is now present as `0`. Fields without the <code>\`json:"...,omitzero"\`</code> 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 <a href="https://pkg.go.dev/encoding/json#Marshal"><code>\`json:"...,omitzero"\`</code> semantics</a> 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`.
|
|
||||||
|
|
||||||
<table>
|
|
||||||
<tr><th>Previous</th> <th>New</th></tr>
|
|
||||||
<tr>
|
|
||||||
<td>
|
|
||||||
|
|
||||||
```go
|
|
||||||
type AnimalParam interface {
|
|
||||||
ImplAnimalParam()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (Dog) ImplAnimalParam() {}
|
|
||||||
func (Cat) ImplAnimalParam() {}
|
|
||||||
```
|
|
||||||
|
|
||||||
</td>
|
|
||||||
<td>
|
|
||||||
|
|
||||||
```go
|
|
||||||
type AnimalUnionParam struct {
|
|
||||||
OfCat *Cat `json:",omitzero,inline`
|
|
||||||
OfDog *Dog `json:",omitzero,inline`
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
|
|
||||||
<tr style="background:rgb(209, 217, 224)">
|
|
||||||
<td>
|
|
||||||
|
|
||||||
```go
|
|
||||||
var dog AnimalParam = DogParam{
|
|
||||||
Name: "spot", ...
|
|
||||||
}
|
|
||||||
var cat AnimalParam = CatParam{
|
|
||||||
Name: "whiskers", ...
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
</td>
|
|
||||||
<td>
|
|
||||||
|
|
||||||
```go
|
|
||||||
dog := AnimalUnionParam{
|
|
||||||
OfDog: &DogParam{Name: "spot", ... },
|
|
||||||
}
|
|
||||||
cat := AnimalUnionParam{
|
|
||||||
OfCat: &CatParam{Name: "whiskers", ... },
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
|
|
||||||
<tr>
|
|
||||||
<td>
|
|
||||||
|
|
||||||
```go
|
|
||||||
var name string
|
|
||||||
switch v := animal.(type) {
|
|
||||||
case Dog:
|
|
||||||
name = v.Name
|
|
||||||
case Cat:
|
|
||||||
name = v.Name
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
</td>
|
|
||||||
<td>
|
|
||||||
|
|
||||||
```go
|
|
||||||
// Accessing fields
|
|
||||||
var name *string = animal.GetName()
|
|
||||||
```
|
|
||||||
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
</table>
|
|
||||||
|
|
||||||
## 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
|
|
||||||
948
vendor/github.com/openai/openai-go/README.md
generated
vendored
948
vendor/github.com/openai/openai-go/README.md
generated
vendored
@@ -1,948 +0,0 @@
|
|||||||
# OpenAI Go API Library
|
|
||||||
|
|
||||||
<a href="https://pkg.go.dev/github.com/openai/openai-go"><img src="https://pkg.go.dev/badge/github.com/openai/openai-go.svg" alt="Go Reference"></a>
|
|
||||||
|
|
||||||
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
|
|
||||||
|
|
||||||
<!-- x-release-please-start-version -->
|
|
||||||
|
|
||||||
```go
|
|
||||||
import (
|
|
||||||
"github.com/openai/openai-go" // imported as openai
|
|
||||||
)
|
|
||||||
```
|
|
||||||
|
|
||||||
<!-- x-release-please-end -->
|
|
||||||
|
|
||||||
Or to pin the version:
|
|
||||||
|
|
||||||
<!-- x-release-please-start-version -->
|
|
||||||
|
|
||||||
```sh
|
|
||||||
go get -u 'github.com/openai/openai-go@v1.12.0'
|
|
||||||
```
|
|
||||||
|
|
||||||
<!-- x-release-please-end -->
|
|
||||||
|
|
||||||
## 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)
|
|
||||||
}
|
|
||||||
|
|
||||||
```
|
|
||||||
|
|
||||||
<details>
|
|
||||||
<summary>Conversations</summary>
|
|
||||||
|
|
||||||
```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)
|
|
||||||
```
|
|
||||||
|
|
||||||
</details>
|
|
||||||
|
|
||||||
<details>
|
|
||||||
<summary>Streaming responses</summary>
|
|
||||||
|
|
||||||
```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)
|
|
||||||
|
|
||||||
</details>
|
|
||||||
|
|
||||||
<details>
|
|
||||||
<summary>Tool calling</summary>
|
|
||||||
|
|
||||||
```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)
|
|
||||||
|
|
||||||
</details>
|
|
||||||
|
|
||||||
<details>
|
|
||||||
<summary>Structured outputs</summary>
|
|
||||||
|
|
||||||
```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)
|
|
||||||
|
|
||||||
</details>
|
|
||||||
|
|
||||||
|
|
||||||
### 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 <code>\`json:"...,required"\`</code>. 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 <code>\`json:"...,omitzero"\`</code>. 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://<azure-openai-resource>.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).
|
|
||||||
29
vendor/github.com/openai/openai-go/SECURITY.md
generated
vendored
29
vendor/github.com/openai/openai-go/SECURITY.md
generated
vendored
@@ -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.
|
|
||||||
440
vendor/github.com/openai/openai-go/aliases.go
generated
vendored
440
vendor/github.com/openai/openai-go/aliases.go
generated
vendored
@@ -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
|
|
||||||
791
vendor/github.com/openai/openai-go/api.md
generated
vendored
791
vendor/github.com/openai/openai-go/api.md
generated
vendored
@@ -1,791 +0,0 @@
|
|||||||
# Shared Params Types
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/shared">shared</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/shared#ChatModel">ChatModel</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/shared">shared</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/shared#ComparisonFilterParam">ComparisonFilterParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/shared">shared</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/shared#CompoundFilterParam">CompoundFilterParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/shared">shared</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/shared#FunctionDefinitionParam">FunctionDefinitionParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/shared">shared</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/shared#FunctionParameters">FunctionParameters</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/shared">shared</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/shared#Metadata">Metadata</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/shared">shared</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/shared#ReasoningParam">ReasoningParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/shared">shared</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/shared#ReasoningEffort">ReasoningEffort</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/shared">shared</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/shared#ResponseFormatJSONObjectParam">ResponseFormatJSONObjectParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/shared">shared</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/shared#ResponseFormatJSONSchemaParam">ResponseFormatJSONSchemaParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/shared">shared</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/shared#ResponseFormatTextParam">ResponseFormatTextParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/shared">shared</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/shared#ResponsesModel">ResponsesModel</a>
|
|
||||||
|
|
||||||
# Shared Response Types
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/shared">shared</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/shared#ChatModel">ChatModel</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/shared">shared</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/shared#ComparisonFilter">ComparisonFilter</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/shared">shared</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/shared#CompoundFilter">CompoundFilter</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/shared">shared</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/shared#ErrorObject">ErrorObject</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/shared">shared</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/shared#FunctionDefinition">FunctionDefinition</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/shared">shared</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/shared#FunctionParameters">FunctionParameters</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/shared">shared</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/shared#Metadata">Metadata</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/shared">shared</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/shared#Reasoning">Reasoning</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/shared">shared</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/shared#ReasoningEffort">ReasoningEffort</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/shared">shared</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/shared#ResponseFormatJSONObject">ResponseFormatJSONObject</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/shared">shared</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/shared#ResponseFormatJSONSchema">ResponseFormatJSONSchema</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/shared">shared</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/shared#ResponseFormatText">ResponseFormatText</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/shared">shared</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/shared#ResponsesModel">ResponsesModel</a>
|
|
||||||
|
|
||||||
# Completions
|
|
||||||
|
|
||||||
Response Types:
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#Completion">Completion</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#CompletionChoice">CompletionChoice</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#CompletionUsage">CompletionUsage</a>
|
|
||||||
|
|
||||||
Methods:
|
|
||||||
|
|
||||||
- <code title="post /completions">client.Completions.<a href="https://pkg.go.dev/github.com/openai/openai-go#CompletionService.New">New</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, body <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#CompletionNewParams">CompletionNewParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#Completion">Completion</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
|
|
||||||
# Chat
|
|
||||||
|
|
||||||
## Completions
|
|
||||||
|
|
||||||
Params Types:
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ChatCompletionAssistantMessageParam">ChatCompletionAssistantMessageParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ChatCompletionAudioParam">ChatCompletionAudioParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ChatCompletionContentPartUnionParam">ChatCompletionContentPartUnionParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ChatCompletionContentPartImageParam">ChatCompletionContentPartImageParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ChatCompletionContentPartInputAudioParam">ChatCompletionContentPartInputAudioParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ChatCompletionContentPartRefusalParam">ChatCompletionContentPartRefusalParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ChatCompletionContentPartTextParam">ChatCompletionContentPartTextParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ChatCompletionDeveloperMessageParam">ChatCompletionDeveloperMessageParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ChatCompletionFunctionCallOptionParam">ChatCompletionFunctionCallOptionParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ChatCompletionFunctionMessageParam">ChatCompletionFunctionMessageParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ChatCompletionMessageParamUnion">ChatCompletionMessageParamUnion</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ChatCompletionMessageToolCallParam">ChatCompletionMessageToolCallParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ChatCompletionNamedToolChoiceParam">ChatCompletionNamedToolChoiceParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ChatCompletionPredictionContentParam">ChatCompletionPredictionContentParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ChatCompletionStreamOptionsParam">ChatCompletionStreamOptionsParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ChatCompletionSystemMessageParam">ChatCompletionSystemMessageParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ChatCompletionToolParam">ChatCompletionToolParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ChatCompletionToolChoiceOptionUnionParam">ChatCompletionToolChoiceOptionUnionParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ChatCompletionToolMessageParam">ChatCompletionToolMessageParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ChatCompletionUserMessageParam">ChatCompletionUserMessageParam</a>
|
|
||||||
|
|
||||||
Response Types:
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ChatCompletion">ChatCompletion</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ChatCompletionAudio">ChatCompletionAudio</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ChatCompletionChunk">ChatCompletionChunk</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ChatCompletionContentPartImage">ChatCompletionContentPartImage</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ChatCompletionContentPartText">ChatCompletionContentPartText</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ChatCompletionDeleted">ChatCompletionDeleted</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ChatCompletionMessage">ChatCompletionMessage</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ChatCompletionMessageToolCall">ChatCompletionMessageToolCall</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ChatCompletionStoreMessage">ChatCompletionStoreMessage</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ChatCompletionTokenLogprob">ChatCompletionTokenLogprob</a>
|
|
||||||
|
|
||||||
Methods:
|
|
||||||
|
|
||||||
- <code title="post /chat/completions">client.Chat.Completions.<a href="https://pkg.go.dev/github.com/openai/openai-go#ChatCompletionService.New">New</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, body <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ChatCompletionNewParams">ChatCompletionNewParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ChatCompletion">ChatCompletion</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="get /chat/completions/{completion_id}">client.Chat.Completions.<a href="https://pkg.go.dev/github.com/openai/openai-go#ChatCompletionService.Get">Get</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, completionID <a href="https://pkg.go.dev/builtin#string">string</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ChatCompletion">ChatCompletion</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="post /chat/completions/{completion_id}">client.Chat.Completions.<a href="https://pkg.go.dev/github.com/openai/openai-go#ChatCompletionService.Update">Update</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, completionID <a href="https://pkg.go.dev/builtin#string">string</a>, body <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ChatCompletionUpdateParams">ChatCompletionUpdateParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ChatCompletion">ChatCompletion</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="get /chat/completions">client.Chat.Completions.<a href="https://pkg.go.dev/github.com/openai/openai-go#ChatCompletionService.List">List</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, query <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ChatCompletionListParams">ChatCompletionListParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go/packages/pagination">pagination</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/packages/pagination#CursorPage">CursorPage</a>[<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ChatCompletion">ChatCompletion</a>], <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="delete /chat/completions/{completion_id}">client.Chat.Completions.<a href="https://pkg.go.dev/github.com/openai/openai-go#ChatCompletionService.Delete">Delete</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, completionID <a href="https://pkg.go.dev/builtin#string">string</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ChatCompletionDeleted">ChatCompletionDeleted</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
|
|
||||||
### Messages
|
|
||||||
|
|
||||||
Methods:
|
|
||||||
|
|
||||||
- <code title="get /chat/completions/{completion_id}/messages">client.Chat.Completions.Messages.<a href="https://pkg.go.dev/github.com/openai/openai-go#ChatCompletionMessageService.List">List</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, completionID <a href="https://pkg.go.dev/builtin#string">string</a>, query <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ChatCompletionMessageListParams">ChatCompletionMessageListParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go/packages/pagination">pagination</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/packages/pagination#CursorPage">CursorPage</a>[<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ChatCompletionStoreMessage">ChatCompletionStoreMessage</a>], <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
|
|
||||||
# Embeddings
|
|
||||||
|
|
||||||
Params Types:
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#EmbeddingModel">EmbeddingModel</a>
|
|
||||||
|
|
||||||
Response Types:
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#CreateEmbeddingResponse">CreateEmbeddingResponse</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#Embedding">Embedding</a>
|
|
||||||
|
|
||||||
Methods:
|
|
||||||
|
|
||||||
- <code title="post /embeddings">client.Embeddings.<a href="https://pkg.go.dev/github.com/openai/openai-go#EmbeddingService.New">New</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, body <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#EmbeddingNewParams">EmbeddingNewParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#CreateEmbeddingResponse">CreateEmbeddingResponse</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
|
|
||||||
# Files
|
|
||||||
|
|
||||||
Params Types:
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FilePurpose">FilePurpose</a>
|
|
||||||
|
|
||||||
Response Types:
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FileDeleted">FileDeleted</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FileObject">FileObject</a>
|
|
||||||
|
|
||||||
Methods:
|
|
||||||
|
|
||||||
- <code title="post /files">client.Files.<a href="https://pkg.go.dev/github.com/openai/openai-go#FileService.New">New</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, body <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FileNewParams">FileNewParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FileObject">FileObject</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="get /files/{file_id}">client.Files.<a href="https://pkg.go.dev/github.com/openai/openai-go#FileService.Get">Get</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, fileID <a href="https://pkg.go.dev/builtin#string">string</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FileObject">FileObject</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="get /files">client.Files.<a href="https://pkg.go.dev/github.com/openai/openai-go#FileService.List">List</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, query <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FileListParams">FileListParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go/packages/pagination">pagination</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/packages/pagination#CursorPage">CursorPage</a>[<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FileObject">FileObject</a>], <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="delete /files/{file_id}">client.Files.<a href="https://pkg.go.dev/github.com/openai/openai-go#FileService.Delete">Delete</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, fileID <a href="https://pkg.go.dev/builtin#string">string</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FileDeleted">FileDeleted</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="get /files/{file_id}/content">client.Files.<a href="https://pkg.go.dev/github.com/openai/openai-go#FileService.Content">Content</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, fileID <a href="https://pkg.go.dev/builtin#string">string</a>) (http.Response, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
|
|
||||||
# Images
|
|
||||||
|
|
||||||
Params Types:
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ImageModel">ImageModel</a>
|
|
||||||
|
|
||||||
Response Types:
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#Image">Image</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ImageEditCompletedEvent">ImageEditCompletedEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ImageEditPartialImageEvent">ImageEditPartialImageEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ImageEditStreamEventUnion">ImageEditStreamEventUnion</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ImageGenCompletedEvent">ImageGenCompletedEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ImageGenPartialImageEvent">ImageGenPartialImageEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ImageGenStreamEventUnion">ImageGenStreamEventUnion</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ImagesResponse">ImagesResponse</a>
|
|
||||||
|
|
||||||
Methods:
|
|
||||||
|
|
||||||
- <code title="post /images/variations">client.Images.<a href="https://pkg.go.dev/github.com/openai/openai-go#ImageService.NewVariation">NewVariation</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, body <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ImageNewVariationParams">ImageNewVariationParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ImagesResponse">ImagesResponse</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="post /images/edits">client.Images.<a href="https://pkg.go.dev/github.com/openai/openai-go#ImageService.Edit">Edit</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, body <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ImageEditParams">ImageEditParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ImagesResponse">ImagesResponse</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="post /images/generations">client.Images.<a href="https://pkg.go.dev/github.com/openai/openai-go#ImageService.Generate">Generate</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, body <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ImageGenerateParams">ImageGenerateParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ImagesResponse">ImagesResponse</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
|
|
||||||
# Audio
|
|
||||||
|
|
||||||
Params Types:
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#AudioModel">AudioModel</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#AudioResponseFormat">AudioResponseFormat</a>
|
|
||||||
|
|
||||||
## Transcriptions
|
|
||||||
|
|
||||||
Params Types:
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#TranscriptionInclude">TranscriptionInclude</a>
|
|
||||||
|
|
||||||
Response Types:
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#Transcription">Transcription</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#TranscriptionStreamEventUnion">TranscriptionStreamEventUnion</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#TranscriptionTextDeltaEvent">TranscriptionTextDeltaEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#TranscriptionTextDoneEvent">TranscriptionTextDoneEvent</a>
|
|
||||||
|
|
||||||
Methods:
|
|
||||||
|
|
||||||
- <code title="post /audio/transcriptions">client.Audio.Transcriptions.<a href="https://pkg.go.dev/github.com/openai/openai-go#AudioTranscriptionService.New">New</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, body <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#AudioTranscriptionNewParams">AudioTranscriptionNewParams</a>) (Transcription, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
|
|
||||||
## Translations
|
|
||||||
|
|
||||||
Response Types:
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#Translation">Translation</a>
|
|
||||||
|
|
||||||
Methods:
|
|
||||||
|
|
||||||
- <code title="post /audio/translations">client.Audio.Translations.<a href="https://pkg.go.dev/github.com/openai/openai-go#AudioTranslationService.New">New</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, body <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#AudioTranslationNewParams">AudioTranslationNewParams</a>) (Translation, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
|
|
||||||
## Speech
|
|
||||||
|
|
||||||
Params Types:
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#SpeechModel">SpeechModel</a>
|
|
||||||
|
|
||||||
Methods:
|
|
||||||
|
|
||||||
- <code title="post /audio/speech">client.Audio.Speech.<a href="https://pkg.go.dev/github.com/openai/openai-go#AudioSpeechService.New">New</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, body <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#AudioSpeechNewParams">AudioSpeechNewParams</a>) (http.Response, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
|
|
||||||
# Moderations
|
|
||||||
|
|
||||||
Params Types:
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ModerationImageURLInputParam">ModerationImageURLInputParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ModerationModel">ModerationModel</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ModerationMultiModalInputUnionParam">ModerationMultiModalInputUnionParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ModerationTextInputParam">ModerationTextInputParam</a>
|
|
||||||
|
|
||||||
Response Types:
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#Moderation">Moderation</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ModerationNewResponse">ModerationNewResponse</a>
|
|
||||||
|
|
||||||
Methods:
|
|
||||||
|
|
||||||
- <code title="post /moderations">client.Moderations.<a href="https://pkg.go.dev/github.com/openai/openai-go#ModerationService.New">New</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, body <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ModerationNewParams">ModerationNewParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ModerationNewResponse">ModerationNewResponse</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
|
|
||||||
# Models
|
|
||||||
|
|
||||||
Response Types:
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#Model">Model</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ModelDeleted">ModelDeleted</a>
|
|
||||||
|
|
||||||
Methods:
|
|
||||||
|
|
||||||
- <code title="get /models/{model}">client.Models.<a href="https://pkg.go.dev/github.com/openai/openai-go#ModelService.Get">Get</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, model <a href="https://pkg.go.dev/builtin#string">string</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#Model">Model</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="get /models">client.Models.<a href="https://pkg.go.dev/github.com/openai/openai-go#ModelService.List">List</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go/packages/pagination">pagination</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/packages/pagination#Page">Page</a>[<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#Model">Model</a>], <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="delete /models/{model}">client.Models.<a href="https://pkg.go.dev/github.com/openai/openai-go#ModelService.Delete">Delete</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, model <a href="https://pkg.go.dev/builtin#string">string</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ModelDeleted">ModelDeleted</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
|
|
||||||
# FineTuning
|
|
||||||
|
|
||||||
## Methods
|
|
||||||
|
|
||||||
Params Types:
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#DpoHyperparameters">DpoHyperparameters</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#DpoMethodParam">DpoMethodParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ReinforcementHyperparameters">ReinforcementHyperparameters</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ReinforcementMethodParam">ReinforcementMethodParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#SupervisedHyperparameters">SupervisedHyperparameters</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#SupervisedMethodParam">SupervisedMethodParam</a>
|
|
||||||
|
|
||||||
Response Types:
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#DpoHyperparametersResp">DpoHyperparametersResp</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#DpoMethod">DpoMethod</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ReinforcementHyperparametersResp">ReinforcementHyperparametersResp</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ReinforcementMethod">ReinforcementMethod</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#SupervisedHyperparametersResp">SupervisedHyperparametersResp</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#SupervisedMethod">SupervisedMethod</a>
|
|
||||||
|
|
||||||
## Jobs
|
|
||||||
|
|
||||||
Response Types:
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FineTuningJob">FineTuningJob</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FineTuningJobEvent">FineTuningJobEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FineTuningJobWandbIntegration">FineTuningJobWandbIntegration</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FineTuningJobWandbIntegrationObject">FineTuningJobWandbIntegrationObject</a>
|
|
||||||
|
|
||||||
Methods:
|
|
||||||
|
|
||||||
- <code title="post /fine_tuning/jobs">client.FineTuning.Jobs.<a href="https://pkg.go.dev/github.com/openai/openai-go#FineTuningJobService.New">New</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, body <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FineTuningJobNewParams">FineTuningJobNewParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FineTuningJob">FineTuningJob</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="get /fine_tuning/jobs/{fine_tuning_job_id}">client.FineTuning.Jobs.<a href="https://pkg.go.dev/github.com/openai/openai-go#FineTuningJobService.Get">Get</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, fineTuningJobID <a href="https://pkg.go.dev/builtin#string">string</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FineTuningJob">FineTuningJob</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="get /fine_tuning/jobs">client.FineTuning.Jobs.<a href="https://pkg.go.dev/github.com/openai/openai-go#FineTuningJobService.List">List</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, query <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FineTuningJobListParams">FineTuningJobListParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go/packages/pagination">pagination</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/packages/pagination#CursorPage">CursorPage</a>[<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FineTuningJob">FineTuningJob</a>], <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="post /fine_tuning/jobs/{fine_tuning_job_id}/cancel">client.FineTuning.Jobs.<a href="https://pkg.go.dev/github.com/openai/openai-go#FineTuningJobService.Cancel">Cancel</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, fineTuningJobID <a href="https://pkg.go.dev/builtin#string">string</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FineTuningJob">FineTuningJob</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="get /fine_tuning/jobs/{fine_tuning_job_id}/events">client.FineTuning.Jobs.<a href="https://pkg.go.dev/github.com/openai/openai-go#FineTuningJobService.ListEvents">ListEvents</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, fineTuningJobID <a href="https://pkg.go.dev/builtin#string">string</a>, query <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FineTuningJobListEventsParams">FineTuningJobListEventsParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go/packages/pagination">pagination</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/packages/pagination#CursorPage">CursorPage</a>[<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FineTuningJobEvent">FineTuningJobEvent</a>], <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="post /fine_tuning/jobs/{fine_tuning_job_id}/pause">client.FineTuning.Jobs.<a href="https://pkg.go.dev/github.com/openai/openai-go#FineTuningJobService.Pause">Pause</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, fineTuningJobID <a href="https://pkg.go.dev/builtin#string">string</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FineTuningJob">FineTuningJob</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="post /fine_tuning/jobs/{fine_tuning_job_id}/resume">client.FineTuning.Jobs.<a href="https://pkg.go.dev/github.com/openai/openai-go#FineTuningJobService.Resume">Resume</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, fineTuningJobID <a href="https://pkg.go.dev/builtin#string">string</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FineTuningJob">FineTuningJob</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
|
|
||||||
### Checkpoints
|
|
||||||
|
|
||||||
Response Types:
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FineTuningJobCheckpoint">FineTuningJobCheckpoint</a>
|
|
||||||
|
|
||||||
Methods:
|
|
||||||
|
|
||||||
- <code title="get /fine_tuning/jobs/{fine_tuning_job_id}/checkpoints">client.FineTuning.Jobs.Checkpoints.<a href="https://pkg.go.dev/github.com/openai/openai-go#FineTuningJobCheckpointService.List">List</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, fineTuningJobID <a href="https://pkg.go.dev/builtin#string">string</a>, query <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FineTuningJobCheckpointListParams">FineTuningJobCheckpointListParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go/packages/pagination">pagination</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/packages/pagination#CursorPage">CursorPage</a>[<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FineTuningJobCheckpoint">FineTuningJobCheckpoint</a>], <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
|
|
||||||
## Checkpoints
|
|
||||||
|
|
||||||
### Permissions
|
|
||||||
|
|
||||||
Response Types:
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FineTuningCheckpointPermissionNewResponse">FineTuningCheckpointPermissionNewResponse</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FineTuningCheckpointPermissionGetResponse">FineTuningCheckpointPermissionGetResponse</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FineTuningCheckpointPermissionDeleteResponse">FineTuningCheckpointPermissionDeleteResponse</a>
|
|
||||||
|
|
||||||
Methods:
|
|
||||||
|
|
||||||
- <code title="post /fine_tuning/checkpoints/{fine_tuned_model_checkpoint}/permissions">client.FineTuning.Checkpoints.Permissions.<a href="https://pkg.go.dev/github.com/openai/openai-go#FineTuningCheckpointPermissionService.New">New</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, fineTunedModelCheckpoint <a href="https://pkg.go.dev/builtin#string">string</a>, body <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FineTuningCheckpointPermissionNewParams">FineTuningCheckpointPermissionNewParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go/packages/pagination">pagination</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/packages/pagination#Page">Page</a>[<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FineTuningCheckpointPermissionNewResponse">FineTuningCheckpointPermissionNewResponse</a>], <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="get /fine_tuning/checkpoints/{fine_tuned_model_checkpoint}/permissions">client.FineTuning.Checkpoints.Permissions.<a href="https://pkg.go.dev/github.com/openai/openai-go#FineTuningCheckpointPermissionService.Get">Get</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, fineTunedModelCheckpoint <a href="https://pkg.go.dev/builtin#string">string</a>, query <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FineTuningCheckpointPermissionGetParams">FineTuningCheckpointPermissionGetParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FineTuningCheckpointPermissionGetResponse">FineTuningCheckpointPermissionGetResponse</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="delete /fine_tuning/checkpoints/{fine_tuned_model_checkpoint}/permissions/{permission_id}">client.FineTuning.Checkpoints.Permissions.<a href="https://pkg.go.dev/github.com/openai/openai-go#FineTuningCheckpointPermissionService.Delete">Delete</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, fineTunedModelCheckpoint <a href="https://pkg.go.dev/builtin#string">string</a>, permissionID <a href="https://pkg.go.dev/builtin#string">string</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FineTuningCheckpointPermissionDeleteResponse">FineTuningCheckpointPermissionDeleteResponse</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
|
|
||||||
## Alpha
|
|
||||||
|
|
||||||
### Graders
|
|
||||||
|
|
||||||
Response Types:
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FineTuningAlphaGraderRunResponse">FineTuningAlphaGraderRunResponse</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FineTuningAlphaGraderValidateResponse">FineTuningAlphaGraderValidateResponse</a>
|
|
||||||
|
|
||||||
Methods:
|
|
||||||
|
|
||||||
- <code title="post /fine_tuning/alpha/graders/run">client.FineTuning.Alpha.Graders.<a href="https://pkg.go.dev/github.com/openai/openai-go#FineTuningAlphaGraderService.Run">Run</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, body <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FineTuningAlphaGraderRunParams">FineTuningAlphaGraderRunParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FineTuningAlphaGraderRunResponse">FineTuningAlphaGraderRunResponse</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="post /fine_tuning/alpha/graders/validate">client.FineTuning.Alpha.Graders.<a href="https://pkg.go.dev/github.com/openai/openai-go#FineTuningAlphaGraderService.Validate">Validate</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, body <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FineTuningAlphaGraderValidateParams">FineTuningAlphaGraderValidateParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FineTuningAlphaGraderValidateResponse">FineTuningAlphaGraderValidateResponse</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
|
|
||||||
# Graders
|
|
||||||
|
|
||||||
## GraderModels
|
|
||||||
|
|
||||||
Params Types:
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#LabelModelGraderParam">LabelModelGraderParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#MultiGraderParam">MultiGraderParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#PythonGraderParam">PythonGraderParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ScoreModelGraderParam">ScoreModelGraderParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#StringCheckGraderParam">StringCheckGraderParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#TextSimilarityGraderParam">TextSimilarityGraderParam</a>
|
|
||||||
|
|
||||||
Response Types:
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#LabelModelGrader">LabelModelGrader</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#MultiGrader">MultiGrader</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#PythonGrader">PythonGrader</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ScoreModelGrader">ScoreModelGrader</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#StringCheckGrader">StringCheckGrader</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#TextSimilarityGrader">TextSimilarityGrader</a>
|
|
||||||
|
|
||||||
# VectorStores
|
|
||||||
|
|
||||||
Params Types:
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#AutoFileChunkingStrategyParam">AutoFileChunkingStrategyParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FileChunkingStrategyParamUnion">FileChunkingStrategyParamUnion</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#StaticFileChunkingStrategyParam">StaticFileChunkingStrategyParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#StaticFileChunkingStrategyObjectParam">StaticFileChunkingStrategyObjectParam</a>
|
|
||||||
|
|
||||||
Response Types:
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FileChunkingStrategyUnion">FileChunkingStrategyUnion</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#OtherFileChunkingStrategyObject">OtherFileChunkingStrategyObject</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#StaticFileChunkingStrategy">StaticFileChunkingStrategy</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#StaticFileChunkingStrategyObject">StaticFileChunkingStrategyObject</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#VectorStore">VectorStore</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#VectorStoreDeleted">VectorStoreDeleted</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#VectorStoreSearchResponse">VectorStoreSearchResponse</a>
|
|
||||||
|
|
||||||
Methods:
|
|
||||||
|
|
||||||
- <code title="post /vector_stores">client.VectorStores.<a href="https://pkg.go.dev/github.com/openai/openai-go#VectorStoreService.New">New</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, body <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#VectorStoreNewParams">VectorStoreNewParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#VectorStore">VectorStore</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="get /vector_stores/{vector_store_id}">client.VectorStores.<a href="https://pkg.go.dev/github.com/openai/openai-go#VectorStoreService.Get">Get</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, vectorStoreID <a href="https://pkg.go.dev/builtin#string">string</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#VectorStore">VectorStore</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="post /vector_stores/{vector_store_id}">client.VectorStores.<a href="https://pkg.go.dev/github.com/openai/openai-go#VectorStoreService.Update">Update</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, vectorStoreID <a href="https://pkg.go.dev/builtin#string">string</a>, body <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#VectorStoreUpdateParams">VectorStoreUpdateParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#VectorStore">VectorStore</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="get /vector_stores">client.VectorStores.<a href="https://pkg.go.dev/github.com/openai/openai-go#VectorStoreService.List">List</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, query <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#VectorStoreListParams">VectorStoreListParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go/packages/pagination">pagination</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/packages/pagination#CursorPage">CursorPage</a>[<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#VectorStore">VectorStore</a>], <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="delete /vector_stores/{vector_store_id}">client.VectorStores.<a href="https://pkg.go.dev/github.com/openai/openai-go#VectorStoreService.Delete">Delete</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, vectorStoreID <a href="https://pkg.go.dev/builtin#string">string</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#VectorStoreDeleted">VectorStoreDeleted</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="post /vector_stores/{vector_store_id}/search">client.VectorStores.<a href="https://pkg.go.dev/github.com/openai/openai-go#VectorStoreService.Search">Search</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, vectorStoreID <a href="https://pkg.go.dev/builtin#string">string</a>, body <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#VectorStoreSearchParams">VectorStoreSearchParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go/packages/pagination">pagination</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/packages/pagination#Page">Page</a>[<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#VectorStoreSearchResponse">VectorStoreSearchResponse</a>], <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
|
|
||||||
## Files
|
|
||||||
|
|
||||||
Response Types:
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#VectorStoreFile">VectorStoreFile</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#VectorStoreFileDeleted">VectorStoreFileDeleted</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#VectorStoreFileContentResponse">VectorStoreFileContentResponse</a>
|
|
||||||
|
|
||||||
Methods:
|
|
||||||
|
|
||||||
- <code title="post /vector_stores/{vector_store_id}/files">client.VectorStores.Files.<a href="https://pkg.go.dev/github.com/openai/openai-go#VectorStoreFileService.New">New</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, vectorStoreID <a href="https://pkg.go.dev/builtin#string">string</a>, body <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#VectorStoreFileNewParams">VectorStoreFileNewParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#VectorStoreFile">VectorStoreFile</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="get /vector_stores/{vector_store_id}/files/{file_id}">client.VectorStores.Files.<a href="https://pkg.go.dev/github.com/openai/openai-go#VectorStoreFileService.Get">Get</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, vectorStoreID <a href="https://pkg.go.dev/builtin#string">string</a>, fileID <a href="https://pkg.go.dev/builtin#string">string</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#VectorStoreFile">VectorStoreFile</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="post /vector_stores/{vector_store_id}/files/{file_id}">client.VectorStores.Files.<a href="https://pkg.go.dev/github.com/openai/openai-go#VectorStoreFileService.Update">Update</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, vectorStoreID <a href="https://pkg.go.dev/builtin#string">string</a>, fileID <a href="https://pkg.go.dev/builtin#string">string</a>, body <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#VectorStoreFileUpdateParams">VectorStoreFileUpdateParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#VectorStoreFile">VectorStoreFile</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="get /vector_stores/{vector_store_id}/files">client.VectorStores.Files.<a href="https://pkg.go.dev/github.com/openai/openai-go#VectorStoreFileService.List">List</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, vectorStoreID <a href="https://pkg.go.dev/builtin#string">string</a>, query <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#VectorStoreFileListParams">VectorStoreFileListParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go/packages/pagination">pagination</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/packages/pagination#CursorPage">CursorPage</a>[<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#VectorStoreFile">VectorStoreFile</a>], <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="delete /vector_stores/{vector_store_id}/files/{file_id}">client.VectorStores.Files.<a href="https://pkg.go.dev/github.com/openai/openai-go#VectorStoreFileService.Delete">Delete</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, vectorStoreID <a href="https://pkg.go.dev/builtin#string">string</a>, fileID <a href="https://pkg.go.dev/builtin#string">string</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#VectorStoreFileDeleted">VectorStoreFileDeleted</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="get /vector_stores/{vector_store_id}/files/{file_id}/content">client.VectorStores.Files.<a href="https://pkg.go.dev/github.com/openai/openai-go#VectorStoreFileService.Content">Content</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, vectorStoreID <a href="https://pkg.go.dev/builtin#string">string</a>, fileID <a href="https://pkg.go.dev/builtin#string">string</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go/packages/pagination">pagination</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/packages/pagination#Page">Page</a>[<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#VectorStoreFileContentResponse">VectorStoreFileContentResponse</a>], <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
|
|
||||||
## FileBatches
|
|
||||||
|
|
||||||
Response Types:
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#VectorStoreFileBatch">VectorStoreFileBatch</a>
|
|
||||||
|
|
||||||
Methods:
|
|
||||||
|
|
||||||
- <code title="post /vector_stores/{vector_store_id}/file_batches">client.VectorStores.FileBatches.<a href="https://pkg.go.dev/github.com/openai/openai-go#VectorStoreFileBatchService.New">New</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, vectorStoreID <a href="https://pkg.go.dev/builtin#string">string</a>, body <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#VectorStoreFileBatchNewParams">VectorStoreFileBatchNewParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#VectorStoreFileBatch">VectorStoreFileBatch</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="get /vector_stores/{vector_store_id}/file_batches/{batch_id}">client.VectorStores.FileBatches.<a href="https://pkg.go.dev/github.com/openai/openai-go#VectorStoreFileBatchService.Get">Get</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, vectorStoreID <a href="https://pkg.go.dev/builtin#string">string</a>, batchID <a href="https://pkg.go.dev/builtin#string">string</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#VectorStoreFileBatch">VectorStoreFileBatch</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="post /vector_stores/{vector_store_id}/file_batches/{batch_id}/cancel">client.VectorStores.FileBatches.<a href="https://pkg.go.dev/github.com/openai/openai-go#VectorStoreFileBatchService.Cancel">Cancel</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, vectorStoreID <a href="https://pkg.go.dev/builtin#string">string</a>, batchID <a href="https://pkg.go.dev/builtin#string">string</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#VectorStoreFileBatch">VectorStoreFileBatch</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="get /vector_stores/{vector_store_id}/file_batches/{batch_id}/files">client.VectorStores.FileBatches.<a href="https://pkg.go.dev/github.com/openai/openai-go#VectorStoreFileBatchService.ListFiles">ListFiles</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, vectorStoreID <a href="https://pkg.go.dev/builtin#string">string</a>, batchID <a href="https://pkg.go.dev/builtin#string">string</a>, query <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#VectorStoreFileBatchListFilesParams">VectorStoreFileBatchListFilesParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go/packages/pagination">pagination</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/packages/pagination#CursorPage">CursorPage</a>[<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#VectorStoreFile">VectorStoreFile</a>], <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
|
|
||||||
# Webhooks
|
|
||||||
|
|
||||||
Response Types:
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/webhooks">webhooks</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/webhooks#BatchCancelledWebhookEvent">BatchCancelledWebhookEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/webhooks">webhooks</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/webhooks#BatchCompletedWebhookEvent">BatchCompletedWebhookEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/webhooks">webhooks</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/webhooks#BatchExpiredWebhookEvent">BatchExpiredWebhookEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/webhooks">webhooks</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/webhooks#BatchFailedWebhookEvent">BatchFailedWebhookEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/webhooks">webhooks</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/webhooks#EvalRunCanceledWebhookEvent">EvalRunCanceledWebhookEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/webhooks">webhooks</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/webhooks#EvalRunFailedWebhookEvent">EvalRunFailedWebhookEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/webhooks">webhooks</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/webhooks#EvalRunSucceededWebhookEvent">EvalRunSucceededWebhookEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/webhooks">webhooks</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/webhooks#FineTuningJobCancelledWebhookEvent">FineTuningJobCancelledWebhookEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/webhooks">webhooks</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/webhooks#FineTuningJobFailedWebhookEvent">FineTuningJobFailedWebhookEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/webhooks">webhooks</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/webhooks#FineTuningJobSucceededWebhookEvent">FineTuningJobSucceededWebhookEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/webhooks">webhooks</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/webhooks#ResponseCancelledWebhookEvent">ResponseCancelledWebhookEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/webhooks">webhooks</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/webhooks#ResponseCompletedWebhookEvent">ResponseCompletedWebhookEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/webhooks">webhooks</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/webhooks#ResponseFailedWebhookEvent">ResponseFailedWebhookEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/webhooks">webhooks</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/webhooks#ResponseIncompleteWebhookEvent">ResponseIncompleteWebhookEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/webhooks">webhooks</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/webhooks#UnwrapWebhookEventUnion">UnwrapWebhookEventUnion</a>
|
|
||||||
|
|
||||||
Methods:
|
|
||||||
|
|
||||||
- <code>client.Webhooks.<a href="https://pkg.go.dev/github.com/openai/openai-go/webhooks#WebhookService.Unwrap">Unwrap</a>(body []<a href="https://pkg.go.dev/builtin#byte">byte</a>, headers <a href="https://pkg.go.dev/net/http">http</a>.<a href="https://pkg.go.dev/net/http#Header">Header</a>, opts ...<a href="https://pkg.go.dev/github.com/openai/openai-go/option">option</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/option#RequestOption">RequestOption</a>) (*<a href="https://pkg.go.dev/github.com/openai/openai-go/webhooks">webhooks</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/webhooks#UnwrapWebhookEventUnion">UnwrapWebhookEventUnion</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code>client.Webhooks.<a href="https://pkg.go.dev/github.com/openai/openai-go/webhooks#WebhookService.UnwrapWithTolerance">UnwrapWithTolerance</a>(body []<a href="https://pkg.go.dev/builtin#byte">byte</a>, headers <a href="https://pkg.go.dev/net/http">http</a>.<a href="https://pkg.go.dev/net/http#Header">Header</a>, tolerance <a href="https://pkg.go.dev/time">time</a>.<a href="https://pkg.go.dev/time#Duration">Duration</a>, opts ...<a href="https://pkg.go.dev/github.com/openai/openai-go/option">option</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/option#RequestOption">RequestOption</a>) (*<a href="https://pkg.go.dev/github.com/openai/openai-go/webhooks">webhooks</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/webhooks#UnwrapWebhookEventUnion">UnwrapWebhookEventUnion</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code>client.Webhooks.<a href="https://pkg.go.dev/github.com/openai/openai-go/webhooks#WebhookService.UnwrapWithToleranceAndTime">UnwrapWithToleranceAndTime</a>(body []<a href="https://pkg.go.dev/builtin#byte">byte</a>, headers <a href="https://pkg.go.dev/net/http">http</a>.<a href="https://pkg.go.dev/net/http#Header">Header</a>, tolerance <a href="https://pkg.go.dev/time">time</a>.<a href="https://pkg.go.dev/time#Duration">Duration</a>, now <a href="https://pkg.go.dev/time">time</a>.<a href="https://pkg.go.dev/time#Time">Time</a>, opts ...<a href="https://pkg.go.dev/github.com/openai/openai-go/option">option</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/option#RequestOption">RequestOption</a>) (*<a href="https://pkg.go.dev/github.com/openai/openai-go/webhooks">webhooks</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/webhooks#UnwrapWebhookEventUnion">UnwrapWebhookEventUnion</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code>client.Webhooks.<a href="https://pkg.go.dev/github.com/openai/openai-go/webhooks#WebhookService.VerifySignature">VerifySignature</a>(body []<a href="https://pkg.go.dev/builtin#byte">byte</a>, headers <a href="https://pkg.go.dev/net/http">http</a>.<a href="https://pkg.go.dev/net/http#Header">Header</a>, opts ...<a href="https://pkg.go.dev/github.com/openai/openai-go/option">option</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/option#RequestOption">RequestOption</a>) <a href="https://pkg.go.dev/builtin#error">error</a></code>
|
|
||||||
- <code>client.Webhooks.<a href="https://pkg.go.dev/github.com/openai/openai-go/webhooks#WebhookService.VerifySignatureWithTolerance">VerifySignatureWithTolerance</a>(body []<a href="https://pkg.go.dev/builtin#byte">byte</a>, headers <a href="https://pkg.go.dev/net/http">http</a>.<a href="https://pkg.go.dev/net/http#Header">Header</a>, tolerance <a href="https://pkg.go.dev/time">time</a>.<a href="https://pkg.go.dev/time#Duration">Duration</a>, opts ...<a href="https://pkg.go.dev/github.com/openai/openai-go/option">option</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/option#RequestOption">RequestOption</a>) <a href="https://pkg.go.dev/builtin#error">error</a></code>
|
|
||||||
- <code>client.Webhooks.<a href="https://pkg.go.dev/github.com/openai/openai-go/webhooks#WebhookService.VerifySignatureWithToleranceAndTime">VerifySignatureWithToleranceAndTime</a>(body []<a href="https://pkg.go.dev/builtin#byte">byte</a>, headers <a href="https://pkg.go.dev/net/http">http</a>.<a href="https://pkg.go.dev/net/http#Header">Header</a>, tolerance <a href="https://pkg.go.dev/time">time</a>.<a href="https://pkg.go.dev/time#Duration">Duration</a>, now <a href="https://pkg.go.dev/time">time</a>.<a href="https://pkg.go.dev/time#Time">Time</a>, opts ...<a href="https://pkg.go.dev/github.com/openai/openai-go/option">option</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/option#RequestOption">RequestOption</a>) <a href="https://pkg.go.dev/builtin#error">error</a></code>
|
|
||||||
|
|
||||||
# Beta
|
|
||||||
|
|
||||||
## Assistants
|
|
||||||
|
|
||||||
Params Types:
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#AssistantToolUnionParam">AssistantToolUnionParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#CodeInterpreterToolParam">CodeInterpreterToolParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FileSearchToolParam">FileSearchToolParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FunctionToolParam">FunctionToolParam</a>
|
|
||||||
|
|
||||||
Response Types:
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#Assistant">Assistant</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#AssistantDeleted">AssistantDeleted</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#AssistantStreamEventUnion">AssistantStreamEventUnion</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#AssistantToolUnion">AssistantToolUnion</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#CodeInterpreterTool">CodeInterpreterTool</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FileSearchTool">FileSearchTool</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FunctionTool">FunctionTool</a>
|
|
||||||
|
|
||||||
Methods:
|
|
||||||
|
|
||||||
- <code title="post /assistants">client.Beta.Assistants.<a href="https://pkg.go.dev/github.com/openai/openai-go#BetaAssistantService.New">New</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, body <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#BetaAssistantNewParams">BetaAssistantNewParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#Assistant">Assistant</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="get /assistants/{assistant_id}">client.Beta.Assistants.<a href="https://pkg.go.dev/github.com/openai/openai-go#BetaAssistantService.Get">Get</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, assistantID <a href="https://pkg.go.dev/builtin#string">string</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#Assistant">Assistant</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="post /assistants/{assistant_id}">client.Beta.Assistants.<a href="https://pkg.go.dev/github.com/openai/openai-go#BetaAssistantService.Update">Update</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, assistantID <a href="https://pkg.go.dev/builtin#string">string</a>, body <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#BetaAssistantUpdateParams">BetaAssistantUpdateParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#Assistant">Assistant</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="get /assistants">client.Beta.Assistants.<a href="https://pkg.go.dev/github.com/openai/openai-go#BetaAssistantService.List">List</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, query <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#BetaAssistantListParams">BetaAssistantListParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go/packages/pagination">pagination</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/packages/pagination#CursorPage">CursorPage</a>[<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#Assistant">Assistant</a>], <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="delete /assistants/{assistant_id}">client.Beta.Assistants.<a href="https://pkg.go.dev/github.com/openai/openai-go#BetaAssistantService.Delete">Delete</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, assistantID <a href="https://pkg.go.dev/builtin#string">string</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#AssistantDeleted">AssistantDeleted</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
|
|
||||||
## Threads
|
|
||||||
|
|
||||||
Params Types:
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#AssistantResponseFormatOptionUnionParam">AssistantResponseFormatOptionUnionParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#AssistantToolChoiceParam">AssistantToolChoiceParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#AssistantToolChoiceFunctionParam">AssistantToolChoiceFunctionParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#AssistantToolChoiceOptionUnionParam">AssistantToolChoiceOptionUnionParam</a>
|
|
||||||
|
|
||||||
Response Types:
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#AssistantResponseFormatOptionUnion">AssistantResponseFormatOptionUnion</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#AssistantToolChoice">AssistantToolChoice</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#AssistantToolChoiceFunction">AssistantToolChoiceFunction</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#AssistantToolChoiceOptionUnion">AssistantToolChoiceOptionUnion</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#Thread">Thread</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ThreadDeleted">ThreadDeleted</a>
|
|
||||||
|
|
||||||
Methods:
|
|
||||||
|
|
||||||
- <code title="post /threads">client.Beta.Threads.<a href="https://pkg.go.dev/github.com/openai/openai-go#BetaThreadService.New">New</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, body <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#BetaThreadNewParams">BetaThreadNewParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#Thread">Thread</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="get /threads/{thread_id}">client.Beta.Threads.<a href="https://pkg.go.dev/github.com/openai/openai-go#BetaThreadService.Get">Get</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, threadID <a href="https://pkg.go.dev/builtin#string">string</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#Thread">Thread</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="post /threads/{thread_id}">client.Beta.Threads.<a href="https://pkg.go.dev/github.com/openai/openai-go#BetaThreadService.Update">Update</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, threadID <a href="https://pkg.go.dev/builtin#string">string</a>, body <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#BetaThreadUpdateParams">BetaThreadUpdateParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#Thread">Thread</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="delete /threads/{thread_id}">client.Beta.Threads.<a href="https://pkg.go.dev/github.com/openai/openai-go#BetaThreadService.Delete">Delete</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, threadID <a href="https://pkg.go.dev/builtin#string">string</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ThreadDeleted">ThreadDeleted</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="post /threads/runs">client.Beta.Threads.<a href="https://pkg.go.dev/github.com/openai/openai-go#BetaThreadService.NewAndRun">NewAndRun</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, body <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#BetaThreadNewAndRunParams">BetaThreadNewAndRunParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#Run">Run</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
|
|
||||||
### Runs
|
|
||||||
|
|
||||||
Response Types:
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#RequiredActionFunctionToolCall">RequiredActionFunctionToolCall</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#Run">Run</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#RunStatus">RunStatus</a>
|
|
||||||
|
|
||||||
Methods:
|
|
||||||
|
|
||||||
- <code title="post /threads/{thread_id}/runs">client.Beta.Threads.Runs.<a href="https://pkg.go.dev/github.com/openai/openai-go#BetaThreadRunService.New">New</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, threadID <a href="https://pkg.go.dev/builtin#string">string</a>, params <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#BetaThreadRunNewParams">BetaThreadRunNewParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#Run">Run</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="get /threads/{thread_id}/runs/{run_id}">client.Beta.Threads.Runs.<a href="https://pkg.go.dev/github.com/openai/openai-go#BetaThreadRunService.Get">Get</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, threadID <a href="https://pkg.go.dev/builtin#string">string</a>, runID <a href="https://pkg.go.dev/builtin#string">string</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#Run">Run</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="post /threads/{thread_id}/runs/{run_id}">client.Beta.Threads.Runs.<a href="https://pkg.go.dev/github.com/openai/openai-go#BetaThreadRunService.Update">Update</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, threadID <a href="https://pkg.go.dev/builtin#string">string</a>, runID <a href="https://pkg.go.dev/builtin#string">string</a>, body <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#BetaThreadRunUpdateParams">BetaThreadRunUpdateParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#Run">Run</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="get /threads/{thread_id}/runs">client.Beta.Threads.Runs.<a href="https://pkg.go.dev/github.com/openai/openai-go#BetaThreadRunService.List">List</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, threadID <a href="https://pkg.go.dev/builtin#string">string</a>, query <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#BetaThreadRunListParams">BetaThreadRunListParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go/packages/pagination">pagination</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/packages/pagination#CursorPage">CursorPage</a>[<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#Run">Run</a>], <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="post /threads/{thread_id}/runs/{run_id}/cancel">client.Beta.Threads.Runs.<a href="https://pkg.go.dev/github.com/openai/openai-go#BetaThreadRunService.Cancel">Cancel</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, threadID <a href="https://pkg.go.dev/builtin#string">string</a>, runID <a href="https://pkg.go.dev/builtin#string">string</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#Run">Run</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="post /threads/{thread_id}/runs/{run_id}/submit_tool_outputs">client.Beta.Threads.Runs.<a href="https://pkg.go.dev/github.com/openai/openai-go#BetaThreadRunService.SubmitToolOutputs">SubmitToolOutputs</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, threadID <a href="https://pkg.go.dev/builtin#string">string</a>, runID <a href="https://pkg.go.dev/builtin#string">string</a>, body <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#BetaThreadRunSubmitToolOutputsParams">BetaThreadRunSubmitToolOutputsParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#Run">Run</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
|
|
||||||
#### Steps
|
|
||||||
|
|
||||||
Params Types:
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#RunStepInclude">RunStepInclude</a>
|
|
||||||
|
|
||||||
Response Types:
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#CodeInterpreterLogs">CodeInterpreterLogs</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#CodeInterpreterOutputImage">CodeInterpreterOutputImage</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#CodeInterpreterToolCall">CodeInterpreterToolCall</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#CodeInterpreterToolCallDelta">CodeInterpreterToolCallDelta</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FileSearchToolCall">FileSearchToolCall</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FileSearchToolCallDelta">FileSearchToolCallDelta</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FunctionToolCall">FunctionToolCall</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FunctionToolCallDelta">FunctionToolCallDelta</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#MessageCreationStepDetails">MessageCreationStepDetails</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#RunStep">RunStep</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#RunStepDelta">RunStepDelta</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#RunStepDeltaEvent">RunStepDeltaEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#RunStepDeltaMessageDelta">RunStepDeltaMessageDelta</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ToolCallUnion">ToolCallUnion</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ToolCallDeltaUnion">ToolCallDeltaUnion</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ToolCallDeltaObject">ToolCallDeltaObject</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ToolCallsStepDetails">ToolCallsStepDetails</a>
|
|
||||||
|
|
||||||
Methods:
|
|
||||||
|
|
||||||
- <code title="get /threads/{thread_id}/runs/{run_id}/steps/{step_id}">client.Beta.Threads.Runs.Steps.<a href="https://pkg.go.dev/github.com/openai/openai-go#BetaThreadRunStepService.Get">Get</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, threadID <a href="https://pkg.go.dev/builtin#string">string</a>, runID <a href="https://pkg.go.dev/builtin#string">string</a>, stepID <a href="https://pkg.go.dev/builtin#string">string</a>, query <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#BetaThreadRunStepGetParams">BetaThreadRunStepGetParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#RunStep">RunStep</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="get /threads/{thread_id}/runs/{run_id}/steps">client.Beta.Threads.Runs.Steps.<a href="https://pkg.go.dev/github.com/openai/openai-go#BetaThreadRunStepService.List">List</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, threadID <a href="https://pkg.go.dev/builtin#string">string</a>, runID <a href="https://pkg.go.dev/builtin#string">string</a>, query <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#BetaThreadRunStepListParams">BetaThreadRunStepListParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go/packages/pagination">pagination</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/packages/pagination#CursorPage">CursorPage</a>[<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#RunStep">RunStep</a>], <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
|
|
||||||
### Messages
|
|
||||||
|
|
||||||
Params Types:
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ImageFileParam">ImageFileParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ImageFileContentBlockParam">ImageFileContentBlockParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ImageURLParam">ImageURLParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ImageURLContentBlockParam">ImageURLContentBlockParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#MessageContentPartParamUnion">MessageContentPartParamUnion</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#TextContentBlockParam">TextContentBlockParam</a>
|
|
||||||
|
|
||||||
Response Types:
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#AnnotationUnion">AnnotationUnion</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#AnnotationDeltaUnion">AnnotationDeltaUnion</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FileCitationAnnotation">FileCitationAnnotation</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FileCitationDeltaAnnotation">FileCitationDeltaAnnotation</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FilePathAnnotation">FilePathAnnotation</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#FilePathDeltaAnnotation">FilePathDeltaAnnotation</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ImageFile">ImageFile</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ImageFileContentBlock">ImageFileContentBlock</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ImageFileDelta">ImageFileDelta</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ImageFileDeltaBlock">ImageFileDeltaBlock</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ImageURL">ImageURL</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ImageURLContentBlock">ImageURLContentBlock</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ImageURLDelta">ImageURLDelta</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ImageURLDeltaBlock">ImageURLDeltaBlock</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#Message">Message</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#MessageContentUnion">MessageContentUnion</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#MessageContentDeltaUnion">MessageContentDeltaUnion</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#MessageDeleted">MessageDeleted</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#MessageDelta">MessageDelta</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#MessageDeltaEvent">MessageDeltaEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#RefusalContentBlock">RefusalContentBlock</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#RefusalDeltaBlock">RefusalDeltaBlock</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#Text">Text</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#TextContentBlock">TextContentBlock</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#TextDelta">TextDelta</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#TextDeltaBlock">TextDeltaBlock</a>
|
|
||||||
|
|
||||||
Methods:
|
|
||||||
|
|
||||||
- <code title="post /threads/{thread_id}/messages">client.Beta.Threads.Messages.<a href="https://pkg.go.dev/github.com/openai/openai-go#BetaThreadMessageService.New">New</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, threadID <a href="https://pkg.go.dev/builtin#string">string</a>, body <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#BetaThreadMessageNewParams">BetaThreadMessageNewParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#Message">Message</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="get /threads/{thread_id}/messages/{message_id}">client.Beta.Threads.Messages.<a href="https://pkg.go.dev/github.com/openai/openai-go#BetaThreadMessageService.Get">Get</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, threadID <a href="https://pkg.go.dev/builtin#string">string</a>, messageID <a href="https://pkg.go.dev/builtin#string">string</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#Message">Message</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="post /threads/{thread_id}/messages/{message_id}">client.Beta.Threads.Messages.<a href="https://pkg.go.dev/github.com/openai/openai-go#BetaThreadMessageService.Update">Update</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, threadID <a href="https://pkg.go.dev/builtin#string">string</a>, messageID <a href="https://pkg.go.dev/builtin#string">string</a>, body <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#BetaThreadMessageUpdateParams">BetaThreadMessageUpdateParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#Message">Message</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="get /threads/{thread_id}/messages">client.Beta.Threads.Messages.<a href="https://pkg.go.dev/github.com/openai/openai-go#BetaThreadMessageService.List">List</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, threadID <a href="https://pkg.go.dev/builtin#string">string</a>, query <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#BetaThreadMessageListParams">BetaThreadMessageListParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go/packages/pagination">pagination</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/packages/pagination#CursorPage">CursorPage</a>[<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#Message">Message</a>], <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="delete /threads/{thread_id}/messages/{message_id}">client.Beta.Threads.Messages.<a href="https://pkg.go.dev/github.com/openai/openai-go#BetaThreadMessageService.Delete">Delete</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, threadID <a href="https://pkg.go.dev/builtin#string">string</a>, messageID <a href="https://pkg.go.dev/builtin#string">string</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#MessageDeleted">MessageDeleted</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
|
|
||||||
# Batches
|
|
||||||
|
|
||||||
Response Types:
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#Batch">Batch</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#BatchError">BatchError</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#BatchRequestCounts">BatchRequestCounts</a>
|
|
||||||
|
|
||||||
Methods:
|
|
||||||
|
|
||||||
- <code title="post /batches">client.Batches.<a href="https://pkg.go.dev/github.com/openai/openai-go#BatchService.New">New</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, body <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#BatchNewParams">BatchNewParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#Batch">Batch</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="get /batches/{batch_id}">client.Batches.<a href="https://pkg.go.dev/github.com/openai/openai-go#BatchService.Get">Get</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, batchID <a href="https://pkg.go.dev/builtin#string">string</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#Batch">Batch</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="get /batches">client.Batches.<a href="https://pkg.go.dev/github.com/openai/openai-go#BatchService.List">List</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, query <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#BatchListParams">BatchListParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go/packages/pagination">pagination</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/packages/pagination#CursorPage">CursorPage</a>[<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#Batch">Batch</a>], <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="post /batches/{batch_id}/cancel">client.Batches.<a href="https://pkg.go.dev/github.com/openai/openai-go#BatchService.Cancel">Cancel</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, batchID <a href="https://pkg.go.dev/builtin#string">string</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#Batch">Batch</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
|
|
||||||
# Uploads
|
|
||||||
|
|
||||||
Response Types:
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#Upload">Upload</a>
|
|
||||||
|
|
||||||
Methods:
|
|
||||||
|
|
||||||
- <code title="post /uploads">client.Uploads.<a href="https://pkg.go.dev/github.com/openai/openai-go#UploadService.New">New</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, body <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#UploadNewParams">UploadNewParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#Upload">Upload</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="post /uploads/{upload_id}/cancel">client.Uploads.<a href="https://pkg.go.dev/github.com/openai/openai-go#UploadService.Cancel">Cancel</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, uploadID <a href="https://pkg.go.dev/builtin#string">string</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#Upload">Upload</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="post /uploads/{upload_id}/complete">client.Uploads.<a href="https://pkg.go.dev/github.com/openai/openai-go#UploadService.Complete">Complete</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, uploadID <a href="https://pkg.go.dev/builtin#string">string</a>, body <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#UploadCompleteParams">UploadCompleteParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#Upload">Upload</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
|
|
||||||
## Parts
|
|
||||||
|
|
||||||
Response Types:
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#UploadPart">UploadPart</a>
|
|
||||||
|
|
||||||
Methods:
|
|
||||||
|
|
||||||
- <code title="post /uploads/{upload_id}/parts">client.Uploads.Parts.<a href="https://pkg.go.dev/github.com/openai/openai-go#UploadPartService.New">New</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, uploadID <a href="https://pkg.go.dev/builtin#string">string</a>, body <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#UploadPartNewParams">UploadPartNewParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#UploadPart">UploadPart</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
|
|
||||||
# Responses
|
|
||||||
|
|
||||||
Params Types:
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ComputerToolParam">ComputerToolParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#EasyInputMessageParam">EasyInputMessageParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#FileSearchToolParam">FileSearchToolParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#FunctionToolParam">FunctionToolParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseCodeInterpreterToolCallParam">ResponseCodeInterpreterToolCallParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseComputerToolCallParam">ResponseComputerToolCallParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseComputerToolCallOutputScreenshotParam">ResponseComputerToolCallOutputScreenshotParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseFileSearchToolCallParam">ResponseFileSearchToolCallParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseFormatTextConfigUnionParam">ResponseFormatTextConfigUnionParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseFormatTextJSONSchemaConfigParam">ResponseFormatTextJSONSchemaConfigParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseFunctionToolCallParam">ResponseFunctionToolCallParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseFunctionWebSearchParam">ResponseFunctionWebSearchParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseIncludable">ResponseIncludable</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseInputParam">ResponseInputParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseInputContentUnionParam">ResponseInputContentUnionParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseInputFileParam">ResponseInputFileParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseInputImageParam">ResponseInputImageParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseInputItemUnionParam">ResponseInputItemUnionParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseInputMessageContentListParam">ResponseInputMessageContentListParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseInputTextParam">ResponseInputTextParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseOutputMessageParam">ResponseOutputMessageParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseOutputRefusalParam">ResponseOutputRefusalParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseOutputTextParam">ResponseOutputTextParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponsePromptParam">ResponsePromptParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseReasoningItemParam">ResponseReasoningItemParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseTextConfigParam">ResponseTextConfigParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ToolUnionParam">ToolUnionParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ToolChoiceFunctionParam">ToolChoiceFunctionParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ToolChoiceMcpParam">ToolChoiceMcpParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ToolChoiceOptions">ToolChoiceOptions</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ToolChoiceTypesParam">ToolChoiceTypesParam</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#WebSearchToolParam">WebSearchToolParam</a>
|
|
||||||
|
|
||||||
Response Types:
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ComputerTool">ComputerTool</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#EasyInputMessage">EasyInputMessage</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#FileSearchTool">FileSearchTool</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#FunctionTool">FunctionTool</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#Response">Response</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseAudioDeltaEvent">ResponseAudioDeltaEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseAudioDoneEvent">ResponseAudioDoneEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseAudioTranscriptDeltaEvent">ResponseAudioTranscriptDeltaEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseAudioTranscriptDoneEvent">ResponseAudioTranscriptDoneEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseCodeInterpreterCallCodeDeltaEvent">ResponseCodeInterpreterCallCodeDeltaEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseCodeInterpreterCallCodeDoneEvent">ResponseCodeInterpreterCallCodeDoneEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseCodeInterpreterCallCompletedEvent">ResponseCodeInterpreterCallCompletedEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseCodeInterpreterCallInProgressEvent">ResponseCodeInterpreterCallInProgressEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseCodeInterpreterCallInterpretingEvent">ResponseCodeInterpreterCallInterpretingEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseCodeInterpreterToolCall">ResponseCodeInterpreterToolCall</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseCompletedEvent">ResponseCompletedEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseComputerToolCall">ResponseComputerToolCall</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseComputerToolCallOutputItem">ResponseComputerToolCallOutputItem</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseComputerToolCallOutputScreenshot">ResponseComputerToolCallOutputScreenshot</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseContentPartAddedEvent">ResponseContentPartAddedEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseContentPartDoneEvent">ResponseContentPartDoneEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseCreatedEvent">ResponseCreatedEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseError">ResponseError</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseErrorEvent">ResponseErrorEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseFailedEvent">ResponseFailedEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseFileSearchCallCompletedEvent">ResponseFileSearchCallCompletedEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseFileSearchCallInProgressEvent">ResponseFileSearchCallInProgressEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseFileSearchCallSearchingEvent">ResponseFileSearchCallSearchingEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseFileSearchToolCall">ResponseFileSearchToolCall</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseFormatTextConfigUnion">ResponseFormatTextConfigUnion</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseFormatTextJSONSchemaConfig">ResponseFormatTextJSONSchemaConfig</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseFunctionCallArgumentsDeltaEvent">ResponseFunctionCallArgumentsDeltaEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseFunctionCallArgumentsDoneEvent">ResponseFunctionCallArgumentsDoneEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseFunctionToolCall">ResponseFunctionToolCall</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseFunctionToolCallItem">ResponseFunctionToolCallItem</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseFunctionToolCallOutputItem">ResponseFunctionToolCallOutputItem</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseFunctionWebSearch">ResponseFunctionWebSearch</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseImageGenCallCompletedEvent">ResponseImageGenCallCompletedEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseImageGenCallGeneratingEvent">ResponseImageGenCallGeneratingEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseImageGenCallInProgressEvent">ResponseImageGenCallInProgressEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseImageGenCallPartialImageEvent">ResponseImageGenCallPartialImageEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseInProgressEvent">ResponseInProgressEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseIncompleteEvent">ResponseIncompleteEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseInputContentUnion">ResponseInputContentUnion</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseInputFile">ResponseInputFile</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseInputImage">ResponseInputImage</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseInputItemUnion">ResponseInputItemUnion</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseInputMessageContentList">ResponseInputMessageContentList</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseInputMessageItem">ResponseInputMessageItem</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseInputText">ResponseInputText</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseItemUnion">ResponseItemUnion</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseMcpCallArgumentsDeltaEvent">ResponseMcpCallArgumentsDeltaEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseMcpCallArgumentsDoneEvent">ResponseMcpCallArgumentsDoneEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseMcpCallCompletedEvent">ResponseMcpCallCompletedEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseMcpCallFailedEvent">ResponseMcpCallFailedEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseMcpCallInProgressEvent">ResponseMcpCallInProgressEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseMcpListToolsCompletedEvent">ResponseMcpListToolsCompletedEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseMcpListToolsFailedEvent">ResponseMcpListToolsFailedEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseMcpListToolsInProgressEvent">ResponseMcpListToolsInProgressEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseOutputItemUnion">ResponseOutputItemUnion</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseOutputItemAddedEvent">ResponseOutputItemAddedEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseOutputItemDoneEvent">ResponseOutputItemDoneEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseOutputMessage">ResponseOutputMessage</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseOutputRefusal">ResponseOutputRefusal</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseOutputText">ResponseOutputText</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseOutputTextAnnotationAddedEvent">ResponseOutputTextAnnotationAddedEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponsePrompt">ResponsePrompt</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseQueuedEvent">ResponseQueuedEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseReasoningItem">ResponseReasoningItem</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseReasoningSummaryDeltaEvent">ResponseReasoningSummaryDeltaEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseReasoningSummaryDoneEvent">ResponseReasoningSummaryDoneEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseReasoningSummaryPartAddedEvent">ResponseReasoningSummaryPartAddedEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseReasoningSummaryPartDoneEvent">ResponseReasoningSummaryPartDoneEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseReasoningSummaryTextDeltaEvent">ResponseReasoningSummaryTextDeltaEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseReasoningSummaryTextDoneEvent">ResponseReasoningSummaryTextDoneEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseRefusalDeltaEvent">ResponseRefusalDeltaEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseRefusalDoneEvent">ResponseRefusalDoneEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseStatus">ResponseStatus</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseStreamEventUnion">ResponseStreamEventUnion</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseTextConfig">ResponseTextConfig</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseTextDeltaEvent">ResponseTextDeltaEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseTextDoneEvent">ResponseTextDoneEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseUsage">ResponseUsage</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseWebSearchCallCompletedEvent">ResponseWebSearchCallCompletedEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseWebSearchCallInProgressEvent">ResponseWebSearchCallInProgressEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseWebSearchCallSearchingEvent">ResponseWebSearchCallSearchingEvent</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ToolUnion">ToolUnion</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ToolChoiceFunction">ToolChoiceFunction</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ToolChoiceMcp">ToolChoiceMcp</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ToolChoiceOptions">ToolChoiceOptions</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ToolChoiceTypes">ToolChoiceTypes</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#WebSearchTool">WebSearchTool</a>
|
|
||||||
|
|
||||||
Methods:
|
|
||||||
|
|
||||||
- <code title="post /responses">client.Responses.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseService.New">New</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, body <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseNewParams">ResponseNewParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#Response">Response</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="get /responses/{response_id}">client.Responses.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseService.Get">Get</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, responseID <a href="https://pkg.go.dev/builtin#string">string</a>, query <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseGetParams">ResponseGetParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#Response">Response</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="delete /responses/{response_id}">client.Responses.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseService.Delete">Delete</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, responseID <a href="https://pkg.go.dev/builtin#string">string</a>) <a href="https://pkg.go.dev/builtin#error">error</a></code>
|
|
||||||
- <code title="post /responses/{response_id}/cancel">client.Responses.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseService.Cancel">Cancel</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, responseID <a href="https://pkg.go.dev/builtin#string">string</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#Response">Response</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
|
|
||||||
## InputItems
|
|
||||||
|
|
||||||
Response Types:
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseItemList">ResponseItemList</a>
|
|
||||||
|
|
||||||
Methods:
|
|
||||||
|
|
||||||
- <code title="get /responses/{response_id}/input_items">client.Responses.InputItems.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#InputItemService.List">List</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, responseID <a href="https://pkg.go.dev/builtin#string">string</a>, query <a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#InputItemListParams">InputItemListParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go/packages/pagination">pagination</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/packages/pagination#CursorPage">CursorPage</a>[<a href="https://pkg.go.dev/github.com/openai/openai-go/responses">responses</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/responses#ResponseItemUnion">ResponseItemUnion</a>], <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
|
|
||||||
# Containers
|
|
||||||
|
|
||||||
Response Types:
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ContainerNewResponse">ContainerNewResponse</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ContainerGetResponse">ContainerGetResponse</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ContainerListResponse">ContainerListResponse</a>
|
|
||||||
|
|
||||||
Methods:
|
|
||||||
|
|
||||||
- <code title="post /containers">client.Containers.<a href="https://pkg.go.dev/github.com/openai/openai-go#ContainerService.New">New</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, body <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ContainerNewParams">ContainerNewParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ContainerNewResponse">ContainerNewResponse</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="get /containers/{container_id}">client.Containers.<a href="https://pkg.go.dev/github.com/openai/openai-go#ContainerService.Get">Get</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, containerID <a href="https://pkg.go.dev/builtin#string">string</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ContainerGetResponse">ContainerGetResponse</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="get /containers">client.Containers.<a href="https://pkg.go.dev/github.com/openai/openai-go#ContainerService.List">List</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, query <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ContainerListParams">ContainerListParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go/packages/pagination">pagination</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/packages/pagination#CursorPage">CursorPage</a>[<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ContainerListResponse">ContainerListResponse</a>], <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="delete /containers/{container_id}">client.Containers.<a href="https://pkg.go.dev/github.com/openai/openai-go#ContainerService.Delete">Delete</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, containerID <a href="https://pkg.go.dev/builtin#string">string</a>) <a href="https://pkg.go.dev/builtin#error">error</a></code>
|
|
||||||
|
|
||||||
## Files
|
|
||||||
|
|
||||||
Response Types:
|
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ContainerFileNewResponse">ContainerFileNewResponse</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ContainerFileGetResponse">ContainerFileGetResponse</a>
|
|
||||||
- <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ContainerFileListResponse">ContainerFileListResponse</a>
|
|
||||||
|
|
||||||
Methods:
|
|
||||||
|
|
||||||
- <code title="post /containers/{container_id}/files">client.Containers.Files.<a href="https://pkg.go.dev/github.com/openai/openai-go#ContainerFileService.New">New</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, containerID <a href="https://pkg.go.dev/builtin#string">string</a>, body <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ContainerFileNewParams">ContainerFileNewParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ContainerFileNewResponse">ContainerFileNewResponse</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="get /containers/{container_id}/files/{file_id}">client.Containers.Files.<a href="https://pkg.go.dev/github.com/openai/openai-go#ContainerFileService.Get">Get</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, containerID <a href="https://pkg.go.dev/builtin#string">string</a>, fileID <a href="https://pkg.go.dev/builtin#string">string</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ContainerFileGetResponse">ContainerFileGetResponse</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="get /containers/{container_id}/files">client.Containers.Files.<a href="https://pkg.go.dev/github.com/openai/openai-go#ContainerFileService.List">List</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, containerID <a href="https://pkg.go.dev/builtin#string">string</a>, query <a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ContainerFileListParams">ContainerFileListParams</a>) (<a href="https://pkg.go.dev/github.com/openai/openai-go/packages/pagination">pagination</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go/packages/pagination#CursorPage">CursorPage</a>[<a href="https://pkg.go.dev/github.com/openai/openai-go">openai</a>.<a href="https://pkg.go.dev/github.com/openai/openai-go#ContainerFileListResponse">ContainerFileListResponse</a>], <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
- <code title="delete /containers/{container_id}/files/{file_id}">client.Containers.Files.<a href="https://pkg.go.dev/github.com/openai/openai-go#ContainerFileService.Delete">Delete</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, containerID <a href="https://pkg.go.dev/builtin#string">string</a>, fileID <a href="https://pkg.go.dev/builtin#string">string</a>) <a href="https://pkg.go.dev/builtin#error">error</a></code>
|
|
||||||
|
|
||||||
### Content
|
|
||||||
|
|
||||||
Methods:
|
|
||||||
|
|
||||||
- <code title="get /containers/{container_id}/files/{file_id}/content">client.Containers.Files.Content.<a href="https://pkg.go.dev/github.com/openai/openai-go#ContainerFileContentService.Get">Get</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, containerID <a href="https://pkg.go.dev/builtin#string">string</a>, fileID <a href="https://pkg.go.dev/builtin#string">string</a>) (http.Response, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
53
vendor/github.com/openai/openai-go/audio.go
generated
vendored
53
vendor/github.com/openai/openai-go/audio.go
generated
vendored
@@ -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"
|
|
||||||
)
|
|
||||||
126
vendor/github.com/openai/openai-go/audiospeech.go
generated
vendored
126
vendor/github.com/openai/openai-go/audiospeech.go
generated
vendored
@@ -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"
|
|
||||||
)
|
|
||||||
654
vendor/github.com/openai/openai-go/audiotranscription.go
generated
vendored
654
vendor/github.com/openai/openai-go/audiotranscription.go
generated
vendored
@@ -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",
|
|
||||||
)
|
|
||||||
}
|
|
||||||
117
vendor/github.com/openai/openai-go/audiotranslation.go
generated
vendored
117
vendor/github.com/openai/openai-go/audiotranslation.go
generated
vendored
@@ -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"
|
|
||||||
)
|
|
||||||
343
vendor/github.com/openai/openai-go/batch.go
generated
vendored
343
vendor/github.com/openai/openai-go/batch.go
generated
vendored
@@ -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,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
31
vendor/github.com/openai/openai-go/beta.go
generated
vendored
31
vendor/github.com/openai/openai-go/beta.go
generated
vendored
@@ -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
|
|
||||||
}
|
|
||||||
2246
vendor/github.com/openai/openai-go/betaassistant.go
generated
vendored
2246
vendor/github.com/openai/openai-go/betaassistant.go
generated
vendored
File diff suppressed because it is too large
Load Diff
1564
vendor/github.com/openai/openai-go/betathread.go
generated
vendored
1564
vendor/github.com/openai/openai-go/betathread.go
generated
vendored
File diff suppressed because it is too large
Load Diff
1712
vendor/github.com/openai/openai-go/betathreadmessage.go
generated
vendored
1712
vendor/github.com/openai/openai-go/betathreadmessage.go
generated
vendored
File diff suppressed because it is too large
Load Diff
960
vendor/github.com/openai/openai-go/betathreadrun.go
generated
vendored
960
vendor/github.com/openai/openai-go/betathreadrun.go
generated
vendored
@@ -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)
|
|
||||||
}
|
|
||||||
1393
vendor/github.com/openai/openai-go/betathreadrunstep.go
generated
vendored
1393
vendor/github.com/openai/openai-go/betathreadrunstep.go
generated
vendored
File diff suppressed because it is too large
Load Diff
28
vendor/github.com/openai/openai-go/chat.go
generated
vendored
28
vendor/github.com/openai/openai-go/chat.go
generated
vendored
@@ -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
|
|
||||||
}
|
|
||||||
2738
vendor/github.com/openai/openai-go/chatcompletion.go
generated
vendored
2738
vendor/github.com/openai/openai-go/chatcompletion.go
generated
vendored
File diff suppressed because it is too large
Load Diff
96
vendor/github.com/openai/openai-go/chatcompletionmessage.go
generated
vendored
96
vendor/github.com/openai/openai-go/chatcompletionmessage.go
generated
vendored
@@ -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"
|
|
||||||
)
|
|
||||||
161
vendor/github.com/openai/openai-go/client.go
generated
vendored
161
vendor/github.com/openai/openai-go/client.go
generated
vendored
@@ -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...)
|
|
||||||
}
|
|
||||||
426
vendor/github.com/openai/openai-go/completion.go
generated
vendored
426
vendor/github.com/openai/openai-go/completion.go
generated
vendored
@@ -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
|
|
||||||
}
|
|
||||||
352
vendor/github.com/openai/openai-go/container.go
generated
vendored
352
vendor/github.com/openai/openai-go/container.go
generated
vendored
@@ -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"
|
|
||||||
)
|
|
||||||
286
vendor/github.com/openai/openai-go/containerfile.go
generated
vendored
286
vendor/github.com/openai/openai-go/containerfile.go
generated
vendored
@@ -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"
|
|
||||||
)
|
|
||||||
49
vendor/github.com/openai/openai-go/containerfilecontent.go
generated
vendored
49
vendor/github.com/openai/openai-go/containerfilecontent.go
generated
vendored
@@ -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
|
|
||||||
}
|
|
||||||
203
vendor/github.com/openai/openai-go/embedding.go
generated
vendored
203
vendor/github.com/openai/openai-go/embedding.go
generated
vendored
@@ -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"
|
|
||||||
)
|
|
||||||
45
vendor/github.com/openai/openai-go/field.go
generated
vendored
45
vendor/github.com/openai/openai-go/field.go
generated
vendored
@@ -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
|
|
||||||
}
|
|
||||||
314
vendor/github.com/openai/openai-go/file.go
generated
vendored
314
vendor/github.com/openai/openai-go/file.go
generated
vendored
@@ -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"
|
|
||||||
)
|
|
||||||
34
vendor/github.com/openai/openai-go/finetuning.go
generated
vendored
34
vendor/github.com/openai/openai-go/finetuning.go
generated
vendored
@@ -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
|
|
||||||
}
|
|
||||||
28
vendor/github.com/openai/openai-go/finetuningalpha.go
generated
vendored
28
vendor/github.com/openai/openai-go/finetuningalpha.go
generated
vendored
@@ -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
|
|
||||||
}
|
|
||||||
672
vendor/github.com/openai/openai-go/finetuningalphagrader.go
generated
vendored
672
vendor/github.com/openai/openai-go/finetuningalphagrader.go
generated
vendored
@@ -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 }
|
|
||||||
28
vendor/github.com/openai/openai-go/finetuningcheckpoint.go
generated
vendored
28
vendor/github.com/openai/openai-go/finetuningcheckpoint.go
generated
vendored
@@ -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
|
|
||||||
}
|
|
||||||
254
vendor/github.com/openai/openai-go/finetuningcheckpointpermission.go
generated
vendored
254
vendor/github.com/openai/openai-go/finetuningcheckpointpermission.go
generated
vendored
@@ -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"
|
|
||||||
)
|
|
||||||
880
vendor/github.com/openai/openai-go/finetuningjob.go
generated
vendored
880
vendor/github.com/openai/openai-go/finetuningjob.go
generated
vendored
@@ -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,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
149
vendor/github.com/openai/openai-go/finetuningjobcheckpoint.go
generated
vendored
149
vendor/github.com/openai/openai-go/finetuningjobcheckpoint.go
generated
vendored
@@ -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,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
1487
vendor/github.com/openai/openai-go/finetuningmethod.go
generated
vendored
1487
vendor/github.com/openai/openai-go/finetuningmethod.go
generated
vendored
File diff suppressed because it is too large
Load Diff
28
vendor/github.com/openai/openai-go/grader.go
generated
vendored
28
vendor/github.com/openai/openai-go/grader.go
generated
vendored
@@ -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
|
|
||||||
}
|
|
||||||
1373
vendor/github.com/openai/openai-go/gradergradermodel.go
generated
vendored
1373
vendor/github.com/openai/openai-go/gradergradermodel.go
generated
vendored
File diff suppressed because it is too large
Load Diff
1300
vendor/github.com/openai/openai-go/image.go
generated
vendored
1300
vendor/github.com/openai/openai-go/image.go
generated
vendored
File diff suppressed because it is too large
Load Diff
58
vendor/github.com/openai/openai-go/internal/apierror/apierror.go
generated
vendored
58
vendor/github.com/openai/openai-go/internal/apierror/apierror.go
generated
vendored
@@ -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
|
|
||||||
}
|
|
||||||
465
vendor/github.com/openai/openai-go/internal/apiform/encoder.go
generated
vendored
465
vendor/github.com/openai/openai-go/internal/apiform/encoder.go
generated
vendored
@@ -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
|
|
||||||
}
|
|
||||||
5
vendor/github.com/openai/openai-go/internal/apiform/form.go
generated
vendored
5
vendor/github.com/openai/openai-go/internal/apiform/form.go
generated
vendored
@@ -1,5 +0,0 @@
|
|||||||
package apiform
|
|
||||||
|
|
||||||
type Marshaler interface {
|
|
||||||
MarshalMultipart() ([]byte, string, error)
|
|
||||||
}
|
|
||||||
20
vendor/github.com/openai/openai-go/internal/apiform/richparam.go
generated
vendored
20
vendor/github.com/openai/openai-go/internal/apiform/richparam.go
generated
vendored
@@ -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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
51
vendor/github.com/openai/openai-go/internal/apiform/tag.go
generated
vendored
51
vendor/github.com/openai/openai-go/internal/apiform/tag.go
generated
vendored
@@ -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
|
|
||||||
}
|
|
||||||
691
vendor/github.com/openai/openai-go/internal/apijson/decoder.go
generated
vendored
691
vendor/github.com/openai/openai-go/internal/apijson/decoder.go
generated
vendored
@@ -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
|
|
||||||
}
|
|
||||||
392
vendor/github.com/openai/openai-go/internal/apijson/encoder.go
generated
vendored
392
vendor/github.com/openai/openai-go/internal/apijson/encoder.go
generated
vendored
@@ -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(".", "\\.", ":", "\\:", "*", "\\*")
|
|
||||||
145
vendor/github.com/openai/openai-go/internal/apijson/enum.go
generated
vendored
145
vendor/github.com/openai/openai-go/internal/apijson/enum.go
generated
vendored
@@ -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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
23
vendor/github.com/openai/openai-go/internal/apijson/field.go
generated
vendored
23
vendor/github.com/openai/openai-go/internal/apijson/field.go
generated
vendored
@@ -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 }
|
|
||||||
120
vendor/github.com/openai/openai-go/internal/apijson/port.go
generated
vendored
120
vendor/github.com/openai/openai-go/internal/apijson/port.go
generated
vendored
@@ -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
|
|
||||||
}
|
|
||||||
51
vendor/github.com/openai/openai-go/internal/apijson/registry.go
generated
vendored
51
vendor/github.com/openai/openai-go/internal/apijson/registry.go
generated
vendored
@@ -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)
|
|
||||||
}
|
|
||||||
67
vendor/github.com/openai/openai-go/internal/apijson/subfield.go
generated
vendored
67
vendor/github.com/openai/openai-go/internal/apijson/subfield.go
generated
vendored
@@ -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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
47
vendor/github.com/openai/openai-go/internal/apijson/tag.go
generated
vendored
47
vendor/github.com/openai/openai-go/internal/apijson/tag.go
generated
vendored
@@ -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
|
|
||||||
}
|
|
||||||
202
vendor/github.com/openai/openai-go/internal/apijson/union.go
generated
vendored
202
vendor/github.com/openai/openai-go/internal/apijson/union.go
generated
vendored
@@ -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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
415
vendor/github.com/openai/openai-go/internal/apiquery/encoder.go
generated
vendored
415
vendor/github.com/openai/openai-go/internal/apiquery/encoder.go
generated
vendored
@@ -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)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
55
vendor/github.com/openai/openai-go/internal/apiquery/query.go
generated
vendored
55
vendor/github.com/openai/openai-go/internal/apiquery/query.go
generated
vendored
@@ -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
|
|
||||||
)
|
|
||||||
20
vendor/github.com/openai/openai-go/internal/apiquery/richparam.go
generated
vendored
20
vendor/github.com/openai/openai-go/internal/apiquery/richparam.go
generated
vendored
@@ -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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
44
vendor/github.com/openai/openai-go/internal/apiquery/tag.go
generated
vendored
44
vendor/github.com/openai/openai-go/internal/apiquery/tag.go
generated
vendored
@@ -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
|
|
||||||
}
|
|
||||||
1324
vendor/github.com/openai/openai-go/internal/encoding/json/decode.go
generated
vendored
1324
vendor/github.com/openai/openai-go/internal/encoding/json/decode.go
generated
vendored
File diff suppressed because it is too large
Load Diff
1391
vendor/github.com/openai/openai-go/internal/encoding/json/encode.go
generated
vendored
1391
vendor/github.com/openai/openai-go/internal/encoding/json/encode.go
generated
vendored
File diff suppressed because it is too large
Load Diff
48
vendor/github.com/openai/openai-go/internal/encoding/json/fold.go
generated
vendored
48
vendor/github.com/openai/openai-go/internal/encoding/json/fold.go
generated
vendored
@@ -1,48 +0,0 @@
|
|||||||
// Copyright 2013 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
|
|
||||||
|
|
||||||
import (
|
|
||||||
"unicode"
|
|
||||||
"unicode/utf8"
|
|
||||||
)
|
|
||||||
|
|
||||||
// foldName returns a folded string such that foldName(x) == foldName(y)
|
|
||||||
// is identical to bytes.EqualFold(x, y).
|
|
||||||
func foldName(in []byte) []byte {
|
|
||||||
// This is inlinable to take advantage of "function outlining".
|
|
||||||
var arr [32]byte // large enough for most JSON names
|
|
||||||
return appendFoldedName(arr[:0], in)
|
|
||||||
}
|
|
||||||
|
|
||||||
func appendFoldedName(out, in []byte) []byte {
|
|
||||||
for i := 0; i < len(in); {
|
|
||||||
// Handle single-byte ASCII.
|
|
||||||
if c := in[i]; c < utf8.RuneSelf {
|
|
||||||
if 'a' <= c && c <= 'z' {
|
|
||||||
c -= 'a' - 'A'
|
|
||||||
}
|
|
||||||
out = append(out, c)
|
|
||||||
i++
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
// Handle multi-byte Unicode.
|
|
||||||
r, n := utf8.DecodeRune(in[i:])
|
|
||||||
out = utf8.AppendRune(out, foldRune(r))
|
|
||||||
i += n
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
// foldRune is returns the smallest rune for all runes in the same fold set.
|
|
||||||
func foldRune(r rune) rune {
|
|
||||||
for {
|
|
||||||
r2 := unicode.SimpleFold(r)
|
|
||||||
if r2 <= r {
|
|
||||||
return r2
|
|
||||||
}
|
|
||||||
r = r2
|
|
||||||
}
|
|
||||||
}
|
|
||||||
182
vendor/github.com/openai/openai-go/internal/encoding/json/indent.go
generated
vendored
182
vendor/github.com/openai/openai-go/internal/encoding/json/indent.go
generated
vendored
@@ -1,182 +0,0 @@
|
|||||||
// 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
|
|
||||||
|
|
||||||
import "bytes"
|
|
||||||
|
|
||||||
// HTMLEscape appends to dst the JSON-encoded src with <, >, &, U+2028 and U+2029
|
|
||||||
// characters inside string literals changed to \u003c, \u003e, \u0026, \u2028, \u2029
|
|
||||||
// so that the JSON will be safe to embed inside HTML <script> tags.
|
|
||||||
// For historical reasons, web browsers don't honor standard HTML
|
|
||||||
// escaping within <script> tags, so an alternative JSON encoding must be used.
|
|
||||||
func HTMLEscape(dst *bytes.Buffer, src []byte) {
|
|
||||||
dst.Grow(len(src))
|
|
||||||
dst.Write(appendHTMLEscape(dst.AvailableBuffer(), src))
|
|
||||||
}
|
|
||||||
|
|
||||||
func appendHTMLEscape(dst, src []byte) []byte {
|
|
||||||
// The characters can only appear in string literals,
|
|
||||||
// so just scan the string one byte at a time.
|
|
||||||
start := 0
|
|
||||||
for i, c := range src {
|
|
||||||
if c == '<' || c == '>' || c == '&' {
|
|
||||||
dst = append(dst, src[start:i]...)
|
|
||||||
dst = append(dst, '\\', 'u', '0', '0', hex[c>>4], hex[c&0xF])
|
|
||||||
start = i + 1
|
|
||||||
}
|
|
||||||
// Convert U+2028 and U+2029 (E2 80 A8 and E2 80 A9).
|
|
||||||
if c == 0xE2 && i+2 < len(src) && src[i+1] == 0x80 && src[i+2]&^1 == 0xA8 {
|
|
||||||
dst = append(dst, src[start:i]...)
|
|
||||||
dst = append(dst, '\\', 'u', '2', '0', '2', hex[src[i+2]&0xF])
|
|
||||||
start = i + len("\u2029")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return append(dst, src[start:]...)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Compact appends to dst the JSON-encoded src with
|
|
||||||
// insignificant space characters elided.
|
|
||||||
func Compact(dst *bytes.Buffer, src []byte) error {
|
|
||||||
dst.Grow(len(src))
|
|
||||||
b := dst.AvailableBuffer()
|
|
||||||
b, err := appendCompact(b, src, false)
|
|
||||||
dst.Write(b)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func appendCompact(dst, src []byte, escape bool) ([]byte, error) {
|
|
||||||
origLen := len(dst)
|
|
||||||
scan := newScanner()
|
|
||||||
defer freeScanner(scan)
|
|
||||||
start := 0
|
|
||||||
for i, c := range src {
|
|
||||||
if escape && (c == '<' || c == '>' || c == '&') {
|
|
||||||
if start < i {
|
|
||||||
dst = append(dst, src[start:i]...)
|
|
||||||
}
|
|
||||||
dst = append(dst, '\\', 'u', '0', '0', hex[c>>4], hex[c&0xF])
|
|
||||||
start = i + 1
|
|
||||||
}
|
|
||||||
// Convert U+2028 and U+2029 (E2 80 A8 and E2 80 A9).
|
|
||||||
if escape && c == 0xE2 && i+2 < len(src) && src[i+1] == 0x80 && src[i+2]&^1 == 0xA8 {
|
|
||||||
if start < i {
|
|
||||||
dst = append(dst, src[start:i]...)
|
|
||||||
}
|
|
||||||
dst = append(dst, '\\', 'u', '2', '0', '2', hex[src[i+2]&0xF])
|
|
||||||
start = i + 3
|
|
||||||
}
|
|
||||||
v := scan.step(scan, c)
|
|
||||||
if v >= scanSkipSpace {
|
|
||||||
if v == scanError {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
if start < i {
|
|
||||||
dst = append(dst, src[start:i]...)
|
|
||||||
}
|
|
||||||
start = i + 1
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if scan.eof() == scanError {
|
|
||||||
return dst[:origLen], scan.err
|
|
||||||
}
|
|
||||||
if start < len(src) {
|
|
||||||
dst = append(dst, src[start:]...)
|
|
||||||
}
|
|
||||||
return dst, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func appendNewline(dst []byte, prefix, indent string, depth int) []byte {
|
|
||||||
dst = append(dst, '\n')
|
|
||||||
dst = append(dst, prefix...)
|
|
||||||
for i := 0; i < depth; i++ {
|
|
||||||
dst = append(dst, indent...)
|
|
||||||
}
|
|
||||||
return dst
|
|
||||||
}
|
|
||||||
|
|
||||||
// indentGrowthFactor specifies the growth factor of indenting JSON input.
|
|
||||||
// Empirically, the growth factor was measured to be between 1.4x to 1.8x
|
|
||||||
// for some set of compacted JSON with the indent being a single tab.
|
|
||||||
// Specify a growth factor slightly larger than what is observed
|
|
||||||
// to reduce probability of allocation in appendIndent.
|
|
||||||
// A factor no higher than 2 ensures that wasted space never exceeds 50%.
|
|
||||||
const indentGrowthFactor = 2
|
|
||||||
|
|
||||||
// Indent appends to dst an indented form of the JSON-encoded src.
|
|
||||||
// Each element in a JSON object or array begins on a new,
|
|
||||||
// indented line beginning with prefix followed by one or more
|
|
||||||
// copies of indent according to the indentation nesting.
|
|
||||||
// The data appended to dst does not begin with the prefix nor
|
|
||||||
// any indentation, to make it easier to embed inside other formatted JSON data.
|
|
||||||
// Although leading space characters (space, tab, carriage return, newline)
|
|
||||||
// at the beginning of src are dropped, trailing space characters
|
|
||||||
// at the end of src are preserved and copied to dst.
|
|
||||||
// For example, if src has no trailing spaces, neither will dst;
|
|
||||||
// if src ends in a trailing newline, so will dst.
|
|
||||||
func Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error {
|
|
||||||
dst.Grow(indentGrowthFactor * len(src))
|
|
||||||
b := dst.AvailableBuffer()
|
|
||||||
b, err := appendIndent(b, src, prefix, indent)
|
|
||||||
dst.Write(b)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func appendIndent(dst, src []byte, prefix, indent string) ([]byte, error) {
|
|
||||||
origLen := len(dst)
|
|
||||||
scan := newScanner()
|
|
||||||
defer freeScanner(scan)
|
|
||||||
needIndent := false
|
|
||||||
depth := 0
|
|
||||||
for _, c := range src {
|
|
||||||
scan.bytes++
|
|
||||||
v := scan.step(scan, c)
|
|
||||||
if v == scanSkipSpace {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if v == scanError {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
if needIndent && v != scanEndObject && v != scanEndArray {
|
|
||||||
needIndent = false
|
|
||||||
depth++
|
|
||||||
dst = appendNewline(dst, prefix, indent, depth)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Emit semantically uninteresting bytes
|
|
||||||
// (in particular, punctuation in strings) unmodified.
|
|
||||||
if v == scanContinue {
|
|
||||||
dst = append(dst, c)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add spacing around real punctuation.
|
|
||||||
switch c {
|
|
||||||
case '{', '[':
|
|
||||||
// delay indent so that empty object and array are formatted as {} and [].
|
|
||||||
needIndent = true
|
|
||||||
dst = append(dst, c)
|
|
||||||
case ',':
|
|
||||||
dst = append(dst, c)
|
|
||||||
dst = appendNewline(dst, prefix, indent, depth)
|
|
||||||
case ':':
|
|
||||||
dst = append(dst, c, ' ')
|
|
||||||
case '}', ']':
|
|
||||||
if needIndent {
|
|
||||||
// suppress indent in empty object/array
|
|
||||||
needIndent = false
|
|
||||||
} else {
|
|
||||||
depth--
|
|
||||||
dst = appendNewline(dst, prefix, indent, depth)
|
|
||||||
}
|
|
||||||
dst = append(dst, c)
|
|
||||||
default:
|
|
||||||
dst = append(dst, c)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if scan.eof() == scanError {
|
|
||||||
return dst[:origLen], scan.err
|
|
||||||
}
|
|
||||||
return dst, nil
|
|
||||||
}
|
|
||||||
610
vendor/github.com/openai/openai-go/internal/encoding/json/scanner.go
generated
vendored
610
vendor/github.com/openai/openai-go/internal/encoding/json/scanner.go
generated
vendored
@@ -1,610 +0,0 @@
|
|||||||
// 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
|
|
||||||
|
|
||||||
// JSON value parser state machine.
|
|
||||||
// Just about at the limit of what is reasonable to write by hand.
|
|
||||||
// Some parts are a bit tedious, but overall it nicely factors out the
|
|
||||||
// otherwise common code from the multiple scanning functions
|
|
||||||
// in this package (Compact, Indent, checkValid, etc).
|
|
||||||
//
|
|
||||||
// This file starts with two simple examples using the scanner
|
|
||||||
// before diving into the scanner itself.
|
|
||||||
|
|
||||||
import (
|
|
||||||
"strconv"
|
|
||||||
"sync"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Valid reports whether data is a valid JSON encoding.
|
|
||||||
func Valid(data []byte) bool {
|
|
||||||
scan := newScanner()
|
|
||||||
defer freeScanner(scan)
|
|
||||||
return checkValid(data, scan) == nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// checkValid verifies that data is valid JSON-encoded data.
|
|
||||||
// scan is passed in for use by checkValid to avoid an allocation.
|
|
||||||
// checkValid returns nil or a SyntaxError.
|
|
||||||
func checkValid(data []byte, scan *scanner) error {
|
|
||||||
scan.reset()
|
|
||||||
for _, c := range data {
|
|
||||||
scan.bytes++
|
|
||||||
if scan.step(scan, c) == scanError {
|
|
||||||
return scan.err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if scan.eof() == scanError {
|
|
||||||
return scan.err
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// A SyntaxError is a description of a JSON syntax error.
|
|
||||||
// [Unmarshal] will return a SyntaxError if the JSON can't be parsed.
|
|
||||||
type SyntaxError struct {
|
|
||||||
msg string // description of error
|
|
||||||
Offset int64 // error occurred after reading Offset bytes
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *SyntaxError) Error() string { return e.msg }
|
|
||||||
|
|
||||||
// A scanner is a JSON scanning state machine.
|
|
||||||
// Callers call scan.reset and then pass bytes in one at a time
|
|
||||||
// by calling scan.step(&scan, c) for each byte.
|
|
||||||
// The return value, referred to as an opcode, tells the
|
|
||||||
// caller about significant parsing events like beginning
|
|
||||||
// and ending literals, objects, and arrays, so that the
|
|
||||||
// caller can follow along if it wishes.
|
|
||||||
// The return value scanEnd indicates that a single top-level
|
|
||||||
// JSON value has been completed, *before* the byte that
|
|
||||||
// just got passed in. (The indication must be delayed in order
|
|
||||||
// to recognize the end of numbers: is 123 a whole value or
|
|
||||||
// the beginning of 12345e+6?).
|
|
||||||
type scanner struct {
|
|
||||||
// The step is a func to be called to execute the next transition.
|
|
||||||
// Also tried using an integer constant and a single func
|
|
||||||
// with a switch, but using the func directly was 10% faster
|
|
||||||
// on a 64-bit Mac Mini, and it's nicer to read.
|
|
||||||
step func(*scanner, byte) int
|
|
||||||
|
|
||||||
// Reached end of top-level value.
|
|
||||||
endTop bool
|
|
||||||
|
|
||||||
// Stack of what we're in the middle of - array values, object keys, object values.
|
|
||||||
parseState []int
|
|
||||||
|
|
||||||
// Error that happened, if any.
|
|
||||||
err error
|
|
||||||
|
|
||||||
// total bytes consumed, updated by decoder.Decode (and deliberately
|
|
||||||
// not set to zero by scan.reset)
|
|
||||||
bytes int64
|
|
||||||
}
|
|
||||||
|
|
||||||
var scannerPool = sync.Pool{
|
|
||||||
New: func() any {
|
|
||||||
return &scanner{}
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
func newScanner() *scanner {
|
|
||||||
scan := scannerPool.Get().(*scanner)
|
|
||||||
// scan.reset by design doesn't set bytes to zero
|
|
||||||
scan.bytes = 0
|
|
||||||
scan.reset()
|
|
||||||
return scan
|
|
||||||
}
|
|
||||||
|
|
||||||
func freeScanner(scan *scanner) {
|
|
||||||
// Avoid hanging on to too much memory in extreme cases.
|
|
||||||
if len(scan.parseState) > 1024 {
|
|
||||||
scan.parseState = nil
|
|
||||||
}
|
|
||||||
scannerPool.Put(scan)
|
|
||||||
}
|
|
||||||
|
|
||||||
// These values are returned by the state transition functions
|
|
||||||
// assigned to scanner.state and the method scanner.eof.
|
|
||||||
// They give details about the current state of the scan that
|
|
||||||
// callers might be interested to know about.
|
|
||||||
// It is okay to ignore the return value of any particular
|
|
||||||
// call to scanner.state: if one call returns scanError,
|
|
||||||
// every subsequent call will return scanError too.
|
|
||||||
const (
|
|
||||||
// Continue.
|
|
||||||
scanContinue = iota // uninteresting byte
|
|
||||||
scanBeginLiteral // end implied by next result != scanContinue
|
|
||||||
scanBeginObject // begin object
|
|
||||||
scanObjectKey // just finished object key (string)
|
|
||||||
scanObjectValue // just finished non-last object value
|
|
||||||
scanEndObject // end object (implies scanObjectValue if possible)
|
|
||||||
scanBeginArray // begin array
|
|
||||||
scanArrayValue // just finished array value
|
|
||||||
scanEndArray // end array (implies scanArrayValue if possible)
|
|
||||||
scanSkipSpace // space byte; can skip; known to be last "continue" result
|
|
||||||
|
|
||||||
// Stop.
|
|
||||||
scanEnd // top-level value ended *before* this byte; known to be first "stop" result
|
|
||||||
scanError // hit an error, scanner.err.
|
|
||||||
)
|
|
||||||
|
|
||||||
// These values are stored in the parseState stack.
|
|
||||||
// They give the current state of a composite value
|
|
||||||
// being scanned. If the parser is inside a nested value
|
|
||||||
// the parseState describes the nested state, outermost at entry 0.
|
|
||||||
const (
|
|
||||||
parseObjectKey = iota // parsing object key (before colon)
|
|
||||||
parseObjectValue // parsing object value (after colon)
|
|
||||||
parseArrayValue // parsing array value
|
|
||||||
)
|
|
||||||
|
|
||||||
// This limits the max nesting depth to prevent stack overflow.
|
|
||||||
// This is permitted by https://tools.ietf.org/html/rfc7159#section-9
|
|
||||||
const maxNestingDepth = 10000
|
|
||||||
|
|
||||||
// reset prepares the scanner for use.
|
|
||||||
// It must be called before calling s.step.
|
|
||||||
func (s *scanner) reset() {
|
|
||||||
s.step = stateBeginValue
|
|
||||||
s.parseState = s.parseState[0:0]
|
|
||||||
s.err = nil
|
|
||||||
s.endTop = false
|
|
||||||
}
|
|
||||||
|
|
||||||
// eof tells the scanner that the end of input has been reached.
|
|
||||||
// It returns a scan status just as s.step does.
|
|
||||||
func (s *scanner) eof() int {
|
|
||||||
if s.err != nil {
|
|
||||||
return scanError
|
|
||||||
}
|
|
||||||
if s.endTop {
|
|
||||||
return scanEnd
|
|
||||||
}
|
|
||||||
s.step(s, ' ')
|
|
||||||
if s.endTop {
|
|
||||||
return scanEnd
|
|
||||||
}
|
|
||||||
if s.err == nil {
|
|
||||||
s.err = &SyntaxError{"unexpected end of JSON input", s.bytes}
|
|
||||||
}
|
|
||||||
return scanError
|
|
||||||
}
|
|
||||||
|
|
||||||
// pushParseState pushes a new parse state p onto the parse stack.
|
|
||||||
// an error state is returned if maxNestingDepth was exceeded, otherwise successState is returned.
|
|
||||||
func (s *scanner) pushParseState(c byte, newParseState int, successState int) int {
|
|
||||||
s.parseState = append(s.parseState, newParseState)
|
|
||||||
if len(s.parseState) <= maxNestingDepth {
|
|
||||||
return successState
|
|
||||||
}
|
|
||||||
return s.error(c, "exceeded max depth")
|
|
||||||
}
|
|
||||||
|
|
||||||
// popParseState pops a parse state (already obtained) off the stack
|
|
||||||
// and updates s.step accordingly.
|
|
||||||
func (s *scanner) popParseState() {
|
|
||||||
n := len(s.parseState) - 1
|
|
||||||
s.parseState = s.parseState[0:n]
|
|
||||||
if n == 0 {
|
|
||||||
s.step = stateEndTop
|
|
||||||
s.endTop = true
|
|
||||||
} else {
|
|
||||||
s.step = stateEndValue
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func isSpace(c byte) bool {
|
|
||||||
return c <= ' ' && (c == ' ' || c == '\t' || c == '\r' || c == '\n')
|
|
||||||
}
|
|
||||||
|
|
||||||
// stateBeginValueOrEmpty is the state after reading `[`.
|
|
||||||
func stateBeginValueOrEmpty(s *scanner, c byte) int {
|
|
||||||
if isSpace(c) {
|
|
||||||
return scanSkipSpace
|
|
||||||
}
|
|
||||||
if c == ']' {
|
|
||||||
return stateEndValue(s, c)
|
|
||||||
}
|
|
||||||
return stateBeginValue(s, c)
|
|
||||||
}
|
|
||||||
|
|
||||||
// stateBeginValue is the state at the beginning of the input.
|
|
||||||
func stateBeginValue(s *scanner, c byte) int {
|
|
||||||
if isSpace(c) {
|
|
||||||
return scanSkipSpace
|
|
||||||
}
|
|
||||||
switch c {
|
|
||||||
case '{':
|
|
||||||
s.step = stateBeginStringOrEmpty
|
|
||||||
return s.pushParseState(c, parseObjectKey, scanBeginObject)
|
|
||||||
case '[':
|
|
||||||
s.step = stateBeginValueOrEmpty
|
|
||||||
return s.pushParseState(c, parseArrayValue, scanBeginArray)
|
|
||||||
case '"':
|
|
||||||
s.step = stateInString
|
|
||||||
return scanBeginLiteral
|
|
||||||
case '-':
|
|
||||||
s.step = stateNeg
|
|
||||||
return scanBeginLiteral
|
|
||||||
case '0': // beginning of 0.123
|
|
||||||
s.step = state0
|
|
||||||
return scanBeginLiteral
|
|
||||||
case 't': // beginning of true
|
|
||||||
s.step = stateT
|
|
||||||
return scanBeginLiteral
|
|
||||||
case 'f': // beginning of false
|
|
||||||
s.step = stateF
|
|
||||||
return scanBeginLiteral
|
|
||||||
case 'n': // beginning of null
|
|
||||||
s.step = stateN
|
|
||||||
return scanBeginLiteral
|
|
||||||
}
|
|
||||||
if '1' <= c && c <= '9' { // beginning of 1234.5
|
|
||||||
s.step = state1
|
|
||||||
return scanBeginLiteral
|
|
||||||
}
|
|
||||||
return s.error(c, "looking for beginning of value")
|
|
||||||
}
|
|
||||||
|
|
||||||
// stateBeginStringOrEmpty is the state after reading `{`.
|
|
||||||
func stateBeginStringOrEmpty(s *scanner, c byte) int {
|
|
||||||
if isSpace(c) {
|
|
||||||
return scanSkipSpace
|
|
||||||
}
|
|
||||||
if c == '}' {
|
|
||||||
n := len(s.parseState)
|
|
||||||
s.parseState[n-1] = parseObjectValue
|
|
||||||
return stateEndValue(s, c)
|
|
||||||
}
|
|
||||||
return stateBeginString(s, c)
|
|
||||||
}
|
|
||||||
|
|
||||||
// stateBeginString is the state after reading `{"key": value,`.
|
|
||||||
func stateBeginString(s *scanner, c byte) int {
|
|
||||||
if isSpace(c) {
|
|
||||||
return scanSkipSpace
|
|
||||||
}
|
|
||||||
if c == '"' {
|
|
||||||
s.step = stateInString
|
|
||||||
return scanBeginLiteral
|
|
||||||
}
|
|
||||||
return s.error(c, "looking for beginning of object key string")
|
|
||||||
}
|
|
||||||
|
|
||||||
// stateEndValue is the state after completing a value,
|
|
||||||
// such as after reading `{}` or `true` or `["x"`.
|
|
||||||
func stateEndValue(s *scanner, c byte) int {
|
|
||||||
n := len(s.parseState)
|
|
||||||
if n == 0 {
|
|
||||||
// Completed top-level before the current byte.
|
|
||||||
s.step = stateEndTop
|
|
||||||
s.endTop = true
|
|
||||||
return stateEndTop(s, c)
|
|
||||||
}
|
|
||||||
if isSpace(c) {
|
|
||||||
s.step = stateEndValue
|
|
||||||
return scanSkipSpace
|
|
||||||
}
|
|
||||||
ps := s.parseState[n-1]
|
|
||||||
switch ps {
|
|
||||||
case parseObjectKey:
|
|
||||||
if c == ':' {
|
|
||||||
s.parseState[n-1] = parseObjectValue
|
|
||||||
s.step = stateBeginValue
|
|
||||||
return scanObjectKey
|
|
||||||
}
|
|
||||||
return s.error(c, "after object key")
|
|
||||||
case parseObjectValue:
|
|
||||||
if c == ',' {
|
|
||||||
s.parseState[n-1] = parseObjectKey
|
|
||||||
s.step = stateBeginString
|
|
||||||
return scanObjectValue
|
|
||||||
}
|
|
||||||
if c == '}' {
|
|
||||||
s.popParseState()
|
|
||||||
return scanEndObject
|
|
||||||
}
|
|
||||||
return s.error(c, "after object key:value pair")
|
|
||||||
case parseArrayValue:
|
|
||||||
if c == ',' {
|
|
||||||
s.step = stateBeginValue
|
|
||||||
return scanArrayValue
|
|
||||||
}
|
|
||||||
if c == ']' {
|
|
||||||
s.popParseState()
|
|
||||||
return scanEndArray
|
|
||||||
}
|
|
||||||
return s.error(c, "after array element")
|
|
||||||
}
|
|
||||||
return s.error(c, "")
|
|
||||||
}
|
|
||||||
|
|
||||||
// stateEndTop is the state after finishing the top-level value,
|
|
||||||
// such as after reading `{}` or `[1,2,3]`.
|
|
||||||
// Only space characters should be seen now.
|
|
||||||
func stateEndTop(s *scanner, c byte) int {
|
|
||||||
if !isSpace(c) {
|
|
||||||
// Complain about non-space byte on next call.
|
|
||||||
s.error(c, "after top-level value")
|
|
||||||
}
|
|
||||||
return scanEnd
|
|
||||||
}
|
|
||||||
|
|
||||||
// stateInString is the state after reading `"`.
|
|
||||||
func stateInString(s *scanner, c byte) int {
|
|
||||||
if c == '"' {
|
|
||||||
s.step = stateEndValue
|
|
||||||
return scanContinue
|
|
||||||
}
|
|
||||||
if c == '\\' {
|
|
||||||
s.step = stateInStringEsc
|
|
||||||
return scanContinue
|
|
||||||
}
|
|
||||||
if c < 0x20 {
|
|
||||||
return s.error(c, "in string literal")
|
|
||||||
}
|
|
||||||
return scanContinue
|
|
||||||
}
|
|
||||||
|
|
||||||
// stateInStringEsc is the state after reading `"\` during a quoted string.
|
|
||||||
func stateInStringEsc(s *scanner, c byte) int {
|
|
||||||
switch c {
|
|
||||||
case 'b', 'f', 'n', 'r', 't', '\\', '/', '"':
|
|
||||||
s.step = stateInString
|
|
||||||
return scanContinue
|
|
||||||
case 'u':
|
|
||||||
s.step = stateInStringEscU
|
|
||||||
return scanContinue
|
|
||||||
}
|
|
||||||
return s.error(c, "in string escape code")
|
|
||||||
}
|
|
||||||
|
|
||||||
// stateInStringEscU is the state after reading `"\u` during a quoted string.
|
|
||||||
func stateInStringEscU(s *scanner, c byte) int {
|
|
||||||
if '0' <= c && c <= '9' || 'a' <= c && c <= 'f' || 'A' <= c && c <= 'F' {
|
|
||||||
s.step = stateInStringEscU1
|
|
||||||
return scanContinue
|
|
||||||
}
|
|
||||||
// numbers
|
|
||||||
return s.error(c, "in \\u hexadecimal character escape")
|
|
||||||
}
|
|
||||||
|
|
||||||
// stateInStringEscU1 is the state after reading `"\u1` during a quoted string.
|
|
||||||
func stateInStringEscU1(s *scanner, c byte) int {
|
|
||||||
if '0' <= c && c <= '9' || 'a' <= c && c <= 'f' || 'A' <= c && c <= 'F' {
|
|
||||||
s.step = stateInStringEscU12
|
|
||||||
return scanContinue
|
|
||||||
}
|
|
||||||
// numbers
|
|
||||||
return s.error(c, "in \\u hexadecimal character escape")
|
|
||||||
}
|
|
||||||
|
|
||||||
// stateInStringEscU12 is the state after reading `"\u12` during a quoted string.
|
|
||||||
func stateInStringEscU12(s *scanner, c byte) int {
|
|
||||||
if '0' <= c && c <= '9' || 'a' <= c && c <= 'f' || 'A' <= c && c <= 'F' {
|
|
||||||
s.step = stateInStringEscU123
|
|
||||||
return scanContinue
|
|
||||||
}
|
|
||||||
// numbers
|
|
||||||
return s.error(c, "in \\u hexadecimal character escape")
|
|
||||||
}
|
|
||||||
|
|
||||||
// stateInStringEscU123 is the state after reading `"\u123` during a quoted string.
|
|
||||||
func stateInStringEscU123(s *scanner, c byte) int {
|
|
||||||
if '0' <= c && c <= '9' || 'a' <= c && c <= 'f' || 'A' <= c && c <= 'F' {
|
|
||||||
s.step = stateInString
|
|
||||||
return scanContinue
|
|
||||||
}
|
|
||||||
// numbers
|
|
||||||
return s.error(c, "in \\u hexadecimal character escape")
|
|
||||||
}
|
|
||||||
|
|
||||||
// stateNeg is the state after reading `-` during a number.
|
|
||||||
func stateNeg(s *scanner, c byte) int {
|
|
||||||
if c == '0' {
|
|
||||||
s.step = state0
|
|
||||||
return scanContinue
|
|
||||||
}
|
|
||||||
if '1' <= c && c <= '9' {
|
|
||||||
s.step = state1
|
|
||||||
return scanContinue
|
|
||||||
}
|
|
||||||
return s.error(c, "in numeric literal")
|
|
||||||
}
|
|
||||||
|
|
||||||
// state1 is the state after reading a non-zero integer during a number,
|
|
||||||
// such as after reading `1` or `100` but not `0`.
|
|
||||||
func state1(s *scanner, c byte) int {
|
|
||||||
if '0' <= c && c <= '9' {
|
|
||||||
s.step = state1
|
|
||||||
return scanContinue
|
|
||||||
}
|
|
||||||
return state0(s, c)
|
|
||||||
}
|
|
||||||
|
|
||||||
// state0 is the state after reading `0` during a number.
|
|
||||||
func state0(s *scanner, c byte) int {
|
|
||||||
if c == '.' {
|
|
||||||
s.step = stateDot
|
|
||||||
return scanContinue
|
|
||||||
}
|
|
||||||
if c == 'e' || c == 'E' {
|
|
||||||
s.step = stateE
|
|
||||||
return scanContinue
|
|
||||||
}
|
|
||||||
return stateEndValue(s, c)
|
|
||||||
}
|
|
||||||
|
|
||||||
// stateDot is the state after reading the integer and decimal point in a number,
|
|
||||||
// such as after reading `1.`.
|
|
||||||
func stateDot(s *scanner, c byte) int {
|
|
||||||
if '0' <= c && c <= '9' {
|
|
||||||
s.step = stateDot0
|
|
||||||
return scanContinue
|
|
||||||
}
|
|
||||||
return s.error(c, "after decimal point in numeric literal")
|
|
||||||
}
|
|
||||||
|
|
||||||
// stateDot0 is the state after reading the integer, decimal point, and subsequent
|
|
||||||
// digits of a number, such as after reading `3.14`.
|
|
||||||
func stateDot0(s *scanner, c byte) int {
|
|
||||||
if '0' <= c && c <= '9' {
|
|
||||||
return scanContinue
|
|
||||||
}
|
|
||||||
if c == 'e' || c == 'E' {
|
|
||||||
s.step = stateE
|
|
||||||
return scanContinue
|
|
||||||
}
|
|
||||||
return stateEndValue(s, c)
|
|
||||||
}
|
|
||||||
|
|
||||||
// stateE is the state after reading the mantissa and e in a number,
|
|
||||||
// such as after reading `314e` or `0.314e`.
|
|
||||||
func stateE(s *scanner, c byte) int {
|
|
||||||
if c == '+' || c == '-' {
|
|
||||||
s.step = stateESign
|
|
||||||
return scanContinue
|
|
||||||
}
|
|
||||||
return stateESign(s, c)
|
|
||||||
}
|
|
||||||
|
|
||||||
// stateESign is the state after reading the mantissa, e, and sign in a number,
|
|
||||||
// such as after reading `314e-` or `0.314e+`.
|
|
||||||
func stateESign(s *scanner, c byte) int {
|
|
||||||
if '0' <= c && c <= '9' {
|
|
||||||
s.step = stateE0
|
|
||||||
return scanContinue
|
|
||||||
}
|
|
||||||
return s.error(c, "in exponent of numeric literal")
|
|
||||||
}
|
|
||||||
|
|
||||||
// stateE0 is the state after reading the mantissa, e, optional sign,
|
|
||||||
// and at least one digit of the exponent in a number,
|
|
||||||
// such as after reading `314e-2` or `0.314e+1` or `3.14e0`.
|
|
||||||
func stateE0(s *scanner, c byte) int {
|
|
||||||
if '0' <= c && c <= '9' {
|
|
||||||
return scanContinue
|
|
||||||
}
|
|
||||||
return stateEndValue(s, c)
|
|
||||||
}
|
|
||||||
|
|
||||||
// stateT is the state after reading `t`.
|
|
||||||
func stateT(s *scanner, c byte) int {
|
|
||||||
if c == 'r' {
|
|
||||||
s.step = stateTr
|
|
||||||
return scanContinue
|
|
||||||
}
|
|
||||||
return s.error(c, "in literal true (expecting 'r')")
|
|
||||||
}
|
|
||||||
|
|
||||||
// stateTr is the state after reading `tr`.
|
|
||||||
func stateTr(s *scanner, c byte) int {
|
|
||||||
if c == 'u' {
|
|
||||||
s.step = stateTru
|
|
||||||
return scanContinue
|
|
||||||
}
|
|
||||||
return s.error(c, "in literal true (expecting 'u')")
|
|
||||||
}
|
|
||||||
|
|
||||||
// stateTru is the state after reading `tru`.
|
|
||||||
func stateTru(s *scanner, c byte) int {
|
|
||||||
if c == 'e' {
|
|
||||||
s.step = stateEndValue
|
|
||||||
return scanContinue
|
|
||||||
}
|
|
||||||
return s.error(c, "in literal true (expecting 'e')")
|
|
||||||
}
|
|
||||||
|
|
||||||
// stateF is the state after reading `f`.
|
|
||||||
func stateF(s *scanner, c byte) int {
|
|
||||||
if c == 'a' {
|
|
||||||
s.step = stateFa
|
|
||||||
return scanContinue
|
|
||||||
}
|
|
||||||
return s.error(c, "in literal false (expecting 'a')")
|
|
||||||
}
|
|
||||||
|
|
||||||
// stateFa is the state after reading `fa`.
|
|
||||||
func stateFa(s *scanner, c byte) int {
|
|
||||||
if c == 'l' {
|
|
||||||
s.step = stateFal
|
|
||||||
return scanContinue
|
|
||||||
}
|
|
||||||
return s.error(c, "in literal false (expecting 'l')")
|
|
||||||
}
|
|
||||||
|
|
||||||
// stateFal is the state after reading `fal`.
|
|
||||||
func stateFal(s *scanner, c byte) int {
|
|
||||||
if c == 's' {
|
|
||||||
s.step = stateFals
|
|
||||||
return scanContinue
|
|
||||||
}
|
|
||||||
return s.error(c, "in literal false (expecting 's')")
|
|
||||||
}
|
|
||||||
|
|
||||||
// stateFals is the state after reading `fals`.
|
|
||||||
func stateFals(s *scanner, c byte) int {
|
|
||||||
if c == 'e' {
|
|
||||||
s.step = stateEndValue
|
|
||||||
return scanContinue
|
|
||||||
}
|
|
||||||
return s.error(c, "in literal false (expecting 'e')")
|
|
||||||
}
|
|
||||||
|
|
||||||
// stateN is the state after reading `n`.
|
|
||||||
func stateN(s *scanner, c byte) int {
|
|
||||||
if c == 'u' {
|
|
||||||
s.step = stateNu
|
|
||||||
return scanContinue
|
|
||||||
}
|
|
||||||
return s.error(c, "in literal null (expecting 'u')")
|
|
||||||
}
|
|
||||||
|
|
||||||
// stateNu is the state after reading `nu`.
|
|
||||||
func stateNu(s *scanner, c byte) int {
|
|
||||||
if c == 'l' {
|
|
||||||
s.step = stateNul
|
|
||||||
return scanContinue
|
|
||||||
}
|
|
||||||
return s.error(c, "in literal null (expecting 'l')")
|
|
||||||
}
|
|
||||||
|
|
||||||
// stateNul is the state after reading `nul`.
|
|
||||||
func stateNul(s *scanner, c byte) int {
|
|
||||||
if c == 'l' {
|
|
||||||
s.step = stateEndValue
|
|
||||||
return scanContinue
|
|
||||||
}
|
|
||||||
return s.error(c, "in literal null (expecting 'l')")
|
|
||||||
}
|
|
||||||
|
|
||||||
// stateError is the state after reaching a syntax error,
|
|
||||||
// such as after reading `[1}` or `5.1.2`.
|
|
||||||
func stateError(s *scanner, c byte) int {
|
|
||||||
return scanError
|
|
||||||
}
|
|
||||||
|
|
||||||
// error records an error and switches to the error state.
|
|
||||||
func (s *scanner) error(c byte, context string) int {
|
|
||||||
s.step = stateError
|
|
||||||
s.err = &SyntaxError{"invalid character " + quoteChar(c) + " " + context, s.bytes}
|
|
||||||
return scanError
|
|
||||||
}
|
|
||||||
|
|
||||||
// quoteChar formats c as a quoted character literal.
|
|
||||||
func quoteChar(c byte) string {
|
|
||||||
// special cases - different from quoted strings
|
|
||||||
if c == '\'' {
|
|
||||||
return `'\''`
|
|
||||||
}
|
|
||||||
if c == '"' {
|
|
||||||
return `'"'`
|
|
||||||
}
|
|
||||||
|
|
||||||
// use quoted string with different quotation marks
|
|
||||||
s := strconv.Quote(string(c))
|
|
||||||
return "'" + s[1:len(s)-1] + "'"
|
|
||||||
}
|
|
||||||
46
vendor/github.com/openai/openai-go/internal/encoding/json/sentinel/null.go
generated
vendored
46
vendor/github.com/openai/openai-go/internal/encoding/json/sentinel/null.go
generated
vendored
@@ -1,46 +0,0 @@
|
|||||||
package sentinel
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/openai/openai-go/internal/encoding/json/shims"
|
|
||||||
"reflect"
|
|
||||||
"sync"
|
|
||||||
)
|
|
||||||
|
|
||||||
type cacheEntry struct {
|
|
||||||
x any
|
|
||||||
ptr uintptr
|
|
||||||
kind reflect.Kind
|
|
||||||
}
|
|
||||||
|
|
||||||
var nullCache sync.Map // map[reflect.Type]cacheEntry
|
|
||||||
|
|
||||||
func NewNullSentinel[T any](mk func() T) T {
|
|
||||||
t := shims.TypeFor[T]()
|
|
||||||
entry, loaded := nullCache.Load(t) // avoid premature allocation
|
|
||||||
if !loaded {
|
|
||||||
x := mk()
|
|
||||||
ptr := reflect.ValueOf(x).Pointer()
|
|
||||||
entry, _ = nullCache.LoadOrStore(t, cacheEntry{x, ptr, t.Kind()})
|
|
||||||
}
|
|
||||||
return entry.(cacheEntry).x.(T)
|
|
||||||
}
|
|
||||||
|
|
||||||
// for internal use only
|
|
||||||
func IsValueNull(v reflect.Value) bool {
|
|
||||||
switch v.Kind() {
|
|
||||||
case reflect.Map, reflect.Slice:
|
|
||||||
null, ok := nullCache.Load(v.Type())
|
|
||||||
return ok && v.Pointer() == null.(cacheEntry).ptr
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func IsNull[T any](v T) bool {
|
|
||||||
t := shims.TypeFor[T]()
|
|
||||||
switch t.Kind() {
|
|
||||||
case reflect.Map, reflect.Slice:
|
|
||||||
null, ok := nullCache.Load(t)
|
|
||||||
return ok && reflect.ValueOf(v).Pointer() == null.(cacheEntry).ptr
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
111
vendor/github.com/openai/openai-go/internal/encoding/json/shims/shims.go
generated
vendored
111
vendor/github.com/openai/openai-go/internal/encoding/json/shims/shims.go
generated
vendored
@@ -1,111 +0,0 @@
|
|||||||
// This package provides shims over Go 1.2{2,3} APIs
|
|
||||||
// which are missing from Go 1.21, and used by the Go 1.24 encoding/json package.
|
|
||||||
//
|
|
||||||
// Inside the vendored package, all shim code has comments that begin look like
|
|
||||||
// // SHIM(...): ...
|
|
||||||
package shims
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/base64"
|
|
||||||
"reflect"
|
|
||||||
"slices"
|
|
||||||
)
|
|
||||||
|
|
||||||
type OverflowableType struct{ reflect.Type }
|
|
||||||
|
|
||||||
func (t OverflowableType) OverflowInt(x int64) bool {
|
|
||||||
k := t.Kind()
|
|
||||||
switch k {
|
|
||||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
|
||||||
bitSize := t.Size() * 8
|
|
||||||
trunc := (x << (64 - bitSize)) >> (64 - bitSize)
|
|
||||||
return x != trunc
|
|
||||||
}
|
|
||||||
panic("reflect: OverflowInt of non-int type " + t.String())
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t OverflowableType) OverflowUint(x uint64) bool {
|
|
||||||
k := t.Kind()
|
|
||||||
switch k {
|
|
||||||
case reflect.Uint, reflect.Uintptr, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
|
||||||
bitSize := t.Size() * 8
|
|
||||||
trunc := (x << (64 - bitSize)) >> (64 - bitSize)
|
|
||||||
return x != trunc
|
|
||||||
}
|
|
||||||
panic("reflect: OverflowUint of non-uint type " + t.String())
|
|
||||||
}
|
|
||||||
|
|
||||||
// Original src code from Go 1.23 go/src/reflect/type.go (taken 1/9/25)
|
|
||||||
/*
|
|
||||||
|
|
||||||
func (t *rtype) OverflowInt(x int64) bool {
|
|
||||||
k := t.Kind()
|
|
||||||
switch k {
|
|
||||||
case Int, Int8, Int16, Int32, Int64:
|
|
||||||
bitSize := t.Size() * 8
|
|
||||||
trunc := (x << (64 - bitSize)) >> (64 - bitSize)
|
|
||||||
return x != trunc
|
|
||||||
}
|
|
||||||
panic("reflect: OverflowInt of non-int type " + t.String())
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *rtype) OverflowUint(x uint64) bool {
|
|
||||||
k := t.Kind()
|
|
||||||
switch k {
|
|
||||||
case Uint, Uintptr, Uint8, Uint16, Uint32, Uint64:
|
|
||||||
bitSize := t.Size() * 8
|
|
||||||
trunc := (x << (64 - bitSize)) >> (64 - bitSize)
|
|
||||||
return x != trunc
|
|
||||||
}
|
|
||||||
panic("reflect: OverflowUint of non-uint type " + t.String())
|
|
||||||
}
|
|
||||||
|
|
||||||
*/
|
|
||||||
|
|
||||||
// TypeFor returns the [Type] that represents the type argument T.
|
|
||||||
func TypeFor[T any]() reflect.Type {
|
|
||||||
var v T
|
|
||||||
if t := reflect.TypeOf(v); t != nil {
|
|
||||||
return t // optimize for T being a non-interface kind
|
|
||||||
}
|
|
||||||
return reflect.TypeOf((*T)(nil)).Elem() // only for an interface kind
|
|
||||||
}
|
|
||||||
|
|
||||||
// Original src code from Go 1.23 go/src/reflect/type.go (taken 1/9/25)
|
|
||||||
/*
|
|
||||||
|
|
||||||
// TypeFor returns the [Type] that represents the type argument T.
|
|
||||||
func TypeFor[T any]() Type {
|
|
||||||
var v T
|
|
||||||
if t := TypeOf(v); t != nil {
|
|
||||||
return t // optimize for T being a non-interface kind
|
|
||||||
}
|
|
||||||
return TypeOf((*T)(nil)).Elem() // only for an interface kind
|
|
||||||
}
|
|
||||||
|
|
||||||
*/
|
|
||||||
|
|
||||||
type AppendableStdEncoding struct{ *base64.Encoding }
|
|
||||||
|
|
||||||
// AppendEncode appends the base64 encoded src to dst
|
|
||||||
// and returns the extended buffer.
|
|
||||||
func (enc AppendableStdEncoding) AppendEncode(dst, src []byte) []byte {
|
|
||||||
n := enc.EncodedLen(len(src))
|
|
||||||
dst = slices.Grow(dst, n)
|
|
||||||
enc.Encode(dst[len(dst):][:n], src)
|
|
||||||
return dst[:len(dst)+n]
|
|
||||||
}
|
|
||||||
|
|
||||||
// Original src code from Go 1.23.4 go/src/encoding/base64/base64.go (taken 1/9/25)
|
|
||||||
/*
|
|
||||||
|
|
||||||
// AppendEncode appends the base64 encoded src to dst
|
|
||||||
// and returns the extended buffer.
|
|
||||||
func (enc *Encoding) AppendEncode(dst, src []byte) []byte {
|
|
||||||
n := enc.EncodedLen(len(src))
|
|
||||||
dst = slices.Grow(dst, n)
|
|
||||||
enc.Encode(dst[len(dst):][:n], src)
|
|
||||||
return dst[:len(dst)+n]
|
|
||||||
}
|
|
||||||
|
|
||||||
*/
|
|
||||||
512
vendor/github.com/openai/openai-go/internal/encoding/json/stream.go
generated
vendored
512
vendor/github.com/openai/openai-go/internal/encoding/json/stream.go
generated
vendored
@@ -1,512 +0,0 @@
|
|||||||
// 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
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"errors"
|
|
||||||
"io"
|
|
||||||
)
|
|
||||||
|
|
||||||
// A Decoder reads and decodes JSON values from an input stream.
|
|
||||||
type Decoder struct {
|
|
||||||
r io.Reader
|
|
||||||
buf []byte
|
|
||||||
d decodeState
|
|
||||||
scanp int // start of unread data in buf
|
|
||||||
scanned int64 // amount of data already scanned
|
|
||||||
scan scanner
|
|
||||||
err error
|
|
||||||
|
|
||||||
tokenState int
|
|
||||||
tokenStack []int
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewDecoder returns a new decoder that reads from r.
|
|
||||||
//
|
|
||||||
// The decoder introduces its own buffering and may
|
|
||||||
// read data from r beyond the JSON values requested.
|
|
||||||
func NewDecoder(r io.Reader) *Decoder {
|
|
||||||
return &Decoder{r: r}
|
|
||||||
}
|
|
||||||
|
|
||||||
// UseNumber causes the Decoder to unmarshal a number into an
|
|
||||||
// interface value as a [Number] instead of as a float64.
|
|
||||||
func (dec *Decoder) UseNumber() { dec.d.useNumber = true }
|
|
||||||
|
|
||||||
// DisallowUnknownFields causes the Decoder to return an error when the destination
|
|
||||||
// is a struct and the input contains object keys which do not match any
|
|
||||||
// non-ignored, exported fields in the destination.
|
|
||||||
func (dec *Decoder) DisallowUnknownFields() { dec.d.disallowUnknownFields = true }
|
|
||||||
|
|
||||||
// Decode reads the next JSON-encoded value from its
|
|
||||||
// input and stores it in the value pointed to by v.
|
|
||||||
//
|
|
||||||
// See the documentation for [Unmarshal] for details about
|
|
||||||
// the conversion of JSON into a Go value.
|
|
||||||
func (dec *Decoder) Decode(v any) error {
|
|
||||||
if dec.err != nil {
|
|
||||||
return dec.err
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := dec.tokenPrepareForDecode(); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
if !dec.tokenValueAllowed() {
|
|
||||||
return &SyntaxError{msg: "not at beginning of value", Offset: dec.InputOffset()}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Read whole value into buffer.
|
|
||||||
n, err := dec.readValue()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
dec.d.init(dec.buf[dec.scanp : dec.scanp+n])
|
|
||||||
dec.scanp += n
|
|
||||||
|
|
||||||
// Don't save err from unmarshal into dec.err:
|
|
||||||
// the connection is still usable since we read a complete JSON
|
|
||||||
// object from it before the error happened.
|
|
||||||
err = dec.d.unmarshal(v)
|
|
||||||
|
|
||||||
// fixup token streaming state
|
|
||||||
dec.tokenValueEnd()
|
|
||||||
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// Buffered returns a reader of the data remaining in the Decoder's
|
|
||||||
// buffer. The reader is valid until the next call to [Decoder.Decode].
|
|
||||||
func (dec *Decoder) Buffered() io.Reader {
|
|
||||||
return bytes.NewReader(dec.buf[dec.scanp:])
|
|
||||||
}
|
|
||||||
|
|
||||||
// readValue reads a JSON value into dec.buf.
|
|
||||||
// It returns the length of the encoding.
|
|
||||||
func (dec *Decoder) readValue() (int, error) {
|
|
||||||
dec.scan.reset()
|
|
||||||
|
|
||||||
scanp := dec.scanp
|
|
||||||
var err error
|
|
||||||
Input:
|
|
||||||
// help the compiler see that scanp is never negative, so it can remove
|
|
||||||
// some bounds checks below.
|
|
||||||
for scanp >= 0 {
|
|
||||||
|
|
||||||
// Look in the buffer for a new value.
|
|
||||||
for ; scanp < len(dec.buf); scanp++ {
|
|
||||||
c := dec.buf[scanp]
|
|
||||||
dec.scan.bytes++
|
|
||||||
switch dec.scan.step(&dec.scan, c) {
|
|
||||||
case scanEnd:
|
|
||||||
// scanEnd is delayed one byte so we decrement
|
|
||||||
// the scanner bytes count by 1 to ensure that
|
|
||||||
// this value is correct in the next call of Decode.
|
|
||||||
dec.scan.bytes--
|
|
||||||
break Input
|
|
||||||
case scanEndObject, scanEndArray:
|
|
||||||
// scanEnd is delayed one byte.
|
|
||||||
// We might block trying to get that byte from src,
|
|
||||||
// so instead invent a space byte.
|
|
||||||
if stateEndValue(&dec.scan, ' ') == scanEnd {
|
|
||||||
scanp++
|
|
||||||
break Input
|
|
||||||
}
|
|
||||||
case scanError:
|
|
||||||
dec.err = dec.scan.err
|
|
||||||
return 0, dec.scan.err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Did the last read have an error?
|
|
||||||
// Delayed until now to allow buffer scan.
|
|
||||||
if err != nil {
|
|
||||||
if err == io.EOF {
|
|
||||||
if dec.scan.step(&dec.scan, ' ') == scanEnd {
|
|
||||||
break Input
|
|
||||||
}
|
|
||||||
if nonSpace(dec.buf) {
|
|
||||||
err = io.ErrUnexpectedEOF
|
|
||||||
}
|
|
||||||
}
|
|
||||||
dec.err = err
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
|
|
||||||
n := scanp - dec.scanp
|
|
||||||
err = dec.refill()
|
|
||||||
scanp = dec.scanp + n
|
|
||||||
}
|
|
||||||
return scanp - dec.scanp, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (dec *Decoder) refill() error {
|
|
||||||
// Make room to read more into the buffer.
|
|
||||||
// First slide down data already consumed.
|
|
||||||
if dec.scanp > 0 {
|
|
||||||
dec.scanned += int64(dec.scanp)
|
|
||||||
n := copy(dec.buf, dec.buf[dec.scanp:])
|
|
||||||
dec.buf = dec.buf[:n]
|
|
||||||
dec.scanp = 0
|
|
||||||
}
|
|
||||||
|
|
||||||
// Grow buffer if not large enough.
|
|
||||||
const minRead = 512
|
|
||||||
if cap(dec.buf)-len(dec.buf) < minRead {
|
|
||||||
newBuf := make([]byte, len(dec.buf), 2*cap(dec.buf)+minRead)
|
|
||||||
copy(newBuf, dec.buf)
|
|
||||||
dec.buf = newBuf
|
|
||||||
}
|
|
||||||
|
|
||||||
// Read. Delay error for next iteration (after scan).
|
|
||||||
n, err := dec.r.Read(dec.buf[len(dec.buf):cap(dec.buf)])
|
|
||||||
dec.buf = dec.buf[0 : len(dec.buf)+n]
|
|
||||||
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func nonSpace(b []byte) bool {
|
|
||||||
for _, c := range b {
|
|
||||||
if !isSpace(c) {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// An Encoder writes JSON values to an output stream.
|
|
||||||
type Encoder struct {
|
|
||||||
w io.Writer
|
|
||||||
err error
|
|
||||||
escapeHTML bool
|
|
||||||
|
|
||||||
indentBuf []byte
|
|
||||||
indentPrefix string
|
|
||||||
indentValue string
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewEncoder returns a new encoder that writes to w.
|
|
||||||
func NewEncoder(w io.Writer) *Encoder {
|
|
||||||
return &Encoder{w: w, escapeHTML: true}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Encode writes the JSON encoding of v to the stream,
|
|
||||||
// with insignificant space characters elided,
|
|
||||||
// followed by a newline character.
|
|
||||||
//
|
|
||||||
// See the documentation for [Marshal] for details about the
|
|
||||||
// conversion of Go values to JSON.
|
|
||||||
func (enc *Encoder) Encode(v any) error {
|
|
||||||
if enc.err != nil {
|
|
||||||
return enc.err
|
|
||||||
}
|
|
||||||
|
|
||||||
e := newEncodeState()
|
|
||||||
defer encodeStatePool.Put(e)
|
|
||||||
|
|
||||||
err := e.marshal(v, encOpts{escapeHTML: enc.escapeHTML})
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// Terminate each value with a newline.
|
|
||||||
// This makes the output look a little nicer
|
|
||||||
// when debugging, and some kind of space
|
|
||||||
// is required if the encoded value was a number,
|
|
||||||
// so that the reader knows there aren't more
|
|
||||||
// digits coming.
|
|
||||||
e.WriteByte('\n')
|
|
||||||
|
|
||||||
b := e.Bytes()
|
|
||||||
if enc.indentPrefix != "" || enc.indentValue != "" {
|
|
||||||
enc.indentBuf, err = appendIndent(enc.indentBuf[:0], b, enc.indentPrefix, enc.indentValue)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
b = enc.indentBuf
|
|
||||||
}
|
|
||||||
if _, err = enc.w.Write(b); err != nil {
|
|
||||||
enc.err = err
|
|
||||||
}
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetIndent instructs the encoder to format each subsequent encoded
|
|
||||||
// value as if indented by the package-level function Indent(dst, src, prefix, indent).
|
|
||||||
// Calling SetIndent("", "") disables indentation.
|
|
||||||
func (enc *Encoder) SetIndent(prefix, indent string) {
|
|
||||||
enc.indentPrefix = prefix
|
|
||||||
enc.indentValue = indent
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetEscapeHTML specifies whether problematic HTML characters
|
|
||||||
// should be escaped inside JSON quoted strings.
|
|
||||||
// The default behavior is to escape &, <, and > to \u0026, \u003c, and \u003e
|
|
||||||
// to avoid certain safety problems that can arise when embedding JSON in HTML.
|
|
||||||
//
|
|
||||||
// In non-HTML settings where the escaping interferes with the readability
|
|
||||||
// of the output, SetEscapeHTML(false) disables this behavior.
|
|
||||||
func (enc *Encoder) SetEscapeHTML(on bool) {
|
|
||||||
enc.escapeHTML = on
|
|
||||||
}
|
|
||||||
|
|
||||||
// RawMessage is a raw encoded JSON value.
|
|
||||||
// It implements [Marshaler] and [Unmarshaler] and can
|
|
||||||
// be used to delay JSON decoding or precompute a JSON encoding.
|
|
||||||
type RawMessage []byte
|
|
||||||
|
|
||||||
// MarshalJSON returns m as the JSON encoding of m.
|
|
||||||
func (m RawMessage) MarshalJSON() ([]byte, error) {
|
|
||||||
if m == nil {
|
|
||||||
return []byte("null"), nil
|
|
||||||
}
|
|
||||||
return m, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// UnmarshalJSON sets *m to a copy of data.
|
|
||||||
func (m *RawMessage) UnmarshalJSON(data []byte) error {
|
|
||||||
if m == nil {
|
|
||||||
return errors.New("json.RawMessage: UnmarshalJSON on nil pointer")
|
|
||||||
}
|
|
||||||
*m = append((*m)[0:0], data...)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var _ Marshaler = (*RawMessage)(nil)
|
|
||||||
var _ Unmarshaler = (*RawMessage)(nil)
|
|
||||||
|
|
||||||
// A Token holds a value of one of these types:
|
|
||||||
//
|
|
||||||
// - [Delim], for the four JSON delimiters [ ] { }
|
|
||||||
// - bool, for JSON booleans
|
|
||||||
// - float64, for JSON numbers
|
|
||||||
// - [Number], for JSON numbers
|
|
||||||
// - string, for JSON string literals
|
|
||||||
// - nil, for JSON null
|
|
||||||
type Token any
|
|
||||||
|
|
||||||
const (
|
|
||||||
tokenTopValue = iota
|
|
||||||
tokenArrayStart
|
|
||||||
tokenArrayValue
|
|
||||||
tokenArrayComma
|
|
||||||
tokenObjectStart
|
|
||||||
tokenObjectKey
|
|
||||||
tokenObjectColon
|
|
||||||
tokenObjectValue
|
|
||||||
tokenObjectComma
|
|
||||||
)
|
|
||||||
|
|
||||||
// advance tokenstate from a separator state to a value state
|
|
||||||
func (dec *Decoder) tokenPrepareForDecode() error {
|
|
||||||
// Note: Not calling peek before switch, to avoid
|
|
||||||
// putting peek into the standard Decode path.
|
|
||||||
// peek is only called when using the Token API.
|
|
||||||
switch dec.tokenState {
|
|
||||||
case tokenArrayComma:
|
|
||||||
c, err := dec.peek()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if c != ',' {
|
|
||||||
return &SyntaxError{"expected comma after array element", dec.InputOffset()}
|
|
||||||
}
|
|
||||||
dec.scanp++
|
|
||||||
dec.tokenState = tokenArrayValue
|
|
||||||
case tokenObjectColon:
|
|
||||||
c, err := dec.peek()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if c != ':' {
|
|
||||||
return &SyntaxError{"expected colon after object key", dec.InputOffset()}
|
|
||||||
}
|
|
||||||
dec.scanp++
|
|
||||||
dec.tokenState = tokenObjectValue
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (dec *Decoder) tokenValueAllowed() bool {
|
|
||||||
switch dec.tokenState {
|
|
||||||
case tokenTopValue, tokenArrayStart, tokenArrayValue, tokenObjectValue:
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func (dec *Decoder) tokenValueEnd() {
|
|
||||||
switch dec.tokenState {
|
|
||||||
case tokenArrayStart, tokenArrayValue:
|
|
||||||
dec.tokenState = tokenArrayComma
|
|
||||||
case tokenObjectValue:
|
|
||||||
dec.tokenState = tokenObjectComma
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// A Delim is a JSON array or object delimiter, one of [ ] { or }.
|
|
||||||
type Delim rune
|
|
||||||
|
|
||||||
func (d Delim) String() string {
|
|
||||||
return string(d)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Token returns the next JSON token in the input stream.
|
|
||||||
// At the end of the input stream, Token returns nil, [io.EOF].
|
|
||||||
//
|
|
||||||
// Token guarantees that the delimiters [ ] { } it returns are
|
|
||||||
// properly nested and matched: if Token encounters an unexpected
|
|
||||||
// delimiter in the input, it will return an error.
|
|
||||||
//
|
|
||||||
// The input stream consists of basic JSON values—bool, string,
|
|
||||||
// number, and null—along with delimiters [ ] { } of type [Delim]
|
|
||||||
// to mark the start and end of arrays and objects.
|
|
||||||
// Commas and colons are elided.
|
|
||||||
func (dec *Decoder) Token() (Token, error) {
|
|
||||||
for {
|
|
||||||
c, err := dec.peek()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
switch c {
|
|
||||||
case '[':
|
|
||||||
if !dec.tokenValueAllowed() {
|
|
||||||
return dec.tokenError(c)
|
|
||||||
}
|
|
||||||
dec.scanp++
|
|
||||||
dec.tokenStack = append(dec.tokenStack, dec.tokenState)
|
|
||||||
dec.tokenState = tokenArrayStart
|
|
||||||
return Delim('['), nil
|
|
||||||
|
|
||||||
case ']':
|
|
||||||
if dec.tokenState != tokenArrayStart && dec.tokenState != tokenArrayComma {
|
|
||||||
return dec.tokenError(c)
|
|
||||||
}
|
|
||||||
dec.scanp++
|
|
||||||
dec.tokenState = dec.tokenStack[len(dec.tokenStack)-1]
|
|
||||||
dec.tokenStack = dec.tokenStack[:len(dec.tokenStack)-1]
|
|
||||||
dec.tokenValueEnd()
|
|
||||||
return Delim(']'), nil
|
|
||||||
|
|
||||||
case '{':
|
|
||||||
if !dec.tokenValueAllowed() {
|
|
||||||
return dec.tokenError(c)
|
|
||||||
}
|
|
||||||
dec.scanp++
|
|
||||||
dec.tokenStack = append(dec.tokenStack, dec.tokenState)
|
|
||||||
dec.tokenState = tokenObjectStart
|
|
||||||
return Delim('{'), nil
|
|
||||||
|
|
||||||
case '}':
|
|
||||||
if dec.tokenState != tokenObjectStart && dec.tokenState != tokenObjectComma {
|
|
||||||
return dec.tokenError(c)
|
|
||||||
}
|
|
||||||
dec.scanp++
|
|
||||||
dec.tokenState = dec.tokenStack[len(dec.tokenStack)-1]
|
|
||||||
dec.tokenStack = dec.tokenStack[:len(dec.tokenStack)-1]
|
|
||||||
dec.tokenValueEnd()
|
|
||||||
return Delim('}'), nil
|
|
||||||
|
|
||||||
case ':':
|
|
||||||
if dec.tokenState != tokenObjectColon {
|
|
||||||
return dec.tokenError(c)
|
|
||||||
}
|
|
||||||
dec.scanp++
|
|
||||||
dec.tokenState = tokenObjectValue
|
|
||||||
continue
|
|
||||||
|
|
||||||
case ',':
|
|
||||||
if dec.tokenState == tokenArrayComma {
|
|
||||||
dec.scanp++
|
|
||||||
dec.tokenState = tokenArrayValue
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if dec.tokenState == tokenObjectComma {
|
|
||||||
dec.scanp++
|
|
||||||
dec.tokenState = tokenObjectKey
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
return dec.tokenError(c)
|
|
||||||
|
|
||||||
case '"':
|
|
||||||
if dec.tokenState == tokenObjectStart || dec.tokenState == tokenObjectKey {
|
|
||||||
var x string
|
|
||||||
old := dec.tokenState
|
|
||||||
dec.tokenState = tokenTopValue
|
|
||||||
err := dec.Decode(&x)
|
|
||||||
dec.tokenState = old
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
dec.tokenState = tokenObjectColon
|
|
||||||
return x, nil
|
|
||||||
}
|
|
||||||
fallthrough
|
|
||||||
|
|
||||||
default:
|
|
||||||
if !dec.tokenValueAllowed() {
|
|
||||||
return dec.tokenError(c)
|
|
||||||
}
|
|
||||||
var x any
|
|
||||||
if err := dec.Decode(&x); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return x, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (dec *Decoder) tokenError(c byte) (Token, error) {
|
|
||||||
var context string
|
|
||||||
switch dec.tokenState {
|
|
||||||
case tokenTopValue:
|
|
||||||
context = " looking for beginning of value"
|
|
||||||
case tokenArrayStart, tokenArrayValue, tokenObjectValue:
|
|
||||||
context = " looking for beginning of value"
|
|
||||||
case tokenArrayComma:
|
|
||||||
context = " after array element"
|
|
||||||
case tokenObjectKey:
|
|
||||||
context = " looking for beginning of object key string"
|
|
||||||
case tokenObjectColon:
|
|
||||||
context = " after object key"
|
|
||||||
case tokenObjectComma:
|
|
||||||
context = " after object key:value pair"
|
|
||||||
}
|
|
||||||
return nil, &SyntaxError{"invalid character " + quoteChar(c) + context, dec.InputOffset()}
|
|
||||||
}
|
|
||||||
|
|
||||||
// More reports whether there is another element in the
|
|
||||||
// current array or object being parsed.
|
|
||||||
func (dec *Decoder) More() bool {
|
|
||||||
c, err := dec.peek()
|
|
||||||
return err == nil && c != ']' && c != '}'
|
|
||||||
}
|
|
||||||
|
|
||||||
func (dec *Decoder) peek() (byte, error) {
|
|
||||||
var err error
|
|
||||||
for {
|
|
||||||
for i := dec.scanp; i < len(dec.buf); i++ {
|
|
||||||
c := dec.buf[i]
|
|
||||||
if isSpace(c) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
dec.scanp = i
|
|
||||||
return c, nil
|
|
||||||
}
|
|
||||||
// buffer has been scanned, now report any error
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
err = dec.refill()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// InputOffset returns the input stream byte offset of the current decoder position.
|
|
||||||
// The offset gives the location of the end of the most recently returned token
|
|
||||||
// and the beginning of the next token.
|
|
||||||
func (dec *Decoder) InputOffset() int64 {
|
|
||||||
return dec.scanned + int64(dec.scanp)
|
|
||||||
}
|
|
||||||
218
vendor/github.com/openai/openai-go/internal/encoding/json/tables.go
generated
vendored
218
vendor/github.com/openai/openai-go/internal/encoding/json/tables.go
generated
vendored
@@ -1,218 +0,0 @@
|
|||||||
// Copyright 2016 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
|
|
||||||
|
|
||||||
import "unicode/utf8"
|
|
||||||
|
|
||||||
// safeSet holds the value true if the ASCII character with the given array
|
|
||||||
// position can be represented inside a JSON string without any further
|
|
||||||
// escaping.
|
|
||||||
//
|
|
||||||
// All values are true except for the ASCII control characters (0-31), the
|
|
||||||
// double quote ("), and the backslash character ("\").
|
|
||||||
var safeSet = [utf8.RuneSelf]bool{
|
|
||||||
' ': true,
|
|
||||||
'!': true,
|
|
||||||
'"': false,
|
|
||||||
'#': true,
|
|
||||||
'$': true,
|
|
||||||
'%': true,
|
|
||||||
'&': true,
|
|
||||||
'\'': true,
|
|
||||||
'(': true,
|
|
||||||
')': true,
|
|
||||||
'*': true,
|
|
||||||
'+': true,
|
|
||||||
',': true,
|
|
||||||
'-': true,
|
|
||||||
'.': true,
|
|
||||||
'/': true,
|
|
||||||
'0': true,
|
|
||||||
'1': true,
|
|
||||||
'2': true,
|
|
||||||
'3': true,
|
|
||||||
'4': true,
|
|
||||||
'5': true,
|
|
||||||
'6': true,
|
|
||||||
'7': true,
|
|
||||||
'8': true,
|
|
||||||
'9': true,
|
|
||||||
':': true,
|
|
||||||
';': true,
|
|
||||||
'<': true,
|
|
||||||
'=': true,
|
|
||||||
'>': true,
|
|
||||||
'?': true,
|
|
||||||
'@': true,
|
|
||||||
'A': true,
|
|
||||||
'B': true,
|
|
||||||
'C': true,
|
|
||||||
'D': true,
|
|
||||||
'E': true,
|
|
||||||
'F': true,
|
|
||||||
'G': true,
|
|
||||||
'H': true,
|
|
||||||
'I': true,
|
|
||||||
'J': true,
|
|
||||||
'K': true,
|
|
||||||
'L': true,
|
|
||||||
'M': true,
|
|
||||||
'N': true,
|
|
||||||
'O': true,
|
|
||||||
'P': true,
|
|
||||||
'Q': true,
|
|
||||||
'R': true,
|
|
||||||
'S': true,
|
|
||||||
'T': true,
|
|
||||||
'U': true,
|
|
||||||
'V': true,
|
|
||||||
'W': true,
|
|
||||||
'X': true,
|
|
||||||
'Y': true,
|
|
||||||
'Z': true,
|
|
||||||
'[': true,
|
|
||||||
'\\': false,
|
|
||||||
']': true,
|
|
||||||
'^': true,
|
|
||||||
'_': true,
|
|
||||||
'`': true,
|
|
||||||
'a': true,
|
|
||||||
'b': true,
|
|
||||||
'c': true,
|
|
||||||
'd': true,
|
|
||||||
'e': true,
|
|
||||||
'f': true,
|
|
||||||
'g': true,
|
|
||||||
'h': true,
|
|
||||||
'i': true,
|
|
||||||
'j': true,
|
|
||||||
'k': true,
|
|
||||||
'l': true,
|
|
||||||
'm': true,
|
|
||||||
'n': true,
|
|
||||||
'o': true,
|
|
||||||
'p': true,
|
|
||||||
'q': true,
|
|
||||||
'r': true,
|
|
||||||
's': true,
|
|
||||||
't': true,
|
|
||||||
'u': true,
|
|
||||||
'v': true,
|
|
||||||
'w': true,
|
|
||||||
'x': true,
|
|
||||||
'y': true,
|
|
||||||
'z': true,
|
|
||||||
'{': true,
|
|
||||||
'|': true,
|
|
||||||
'}': true,
|
|
||||||
'~': true,
|
|
||||||
'\u007f': true,
|
|
||||||
}
|
|
||||||
|
|
||||||
// htmlSafeSet holds the value true if the ASCII character with the given
|
|
||||||
// array position can be safely represented inside a JSON string, embedded
|
|
||||||
// inside of HTML <script> tags, without any additional escaping.
|
|
||||||
//
|
|
||||||
// All values are true except for the ASCII control characters (0-31), the
|
|
||||||
// double quote ("), the backslash character ("\"), HTML opening and closing
|
|
||||||
// tags ("<" and ">"), and the ampersand ("&").
|
|
||||||
var htmlSafeSet = [utf8.RuneSelf]bool{
|
|
||||||
' ': true,
|
|
||||||
'!': true,
|
|
||||||
'"': false,
|
|
||||||
'#': true,
|
|
||||||
'$': true,
|
|
||||||
'%': true,
|
|
||||||
'&': false,
|
|
||||||
'\'': true,
|
|
||||||
'(': true,
|
|
||||||
')': true,
|
|
||||||
'*': true,
|
|
||||||
'+': true,
|
|
||||||
',': true,
|
|
||||||
'-': true,
|
|
||||||
'.': true,
|
|
||||||
'/': true,
|
|
||||||
'0': true,
|
|
||||||
'1': true,
|
|
||||||
'2': true,
|
|
||||||
'3': true,
|
|
||||||
'4': true,
|
|
||||||
'5': true,
|
|
||||||
'6': true,
|
|
||||||
'7': true,
|
|
||||||
'8': true,
|
|
||||||
'9': true,
|
|
||||||
':': true,
|
|
||||||
';': true,
|
|
||||||
'<': false,
|
|
||||||
'=': true,
|
|
||||||
'>': false,
|
|
||||||
'?': true,
|
|
||||||
'@': true,
|
|
||||||
'A': true,
|
|
||||||
'B': true,
|
|
||||||
'C': true,
|
|
||||||
'D': true,
|
|
||||||
'E': true,
|
|
||||||
'F': true,
|
|
||||||
'G': true,
|
|
||||||
'H': true,
|
|
||||||
'I': true,
|
|
||||||
'J': true,
|
|
||||||
'K': true,
|
|
||||||
'L': true,
|
|
||||||
'M': true,
|
|
||||||
'N': true,
|
|
||||||
'O': true,
|
|
||||||
'P': true,
|
|
||||||
'Q': true,
|
|
||||||
'R': true,
|
|
||||||
'S': true,
|
|
||||||
'T': true,
|
|
||||||
'U': true,
|
|
||||||
'V': true,
|
|
||||||
'W': true,
|
|
||||||
'X': true,
|
|
||||||
'Y': true,
|
|
||||||
'Z': true,
|
|
||||||
'[': true,
|
|
||||||
'\\': false,
|
|
||||||
']': true,
|
|
||||||
'^': true,
|
|
||||||
'_': true,
|
|
||||||
'`': true,
|
|
||||||
'a': true,
|
|
||||||
'b': true,
|
|
||||||
'c': true,
|
|
||||||
'd': true,
|
|
||||||
'e': true,
|
|
||||||
'f': true,
|
|
||||||
'g': true,
|
|
||||||
'h': true,
|
|
||||||
'i': true,
|
|
||||||
'j': true,
|
|
||||||
'k': true,
|
|
||||||
'l': true,
|
|
||||||
'm': true,
|
|
||||||
'n': true,
|
|
||||||
'o': true,
|
|
||||||
'p': true,
|
|
||||||
'q': true,
|
|
||||||
'r': true,
|
|
||||||
's': true,
|
|
||||||
't': true,
|
|
||||||
'u': true,
|
|
||||||
'v': true,
|
|
||||||
'w': true,
|
|
||||||
'x': true,
|
|
||||||
'y': true,
|
|
||||||
'z': true,
|
|
||||||
'{': true,
|
|
||||||
'|': true,
|
|
||||||
'}': true,
|
|
||||||
'~': true,
|
|
||||||
'\u007f': true,
|
|
||||||
}
|
|
||||||
38
vendor/github.com/openai/openai-go/internal/encoding/json/tags.go
generated
vendored
38
vendor/github.com/openai/openai-go/internal/encoding/json/tags.go
generated
vendored
@@ -1,38 +0,0 @@
|
|||||||
// Copyright 2011 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
|
|
||||||
|
|
||||||
import (
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
// tagOptions is the string following a comma in a struct field's "json"
|
|
||||||
// tag, or the empty string. It does not include the leading comma.
|
|
||||||
type tagOptions string
|
|
||||||
|
|
||||||
// parseTag splits a struct field's json tag into its name and
|
|
||||||
// comma-separated options.
|
|
||||||
func parseTag(tag string) (string, tagOptions) {
|
|
||||||
tag, opt, _ := strings.Cut(tag, ",")
|
|
||||||
return tag, tagOptions(opt)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Contains reports whether a comma-separated list of options
|
|
||||||
// contains a particular substr flag. substr must be surrounded by a
|
|
||||||
// string boundary or commas.
|
|
||||||
func (o tagOptions) Contains(optionName string) bool {
|
|
||||||
if len(o) == 0 {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
s := string(o)
|
|
||||||
for s != "" {
|
|
||||||
var name string
|
|
||||||
name, s, _ = strings.Cut(s, ",")
|
|
||||||
if name == optionName {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
61
vendor/github.com/openai/openai-go/internal/encoding/json/time.go
generated
vendored
61
vendor/github.com/openai/openai-go/internal/encoding/json/time.go
generated
vendored
@@ -1,61 +0,0 @@
|
|||||||
// EDIT(begin): custom time marshaler
|
|
||||||
package json
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/openai/openai-go/internal/encoding/json/shims"
|
|
||||||
"reflect"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
type TimeMarshaler interface {
|
|
||||||
MarshalJSONWithTimeLayout(string) []byte
|
|
||||||
}
|
|
||||||
|
|
||||||
func TimeLayout(fmt string) string {
|
|
||||||
switch fmt {
|
|
||||||
case "", "date-time":
|
|
||||||
return time.RFC3339
|
|
||||||
case "date":
|
|
||||||
return time.DateOnly
|
|
||||||
default:
|
|
||||||
return fmt
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var timeType = shims.TypeFor[time.Time]()
|
|
||||||
|
|
||||||
func newTimeEncoder() encoderFunc {
|
|
||||||
return func(e *encodeState, v reflect.Value, opts encOpts) {
|
|
||||||
t := v.Interface().(time.Time)
|
|
||||||
fmtted := t.Format(TimeLayout(opts.timefmt))
|
|
||||||
stringEncoder(e, reflect.ValueOf(fmtted), opts)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Uses continuation passing style, to add the timefmt option to k
|
|
||||||
func continueWithTimeFmt(timefmt string, k encoderFunc) encoderFunc {
|
|
||||||
return func(e *encodeState, v reflect.Value, opts encOpts) {
|
|
||||||
opts.timefmt = timefmt
|
|
||||||
k(e, v, opts)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func timeMarshalEncoder(e *encodeState, v reflect.Value, opts encOpts) bool {
|
|
||||||
tm, ok := v.Interface().(TimeMarshaler)
|
|
||||||
if !ok {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
b := tm.MarshalJSONWithTimeLayout(opts.timefmt)
|
|
||||||
if b != nil {
|
|
||||||
e.Grow(len(b))
|
|
||||||
out := e.AvailableBuffer()
|
|
||||||
out, _ = appendCompact(out, b, opts.escapeHTML)
|
|
||||||
e.Buffer.Write(out)
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// EDIT(end)
|
|
||||||
30
vendor/github.com/openai/openai-go/internal/paramutil/field.go
generated
vendored
30
vendor/github.com/openai/openai-go/internal/paramutil/field.go
generated
vendored
@@ -1,30 +0,0 @@
|
|||||||
package paramutil
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/openai/openai-go/packages/param"
|
|
||||||
"github.com/openai/openai-go/packages/respjson"
|
|
||||||
)
|
|
||||||
|
|
||||||
func AddrIfPresent[T comparable](v param.Opt[T]) *T {
|
|
||||||
if v.Valid() {
|
|
||||||
return &v.Value
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func ToOpt[T comparable](v T, meta respjson.Field) param.Opt[T] {
|
|
||||||
if meta.Valid() {
|
|
||||||
return param.NewOpt(v)
|
|
||||||
} else if meta.Raw() == respjson.Null {
|
|
||||||
return param.Null[T]()
|
|
||||||
}
|
|
||||||
return param.Opt[T]{}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Checks if the value is not omitted and not null
|
|
||||||
func Valid(v param.ParamStruct) bool {
|
|
||||||
if ovr, ok := v.Overrides(); ok {
|
|
||||||
return ovr != nil
|
|
||||||
}
|
|
||||||
return !param.IsNull(v) && !param.IsOmitted(v)
|
|
||||||
}
|
|
||||||
48
vendor/github.com/openai/openai-go/internal/paramutil/union.go
generated
vendored
48
vendor/github.com/openai/openai-go/internal/paramutil/union.go
generated
vendored
@@ -1,48 +0,0 @@
|
|||||||
package paramutil
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"github.com/openai/openai-go/packages/param"
|
|
||||||
"reflect"
|
|
||||||
)
|
|
||||||
|
|
||||||
var paramUnionType = reflect.TypeOf(param.APIUnion{})
|
|
||||||
|
|
||||||
// VariantFromUnion can be used to extract the present variant from a param union type.
|
|
||||||
// A param union type is a struct with an embedded field of [APIUnion].
|
|
||||||
func VariantFromUnion(u reflect.Value) (any, error) {
|
|
||||||
if u.Kind() == reflect.Ptr {
|
|
||||||
u = u.Elem()
|
|
||||||
}
|
|
||||||
|
|
||||||
if u.Kind() != reflect.Struct {
|
|
||||||
return nil, fmt.Errorf("param: cannot extract variant from non-struct union")
|
|
||||||
}
|
|
||||||
|
|
||||||
isUnion := false
|
|
||||||
nVariants := 0
|
|
||||||
variantIdx := -1
|
|
||||||
for i := 0; i < u.NumField(); i++ {
|
|
||||||
if !u.Field(i).IsZero() {
|
|
||||||
nVariants++
|
|
||||||
variantIdx = i
|
|
||||||
}
|
|
||||||
if u.Field(i).Type() == paramUnionType {
|
|
||||||
isUnion = u.Type().Field(i).Anonymous
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if !isUnion {
|
|
||||||
return nil, fmt.Errorf("param: cannot extract variant from non-union")
|
|
||||||
}
|
|
||||||
|
|
||||||
if nVariants > 1 {
|
|
||||||
return nil, fmt.Errorf("param: cannot extract variant from union with multiple variants")
|
|
||||||
}
|
|
||||||
|
|
||||||
if nVariants == 0 {
|
|
||||||
return nil, fmt.Errorf("param: cannot extract variant from union with no variants")
|
|
||||||
}
|
|
||||||
|
|
||||||
return u.Field(variantIdx).Interface(), nil
|
|
||||||
}
|
|
||||||
635
vendor/github.com/openai/openai-go/internal/requestconfig/requestconfig.go
generated
vendored
635
vendor/github.com/openai/openai-go/internal/requestconfig/requestconfig.go
generated
vendored
@@ -1,635 +0,0 @@
|
|||||||
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
||||||
|
|
||||||
package requestconfig
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"math"
|
|
||||||
"math/rand"
|
|
||||||
"mime"
|
|
||||||
"net/http"
|
|
||||||
"net/url"
|
|
||||||
"runtime"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/openai/openai-go/internal"
|
|
||||||
"github.com/openai/openai-go/internal/apierror"
|
|
||||||
"github.com/openai/openai-go/internal/apiform"
|
|
||||||
"github.com/openai/openai-go/internal/apiquery"
|
|
||||||
"github.com/tidwall/gjson"
|
|
||||||
)
|
|
||||||
|
|
||||||
func getDefaultHeaders() map[string]string {
|
|
||||||
return map[string]string{
|
|
||||||
"User-Agent": fmt.Sprintf("OpenAI/Go %s", internal.PackageVersion),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func getNormalizedOS() string {
|
|
||||||
switch runtime.GOOS {
|
|
||||||
case "ios":
|
|
||||||
return "iOS"
|
|
||||||
case "android":
|
|
||||||
return "Android"
|
|
||||||
case "darwin":
|
|
||||||
return "MacOS"
|
|
||||||
case "window":
|
|
||||||
return "Windows"
|
|
||||||
case "freebsd":
|
|
||||||
return "FreeBSD"
|
|
||||||
case "openbsd":
|
|
||||||
return "OpenBSD"
|
|
||||||
case "linux":
|
|
||||||
return "Linux"
|
|
||||||
default:
|
|
||||||
return fmt.Sprintf("Other:%s", runtime.GOOS)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func getNormalizedArchitecture() string {
|
|
||||||
switch runtime.GOARCH {
|
|
||||||
case "386":
|
|
||||||
return "x32"
|
|
||||||
case "amd64":
|
|
||||||
return "x64"
|
|
||||||
case "arm":
|
|
||||||
return "arm"
|
|
||||||
case "arm64":
|
|
||||||
return "arm64"
|
|
||||||
default:
|
|
||||||
return fmt.Sprintf("other:%s", runtime.GOARCH)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func getPlatformProperties() map[string]string {
|
|
||||||
return map[string]string{
|
|
||||||
"X-Stainless-Lang": "go",
|
|
||||||
"X-Stainless-Package-Version": internal.PackageVersion,
|
|
||||||
"X-Stainless-OS": getNormalizedOS(),
|
|
||||||
"X-Stainless-Arch": getNormalizedArchitecture(),
|
|
||||||
"X-Stainless-Runtime": "go",
|
|
||||||
"X-Stainless-Runtime-Version": runtime.Version(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type RequestOption interface {
|
|
||||||
Apply(*RequestConfig) error
|
|
||||||
}
|
|
||||||
|
|
||||||
type RequestOptionFunc func(*RequestConfig) error
|
|
||||||
type PreRequestOptionFunc func(*RequestConfig) error
|
|
||||||
|
|
||||||
func (s RequestOptionFunc) Apply(r *RequestConfig) error { return s(r) }
|
|
||||||
func (s PreRequestOptionFunc) Apply(r *RequestConfig) error { return s(r) }
|
|
||||||
|
|
||||||
func NewRequestConfig(ctx context.Context, method string, u string, body any, dst any, opts ...RequestOption) (*RequestConfig, error) {
|
|
||||||
var reader io.Reader
|
|
||||||
|
|
||||||
contentType := "application/json"
|
|
||||||
hasSerializationFunc := false
|
|
||||||
|
|
||||||
if body, ok := body.(json.Marshaler); ok {
|
|
||||||
content, err := body.MarshalJSON()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
reader = bytes.NewBuffer(content)
|
|
||||||
hasSerializationFunc = true
|
|
||||||
}
|
|
||||||
if body, ok := body.(apiform.Marshaler); ok {
|
|
||||||
var (
|
|
||||||
content []byte
|
|
||||||
err error
|
|
||||||
)
|
|
||||||
content, contentType, err = body.MarshalMultipart()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
reader = bytes.NewBuffer(content)
|
|
||||||
hasSerializationFunc = true
|
|
||||||
}
|
|
||||||
if body, ok := body.(apiquery.Queryer); ok {
|
|
||||||
hasSerializationFunc = true
|
|
||||||
q, err := body.URLQuery()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
params := q.Encode()
|
|
||||||
if params != "" {
|
|
||||||
u = u + "?" + params
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if body, ok := body.([]byte); ok {
|
|
||||||
reader = bytes.NewBuffer(body)
|
|
||||||
hasSerializationFunc = true
|
|
||||||
}
|
|
||||||
if body, ok := body.(io.Reader); ok {
|
|
||||||
reader = body
|
|
||||||
hasSerializationFunc = true
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fallback to json serialization if none of the serialization functions that we expect
|
|
||||||
// to see is present.
|
|
||||||
if body != nil && !hasSerializationFunc {
|
|
||||||
content, err := json.Marshal(body)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
reader = bytes.NewBuffer(content)
|
|
||||||
}
|
|
||||||
|
|
||||||
req, err := http.NewRequestWithContext(ctx, method, u, nil)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if reader != nil {
|
|
||||||
req.Header.Set("Content-Type", contentType)
|
|
||||||
}
|
|
||||||
|
|
||||||
req.Header.Set("Accept", "application/json")
|
|
||||||
req.Header.Set("X-Stainless-Retry-Count", "0")
|
|
||||||
req.Header.Set("X-Stainless-Timeout", "0")
|
|
||||||
for k, v := range getDefaultHeaders() {
|
|
||||||
req.Header.Add(k, v)
|
|
||||||
}
|
|
||||||
|
|
||||||
for k, v := range getPlatformProperties() {
|
|
||||||
req.Header.Add(k, v)
|
|
||||||
}
|
|
||||||
cfg := RequestConfig{
|
|
||||||
MaxRetries: 2,
|
|
||||||
Context: ctx,
|
|
||||||
Request: req,
|
|
||||||
HTTPClient: http.DefaultClient,
|
|
||||||
Body: reader,
|
|
||||||
}
|
|
||||||
cfg.ResponseBodyInto = dst
|
|
||||||
err = cfg.Apply(opts...)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// This must run after `cfg.Apply(...)` above in case the request timeout gets modified. We also only
|
|
||||||
// apply our own logic for it if it's still "0" from above. If it's not, then it was deleted or modified
|
|
||||||
// by the user and we should respect that.
|
|
||||||
if req.Header.Get("X-Stainless-Timeout") == "0" {
|
|
||||||
if cfg.RequestTimeout == time.Duration(0) {
|
|
||||||
req.Header.Del("X-Stainless-Timeout")
|
|
||||||
} else {
|
|
||||||
req.Header.Set("X-Stainless-Timeout", strconv.Itoa(int(cfg.RequestTimeout.Seconds())))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return &cfg, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// This interface is primarily used to describe an [*http.Client], but also
|
|
||||||
// supports custom HTTP implementations.
|
|
||||||
type HTTPDoer interface {
|
|
||||||
Do(req *http.Request) (*http.Response, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
// RequestConfig represents all the state related to one request.
|
|
||||||
//
|
|
||||||
// Editing the variables inside RequestConfig directly is unstable api. Prefer
|
|
||||||
// composing the RequestOption instead if possible.
|
|
||||||
type RequestConfig struct {
|
|
||||||
MaxRetries int
|
|
||||||
RequestTimeout time.Duration
|
|
||||||
Context context.Context
|
|
||||||
Request *http.Request
|
|
||||||
BaseURL *url.URL
|
|
||||||
// DefaultBaseURL will be used if BaseURL is not explicitly overridden using
|
|
||||||
// WithBaseURL.
|
|
||||||
DefaultBaseURL *url.URL
|
|
||||||
CustomHTTPDoer HTTPDoer
|
|
||||||
HTTPClient *http.Client
|
|
||||||
Middlewares []middleware
|
|
||||||
APIKey string
|
|
||||||
Organization string
|
|
||||||
Project string
|
|
||||||
WebhookSecret string
|
|
||||||
// If ResponseBodyInto not nil, then we will attempt to deserialize into
|
|
||||||
// ResponseBodyInto. If Destination is a []byte, then it will return the body as
|
|
||||||
// is.
|
|
||||||
ResponseBodyInto any
|
|
||||||
// ResponseInto copies the \*http.Response of the corresponding request into the
|
|
||||||
// given address
|
|
||||||
ResponseInto **http.Response
|
|
||||||
Body io.Reader
|
|
||||||
}
|
|
||||||
|
|
||||||
// middleware is exactly the same type as the Middleware type found in the [option] package,
|
|
||||||
// but it is redeclared here for circular dependency issues.
|
|
||||||
type middleware = func(*http.Request, middlewareNext) (*http.Response, error)
|
|
||||||
|
|
||||||
// middlewareNext is exactly the same type as the MiddlewareNext type found in the [option] package,
|
|
||||||
// but it is redeclared here for circular dependency issues.
|
|
||||||
type middlewareNext = func(*http.Request) (*http.Response, error)
|
|
||||||
|
|
||||||
func applyMiddleware(middleware middleware, next middlewareNext) middlewareNext {
|
|
||||||
return func(req *http.Request) (res *http.Response, err error) {
|
|
||||||
return middleware(req, next)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func shouldRetry(req *http.Request, res *http.Response) bool {
|
|
||||||
// If there is no way to recover the Body, then we shouldn't retry.
|
|
||||||
if req.Body != nil && req.GetBody == nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// If there is no response, that indicates that there is a connection error
|
|
||||||
// so we retry the request.
|
|
||||||
if res == nil {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
// If the header explicitly wants a retry behavior, respect that over the
|
|
||||||
// http status code.
|
|
||||||
if res.Header.Get("x-should-retry") == "true" {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
if res.Header.Get("x-should-retry") == "false" {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
return res.StatusCode == http.StatusRequestTimeout ||
|
|
||||||
res.StatusCode == http.StatusConflict ||
|
|
||||||
res.StatusCode == http.StatusTooManyRequests ||
|
|
||||||
res.StatusCode >= http.StatusInternalServerError
|
|
||||||
}
|
|
||||||
|
|
||||||
func parseRetryAfterHeader(resp *http.Response) (time.Duration, bool) {
|
|
||||||
if resp == nil {
|
|
||||||
return 0, false
|
|
||||||
}
|
|
||||||
|
|
||||||
type retryData struct {
|
|
||||||
header string
|
|
||||||
units time.Duration
|
|
||||||
|
|
||||||
// custom is used when the regular algorithm failed and is optional.
|
|
||||||
// the returned duration is used verbatim (units is not applied).
|
|
||||||
custom func(string) (time.Duration, bool)
|
|
||||||
}
|
|
||||||
|
|
||||||
nop := func(string) (time.Duration, bool) { return 0, false }
|
|
||||||
|
|
||||||
// the headers are listed in order of preference
|
|
||||||
retries := []retryData{
|
|
||||||
{
|
|
||||||
header: "Retry-After-Ms",
|
|
||||||
units: time.Millisecond,
|
|
||||||
custom: nop,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
header: "Retry-After",
|
|
||||||
units: time.Second,
|
|
||||||
|
|
||||||
// retry-after values are expressed in either number of
|
|
||||||
// seconds or an HTTP-date indicating when to try again
|
|
||||||
custom: func(ra string) (time.Duration, bool) {
|
|
||||||
t, err := time.Parse(time.RFC1123, ra)
|
|
||||||
if err != nil {
|
|
||||||
return 0, false
|
|
||||||
}
|
|
||||||
return time.Until(t), true
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, retry := range retries {
|
|
||||||
v := resp.Header.Get(retry.header)
|
|
||||||
if v == "" {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if retryAfter, err := strconv.ParseFloat(v, 64); err == nil {
|
|
||||||
return time.Duration(retryAfter * float64(retry.units)), true
|
|
||||||
}
|
|
||||||
if d, ok := retry.custom(v); ok {
|
|
||||||
return d, true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return 0, false
|
|
||||||
}
|
|
||||||
|
|
||||||
// isBeforeContextDeadline reports whether the non-zero Time t is
|
|
||||||
// before ctx's deadline. If ctx does not have a deadline, it
|
|
||||||
// always reports true (the deadline is considered infinite).
|
|
||||||
func isBeforeContextDeadline(t time.Time, ctx context.Context) bool {
|
|
||||||
d, ok := ctx.Deadline()
|
|
||||||
if !ok {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
return t.Before(d)
|
|
||||||
}
|
|
||||||
|
|
||||||
// bodyWithTimeout is an io.ReadCloser which can observe a context's cancel func
|
|
||||||
// to handle timeouts etc. It wraps an existing io.ReadCloser.
|
|
||||||
type bodyWithTimeout struct {
|
|
||||||
stop func() // stops the time.Timer waiting to cancel the request
|
|
||||||
rc io.ReadCloser
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *bodyWithTimeout) Read(p []byte) (n int, err error) {
|
|
||||||
n, err = b.rc.Read(p)
|
|
||||||
if err == nil {
|
|
||||||
return n, nil
|
|
||||||
}
|
|
||||||
if err == io.EOF {
|
|
||||||
return n, err
|
|
||||||
}
|
|
||||||
return n, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *bodyWithTimeout) Close() error {
|
|
||||||
err := b.rc.Close()
|
|
||||||
b.stop()
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func retryDelay(res *http.Response, retryCount int) time.Duration {
|
|
||||||
// If the API asks us to wait a certain amount of time (and it's a reasonable amount),
|
|
||||||
// just do what it says.
|
|
||||||
|
|
||||||
if retryAfterDelay, ok := parseRetryAfterHeader(res); ok && 0 <= retryAfterDelay && retryAfterDelay < time.Minute {
|
|
||||||
return retryAfterDelay
|
|
||||||
}
|
|
||||||
|
|
||||||
maxDelay := 8 * time.Second
|
|
||||||
delay := time.Duration(0.5 * float64(time.Second) * math.Pow(2, float64(retryCount)))
|
|
||||||
if delay > maxDelay {
|
|
||||||
delay = maxDelay
|
|
||||||
}
|
|
||||||
|
|
||||||
jitter := rand.Int63n(int64(delay / 4))
|
|
||||||
delay -= time.Duration(jitter)
|
|
||||||
return delay
|
|
||||||
}
|
|
||||||
|
|
||||||
func (cfg *RequestConfig) Execute() (err error) {
|
|
||||||
if cfg.BaseURL == nil {
|
|
||||||
if cfg.DefaultBaseURL != nil {
|
|
||||||
cfg.BaseURL = cfg.DefaultBaseURL
|
|
||||||
} else {
|
|
||||||
return fmt.Errorf("requestconfig: base url is not set")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
cfg.Request.URL, err = cfg.BaseURL.Parse(strings.TrimLeft(cfg.Request.URL.String(), "/"))
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
if cfg.Body != nil && cfg.Request.Body == nil {
|
|
||||||
switch body := cfg.Body.(type) {
|
|
||||||
case *bytes.Buffer:
|
|
||||||
b := body.Bytes()
|
|
||||||
cfg.Request.ContentLength = int64(body.Len())
|
|
||||||
cfg.Request.GetBody = func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(b)), nil }
|
|
||||||
cfg.Request.Body, _ = cfg.Request.GetBody()
|
|
||||||
case *bytes.Reader:
|
|
||||||
cfg.Request.ContentLength = int64(body.Len())
|
|
||||||
cfg.Request.GetBody = func() (io.ReadCloser, error) {
|
|
||||||
_, err := body.Seek(0, 0)
|
|
||||||
return io.NopCloser(body), err
|
|
||||||
}
|
|
||||||
cfg.Request.Body, _ = cfg.Request.GetBody()
|
|
||||||
default:
|
|
||||||
if rc, ok := body.(io.ReadCloser); ok {
|
|
||||||
cfg.Request.Body = rc
|
|
||||||
} else {
|
|
||||||
cfg.Request.Body = io.NopCloser(body)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
handler := cfg.HTTPClient.Do
|
|
||||||
if cfg.CustomHTTPDoer != nil {
|
|
||||||
handler = cfg.CustomHTTPDoer.Do
|
|
||||||
}
|
|
||||||
for i := len(cfg.Middlewares) - 1; i >= 0; i -= 1 {
|
|
||||||
handler = applyMiddleware(cfg.Middlewares[i], handler)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Don't send the current retry count in the headers if the caller modified the header defaults.
|
|
||||||
shouldSendRetryCount := cfg.Request.Header.Get("X-Stainless-Retry-Count") == "0"
|
|
||||||
|
|
||||||
var res *http.Response
|
|
||||||
var cancel context.CancelFunc
|
|
||||||
for retryCount := 0; retryCount <= cfg.MaxRetries; retryCount += 1 {
|
|
||||||
ctx := cfg.Request.Context()
|
|
||||||
if cfg.RequestTimeout != time.Duration(0) && isBeforeContextDeadline(time.Now().Add(cfg.RequestTimeout), ctx) {
|
|
||||||
ctx, cancel = context.WithTimeout(ctx, cfg.RequestTimeout)
|
|
||||||
defer func() {
|
|
||||||
// The cancel function is nil if it was handed off to be handled in a different scope.
|
|
||||||
if cancel != nil {
|
|
||||||
cancel()
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
req := cfg.Request.Clone(ctx)
|
|
||||||
if shouldSendRetryCount {
|
|
||||||
req.Header.Set("X-Stainless-Retry-Count", strconv.Itoa(retryCount))
|
|
||||||
}
|
|
||||||
|
|
||||||
res, err = handler(req)
|
|
||||||
if ctx != nil && ctx.Err() != nil {
|
|
||||||
return ctx.Err()
|
|
||||||
}
|
|
||||||
if !shouldRetry(cfg.Request, res) || retryCount >= cfg.MaxRetries {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
// Prepare next request and wait for the retry delay
|
|
||||||
if cfg.Request.GetBody != nil {
|
|
||||||
cfg.Request.Body, err = cfg.Request.GetBody()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Can't actually refresh the body, so we don't attempt to retry here
|
|
||||||
if cfg.Request.GetBody == nil && cfg.Request.Body != nil {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
time.Sleep(retryDelay(res, retryCount))
|
|
||||||
}
|
|
||||||
|
|
||||||
// Save *http.Response if it is requested to, even if there was an error making the request. This is
|
|
||||||
// useful in cases where you might want to debug by inspecting the response. Note that if err != nil,
|
|
||||||
// the response should be generally be empty, but there are edge cases.
|
|
||||||
if cfg.ResponseInto != nil {
|
|
||||||
*cfg.ResponseInto = res
|
|
||||||
}
|
|
||||||
if responseBodyInto, ok := cfg.ResponseBodyInto.(**http.Response); ok {
|
|
||||||
*responseBodyInto = res
|
|
||||||
}
|
|
||||||
|
|
||||||
// If there was a connection error in the final request or any other transport error,
|
|
||||||
// return that early without trying to coerce into an APIError.
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
if res.StatusCode >= 400 {
|
|
||||||
contents, err := io.ReadAll(res.Body)
|
|
||||||
res.Body.Close()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// If there is an APIError, re-populate the response body so that debugging
|
|
||||||
// utilities can conveniently dump the response without issue.
|
|
||||||
res.Body = io.NopCloser(bytes.NewBuffer(contents))
|
|
||||||
|
|
||||||
// Load the contents into the error format if it is provided.
|
|
||||||
aerr := apierror.Error{Request: cfg.Request, Response: res, StatusCode: res.StatusCode}
|
|
||||||
unwrapped := gjson.GetBytes(contents, "error").Raw
|
|
||||||
err = aerr.UnmarshalJSON([]byte(unwrapped))
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return &aerr
|
|
||||||
}
|
|
||||||
|
|
||||||
_, intoCustomResponseBody := cfg.ResponseBodyInto.(**http.Response)
|
|
||||||
if cfg.ResponseBodyInto == nil || intoCustomResponseBody {
|
|
||||||
// We aren't reading the response body in this scope, but whoever is will need the
|
|
||||||
// cancel func from the context to observe request timeouts.
|
|
||||||
// Put the cancel function in the response body so it can be handled elsewhere.
|
|
||||||
if cancel != nil {
|
|
||||||
res.Body = &bodyWithTimeout{rc: res.Body, stop: cancel}
|
|
||||||
cancel = nil
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
contents, err := io.ReadAll(res.Body)
|
|
||||||
res.Body.Close()
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("error reading response body: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// If we are not json, return plaintext
|
|
||||||
contentType := res.Header.Get("content-type")
|
|
||||||
mediaType, _, _ := mime.ParseMediaType(contentType)
|
|
||||||
isJSON := strings.Contains(mediaType, "application/json") || strings.HasSuffix(mediaType, "+json")
|
|
||||||
if !isJSON {
|
|
||||||
switch dst := cfg.ResponseBodyInto.(type) {
|
|
||||||
case *string:
|
|
||||||
*dst = string(contents)
|
|
||||||
case **string:
|
|
||||||
tmp := string(contents)
|
|
||||||
*dst = &tmp
|
|
||||||
case *[]byte:
|
|
||||||
*dst = contents
|
|
||||||
default:
|
|
||||||
return fmt.Errorf("expected destination type of 'string' or '[]byte' for responses with content-type '%s' that is not 'application/json'", contentType)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
switch dst := cfg.ResponseBodyInto.(type) {
|
|
||||||
// If the response happens to be a byte array, deserialize the body as-is.
|
|
||||||
case *[]byte:
|
|
||||||
*dst = contents
|
|
||||||
default:
|
|
||||||
err = json.NewDecoder(bytes.NewReader(contents)).Decode(cfg.ResponseBodyInto)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("error parsing response json: %w", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func ExecuteNewRequest(ctx context.Context, method string, u string, body any, dst any, opts ...RequestOption) error {
|
|
||||||
cfg, err := NewRequestConfig(ctx, method, u, body, dst, opts...)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return cfg.Execute()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (cfg *RequestConfig) Clone(ctx context.Context) *RequestConfig {
|
|
||||||
if cfg == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
req := cfg.Request.Clone(ctx)
|
|
||||||
var err error
|
|
||||||
if req.Body != nil {
|
|
||||||
req.Body, err = req.GetBody()
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
new := &RequestConfig{
|
|
||||||
MaxRetries: cfg.MaxRetries,
|
|
||||||
RequestTimeout: cfg.RequestTimeout,
|
|
||||||
Context: ctx,
|
|
||||||
Request: req,
|
|
||||||
BaseURL: cfg.BaseURL,
|
|
||||||
HTTPClient: cfg.HTTPClient,
|
|
||||||
Middlewares: cfg.Middlewares,
|
|
||||||
APIKey: cfg.APIKey,
|
|
||||||
Organization: cfg.Organization,
|
|
||||||
Project: cfg.Project,
|
|
||||||
WebhookSecret: cfg.WebhookSecret,
|
|
||||||
}
|
|
||||||
|
|
||||||
return new
|
|
||||||
}
|
|
||||||
|
|
||||||
func (cfg *RequestConfig) Apply(opts ...RequestOption) error {
|
|
||||||
for _, opt := range opts {
|
|
||||||
err := opt.Apply(cfg)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// PreRequestOptions is used to collect all the options which need to be known before
|
|
||||||
// a call to [RequestConfig.ExecuteNewRequest], such as path parameters
|
|
||||||
// or global defaults.
|
|
||||||
// PreRequestOptions will return a [RequestConfig] with the options applied.
|
|
||||||
//
|
|
||||||
// Only request option functions of type [PreRequestOptionFunc] are applied.
|
|
||||||
func PreRequestOptions(opts ...RequestOption) (RequestConfig, error) {
|
|
||||||
cfg := RequestConfig{}
|
|
||||||
for _, opt := range opts {
|
|
||||||
if opt, ok := opt.(PreRequestOptionFunc); ok {
|
|
||||||
err := opt.Apply(&cfg)
|
|
||||||
if err != nil {
|
|
||||||
return cfg, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return cfg, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithDefaultBaseURL returns a RequestOption that sets the client's default Base URL.
|
|
||||||
// This is always overridden by setting a base URL with WithBaseURL.
|
|
||||||
// WithBaseURL should be used instead of WithDefaultBaseURL except in internal code.
|
|
||||||
func WithDefaultBaseURL(baseURL string) RequestOption {
|
|
||||||
u, err := url.Parse(baseURL)
|
|
||||||
return RequestOptionFunc(func(r *RequestConfig) error {
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
r.DefaultBaseURL = u
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
}
|
|
||||||
5
vendor/github.com/openai/openai-go/internal/version.go
generated
vendored
5
vendor/github.com/openai/openai-go/internal/version.go
generated
vendored
@@ -1,5 +0,0 @@
|
|||||||
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
||||||
|
|
||||||
package internal
|
|
||||||
|
|
||||||
const PackageVersion = "1.12.0" // x-release-please-version
|
|
||||||
134
vendor/github.com/openai/openai-go/model.go
generated
vendored
134
vendor/github.com/openai/openai-go/model.go
generated
vendored
@@ -1,134 +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/apijson"
|
|
||||||
"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/respjson"
|
|
||||||
"github.com/openai/openai-go/shared/constant"
|
|
||||||
)
|
|
||||||
|
|
||||||
// ModelService 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 [NewModelService] method instead.
|
|
||||||
type ModelService struct {
|
|
||||||
Options []option.RequestOption
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewModelService 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 NewModelService(opts ...option.RequestOption) (r ModelService) {
|
|
||||||
r = ModelService{}
|
|
||||||
r.Options = opts
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Retrieves a model instance, providing basic information about the model such as
|
|
||||||
// the owner and permissioning.
|
|
||||||
func (r *ModelService) Get(ctx context.Context, model string, opts ...option.RequestOption) (res *Model, err error) {
|
|
||||||
opts = append(r.Options[:], opts...)
|
|
||||||
if model == "" {
|
|
||||||
err = errors.New("missing required model parameter")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
path := fmt.Sprintf("models/%s", model)
|
|
||||||
err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Lists the currently available models, and provides basic information about each
|
|
||||||
// one such as the owner and availability.
|
|
||||||
func (r *ModelService) List(ctx context.Context, opts ...option.RequestOption) (res *pagination.Page[Model], err error) {
|
|
||||||
var raw *http.Response
|
|
||||||
opts = append(r.Options[:], opts...)
|
|
||||||
opts = append([]option.RequestOption{option.WithResponseInto(&raw)}, opts...)
|
|
||||||
path := "models"
|
|
||||||
cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, nil, &res, opts...)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
err = cfg.Execute()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
res.SetPageConfig(cfg, raw)
|
|
||||||
return res, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Lists the currently available models, and provides basic information about each
|
|
||||||
// one such as the owner and availability.
|
|
||||||
func (r *ModelService) ListAutoPaging(ctx context.Context, opts ...option.RequestOption) *pagination.PageAutoPager[Model] {
|
|
||||||
return pagination.NewPageAutoPager(r.List(ctx, opts...))
|
|
||||||
}
|
|
||||||
|
|
||||||
// Delete a fine-tuned model. You must have the Owner role in your organization to
|
|
||||||
// delete a model.
|
|
||||||
func (r *ModelService) Delete(ctx context.Context, model string, opts ...option.RequestOption) (res *ModelDeleted, err error) {
|
|
||||||
opts = append(r.Options[:], opts...)
|
|
||||||
if model == "" {
|
|
||||||
err = errors.New("missing required model parameter")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
path := fmt.Sprintf("models/%s", model)
|
|
||||||
err = requestconfig.ExecuteNewRequest(ctx, http.MethodDelete, path, nil, &res, opts...)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Describes an OpenAI model offering that can be used with the API.
|
|
||||||
type Model struct {
|
|
||||||
// The model identifier, which can be referenced in the API endpoints.
|
|
||||||
ID string `json:"id,required"`
|
|
||||||
// The Unix timestamp (in seconds) when the model was created.
|
|
||||||
Created int64 `json:"created,required"`
|
|
||||||
// The object type, which is always "model".
|
|
||||||
Object constant.Model `json:"object,required"`
|
|
||||||
// The organization that owns the model.
|
|
||||||
OwnedBy string `json:"owned_by,required"`
|
|
||||||
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
|
|
||||||
JSON struct {
|
|
||||||
ID respjson.Field
|
|
||||||
Created respjson.Field
|
|
||||||
Object respjson.Field
|
|
||||||
OwnedBy respjson.Field
|
|
||||||
ExtraFields map[string]respjson.Field
|
|
||||||
raw string
|
|
||||||
} `json:"-"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Returns the unmodified JSON received from the API
|
|
||||||
func (r Model) RawJSON() string { return r.JSON.raw }
|
|
||||||
func (r *Model) UnmarshalJSON(data []byte) error {
|
|
||||||
return apijson.UnmarshalRoot(data, r)
|
|
||||||
}
|
|
||||||
|
|
||||||
type ModelDeleted struct {
|
|
||||||
ID string `json:"id,required"`
|
|
||||||
Deleted bool `json:"deleted,required"`
|
|
||||||
Object string `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 ModelDeleted) RawJSON() string { return r.JSON.raw }
|
|
||||||
func (r *ModelDeleted) UnmarshalJSON(data []byte) error {
|
|
||||||
return apijson.UnmarshalRoot(data, r)
|
|
||||||
}
|
|
||||||
485
vendor/github.com/openai/openai-go/moderation.go
generated
vendored
485
vendor/github.com/openai/openai-go/moderation.go
generated
vendored
@@ -1,485 +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"
|
|
||||||
)
|
|
||||||
|
|
||||||
// ModerationService 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 [NewModerationService] method instead.
|
|
||||||
type ModerationService struct {
|
|
||||||
Options []option.RequestOption
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewModerationService 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 NewModerationService(opts ...option.RequestOption) (r ModerationService) {
|
|
||||||
r = ModerationService{}
|
|
||||||
r.Options = opts
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Classifies if text and/or image inputs are potentially harmful. Learn more in
|
|
||||||
// the [moderation guide](https://platform.openai.com/docs/guides/moderation).
|
|
||||||
func (r *ModerationService) New(ctx context.Context, body ModerationNewParams, opts ...option.RequestOption) (res *ModerationNewResponse, err error) {
|
|
||||||
opts = append(r.Options[:], opts...)
|
|
||||||
path := "moderations"
|
|
||||||
err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
type Moderation struct {
|
|
||||||
// A list of the categories, and whether they are flagged or not.
|
|
||||||
Categories ModerationCategories `json:"categories,required"`
|
|
||||||
// A list of the categories along with the input type(s) that the score applies to.
|
|
||||||
CategoryAppliedInputTypes ModerationCategoryAppliedInputTypes `json:"category_applied_input_types,required"`
|
|
||||||
// A list of the categories along with their scores as predicted by model.
|
|
||||||
CategoryScores ModerationCategoryScores `json:"category_scores,required"`
|
|
||||||
// Whether any of the below categories are flagged.
|
|
||||||
Flagged bool `json:"flagged,required"`
|
|
||||||
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
|
|
||||||
JSON struct {
|
|
||||||
Categories respjson.Field
|
|
||||||
CategoryAppliedInputTypes respjson.Field
|
|
||||||
CategoryScores respjson.Field
|
|
||||||
Flagged respjson.Field
|
|
||||||
ExtraFields map[string]respjson.Field
|
|
||||||
raw string
|
|
||||||
} `json:"-"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Returns the unmodified JSON received from the API
|
|
||||||
func (r Moderation) RawJSON() string { return r.JSON.raw }
|
|
||||||
func (r *Moderation) UnmarshalJSON(data []byte) error {
|
|
||||||
return apijson.UnmarshalRoot(data, r)
|
|
||||||
}
|
|
||||||
|
|
||||||
// A list of the categories, and whether they are flagged or not.
|
|
||||||
type ModerationCategories struct {
|
|
||||||
// Content that expresses, incites, or promotes harassing language towards any
|
|
||||||
// target.
|
|
||||||
Harassment bool `json:"harassment,required"`
|
|
||||||
// Harassment content that also includes violence or serious harm towards any
|
|
||||||
// target.
|
|
||||||
HarassmentThreatening bool `json:"harassment/threatening,required"`
|
|
||||||
// Content that expresses, incites, or promotes hate based on race, gender,
|
|
||||||
// ethnicity, religion, nationality, sexual orientation, disability status, or
|
|
||||||
// caste. Hateful content aimed at non-protected groups (e.g., chess players) is
|
|
||||||
// harassment.
|
|
||||||
Hate bool `json:"hate,required"`
|
|
||||||
// Hateful content that also includes violence or serious harm towards the targeted
|
|
||||||
// group based on race, gender, ethnicity, religion, nationality, sexual
|
|
||||||
// orientation, disability status, or caste.
|
|
||||||
HateThreatening bool `json:"hate/threatening,required"`
|
|
||||||
// Content that includes instructions or advice that facilitate the planning or
|
|
||||||
// execution of wrongdoing, or that gives advice or instruction on how to commit
|
|
||||||
// illicit acts. For example, "how to shoplift" would fit this category.
|
|
||||||
Illicit bool `json:"illicit,required"`
|
|
||||||
// Content that includes instructions or advice that facilitate the planning or
|
|
||||||
// execution of wrongdoing that also includes violence, or that gives advice or
|
|
||||||
// instruction on the procurement of any weapon.
|
|
||||||
IllicitViolent bool `json:"illicit/violent,required"`
|
|
||||||
// Content that promotes, encourages, or depicts acts of self-harm, such as
|
|
||||||
// suicide, cutting, and eating disorders.
|
|
||||||
SelfHarm bool `json:"self-harm,required"`
|
|
||||||
// Content that encourages performing acts of self-harm, such as suicide, cutting,
|
|
||||||
// and eating disorders, or that gives instructions or advice on how to commit such
|
|
||||||
// acts.
|
|
||||||
SelfHarmInstructions bool `json:"self-harm/instructions,required"`
|
|
||||||
// Content where the speaker expresses that they are engaging or intend to engage
|
|
||||||
// in acts of self-harm, such as suicide, cutting, and eating disorders.
|
|
||||||
SelfHarmIntent bool `json:"self-harm/intent,required"`
|
|
||||||
// Content meant to arouse sexual excitement, such as the description of sexual
|
|
||||||
// activity, or that promotes sexual services (excluding sex education and
|
|
||||||
// wellness).
|
|
||||||
Sexual bool `json:"sexual,required"`
|
|
||||||
// Sexual content that includes an individual who is under 18 years old.
|
|
||||||
SexualMinors bool `json:"sexual/minors,required"`
|
|
||||||
// Content that depicts death, violence, or physical injury.
|
|
||||||
Violence bool `json:"violence,required"`
|
|
||||||
// Content that depicts death, violence, or physical injury in graphic detail.
|
|
||||||
ViolenceGraphic bool `json:"violence/graphic,required"`
|
|
||||||
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
|
|
||||||
JSON struct {
|
|
||||||
Harassment respjson.Field
|
|
||||||
HarassmentThreatening respjson.Field
|
|
||||||
Hate respjson.Field
|
|
||||||
HateThreatening respjson.Field
|
|
||||||
Illicit respjson.Field
|
|
||||||
IllicitViolent respjson.Field
|
|
||||||
SelfHarm respjson.Field
|
|
||||||
SelfHarmInstructions respjson.Field
|
|
||||||
SelfHarmIntent respjson.Field
|
|
||||||
Sexual respjson.Field
|
|
||||||
SexualMinors respjson.Field
|
|
||||||
Violence respjson.Field
|
|
||||||
ViolenceGraphic respjson.Field
|
|
||||||
ExtraFields map[string]respjson.Field
|
|
||||||
raw string
|
|
||||||
} `json:"-"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Returns the unmodified JSON received from the API
|
|
||||||
func (r ModerationCategories) RawJSON() string { return r.JSON.raw }
|
|
||||||
func (r *ModerationCategories) UnmarshalJSON(data []byte) error {
|
|
||||||
return apijson.UnmarshalRoot(data, r)
|
|
||||||
}
|
|
||||||
|
|
||||||
// A list of the categories along with the input type(s) that the score applies to.
|
|
||||||
type ModerationCategoryAppliedInputTypes struct {
|
|
||||||
// The applied input type(s) for the category 'harassment'.
|
|
||||||
//
|
|
||||||
// Any of "text".
|
|
||||||
Harassment []string `json:"harassment,required"`
|
|
||||||
// The applied input type(s) for the category 'harassment/threatening'.
|
|
||||||
//
|
|
||||||
// Any of "text".
|
|
||||||
HarassmentThreatening []string `json:"harassment/threatening,required"`
|
|
||||||
// The applied input type(s) for the category 'hate'.
|
|
||||||
//
|
|
||||||
// Any of "text".
|
|
||||||
Hate []string `json:"hate,required"`
|
|
||||||
// The applied input type(s) for the category 'hate/threatening'.
|
|
||||||
//
|
|
||||||
// Any of "text".
|
|
||||||
HateThreatening []string `json:"hate/threatening,required"`
|
|
||||||
// The applied input type(s) for the category 'illicit'.
|
|
||||||
//
|
|
||||||
// Any of "text".
|
|
||||||
Illicit []string `json:"illicit,required"`
|
|
||||||
// The applied input type(s) for the category 'illicit/violent'.
|
|
||||||
//
|
|
||||||
// Any of "text".
|
|
||||||
IllicitViolent []string `json:"illicit/violent,required"`
|
|
||||||
// The applied input type(s) for the category 'self-harm'.
|
|
||||||
//
|
|
||||||
// Any of "text", "image".
|
|
||||||
SelfHarm []string `json:"self-harm,required"`
|
|
||||||
// The applied input type(s) for the category 'self-harm/instructions'.
|
|
||||||
//
|
|
||||||
// Any of "text", "image".
|
|
||||||
SelfHarmInstructions []string `json:"self-harm/instructions,required"`
|
|
||||||
// The applied input type(s) for the category 'self-harm/intent'.
|
|
||||||
//
|
|
||||||
// Any of "text", "image".
|
|
||||||
SelfHarmIntent []string `json:"self-harm/intent,required"`
|
|
||||||
// The applied input type(s) for the category 'sexual'.
|
|
||||||
//
|
|
||||||
// Any of "text", "image".
|
|
||||||
Sexual []string `json:"sexual,required"`
|
|
||||||
// The applied input type(s) for the category 'sexual/minors'.
|
|
||||||
//
|
|
||||||
// Any of "text".
|
|
||||||
SexualMinors []string `json:"sexual/minors,required"`
|
|
||||||
// The applied input type(s) for the category 'violence'.
|
|
||||||
//
|
|
||||||
// Any of "text", "image".
|
|
||||||
Violence []string `json:"violence,required"`
|
|
||||||
// The applied input type(s) for the category 'violence/graphic'.
|
|
||||||
//
|
|
||||||
// Any of "text", "image".
|
|
||||||
ViolenceGraphic []string `json:"violence/graphic,required"`
|
|
||||||
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
|
|
||||||
JSON struct {
|
|
||||||
Harassment respjson.Field
|
|
||||||
HarassmentThreatening respjson.Field
|
|
||||||
Hate respjson.Field
|
|
||||||
HateThreatening respjson.Field
|
|
||||||
Illicit respjson.Field
|
|
||||||
IllicitViolent respjson.Field
|
|
||||||
SelfHarm respjson.Field
|
|
||||||
SelfHarmInstructions respjson.Field
|
|
||||||
SelfHarmIntent respjson.Field
|
|
||||||
Sexual respjson.Field
|
|
||||||
SexualMinors respjson.Field
|
|
||||||
Violence respjson.Field
|
|
||||||
ViolenceGraphic respjson.Field
|
|
||||||
ExtraFields map[string]respjson.Field
|
|
||||||
raw string
|
|
||||||
} `json:"-"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Returns the unmodified JSON received from the API
|
|
||||||
func (r ModerationCategoryAppliedInputTypes) RawJSON() string { return r.JSON.raw }
|
|
||||||
func (r *ModerationCategoryAppliedInputTypes) UnmarshalJSON(data []byte) error {
|
|
||||||
return apijson.UnmarshalRoot(data, r)
|
|
||||||
}
|
|
||||||
|
|
||||||
// A list of the categories along with their scores as predicted by model.
|
|
||||||
type ModerationCategoryScores struct {
|
|
||||||
// The score for the category 'harassment'.
|
|
||||||
Harassment float64 `json:"harassment,required"`
|
|
||||||
// The score for the category 'harassment/threatening'.
|
|
||||||
HarassmentThreatening float64 `json:"harassment/threatening,required"`
|
|
||||||
// The score for the category 'hate'.
|
|
||||||
Hate float64 `json:"hate,required"`
|
|
||||||
// The score for the category 'hate/threatening'.
|
|
||||||
HateThreatening float64 `json:"hate/threatening,required"`
|
|
||||||
// The score for the category 'illicit'.
|
|
||||||
Illicit float64 `json:"illicit,required"`
|
|
||||||
// The score for the category 'illicit/violent'.
|
|
||||||
IllicitViolent float64 `json:"illicit/violent,required"`
|
|
||||||
// The score for the category 'self-harm'.
|
|
||||||
SelfHarm float64 `json:"self-harm,required"`
|
|
||||||
// The score for the category 'self-harm/instructions'.
|
|
||||||
SelfHarmInstructions float64 `json:"self-harm/instructions,required"`
|
|
||||||
// The score for the category 'self-harm/intent'.
|
|
||||||
SelfHarmIntent float64 `json:"self-harm/intent,required"`
|
|
||||||
// The score for the category 'sexual'.
|
|
||||||
Sexual float64 `json:"sexual,required"`
|
|
||||||
// The score for the category 'sexual/minors'.
|
|
||||||
SexualMinors float64 `json:"sexual/minors,required"`
|
|
||||||
// The score for the category 'violence'.
|
|
||||||
Violence float64 `json:"violence,required"`
|
|
||||||
// The score for the category 'violence/graphic'.
|
|
||||||
ViolenceGraphic float64 `json:"violence/graphic,required"`
|
|
||||||
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
|
|
||||||
JSON struct {
|
|
||||||
Harassment respjson.Field
|
|
||||||
HarassmentThreatening respjson.Field
|
|
||||||
Hate respjson.Field
|
|
||||||
HateThreatening respjson.Field
|
|
||||||
Illicit respjson.Field
|
|
||||||
IllicitViolent respjson.Field
|
|
||||||
SelfHarm respjson.Field
|
|
||||||
SelfHarmInstructions respjson.Field
|
|
||||||
SelfHarmIntent respjson.Field
|
|
||||||
Sexual respjson.Field
|
|
||||||
SexualMinors respjson.Field
|
|
||||||
Violence respjson.Field
|
|
||||||
ViolenceGraphic respjson.Field
|
|
||||||
ExtraFields map[string]respjson.Field
|
|
||||||
raw string
|
|
||||||
} `json:"-"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Returns the unmodified JSON received from the API
|
|
||||||
func (r ModerationCategoryScores) RawJSON() string { return r.JSON.raw }
|
|
||||||
func (r *ModerationCategoryScores) UnmarshalJSON(data []byte) error {
|
|
||||||
return apijson.UnmarshalRoot(data, r)
|
|
||||||
}
|
|
||||||
|
|
||||||
// An object describing an image to classify.
|
|
||||||
//
|
|
||||||
// The properties ImageURL, Type are required.
|
|
||||||
type ModerationImageURLInputParam struct {
|
|
||||||
// Contains either an image URL or a data URL for a base64 encoded image.
|
|
||||||
ImageURL ModerationImageURLInputImageURLParam `json:"image_url,omitzero,required"`
|
|
||||||
// Always `image_url`.
|
|
||||||
//
|
|
||||||
// This field can be elided, and will marshal its zero value as "image_url".
|
|
||||||
Type constant.ImageURL `json:"type,required"`
|
|
||||||
paramObj
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r ModerationImageURLInputParam) MarshalJSON() (data []byte, err error) {
|
|
||||||
type shadow ModerationImageURLInputParam
|
|
||||||
return param.MarshalObject(r, (*shadow)(&r))
|
|
||||||
}
|
|
||||||
func (r *ModerationImageURLInputParam) UnmarshalJSON(data []byte) error {
|
|
||||||
return apijson.UnmarshalRoot(data, r)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Contains either an image URL or a data URL for a base64 encoded image.
|
|
||||||
//
|
|
||||||
// The property URL is required.
|
|
||||||
type ModerationImageURLInputImageURLParam struct {
|
|
||||||
// Either a URL of the image or the base64 encoded image data.
|
|
||||||
URL string `json:"url,required" format:"uri"`
|
|
||||||
paramObj
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r ModerationImageURLInputImageURLParam) MarshalJSON() (data []byte, err error) {
|
|
||||||
type shadow ModerationImageURLInputImageURLParam
|
|
||||||
return param.MarshalObject(r, (*shadow)(&r))
|
|
||||||
}
|
|
||||||
func (r *ModerationImageURLInputImageURLParam) UnmarshalJSON(data []byte) error {
|
|
||||||
return apijson.UnmarshalRoot(data, r)
|
|
||||||
}
|
|
||||||
|
|
||||||
type ModerationModel = string
|
|
||||||
|
|
||||||
const (
|
|
||||||
ModerationModelOmniModerationLatest ModerationModel = "omni-moderation-latest"
|
|
||||||
ModerationModelOmniModeration2024_09_26 ModerationModel = "omni-moderation-2024-09-26"
|
|
||||||
ModerationModelTextModerationLatest ModerationModel = "text-moderation-latest"
|
|
||||||
ModerationModelTextModerationStable ModerationModel = "text-moderation-stable"
|
|
||||||
)
|
|
||||||
|
|
||||||
func ModerationMultiModalInputParamOfImageURL(imageURL ModerationImageURLInputImageURLParam) ModerationMultiModalInputUnionParam {
|
|
||||||
var variant ModerationImageURLInputParam
|
|
||||||
variant.ImageURL = imageURL
|
|
||||||
return ModerationMultiModalInputUnionParam{OfImageURL: &variant}
|
|
||||||
}
|
|
||||||
|
|
||||||
func ModerationMultiModalInputParamOfText(text string) ModerationMultiModalInputUnionParam {
|
|
||||||
var variant ModerationTextInputParam
|
|
||||||
variant.Text = text
|
|
||||||
return ModerationMultiModalInputUnionParam{OfText: &variant}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Only one field can be non-zero.
|
|
||||||
//
|
|
||||||
// Use [param.IsOmitted] to confirm if a field is set.
|
|
||||||
type ModerationMultiModalInputUnionParam struct {
|
|
||||||
OfImageURL *ModerationImageURLInputParam `json:",omitzero,inline"`
|
|
||||||
OfText *ModerationTextInputParam `json:",omitzero,inline"`
|
|
||||||
paramUnion
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u ModerationMultiModalInputUnionParam) MarshalJSON() ([]byte, error) {
|
|
||||||
return param.MarshalUnion(u, u.OfImageURL, u.OfText)
|
|
||||||
}
|
|
||||||
func (u *ModerationMultiModalInputUnionParam) UnmarshalJSON(data []byte) error {
|
|
||||||
return apijson.UnmarshalRoot(data, u)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u *ModerationMultiModalInputUnionParam) asAny() any {
|
|
||||||
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 ModerationMultiModalInputUnionParam) GetImageURL() *ModerationImageURLInputImageURLParam {
|
|
||||||
if vt := u.OfImageURL; vt != nil {
|
|
||||||
return &vt.ImageURL
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Returns a pointer to the underlying variant's property, if present.
|
|
||||||
func (u ModerationMultiModalInputUnionParam) 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 ModerationMultiModalInputUnionParam) GetType() *string {
|
|
||||||
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[ModerationMultiModalInputUnionParam](
|
|
||||||
"type",
|
|
||||||
apijson.Discriminator[ModerationImageURLInputParam]("image_url"),
|
|
||||||
apijson.Discriminator[ModerationTextInputParam]("text"),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// An object describing text to classify.
|
|
||||||
//
|
|
||||||
// The properties Text, Type are required.
|
|
||||||
type ModerationTextInputParam struct {
|
|
||||||
// A string of text to classify.
|
|
||||||
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 ModerationTextInputParam) MarshalJSON() (data []byte, err error) {
|
|
||||||
type shadow ModerationTextInputParam
|
|
||||||
return param.MarshalObject(r, (*shadow)(&r))
|
|
||||||
}
|
|
||||||
func (r *ModerationTextInputParam) UnmarshalJSON(data []byte) error {
|
|
||||||
return apijson.UnmarshalRoot(data, r)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Represents if a given text input is potentially harmful.
|
|
||||||
type ModerationNewResponse struct {
|
|
||||||
// The unique identifier for the moderation request.
|
|
||||||
ID string `json:"id,required"`
|
|
||||||
// The model used to generate the moderation results.
|
|
||||||
Model string `json:"model,required"`
|
|
||||||
// A list of moderation objects.
|
|
||||||
Results []Moderation `json:"results,required"`
|
|
||||||
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
|
|
||||||
JSON struct {
|
|
||||||
ID respjson.Field
|
|
||||||
Model respjson.Field
|
|
||||||
Results respjson.Field
|
|
||||||
ExtraFields map[string]respjson.Field
|
|
||||||
raw string
|
|
||||||
} `json:"-"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Returns the unmodified JSON received from the API
|
|
||||||
func (r ModerationNewResponse) RawJSON() string { return r.JSON.raw }
|
|
||||||
func (r *ModerationNewResponse) UnmarshalJSON(data []byte) error {
|
|
||||||
return apijson.UnmarshalRoot(data, r)
|
|
||||||
}
|
|
||||||
|
|
||||||
type ModerationNewParams struct {
|
|
||||||
// Input (or inputs) to classify. Can be a single string, an array of strings, or
|
|
||||||
// an array of multi-modal input objects similar to other models.
|
|
||||||
Input ModerationNewParamsInputUnion `json:"input,omitzero,required"`
|
|
||||||
// The content moderation model you would like to use. Learn more in
|
|
||||||
// [the moderation guide](https://platform.openai.com/docs/guides/moderation), and
|
|
||||||
// learn about available models
|
|
||||||
// [here](https://platform.openai.com/docs/models#moderation).
|
|
||||||
Model ModerationModel `json:"model,omitzero"`
|
|
||||||
paramObj
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r ModerationNewParams) MarshalJSON() (data []byte, err error) {
|
|
||||||
type shadow ModerationNewParams
|
|
||||||
return param.MarshalObject(r, (*shadow)(&r))
|
|
||||||
}
|
|
||||||
func (r *ModerationNewParams) 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 ModerationNewParamsInputUnion struct {
|
|
||||||
OfString param.Opt[string] `json:",omitzero,inline"`
|
|
||||||
OfStringArray []string `json:",omitzero,inline"`
|
|
||||||
OfModerationMultiModalArray []ModerationMultiModalInputUnionParam `json:",omitzero,inline"`
|
|
||||||
paramUnion
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u ModerationNewParamsInputUnion) MarshalJSON() ([]byte, error) {
|
|
||||||
return param.MarshalUnion(u, u.OfString, u.OfStringArray, u.OfModerationMultiModalArray)
|
|
||||||
}
|
|
||||||
func (u *ModerationNewParamsInputUnion) UnmarshalJSON(data []byte) error {
|
|
||||||
return apijson.UnmarshalRoot(data, u)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u *ModerationNewParamsInputUnion) asAny() any {
|
|
||||||
if !param.IsOmitted(u.OfString) {
|
|
||||||
return &u.OfString.Value
|
|
||||||
} else if !param.IsOmitted(u.OfStringArray) {
|
|
||||||
return &u.OfStringArray
|
|
||||||
} else if !param.IsOmitted(u.OfModerationMultiModalArray) {
|
|
||||||
return &u.OfModerationMultiModalArray
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
38
vendor/github.com/openai/openai-go/option/middleware.go
generated
vendored
38
vendor/github.com/openai/openai-go/option/middleware.go
generated
vendored
@@ -1,38 +0,0 @@
|
|||||||
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
||||||
|
|
||||||
package option
|
|
||||||
|
|
||||||
import (
|
|
||||||
"log"
|
|
||||||
"net/http"
|
|
||||||
"net/http/httputil"
|
|
||||||
)
|
|
||||||
|
|
||||||
// WithDebugLog logs the HTTP request and response content.
|
|
||||||
// If the logger parameter is nil, it uses the default logger.
|
|
||||||
//
|
|
||||||
// WithDebugLog is for debugging and development purposes only.
|
|
||||||
// It should not be used in production code. The behavior and interface
|
|
||||||
// of WithDebugLog is not guaranteed to be stable.
|
|
||||||
func WithDebugLog(logger *log.Logger) RequestOption {
|
|
||||||
return WithMiddleware(func(req *http.Request, nxt MiddlewareNext) (*http.Response, error) {
|
|
||||||
if logger == nil {
|
|
||||||
logger = log.Default()
|
|
||||||
}
|
|
||||||
|
|
||||||
if reqBytes, err := httputil.DumpRequest(req, true); err == nil {
|
|
||||||
logger.Printf("Request Content:\n%s\n", reqBytes)
|
|
||||||
}
|
|
||||||
|
|
||||||
resp, err := nxt(req)
|
|
||||||
if err != nil {
|
|
||||||
return resp, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if respBytes, err := httputil.DumpResponse(resp, true); err == nil {
|
|
||||||
logger.Printf("Response Content:\n%s\n", respBytes)
|
|
||||||
}
|
|
||||||
|
|
||||||
return resp, err
|
|
||||||
})
|
|
||||||
}
|
|
||||||
299
vendor/github.com/openai/openai-go/option/requestoption.go
generated
vendored
299
vendor/github.com/openai/openai-go/option/requestoption.go
generated
vendored
@@ -1,299 +0,0 @@
|
|||||||
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
||||||
|
|
||||||
package option
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"net/http"
|
|
||||||
"net/url"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/openai/openai-go/internal/requestconfig"
|
|
||||||
"github.com/tidwall/sjson"
|
|
||||||
)
|
|
||||||
|
|
||||||
// RequestOption is an option for the requests made by the openai API Client
|
|
||||||
// which can be supplied to clients, services, and methods. You can read more about this functional
|
|
||||||
// options pattern in our [README].
|
|
||||||
//
|
|
||||||
// [README]: https://pkg.go.dev/github.com/openai/openai-go#readme-requestoptions
|
|
||||||
type RequestOption = requestconfig.RequestOption
|
|
||||||
|
|
||||||
// WithBaseURL returns a RequestOption that sets the BaseURL for the client.
|
|
||||||
//
|
|
||||||
// For security reasons, ensure that the base URL is trusted.
|
|
||||||
func WithBaseURL(base string) RequestOption {
|
|
||||||
u, err := url.Parse(base)
|
|
||||||
if err == nil && u.Path != "" && !strings.HasSuffix(u.Path, "/") {
|
|
||||||
u.Path += "/"
|
|
||||||
}
|
|
||||||
|
|
||||||
return requestconfig.RequestOptionFunc(func(r *requestconfig.RequestConfig) error {
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("requestoption: WithBaseURL failed to parse url %s", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
r.BaseURL = u
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// HTTPClient is primarily used to describe an [*http.Client], but also
|
|
||||||
// supports custom implementations.
|
|
||||||
//
|
|
||||||
// For bespoke implementations, prefer using an [*http.Client] with a
|
|
||||||
// custom transport. See [http.RoundTripper] for further information.
|
|
||||||
type HTTPClient interface {
|
|
||||||
Do(*http.Request) (*http.Response, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithHTTPClient returns a RequestOption that changes the underlying http client used to make this
|
|
||||||
// request, which by default is [http.DefaultClient].
|
|
||||||
//
|
|
||||||
// For custom uses cases, it is recommended to provide an [*http.Client] with a custom
|
|
||||||
// [http.RoundTripper] as its transport, rather than directly implementing [HTTPClient].
|
|
||||||
func WithHTTPClient(client HTTPClient) RequestOption {
|
|
||||||
return requestconfig.RequestOptionFunc(func(r *requestconfig.RequestConfig) error {
|
|
||||||
if client == nil {
|
|
||||||
return fmt.Errorf("requestoption: custom http client cannot be nil")
|
|
||||||
}
|
|
||||||
|
|
||||||
if c, ok := client.(*http.Client); ok {
|
|
||||||
// Prefer the native client if possible.
|
|
||||||
r.HTTPClient = c
|
|
||||||
r.CustomHTTPDoer = nil
|
|
||||||
} else {
|
|
||||||
r.CustomHTTPDoer = client
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// MiddlewareNext is a function which is called by a middleware to pass an HTTP request
|
|
||||||
// to the next stage in the middleware chain.
|
|
||||||
type MiddlewareNext = func(*http.Request) (*http.Response, error)
|
|
||||||
|
|
||||||
// Middleware is a function which intercepts HTTP requests, processing or modifying
|
|
||||||
// them, and then passing the request to the next middleware or handler
|
|
||||||
// in the chain by calling the provided MiddlewareNext function.
|
|
||||||
type Middleware = func(*http.Request, MiddlewareNext) (*http.Response, error)
|
|
||||||
|
|
||||||
// WithMiddleware returns a RequestOption that applies the given middleware
|
|
||||||
// to the requests made. Each middleware will execute in the order they were given.
|
|
||||||
func WithMiddleware(middlewares ...Middleware) RequestOption {
|
|
||||||
return requestconfig.RequestOptionFunc(func(r *requestconfig.RequestConfig) error {
|
|
||||||
r.Middlewares = append(r.Middlewares, middlewares...)
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithMaxRetries returns a RequestOption that sets the maximum number of retries that the client
|
|
||||||
// attempts to make. When given 0, the client only makes one request. By
|
|
||||||
// default, the client retries two times.
|
|
||||||
//
|
|
||||||
// WithMaxRetries panics when retries is negative.
|
|
||||||
func WithMaxRetries(retries int) RequestOption {
|
|
||||||
if retries < 0 {
|
|
||||||
panic("option: cannot have fewer than 0 retries")
|
|
||||||
}
|
|
||||||
return requestconfig.RequestOptionFunc(func(r *requestconfig.RequestConfig) error {
|
|
||||||
r.MaxRetries = retries
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithHeader returns a RequestOption that sets the header value to the associated key. It overwrites
|
|
||||||
// any value if there was one already present.
|
|
||||||
func WithHeader(key, value string) RequestOption {
|
|
||||||
return requestconfig.RequestOptionFunc(func(r *requestconfig.RequestConfig) error {
|
|
||||||
r.Request.Header.Set(key, value)
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithHeaderAdd returns a RequestOption that adds the header value to the associated key. It appends
|
|
||||||
// onto any existing values.
|
|
||||||
func WithHeaderAdd(key, value string) RequestOption {
|
|
||||||
return requestconfig.RequestOptionFunc(func(r *requestconfig.RequestConfig) error {
|
|
||||||
r.Request.Header.Add(key, value)
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithHeaderDel returns a RequestOption that deletes the header value(s) associated with the given key.
|
|
||||||
func WithHeaderDel(key string) RequestOption {
|
|
||||||
return requestconfig.RequestOptionFunc(func(r *requestconfig.RequestConfig) error {
|
|
||||||
r.Request.Header.Del(key)
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithQuery returns a RequestOption that sets the query value to the associated key. It overwrites
|
|
||||||
// any value if there was one already present.
|
|
||||||
func WithQuery(key, value string) RequestOption {
|
|
||||||
return requestconfig.RequestOptionFunc(func(r *requestconfig.RequestConfig) error {
|
|
||||||
query := r.Request.URL.Query()
|
|
||||||
query.Set(key, value)
|
|
||||||
r.Request.URL.RawQuery = query.Encode()
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithQueryAdd returns a RequestOption that adds the query value to the associated key. It appends
|
|
||||||
// onto any existing values.
|
|
||||||
func WithQueryAdd(key, value string) RequestOption {
|
|
||||||
return requestconfig.RequestOptionFunc(func(r *requestconfig.RequestConfig) error {
|
|
||||||
query := r.Request.URL.Query()
|
|
||||||
query.Add(key, value)
|
|
||||||
r.Request.URL.RawQuery = query.Encode()
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithQueryDel returns a RequestOption that deletes the query value(s) associated with the key.
|
|
||||||
func WithQueryDel(key string) RequestOption {
|
|
||||||
return requestconfig.RequestOptionFunc(func(r *requestconfig.RequestConfig) error {
|
|
||||||
query := r.Request.URL.Query()
|
|
||||||
query.Del(key)
|
|
||||||
r.Request.URL.RawQuery = query.Encode()
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithJSONSet returns a RequestOption that sets the body's JSON value associated with the key.
|
|
||||||
// The key accepts a string as defined by the [sjson format].
|
|
||||||
//
|
|
||||||
// [sjson format]: https://github.com/tidwall/sjson
|
|
||||||
func WithJSONSet(key string, value any) RequestOption {
|
|
||||||
return requestconfig.RequestOptionFunc(func(r *requestconfig.RequestConfig) (err error) {
|
|
||||||
var b []byte
|
|
||||||
|
|
||||||
if r.Body == nil {
|
|
||||||
b, err = sjson.SetBytes(nil, key, value)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
} else if buffer, ok := r.Body.(*bytes.Buffer); ok {
|
|
||||||
b = buffer.Bytes()
|
|
||||||
b, err = sjson.SetBytes(b, key, value)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return fmt.Errorf("cannot use WithJSONSet on a body that is not serialized as *bytes.Buffer")
|
|
||||||
}
|
|
||||||
|
|
||||||
r.Body = bytes.NewBuffer(b)
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithJSONDel returns a RequestOption that deletes the body's JSON value associated with the key.
|
|
||||||
// The key accepts a string as defined by the [sjson format].
|
|
||||||
//
|
|
||||||
// [sjson format]: https://github.com/tidwall/sjson
|
|
||||||
func WithJSONDel(key string) RequestOption {
|
|
||||||
return requestconfig.RequestOptionFunc(func(r *requestconfig.RequestConfig) (err error) {
|
|
||||||
if buffer, ok := r.Body.(*bytes.Buffer); ok {
|
|
||||||
b := buffer.Bytes()
|
|
||||||
b, err = sjson.DeleteBytes(b, key)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
r.Body = bytes.NewBuffer(b)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return fmt.Errorf("cannot use WithJSONDel on a body that is not serialized as *bytes.Buffer")
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithResponseBodyInto returns a RequestOption that overwrites the deserialization target with
|
|
||||||
// the given destination. If provided, we don't deserialize into the default struct.
|
|
||||||
func WithResponseBodyInto(dst any) RequestOption {
|
|
||||||
return requestconfig.RequestOptionFunc(func(r *requestconfig.RequestConfig) error {
|
|
||||||
r.ResponseBodyInto = dst
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithResponseInto returns a RequestOption that copies the [*http.Response] into the given address.
|
|
||||||
func WithResponseInto(dst **http.Response) RequestOption {
|
|
||||||
return requestconfig.RequestOptionFunc(func(r *requestconfig.RequestConfig) error {
|
|
||||||
r.ResponseInto = dst
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithRequestBody returns a RequestOption that provides a custom serialized body with the given
|
|
||||||
// content type.
|
|
||||||
//
|
|
||||||
// body accepts an io.Reader or raw []bytes.
|
|
||||||
func WithRequestBody(contentType string, body any) RequestOption {
|
|
||||||
return requestconfig.RequestOptionFunc(func(r *requestconfig.RequestConfig) error {
|
|
||||||
if reader, ok := body.(io.Reader); ok {
|
|
||||||
r.Body = reader
|
|
||||||
return r.Apply(WithHeader("Content-Type", contentType))
|
|
||||||
}
|
|
||||||
|
|
||||||
if b, ok := body.([]byte); ok {
|
|
||||||
r.Body = bytes.NewBuffer(b)
|
|
||||||
return r.Apply(WithHeader("Content-Type", contentType))
|
|
||||||
}
|
|
||||||
|
|
||||||
return fmt.Errorf("body must be a byte slice or implement io.Reader")
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithRequestTimeout returns a RequestOption that sets the timeout for
|
|
||||||
// each request attempt. This should be smaller than the timeout defined in
|
|
||||||
// the context, which spans all retries.
|
|
||||||
func WithRequestTimeout(dur time.Duration) RequestOption {
|
|
||||||
return requestconfig.RequestOptionFunc(func(r *requestconfig.RequestConfig) error {
|
|
||||||
r.RequestTimeout = dur
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithEnvironmentProduction returns a RequestOption that sets the current
|
|
||||||
// environment to be the "production" environment. An environment specifies which base URL
|
|
||||||
// to use by default.
|
|
||||||
func WithEnvironmentProduction() RequestOption {
|
|
||||||
return requestconfig.WithDefaultBaseURL("https://api.openai.com/v1/")
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithAPIKey returns a RequestOption that sets the client setting "api_key".
|
|
||||||
func WithAPIKey(value string) RequestOption {
|
|
||||||
return requestconfig.RequestOptionFunc(func(r *requestconfig.RequestConfig) error {
|
|
||||||
r.APIKey = value
|
|
||||||
return r.Apply(WithHeader("authorization", fmt.Sprintf("Bearer %s", r.APIKey)))
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithOrganization returns a RequestOption that sets the client setting "organization".
|
|
||||||
func WithOrganization(value string) RequestOption {
|
|
||||||
return requestconfig.RequestOptionFunc(func(r *requestconfig.RequestConfig) error {
|
|
||||||
r.Organization = value
|
|
||||||
return r.Apply(WithHeader("OpenAI-Organization", value))
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithProject returns a RequestOption that sets the client setting "project".
|
|
||||||
func WithProject(value string) RequestOption {
|
|
||||||
return requestconfig.RequestOptionFunc(func(r *requestconfig.RequestConfig) error {
|
|
||||||
r.Project = value
|
|
||||||
return r.Apply(WithHeader("OpenAI-Project", value))
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithWebhookSecret returns a RequestOption that sets the client setting "webhook_secret".
|
|
||||||
func WithWebhookSecret(value string) requestconfig.PreRequestOptionFunc {
|
|
||||||
return requestconfig.PreRequestOptionFunc(func(r *requestconfig.RequestConfig) error {
|
|
||||||
r.WebhookSecret = value
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
}
|
|
||||||
223
vendor/github.com/openai/openai-go/packages/pagination/pagination.go
generated
vendored
223
vendor/github.com/openai/openai-go/packages/pagination/pagination.go
generated
vendored
@@ -1,223 +0,0 @@
|
|||||||
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
||||||
|
|
||||||
package pagination
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/http"
|
|
||||||
"reflect"
|
|
||||||
|
|
||||||
"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"
|
|
||||||
)
|
|
||||||
|
|
||||||
// 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 Page[T any] struct {
|
|
||||||
Data []T `json:"data"`
|
|
||||||
Object string `json:"object,required"`
|
|
||||||
// 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:"-"`
|
|
||||||
cfg *requestconfig.RequestConfig
|
|
||||||
res *http.Response
|
|
||||||
}
|
|
||||||
|
|
||||||
// Returns the unmodified JSON received from the API
|
|
||||||
func (r Page[T]) RawJSON() string { return r.JSON.raw }
|
|
||||||
func (r *Page[T]) UnmarshalJSON(data []byte) error {
|
|
||||||
return apijson.UnmarshalRoot(data, r)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetNextPage returns the next page as defined by this pagination style. When
|
|
||||||
// there is no next page, this function will return a 'nil' for the page value, but
|
|
||||||
// will not return an error
|
|
||||||
func (r *Page[T]) GetNextPage() (res *Page[T], err error) {
|
|
||||||
if len(r.Data) == 0 {
|
|
||||||
return nil, nil
|
|
||||||
}
|
|
||||||
// This page represents a response that isn't actually paginated at the API level
|
|
||||||
// so there will never be a next page.
|
|
||||||
cfg := (*requestconfig.RequestConfig)(nil)
|
|
||||||
if cfg == nil {
|
|
||||||
return nil, nil
|
|
||||||
}
|
|
||||||
var raw *http.Response
|
|
||||||
cfg.ResponseInto = &raw
|
|
||||||
cfg.ResponseBodyInto = &res
|
|
||||||
err = cfg.Execute()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
res.SetPageConfig(cfg, raw)
|
|
||||||
return res, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *Page[T]) SetPageConfig(cfg *requestconfig.RequestConfig, res *http.Response) {
|
|
||||||
if r == nil {
|
|
||||||
r = &Page[T]{}
|
|
||||||
}
|
|
||||||
r.cfg = cfg
|
|
||||||
r.res = res
|
|
||||||
}
|
|
||||||
|
|
||||||
type PageAutoPager[T any] struct {
|
|
||||||
page *Page[T]
|
|
||||||
cur T
|
|
||||||
idx int
|
|
||||||
run int
|
|
||||||
err error
|
|
||||||
paramObj
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewPageAutoPager[T any](page *Page[T], err error) *PageAutoPager[T] {
|
|
||||||
return &PageAutoPager[T]{
|
|
||||||
page: page,
|
|
||||||
err: err,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *PageAutoPager[T]) Next() bool {
|
|
||||||
if r.page == nil || len(r.page.Data) == 0 {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if r.idx >= len(r.page.Data) {
|
|
||||||
r.idx = 0
|
|
||||||
r.page, r.err = r.page.GetNextPage()
|
|
||||||
if r.err != nil || r.page == nil || len(r.page.Data) == 0 {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
r.cur = r.page.Data[r.idx]
|
|
||||||
r.run += 1
|
|
||||||
r.idx += 1
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *PageAutoPager[T]) Current() T {
|
|
||||||
return r.cur
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *PageAutoPager[T]) Err() error {
|
|
||||||
return r.err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *PageAutoPager[T]) Index() int {
|
|
||||||
return r.run
|
|
||||||
}
|
|
||||||
|
|
||||||
type CursorPage[T any] struct {
|
|
||||||
Data []T `json:"data"`
|
|
||||||
HasMore bool `json:"has_more"`
|
|
||||||
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
|
|
||||||
JSON struct {
|
|
||||||
Data respjson.Field
|
|
||||||
HasMore respjson.Field
|
|
||||||
ExtraFields map[string]respjson.Field
|
|
||||||
raw string
|
|
||||||
} `json:"-"`
|
|
||||||
cfg *requestconfig.RequestConfig
|
|
||||||
res *http.Response
|
|
||||||
}
|
|
||||||
|
|
||||||
// Returns the unmodified JSON received from the API
|
|
||||||
func (r CursorPage[T]) RawJSON() string { return r.JSON.raw }
|
|
||||||
func (r *CursorPage[T]) UnmarshalJSON(data []byte) error {
|
|
||||||
return apijson.UnmarshalRoot(data, r)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetNextPage returns the next page as defined by this pagination style. When
|
|
||||||
// there is no next page, this function will return a 'nil' for the page value, but
|
|
||||||
// will not return an error
|
|
||||||
func (r *CursorPage[T]) GetNextPage() (res *CursorPage[T], err error) {
|
|
||||||
if len(r.Data) == 0 {
|
|
||||||
return nil, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if r.JSON.HasMore.Valid() && r.HasMore == false {
|
|
||||||
return nil, nil
|
|
||||||
}
|
|
||||||
items := r.Data
|
|
||||||
if items == nil || len(items) == 0 {
|
|
||||||
return nil, nil
|
|
||||||
}
|
|
||||||
cfg := r.cfg.Clone(r.cfg.Context)
|
|
||||||
value := reflect.ValueOf(items[len(items)-1])
|
|
||||||
field := value.FieldByName("ID")
|
|
||||||
err = cfg.Apply(option.WithQuery("after", field.Interface().(string)))
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
var raw *http.Response
|
|
||||||
cfg.ResponseInto = &raw
|
|
||||||
cfg.ResponseBodyInto = &res
|
|
||||||
err = cfg.Execute()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
res.SetPageConfig(cfg, raw)
|
|
||||||
return res, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *CursorPage[T]) SetPageConfig(cfg *requestconfig.RequestConfig, res *http.Response) {
|
|
||||||
if r == nil {
|
|
||||||
r = &CursorPage[T]{}
|
|
||||||
}
|
|
||||||
r.cfg = cfg
|
|
||||||
r.res = res
|
|
||||||
}
|
|
||||||
|
|
||||||
type CursorPageAutoPager[T any] struct {
|
|
||||||
page *CursorPage[T]
|
|
||||||
cur T
|
|
||||||
idx int
|
|
||||||
run int
|
|
||||||
err error
|
|
||||||
paramObj
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewCursorPageAutoPager[T any](page *CursorPage[T], err error) *CursorPageAutoPager[T] {
|
|
||||||
return &CursorPageAutoPager[T]{
|
|
||||||
page: page,
|
|
||||||
err: err,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *CursorPageAutoPager[T]) Next() bool {
|
|
||||||
if r.page == nil || len(r.page.Data) == 0 {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if r.idx >= len(r.page.Data) {
|
|
||||||
r.idx = 0
|
|
||||||
r.page, r.err = r.page.GetNextPage()
|
|
||||||
if r.err != nil || r.page == nil || len(r.page.Data) == 0 {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
r.cur = r.page.Data[r.idx]
|
|
||||||
r.run += 1
|
|
||||||
r.idx += 1
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *CursorPageAutoPager[T]) Current() T {
|
|
||||||
return r.cur
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *CursorPageAutoPager[T]) Err() error {
|
|
||||||
return r.err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *CursorPageAutoPager[T]) Index() int {
|
|
||||||
return r.run
|
|
||||||
}
|
|
||||||
101
vendor/github.com/openai/openai-go/packages/param/encoder.go
generated
vendored
101
vendor/github.com/openai/openai-go/packages/param/encoder.go
generated
vendored
@@ -1,101 +0,0 @@
|
|||||||
package param
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"reflect"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
shimjson "github.com/openai/openai-go/internal/encoding/json"
|
|
||||||
|
|
||||||
"github.com/tidwall/sjson"
|
|
||||||
)
|
|
||||||
|
|
||||||
// EncodedAsDate is not be stable and shouldn't be relied upon
|
|
||||||
type EncodedAsDate Opt[time.Time]
|
|
||||||
|
|
||||||
type forceOmit int
|
|
||||||
|
|
||||||
func (m EncodedAsDate) MarshalJSON() ([]byte, error) {
|
|
||||||
underlying := Opt[time.Time](m)
|
|
||||||
bytes := underlying.MarshalJSONWithTimeLayout("2006-01-02")
|
|
||||||
if len(bytes) > 0 {
|
|
||||||
return bytes, nil
|
|
||||||
}
|
|
||||||
return underlying.MarshalJSON()
|
|
||||||
}
|
|
||||||
|
|
||||||
// MarshalObject uses a shimmed 'encoding/json' from Go 1.24, to support the 'omitzero' tag
|
|
||||||
//
|
|
||||||
// Stability for the API of MarshalObject is not guaranteed.
|
|
||||||
func MarshalObject[T ParamStruct](f T, underlying any) ([]byte, error) {
|
|
||||||
return MarshalWithExtras(f, underlying, f.extraFields())
|
|
||||||
}
|
|
||||||
|
|
||||||
// MarshalWithExtras is used to marshal a struct with additional properties.
|
|
||||||
//
|
|
||||||
// Stability for the API of MarshalWithExtras is not guaranteed.
|
|
||||||
func MarshalWithExtras[T ParamStruct, R any](f T, underlying any, extras map[string]R) ([]byte, error) {
|
|
||||||
if f.null() {
|
|
||||||
return []byte("null"), nil
|
|
||||||
} else if len(extras) > 0 {
|
|
||||||
bytes, err := shimjson.Marshal(underlying)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
for k, v := range extras {
|
|
||||||
var a any = v
|
|
||||||
if a == Omit {
|
|
||||||
// Errors when handling ForceOmitted are ignored.
|
|
||||||
if b, e := sjson.DeleteBytes(bytes, k); e == nil {
|
|
||||||
bytes = b
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
bytes, err = sjson.SetBytes(bytes, k, v)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return bytes, nil
|
|
||||||
} else if ovr, ok := f.Overrides(); ok {
|
|
||||||
return shimjson.Marshal(ovr)
|
|
||||||
} else {
|
|
||||||
return shimjson.Marshal(underlying)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// MarshalUnion uses a shimmed 'encoding/json' from Go 1.24, to support the 'omitzero' tag
|
|
||||||
//
|
|
||||||
// Stability for the API of MarshalUnion is not guaranteed.
|
|
||||||
func MarshalUnion[T ParamStruct](metadata T, variants ...any) ([]byte, error) {
|
|
||||||
nPresent := 0
|
|
||||||
presentIdx := -1
|
|
||||||
for i, variant := range variants {
|
|
||||||
if !IsOmitted(variant) {
|
|
||||||
nPresent++
|
|
||||||
presentIdx = i
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if nPresent == 0 || presentIdx == -1 {
|
|
||||||
if ovr, ok := metadata.Overrides(); ok {
|
|
||||||
return shimjson.Marshal(ovr)
|
|
||||||
}
|
|
||||||
return []byte(`null`), nil
|
|
||||||
} else if nPresent > 1 {
|
|
||||||
return nil, &json.MarshalerError{
|
|
||||||
Type: typeFor[T](),
|
|
||||||
Err: fmt.Errorf("expected union to have only one present variant, got %d", nPresent),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return shimjson.Marshal(variants[presentIdx])
|
|
||||||
}
|
|
||||||
|
|
||||||
// typeFor is shimmed from Go 1.23 "reflect" package
|
|
||||||
func typeFor[T any]() reflect.Type {
|
|
||||||
var v T
|
|
||||||
if t := reflect.TypeOf(v); t != nil {
|
|
||||||
return t // optimize for T being a non-interface kind
|
|
||||||
}
|
|
||||||
return reflect.TypeOf((*T)(nil)).Elem() // only for an interface kind
|
|
||||||
}
|
|
||||||
19
vendor/github.com/openai/openai-go/packages/param/null.go
generated
vendored
19
vendor/github.com/openai/openai-go/packages/param/null.go
generated
vendored
@@ -1,19 +0,0 @@
|
|||||||
package param
|
|
||||||
|
|
||||||
import "github.com/openai/openai-go/internal/encoding/json/sentinel"
|
|
||||||
|
|
||||||
// NullMap returns a non-nil map with a length of 0.
|
|
||||||
// When used with [MarshalObject] or [MarshalUnion], it will be marshaled as null.
|
|
||||||
//
|
|
||||||
// It is unspecified behavior to mutate the map returned by [NullMap].
|
|
||||||
func NullMap[MapT ~map[string]T, T any]() MapT {
|
|
||||||
return sentinel.NewNullSentinel(func() MapT { return make(MapT, 1) })
|
|
||||||
}
|
|
||||||
|
|
||||||
// NullSlice returns a non-nil slice with a length of 0.
|
|
||||||
// When used with [MarshalObject] or [MarshalUnion], it will be marshaled as null.
|
|
||||||
//
|
|
||||||
// It is unspecified behavior to mutate the slice returned by [NullSlice].
|
|
||||||
func NullSlice[SliceT ~[]T, T any]() SliceT {
|
|
||||||
return sentinel.NewNullSentinel(func() SliceT { return make(SliceT, 0, 1) })
|
|
||||||
}
|
|
||||||
121
vendor/github.com/openai/openai-go/packages/param/option.go
generated
vendored
121
vendor/github.com/openai/openai-go/packages/param/option.go
generated
vendored
@@ -1,121 +0,0 @@
|
|||||||
package param
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
shimjson "github.com/openai/openai-go/internal/encoding/json"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
func NewOpt[T comparable](v T) Opt[T] {
|
|
||||||
return Opt[T]{Value: v, status: included}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Null creates optional field with the JSON value "null".
|
|
||||||
//
|
|
||||||
// To set a struct to null, use [NullStruct].
|
|
||||||
func Null[T comparable]() Opt[T] { return Opt[T]{status: null} }
|
|
||||||
|
|
||||||
type status int8
|
|
||||||
|
|
||||||
const (
|
|
||||||
omitted status = iota
|
|
||||||
null
|
|
||||||
included
|
|
||||||
)
|
|
||||||
|
|
||||||
// Opt represents an optional parameter of type T. Use
|
|
||||||
// the [Opt.Valid] method to confirm.
|
|
||||||
type Opt[T comparable] struct {
|
|
||||||
Value T
|
|
||||||
// indicates whether the field should be omitted, null, or valid
|
|
||||||
status status
|
|
||||||
opt
|
|
||||||
}
|
|
||||||
|
|
||||||
// Valid returns true if the value is not "null" or omitted.
|
|
||||||
//
|
|
||||||
// To check if explicitly null, use [Opt.Null].
|
|
||||||
func (o Opt[T]) Valid() bool {
|
|
||||||
var empty Opt[T]
|
|
||||||
return o.status == included || o != empty && o.status != null
|
|
||||||
}
|
|
||||||
|
|
||||||
func (o Opt[T]) Or(v T) T {
|
|
||||||
if o.Valid() {
|
|
||||||
return o.Value
|
|
||||||
}
|
|
||||||
return v
|
|
||||||
}
|
|
||||||
|
|
||||||
func (o Opt[T]) String() string {
|
|
||||||
if o.null() {
|
|
||||||
return "null"
|
|
||||||
}
|
|
||||||
if s, ok := any(o.Value).(fmt.Stringer); ok {
|
|
||||||
return s.String()
|
|
||||||
}
|
|
||||||
return fmt.Sprintf("%v", o.Value)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (o Opt[T]) MarshalJSON() ([]byte, error) {
|
|
||||||
if !o.Valid() {
|
|
||||||
return []byte("null"), nil
|
|
||||||
}
|
|
||||||
return json.Marshal(o.Value)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (o *Opt[T]) UnmarshalJSON(data []byte) error {
|
|
||||||
if string(data) == "null" {
|
|
||||||
o.status = null
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var value *T
|
|
||||||
if err := json.Unmarshal(data, &value); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
if value == nil {
|
|
||||||
o.status = omitted
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
o.status = included
|
|
||||||
o.Value = *value
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// MarshalJSONWithTimeLayout is necessary to bypass the internal caching performed
|
|
||||||
// by [json.Marshal]. Prefer to use [Opt.MarshalJSON] instead.
|
|
||||||
//
|
|
||||||
// This function requires that the generic type parameter of [Opt] is not [time.Time].
|
|
||||||
func (o Opt[T]) MarshalJSONWithTimeLayout(format string) []byte {
|
|
||||||
t, ok := any(o.Value).(time.Time)
|
|
||||||
if !ok || o.null() {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
b, err := json.Marshal(t.Format(shimjson.TimeLayout(format)))
|
|
||||||
if err != nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return b
|
|
||||||
}
|
|
||||||
|
|
||||||
func (o Opt[T]) null() bool { return o.status == null }
|
|
||||||
func (o Opt[T]) isZero() bool { return o == Opt[T]{} }
|
|
||||||
|
|
||||||
// opt helps limit the [Optional] interface to only types in this package
|
|
||||||
type opt struct{}
|
|
||||||
|
|
||||||
func (opt) implOpt() {}
|
|
||||||
|
|
||||||
// This interface is useful for internal purposes.
|
|
||||||
type Optional interface {
|
|
||||||
Valid() bool
|
|
||||||
null() bool
|
|
||||||
|
|
||||||
isZero() bool
|
|
||||||
implOpt()
|
|
||||||
}
|
|
||||||
168
vendor/github.com/openai/openai-go/packages/param/param.go
generated
vendored
168
vendor/github.com/openai/openai-go/packages/param/param.go
generated
vendored
@@ -1,168 +0,0 @@
|
|||||||
package param
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"github.com/openai/openai-go/internal/encoding/json/sentinel"
|
|
||||||
"reflect"
|
|
||||||
)
|
|
||||||
|
|
||||||
// NullStruct is used to set a struct to the JSON value null.
|
|
||||||
// Check for null structs with [IsNull].
|
|
||||||
//
|
|
||||||
// Only the first type parameter should be provided,
|
|
||||||
// the type PtrT will be inferred.
|
|
||||||
//
|
|
||||||
// json.Marshal(param.NullStruct[MyStruct]()) -> 'null'
|
|
||||||
//
|
|
||||||
// To send null to an [Opt] field use [Null].
|
|
||||||
func NullStruct[T ParamStruct, PtrT InferPtr[T]]() T {
|
|
||||||
var t T
|
|
||||||
pt := PtrT(&t)
|
|
||||||
pt.setMetadata(nil)
|
|
||||||
return *pt
|
|
||||||
}
|
|
||||||
|
|
||||||
// Override replaces the value of a struct with any type.
|
|
||||||
//
|
|
||||||
// Only the first type parameter should be provided,
|
|
||||||
// the type PtrT will be inferred.
|
|
||||||
//
|
|
||||||
// It's often useful for providing raw JSON
|
|
||||||
//
|
|
||||||
// param.Override[MyStruct](json.RawMessage(`{"foo": "bar"}`))
|
|
||||||
//
|
|
||||||
// The public fields of the returned struct T will be unset.
|
|
||||||
//
|
|
||||||
// To override a specific field in a struct, use its [SetExtraFields] method.
|
|
||||||
func Override[T ParamStruct, PtrT InferPtr[T]](v any) T {
|
|
||||||
var t T
|
|
||||||
pt := PtrT(&t)
|
|
||||||
pt.setMetadata(v)
|
|
||||||
return *pt
|
|
||||||
}
|
|
||||||
|
|
||||||
// IsOmitted returns true if v is the zero value of its type.
|
|
||||||
//
|
|
||||||
// If IsOmitted is true, and the field uses a `json:"...,omitzero"` tag,
|
|
||||||
// the field will be omitted from the request.
|
|
||||||
//
|
|
||||||
// If v is set explicitly to the JSON value "null", IsOmitted returns false.
|
|
||||||
func IsOmitted(v any) bool {
|
|
||||||
if v == nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if o, ok := v.(Optional); ok {
|
|
||||||
return o.isZero()
|
|
||||||
}
|
|
||||||
return reflect.ValueOf(v).IsZero()
|
|
||||||
}
|
|
||||||
|
|
||||||
// IsNull returns true if v was set to the JSON value null.
|
|
||||||
//
|
|
||||||
// To set a param to null use [NullStruct], [Null], [NullMap], or [NullSlice]
|
|
||||||
// depending on the type of v.
|
|
||||||
//
|
|
||||||
// IsNull returns false if the value is omitted.
|
|
||||||
func IsNull[T any](v T) bool {
|
|
||||||
if nullable, ok := any(v).(ParamNullable); ok {
|
|
||||||
return nullable.null()
|
|
||||||
}
|
|
||||||
|
|
||||||
switch reflect.TypeOf(v).Kind() {
|
|
||||||
case reflect.Slice, reflect.Map:
|
|
||||||
return sentinel.IsNull(v)
|
|
||||||
}
|
|
||||||
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// ParamNullable encapsulates all structs in parameters,
|
|
||||||
// and all [Opt] types in parameters.
|
|
||||||
type ParamNullable interface {
|
|
||||||
null() bool
|
|
||||||
}
|
|
||||||
|
|
||||||
// ParamStruct represents the set of all structs that are
|
|
||||||
// used in API parameters, by convention these usually end in
|
|
||||||
// "Params" or "Param".
|
|
||||||
type ParamStruct interface {
|
|
||||||
Overrides() (any, bool)
|
|
||||||
null() bool
|
|
||||||
extraFields() map[string]any
|
|
||||||
}
|
|
||||||
|
|
||||||
// This is an implementation detail and should never be explicitly set.
|
|
||||||
type InferPtr[T ParamStruct] interface {
|
|
||||||
setMetadata(any)
|
|
||||||
*T
|
|
||||||
}
|
|
||||||
|
|
||||||
// APIObject should be embedded in api object fields, preferably using an alias to make private
|
|
||||||
type APIObject struct{ metadata }
|
|
||||||
|
|
||||||
// APIUnion should be embedded in all api unions fields, preferably using an alias to make private
|
|
||||||
type APIUnion struct{ metadata }
|
|
||||||
|
|
||||||
// Overrides returns the value of the struct when it is created with
|
|
||||||
// [Override], the second argument helps differentiate an explicit null.
|
|
||||||
func (m metadata) Overrides() (any, bool) {
|
|
||||||
if _, ok := m.any.(metadataExtraFields); ok {
|
|
||||||
return nil, false
|
|
||||||
}
|
|
||||||
return m.any, m.any != nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// ExtraFields returns the extra fields added to the JSON object.
|
|
||||||
func (m metadata) ExtraFields() map[string]any {
|
|
||||||
if extras, ok := m.any.(metadataExtraFields); ok {
|
|
||||||
return extras
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Omit can be used with [metadata.SetExtraFields] to ensure that a
|
|
||||||
// required field is omitted. This is useful as an escape hatch for
|
|
||||||
// when a required is unwanted for some unexpected reason.
|
|
||||||
const Omit forceOmit = -1
|
|
||||||
|
|
||||||
// SetExtraFields adds extra fields to the JSON object.
|
|
||||||
//
|
|
||||||
// SetExtraFields will override any existing fields with the same key.
|
|
||||||
// For security reasons, ensure this is only used with trusted input data.
|
|
||||||
//
|
|
||||||
// To intentionally omit a required field, use [Omit].
|
|
||||||
//
|
|
||||||
// foo.SetExtraFields(map[string]any{"bar": Omit})
|
|
||||||
//
|
|
||||||
// If the struct already contains the field ExtraFields, then this
|
|
||||||
// method will have no effect.
|
|
||||||
func (m *metadata) SetExtraFields(extraFields map[string]any) {
|
|
||||||
m.any = metadataExtraFields(extraFields)
|
|
||||||
}
|
|
||||||
|
|
||||||
// extraFields aliases [metadata.ExtraFields] to avoid name collisions.
|
|
||||||
func (m metadata) extraFields() map[string]any { return m.ExtraFields() }
|
|
||||||
|
|
||||||
func (m metadata) null() bool {
|
|
||||||
if _, ok := m.any.(metadataNull); ok {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
if msg, ok := m.any.(json.RawMessage); ok {
|
|
||||||
return string(msg) == "null"
|
|
||||||
}
|
|
||||||
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
type metadata struct{ any }
|
|
||||||
type metadataNull struct{}
|
|
||||||
type metadataExtraFields map[string]any
|
|
||||||
|
|
||||||
func (m *metadata) setMetadata(override any) {
|
|
||||||
if override == nil {
|
|
||||||
m.any = metadataNull{}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
m.any = override
|
|
||||||
}
|
|
||||||
88
vendor/github.com/openai/openai-go/packages/respjson/respjson.go
generated
vendored
88
vendor/github.com/openai/openai-go/packages/respjson/respjson.go
generated
vendored
@@ -1,88 +0,0 @@
|
|||||||
package respjson
|
|
||||||
|
|
||||||
// A Field provides metadata to indicate the presence of a value.
|
|
||||||
//
|
|
||||||
// Use [Field.Valid] to check if an optional value was null or omitted.
|
|
||||||
//
|
|
||||||
// A Field will always occur in the following structure, where it
|
|
||||||
// mirrors the original field in it's parent struct:
|
|
||||||
//
|
|
||||||
// type ExampleObject struct {
|
|
||||||
// Foo bool `json:"foo"`
|
|
||||||
// Bar int `json:"bar"`
|
|
||||||
// // ...
|
|
||||||
//
|
|
||||||
// // JSON provides metadata about the object.
|
|
||||||
// JSON struct {
|
|
||||||
// Foo Field
|
|
||||||
// Bar Field
|
|
||||||
// // ...
|
|
||||||
// } `json:"-"`
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// To differentiate a "nullish" value from the zero value,
|
|
||||||
// use the [Field.Valid] method.
|
|
||||||
//
|
|
||||||
// if !example.JSON.Foo.Valid() {
|
|
||||||
// println("Foo is null or omitted")
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// if example.Foo {
|
|
||||||
// println("Foo is true")
|
|
||||||
// } else {
|
|
||||||
// println("Foo is false")
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// To differentiate if a field was omitted or the JSON value "null",
|
|
||||||
// use the [Field.Raw] method.
|
|
||||||
//
|
|
||||||
// if example.JSON.Foo.Raw() == "null" {
|
|
||||||
// println("Foo is null")
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// if example.JSON.Foo.Raw() == "" {
|
|
||||||
// println("Foo was omitted")
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// Otherwise, if the field was invalid and couldn't be marshalled successfully,
|
|
||||||
// [Field.Valid] will be false and [Field.Raw] will not be empty.
|
|
||||||
type Field struct {
|
|
||||||
status
|
|
||||||
raw string
|
|
||||||
}
|
|
||||||
|
|
||||||
const (
|
|
||||||
omitted status = iota
|
|
||||||
null
|
|
||||||
invalid
|
|
||||||
valid
|
|
||||||
)
|
|
||||||
|
|
||||||
type status int8
|
|
||||||
|
|
||||||
// Valid returns true if the parent field was set.
|
|
||||||
// Valid returns false if the value doesn't exist, is JSON null, or
|
|
||||||
// is an unexpected type.
|
|
||||||
func (j Field) Valid() bool { return j.status > invalid }
|
|
||||||
|
|
||||||
const Null string = "null"
|
|
||||||
const Omitted string = ""
|
|
||||||
|
|
||||||
// Returns the raw JSON value of the field.
|
|
||||||
func (j Field) Raw() string {
|
|
||||||
if j.status == omitted {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
return j.raw
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewField(raw string) Field {
|
|
||||||
if raw == "null" {
|
|
||||||
return Field{status: null, raw: Null}
|
|
||||||
}
|
|
||||||
return Field{status: valid, raw: raw}
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewInvalidField(raw string) Field {
|
|
||||||
return Field{status: invalid, raw: raw}
|
|
||||||
}
|
|
||||||
217
vendor/github.com/openai/openai-go/packages/ssestream/ssestream.go
generated
vendored
217
vendor/github.com/openai/openai-go/packages/ssestream/ssestream.go
generated
vendored
@@ -1,217 +0,0 @@
|
|||||||
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
||||||
|
|
||||||
package ssestream
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bufio"
|
|
||||||
"bytes"
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"net/http"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/tidwall/gjson"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Decoder interface {
|
|
||||||
Event() Event
|
|
||||||
Next() bool
|
|
||||||
Close() error
|
|
||||||
Err() error
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewDecoder(res *http.Response) Decoder {
|
|
||||||
if res == nil || res.Body == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var decoder Decoder
|
|
||||||
contentType := res.Header.Get("content-type")
|
|
||||||
if t, ok := decoderTypes[contentType]; ok {
|
|
||||||
decoder = t(res.Body)
|
|
||||||
} else {
|
|
||||||
scn := bufio.NewScanner(res.Body)
|
|
||||||
scn.Buffer(nil, bufio.MaxScanTokenSize<<9)
|
|
||||||
decoder = &eventStreamDecoder{rc: res.Body, scn: scn}
|
|
||||||
}
|
|
||||||
return decoder
|
|
||||||
}
|
|
||||||
|
|
||||||
var decoderTypes = map[string](func(io.ReadCloser) Decoder){}
|
|
||||||
|
|
||||||
func RegisterDecoder(contentType string, decoder func(io.ReadCloser) Decoder) {
|
|
||||||
decoderTypes[strings.ToLower(contentType)] = decoder
|
|
||||||
}
|
|
||||||
|
|
||||||
type Event struct {
|
|
||||||
Type string
|
|
||||||
Data []byte
|
|
||||||
}
|
|
||||||
|
|
||||||
// A base implementation of a Decoder for text/event-stream.
|
|
||||||
type eventStreamDecoder struct {
|
|
||||||
evt Event
|
|
||||||
rc io.ReadCloser
|
|
||||||
scn *bufio.Scanner
|
|
||||||
err error
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *eventStreamDecoder) Next() bool {
|
|
||||||
if s.err != nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
event := ""
|
|
||||||
data := bytes.NewBuffer(nil)
|
|
||||||
|
|
||||||
for s.scn.Scan() {
|
|
||||||
txt := s.scn.Bytes()
|
|
||||||
|
|
||||||
// Dispatch event on an empty line
|
|
||||||
if len(txt) == 0 {
|
|
||||||
s.evt = Event{
|
|
||||||
Type: event,
|
|
||||||
Data: data.Bytes(),
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
// Split a string like "event: bar" into name="event" and value=" bar".
|
|
||||||
name, value, _ := bytes.Cut(txt, []byte(":"))
|
|
||||||
|
|
||||||
// Consume an optional space after the colon if it exists.
|
|
||||||
if len(value) > 0 && value[0] == ' ' {
|
|
||||||
value = value[1:]
|
|
||||||
}
|
|
||||||
|
|
||||||
switch string(name) {
|
|
||||||
case "":
|
|
||||||
// An empty line in the for ": something" is a comment and should be ignored.
|
|
||||||
continue
|
|
||||||
case "event":
|
|
||||||
event = string(value)
|
|
||||||
case "data":
|
|
||||||
_, s.err = data.Write(value)
|
|
||||||
if s.err != nil {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
_, s.err = data.WriteRune('\n')
|
|
||||||
if s.err != nil {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if s.scn.Err() != nil {
|
|
||||||
s.err = s.scn.Err()
|
|
||||||
}
|
|
||||||
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *eventStreamDecoder) Event() Event {
|
|
||||||
return s.evt
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *eventStreamDecoder) Close() error {
|
|
||||||
return s.rc.Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *eventStreamDecoder) Err() error {
|
|
||||||
return s.err
|
|
||||||
}
|
|
||||||
|
|
||||||
type Stream[T any] struct {
|
|
||||||
decoder Decoder
|
|
||||||
cur T
|
|
||||||
err error
|
|
||||||
done bool
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewStream[T any](decoder Decoder, err error) *Stream[T] {
|
|
||||||
return &Stream[T]{
|
|
||||||
decoder: decoder,
|
|
||||||
err: err,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Next returns false if the stream has ended or an error occurred.
|
|
||||||
// Call Stream.Current() to get the current value.
|
|
||||||
// Call Stream.Err() to get the error.
|
|
||||||
//
|
|
||||||
// for stream.Next() {
|
|
||||||
// data := stream.Current()
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// if stream.Err() != nil {
|
|
||||||
// ...
|
|
||||||
// }
|
|
||||||
func (s *Stream[T]) Next() bool {
|
|
||||||
if s.err != nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
for s.decoder.Next() {
|
|
||||||
if s.done {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
if bytes.HasPrefix(s.decoder.Event().Data, []byte("[DONE]")) {
|
|
||||||
// In this case we don't break because we still want to iterate through the full stream.
|
|
||||||
s.done = true
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
var nxt T
|
|
||||||
|
|
||||||
if s.decoder.Event().Type == "" || !strings.HasPrefix(s.decoder.Event().Type, "thread.") {
|
|
||||||
ep := gjson.GetBytes(s.decoder.Event().Data, "error")
|
|
||||||
if ep.Exists() {
|
|
||||||
s.err = fmt.Errorf("received error while streaming: %s", ep.String())
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
s.err = json.Unmarshal(s.decoder.Event().Data, &nxt)
|
|
||||||
if s.err != nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
s.cur = nxt
|
|
||||||
return true
|
|
||||||
} else {
|
|
||||||
ep := gjson.GetBytes(s.decoder.Event().Data, "error")
|
|
||||||
if ep.Exists() {
|
|
||||||
s.err = fmt.Errorf("received error while streaming: %s", ep.String())
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
event := s.decoder.Event().Type
|
|
||||||
data := s.decoder.Event().Data
|
|
||||||
s.err = json.Unmarshal([]byte(fmt.Sprintf(`{ "event": %q, "data": %s }`, event, data)), &nxt)
|
|
||||||
if s.err != nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
s.cur = nxt
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// decoder.Next() may be false because of an error
|
|
||||||
s.err = s.decoder.Err()
|
|
||||||
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Stream[T]) Current() T {
|
|
||||||
return s.cur
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Stream[T]) Err() error {
|
|
||||||
return s.err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Stream[T]) Close() error {
|
|
||||||
if s.decoder == nil {
|
|
||||||
// already closed
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return s.decoder.Close()
|
|
||||||
}
|
|
||||||
95
vendor/github.com/openai/openai-go/polling.go
generated
vendored
95
vendor/github.com/openai/openai-go/polling.go
generated
vendored
@@ -1,95 +0,0 @@
|
|||||||
package openai
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"net/http"
|
|
||||||
"strconv"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/openai/openai-go/option"
|
|
||||||
)
|
|
||||||
|
|
||||||
func mkPollingOptions(pollIntervalMs int) []option.RequestOption {
|
|
||||||
options := []option.RequestOption{option.WithHeader("X-Stainless-Poll-Helper", "true")}
|
|
||||||
if pollIntervalMs > 0 {
|
|
||||||
options = append(options, option.WithHeader("X-Stainless-Poll-Interval", fmt.Sprintf("%d", pollIntervalMs)))
|
|
||||||
}
|
|
||||||
return options
|
|
||||||
}
|
|
||||||
|
|
||||||
func getPollInterval(raw *http.Response) (ms int) {
|
|
||||||
if ms, err := strconv.Atoi(raw.Header.Get("openai-poll-after-ms")); err == nil {
|
|
||||||
return ms
|
|
||||||
}
|
|
||||||
return 1000
|
|
||||||
}
|
|
||||||
|
|
||||||
// PollStatus waits until a VectorStoreFile is no longer in an incomplete state and returns it.
|
|
||||||
// Pass 0 as pollIntervalMs to use the default polling interval of 1 second.
|
|
||||||
func (r *VectorStoreFileService) PollStatus(ctx context.Context, vectorStoreID string, fileID string, pollIntervalMs int, opts ...option.RequestOption) (*VectorStoreFile, error) {
|
|
||||||
var raw *http.Response
|
|
||||||
opts = append(opts, mkPollingOptions(pollIntervalMs)...)
|
|
||||||
opts = append(opts, option.WithResponseInto(&raw))
|
|
||||||
for {
|
|
||||||
file, err := r.Get(ctx, fileID, vectorStoreID, opts...)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("vector store file poll: received %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
switch file.Status {
|
|
||||||
case VectorStoreFileStatusInProgress:
|
|
||||||
if pollIntervalMs <= 0 {
|
|
||||||
pollIntervalMs = getPollInterval(raw)
|
|
||||||
}
|
|
||||||
time.Sleep(time.Duration(pollIntervalMs) * time.Millisecond)
|
|
||||||
case VectorStoreFileStatusCancelled,
|
|
||||||
VectorStoreFileStatusCompleted,
|
|
||||||
VectorStoreFileStatusFailed:
|
|
||||||
return file, nil
|
|
||||||
default:
|
|
||||||
return nil, fmt.Errorf("invalid vector store file status during polling: received %s", file.Status)
|
|
||||||
}
|
|
||||||
|
|
||||||
select {
|
|
||||||
case <-ctx.Done():
|
|
||||||
return nil, ctx.Err()
|
|
||||||
default:
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// PollStatus waits until a BetaVectorStoreFileBatch is no longer in an incomplete state and returns it.
|
|
||||||
// Pass 0 as pollIntervalMs to use the default polling interval of 1 second.
|
|
||||||
func (r *VectorStoreFileBatchService) PollStatus(ctx context.Context, vectorStoreID string, batchID string, pollIntervalMs int, opts ...option.RequestOption) (*VectorStoreFileBatch, error) {
|
|
||||||
var raw *http.Response
|
|
||||||
opts = append(opts, option.WithResponseInto(&raw))
|
|
||||||
opts = append(opts, mkPollingOptions(pollIntervalMs)...)
|
|
||||||
for {
|
|
||||||
batch, err := r.Get(ctx, batchID, vectorStoreID, opts...)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("vector store file batch poll: received %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
switch batch.Status {
|
|
||||||
case VectorStoreFileBatchStatusInProgress:
|
|
||||||
if pollIntervalMs <= 0 {
|
|
||||||
pollIntervalMs = getPollInterval(raw)
|
|
||||||
}
|
|
||||||
time.Sleep(time.Duration(pollIntervalMs) * time.Millisecond)
|
|
||||||
case VectorStoreFileBatchStatusCancelled,
|
|
||||||
VectorStoreFileBatchStatusCompleted,
|
|
||||||
VectorStoreFileBatchStatusFailed:
|
|
||||||
return batch, nil
|
|
||||||
default:
|
|
||||||
return nil, fmt.Errorf("invalid vector store file batch status during polling: received %s", batch.Status)
|
|
||||||
}
|
|
||||||
|
|
||||||
select {
|
|
||||||
case <-ctx.Done():
|
|
||||||
return nil, ctx.Err()
|
|
||||||
default:
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
67
vendor/github.com/openai/openai-go/release-please-config.json
generated
vendored
67
vendor/github.com/openai/openai-go/release-please-config.json
generated
vendored
@@ -1,67 +0,0 @@
|
|||||||
{
|
|
||||||
"packages": {
|
|
||||||
".": {}
|
|
||||||
},
|
|
||||||
"$schema": "https://raw.githubusercontent.com/stainless-api/release-please/main/schemas/config.json",
|
|
||||||
"include-v-in-tag": true,
|
|
||||||
"include-component-in-tag": false,
|
|
||||||
"versioning": "prerelease",
|
|
||||||
"prerelease": true,
|
|
||||||
"bump-minor-pre-major": true,
|
|
||||||
"bump-patch-for-minor-pre-major": false,
|
|
||||||
"pull-request-header": "Automated Release PR",
|
|
||||||
"pull-request-title-pattern": "release: ${version}",
|
|
||||||
"changelog-sections": [
|
|
||||||
{
|
|
||||||
"type": "feat",
|
|
||||||
"section": "Features"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "fix",
|
|
||||||
"section": "Bug Fixes"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "perf",
|
|
||||||
"section": "Performance Improvements"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "revert",
|
|
||||||
"section": "Reverts"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "chore",
|
|
||||||
"section": "Chores"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "docs",
|
|
||||||
"section": "Documentation"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "style",
|
|
||||||
"section": "Styles"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "refactor",
|
|
||||||
"section": "Refactors"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "test",
|
|
||||||
"section": "Tests",
|
|
||||||
"hidden": true
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "build",
|
|
||||||
"section": "Build System"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "ci",
|
|
||||||
"section": "Continuous Integration",
|
|
||||||
"hidden": true
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"release-type": "go",
|
|
||||||
"extra-files": [
|
|
||||||
"internal/version.go",
|
|
||||||
"README.md"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user