together

package module
v0.0.1-alpha.1 Latest Latest
Warning

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

Go to latest
Published: Jun 13, 2024 License: Apache-2.0 Imports: 13 Imported by: 5 modules, 2 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Together Go API Library

Go Reference

The Together Go library provides convenient access to the Together REST API from applications written in Go. The full API of this library can be found in api.md.

It is generated with Stainless.

Installation

import (
	"github.com/togethercomputer/together-go" // imported as together
)

Or to pin the version:

go get -u 'github.com/togethercomputer/together-go@v0.0.1-alpha.1'

Requirements

This library requires Go 1.18+.

Usage

The full API of this library can be found in api.md.

package main

import (
	"context"
	"fmt"

	"github.com/togethercomputer/together-go"
	"github.com/togethercomputer/together-go/option"
)

func main() {
	client := together.NewClient(
		option.WithAPIKey("My API Key"), // defaults to os.LookupEnv("TOGETHER_API_KEY")
	)
	chatCompletion, err := client.Chat.Completions.New(context.TODO(), together.ChatCompletionNewParamsChatCompletionRequest{
		Messages: together.F([]together.ChatCompletionNewParamsChatCompletionRequestMessage{{
			Role:    together.F(together.ChatCompletionNewParamsChatCompletionRequestMessagesRoleUser),
			Content: together.F("Say this is a test!"),
		}}),
		Model: together.F("mistralai/Mixtral-8x7B-Instruct-v0.1"),
	})
	if err != nil {
		panic(err.Error())
	}
	fmt.Printf("%+v\n", chatCompletion.Choices)
}

Request fields

All request parameters are wrapped in a generic Field type, which we use to distinguish zero values from null or omitted fields.

This prevents accidentally sending a zero value if you forget a required parameter, and enables explicitly sending null, false, '', or 0 on optional parameters. Any field not specified is not sent.

To construct fields with values, use the helpers String(), Int(), Float(), or most commonly, the generic F[T](). To send a null, use Null[T](), and to send a nonconforming value, use Raw[T](any). For example:

params := FooParams{
	Name: together.F("hello"),

	// Explicitly send `"description": null`
	Description: together.Null[string](),

	Point: together.F(together.Point{
		X: together.Int(0),
		Y: together.Int(1),

		// In cases where the API specifies a given type,
		// but you want to send something else, use `Raw`:
		Z: together.Raw[int64](0.01), // sends a float
	}),
}
Response objects

All fields in response structs are value types (not pointers or wrappers).

If a given field is null, not present, or invalid, the corresponding field will simply be its zero value.

All response structs also include a special JSON field, containing more detailed information about each property, which you can use like so:

if res.Name == "" {
	// true if `"name"` is either not present or explicitly null
	res.JSON.Name.IsNull()

	// true if the `"name"` key was not present in the repsonse JSON at all
	res.JSON.Name.IsMissing()

	// When the API returns data that cannot be coerced to the expected type:
	if res.JSON.Name.IsInvalid() {
		raw := res.JSON.Name.Raw()

		legacyName := struct{
			First string `json:"first"`
			Last  string `json:"last"`
		}{}
		json.Unmarshal([]byte(raw), &legacyName)
		name = legacyName.First + " " + legacyName.Last
	}
}

These .JSON structs also include an Extras 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.

body := res.JSON.ExtraFields["my_unexpected_field"].Raw()
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:

client := together.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"}),
)

See the full list of request options.

Pagination

This library provides some conveniences for working with paginated list endpoints.

You can use .ListAutoPaging() methods to iterate through items across all pages:

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.:

Errors

When the API returns a non-success status code, we return an error with type *together.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:

