aimlapi

package
v0.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 17, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultPartnerID   = "part_62yQoGYDq4Yqnrj2R1iGrDNJ"
	DefaultPartnerName = "Gitlawb"
	PartnerHeaderName  = "X-AIMLAPI-Partner-ID"
	// DefaultReturnURL is the https fallback the browser is sent to after the
	// checkout / OAuth consent finishes when no frontend base is known. It must be
	// a real web page the browser can open — NOT a custom scheme like
	// zero://aimlapi/complete, which fails with "the scheme does not have a
	// registered handler" because the CLI registers no OS protocol handler. The
	// CLI learns of success by polling; this URL is purely the browser's landing.
	DefaultReturnURL = "https://aimlapi.com/app"
	DefaultModel     = "anthropic/claude-sonnet-5"

	MinAmountUSDMinor     = 2000
	MaxAmountUSDMinor     = 1000000
	DefaultAmountUSDMinor = 2500
)
View Source
const (
	// Path A — existing API key. Pick-path prompt + option labels.
	MsgAPIKeyInputPrompt = "Enter your aimlapi.com key."
	MsgAPIKeyInvalid     = "API key is invalid. Please make sure you enter a valid aimlapi.com key."
	MsgPickPathPrompt    = "Do you have aimlapi.com key?"
	MsgPickPathHaveKey   = "I already have aimlapi.com key"
	MsgPickPathHaveHint  = "Proceed to paste the key"
	MsgPickPathNewUser   = "I am a new user"
	MsgPickPathNewHint   = "One click set up"
	// Path B — email.
	MsgEnterEmail           = "Enter your email.\nTo access aimlapi.com dashboard."
	MsgEmailInvalid         = "Email format is incorrect."
	MsgAccountActionInvalid = "aimlapi.com returned an unsupported account action. Please try again."
	// %s = email
	MsgCodeSent      = "We sent a 6-digit code to %s.\nEnter it below to continue."
	MsgCodeIncorrect = "Code you've entered is incorrect."

	// Balance check.
	MsgLowBalance     = "Your aimlapi.com balance is running low.\nIt is recommended to top up your balance."
	MsgEverythingRuns = "Everything is ready."
	// Low-balance choices (spec wording).
	MsgLowBalanceTopUp = "Sure, let's do that"
	MsgLowBalanceSkip  = "I'll skip topping up the balance for now"

	// Top-up workflow.
	MsgTopUpPrompt    = "Add credits.\nEnter an amount (min $20)."
	MsgAmountRequired = "Please enter a top-up amount."
	// %s = checkout URL
	MsgTopUpBrowserFallback = "If the browser did not open automatically please use this link to top up your account: %s"
	MsgTopUpFailed          = "Top up failed. Please try again."
	MsgTopUpSuccess         = "Top-up successful."

	// Success — key delivered.
	// %s = amount in dollars (e.g. "25")
	MsgTopUpAddedFmt = "$%s has been added to your balance."
	// %s = email
	MsgSuccessMagicLink = "We've emailed you a magic link to %s. Use it to access your aimlapi.com account and review your usage and balance."
)

Variables

This section is empty.

Functions

func BuildPartnerCheckoutReturnURLs

func BuildPartnerCheckoutReturnURLs(appBaseURL string, sessionToken string) (successURL string, cancelURL string)

func BuildPartnerReturnURL

func BuildPartnerReturnURL(frontendBaseURL string) string

