github.com/anthropics/anthropic-sdk-go@v1.70.1/completion.go (about) 1 // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 3 package anthropic 4 5 import ( 6 "context" 7 "fmt" 8 "net/http" 9 "slices" 10 11 "github.com/anthropics/anthropic-sdk-go/internal/apijson" 12 "github.com/anthropics/anthropic-sdk-go/internal/requestconfig" 13 "github.com/anthropics/anthropic-sdk-go/option" 14 "github.com/anthropics/anthropic-sdk-go/packages/param" 15 "github.com/anthropics/anthropic-sdk-go/packages/respjson" 16 "github.com/anthropics/anthropic-sdk-go/packages/ssestream" 17 "github.com/anthropics/anthropic-sdk-go/shared/constant" 18 ) 19 20 // CompletionService contains methods and other services that help with interacting 21 // with the anthropic API. 22 // 23 // Note, unlike clients, this service does not read variables from the environment 24 // automatically. You should not instantiate this service directly, and instead use 25 // the [NewCompletionService] method instead. 26 type CompletionService struct { 27 Options []option.RequestOption 28 } 29 30 // NewCompletionService generates a new service that applies the given options to 31 // each request. These options are applied after the parent client's options (if 32 // there is one), and before any request-specific options. 33 func NewCompletionService(opts ...option.RequestOption) (r CompletionService) { 34 r = CompletionService{} 35 r.Options = opts 36 return 37 } 38 39 // [Legacy] Create a Text Completion. 40 // 41 // The Text Completions API is a legacy API. We recommend using the 42 // [Messages API](https://platform.claude.com/docs/en/api/messages) going forward. 43 // 44 // Future models and features will not be compatible with Text Completions. See our 45 // [migration guide](https://platform.claude.com/docs/en/build-with-claude/working-with-messages) 46 // for guidance in migrating from Text Completions to Messages. 47 // 48 // Note: If you choose to set a timeout for this request, we recommend 10 minutes. 49 func (r *CompletionService) New(ctx context.Context, params CompletionNewParams, opts ...option.RequestOption) (res *Completion, err error) { 50 for _, v := range params.Betas { 51 opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) 52 } 53 if !param.IsOmitted(params.WorkspaceID) { 54 opts = append(opts, option.WithHeader("anthropic-workspace-id", fmt.Sprintf("%v", params.WorkspaceID.Value))) 55 } 56 opts = slices.Concat(r.Options, opts) 57 path := "v1/complete" 58 err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, params, &res, opts...) 59 return res, err 60 } 61 62 // [Legacy] Create a Text Completion. 63 // 64 // The Text Completions API is a legacy API. We recommend using the 65 // [Messages API](https://platform.claude.com/docs/en/api/messages) going forward. 66 // 67 // Future models and features will not be compatible with Text Completions. See our 68 // [migration guide](https://platform.claude.com/docs/en/build-with-claude/working-with-messages) 69 // for guidance in migrating from Text Completions to Messages. 70 // 71 // Note: If you choose to set a timeout for this request, we recommend 10 minutes. 72 func (r *CompletionService) NewStreaming(ctx context.Context, params CompletionNewParams, opts ...option.RequestOption) (stream *ssestream.Stream[Completion]) { 73 var ( 74 raw *http.Response 75 err error 76 ) 77 for _, v := range params.Betas { 78 opts = append(opts, option.WithHeaderAdd("anthropic-beta", fmt.Sprintf("%v", v))) 79 } 80 if !param.IsOmitted(params.WorkspaceID) { 81 opts = append(opts, option.WithHeader("anthropic-workspace-id", fmt.Sprintf("%v", params.WorkspaceID.Value))) 82 } 83 opts = slices.Concat(r.Options, opts) 84 opts = append(opts, option.WithJSONSet("stream", true)) 85 path := "v1/complete" 86 err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, params, &raw, opts...) 87 return ssestream.NewStream[Completion](ssestream.NewDecoder(raw), err) 88 } 89 90 type Completion struct { 91 // Unique object identifier. 92 // 93 // The format and length of IDs may change over time. 94 ID string `json:"id" api:"required"` 95 // The resulting completion up to and excluding the stop sequences. 96 Completion string `json:"completion" api:"required"` 97 // The model that will complete your prompt. 98 // 99 // See [models](https://docs.anthropic.com/en/docs/models-overview) for additional 100 // details and options. 101 Model Model `json:"model" api:"required"` 102 // The reason that we stopped. 103 // 104 // This may be one the following values: 105 // 106 // - `"stop_sequence"`: we reached a stop sequence — either provided by you via the 107 // `stop_sequences` parameter, or a stop sequence built into the model 108 // - `"max_tokens"`: we exceeded `max_tokens_to_sample` or the model's maximum 109 StopReason string `json:"stop_reason" api:"required"` 110 // Object type. 111 // 112 // For Text Completions, this is always `"completion"`. 113 Type constant.Completion `json:"type" default:"completion"` 114 // JSON contains metadata for fields, check presence with [respjson.Field.Valid]. 115 JSON struct { 116 ID respjson.Field 117 Completion respjson.Field 118 Model respjson.Field 119 StopReason respjson.Field 120 Type respjson.Field 121 ExtraFields map[string]respjson.Field 122 raw string 123 } `json:"-"` 124 } 125 126 // Returns the unmodified JSON received from the API 127 func (r Completion) RawJSON() string { return r.JSON.raw } 128 func (r *Completion) UnmarshalJSON(data []byte) error { 129 return apijson.UnmarshalRoot(data, r) 130 } 131 132 type CompletionNewParams struct { 133 // The maximum number of tokens to generate before stopping. 134 // 135 // Note that our models may stop _before_ reaching this maximum. This parameter 136 // only specifies the absolute maximum number of tokens to generate. 137 MaxTokensToSample int64 `json:"max_tokens_to_sample" api:"required"` 138 // The model that will complete your prompt. 139 // 140 // See [models](https://docs.anthropic.com/en/docs/models-overview) for additional 141 // details and options. 142 Model Model `json:"model,omitzero" api:"required"` 143 // The prompt that you want Claude to complete. 144 // 145 // For proper response generation you will need to format your prompt using 146 // alternating `\n\nHuman:` and `\n\nAssistant:` conversational turns. For example: 147 // 148 // ``` 149 // "\n\nHuman: {userQuestion}\n\nAssistant:" 150 // ``` 151 // 152 // See 153 // [prompt validation](https://platform.claude.com/docs/en/build-with-claude/working-with-messages) 154 // and our guide to 155 // [prompt design](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/overview) 156 // for more details. 157 Prompt string `json:"prompt" api:"required"` 158 // Amount of randomness injected into the response. 159 // 160 // Defaults to `1.0`. Ranges from `0.0` to `1.0`. Use `temperature` closer to `0.0` 161 // for analytical / multiple choice, and closer to `1.0` for creative and 162 // generative tasks. 163 // 164 // Note that even with `temperature` of `0.0`, the results will not be fully 165 // deterministic. 166 Temperature param.Opt[float64] `json:"temperature,omitzero"` 167 // Only sample from the top K options for each subsequent token. 168 // 169 // Used to remove "long tail" low probability responses. 170 // [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277). 171 // 172 // Recommended for advanced use cases only. 173 TopK param.Opt[int64] `json:"top_k,omitzero"` 174 // Use nucleus sampling. 175 // 176 // In nucleus sampling, we compute the cumulative distribution over all the options 177 // for each subsequent token in decreasing probability order and cut it off once it 178 // reaches a particular probability specified by `top_p`. 179 // 180 // Recommended for advanced use cases only. 181 TopP param.Opt[float64] `json:"top_p,omitzero"` 182 WorkspaceID param.Opt[string] `header:"anthropic-workspace-id,omitzero" json:"-"` 183 // An object describing metadata about the request. 184 Metadata MetadataParam `json:"metadata,omitzero"` 185 // Sequences that will cause the model to stop generating. 186 // 187 // Our models stop on `"\n\nHuman:"`, and may include additional built-in stop 188 // sequences in the future. By providing the stop_sequences parameter, you may 189 // include additional strings that will cause the model to stop generating. 190 StopSequences []string `json:"stop_sequences,omitzero"` 191 // Optional header to specify the beta version(s) you want to use. 192 Betas []AnthropicBeta `header:"anthropic-beta,omitzero" json:"-"` 193 paramObj 194 } 195 196 func (r CompletionNewParams) MarshalJSON() (data []byte, err error) { 197 type shadow CompletionNewParams 198 return param.MarshalObject(r, (*shadow)(&r)) 199 } 200 func (r *CompletionNewParams) UnmarshalJSON(data []byte) error { 201 return apijson.UnmarshalRoot(data, r) 202 }