_, err := client.Chat.Completions.New(context.TODO(), together.ChatCompletionNewParamsChatCompletionRequest{
	Messages: together.F([]together.ChatCompletionNewParamsChatCompletionRequestMessage{{
		Role:    together.F(together.ChatCompletionNewParamsChatCompletionRequestMessagesRoleUser),
		Content: together.F("Say this is a test"),
	}}),
	Model: together.F("mistralai/Mixtral-8x7B-Instruct-v0.1"),
})
if err != nil {
	var apierr *together.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 "/chat/completions": 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, the context timeout does not start over. To set a per-retry timeout, use option.WithRequestTimeout().

// 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,
	together.ChatCompletionNewParamsChatCompletionRequest{
		Messages: together.F([]together.ChatCompletionNewParamsChatCompletionRequestMessage{{
			Role:    together.F(together.ChatCompletionNewParamsChatCompletionRequestMessagesRoleUser),
			Content: together.F("Say this is a test"),
		}}),
		Model: together.F("mistralai/Mixtral-8x7B-Instruct-v0.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 param.Field[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 together.FileParam(reader io.Reader, filename string, contentType string) which can be used to wrap any io.Reader with the appropriate file name and content type.

Retries

Certain errors will be automatically retried 5 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:

// Configure the default for all requests:
client := together.NewClient(
	option.WithMaxRetries(0), // default is 2
)

// Override per-request:
client.Chat.Completions.New(
	context.TODO(),
	together.ChatCompletionNewParamsChatCompletionRequest{
		Messages: together.F([]together.ChatCompletionNewParamsChatCompletionRequestMessage{{
			Role:    together.F(together.ChatCompletionNewParamsChatCompletionRequestMessagesRoleUser),
			Content: together.F("Say this is a test"),
		}}),
		Model: together.F("mistralai/Mixtral-8x7B-Instruct-v0.1"),
	},
	option.WithMaxRetries(5),
)
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.

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]interface{}

    // 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.

params := FooNewParams{
    ID:   together.F("id_xxxx"),
    Data: together.F(FooNewParamsData{
        FirstName: together.F("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.

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 := together.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.

Semantic versioning

This package generally follows SemVer 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 with questions, bugs, or suggestions.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Bool

func Bool(value bool) param.Field[bool]

Bool is a param field helper which helps specify bools.

func F

func F[T any](value T) param.Field[T]

F is a param field helper used to initialize a param.Field generic struct. This helps specify null, zero values, and overrides, as well as normal values. You can read more about this in our README.

func FileParam

func FileParam(reader io.Reader, filename string, contentType string) param.Field[io.Reader]

FileParam is a param field helper which helps files with a mime content-type.

func Float

func Float(value float64) param.Field[float64]

Float is a param field helper which helps specify floats.

func Int

func Int(value int64) param.Field[int64]

Int is a param field helper which helps specify integers. This is particularly helpful when specifying integer constants for fields.

func Null

func Null[T any]() param.Field[T]

Null is a param field helper which explicitly sends null to the API.

func Raw

func Raw[T any](value any) param.Field[T]

Raw is a param field helper for specifying values for fields when the type you are looking to send is different from the type that is specified in the SDK. For example, if the type of the field is an integer, but you want to send a float, you could do that by setting the corresponding field with Raw[int](0.5).

func String

func String(value string) param.Field[string]

String is a param field helper which helps specify strings.

Types

type ChatCompletion

type ChatCompletion struct {
	ID      string                 `json:"id"`
	Choices []ChatCompletionChoice `json:"choices"`
	Created int64                  `json:"created"`
	Model   string                 `json:"model"`
	Object  ChatCompletionObject   `json:"object"`
	Usage   ChatCompletionUsage    `json:"usage,nullable"`
	JSON    chatCompletionJSON     `json:"-"`
}

func (*ChatCompletion) UnmarshalJSON

func (r *ChatCompletion) UnmarshalJSON(data []byte) (err error)

type ChatCompletionChoice

type ChatCompletionChoice struct {
	FinishReason ChatCompletionChoicesFinishReason `json:"finish_reason"`
	Logprobs     LogProbs                          `json:"logprobs,nullable"`
	Message      ChatCompletionChoicesMessage      `json:"message"`
	JSON         chatCompletionChoiceJSON          `json:"-"`
}

func (*ChatCompletionChoice) UnmarshalJSON

func (r *ChatCompletionChoice) UnmarshalJSON(data []byte) (err error)

type ChatCompletionChoicesFinishReason

type ChatCompletionChoicesFinishReason string
const (
	ChatCompletionChoicesFinishReasonStop      ChatCompletionChoicesFinishReason = "stop"
	ChatCompletionChoicesFinishReasonEos       ChatCompletionChoicesFinishReason = "eos"
	ChatCompletionChoicesFinishReasonLength    ChatCompletionChoicesFinishReason = "length"
	ChatCompletionChoicesFinishReasonToolCalls ChatCompletionChoicesFinishReason = "tool_calls"
)

func (ChatCompletionChoicesFinishReason) IsKnown

type ChatCompletionChoicesMessage

type ChatCompletionChoicesMessage struct {
	Content string                           `json:"content"`
	Role    string                           `json:"role"`
	JSON    chatCompletionChoicesMessageJSON `json:"-"`
}

func (*ChatCompletionChoicesMessage) UnmarshalJSON

func (r *ChatCompletionChoicesMessage) UnmarshalJSON(data []byte) (err error)

type ChatCompletionChunk

type ChatCompletionChunk struct {
	ID           string                          `json:"id,required"`
	Token        ChatCompletionChunkToken        `json:"token,required"`
	Choices      []ChatCompletionChunkChoice     `json:"choices,required"`
	Created      int64                           `json:"created,required"`
	Object       ChatCompletionChunkObject       `json:"object,required"`
	FinishReason ChatCompletionChunkFinishReason `json:"finish_reason,nullable"`
	Usage        ChatCompletionUsage             `json:"usage,nullable"`
	JSON         chatCompletionChunkJSON         `json:"-"`
}

func (*ChatCompletionChunk) UnmarshalJSON

func (r *ChatCompletionChunk) UnmarshalJSON(data []byte) (err error)

type ChatCompletionChunkChoice

type ChatCompletionChunkChoice struct {
	Delta ChatCompletionChunkChoicesDelta `json:"delta,required"`
	Index int64                           `json:"index,required"`
	JSON  chatCompletionChunkChoiceJSON   `json:"-"`
}

func (*ChatCompletionChunkChoice) UnmarshalJSON

func (r *ChatCompletionChunkChoice) UnmarshalJSON(data []byte) (err error)

type ChatCompletionChunkChoicesDelta

type ChatCompletionChunkChoicesDelta struct {
	Content string                              `json:"content,required"`
	JSON    chatCompletionChunkChoicesDeltaJSON `json:"-"`
}

func (*ChatCompletionChunkChoicesDelta) UnmarshalJSON

func (r *ChatCompletionChunkChoicesDelta) UnmarshalJSON(data []byte) (err error)

type ChatCompletionChunkFinishReason

type ChatCompletionChunkFinishReason string
const (
	ChatCompletionChunkFinishReasonStop      ChatCompletionChunkFinishReason = "stop"
	ChatCompletionChunkFinishReasonEos       ChatCompletionChunkFinishReason = "eos"
	ChatCompletionChunkFinishReasonLength    ChatCompletionChunkFinishReason = "length"
	ChatCompletionChunkFinishReasonToolCalls ChatCompletionChunkFinishReason = "tool_calls"
)

func (ChatCompletionChunkFinishReason) IsKnown

type ChatCompletionChunkObject

type ChatCompletionChunkObject string
const (
	ChatCompletionChunkObjectChatCompletionChunk ChatCompletionChunkObject = "chat.completion.chunk"
)

func (ChatCompletionChunkObject) IsKnown

func (r ChatCompletionChunkObject) IsKnown() bool

type ChatCompletionChunkToken

type ChatCompletionChunkToken struct {
	ID      int64                        `json:"id,required"`
	Logprob float64                      `json:"logprob,required"`
	Special bool                         `json:"special,required"`
	Text    string                       `json:"text,required"`
	JSON    chatCompletionChunkTokenJSON `json:"-"`
}

func (*ChatCompletionChunkToken) UnmarshalJSON

func (r *ChatCompletionChunkToken) UnmarshalJSON(data []byte) (err error)

type ChatCompletionNewParams

type ChatCompletionNewParams interface {
	ImplementsChatCompletionNewParams()
}

This interface is a union satisfied by one of the following: ChatCompletionNewParamsChatCompletionRequest, ChatCompletionNewParamsChatCompletionRequest.

type ChatCompletionNewParamsChatCompletionRequest

type ChatCompletionNewParamsChatCompletionRequest struct {
	// A list of messages comprising the conversation so far.
	Messages param.Field[[]ChatCompletionNewParamsChatCompletionRequestMessage] `json:"messages,required"`
	// The name of the model to query.
	Model param.Field[string] `json:"model,required"`
	// If set, tokens are returned as Server-Sent Events as they are made available.
	// Stream terminates with `data: [DONE]`
	Stream param.Field[ChatCompletionNewParamsChatCompletionRequestStream] `json:"stream,required"`
	// If set, the response will contain the prompt, and will also return prompt
	// logprobs if set with logprobs.
	Echo param.Field[bool] `json:"echo"`
	// The `frequency_penalty` parameter is a number between -2.0 and 2.0 where a
	// positive value will decrease the likelihood of repeating tokens that were
	// mentioned prior.
	FrequencyPenalty param.Field[float64] `json:"frequency_penalty"`
	// The `logit_bias` parameter allows us to adjust the likelihood of specific tokens
	// appearing in the generated output.
	LogitBias param.Field[map[string]interface{}] `json:"logit_bias"`
	// Determines the number of most likely tokens to return at each token position log
	// probabilities to return
	Logprobs param.Field[int64] `json:"logprobs"`
	// The maximum number of tokens to generate.
	MaxTokens param.Field[int64] `json:"max_tokens"`
	// The `min_p` parameter is a number between 0 and 1 and an alternative to
	// `temperature`.
	MinP param.Field[float64] `json:"min_p"`
	// Number of generations to return
	N param.Field[int64] `json:"n"`
	// The `presence_penalty` parameter is a number between -2.0 and 2.0 where a
	// positive value will increase the likelihood of a model talking about new topics.
	PresencePenalty param.Field[float64] `json:"presence_penalty"`
	// A number that controls the diversity of generated text by reducing the
	// likelihood of repeated sequences. Higher values decrease repetition.
	RepetitionPenalty param.Field[float64] `json:"repetition_penalty"`
	// Specifies the format of the response.
	ResponseFormat param.Field[ChatCompletionNewParamsChatCompletionRequestResponseFormat] `json:"response_format"`
	// The name of the safety model to use.
	SafetyModel param.Field[string] `json:"safety_model"`
	// A list of string sequences that will truncate (stop) inference text output.
	Stop param.Field[[]string] `json:"stop"`
	// Determines the degree of randomness in the response.
	Temperature param.Field[float64] `json:"temperature"`
	// The choice of tool to use.
	ToolChoice param.Field[ChatCompletionNewParamsChatCompletionRequestToolChoiceUnion] `json:"tool_choice"`
	// A list of tools to be used in the query.
	Tools param.Field[[]ToolsParam] `json:"tools"`
	// The `top_k` parameter is used to limit the number of choices for the next
	// predicted word or token.
	TopK param.Field[int64] `json:"top_k"`
	// The `top_p` (nucleus) parameter is used to dynamically adjust the number of
	// choices for each predicted token based on the cumulative probabilities.
	TopP param.Field[float64] `json:"top_p"`
}

func (ChatCompletionNewParamsChatCompletionRequest) ImplementsChatCompletionNewParams

func (ChatCompletionNewParamsChatCompletionRequest) ImplementsChatCompletionNewParams()

func (ChatCompletionNewParamsChatCompletionRequest) MarshalJSON

func (r ChatCompletionNewParamsChatCompletionRequest) MarshalJSON() (data []byte, err error)

type ChatCompletionNewParamsChatCompletionRequestMessage

type ChatCompletionNewParamsChatCompletionRequestMessage struct {
	// The contents of the message.
	Content param.Field[string] `json:"content,required"`
	// The role of the messages author. Choice between: system, user, or assistant.
	Role param.Field[ChatCompletionNewParamsChatCompletionRequestMessagesRole] `json:"role,required"`
}

func (ChatCompletionNewParamsChatCompletionRequestMessage) MarshalJSON

func (r ChatCompletionNewParamsChatCompletionRequestMessage) MarshalJSON() (data []byte, err error)

type ChatCompletionNewParamsChatCompletionRequestMessagesRole

type ChatCompletionNewParamsChatCompletionRequestMessagesRole string

The role of the messages author. Choice between: system, user, or assistant.

const (
	ChatCompletionNewParamsChatCompletionRequestMessagesRoleSystem    ChatCompletionNewParamsChatCompletionRequestMessagesRole = "system"
	ChatCompletionNewParamsChatCompletionRequestMessagesRoleUser      ChatCompletionNewParamsChatCompletionRequestMessagesRole = "user"
	ChatCompletionNewParamsChatCompletionRequestMessagesRoleAssistant ChatCompletionNewParamsChatCompletionRequestMessagesRole = "assistant"
)

func (ChatCompletionNewParamsChatCompletionRequestMessagesRole) IsKnown

type ChatCompletionNewParamsChatCompletionRequestResponseFormat

type ChatCompletionNewParamsChatCompletionRequestResponseFormat struct {
	// The schema of the response format.
	Schema param.Field[map[string]string] `json:"schema"`
	// The type of the response format.
	Type param.Field[string] `json:"type"`
}

Specifies the format of the response.

func (ChatCompletionNewParamsChatCompletionRequestResponseFormat) MarshalJSON

type ChatCompletionNewParamsChatCompletionRequestStream

type ChatCompletionNewParamsChatCompletionRequestStream bool

If set, tokens are returned as Server-Sent Events as they are made available. Stream terminates with `data: [DONE]`

const (
	ChatCompletionNewParamsChatCompletionRequestStreamFalse ChatCompletionNewParamsChatCompletionRequestStream = false
)

func (ChatCompletionNewParamsChatCompletionRequestStream) IsKnown

type ChatCompletionNewParamsChatCompletionRequestToolChoice

type ChatCompletionNewParamsChatCompletionRequestToolChoice struct {
	Type     param.Field[string]      `json:"type"`
	Function param.Field[interface{}] `json:"function,required"`
}

The choice of tool to use.

func (ChatCompletionNewParamsChatCompletionRequestToolChoice) ImplementsChatCompletionNewParamsChatCompletionRequestToolChoiceUnion

func (r ChatCompletionNewParamsChatCompletionRequestToolChoice) ImplementsChatCompletionNewParamsChatCompletionRequestToolChoiceUnion()

func (ChatCompletionNewParamsChatCompletionRequestToolChoice) MarshalJSON

type ChatCompletionNewParamsChatCompletionRequestToolChoiceUnion

type ChatCompletionNewParamsChatCompletionRequestToolChoiceUnion interface {
	ImplementsChatCompletionNewParamsChatCompletionRequestToolChoiceUnion()
}

The choice of tool to use.

Satisfied by [shared.UnionString], ToolChoiceParam, ChatCompletionNewParamsChatCompletionRequestToolChoice.

type ChatCompletionObject

type ChatCompletionObject string
const (
	ChatCompletionObjectChatCompletion ChatCompletionObject = "chat.completion"
)

func (ChatCompletionObject) IsKnown

func (r ChatCompletionObject) IsKnown() bool

type ChatCompletionService

type ChatCompletionService struct {
	Options []option.RequestOption
}

ChatCompletionService contains methods and other services that help with interacting with the together API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewChatCompletionService method instead.

func NewChatCompletionService

func NewChatCompletionService(opts ...option.RequestOption) (r *ChatCompletionService)

NewChatCompletionService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*ChatCompletionService) New

Creates a model response for the given chat conversation.

type ChatCompletionUsage

type ChatCompletionUsage struct {
	CompletionTokens int64                   `json:"completion_tokens,required"`
	PromptTokens     int64                   `json:"prompt_tokens,required"`
	TotalTokens      int64                   `json:"total_tokens,required"`
	JSON             chatCompletionUsageJSON `json:"-"`
}

func (*ChatCompletionUsage) UnmarshalJSON

func (r *ChatCompletionUsage) UnmarshalJSON(data []byte) (err error)

type ChatService

type ChatService struct {
	Options     []option.RequestOption
	Completions *ChatCompletionService
}

ChatService contains methods and other services that help with interacting with the together 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.

func NewChatService

func NewChatService(opts ...option.RequestOption) (r *ChatService)

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.

type Client

type Client struct {
	Options     []option.RequestOption
	Chat        *ChatService
	Completions *CompletionService
	Embeddings  *EmbeddingService
	Files       *FileService
	FineTune    *FineTuneService
	Images      *ImageService
	Models      *ModelService
}

Client creates a struct with services and top level methods that help with interacting with the together API. You should not instantiate this client directly, and instead use the NewClient method instead.

func NewClient

func NewClient(opts ...option.RequestOption) (r *Client)

NewClient generates a new client with the default option read from the environment (TOGETHER_API_KEY). 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 (*Client) Delete

func (r *Client) Delete(ctx context.Context, path string, params interface{}, res interface{}, opts ...option.RequestOption) error

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 (*Client) Execute

func (r *Client) Execute(ctx context.Context, method string, path string, params interface{}, res interface{}, opts ...option.RequestOption) error

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 (*Client) Get

func (r *Client) Get(ctx context.Context, path string, params interface{}, res interface{}, opts ...option.RequestOption) error

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 (*Client) Patch

func (r *Client) Patch(ctx context.Context, path string, params interface{}, res interface{}, opts ...option.RequestOption) error

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 (*Client) Post

func (r *Client) Post(ctx context.Context, path string, params interface{}, res interface{}, opts ...option.RequestOption) error

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 (*Client) Put

func (r *Client) Put(ctx context.Context, path string, params interface{}, res interface{}, opts ...option.RequestOption) error

Put makes a PUT request with the given URL, params, and optionally deserializes to a response. See [Execute] documentation on the params and response.

type Completion

type Completion struct {
	ID      string              `json:"id,required"`
	Choices []CompletionChoice  `json:"choices,required"`
	Created int64               `json:"created,required"`
	Model   string              `json:"model,required"`
	Object  CompletionObject    `json:"object,required"`
	Usage   ChatCompletionUsage `json:"usage,required,nullable"`
	Prompt  []CompletionPrompt  `json:"prompt"`
	JSON    completionJSON      `json:"-"`
}

func (*Completion) UnmarshalJSON

func (r *Completion) UnmarshalJSON(data []byte) (err error)

type CompletionChoice

type CompletionChoice struct {
	FinishReason CompletionChoicesFinishReason `json:"finish_reason"`
	Logprobs     LogProbs                      `json:"logprobs,nullable"`
	Text         string                        `json:"text"`
	JSON         completionChoiceJSON          `json:"-"`
}

func (*CompletionChoice) UnmarshalJSON

func (r *CompletionChoice) UnmarshalJSON(data []byte) (err error)

type CompletionChoicesFinishReason

type CompletionChoicesFinishReason string
const (
	CompletionChoicesFinishReasonStop      CompletionChoicesFinishReason = "stop"
	CompletionChoicesFinishReasonEos       CompletionChoicesFinishReason = "eos"
	CompletionChoicesFinishReasonLength    CompletionChoicesFinishReason = "length"
	CompletionChoicesFinishReasonToolCalls CompletionChoicesFinishReason = "tool_calls"
)

func (CompletionChoicesFinishReason) IsKnown

func (r CompletionChoicesFinishReason) IsKnown() bool

type CompletionNewParams

type CompletionNewParams interface {
	ImplementsCompletionNewParams()
}

This interface is a union satisfied by one of the following: CompletionNewParamsCompletionRequest, CompletionNewParamsCompletionRequest.

type CompletionNewParamsCompletionRequest

type CompletionNewParamsCompletionRequest struct {
	// The name of the model to query.
	Model param.Field[string] `json:"model,required"`
	// A string providing context for the model to complete.
	Prompt param.Field[string] `json:"prompt,required"`
	// If set, tokens are returned as Server-Sent Events as they are made available.
	// Stream terminates with `data: [DONE]`
	Stream param.Field[CompletionNewParamsCompletionRequestStream] `json:"stream,required"`
	// If set, the response will contain the prompt, and will also return prompt
	// logprobs if set with logprobs.
	Echo param.Field[bool] `json:"echo"`
	// The `frequency_penalty` parameter is a number between -2.0 and 2.0 where a
	// positive value will decrease the likelihood of repeating tokens that were
	// mentioned prior.
	FrequencyPenalty param.Field[float64] `json:"frequency_penalty"`
	// The `logit_bias` parameter allows us to adjust the likelihood of specific tokens
	// appearing in the generated output.
	LogitBias param.Field[map[string]interface{}] `json:"logit_bias"`
	// Determines the number of most likely tokens to return at each token position log
	// probabilities to return
	Logprobs param.Field[int64] `json:"logprobs"`
	// The maximum number of tokens to generate.
	MaxTokens param.Field[int64] `json:"max_tokens"`
	// The `min_p` parameter is a number between 0 and 1 and an alternative to
	// `temperature`.
	MinP param.Field[float64] `json:"min_p"`
	// Number of generations to return
	N param.Field[int64] `json:"n"`
	// The `presence_penalty` parameter is a number between -2.0 and 2.0 where a
	// positive value will increase the likelihood of a model talking about new topics.
	PresencePenalty param.Field[float64] `json:"presence_penalty"`
	// A number that controls the diversity of generated text by reducing the
	// likelihood of repeated sequences. Higher values decrease repetition.
	RepetitionPenalty param.Field[float64] `json:"repetition_penalty"`
	// The name of the safety model to use.
	SafetyModel param.Field[string] `json:"safety_model"`
	// A list of string sequences that will truncate (stop) inference text output.
	Stop param.Field[[]string] `json:"stop"`
	// Determines the degree of randomness in the response.
	Temperature param.Field[float64] `json:"temperature"`
	// The `top_k` parameter is used to limit the number of choices for the next
	// predicted word or token.
	TopK param.Field[int64] `json:"top_k"`
	// The `top_p` (nucleus) parameter is used to dynamically adjust the number of
	// choices for each predicted token based on the cumulative probabilities.
	TopP param.Field[float64] `json:"top_p"`
}

func (CompletionNewParamsCompletionRequest) ImplementsCompletionNewParams

func (CompletionNewParamsCompletionRequest) ImplementsCompletionNewParams()

func (CompletionNewParamsCompletionRequest) MarshalJSON

func (r CompletionNewParamsCompletionRequest) MarshalJSON() (data []byte, err error)

type CompletionNewParamsCompletionRequestStream

type CompletionNewParamsCompletionRequestStream bool

If set, tokens are returned as Server-Sent Events as they are made available. Stream terminates with `data: [DONE]`

const (
	CompletionNewParamsCompletionRequestStreamFalse CompletionNewParamsCompletionRequestStream = false
)

func (CompletionNewParamsCompletionRequestStream) IsKnown

type CompletionObject

type CompletionObject string
const (
	CompletionObjectTextCompletion CompletionObject = "text_completion"
)

func (CompletionObject) IsKnown

func (r CompletionObject) IsKnown() bool

type CompletionPrompt

type CompletionPrompt struct {
	Logprobs LogProbs             `json:"logprobs"`
	Text     string               `json:"text"`
	JSON     completionPromptJSON `json:"-"`
}

func (*CompletionPrompt) UnmarshalJSON

func (r *CompletionPrompt) UnmarshalJSON(data []byte) (err error)

type CompletionService

type CompletionService struct {
	Options []option.RequestOption
}

CompletionService contains methods and other services that help with interacting with the together 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.

func NewCompletionService

func NewCompletionService(opts ...option.RequestOption) (r *CompletionService)

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 (*CompletionService) New

Creates a completion for the provided prompt and parameters

type Embedding

type Embedding struct {
	Data   []EmbeddingData `json:"data,required"`
	Model  string          `json:"model,required"`
	Object EmbeddingObject `json:"object,required"`
	JSON   embeddingJSON   `json:"-"`
}

func (*Embedding) UnmarshalJSON

func (r *Embedding) UnmarshalJSON(data []byte) (err error)

type EmbeddingData

type EmbeddingData struct {
	Embedding []float64           `json:"embedding,required"`
	Index     int64               `json:"index,required"`
	Object    EmbeddingDataObject `json:"object,required"`
	JSON      embeddingDataJSON   `json:"-"`
}

func (*EmbeddingData) UnmarshalJSON

func (r *EmbeddingData) UnmarshalJSON(data []byte) (err error)

type EmbeddingDataObject

type EmbeddingDataObject string
const (
	EmbeddingDataObjectEmbedding EmbeddingDataObject = "embedding"
)

func (EmbeddingDataObject) IsKnown

func (r EmbeddingDataObject) IsKnown() bool

type EmbeddingNewParams

type EmbeddingNewParams struct {
	// A string providing the text for the model to embed.
	Input param.Field[string] `json:"input,required"`
	// The name of the embedding model to use.
	Model param.Field[string] `json:"model,required"`
}

func (EmbeddingNewParams) MarshalJSON

func (r EmbeddingNewParams) MarshalJSON() (data []byte, err error)

type EmbeddingObject

type EmbeddingObject string
const (
	EmbeddingObjectList EmbeddingObject = "list"
)

func (EmbeddingObject) IsKnown

func (r EmbeddingObject) IsKnown() bool

type EmbeddingService

type EmbeddingService struct {
	Options []option.RequestOption
}

EmbeddingService contains methods and other services that help with interacting with the together 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.

func NewEmbeddingService

func NewEmbeddingService(opts ...option.RequestOption) (r *EmbeddingService)

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 (*EmbeddingService) New

func (r *EmbeddingService) New(ctx context.Context, body EmbeddingNewParams, opts ...option.RequestOption) (res *Embedding, err error)

Creates an embedding vector representing the input text

type Error

type Error = apierror.Error

type FileDeleteResponse

type FileDeleteResponse struct {
	ID      string                 `json:"id"`
	Deleted bool                   `json:"deleted"`
	JSON    fileDeleteResponseJSON `json:"-"`
}

func (*FileDeleteResponse) UnmarshalJSON

func (r *FileDeleteResponse) UnmarshalJSON(data []byte) (err error)

type FileGetResponse

type FileGetResponse struct {
	ID        string                  `json:"id,required"`
	Bytes     int64                   `json:"bytes,required"`
	CreatedAt int64                   `json:"created_at,required"`
	Filename  string                  `json:"filename,required"`
	FileType  FileGetResponseFileType `json:"FileType,required"`
	LineCount int64                   `json:"LineCount,required"`
	Object    string                  `json:"object,required"`
	Processed bool                    `json:"Processed,required"`
	Purpose   FileGetResponsePurpose  `json:"purpose,required"`
	JSON      fileGetResponseJSON     `json:"-"`
}

func (*FileGetResponse) UnmarshalJSON

func (r *FileGetResponse) UnmarshalJSON(data []byte) (err error)

type FileGetResponseFileType

type FileGetResponseFileType string
const (
	FileGetResponseFileTypeJsonl   FileGetResponseFileType = "jsonl"
	FileGetResponseFileTypeParquet FileGetResponseFileType = "parquet"
)

func (FileGetResponseFileType) IsKnown

func (r FileGetResponseFileType) IsKnown() bool

type FileGetResponsePurpose

type FileGetResponsePurpose string
const (
	FileGetResponsePurposeFineTune FileGetResponsePurpose = "fine-tune"
)

func (FileGetResponsePurpose) IsKnown

func (r FileGetResponsePurpose) IsKnown() bool

type FileListResponse

type FileListResponse struct {
	Data []FileListResponseData `json:"data,required"`
	JSON fileListResponseJSON   `json:"-"`
}

func (*FileListResponse) UnmarshalJSON

func (r *FileListResponse) UnmarshalJSON(data []byte) (err error)

type FileListResponseData

type FileListResponseData struct {
	ID        string                       `json:"id,required"`
	Bytes     int64                        `json:"bytes,required"`
	CreatedAt int64                        `json:"created_at,required"`
	Filename  string                       `json:"filename,required"`
	FileType  FileListResponseDataFileType `json:"FileType,required"`
	LineCount int64                        `json:"LineCount,required"`
	Object    string                       `json:"object,required"`
	Processed bool                         `json:"Processed,required"`
	Purpose   FileListResponseDataPurpose  `json:"purpose,required"`
	JSON      fileListResponseDataJSON     `json:"-"`
}

func (*FileListResponseData) UnmarshalJSON

func (r *FileListResponseData) UnmarshalJSON(data []byte) (err error)

type FileListResponseDataFileType

type FileListResponseDataFileType string
const (
	FileListResponseDataFileTypeJsonl   FileListResponseDataFileType = "jsonl"
	FileListResponseDataFileTypeParquet FileListResponseDataFileType = "parquet"
)

func (FileListResponseDataFileType) IsKnown

func (r FileListResponseDataFileType) IsKnown() bool

type FileListResponseDataPurpose

type FileListResponseDataPurpose string
const (
	FileListResponseDataPurposeFineTune FileListResponseDataPurpose = "fine-tune"
)

func (FileListResponseDataPurpose) IsKnown

func (r FileListResponseDataPurpose) IsKnown() bool

type FileService

type FileService struct {
	Options []option.RequestOption
}

FileService contains methods and other services that help with interacting with the together 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.

func NewFileService

func NewFileService(opts ...option.RequestOption) (r *FileService)

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 (*FileService) Content

func (r *FileService) Content(ctx context.Context, id string, opts ...option.RequestOption) (res *http.Response, err error)

Retrieve file content

func (*FileService) Delete

func (r *FileService) Delete(ctx context.Context, id string, opts ...option.RequestOption) (res *FileDeleteResponse, err error)

Delete a file

func (*FileService) Get

func (r *FileService) Get(ctx context.Context, id string, opts ...option.RequestOption) (res *FileGetResponse, err error)

Retrieve a file

func (*FileService) List

func (r *FileService) List(ctx context.Context, opts ...option.RequestOption) (res *FileListResponse, err error)

List all files

type FineTune

type FineTune struct {
	ID                   string          `json:"id,required" format:"uuid"`
	Status               FineTuneStatus  `json:"status,required"`
	BatchSize            int64           `json:"batch_size"`
	CreatedAt            string          `json:"created_at"`
	EpochsCompleted      int64           `json:"epochs_completed"`
	EvalSteps            int64           `json:"eval_steps"`
	Events               []FineTuneEvent `json:"events"`
	JobID                string          `json:"job_id"`
	LearningRate         float64         `json:"learning_rate"`
	Lora                 bool            `json:"lora"`
	LoraAlpha            int64           `json:"lora_alpha"`
	LoraDropout          int64           `json:"lora_dropout"`
	LoraR                int64           `json:"lora_r"`
	Model                string          `json:"model"`
	ModelOutputName      string          `json:"model_output_name"`
	ModelOutputPath      string          `json:"model_output_path"`
	NCheckpoints         int64           `json:"n_checkpoints"`
	NEpochs              int64           `json:"n_epochs"`
	ParamCount           int64           `json:"param_count"`
	QueueDepth           int64           `json:"queue_depth"`
	TokenCount           int64           `json:"token_count"`
	TotalPrice           int64           `json:"total_price"`
	TrainingFile         string          `json:"training_file"`
	TrainingFileNumLines int64           `json:"TrainingFileNumLines"`
	TrainingFileSize     int64           `json:"TrainingFileSize"`
	UpdatedAt            string          `json:"updated_at"`
	ValidationFile       string          `json:"validation_file"`
	WandbProjectName     string          `json:"wandb_project_name"`
	WandbURL             string          `json:"wandb_url"`
	JSON                 fineTuneJSON    `json:"-"`
}

func (*FineTune) UnmarshalJSON

func (r *FineTune) UnmarshalJSON(data []byte) (err error)

type FineTuneDownloadParams

type FineTuneDownloadParams struct {
	// Fine-tune ID to download. A string that starts with `ft-`.
	FtID param.Field[string] `query:"ft_id,required"`
	// Specifies step number for checkpoint to download.
	CheckpointStep param.Field[int64] `query:"checkpoint_step"`
	// Specifies output file name for downloaded model. Defaults to
	// `$PWD/{model_name}.{extension}`.
	Output param.Field[string] `query:"output"`
}

func (FineTuneDownloadParams) URLQuery

func (r FineTuneDownloadParams) URLQuery() (v url.Values)

URLQuery serializes FineTuneDownloadParams's query parameters as `url.Values`.

type FineTuneDownloadResponse

type FineTuneDownloadResponse struct {
	ID             string                       `json:"id"`
	CheckpointStep int64                        `json:"checkpoint_step"`
	Filename       string                       `json:"filename"`
	Object         interface{}                  `json:"object"`
	Size           int64                        `json:"size"`
	JSON           fineTuneDownloadResponseJSON `json:"-"`
}

func (*FineTuneDownloadResponse) UnmarshalJSON

func (r *FineTuneDownloadResponse) UnmarshalJSON(data []byte) (err error)

type FineTuneEvent

type FineTuneEvent struct {
	CreatedAt  string               `json:"created_at"`
	Hash       string               `json:"hash"`
	Level      FineTuneEventsLevel  `json:"level,nullable"`
	Message    string               `json:"message"`
	Object     FineTuneEventsObject `json:"object"`
	ParamCount int64                `json:"param_count"`
	TokenCount int64                `json:"token_count"`
	Type       FineTuneEventsType   `json:"type"`
	WandbURL   string               `json:"wandb_url"`
	JSON       fineTuneEventJSON    `json:"-"`
}

func (*FineTuneEvent) UnmarshalJSON

func (r *FineTuneEvent) UnmarshalJSON(data []byte) (err error)

type FineTuneEventsLevel

type FineTuneEventsLevel string
const (
	FineTuneEventsLevelInfo           FineTuneEventsLevel = "info"
	FineTuneEventsLevelWarning        FineTuneEventsLevel = "warning"
	FineTuneEventsLevelError          FineTuneEventsLevel = "error"
	FineTuneEventsLevelLegacyInfo     FineTuneEventsLevel = "legacy_info"
	FineTuneEventsLevelLegacyIwarning FineTuneEventsLevel = "legacy_iwarning"
	FineTuneEventsLevelLegacyIerror   FineTuneEventsLevel = "legacy_ierror"
)

func (FineTuneEventsLevel) IsKnown

func (r FineTuneEventsLevel) IsKnown() bool

type FineTuneEventsObject

type FineTuneEventsObject string
const (
	FineTuneEventsObjectFinetuneEvent FineTuneEventsObject = "FinetuneEvent"
)

func (FineTuneEventsObject) IsKnown

func (r FineTuneEventsObject) IsKnown() bool

type FineTuneEventsType

type FineTuneEventsType string
const (
	FineTuneEventsTypeJobPending                     FineTuneEventsType = "job_pending"
	FineTuneEventsTypeJobStart                       FineTuneEventsType = "job_start"
	FineTuneEventsTypeJobStopped                     FineTuneEventsType = "job_stopped"
	FineTuneEventsTypeModelDownloading               FineTuneEventsType = "model_downloading"
	FineTuneEventsTypeModelDownloadComplete          FineTuneEventsType = "model_download_complete"
	FineTuneEventsTypeTrainingDataDownloading        FineTuneEventsType = "training_data_downloading"
	FineTuneEventsTypeTrainingDataDownloadComplete   FineTuneEventsType = "training_data_download_complete"
	FineTuneEventsTypeValidationDataDownloading      FineTuneEventsType = "validation_data_downloading"
	FineTuneEventsTypeValidationDataDownloadComplete FineTuneEventsType = "validation_data_download_complete"
	FineTuneEventsTypeWandbInit                      FineTuneEventsType = "wandb_init"
	FineTuneEventsTypeTrainingStart                  FineTuneEventsType = "training_start"
	FineTuneEventsTypeCheckpointSave                 FineTuneEventsType = "checkpoint_save"
	FineTuneEventsTypeBillingLimit                   FineTuneEventsType = "billing_limit"
	FineTuneEventsTypeEpochComplete                  FineTuneEventsType = "epoch_complete"
	FineTuneEventsTypeTrainingComplete               FineTuneEventsType = "training_complete"
	FineTuneEventsTypeModelCompressing               FineTuneEventsType = "model_compressing"
	FineTuneEventsTypeModelCompressionComplete       FineTuneEventsType = "model_compression_complete"
	FineTuneEventsTypeModelUploading                 FineTuneEventsType = "model_uploading"
	FineTuneEventsTypeModelUploadComplete            FineTuneEventsType = "model_upload_complete"
	FineTuneEventsTypeJobComplete                    FineTuneEventsType = "job_complete"
	FineTuneEventsTypeJobError                       FineTuneEventsType = "job_error"
	FineTuneEventsTypeCancelRequested                FineTuneEventsType = "cancel_requested"
	FineTuneEventsTypeJobRestarted                   FineTuneEventsType = "job_restarted"
	FineTuneEventsTypeRefund                         FineTuneEventsType = "refund"
	FineTuneEventsTypeWarning                        FineTuneEventsType = "warning"
)

func (FineTuneEventsType) IsKnown

func (r FineTuneEventsType) IsKnown() bool

type FineTuneListResponse

type FineTuneListResponse struct {
	Data []FineTune               `json:"data,required"`
	JSON fineTuneListResponseJSON `json:"-"`
}

func (*FineTuneListResponse) UnmarshalJSON

func (r *FineTuneListResponse) UnmarshalJSON(data []byte) (err error)

type FineTuneNewParams

type FineTuneNewParams struct {
	// Name of the base model to run fine-tune job on
	Model param.Field[string] `json:"model,required"`
	// File-ID of a file uploaded to the Together API
	TrainingFile param.Field[string] `json:"training_file,required"`
	// Batch size for fine-tuning
	BatchSize param.Field[int64] `json:"batch_size"`
	// Learning rate multiplier to use for training
	LearningRate param.Field[float64] `json:"learning_rate"`
	// Number of checkpoints to save during fine-tuning
	NCheckpoints param.Field[int64] `json:"n_checkpoints"`
	// Number of epochs for fine-tuning
	NEpochs param.Field[int64] `json:"n_epochs"`
	// Suffix that will be added to your fine-tuned model name
	Suffix param.Field[string] `json:"suffix"`
	// API key for Weights & Biases integration
	WandbAPIKey param.Field[string] `json:"wandb_api_key"`
}

func (FineTuneNewParams) MarshalJSON

func (r FineTuneNewParams) MarshalJSON() (data []byte, err error)

type FineTuneService

type FineTuneService struct {
	Options []option.RequestOption
}

FineTuneService contains methods and other services that help with interacting with the together 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 NewFineTuneService method instead.

func NewFineTuneService

func NewFineTuneService(opts ...option.RequestOption) (r *FineTuneService)

NewFineTuneService 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 (*FineTuneService) Cancel

func (r *FineTuneService) Cancel(ctx context.Context, id string, opts ...option.RequestOption) (res *FineTune, err error)

Cancels a running fine-tuning job.

func (*FineTuneService) Download

Downloads a compressed fine-tuned model or checkpoint to local disk.

func (*FineTuneService) Get

func (r *FineTuneService) Get(ctx context.Context, id string, opts ...option.RequestOption) (res *FineTune, err error)

Retrieve fine-tune job details

func (*FineTuneService) List

func (r *FineTuneService) List(ctx context.Context, opts ...option.RequestOption) (res *FineTuneListResponse, err error)

List fine-tune job history

func (*FineTuneService) ListEvents

func (r *FineTuneService) ListEvents(ctx context.Context, id string, opts ...option.RequestOption) (res *FineTuneEvent, err error)

List events of a fine-tune job

func (*FineTuneService) New

func (r *FineTuneService) New(ctx context.Context, body FineTuneNewParams, opts ...option.RequestOption) (res *FineTune, err error)

Create a fine-tuning job

type FineTuneStatus

type FineTuneStatus string
const (
	FineTuneStatusPending         FineTuneStatus = "pending"
	FineTuneStatusQueued          FineTuneStatus = "queued"
	FineTuneStatusRunning         FineTuneStatus = "running"
	FineTuneStatusCompressing     FineTuneStatus = "compressing"
	FineTuneStatusUploading       FineTuneStatus = "uploading"
	FineTuneStatusCancelRequested FineTuneStatus = "cancel_requested"
	FineTuneStatusCancelled       FineTuneStatus = "cancelled"
	FineTuneStatusError           FineTuneStatus = "error"
	FineTuneStatusCompleted       FineTuneStatus = "completed"
)

func (FineTuneStatus) IsKnown

func (r FineTuneStatus) IsKnown() bool

type ImageFile

type ImageFile struct {
	ID     string          `json:"id,required"`
	Data   []ImageFileData `json:"data,required"`
	Model  string          `json:"model,required"`
	Object ImageFileObject `json:"object,required"`
	JSON   imageFileJSON   `json:"-"`
}

func (*ImageFile) UnmarshalJSON

func (r *ImageFile) UnmarshalJSON(data []byte) (err error)

type ImageFileData

type ImageFileData struct {
	B64Json string            `json:"b64_json,required"`
	Index   int64             `json:"index,required"`
	JSON    imageFileDataJSON `json:"-"`
}

func (*ImageFileData) UnmarshalJSON

func (r *ImageFileData) UnmarshalJSON(data []byte) (err error)

type ImageFileObject

type ImageFileObject string
const (
	ImageFileObjectList ImageFileObject = "list"
)

func (ImageFileObject) IsKnown

func (r ImageFileObject) IsKnown() bool

type ImageNewParams

type ImageNewParams struct {
	// The model to use for image generation.
	Model param.Field[string] `json:"model,required"`
	// A description of the desired images. Maximum length varies by model.
	Prompt param.Field[string] `json:"prompt,required"`
	// Height of the image to generate in number of pixels.
	Height param.Field[int64] `json:"height"`
	// Number of image results to generate.
	N param.Field[int64] `json:"n"`
	// The prompt or prompts not to guide the image generation.
	NegativePrompt param.Field[string] `json:"negative_prompt"`
	// Seed used for generation. Can be used to reproduce image generations.
	Seed param.Field[int64] `json:"seed"`
	// Number of generation steps.
	Steps param.Field[int64] `json:"steps"`
	// Width of the image to generate in number of pixels.
	Width param.Field[int64] `json:"width"`
}

func (ImageNewParams) MarshalJSON

func (r ImageNewParams) MarshalJSON() (data []byte, err error)

type ImageService

type ImageService struct {
	Options []option.RequestOption
}

ImageService contains methods and other services that help with interacting with the together API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewImageService method instead.

func NewImageService

func NewImageService(opts ...option.RequestOption) (r *ImageService)

NewImageService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*ImageService) New

func (r *ImageService) New(ctx context.Context, body ImageNewParams, opts ...option.RequestOption) (res *ImageFile, err error)

Generate images based on a given prompt using a specified model

type LogProbs

type LogProbs struct {
	// List of token log probabilities
	TokenLogprobs []float64 `json:"token_logprobs"`
	// List of token strings
	Tokens []string     `json:"tokens"`
	JSON   logProbsJSON `json:"-"`
}

func (*LogProbs) UnmarshalJSON

func (r *LogProbs) UnmarshalJSON(data []byte) (err error)

type ModelListResponse

type ModelListResponse struct {
	ID            string                   `json:"id,required"`
	Created       int64                    `json:"created,required"`
	Object        string                   `json:"object,required"`
	Type          ModelListResponseType    `json:"type,required"`
	ContextLength int64                    `json:"context_length"`
	DisplayName   string                   `json:"display_name"`
	License       string                   `json:"license"`
	Link          string                   `json:"link"`
	Organization  string                   `json:"organization"`
	Pricing       ModelListResponsePricing `json:"pricing"`
	JSON          modelListResponseJSON    `json:"-"`
}

func (*ModelListResponse) UnmarshalJSON

func (r *ModelListResponse) UnmarshalJSON(data []byte) (err error)

type ModelListResponsePricing

type ModelListResponsePricing struct {
	Base     float64                      `json:"base,required"`
	Finetune float64                      `json:"finetune,required"`
	Hourly   float64                      `json:"hourly,required"`
	Input    float64                      `json:"input,required"`
	Output   float64                      `json:"output,required"`
	JSON     modelListResponsePricingJSON `json:"-"`
}

func (*ModelListResponsePricing) UnmarshalJSON

func (r *ModelListResponsePricing) UnmarshalJSON(data []byte) (err error)

type ModelListResponseType

type ModelListResponseType string
const (
	ModelListResponseTypeChat       ModelListResponseType = "chat"
	ModelListResponseTypeLanguage   ModelListResponseType = "language"
	ModelListResponseTypeCode       ModelListResponseType = "code"
	ModelListResponseTypeImage      ModelListResponseType = "image"
	ModelListResponseTypeEmbedding  ModelListResponseType = "embedding"
	ModelListResponseTypeModeration ModelListResponseType = "moderation"
)

func (ModelListResponseType) IsKnown

func (r ModelListResponseType) IsKnown() bool

type ModelService

type ModelService struct {
	Options []option.RequestOption
}

ModelService contains methods and other services that help with interacting with the together 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.

func NewModelService

func NewModelService(opts ...option.RequestOption) (r *ModelService)

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 (*ModelService) List

func (r *ModelService) List(ctx context.Context, opts ...option.RequestOption) (res *[]ModelListResponse, err error)

Lists all the available models

type ToolChoiceFunctionParam

type ToolChoiceFunctionParam struct {
	Name param.Field[string] `json:"name"`
}

func (ToolChoiceFunctionParam) MarshalJSON

func (r ToolChoiceFunctionParam) MarshalJSON() (data []byte, err error)

type ToolChoiceParam

type ToolChoiceParam struct {
	Function param.Field[ToolChoiceFunctionParam] `json:"function"`
	Type     param.Field[string]                  `json:"type"`
}

func (ToolChoiceParam) ImplementsChatCompletionNewParamsChatCompletionRequestToolChoiceUnion

func (r ToolChoiceParam) ImplementsChatCompletionNewParamsChatCompletionRequestToolChoiceUnion()

func (ToolChoiceParam) MarshalJSON

func (r ToolChoiceParam) MarshalJSON() (data []byte, err error)

type ToolsFunctionParam

type ToolsFunctionParam struct {
	Description param.Field[string] `json:"description"`
	Name        param.Field[string] `json:"name"`
	// A map of parameter names to their values.
	Parameters param.Field[map[string]interface{}] `json:"parameters"`
}

func (ToolsFunctionParam) MarshalJSON

func (r ToolsFunctionParam) MarshalJSON() (data []byte, err error)

type ToolsParam

type ToolsParam struct {
	Function param.Field[ToolsFunctionParam] `json:"function"`
	Type     param.Field[string]             `json:"type"`
}

func (ToolsParam) MarshalJSON

func (r ToolsParam) MarshalJSON() (data []byte, err error)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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