BuildPartnerReturnURL returns the https page the browser is sent back to once the partner checkout or OAuth consent completes — the aimlapi web app the user opened the flow from. frontendBaseURL is normally endpoints.VerificationBaseURL (the front that hosts the login/consent page), so the return follows the same environment. AIMLAPI_RETURN_URL overrides it outright; an empty base falls back to DefaultReturnURL. It is deliberately NOT a custom scheme (zero://…): no browser can hand a custom scheme off without an OS-registered handler, which a CLI does not install.

func NewPaymentSessionID

func NewPaymentSessionID() (string, error)

NewPaymentSessionID returns a random UUIDv4-shaped idempotency id for a top-up. The caller generates it once per top-up intent and reuses it on retry so the backend (and Stripe) coalesce retries onto the same checkout instead of a second charge.

func ParseAmountUSD

func ParseAmountUSD(value string) (int, error)

ParseAmountUSD parses a dollar string into USD minor units (cents), enforcing the min/max top-up bounds. An empty value yields the default amount.

func ResolvePartnerID

func ResolvePartnerID(explicit string) string

ResolvePartnerID applies the same explicit-option, environment, and default precedence everywhere partner attribution is used. Keeping checkout creation and saved inference profiles on one resolver prevents them from attributing the same user to different partners.

func ValidEmail

func ValidEmail(value string) bool

ValidEmail performs the lightweight validation used before starting the passwordless onboarding request.

func WithResolvedPartnerHeader

func WithResolvedPartnerHeader(headers map[string]string) map[string]string

WithResolvedPartnerHeader returns a copy with the effective partner ID set. Header matching is case-insensitive so an existing spelling is replaced rather than duplicated. Callers remain responsible for applying catalog attribution only to the canonical AIMLAPI endpoint.

Types

type APIError

type APIError struct {
	Message string
	Status  int
	Body    string
}

APIError is a non-2xx HTTP response from the aimlapi.com API. Status carries the code so callers can branch (e.g. 401 = bad key, 5xx = retryable).

func (APIError) Error

func (e APIError) Error() string

Error renders the method, endpoint, status, and (when present) the response body.

type AuthResult

type AuthResult struct {
	Token string `json:"token"`
	Exp   int64  `json:"exp"`
}

AuthResult is the bearer token minted by a passwordless sign-in / sign-up.

type BalanceResult

type BalanceResult struct {
	Balance             float64 `json:"balance"`
	LowBalance          bool    `json:"lowBalance"`
	LowBalanceThreshold float64 `json:"lowBalanceThreshold"`
}

BalanceResult is the wallet balance returned by GetBalance, with the backend's low-balance flag and threshold.

type CheckResult

type CheckResult struct {
	// "sign-in" (account exists) or "sign-up" (no account yet).
	Action   string  `json:"action"`
	Provider *string `json:"provider"`
}

CheckResult reports whether an email already has an account, driving the sign-in vs sign-up branch of the onboarding flow.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client talks to the aimlapi.com auth, app, and inference APIs for the onboarding and partner-checkout top-up flows.

func NewClient

func NewClient(endpoints Endpoints, httpClient *http.Client) *Client

func (*Client) CheckAccount

func (c *Client) CheckAccount(ctx context.Context, email string) (CheckResult, error)

CheckAccount reports whether an email already has an aimlapi.com account (Action "sign-in") or not ("sign-up").

func (*Client) CreateKey

func (c *Client) CreateKey(ctx context.Context, bearer string, name string) (CreatedKey, error)

CreateKey mints a fresh API key for a session-holding user.

func (*Client) CreatePasswordlessAccount

func (c *Client) CreatePasswordlessAccount(ctx context.Context, email string) (AuthResult, error)

CreatePasswordlessAccount registers a new email-only account and returns its session bearer token.

func (*Client) CreateSession

func (c *Client) CreateSession(ctx context.Context, partnerID string, partnerName string, returnURL string) (PartnerCheckoutSession, error)

CreateSession opens a partner-checkout session attributed to partnerID; the returned SessionToken addresses it on the pay/exchange/poll calls.

func (*Client) Exchange

func (c *Client) Exchange(ctx context.Context, bearer string, sessionToken string) (ExchangeResult, error)

Exchange converts a paid session into a freshly minted API key (new-account flow).

func (*Client) GetBalance

func (c *Client) GetBalance(ctx context.Context, apiKey string) (BalanceResult, error)

GetBalance doubles as key validation: a 401 means the key is invalid, a 2xx returns the wallet balance. Auth is the raw API key itself.

func (*Client) GetSession

func (c *Client) GetSession(ctx context.Context, sessionToken string) (PartnerCheckoutSession, error)

GetSession fetches the current state of a partner-checkout session; used to poll for payment completion.

func (*Client) Pay

func (c *Client) Pay(ctx context.Context, bearer string, sessionToken string, amountUSDMinor int, paymentSessionID string, method PaymentMethod, successURL string, cancelURL string, autoTopUp bool) (PayResult, error)

Pay initiates payment for a session and returns the hosted checkout URL. autoTopUp enrolls the account in automatic top-up at checkout time.

func (*Client) SendSignInCode

func (c *Client) SendSignInCode(ctx context.Context, email string) error

SendSignInCode emails a 6-digit sign-in code to an existing account.

func (*Client) TopUpByKey

func (c *Client) TopUpByKey(ctx context.Context, apiKey string, req TopUpByKeyRequest) (TopUpByKeyResult, error)

TopUpByKey funds a partner-checkout session using the raw API key that owns the account (Path A / env key), returning the hosted checkout. It binds the session to the key's account server-side, so no email session is needed and no key is exchanged. req.PaymentSessionID makes a retry idempotent (same id → same checkout, never a second charge).

func (*Client) VerifySignInCode

func (c *Client) VerifySignInCode(ctx context.Context, email string, code string) (AuthResult, error)

VerifySignInCode exchanges an emailed code for a session bearer token.

type CreatedKey

type CreatedKey struct {
	Key string `json:"key"`
	ID  string `json:"id"`
}

CreatedKey is an API key minted by CreateKey.

type Endpoints

type Endpoints struct {
	AuthBaseURL      string
	AppBaseURL       string
	InferenceBaseURL string
	PayBaseURL       string
	// VerificationBaseURL is the aimlapi web-app frontend base. The browser is sent
	// back here after the partner checkout completes (see BuildPartnerReturnURL), so
	// it must point at the same environment's front as the one the CLI is talking to
	// to land the user there. Empty falls back to DefaultReturnURL.
	VerificationBaseURL string
}

func ResolveEndpoints

func ResolveEndpoints() Endpoints

type ExchangeResult

type ExchangeResult struct {
	APIKey   string `json:"apiKey"`
	APIKeyID string `json:"apiKeyId"`
}

ExchangeResult holds the API key minted when a paid session is exchanged.

type PartnerCheckoutSession

type PartnerCheckoutSession struct {
	ID             string        `json:"id"`
	SessionToken   string        `json:"sessionToken"`
	PartnerID      string        `json:"partnerId"`
	PartnerName    *string       `json:"partnerName"`
	UserID         *int64        `json:"userId"`
	AmountUSDMinor *int64        `json:"amountUsdMinor"`
	Status         SessionStatus `json:"status"`
	IssuedKeyID    *string       `json:"issuedKeyId"`
	ReturnURL      *string       `json:"returnUrl"`
}

PartnerCheckoutSession is a partner-attributed top-up session; its SessionToken addresses it on later pay/exchange/poll calls.

type PayResult

type PayResult struct {
	Checkout        PaymentSession         `json:"checkout"`
	PartnerCheckout PartnerCheckoutSession `json:"partnerCheckout"`
}

PayResult pairs the hosted checkout with the updated partner-checkout session returned when a top-up payment is initiated.

type PaymentMethod

type PaymentMethod string

PaymentMethod selects how a partner-checkout top-up is paid for.

const (
	PaymentMethodCard   PaymentMethod = "card"
	PaymentMethodCrypto PaymentMethod = "crypto"
)

type PaymentSession

type PaymentSession struct {
	ProviderSessionID string `json:"providerSessionId"`
	PayURL            string `json:"payUrl"`
}

PaymentSession is the hosted payment-provider checkout; PayURL is the page the user opens to pay.

type ProvisionedKey

type ProvisionedKey struct {
	APIKey   string
	APIKeyID string
	BaseURL  string
	Model    string
}

ProvisionedKey is the outcome of a top-up: the (optionally minted) API key plus the inference base URL and model to write into the provider profile.

func StreamTopUp

func StreamTopUp(ctx context.Context, options StreamTopUpOptions) (ProvisionedKey, error)

StreamTopUp performs the browser-checkout top-up and reports progress via OnStatus.

func StreamTopUpByKey

func StreamTopUpByKey(ctx context.Context, options StreamTopUpByKeyOptions) (ProvisionedKey, error)

StreamTopUpByKey funds the account behind APIKey via the hosted checkout and reports progress through OnStatus. It returns an empty ProvisionedKey: the pasted/env key is unchanged, only the balance grows.

type SessionStatus

type SessionStatus string

SessionStatus is the lifecycle state of a partner-checkout session, as reported by the aimlapi.com backend while polling for payment.

const (
	SessionStatusPendingAuth    SessionStatus = "pending_auth"
	SessionStatusPendingPayment SessionStatus = "pending_payment"
	SessionStatusPaid           SessionStatus = "paid"
	SessionStatusExchanging     SessionStatus = "exchanging"
	SessionStatusExchanged      SessionStatus = "exchanged"
	SessionStatusCancelled      SessionStatus = "cancelled"
	SessionStatusExpired        SessionStatus = "expired"
	SessionStatusFailed         SessionStatus = "failed"
)

type Status

type Status string

Status is a progress phase reported by StreamTopUp through its OnStatus callback.

const (
	StatusCreatingSession Status = "creating-session"
	StatusOpeningCheckout Status = "opening-checkout"
	StatusWaitingPayment  Status = "waiting-payment"
	StatusProvisioningKey Status = "provisioning-key"
)

type StreamTopUpByKeyOptions

type StreamTopUpByKeyOptions struct {
	APIKey           string // raw key that owns the account (required)
	AmountUSD        string // dollars; parsed via ParseAmountUSD (min $20)
	InferenceBaseURL string // validated key endpoint; empty uses ResolveEndpoints
	AutoTopUp        bool   // enroll the account in automatic top-up at checkout time
	PartnerID        string
	PartnerName      string
	NoOpen           bool

	// ResumeSessionToken resumes an existing partner-checkout session instead of
	// opening a new one. PaymentSessionID is the idempotency handle carried across
	// retries so a re-issued pay returns the same checkout, never a second charge.
	ResumeSessionToken string
	PaymentSessionID   string // required; generate once via NewPaymentSessionID, reuse on retry

	HTTPClient  *http.Client
	OpenBrowser func(string) error
	OnStatus    func(Status, string)
	OnSession   func(sessionToken string)
}

StreamTopUpByKeyOptions drives a top-up funded with the API key that already owns the account (Path A pasted key, or AIMLAPI_API_KEY). Unlike StreamTopUp it needs no email session and never exchanges a key — the caller already holds one, so it only funds the wallet: create-session → pay-by-key → wait-for-payment.

type StreamTopUpOptions

type StreamTopUpOptions struct {
	SessionToken string // user session bearer (required)
	AmountUSD    string // dollars; parsed via ParseAmountUSD (min $20)
	// InferenceBaseURL pins key-bound billing and the returned provider profile to
	// the endpoint that validated the credential. Empty uses ResolveEndpoints.
	InferenceBaseURL string
	Method           PaymentMethod
	AutoTopUp        bool // enroll the account in automatic top-up at checkout time
	Exchange         bool // exchange the paid session into a new key (new accounts)
	Model            string
	PartnerID        string
	PartnerName      string
	NoOpen           bool

	// ResumeSessionToken, when set, resumes that partner-checkout session instead
	// of opening a new one, so a retry after an ambiguous failure (a lost Pay/
	// Exchange response) can never double-charge or strand an already-paid session.
	ResumeSessionToken string
	// PaymentSessionID is generated once per amount/auto-top-up intent and reused
	// on retry so an ambiguous Pay response cannot create a second checkout.
	PaymentSessionID string

	HTTPClient  *http.Client
	OpenBrowser func(string) error
	OnStatus    func(Status, string)
	// OnSession reports the partner-checkout session token the moment it exists (a
	// fresh CreateSession, or the resumed one), so the caller can retain it and
	// resume on a later failure. It fires with "" when the session is dead and the
	// retained token should be dropped (a fresh run must start over).
	OnSession func(sessionToken string)
}

StreamTopUpOptions drives a session-based partner-checkout top-up for the interactive (TUI) onboarding. The caller already holds a user session — obtained from an email-code sign-in (Path B existing) or a passwordless new account (Path B sign-up) — so this skips authentication and runs create-session → pay → wait-for-payment, optionally exchanging the paid session into a fresh key (new accounts) versus keeping the caller's key.

type TopUpByKeyRequest

type TopUpByKeyRequest struct {
	SessionToken     string
	AmountUSDMinor   int
	PaymentSessionID string // idempotency: same id → same checkout, never a second charge
	AutoTopUp        bool   // enroll the account in automatic top-up at checkout (card, saved off-session)
	SuccessURL       string
	CancelURL        string
}

TopUpByKeyRequest funds a partner-checkout session with the API key that owns the account (Path A / env key), instead of an email session.

type TopUpByKeyResult

type TopUpByKeyResult struct {
	Checkout PaymentSession `json:"checkout"`
}

TopUpByKeyResult is the hosted checkout returned by TopUpByKey.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL