diff options
Diffstat (limited to 'vendor/github.com')
28 files changed, 18524 insertions, 0 deletions
diff --git a/vendor/github.com/google/generative-ai-go/LICENSE b/vendor/github.com/google/generative-ai-go/LICENSE new file mode 100644 index 000000000..261eeb9e9 --- /dev/null +++ b/vendor/github.com/google/generative-ai-go/LICENSE @@ -0,0 +1,201 @@ + 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 [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/google/generative-ai-go/genai/chat.go b/vendor/github.com/google/generative-ai-go/genai/chat.go new file mode 100644 index 000000000..169b24b5d --- /dev/null +++ b/vendor/github.com/google/generative-ai-go/genai/chat.go @@ -0,0 +1,71 @@ +// Copyright 2023 Google LLC +// +// 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. + +package genai + +import ( + "context" +) + +// A ChatSession provides interactive chat. +type ChatSession struct { + m *GenerativeModel + History []*Content +} + +// StartChat starts a chat session. +func (m *GenerativeModel) StartChat() *ChatSession { + return &ChatSession{m: m} +} + +// SendMessage sends a request to the model as part of a chat session. +func (cs *ChatSession) SendMessage(ctx context.Context, parts ...Part) (*GenerateContentResponse, error) { + // Call the underlying client with the entire history plus the argument Content. + cs.History = append(cs.History, newUserContent(parts)) + req := cs.m.newGenerateContentRequest(cs.History...) + req.GenerationConfig.CandidateCount = Ptr[int32](1) + resp, err := cs.m.generateContent(ctx, req) + if err != nil { + return nil, err + } + cs.addToHistory(resp.Candidates) + return resp, nil +} + +// SendMessageStream is like SendMessage, but with a streaming request. +func (cs *ChatSession) SendMessageStream(ctx context.Context, parts ...Part) *GenerateContentResponseIterator { + cs.History = append(cs.History, newUserContent(parts)) + req := cs.m.newGenerateContentRequest(cs.History...) + req.GenerationConfig.CandidateCount = Ptr[int32](1) + streamClient, err := cs.m.c.c.StreamGenerateContent(ctx, req) + return &GenerateContentResponseIterator{ + sc: streamClient, + err: err, + cs: cs, + } +} + +// By default, use the first candidate for history. The user can modify that if they want. +func (cs *ChatSession) addToHistory(cands []*Candidate) bool { + if len(cands) > 0 { + c := cands[0].Content + if c == nil { + return false + } + c.Role = roleModel + cs.History = append(cs.History, c) + return true + } + return false +} diff --git a/vendor/github.com/google/generative-ai-go/genai/client.go b/vendor/github.com/google/generative-ai-go/genai/client.go new file mode 100644 index 000000000..652312978 --- /dev/null +++ b/vendor/github.com/google/generative-ai-go/genai/client.go @@ -0,0 +1,401 @@ +// Copyright 2023 Google LLC +// +// 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. + +// For the following go:generate line to work, do the following: +// Install the protoveener tool: +// git clone https://github.com/googleapis/google-cloud-go +// cd google-cloud-go +// go install ./internal/protoveneer/cmd/protoveneer +// +// Set the environment variable GOOGLE_CLOUD_GO to the path to the above repo on your machine. +// For example: +// export GOOGLE_CLOUD_GO=$HOME/repos/google-cloud-go + +//go:generate protoveneer -license license.txt config.yaml $GOOGLE_CLOUD_GO/ai/generativelanguage/apiv1beta/generativelanguagepb + +package genai + +import ( + "context" + "errors" + "fmt" + "io" + "reflect" + "strings" + + gl "cloud.google.com/go/ai/generativelanguage/apiv1beta" + pb "cloud.google.com/go/ai/generativelanguage/apiv1beta/generativelanguagepb" + "github.com/google/generative-ai-go/genai/internal" + gld "github.com/google/generative-ai-go/genai/internal/generativelanguage/v1beta" // discovery client + + "github.com/google/generative-ai-go/internal/support" + "google.golang.org/api/iterator" + "google.golang.org/api/option" +) + +// A Client is a Google generative AI client. +type Client struct { + c *gl.GenerativeClient + mc *gl.ModelClient + fc *gl.FileClient + ds *gld.Service +} + +// NewClient creates a new Google generative AI client. +// +// Clients should be reused instead of created as needed. The methods of Client +// are safe for concurrent use by multiple goroutines. +// +// You may configure the client by passing in options from the [google.golang.org/api/option] +// package. +func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + if !hasAuthOption(opts) { + return nil, errors.New(`You need an auth option to use this client. +for an API Key: Visit https://ai.google.dev to get one, put it in an environment variable like GEMINI_API_KEY, +then pass it as an option: + genai.NewClient(ctx, option.WithAPIKey(os.Getenv("GEMINI_API_KEY"))) +(If you're doing that already, then maybe the environment variable is empty or unset.) +Import the option package as "google.golang.org/api/option".`) + } + c, err := gl.NewGenerativeRESTClient(ctx, opts...) + if err != nil { + return nil, err + } + mc, err := gl.NewModelRESTClient(ctx, opts...) + if err != nil { + return nil, err + } + fc, err := gl.NewFileRESTClient(ctx, opts...) + if err != nil { + return nil, err + } + ds, err := gld.NewService(ctx, opts...) + if err != nil { + return nil, err + } + c.SetGoogleClientInfo("gccl", "v"+internal.Version, "genai-go", internal.Version) + return &Client{c, mc, fc, ds}, nil +} + +// hasAuthOption reports whether an authentication-related option was provided. +// +// There is no good way to make these checks, because the types of the options +// are unexported, and the struct that they populates is in an internal package. +func hasAuthOption(opts []option.ClientOption) bool { + for _, opt := range opts { + v := reflect.ValueOf(opt) + ts := v.Type().String() + + switch ts { + case "option.withAPIKey": + return v.String() != "" + + case "option.withHttpClient", + "option.withTokenSource", + "option.withCredentialsFile", + "option.withCredentialsJSON": + return true + } + } + return false +} + +// Close closes the client. +func (c *Client) Close() error { + return errors.Join(c.c.Close(), c.mc.Close(), c.fc.Close()) +} + +// GenerativeModel is a model that can generate text. +// Create one with [Client.GenerativeModel], then configure +// it by setting the exported fields. +type GenerativeModel struct { + c *Client + fullName string + + GenerationConfig + SafetySettings []*SafetySetting + Tools []*Tool + ToolConfig *ToolConfig // configuration for tools + // SystemInstruction (also known as "system prompt") is a more forceful prompt to the model. + // The model will adhere the instructions more strongly than if they appeared in a normal prompt. + SystemInstruction *Content +} + +// GenerativeModel creates a new instance of the named generative model. +// For instance, "gemini-1.0-pro" or "models/gemini-1.0-pro". +// +// To access a tuned model named NAME, pass "tunedModels/NAME". +func (c *Client) GenerativeModel(name string) *GenerativeModel { + return &GenerativeModel{ + c: c, + fullName: fullModelName(name), + } +} + +func fullModelName(name string) string { + if strings.ContainsRune(name, '/') { + return name + } + return "models/" + name +} + +// GenerateContent produces a single request and response. +func (m *GenerativeModel) GenerateContent(ctx context.Context, parts ...Part) (*GenerateContentResponse, error) { + content := newUserContent(parts) + req := m.newGenerateContentRequest(content) + res, err := m.c.c.GenerateContent(ctx, req) + if err != nil { + return nil, err + } + return protoToResponse(res) +} + +// GenerateContentStream returns an iterator that enumerates responses. +func (m *GenerativeModel) GenerateContentStream(ctx context.Context, parts ...Part) *GenerateContentResponseIterator { + streamClient, err := m.c.c.StreamGenerateContent(ctx, m.newGenerateContentRequest(newUserContent(parts))) + return &GenerateContentResponseIterator{ + sc: streamClient, + err: err, + } +} + +func (m *GenerativeModel) generateContent(ctx context.Context, req *pb.GenerateContentRequest) (*GenerateContentResponse, error) { + streamClient, err := m.c.c.StreamGenerateContent(ctx, req) + iter := &GenerateContentResponseIterator{ + sc: streamClient, + err: err, + } + for { + _, err := iter.Next() + if err == iterator.Done { + return iter.merged, nil + } + if err != nil { + return nil, err + } + } +} + +func (m *GenerativeModel) newGenerateContentRequest(contents ...*Content) *pb.GenerateContentRequest { + return &pb.GenerateContentRequest{ + Model: m.fullName, + Contents: support.TransformSlice(contents, (*Content).toProto), + SafetySettings: support.TransformSlice(m.SafetySettings, (*SafetySetting).toProto), + Tools: support.TransformSlice(m.Tools, (*Tool).toProto), + ToolConfig: m.ToolConfig.toProto(), + GenerationConfig: m.GenerationConfig.toProto(), + SystemInstruction: m.SystemInstruction.toProto(), + } +} + +func newUserContent(parts []Part) *Content { + return &Content{Role: roleUser, Parts: parts} +} + +// GenerateContentResponseIterator is an iterator over GnerateContentResponse. +type GenerateContentResponseIterator struct { + sc pb.GenerativeService_StreamGenerateContentClient + err error + merged *GenerateContentResponse + cs *ChatSession +} + +// Next returns the next response. +func (iter *GenerateContentResponseIterator) Next() (*GenerateContentResponse, error) { + if iter.err != nil { + return nil, iter.err + } + resp, err := iter.sc.Recv() + iter.err = err + if err == io.EOF { + if iter.cs != nil && iter.merged != nil { + iter.cs.addToHistory(iter.merged.Candidates) + } + return nil, iterator.Done + } + if err != nil { + return nil, err + } + gcp, err := protoToResponse(resp) + if err != nil { + iter.err = err + return nil, err + } + // Merge this response in with the ones we've already seen. + iter.merged = joinResponses(iter.merged, gcp) + // If this is part of a ChatSession, remember the response for the history. + return gcp, nil +} + +func protoToResponse(resp *pb.GenerateContentResponse) (*GenerateContentResponse, error) { + gcp := (GenerateContentResponse{}).fromProto(resp) + if gcp == nil { + return nil, errors.New("empty response from model") + } + // Assume a non-nil PromptFeedback is an error. + // TODO: confirm. + if gcp.PromptFeedback != nil && gcp.PromptFeedback.BlockReason != BlockReasonUnspecified { + return nil, &BlockedError{PromptFeedback: gcp.PromptFeedback} + } + + // If any candidate is blocked, error. + // TODO: is this too harsh? + for _, c := range gcp.Candidates { + if c.FinishReason == FinishReasonSafety || c.FinishReason == FinishReasonRecitation { + return nil, &BlockedError{Candidate: c} + } + } + return gcp, nil +} + +// CountTokens counts the number of tokens in the content. +func (m *GenerativeModel) CountTokens(ctx context.Context, parts ...Part) (*CountTokensResponse, error) { + req := m.newCountTokensRequest(newUserContent(parts)) + res, err := m.c.c.CountTokens(ctx, req) + if err != nil { + return nil, err + } + + return (CountTokensResponse{}).fromProto(res), nil +} + +func (m *GenerativeModel) newCountTokensRequest(contents ...*Content) *pb.CountTokensRequest { + return &pb.CountTokensRequest{ + Model: m.fullName, + Contents: support.TransformSlice(contents, (*Content).toProto), + } +} + +// Info returns information about the model. +func (m *GenerativeModel) Info(ctx context.Context) (*ModelInfo, error) { + return m.c.modelInfo(ctx, m.fullName) +} + +func (c *Client) modelInfo(ctx context.Context, fullName string) (*ModelInfo, error) { + req := &pb.GetModelRequest{Name: fullName} + res, err := c.mc.GetModel(ctx, req) + if err != nil { + return nil, err + } + return (ModelInfo{}).fromProto(res), nil +} + +// A BlockedError indicates that the model's response was blocked. +// There can be two underlying causes: the prompt or a candidate response. +type BlockedError struct { + // If non-nil, the model's response was blocked. + // Consult the FinishReason field for details. + Candidate *Candidate + + // If non-nil, there was a problem with the prompt. + PromptFeedback *PromptFeedback +} + +func (e *BlockedError) Error() string { + var b strings.Builder + fmt.Fprintf(&b, "blocked: ") + if e.Candidate != nil { + fmt.Fprintf(&b, "candidate: %s", e.Candidate.FinishReason) + } + if e.PromptFeedback != nil { + if e.Candidate != nil { + fmt.Fprintf(&b, ", ") + } + fmt.Fprintf(&b, "prompt: %v", e.PromptFeedback.BlockReason) + } + return b.String() +} + +// joinResponses merges the two responses, which should be the result of a streaming call. +// The first argument is modified. +func joinResponses(dest, src *GenerateContentResponse) *GenerateContentResponse { + if dest == nil { + return src + } + dest.Candidates = joinCandidateLists(dest.Candidates, src.Candidates) + // Keep dest.PromptFeedback. + // TODO: Take the last UsageMetadata. + return dest +} + +func joinCandidateLists(dest, src []*Candidate) []*Candidate { + indexToSrcCandidate := map[int32]*Candidate{} + for _, s := range src { + indexToSrcCandidate[s.Index] = s + } + for _, d := range dest { + s := indexToSrcCandidate[d.Index] + if s != nil { + d.Content = joinContent(d.Content, s.Content) + // Take the last of these. + d.FinishReason = s.FinishReason + // d.FinishMessage = s.FinishMessage + d.SafetyRatings = s.SafetyRatings + d.CitationMetadata = joinCitationMetadata(d.CitationMetadata, s.CitationMetadata) + } + } + return dest +} + +func joinCitationMetadata(dest, src *CitationMetadata) *CitationMetadata { + if dest == nil { + return src + } + if src == nil { + return dest + } + dest.CitationSources = append(dest.CitationSources, src.CitationSources...) + return dest +} + +func joinContent(dest, src *Content) *Content { + if dest == nil { + return src + } + if src == nil { + return dest + } + // Assume roles are the same. + dest.Parts = joinParts(dest.Parts, src.Parts) + return dest +} + +func joinParts(dest, src []Part) []Part { + return mergeTexts(append(dest, src...)) +} + +func mergeTexts(in []Part) []Part { + var out []Part + i := 0 + for i < len(in) { + if t, ok := in[i].(Text); ok { + texts := []string{string(t)} + var j int + for j = i + 1; j < len(in); j++ { + if t, ok := in[j].(Text); ok { + texts = append(texts, string(t)) + } else { + break + } + } + // j is just after the last Text. + out = append(out, Text(strings.Join(texts, ""))) + i = j + } else { + out = append(out, in[i]) + i++ + } + } + return out +} diff --git a/vendor/github.com/google/generative-ai-go/genai/config.yaml b/vendor/github.com/google/generative-ai-go/genai/config.yaml new file mode 100644 index 000000000..acaa46962 --- /dev/null +++ b/vendor/github.com/google/generative-ai-go/genai/config.yaml @@ -0,0 +1,186 @@ +# Copyright 2023 Google LLC +# +# 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. + +# Configuration for the protoveneer tool. + +package: genai + +protoImportPath: cloud.google.com/go/ai/generativelanguage/apiv1beta/generativelanguagepb +supportImportPath: github.com/google/generative-ai-go/internal/support + +types: + HarmCategory: + protoPrefix: HarmCategory_HARM_CATEGORY_ + docVerb: specifies + + SafetySetting_HarmBlockThreshold: + name: HarmBlockThreshold + protoPrefix: SafetySetting_BLOCK_ + veneerPrefix: HarmBlock + docVerb: specifies + valueNames: + SafetySetting_HARM_BLOCK_THRESHOLD_UNSPECIFIED: HarmBlockUnspecified + + SafetyRating_HarmProbability: + name: HarmProbability + protoPrefix: SafetyRating_ + docVerb: specifies + valueNames: + SafetyRating_HARM_PROBABILITY_UNSPECIFIED: HarmProbabilityUnspecified + + Candidate_FinishReason: + name: FinishReason + protoPrefix: Candidate_ + + GenerateContentResponse: + doc: 'is the response from a GenerateContent or GenerateContentStream call.' + + GenerateContentResponse_PromptFeedback_BlockReason: + name: BlockReason + protoPrefix: GenerateContentResponse_PromptFeedback_ + + Content: + fields: + Parts: + type: '[]Part' + + Blob: + fields: + MimeType: + name: MIMEType + docVerb: contains + + FileData: + fields: + MimeType: + name: MIMEType + FileUri: + name: URI + # TODO(jba): support field doc in protoveneer + # doc: 'The URI returned from UploadFile or GetFile.' + + GenerationConfig: + fields: + ResponseMimeType: + name: ResponseMIMEType + + SafetySetting: + + SafetyRating: + docVerb: 'is the' + + CitationMetadata: + + CitationSource: + docVerb: contains + fields: + Uri: + name: URI + License: + type: string + + Candidate: + fields: + Index: + type: int32 + GroundingAttributions: + omit: true + + GenerateContentResponse_PromptFeedback: + name: PromptFeedback + docVerb: contains + + CountTokensResponse: + + TaskType: + protoPrefix: TaskType + valueNames: + TaskType_TASK_TYPE_UNSPECIFIED: TaskTypeUnspecified + + EmbedContentResponse: + BatchEmbedContentsResponse: + + ContentEmbedding: + + Model: + name: ModelInfo + doc: 'is information about a language model.' + fields: + BaseModelId: + name: BaseModelID + Temperature: + type: float32 + TopP: + type: float32 + TopK: + type: int32 + + # Types for function calling + Tool: + ToolConfig: + FunctionDeclaration: + FunctionCall: + FunctionResponse: + Schema: + + Type: + protoPrefix: Type_ + veneerPrefix: '' + + FunctionCallingConfig: + doc: 'holds configuration for function calling.' + + FunctionCallingConfig_Mode: + name: FunctionCallingMode + protoPrefix: FunctionCallingConfig + veneerPrefix: FunctionCalling + valueNames: + FunctionCallingConfig_MODE_UNSPECIFIED: FunctionCallingUnspecified + + File: + fields: + Uri: + name: URI + MimeType: + name: MIMEType + Error: + # TODO(jba): support or convert status.Status + omit: true + Metadata: + # TODO(jba): support + omit: true + File_State: + name: FileState + docVerb: represents + protoPrefix: File + veneerPrefix: FileState + valueNames: + File_STATE_UNSPECIFIED: FileStateUnspecified + + GenerateContentResponse_UsageMetadata: + name: UsageMetadata + fields: + PromptTokenCount: + type: int32 + CandidatesTokenCount: + type: int32 + TotalTokenCount: + type: int32 + +# Omit everything not explicitly configured. +omitTypes: + - '*' + +converters: + Part: partToProto, partFromProto diff --git a/vendor/github.com/google/generative-ai-go/genai/content.go b/vendor/github.com/google/generative-ai-go/genai/content.go new file mode 100644 index 000000000..2c34d0e3b --- /dev/null +++ b/vendor/github.com/google/generative-ai-go/genai/content.go @@ -0,0 +1,145 @@ +// Copyright 2023 Google LLC +// +// 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. + +package genai + +import ( + "fmt" + + pb "cloud.google.com/go/ai/generativelanguage/apiv1beta/generativelanguagepb" +) + +const ( + roleUser = "user" + roleModel = "model" +) + +// A Part is either a Text, a Blob or a FunctionResponse. +type Part interface { + toPart() *pb.Part +} + +func partToProto(p Part) *pb.Part { + if p == nil { + return nil + } + return p.toPart() +} + +func partFromProto(p *pb.Part) Part { + switch d := p.Data.(type) { + case *pb.Part_Text: + return Text(d.Text) + case *pb.Part_InlineData: + return Blob{ + MIMEType: d.InlineData.MimeType, + Data: d.InlineData.Data, + } + case *pb.Part_FunctionCall: + return *(FunctionCall{}).fromProto(d.FunctionCall) + + case *pb.Part_FunctionResponse: + panic("FunctionResponse unimplemented") + + default: + panic(fmt.Errorf("unknown Part.Data type %T", p.Data)) + } +} + +// A Text is a piece of text, like a question or phrase. +type Text string + +func (t Text) toPart() *pb.Part { + return &pb.Part{ + Data: &pb.Part_Text{Text: string(t)}, + } +} + +func (b Blob) toPart() *pb.Part { + return &pb.Part{ + Data: &pb.Part_InlineData{ + InlineData: b.toProto(), + }, + } +} + +// ImageData is a convenience function for creating an image +// Blob for input to a model. +// The format should be the second part of the MIME type, after "image/". +// For example, for a PNG image, pass "png". +func ImageData(format string, data []byte) Blob { + return Blob{ + MIMEType: "image/" + format, + Data: data, + } +} + +func (f FunctionCall) toPart() *pb.Part { + return &pb.Part{ + Data: &pb.Part_FunctionCall{ + FunctionCall: f.toProto(), + }, + } +} + +func (f FunctionResponse) toPart() *pb.Part { + return &pb.Part{ + Data: &pb.Part_FunctionResponse{ + FunctionResponse: f.toProto(), + }, + } +} + +func (fd FileData) toPart() *pb.Part { + return &pb.Part{ + Data: &pb.Part_FileData{ + FileData: fd.toProto(), + }, + } +} + +// Ptr returns a pointer to its argument. +// It can be used to initialize pointer fields: +// +// model.Temperature = genai.Ptr[float32](0.1) +func Ptr[T any](t T) *T { return &t } + +// SetCandidateCount sets the CandidateCount field. +func (c *GenerationConfig) SetCandidateCount(x int32) { c.CandidateCount = &x } + +// SetMaxOutputTokens sets the MaxOutputTokens field. +func (c *GenerationConfig) SetMaxOutputTokens(x int32) { c.MaxOutputTokens = &x } + +// SetTemperature sets the Temperature field. +func (c *GenerationConfig) SetTemperature(x float32) { c.Temperature = &x } + +// SetTopP sets the TopP field. +func (c *GenerationConfig) SetTopP(x float32) { c.TopP = &x } + +// SetTopK sets the TopK field. +func (c *GenerationConfig) SetTopK(x int32) { c.TopK = &x } + +// FunctionCalls return all the FunctionCall parts in the candidate. +func (c *Candidate) FunctionCalls() []FunctionCall { + if c.Content == nil { + return nil + } + var fcs []FunctionCall + for _, p := range c.Content.Parts { + if fc, ok := p.(FunctionCall); ok { + fcs = append(fcs, fc) + } + } + return fcs +} diff --git a/vendor/github.com/google/generative-ai-go/genai/doc.go b/vendor/github.com/google/generative-ai-go/genai/doc.go new file mode 100644 index 000000000..b88bab537 --- /dev/null +++ b/vendor/github.com/google/generative-ai-go/genai/doc.go @@ -0,0 +1,32 @@ +// Copyright 2023 Google LLC +// +// 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. + +// Package genai is a client for the Google AI generative models. +// +// NOTE: This client uses the v1beta version of the API. +// +// # Getting started +// +// Reading the [examples] is the best way to learn how to use this package. +// +// # Authorization +// +// You will need an API key to use the service. +// See the [setup tutorial] for details. +// +// # Errors +// +// [examples]: https://pkg.go.dev/github.com/google/generative-ai-go/genai#pkg-examples +// [setup tutorial]: https://ai.google.dev/tutorials/setup +package genai diff --git a/vendor/github.com/google/generative-ai-go/genai/embed.go b/vendor/github.com/google/generative-ai-go/genai/embed.go new file mode 100644 index 000000000..8af76240f --- /dev/null +++ b/vendor/github.com/google/generative-ai-go/genai/embed.go @@ -0,0 +1,125 @@ +// Copyright 2023 Google LLC +// +// 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. + +package genai + +import ( + "context" + + pb "cloud.google.com/go/ai/generativelanguage/apiv1beta/generativelanguagepb" +) + +// EmbeddingModel creates a new instance of the named embedding model. +// Example name: "embedding-001" or "models/embedding-001". +func (c *Client) EmbeddingModel(name string) *EmbeddingModel { + return &EmbeddingModel{ + c: c, + name: name, + fullName: fullModelName(name), + } +} + +// EmbeddingModel is a model that computes embeddings. +// Create one with [Client.EmbeddingModel]. +type EmbeddingModel struct { + c *Client + name string + fullName string + // TaskType describes how the embedding will be used. + TaskType TaskType +} + +// Name returns the name of the EmbeddingModel. +func (m *EmbeddingModel) Name() string { + return m.name +} + +// EmbedContent returns an embedding for the list of parts. +func (m *EmbeddingModel) EmbedContent(ctx context.Context, parts ...Part) (*EmbedContentResponse, error) { + return m.EmbedContentWithTitle(ctx, "", parts...) +} + +// EmbedContentWithTitle returns an embedding for the list of parts. +// If the given title is non-empty, it is passed to the model and +// the task type is set to TaskTypeRetrievalDocument. +func (m *EmbeddingModel) EmbedContentWithTitle(ctx context.Context, title string, parts ...Part) (*EmbedContentResponse, error) { + req := newEmbedContentRequest(m.fullName, m.TaskType, title, parts) + res, err := m.c.c.EmbedContent(ctx, req) + if err != nil { + return nil, err + } + return (EmbedContentResponse{}).fromProto(res), nil +} + +func newEmbedContentRequest(model string, tt TaskType, title string, parts []Part) *pb.EmbedContentRequest { + req := &pb.EmbedContentRequest{ + Model: model, + Content: newUserContent(parts).toProto(), + } + // A non-empty title overrides the task type. + if title != "" { + req.Title = &title + tt = TaskTypeRetrievalDocument + } + if tt != TaskTypeUnspecified { + taskType := pb.TaskType(tt) + req.TaskType = &taskType + } + return req +} + +// An EmbeddingBatch holds a collection of embedding requests. +type EmbeddingBatch struct { + tt TaskType + req *pb.BatchEmbedContentsRequest +} + +// NewBatch returns a new, empty EmbeddingBatch with the same TaskType as the model. +// Make multiple calls to [EmbeddingBatch.AddContent] or [EmbeddingBatch.AddContentWithTitle]. +// Then pass the EmbeddingBatch to [EmbeddingModel.BatchEmbedContents] to get +// all the embeddings in a single call to the model. +func (m *EmbeddingModel) NewBatch() *EmbeddingBatch { + return &EmbeddingBatch{ + tt: m.TaskType, + req: &pb.BatchEmbedContentsRequest{ + Model: m.fullName, + }, + } +} + +// AddContent adds a content to the batch. +func (b *EmbeddingBatch) AddContent(parts ...Part) *EmbeddingBatch { + b.AddContentWithTitle("", parts...) + return b +} + +// AddContent adds a content to the batch with a title. +func (b *EmbeddingBatch) AddContentWithTitle(title string, parts ...Part) *EmbeddingBatch { + b.req.Requests = append(b.req.Requests, newEmbedContentRequest(b.req.Model, b.tt, title, parts)) + return b +} + +// BatchEmbedContents returns the embeddings for all the contents in the batch. +func (m *EmbeddingModel) BatchEmbedContents(ctx context.Context, b *EmbeddingBatch) (*BatchEmbedContentsResponse, error) { + res, err := m.c.c.BatchEmbedContents(ctx, b.req) + if err != nil { + return nil, err + } + return (BatchEmbedContentsResponse{}).fromProto(res), nil +} + +// Info returns information about the model. +func (m *EmbeddingModel) Info(ctx context.Context) (*ModelInfo, error) { + return m.c.modelInfo(ctx, m.fullName) +} diff --git a/vendor/github.com/google/generative-ai-go/genai/files.go b/vendor/github.com/google/generative-ai-go/genai/files.go new file mode 100644 index 000000000..07e69cc25 --- /dev/null +++ b/vendor/github.com/google/generative-ai-go/genai/files.go @@ -0,0 +1,123 @@ +// Copyright 2023 Google LLC +// +// 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. + +package genai + +//go:generate ../devtools/generate_discovery_client.sh + +import ( + "context" + "io" + "strings" + + gl "cloud.google.com/go/ai/generativelanguage/apiv1beta" + pb "cloud.google.com/go/ai/generativelanguage/apiv1beta/generativelanguagepb" + gld "github.com/google/generative-ai-go/genai/internal/generativelanguage/v1beta" // discovery client + "google.golang.org/api/googleapi" + "google.golang.org/api/iterator" +) + +// UploadFileOptions are options for [Client.UploadFile]. +type UploadFileOptions struct { + DisplayName string // a more readable name for the file + MIMEType string // the MIME type of the file; if omitted, it will be inferred +} + +// UploadFile copies the contents of the given io.Reader to file storage associated +// with the service, and returns information about the resulting file. +// +// The name may be empty, in which case a unique name will be generated. +// Otherwise, it can contain up to 40 characters that are lowercase +// alphanumeric or dashes (-), not starting or ending with a dash. +// The string "files/" is prepended to the name if it does not contain a '/'. +// +// Use the returned file's URI field with a [FileData] Part to use it for generation. +// +// It is an error to upload a file that already exists. +func (c *Client) UploadFile(ctx context.Context, name string, r io.Reader, opts *UploadFileOptions) (*File, error) { + if name != "" { + name = userNameToServiceName(name) + } + req := &gld.CreateFileRequest{ + File: &gld.File{Name: name}, + } + if opts != nil && opts.DisplayName != "" { + req.File.DisplayName = opts.DisplayName + } + call := c.ds.Media.Upload(req) + var mopts []googleapi.MediaOption + if opts != nil && opts.MIMEType != "" { + mopts = append(mopts, googleapi.ContentType(opts.MIMEType)) + } + call.Media(r, mopts...) + res, err := call.Do() + if err != nil { + return nil, err + } + // Don't return the result, because it contains a file as represented by the + // discovery client and we'd have to write code to convert it to this package's + // File type. + // Instead, make a GetFile call to get the proto file, which our generated code can convert. + return c.GetFile(ctx, res.File.Name) +} + +// GetFile returns the named file. +func (c *Client) GetFile(ctx context.Context, name string) (*File, error) { + pf, err := c.fc.GetFile(ctx, &pb.GetFileRequest{Name: userNameToServiceName(name)}) + if err != nil { + return nil, err + } + return (File{}).fromProto(pf), nil +} + +// DeleteFile deletes the file with the given name. +// It is an error to delete a file that does not exist. +func (c *Client) DeleteFile(ctx context.Context, name string) error { + return c.fc.DeleteFile(ctx, &pb.DeleteFileRequest{Name: userNameToServiceName(name)}) +} + +// userNameToServiceName converts a name supplied by the user to a name required by the service. +func userNameToServiceName(name string) string { + if strings.ContainsRune(name, '/') { + return name + } + return "files/" + name +} + +// ListFiles returns an iterator over the uploaded files. +func (c *Client) ListFiles(ctx context.Context) *FileIterator { + return &FileIterator{ + it: c.fc.ListFiles(ctx, &pb.ListFilesRequest{}), + } +} + +// A FileIterator iterates over Files. +type FileIterator struct { + it *gl.FileIterator +} + +// Next returns the next result. Its second return value is iterator.Done if there are no more +// results. Once Next returns Done, all subsequent calls will return Done. +func (it *FileIterator) Next() (*File, error) { + m, err := it.it.Next() + if err != nil { + return nil, err + } + return (File{}).fromProto(m), nil +} + +// PageInfo supports pagination. See the google.golang.org/api/iterator package for details. +func (it *FileIterator) PageInfo() *iterator.PageInfo { + return it.it.PageInfo() +} diff --git a/vendor/github.com/google/generative-ai-go/genai/generativelanguagepb_veneer.gen.go b/vendor/github.com/google/generative-ai-go/genai/generativelanguagepb_veneer.gen.go new file mode 100644 index 000000000..11ca1d2c0 --- /dev/null +++ b/vendor/github.com/google/generative-ai-go/genai/generativelanguagepb_veneer.gen.go @@ -0,0 +1,1369 @@ +// Copyright 2024 Google LLC +// +// 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. + +// This file was generated by protoveneer. DO NOT EDIT. + +package genai + +import ( + "fmt" + + pb "cloud.google.com/go/ai/generativelanguage/apiv1beta/generativelanguagepb" + "github.com/google/generative-ai-go/internal/support" + "google.golang.org/protobuf/types/known/timestamppb" + "time" +) + +// BatchEmbedContentsResponse is the response to a `BatchEmbedContentsRequest`. +type BatchEmbedContentsResponse struct { + // Output only. The embeddings for each request, in the same order as provided + // in the batch request. + Embeddings []*ContentEmbedding +} + +func (v *BatchEmbedContentsResponse) toProto() *pb.BatchEmbedContentsResponse { + if v == nil { + return nil + } + return &pb.BatchEmbedContentsResponse{ + Embeddings: support.TransformSlice(v.Embeddings, (*ContentEmbedding).toProto), + } +} + +func (BatchEmbedContentsResponse) fromProto(p *pb.BatchEmbedContentsResponse) *BatchEmbedContentsResponse { + if p == nil { + return nil + } + return &BatchEmbedContentsResponse{ + Embeddings: support.TransformSlice(p.Embeddings, (ContentEmbedding{}).fromProto), + } +} + +// Blob contains raw media bytes. +// +// Text should not be sent as raw bytes, use the 'text' field. +type Blob struct { + // The IANA standard MIME type of the source data. + // Examples: + // - image/png + // - image/jpeg + // + // If an unsupported MIME type is provided, an error will be returned. For a + // complete list of supported types, see [Supported file + // formats](https://ai.google.dev/gemini-api/docs/prompting_with_media#supported_file_formats). + MIMEType string + // Raw bytes for media formats. + Data []byte +} + +func (v *Blob) toProto() *pb.Blob { + if v == nil { + return nil + } + return &pb.Blob{ + MimeType: v.MIMEType, + Data: v.Data, + } +} + +func (Blob) fromProto(p *pb.Blob) *Blob { + if p == nil { + return nil + } + return &Blob{ + MIMEType: p.MimeType, + Data: p.Data, + } +} + +// BlockReason is specifies what was the reason why prompt was blocked. +type BlockReason int32 + +const ( + // BlockReasonUnspecified means default value. This value is unused. + BlockReasonUnspecified BlockReason = 0 + // BlockReasonSafety means prompt was blocked due to safety reasons. You can inspect + // `safety_ratings` to understand which safety category blocked it. + BlockReasonSafety BlockReason = 1 + // BlockReasonOther means prompt was blocked due to unknown reaasons. + BlockReasonOther BlockReason = 2 +) + +var namesForBlockReason = map[BlockReason]string{ + BlockReasonUnspecified: "BlockReasonUnspecified", + BlockReasonSafety: "BlockReasonSafety", + BlockReasonOther: "BlockReasonOther", +} + +func (v BlockReason) String() string { + if n, ok := namesForBlockReason[v]; ok { + return n + } + return fmt.Sprintf("BlockReason(%d)", v) +} + +// Candidate is a response candidate generated from the model. +type Candidate struct { + // Output only. Index of the candidate in the list of candidates. + Index int32 + // Output only. Generated content returned from the model. + Content *Content + // Optional. Output only. The reason why the model stopped generating tokens. + // + // If empty, the model has not stopped generating the tokens. + FinishReason FinishReason + // List of ratings for the safety of a response candidate. + // + // There is at most one rating per category. + SafetyRatings []*SafetyRating + // Output only. Citation information for model-generated candidate. + // + // This field may be populated with recitation information for any text + // included in the `content`. These are passages that are "recited" from + // copyrighted material in the foundational LLM's training data. + CitationMetadata *CitationMetadata + // Output only. Token count for this candidate. + TokenCount int32 +} + +func (v *Candidate) toProto() *pb.Candidate { + if v == nil { + return nil + } + return &pb.Candidate{ + Index: support.AddrOrNil(v.Index), + Content: v.Content.toProto(), + FinishReason: pb.Candidate_FinishReason(v.FinishReason), + SafetyRatings: support.TransformSlice(v.SafetyRatings, (*SafetyRating).toProto), + CitationMetadata: v.CitationMetadata.toProto(), + TokenCount: v.TokenCount, + } +} + +func (Candidate) fromProto(p *pb.Candidate) *Candidate { + if p == nil { + return nil + } + return &Candidate{ + Index: support.DerefOrZero(p.Index), + Content: (Content{}).fromProto(p.Content), + FinishReason: FinishReason(p.FinishReason), + SafetyRatings: support.TransformSlice(p.SafetyRatings, (SafetyRating{}).fromProto), + CitationMetadata: (CitationMetadata{}).fromProto(p.CitationMetadata), + TokenCount: p.TokenCount, + } +} + +// CitationMetadata is a collection of source attributions for a piece of content. +type CitationMetadata struct { + // Citations to sources for a specific response. + CitationSources []*CitationSource +} + +func (v *CitationMetadata) toProto() *pb.CitationMetadata { + if v == nil { + return nil + } + return &pb.CitationMetadata{ + CitationSources: support.TransformSlice(v.CitationSources, (*CitationSource).toProto), + } +} + +func (CitationMetadata) fromProto(p *pb.CitationMetadata) *CitationMetadata { + if p == nil { + return nil + } + return &CitationMetadata{ + CitationSources: support.TransformSlice(p.CitationSources, (CitationSource{}).fromProto), + } +} + +// CitationSource contains a citation to a source for a portion of a specific response. +type CitationSource struct { + // Optional. Start of segment of the response that is attributed to this + // source. + // + // Index indicates the start of the segment, measured in bytes. + StartIndex *int32 + // Optional. End of the attributed segment, exclusive. + EndIndex *int32 + // Optional. URI that is attributed as a source for a portion of the text. + URI *string + // Optional. License for the GitHub project that is attributed as a source for + // segment. + // + // License info is required for code citations. + License string +} + +func (v *CitationSource) toProto() *pb.CitationSource { + if v == nil { + return nil + } + return &pb.CitationSource{ + StartIndex: v.StartIndex, + EndIndex: v.EndIndex, + Uri: v.URI, + License: support.AddrOrNil(v.License), + } +} + +func (CitationSource) fromProto(p *pb.CitationSource) *CitationSource { + if p == nil { + return nil + } + return &CitationSource{ + StartIndex: p.StartIndex, + EndIndex: p.EndIndex, + URI: p.Uri, + License: support.DerefOrZero(p.License), + } +} + +// Content is the base structured datatype containing multi-part content of a message. +// +// A `Content` includes a `role` field designating the producer of the `Content` +// and a `parts` field containing multi-part data that contains the content of +// the message turn. +type Content struct { + // Ordered `Parts` that constitute a single message. Parts may have different + // MIME types. + Parts []Part + // Optional. The producer of the content. Must be either 'user' or 'model'. + // + // Useful to set for multi-turn conversations, otherwise can be left blank + // or unset. + Role string +} + +func (v *Content) toProto() *pb.Content { + if v == nil { + return nil + } + return &pb.Content{ + Parts: support.TransformSlice(v.Parts, partToProto), + Role: v.Role, + } +} + +func (Content) fromProto(p *pb.Content) *Content { + if p == nil { + return nil + } + return &Content{ + Parts: support.TransformSlice(p.Parts, partFromProto), + Role: p.Role, + } +} + +// ContentEmbedding is a list of floats representing an embedding. +type ContentEmbedding struct { + // The embedding values. + Values []float32 +} + +func (v *ContentEmbedding) toProto() *pb.ContentEmbedding { + if v == nil { + return nil + } + return &pb.ContentEmbedding{ + Values: v.Values, + } +} + +func (ContentEmbedding) fromProto(p *pb.ContentEmbedding) *ContentEmbedding { + if p == nil { + return nil + } + return &ContentEmbedding{ + Values: p.Values, + } +} + +// CountTokensResponse is a response from `CountTokens`. +// +// It returns the model's `token_count` for the `prompt`. +type CountTokensResponse struct { + // The number of tokens that the `model` tokenizes the `prompt` into. + // + // Always non-negative. + TotalTokens int32 +} + +func (v *CountTokensResponse) toProto() *pb.CountTokensResponse { + if v == nil { + return nil + } + return &pb.CountTokensResponse{ + TotalTokens: v.TotalTokens, + } +} + +func (CountTokensResponse) fromProto(p *pb.CountTokensResponse) *CountTokensResponse { + if p == nil { + return nil + } + return &CountTokensResponse{ + TotalTokens: p.TotalTokens, + } +} + +// EmbedContentResponse is the response to an `EmbedContentRequest`. +type EmbedContentResponse struct { + // Output only. The embedding generated from the input content. + Embedding *ContentEmbedding +} + +func (v *EmbedContentResponse) toProto() *pb.EmbedContentResponse { + if v == nil { + return nil + } + return &pb.EmbedContentResponse{ + Embedding: v.Embedding.toProto(), + } +} + +func (EmbedContentResponse) fromProto(p *pb.EmbedContentResponse) *EmbedContentResponse { + if p == nil { + return nil + } + return &EmbedContentResponse{ + Embedding: (ContentEmbedding{}).fromProto(p.Embedding), + } +} + +// File is a file uploaded to the API. +type File struct { + // Immutable. Identifier. The `File` resource name. The ID (name excluding the + // "files/" prefix) can contain up to 40 characters that are lowercase + // alphanumeric or dashes (-). The ID cannot start or end with a dash. If the + // name is empty on create, a unique name will be generated. Example: + // `files/123-456` + Name string + // Optional. The human-readable display name for the `File`. The display name + // must be no more than 512 characters in length, including spaces. Example: + // "Welcome Image" + DisplayName string + // Output only. MIME type of the file. + MIMEType string + // Output only. Size of the file in bytes. + SizeBytes int64 + // Output only. The timestamp of when the `File` was created. + CreateTime time.Time + // Output only. The timestamp of when the `File` was last updated. + UpdateTime time.Time + // Output only. The timestamp of when the `File` will be deleted. Only set if + // the `File` is scheduled to expire. + ExpirationTime time.Time + // Output only. SHA-256 hash of the uploaded bytes. + Sha256Hash []byte + // Output only. The uri of the `File`. + URI string + // Output only. Processing state of the File. + State FileState +} + +func (v *File) toProto() *pb.File { + if v == nil { + return nil + } + return &pb.File{ + Name: v.Name, + DisplayName: v.DisplayName, + MimeType: v.MIMEType, + SizeBytes: v.SizeBytes, + CreateTime: timestamppb.New(v.CreateTime), + UpdateTime: timestamppb.New(v.UpdateTime), + ExpirationTime: timestamppb.New(v.ExpirationTime), + Sha256Hash: v.Sha256Hash, + Uri: v.URI, + State: pb.File_State(v.State), + } +} + +func (File) fromProto(p *pb.File) *File { + if p == nil { + return nil + } + return &File{ + Name: p.Name, + DisplayName: p.DisplayName, + MIMEType: p.MimeType, + SizeBytes: p.SizeBytes, + CreateTime: support.TimeFromProto(p.CreateTime), + UpdateTime: support.TimeFromProto(p.UpdateTime), + ExpirationTime: support.TimeFromProto(p.ExpirationTime), + Sha256Hash: p.Sha256Hash, + URI: p.Uri, + State: FileState(p.State), + } +} + +// FileData is URI based data. +type FileData struct { + // Optional. The IANA standard MIME type of the source data. + MIMEType string + // Required. URI. + URI string +} + +func (v *FileData) toProto() *pb.FileData { + if v == nil { + return nil + } + return &pb.FileData{ + MimeType: v.MIMEType, + FileUri: v.URI, + } +} + +func (FileData) fromProto(p *pb.FileData) *FileData { + if p == nil { + return nil + } + return &FileData{ + MIMEType: p.MimeType, + URI: p.FileUri, + } +} + +// FileState represents states for the lifecycle of a File. +type FileState int32 + +const ( + // FileStateUnspecified means the default value. This value is used if the state is omitted. + FileStateUnspecified FileState = 0 + // FileStateProcessing means file is being processed and cannot be used for inference yet. + FileStateProcessing FileState = 1 + // FileStateActive means file is processed and available for inference. + FileStateActive FileState = 2 + // FileStateFailed means file failed processing. + FileStateFailed FileState = 10 +) + +var namesForFileState = map[FileState]string{ + FileStateUnspecified: "FileStateUnspecified", + FileStateProcessing: "FileStateProcessing", + FileStateActive: "FileStateActive", + FileStateFailed: "FileStateFailed", +} + +func (v FileState) String() string { + if n, ok := namesForFileState[v]; ok { + return n + } + return fmt.Sprintf("FileState(%d)", v) +} + +// FinishReason is defines the reason why the model stopped generating tokens. +type FinishReason int32 + +const ( + // FinishReasonUnspecified means default value. This value is unused. + FinishReasonUnspecified FinishReason = 0 + // FinishReasonStop means natural stop point of the model or provided stop sequence. + FinishReasonStop FinishReason = 1 + // FinishReasonMaxTokens means the maximum number of tokens as specified in the request was reached. + FinishReasonMaxTokens FinishReason = 2 + // FinishReasonSafety means the candidate content was flagged for safety reasons. + FinishReasonSafety FinishReason = 3 + // FinishReasonRecitation means the candidate content was flagged for recitation reasons. + FinishReasonRecitation FinishReason = 4 + // FinishReasonOther means unknown reason. + FinishReasonOther FinishReason = 5 +) + +var namesForFinishReason = map[FinishReason]string{ + FinishReasonUnspecified: "FinishReasonUnspecified", + FinishReasonStop: "FinishReasonStop", + FinishReasonMaxTokens: "FinishReasonMaxTokens", + FinishReasonSafety: "FinishReasonSafety", + FinishReasonRecitation: "FinishReasonRecitation", + FinishReasonOther: "FinishReasonOther", +} + +func (v FinishReason) String() string { + if n, ok := namesForFinishReason[v]; ok { + return n + } + return fmt.Sprintf("FinishReason(%d)", v) +} + +// FunctionCall is a predicted `FunctionCall` returned from the model that contains +// a string representing the `FunctionDeclaration.name` with the +// arguments and their values. +type FunctionCall struct { + // Required. The name of the function to call. + // Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum + // length of 63. + Name string + // Optional. The function parameters and values in JSON object format. + Args map[string]any +} + +func (v *FunctionCall) toProto() *pb.FunctionCall { + if v == nil { + return nil + } + return &pb.FunctionCall{ + Name: v.Name, + Args: support.MapToStructPB(v.Args), + } +} + +func (FunctionCall) fromProto(p *pb.FunctionCall) *FunctionCall { + if p == nil { + return nil + } + return &FunctionCall{ + Name: p.Name, + Args: support.MapFromStructPB(p.Args), + } +} + +// FunctionCallingConfig holds configuration for function calling. +type FunctionCallingConfig struct { + // Optional. Specifies the mode in which function calling should execute. If + // unspecified, the default value will be set to AUTO. + Mode FunctionCallingMode + // Optional. A set of function names that, when provided, limits the functions + // the model will call. + // + // This should only be set when the Mode is ANY. Function names + // should match [FunctionDeclaration.name]. With mode set to ANY, model will + // predict a function call from the set of function names provided. + AllowedFunctionNames []string +} + +func (v *FunctionCallingConfig) toProto() *pb.FunctionCallingConfig { + if v == nil { + return nil + } + return &pb.FunctionCallingConfig{ + Mode: pb.FunctionCallingConfig_Mode(v.Mode), + AllowedFunctionNames: v.AllowedFunctionNames, + } +} + +func (FunctionCallingConfig) fromProto(p *pb.FunctionCallingConfig) *FunctionCallingConfig { + if p == nil { + return nil + } + return &FunctionCallingConfig{ + Mode: FunctionCallingMode(p.Mode), + AllowedFunctionNames: p.AllowedFunctionNames, + } +} + +// FunctionCallingMode is defines the execution behavior for function calling by defining the +// execution mode. +type FunctionCallingMode int32 + +const ( + // FunctionCallingUnspecified means unspecified function calling mode. This value should not be used. + FunctionCallingUnspecified FunctionCallingMode = 0 + // FunctionCallingAuto means default model behavior, model decides to predict either a function call + // or a natural language repspose. + FunctionCallingAuto FunctionCallingMode = 1 + // FunctionCallingAny means model is constrained to always predicting a function call only. + // If "allowed_function_names" are set, the predicted function call will be + // limited to any one of "allowed_function_names", else the predicted + // function call will be any one of the provided "function_declarations". + FunctionCallingAny FunctionCallingMode = 2 + // FunctionCallingNone means model will not predict any function call. Model behavior is same as when + // not passing any function declarations. + FunctionCallingNone FunctionCallingMode = 3 +) + +var namesForFunctionCallingMode = map[FunctionCallingMode]string{ + FunctionCallingUnspecified: "FunctionCallingUnspecified", + FunctionCallingAuto: "FunctionCallingAuto", + FunctionCallingAny: "FunctionCallingAny", + FunctionCallingNone: "FunctionCallingNone", +} + +func (v FunctionCallingMode) String() string { + if n, ok := namesForFunctionCallingMode[v]; ok { + return n + } + return fmt.Sprintf("FunctionCallingMode(%d)", v) +} + +// FunctionDeclaration is structured representation of a function declaration as defined by the +// [OpenAPI 3.03 specification](https://spec.openapis.org/oas/v3.0.3). Included +// in this declaration are the function name and parameters. This +// FunctionDeclaration is a representation of a block of code that can be used +// as a `Tool` by the model and executed by the client. +type FunctionDeclaration struct { + // Required. The name of the function. + // Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum + // length of 63. + Name string + // Required. A brief description of the function. + Description string + // Optional. Describes the parameters to this function. Reflects the Open + // API 3.03 Parameter Object string Key: the name of the parameter. Parameter + // names are case sensitive. Schema Value: the Schema defining the type used + // for the parameter. + Parameters *Schema +} + +func (v *FunctionDeclaration) toProto() *pb.FunctionDeclaration { + if v == nil { + return nil + } + return &pb.FunctionDeclaration{ + Name: v.Name, + Description: v.Description, + Parameters: v.Parameters.toProto(), + } +} + +func (FunctionDeclaration) fromProto(p *pb.FunctionDeclaration) *FunctionDeclaration { + if p == nil { + return nil + } + return &FunctionDeclaration{ + Name: p.Name, + Description: p.Description, + Parameters: (Schema{}).fromProto(p.Parameters), + } +} + +// FunctionResponse is the result output from a `FunctionCall` that contains a string +// representing the `FunctionDeclaration.name` and a structured JSON +// object containing any output from the function is used as context to +// the model. This should contain the result of a`FunctionCall` made +// based on model prediction. +type FunctionResponse struct { + // Required. The name of the function to call. + // Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum + // length of 63. + Name string + // Required. The function response in JSON object format. + Response map[string]any +} + +func (v *FunctionResponse) toProto() *pb.FunctionResponse { + if v == nil { + return nil + } + return &pb.FunctionResponse{ + Name: v.Name, + Response: support.MapToStructPB(v.Response), + } +} + +func (FunctionResponse) fromProto(p *pb.FunctionResponse) *FunctionResponse { + if p == nil { + return nil + } + return &FunctionResponse{ + Name: p.Name, + Response: support.MapFromStructPB(p.Response), + } +} + +// GenerateContentResponse is the response from a GenerateContent or GenerateContentStream call. +// +// Note on safety ratings and content filtering. They are reported for both +// prompt in `GenerateContentResponse.prompt_feedback` and for each candidate +// in `finish_reason` and in `safety_ratings`. The API contract is that: +// - either all requested candidates are returned or no candidates at all +// - no candidates are returned only if there was something wrong with the +// prompt (see `prompt_feedback`) +// - feedback on each candidate is reported on `finish_reason` and +// `safety_ratings`. +type GenerateContentResponse struct { + // Candidate responses from the model. + Candidates []*Candidate + // Returns the prompt's feedback related to the content filters. + PromptFeedback *PromptFeedback + // Output only. Metadata on the generation requests' token usage. + UsageMetadata *UsageMetadata +} + +func (v *GenerateContentResponse) toProto() *pb.GenerateContentResponse { + if v == nil { + return nil + } + return &pb.GenerateContentResponse{ + Candidates: support.TransformSlice(v.Candidates, (*Candidate).toProto), + PromptFeedback: v.PromptFeedback.toProto(), + UsageMetadata: v.UsageMetadata.toProto(), + } +} + +func (GenerateContentResponse) fromProto(p *pb.GenerateContentResponse) *GenerateContentResponse { + if p == nil { + return nil + } + return &GenerateContentResponse{ + Candidates: support.TransformSlice(p.Candidates, (Candidate{}).fromProto), + PromptFeedback: (PromptFeedback{}).fromProto(p.PromptFeedback), + UsageMetadata: (UsageMetadata{}).fromProto(p.UsageMetadata), + } +} + +// GenerationConfig is configuration options for model generation and outputs. Not all parameters +// may be configurable for every model. +type GenerationConfig struct { + // Optional. Number of generated responses to return. + // + // Currently, this value can only be set to 1. If unset, this will default + // to 1. + CandidateCount *int32 + // Optional. The set of character sequences (up to 5) that will stop output + // generation. If specified, the API will stop at the first appearance of a + // stop sequence. The stop sequence will not be included as part of the + // response. + StopSequences []string + // Optional. The maximum number of tokens to include in a candidate. + // + // Note: The default value varies by model, see the `Model.output_token_limit` + // attribute of the `Model` returned from the `getModel` function. + MaxOutputTokens *int32 + // Optional. Controls the randomness of the output. + // + // Note: The default value varies by model, see the `Model.temperature` + // attribute of the `Model` returned from the `getModel` function. + // + // Values can range from [0.0, 2.0]. + Temperature *float32 + // Optional. The maximum cumulative probability of tokens to consider when + // sampling. + // + // The model uses combined Top-k and nucleus sampling. + // + // Tokens are sorted based on their assigned probabilities so that only the + // most likely tokens are considered. Top-k sampling directly limits the + // maximum number of tokens to consider, while Nucleus sampling limits number + // of tokens based on the cumulative probability. + // + // Note: The default value varies by model, see the `Model.top_p` + // attribute of the `Model` returned from the `getModel` function. + TopP *float32 + // Optional. The maximum number of tokens to consider when sampling. + // + // Models use nucleus sampling or combined Top-k and nucleus sampling. + // Top-k sampling considers the set of `top_k` most probable tokens. + // Models running with nucleus sampling don't allow top_k setting. + // + // Note: The default value varies by model, see the `Model.top_k` + // attribute of the `Model` returned from the `getModel` function. Empty + // `top_k` field in `Model` indicates the model doesn't apply top-k sampling + // and doesn't allow setting `top_k` on requests. + TopK *int32 + // Optional. Output response mimetype of the generated candidate text. + // Supported mimetype: + // `text/plain`: (default) Text output. + // `application/json`: JSON response in the candidates. + ResponseMIMEType string + // Optional. Output response schema of the generated candidate text when + // response mime type can have schema. Schema can be objects, primitives or + // arrays and is a subset of [OpenAPI + // schema](https://spec.openapis.org/oas/v3.0.3#schema). + // + // If set, a compatible response_mime_type must also be set. + // Compatible mimetypes: + // `application/json`: Schema for JSON response. + ResponseSchema *Schema +} + +func (v *GenerationConfig) toProto() *pb.GenerationConfig { + if v == nil { + return nil + } + return &pb.GenerationConfig{ + CandidateCount: v.CandidateCount, + StopSequences: v.StopSequences, + MaxOutputTokens: v.MaxOutputTokens, + Temperature: v.Temperature, + TopP: v.TopP, + TopK: v.TopK, + ResponseMimeType: v.ResponseMIMEType, + ResponseSchema: v.ResponseSchema.toProto(), + } +} + +func (GenerationConfig) fromProto(p *pb.GenerationConfig) *GenerationConfig { + if p == nil { + return nil + } + return &GenerationConfig{ + CandidateCount: p.CandidateCount, + StopSequences: p.StopSequences, + MaxOutputTokens: p.MaxOutputTokens, + Temperature: p.Temperature, + TopP: p.TopP, + TopK: p.TopK, + ResponseMIMEType: p.ResponseMimeType, + ResponseSchema: (Schema{}).fromProto(p.ResponseSchema), + } +} + +// HarmBlockThreshold specifies block at and beyond a specified harm probability. +type HarmBlockThreshold int32 + +const ( + // HarmBlockUnspecified means threshold is unspecified. + HarmBlockUnspecified HarmBlockThreshold = 0 + // HarmBlockLowAndAbove means content with NEGLIGIBLE will be allowed. + HarmBlockLowAndAbove HarmBlockThreshold = 1 + // HarmBlockMediumAndAbove means content with NEGLIGIBLE and LOW will be allowed. + HarmBlockMediumAndAbove HarmBlockThreshold = 2 + // HarmBlockOnlyHigh means content with NEGLIGIBLE, LOW, and MEDIUM will be allowed. + HarmBlockOnlyHigh HarmBlockThreshold = 3 + // HarmBlockNone means all content will be allowed. + HarmBlockNone HarmBlockThreshold = 4 +) + +var namesForHarmBlockThreshold = map[HarmBlockThreshold]string{ + HarmBlockUnspecified: "HarmBlockUnspecified", + HarmBlockLowAndAbove: "HarmBlockLowAndAbove", + HarmBlockMediumAndAbove: "HarmBlockMediumAndAbove", + HarmBlockOnlyHigh: "HarmBlockOnlyHigh", + HarmBlockNone: "HarmBlockNone", +} + +func (v HarmBlockThreshold) String() string { + if n, ok := namesForHarmBlockThreshold[v]; ok { + return n + } + return fmt.Sprintf("HarmBlockThreshold(%d)", v) +} + +// HarmCategory specifies the category of a rating. +// +// These categories cover various kinds of harms that developers +// may wish to adjust. +type HarmCategory int32 + +const ( + // HarmCategoryUnspecified means category is unspecified. + HarmCategoryUnspecified HarmCategory = 0 + // HarmCategoryDerogatory means negative or harmful comments targeting identity and/or protected attribute. + HarmCategoryDerogatory HarmCategory = 1 + // HarmCategoryToxicity means content that is rude, disrespectful, or profane. + HarmCategoryToxicity HarmCategory = 2 + // HarmCategoryViolence means describes scenarios depicting violence against an individual or group, or + // general descriptions of gore. + HarmCategoryViolence HarmCategory = 3 + // HarmCategorySexual means contains references to sexual acts or other lewd content. + HarmCategorySexual HarmCategory = 4 + // HarmCategoryMedical means promotes unchecked medical advice. + HarmCategoryMedical HarmCategory = 5 + // HarmCategoryDangerous means dangerous content that promotes, facilitates, or encourages harmful acts. + HarmCategoryDangerous HarmCategory = 6 + // HarmCategoryHarassment means harasment content. + HarmCategoryHarassment HarmCategory = 7 + // HarmCategoryHateSpeech means hate speech and content. + HarmCategoryHateSpeech HarmCategory = 8 + // HarmCategorySexuallyExplicit means sexually explicit content. + HarmCategorySexuallyExplicit HarmCategory = 9 + // HarmCategoryDangerousContent means dangerous content. + HarmCategoryDangerousContent HarmCategory = 10 +) + +var namesForHarmCategory = map[HarmCategory]string{ + HarmCategoryUnspecified: "HarmCategoryUnspecified", + HarmCategoryDerogatory: "HarmCategoryDerogatory", + HarmCategoryToxicity: "HarmCategoryToxicity", + HarmCategoryViolence: "HarmCategoryViolence", + HarmCategorySexual: "HarmCategorySexual", + HarmCategoryMedical: "HarmCategoryMedical", + HarmCategoryDangerous: "HarmCategoryDangerous", + HarmCategoryHarassment: "HarmCategoryHarassment", + HarmCategoryHateSpeech: "HarmCategoryHateSpeech", + HarmCategorySexuallyExplicit: "HarmCategorySexuallyExplicit", + HarmCategoryDangerousContent: "HarmCategoryDangerousContent", +} + +func (v HarmCategory) String() string { + if n, ok := namesForHarmCategory[v]; ok { + return n + } + return fmt.Sprintf("HarmCategory(%d)", v) +} + +// HarmProbability specifies the probability that a piece of content is harmful. +// +// The classification system gives the probability of the content being +// unsafe. This does not indicate the severity of harm for a piece of content. +type HarmProbability int32 + +const ( + // HarmProbabilityUnspecified means probability is unspecified. + HarmProbabilityUnspecified HarmProbability = 0 + // HarmProbabilityNegligible means content has a negligible chance of being unsafe. + HarmProbabilityNegligible HarmProbability = 1 + // HarmProbabilityLow means content has a low chance of being unsafe. + HarmProbabilityLow HarmProbability = 2 + // HarmProbabilityMedium means content has a medium chance of being unsafe. + HarmProbabilityMedium HarmProbability = 3 + // HarmProbabilityHigh means content has a high chance of being unsafe. + HarmProbabilityHigh HarmProbability = 4 +) + +var namesForHarmProbability = map[HarmProbability]string{ + HarmProbabilityUnspecified: "HarmProbabilityUnspecified", + HarmProbabilityNegligible: "HarmProbabilityNegligible", + HarmProbabilityLow: "HarmProbabilityLow", + HarmProbabilityMedium: "HarmProbabilityMedium", + HarmProbabilityHigh: "HarmProbabilityHigh", +} + +func (v HarmProbability) String() string { + if n, ok := namesForHarmProbability[v]; ok { + return n + } + return fmt.Sprintf("HarmProbability(%d)", v) +} + +// ModelInfo is information about a language model. +type ModelInfo struct { + // Required. The resource name of the `Model`. + // + // Format: `models/{model}` with a `{model}` naming convention of: + // + // * "{base_model_id}-{version}" + // + // Examples: + // + // * `models/chat-bison-001` + Name string + // Required. The name of the base model, pass this to the generation request. + // + // Examples: + // + // * `chat-bison` + BaseModelID string + // Required. The version number of the model. + // + // This represents the major version + Version string + // The human-readable name of the model. E.g. "Chat Bison". + // + // The name can be up to 128 characters long and can consist of any UTF-8 + // characters. + DisplayName string + // A short description of the model. + Description string + // Maximum number of input tokens allowed for this model. + InputTokenLimit int32 + // Maximum number of output tokens available for this model. + OutputTokenLimit int32 + // The model's supported generation methods. + // + // The method names are defined as Pascal case + // strings, such as `generateMessage` which correspond to API methods. + SupportedGenerationMethods []string + // Controls the randomness of the output. + // + // Values can range over `[0.0,1.0]`, inclusive. A value closer to `1.0` will + // produce responses that are more varied, while a value closer to `0.0` will + // typically result in less surprising responses from the model. + // This value specifies default to be used by the backend while making the + // call to the model. + Temperature float32 + // For Nucleus sampling. + // + // Nucleus sampling considers the smallest set of tokens whose probability + // sum is at least `top_p`. + // This value specifies default to be used by the backend while making the + // call to the model. + TopP float32 + // For Top-k sampling. + // + // Top-k sampling considers the set of `top_k` most probable tokens. + // This value specifies default to be used by the backend while making the + // call to the model. + // If empty, indicates the model doesn't use top-k sampling, and `top_k` isn't + // allowed as a generation parameter. + TopK int32 +} + +func (v *ModelInfo) toProto() *pb.Model { + if v == nil { + return nil + } + return &pb.Model{ + Name: v.Name, + BaseModelId: v.BaseModelID, + Version: v.Version, + DisplayName: v.DisplayName, + Description: v.Description, + InputTokenLimit: v.InputTokenLimit, + OutputTokenLimit: v.OutputTokenLimit, + SupportedGenerationMethods: v.SupportedGenerationMethods, + Temperature: support.AddrOrNil(v.Temperature), + TopP: support.AddrOrNil(v.TopP), + TopK: support.AddrOrNil(v.TopK), + } +} + +func (ModelInfo) fromProto(p *pb.Model) *ModelInfo { + if p == nil { + return nil + } + return &ModelInfo{ + Name: p.Name, + BaseModelID: p.BaseModelId, + Version: p.Version, + DisplayName: p.DisplayName, + Description: p.Description, + InputTokenLimit: p.InputTokenLimit, + OutputTokenLimit: p.OutputTokenLimit, + SupportedGenerationMethods: p.SupportedGenerationMethods, + Temperature: support.DerefOrZero(p.Temperature), + TopP: support.DerefOrZero(p.TopP), + TopK: support.DerefOrZero(p.TopK), + } +} + +// PromptFeedback contains a set of the feedback metadata the prompt specified in +// `GenerateContentRequest.content`. +type PromptFeedback struct { + // Optional. If set, the prompt was blocked and no candidates are returned. + // Rephrase your prompt. + BlockReason BlockReason + // Ratings for safety of the prompt. + // There is at most one rating per category. + SafetyRatings []*SafetyRating +} + +func (v *PromptFeedback) toProto() *pb.GenerateContentResponse_PromptFeedback { + if v == nil { + return nil + } + return &pb.GenerateContentResponse_PromptFeedback{ + BlockReason: pb.GenerateContentResponse_PromptFeedback_BlockReason(v.BlockReason), + SafetyRatings: support.TransformSlice(v.SafetyRatings, (*SafetyRating).toProto), + } +} + +func (PromptFeedback) fromProto(p *pb.GenerateContentResponse_PromptFeedback) *PromptFeedback { + if p == nil { + return nil + } + return &PromptFeedback{ + BlockReason: BlockReason(p.BlockReason), + SafetyRatings: support.TransformSlice(p.SafetyRatings, (SafetyRating{}).fromProto), + } +} + +// SafetyRating is the safety rating for a piece of content. +// +// The safety rating contains the category of harm and the +// harm probability level in that category for a piece of content. +// Content is classified for safety across a number of +// harm categories and the probability of the harm classification is included +// here. +type SafetyRating struct { + // Required. The category for this rating. + Category HarmCategory + // Required. The probability of harm for this content. + Probability HarmProbability + // Was this content blocked because of this rating? + Blocked bool +} + +func (v *SafetyRating) toProto() *pb.SafetyRating { + if v == nil { + return nil + } + return &pb.SafetyRating{ + Category: pb.HarmCategory(v.Category), + Probability: pb.SafetyRating_HarmProbability(v.Probability), + Blocked: v.Blocked, + } +} + +func (SafetyRating) fromProto(p *pb.SafetyRating) *SafetyRating { + if p == nil { + return nil + } + return &SafetyRating{ + Category: HarmCategory(p.Category), + Probability: HarmProbability(p.Probability), + Blocked: p.Blocked, + } +} + +// SafetySetting is safety setting, affecting the safety-blocking behavior. +// +// Passing a safety setting for a category changes the allowed probability that +// content is blocked. +type SafetySetting struct { + // Required. The category for this setting. + Category HarmCategory + // Required. Controls the probability threshold at which harm is blocked. + Threshold HarmBlockThreshold +} + +func (v *SafetySetting) toProto() *pb.SafetySetting { + if v == nil { + return nil + } + return &pb.SafetySetting{ + Category: pb.HarmCategory(v.Category), + Threshold: pb.SafetySetting_HarmBlockThreshold(v.Threshold), + } +} + +func (SafetySetting) fromProto(p *pb.SafetySetting) *SafetySetting { + if p == nil { + return nil + } + return &SafetySetting{ + Category: HarmCategory(p.Category), + Threshold: HarmBlockThreshold(p.Threshold), + } +} + +// Schema is the `Schema` object allows the definition of input and output data types. +// These types can be objects, but also primitives and arrays. +// Represents a select subset of an [OpenAPI 3.0 schema +// object](https://spec.openapis.org/oas/v3.0.3#schema). +type Schema struct { + // Required. Data type. + Type Type + // Optional. The format of the data. This is used only for primitive + // datatypes. Supported formats: + // + // for NUMBER type: float, double + // for INTEGER type: int32, int64 + Format string + // Optional. A brief description of the parameter. This could contain examples + // of use. Parameter description may be formatted as Markdown. + Description string + // Optional. Indicates if the value may be null. + Nullable bool + // Optional. Possible values of the element of Type.STRING with enum format. + // For example we can define an Enum Direction as : + // {type:STRING, format:enum, enum:["EAST", NORTH", "SOUTH", "WEST"]} + Enum []string + // Optional. Schema of the elements of Type.ARRAY. + Items *Schema + // Optional. Properties of Type.OBJECT. + Properties map[string]*Schema + // Optional. Required properties of Type.OBJECT. + Required []string +} + +func (v *Schema) toProto() *pb.Schema { + if v == nil { + return nil + } + return &pb.Schema{ + Type: pb.Type(v.Type), + Format: v.Format, + Description: v.Description, + Nullable: v.Nullable, + Enum: v.Enum, + Items: v.Items.toProto(), + Properties: support.TransformMapValues(v.Properties, (*Schema).toProto), + Required: v.Required, + } +} + +func (Schema) fromProto(p *pb.Schema) *Schema { + if p == nil { + return nil + } + return &Schema{ + Type: Type(p.Type), + Format: p.Format, + Description: p.Description, + Nullable: p.Nullable, + Enum: p.Enum, + Items: (Schema{}).fromProto(p.Items), + Properties: support.TransformMapValues(p.Properties, (Schema{}).fromProto), + Required: p.Required, + } +} + +// TaskType is type of task for which the embedding will be used. +type TaskType int32 + +const ( + // TaskTypeUnspecified means unset value, which will default to one of the other enum values. + TaskTypeUnspecified TaskType = 0 + // TaskTypeRetrievalQuery means specifies the given text is a query in a search/retrieval setting. + TaskTypeRetrievalQuery TaskType = 1 + // TaskTypeRetrievalDocument means specifies the given text is a document from the corpus being searched. + TaskTypeRetrievalDocument TaskType = 2 + // TaskTypeSemanticSimilarity means specifies the given text will be used for STS. + TaskTypeSemanticSimilarity TaskType = 3 + // TaskTypeClassification means specifies that the given text will be classified. + TaskTypeClassification TaskType = 4 + // TaskTypeClustering means specifies that the embeddings will be used for clustering. + TaskTypeClustering TaskType = 5 + // TaskTypeQuestionAnswering means specifies that the given text will be used for question answering. + TaskTypeQuestionAnswering TaskType = 6 + // TaskTypeFactVerification means specifies that the given text will be used for fact verification. + TaskTypeFactVerification TaskType = 7 +) + +var namesForTaskType = map[TaskType]string{ + TaskTypeUnspecified: "TaskTypeUnspecified", + TaskTypeRetrievalQuery: "TaskTypeRetrievalQuery", + TaskTypeRetrievalDocument: "TaskTypeRetrievalDocument", + TaskTypeSemanticSimilarity: "TaskTypeSemanticSimilarity", + TaskTypeClassification: "TaskTypeClassification", + TaskTypeClustering: "TaskTypeClustering", + TaskTypeQuestionAnswering: "TaskTypeQuestionAnswering", + TaskTypeFactVerification: "TaskTypeFactVerification", +} + +func (v TaskType) String() string { + if n, ok := namesForTaskType[v]; ok { + return n + } + return fmt.Sprintf("TaskType(%d)", v) +} + +// Tool details that the model may use to generate response. +// +// A `Tool` is a piece of code that enables the system to interact with +// external systems to perform an action, or set of actions, outside of +// knowledge and scope of the model. +type Tool struct { + // Optional. A list of `FunctionDeclarations` available to the model that can + // be used for function calling. + // + // The model or system does not execute the function. Instead the defined + // function may be returned as a [FunctionCall][content.part.function_call] + // with arguments to the client side for execution. The model may decide to + // call a subset of these functions by populating + // [FunctionCall][content.part.function_call] in the response. The next + // conversation turn may contain a + // [FunctionResponse][content.part.function_response] + // with the [content.role] "function" generation context for the next model + // turn. + FunctionDeclarations []*FunctionDeclaration +} + +func (v *Tool) toProto() *pb.Tool { + if v == nil { + return nil + } + return &pb.Tool{ + FunctionDeclarations: support.TransformSlice(v.FunctionDeclarations, (*FunctionDeclaration).toProto), + } +} + +func (Tool) fromProto(p *pb.Tool) *Tool { + if p == nil { + return nil + } + return &Tool{ + FunctionDeclarations: support.TransformSlice(p.FunctionDeclarations, (FunctionDeclaration{}).fromProto), + } +} + +// ToolConfig is the Tool configuration containing parameters for specifying `Tool` use +// in the request. +type ToolConfig struct { + // Optional. Function calling config. + FunctionCallingConfig *FunctionCallingConfig +} + +func (v *ToolConfig) toProto() *pb.ToolConfig { + if v == nil { + return nil + } + return &pb.ToolConfig{ + FunctionCallingConfig: v.FunctionCallingConfig.toProto(), + } +} + +func (ToolConfig) fromProto(p *pb.ToolConfig) *ToolConfig { + if p == nil { + return nil + } + return &ToolConfig{ + FunctionCallingConfig: (FunctionCallingConfig{}).fromProto(p.FunctionCallingConfig), + } +} + +// Type contains the list of OpenAPI data types as defined by +// https://spec.openapis.org/oas/v3.0.3#data-types +type Type int32 + +const ( + // TypeUnspecified means not specified, should not be used. + TypeUnspecified Type = 0 + // TypeString means string type. + TypeString Type = 1 + // TypeNumber means number type. + TypeNumber Type = 2 + // TypeInteger means integer type. + TypeInteger Type = 3 + // TypeBoolean means boolean type. + TypeBoolean Type = 4 + // TypeArray means array type. + TypeArray Type = 5 + // TypeObject means object type. + TypeObject Type = 6 +) + +var namesForType = map[Type]string{ + TypeUnspecified: "TypeUnspecified", + TypeString: "TypeString", + TypeNumber: "TypeNumber", + TypeInteger: "TypeInteger", + TypeBoolean: "TypeBoolean", + TypeArray: "TypeArray", + TypeObject: "TypeObject", +} + +func (v Type) String() string { + if n, ok := namesForType[v]; ok { + return n + } + return fmt.Sprintf("Type(%d)", v) +} + +// UsageMetadata is metadata on the generation request's token usage. +type UsageMetadata struct { + // Number of tokens in the prompt. + PromptTokenCount int32 + // Total number of tokens across the generated candidates. + CandidatesTokenCount int32 + // Total token count for the generation request (prompt + candidates). + TotalTokenCount int32 +} + +func (v *UsageMetadata) toProto() *pb.GenerateContentResponse_UsageMetadata { + if v == nil { + return nil + } + return &pb.GenerateContentResponse_UsageMetadata{ + PromptTokenCount: v.PromptTokenCount, + CandidatesTokenCount: v.CandidatesTokenCount, + TotalTokenCount: v.TotalTokenCount, + } +} + +func (UsageMetadata) fromProto(p *pb.GenerateContentResponse_UsageMetadata) *UsageMetadata { + if p == nil { + return nil + } + return &UsageMetadata{ + PromptTokenCount: p.PromptTokenCount, + CandidatesTokenCount: p.CandidatesTokenCount, + TotalTokenCount: p.TotalTokenCount, + } +} diff --git a/vendor/github.com/google/generative-ai-go/genai/internal/generativelanguage/v1beta/generativelanguage-api.json b/vendor/github.com/google/generative-ai-go/genai/internal/generativelanguage/v1beta/generativelanguage-api.json new file mode 100644 index 000000000..0ec3a9bb7 --- /dev/null +++ b/vendor/github.com/google/generative-ai-go/genai/internal/generativelanguage/v1beta/generativelanguage-api.json @@ -0,0 +1,4052 @@ +{ + "description": "The Gemini API allows developers to build generative AI applications using Gemini models. Gemini is our most capable model, built from the ground up to be multimodal. It can generalize and seamlessly understand, operate across, and combine different types of information including language, images, audio, video, and code. You can use the Gemini API for use cases like reasoning across text and images, content generation, dialogue agents, summarization and classification systems, and more.", + "version": "v1beta", + "version_module": true, + "ownerName": "Google", + "discoveryVersion": "v1", + "protocol": "rest", + "icons": { + "x16": "http://www.google.com/images/icons/product/search-16.gif", + "x32": "http://www.google.com/images/icons/product/search-32.gif" + }, + "kind": "discovery#restDescription", + "name": "generativelanguage", + "title": "Generative Language API", + "schemas": { + "ListTunedModelsResponse": { + "id": "ListTunedModelsResponse", + "properties": { + "nextPageToken": { + "description": "A token, which can be sent as `page_token` to retrieve the next page. If this field is omitted, there are no more pages.", + "type": "string" + }, + "tunedModels": { + "type": "array", + "description": "The returned Models.", + "items": { + "$ref": "TunedModel" + } + } + }, + "type": "object", + "description": "Response from `ListTunedModels` containing a paginated list of Models." + }, + "GenerateMessageResponse": { + "type": "object", + "description": "The response from the model. This includes candidate messages and conversation history in the form of chronologically-ordered messages.", + "id": "GenerateMessageResponse", + "properties": { + "filters": { + "description": "A set of content filtering metadata for the prompt and response text. This indicates which `SafetyCategory`(s) blocked a candidate from this response, the lowest `HarmProbability` that triggered a block, and the HarmThreshold setting for that category.", + "type": "array", + "items": { + "$ref": "ContentFilter" + } + }, + "messages": { + "description": "The conversation history used by the model.", + "items": { + "$ref": "Message" + }, + "type": "array" + }, + "candidates": { + "description": "Candidate response messages from the model.", + "type": "array", + "items": { + "$ref": "Message" + } + } + } + }, + "QueryCorpusResponse": { + "properties": { + "relevantChunks": { + "type": "array", + "description": "The relevant chunks.", + "items": { + "$ref": "RelevantChunk" + } + } + }, + "description": "Response from `QueryCorpus` containing a list of relevant chunks.", + "id": "QueryCorpusResponse", + "type": "object" + }, + "CreateChunkRequest": { + "id": "CreateChunkRequest", + "description": "Request to create a `Chunk`.", + "properties": { + "parent": { + "description": "Required. The name of the `Document` where this `Chunk` will be created. Example: `corpora/my-corpus-123/documents/the-doc-abc`", + "type": "string" + }, + "chunk": { + "description": "Required. The `Chunk` to create.", + "$ref": "Chunk" + } + }, + "type": "object" + }, + "CountTokensRequest": { + "description": "Counts the number of tokens in the `prompt` sent to a model. Models may tokenize text differently, so each model may return a different `token_count`.", + "type": "object", + "id": "CountTokensRequest", + "properties": { + "generateContentRequest": { + "$ref": "GenerateContentRequest", + "description": "Optional. The overall input given to the model. CountTokens will count prompt, function calling, etc." + }, + "contents": { + "description": "Optional. The input given to the model as a prompt. This field is ignored when `generate_content_request` is set.", + "items": { + "$ref": "Content" + }, + "type": "array" + } + } + }, + "EmbedContentResponse": { + "id": "EmbedContentResponse", + "type": "object", + "description": "The response to an `EmbedContentRequest`.", + "properties": { + "embedding": { + "$ref": "ContentEmbedding", + "description": "Output only. The embedding generated from the input content.", + "readOnly": true + } + } + }, + "ContentFilter": { + "id": "ContentFilter", + "type": "object", + "description": "Content filtering metadata associated with processing a single request. ContentFilter contains a reason and an optional supporting string. The reason may be unspecified.", + "properties": { + "message": { + "type": "string", + "description": "A string that describes the filtering behavior in more detail." + }, + "reason": { + "description": "The reason content was blocked during request processing.", + "type": "string", + "enum": [ + "BLOCKED_REASON_UNSPECIFIED", + "SAFETY", + "OTHER" + ], + "enumDescriptions": [ + "A blocked reason was not specified.", + "Content was blocked by safety settings.", + "Content was blocked, but the reason is uncategorized." + ] + } + } + }, + "GroundingPassages": { + "description": "A repeated list of passages.", + "properties": { + "passages": { + "description": "List of passages.", + "items": { + "$ref": "GroundingPassage" + }, + "type": "array" + } + }, + "type": "object", + "id": "GroundingPassages" + }, + "TransferOwnershipRequest": { + "properties": { + "emailAddress": { + "type": "string", + "description": "Required. The email address of the user to whom the tuned model is being transferred to." + } + }, + "type": "object", + "id": "TransferOwnershipRequest", + "description": "Request to transfer the ownership of the tuned model." + }, + "CitationMetadata": { + "type": "object", + "id": "CitationMetadata", + "properties": { + "citationSources": { + "items": { + "$ref": "CitationSource" + }, + "type": "array", + "description": "Citations to sources for a specific response." + } + }, + "description": "A collection of source attributions for a piece of content." + }, + "Permission": { + "description": "Permission resource grants user, group or the rest of the world access to the PaLM API resource (e.g. a tuned model, corpus). A role is a collection of permitted operations that allows users to perform specific actions on PaLM API resources. To make them available to users, groups, or service accounts, you assign roles. When you assign a role, you grant permissions that the role contains. There are three concentric roles. Each role is a superset of the previous role's permitted operations: - reader can use the resource (e.g. tuned model, corpus) for inference - writer has reader's permissions and additionally can edit and share - owner has writer's permissions and additionally can delete", + "type": "object", + "id": "Permission", + "properties": { + "granteeType": { + "enumDescriptions": [ + "The default value. This value is unused.", + "Represents a user. When set, you must provide email_address for the user.", + "Represents a group. When set, you must provide email_address for the group.", + "Represents access to everyone. No extra information is required." + ], + "enum": [ + "GRANTEE_TYPE_UNSPECIFIED", + "USER", + "GROUP", + "EVERYONE" + ], + "type": "string", + "description": "Optional. Immutable. The type of the grantee." + }, + "name": { + "type": "string", + "description": "Output only. Identifier. The permission name. A unique name will be generated on create. Examples: tunedModels/{tuned_model}/permissions/{permission} corpora/{corpus}/permissions/{permission} Output only.", + "readOnly": true + }, + "role": { + "enum": [ + "ROLE_UNSPECIFIED", + "OWNER", + "WRITER", + "READER" + ], + "enumDescriptions": [ + "The default value. This value is unused.", + "Owner can use, update, share and delete the resource.", + "Writer can use, update and share the resource.", + "Reader can use the resource." + ], + "description": "Required. The role granted by this permission.", + "type": "string" + }, + "emailAddress": { + "description": "Optional. Immutable. The email address of the user of group which this permission refers. Field is not set when permission's grantee type is EVERYONE.", + "type": "string" + } + } + }, + "EmbedTextRequest": { + "id": "EmbedTextRequest", + "description": "Request to get a text embedding from the model.", + "type": "object", + "properties": { + "text": { + "description": "Optional. The free-form input text that the model will turn into an embedding.", + "type": "string" + }, + "model": { + "description": "Required. The model name to use with the format model=models/{model}.", + "type": "string" + } + } + }, + "Content": { + "description": "The base structured datatype containing multi-part content of a message. A `Content` includes a `role` field designating the producer of the `Content` and a `parts` field containing multi-part data that contains the content of the message turn.", + "properties": { + "parts": { + "description": "Ordered `Parts` that constitute a single message. Parts may have different MIME types.", + "type": "array", + "items": { + "$ref": "Part" + } + }, + "role": { + "type": "string", + "description": "Optional. The producer of the content. Must be either 'user' or 'model'. Useful to set for multi-turn conversations, otherwise can be left blank or unset." + } + }, + "id": "Content", + "type": "object" + }, + "VideoMetadata": { + "id": "VideoMetadata", + "type": "object", + "properties": { + "videoDuration": { + "description": "Duration of the video.", + "format": "google-duration", + "type": "string" + } + }, + "description": "Metadata for a video `File`." + }, + "FunctionDeclaration": { + "id": "FunctionDeclaration", + "properties": { + "name": { + "type": "string", + "description": "Required. The name of the function. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 63." + }, + "parameters": { + "$ref": "Schema", + "description": "Optional. Describes the parameters to this function. Reflects the Open API 3.03 Parameter Object string Key: the name of the parameter. Parameter names are case sensitive. Schema Value: the Schema defining the type used for the parameter." + }, + "description": { + "description": "Required. A brief description of the function.", + "type": "string" + } + }, + "description": "Structured representation of a function declaration as defined by the [OpenAPI 3.03 specification](https://spec.openapis.org/oas/v3.0.3). Included in this declaration are the function name and parameters. This FunctionDeclaration is a representation of a block of code that can be used as a `Tool` by the model and executed by the client.", + "type": "object" + }, + "QueryCorpusRequest": { + "id": "QueryCorpusRequest", + "properties": { + "query": { + "description": "Required. Query string to perform semantic search.", + "type": "string" + }, + "metadataFilters": { + "description": "Optional. Filter for `Chunk` and `Document` metadata. Each `MetadataFilter` object should correspond to a unique key. Multiple `MetadataFilter` objects are joined by logical \"AND\"s. Example query at document level: (year \u003e= 2020 OR year \u003c 2010) AND (genre = drama OR genre = action) `MetadataFilter` object list: metadata_filters = [ {key = \"document.custom_metadata.year\" conditions = [{int_value = 2020, operation = GREATER_EQUAL}, {int_value = 2010, operation = LESS}]}, {key = \"document.custom_metadata.year\" conditions = [{int_value = 2020, operation = GREATER_EQUAL}, {int_value = 2010, operation = LESS}]}, {key = \"document.custom_metadata.genre\" conditions = [{string_value = \"drama\", operation = EQUAL}, {string_value = \"action\", operation = EQUAL}]}] Example query at chunk level for a numeric range of values: (year \u003e 2015 AND year \u003c= 2020) `MetadataFilter` object list: metadata_filters = [ {key = \"chunk.custom_metadata.year\" conditions = [{int_value = 2015, operation = GREATER}]}, {key = \"chunk.custom_metadata.year\" conditions = [{int_value = 2020, operation = LESS_EQUAL}]}] Note: \"AND\"s for the same key are only supported for numeric values. String values only support \"OR\"s for the same key.", + "type": "array", + "items": { + "$ref": "MetadataFilter" + } + }, + "resultsCount": { + "format": "int32", + "description": "Optional. The maximum number of `Chunk`s to return. The service may return fewer `Chunk`s. If unspecified, at most 10 `Chunk`s will be returned. The maximum specified result count is 100.", + "type": "integer" + } + }, + "description": "Request for querying a `Corpus`.", + "type": "object" + }, + "GenerateContentResponse": { + "description": "Response from the model supporting multiple candidates. Note on safety ratings and content filtering. They are reported for both prompt in `GenerateContentResponse.prompt_feedback` and for each candidate in `finish_reason` and in `safety_ratings`. The API contract is that: - either all requested candidates are returned or no candidates at all - no candidates are returned only if there was something wrong with the prompt (see `prompt_feedback`) - feedback on each candidate is reported on `finish_reason` and `safety_ratings`.", + "properties": { + "candidates": { + "items": { + "$ref": "Candidate" + }, + "type": "array", + "description": "Candidate responses from the model." + }, + "usageMetadata": { + "description": "Output only. Metadata on the generation requests' token usage.", + "readOnly": true, + "$ref": "UsageMetadata" + }, + "promptFeedback": { + "$ref": "PromptFeedback", + "description": "Returns the prompt's feedback related to the content filters." + } + }, + "id": "GenerateContentResponse", + "type": "object" + }, + "TuningExample": { + "properties": { + "output": { + "description": "Required. The expected model output.", + "type": "string" + }, + "textInput": { + "description": "Optional. Text model input.", + "type": "string" + } + }, + "id": "TuningExample", + "description": "A single example for tuning.", + "type": "object" + }, + "Embedding": { + "properties": { + "value": { + "items": { + "format": "float", + "type": "number" + }, + "description": "The embedding values.", + "type": "array" + } + }, + "id": "Embedding", + "description": "A list of floats representing the embedding.", + "type": "object" + }, + "BatchEmbedTextResponse": { + "description": "The response to a EmbedTextRequest.", + "type": "object", + "id": "BatchEmbedTextResponse", + "properties": { + "embeddings": { + "description": "Output only. The embeddings generated from the input text.", + "items": { + "$ref": "Embedding" + }, + "readOnly": true, + "type": "array" + } + } + }, + "BatchEmbedContentsRequest": { + "id": "BatchEmbedContentsRequest", + "properties": { + "requests": { + "description": "Required. Embed requests for the batch. The model in each of these requests must match the model specified `BatchEmbedContentsRequest.model`.", + "type": "array", + "items": { + "$ref": "EmbedContentRequest" + } + } + }, + "type": "object", + "description": "Batch request to get embeddings from the model for a list of prompts." + }, + "Part": { + "properties": { + "inlineData": { + "$ref": "Blob", + "description": "Inline media bytes." + }, + "functionCall": { + "$ref": "FunctionCall", + "description": "A predicted `FunctionCall` returned from the model that contains a string representing the `FunctionDeclaration.name` with the arguments and their values." + }, + "fileData": { + "description": "URI based data.", + "$ref": "FileData" + }, + "functionResponse": { + "$ref": "FunctionResponse", + "description": "The result output of a `FunctionCall` that contains a string representing the `FunctionDeclaration.name` and a structured JSON object containing any output from the function is used as context to the model." + }, + "text": { + "description": "Inline text.", + "type": "string" + } + }, + "description": "A datatype containing media that is part of a multi-part `Content` message. A `Part` consists of data which has an associated datatype. A `Part` can only contain one of the accepted types in `Part.data`. A `Part` must have a fixed IANA MIME type identifying the type and subtype of the media if the `inline_data` field is filled with raw bytes.", + "id": "Part", + "type": "object" + }, + "Blob": { + "type": "object", + "description": "Raw media bytes. Text should not be sent as raw bytes, use the 'text' field.", + "properties": { + "data": { + "format": "byte", + "description": "Raw bytes for media formats.", + "type": "string" + }, + "mimeType": { + "description": "The IANA standard MIME type of the source data. Examples: - image/png - image/jpeg If an unsupported MIME type is provided, an error will be returned. For a complete list of supported types, see [Supported file formats](https://ai.google.dev/gemini-api/docs/prompting_with_media#supported_file_formats).", + "type": "string" + } + }, + "id": "Blob" + }, + "Candidate": { + "type": "object", + "properties": { + "tokenCount": { + "description": "Output only. Token count for this candidate.", + "format": "int32", + "type": "integer", + "readOnly": true + }, + "groundingAttributions": { + "items": { + "$ref": "GroundingAttribution" + }, + "type": "array", + "readOnly": true, + "description": "Output only. Attribution information for sources that contributed to a grounded answer. This field is populated for `GenerateAnswer` calls." + }, + "content": { + "description": "Output only. Generated content returned from the model.", + "$ref": "Content", + "readOnly": true + }, + "index": { + "type": "integer", + "format": "int32", + "readOnly": true, + "description": "Output only. Index of the candidate in the list of candidates." + }, + "safetyRatings": { + "items": { + "$ref": "SafetyRating" + }, + "type": "array", + "description": "List of ratings for the safety of a response candidate. There is at most one rating per category." + }, + "citationMetadata": { + "description": "Output only. Citation information for model-generated candidate. This field may be populated with recitation information for any text included in the `content`. These are passages that are \"recited\" from copyrighted material in the foundational LLM's training data.", + "readOnly": true, + "$ref": "CitationMetadata" + }, + "finishReason": { + "description": "Optional. Output only. The reason why the model stopped generating tokens. If empty, the model has not stopped generating the tokens.", + "readOnly": true, + "enumDescriptions": [ + "Default value. This value is unused.", + "Natural stop point of the model or provided stop sequence.", + "The maximum number of tokens as specified in the request was reached.", + "The candidate content was flagged for safety reasons.", + "The candidate content was flagged for recitation reasons.", + "Unknown reason." + ], + "enum": [ + "FINISH_REASON_UNSPECIFIED", + "STOP", + "MAX_TOKENS", + "SAFETY", + "RECITATION", + "OTHER" + ], + "type": "string" + } + }, + "id": "Candidate", + "description": "A response candidate generated from the model." + }, + "QueryDocumentResponse": { + "type": "object", + "description": "Response from `QueryDocument` containing a list of relevant chunks.", + "id": "QueryDocumentResponse", + "properties": { + "relevantChunks": { + "description": "The returned relevant chunks.", + "type": "array", + "items": { + "$ref": "RelevantChunk" + } + } + } + }, + "Operation": { + "type": "object", + "properties": { + "done": { + "description": "If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.", + "type": "boolean" + }, + "error": { + "description": "The error result of the operation in case of failure or cancellation.", + "$ref": "Status" + }, + "name": { + "description": "The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.", + "type": "string" + }, + "response": { + "description": "The normal, successful response of the operation. If the original method returns no data on success, such as `Delete`, the response is `google.protobuf.Empty`. If the original method is standard `Get`/`Create`/`Update`, the response should be the resource. For other methods, the response should have the type `XxxResponse`, where `Xxx` is the original method name. For example, if the original method name is `TakeSnapshot()`, the inferred response type is `TakeSnapshotResponse`.", + "type": "object", + "additionalProperties": { + "description": "Properties of the object. Contains field @type with type URL.", + "type": "any" + } + }, + "metadata": { + "additionalProperties": { + "description": "Properties of the object. Contains field @type with type URL.", + "type": "any" + }, + "description": "Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.", + "type": "object" + } + }, + "id": "Operation", + "description": "This resource represents a long-running operation that is the result of a network API call." + }, + "GenerateAnswerResponse": { + "type": "object", + "properties": { + "answerableProbability": { + "type": "number", + "readOnly": true, + "format": "float", + "description": "Output only. The model's estimate of the probability that its answer is correct and grounded in the input passages. A low answerable_probability indicates that the answer might not be grounded in the sources. When `answerable_probability` is low, some clients may wish to: * Display a message to the effect of \"We couldn’t answer that question\" to the user. * Fall back to a general-purpose LLM that answers the question from world knowledge. The threshold and nature of such fallbacks will depend on individual clients’ use cases. 0.5 is a good starting threshold." + }, + "answer": { + "description": "Candidate answer from the model. Note: The model *always* attempts to provide a grounded answer, even when the answer is unlikely to be answerable from the given passages. In that case, a low-quality or ungrounded answer may be provided, along with a low `answerable_probability`.", + "$ref": "Candidate" + }, + "inputFeedback": { + "$ref": "InputFeedback", + "readOnly": true, + "description": "Output only. Feedback related to the input data used to answer the question, as opposed to model-generated response to the question. \"Input data\" can be one or more of the following: - Question specified by the last entry in `GenerateAnswerRequest.content` - Conversation history specified by the other entries in `GenerateAnswerRequest.content` - Grounding sources (`GenerateAnswerRequest.semantic_retriever` or `GenerateAnswerRequest.inline_passages`)" + } + }, + "id": "GenerateAnswerResponse", + "description": "Response from the model for a grounded answer." + }, + "GenerateContentRequest": { + "properties": { + "contents": { + "description": "Required. The content of the current conversation with the model. For single-turn queries, this is a single instance. For multi-turn queries, this is a repeated field that contains conversation history + latest request.", + "type": "array", + "items": { + "$ref": "Content" + } + }, + "model": { + "description": "Required. The name of the `Model` to use for generating the completion. Format: `name=models/{model}`.", + "type": "string" + }, + "safetySettings": { + "type": "array", + "items": { + "$ref": "SafetySetting" + }, + "description": "Optional. A list of unique `SafetySetting` instances for blocking unsafe content. This will be enforced on the `GenerateContentRequest.contents` and `GenerateContentResponse.candidates`. There should not be more than one setting for each `SafetyCategory` type. The API will block any contents and responses that fail to meet the thresholds set by these settings. This list overrides the default settings for each `SafetyCategory` specified in the safety_settings. If there is no `SafetySetting` for a given `SafetyCategory` provided in the list, the API will use the default safety setting for that category. Harm categories HARM_CATEGORY_HATE_SPEECH, HARM_CATEGORY_SEXUALLY_EXPLICIT, HARM_CATEGORY_DANGEROUS_CONTENT, HARM_CATEGORY_HARASSMENT are supported." + }, + "toolConfig": { + "description": "Optional. Tool configuration for any `Tool` specified in the request.", + "$ref": "ToolConfig" + }, + "tools": { + "items": { + "$ref": "Tool" + }, + "type": "array", + "description": "Optional. A list of `Tools` the model may use to generate the next response. A `Tool` is a piece of code that enables the system to interact with external systems to perform an action, or set of actions, outside of knowledge and scope of the model. The only supported tool is currently `Function`." + }, + "systemInstruction": { + "$ref": "Content", + "description": "Optional. Developer set system instruction. Currently, text only." + }, + "generationConfig": { + "$ref": "GenerationConfig", + "description": "Optional. Configuration options for model generation and outputs." + } + }, + "description": "Request to generate a completion from the model.", + "type": "object", + "id": "GenerateContentRequest" + }, + "InputFeedback": { + "type": "object", + "properties": { + "safetyRatings": { + "type": "array", + "description": "Ratings for safety of the input. There is at most one rating per category.", + "items": { + "$ref": "SafetyRating" + } + }, + "blockReason": { + "type": "string", + "enumDescriptions": [ + "Default value. This value is unused.", + "Input was blocked due to safety reasons. You can inspect `safety_ratings` to understand which safety category blocked it.", + "Input was blocked due to other reasons." + ], + "enum": [ + "BLOCK_REASON_UNSPECIFIED", + "SAFETY", + "OTHER" + ], + "description": "Optional. If set, the input was blocked and no candidates are returned. Rephrase your input." + } + }, + "id": "InputFeedback", + "description": "Feedback related to the input data used to answer the question, as opposed to model-generated response to the question." + }, + "GenerateTextRequest": { + "properties": { + "candidateCount": { + "type": "integer", + "description": "Optional. Number of generated responses to return. This value must be between [1, 8], inclusive. If unset, this will default to 1.", + "format": "int32" + }, + "prompt": { + "$ref": "TextPrompt", + "description": "Required. The free-form input text given to the model as a prompt. Given a prompt, the model will generate a TextCompletion response it predicts as the completion of the input text." + }, + "safetySettings": { + "type": "array", + "items": { + "$ref": "SafetySetting" + }, + "description": "Optional. A list of unique `SafetySetting` instances for blocking unsafe content. that will be enforced on the `GenerateTextRequest.prompt` and `GenerateTextResponse.candidates`. There should not be more than one setting for each `SafetyCategory` type. The API will block any prompts and responses that fail to meet the thresholds set by these settings. This list overrides the default settings for each `SafetyCategory` specified in the safety_settings. If there is no `SafetySetting` for a given `SafetyCategory` provided in the list, the API will use the default safety setting for that category. Harm categories HARM_CATEGORY_DEROGATORY, HARM_CATEGORY_TOXICITY, HARM_CATEGORY_VIOLENCE, HARM_CATEGORY_SEXUAL, HARM_CATEGORY_MEDICAL, HARM_CATEGORY_DANGEROUS are supported in text service." + }, + "topP": { + "type": "number", + "description": "Optional. The maximum cumulative probability of tokens to consider when sampling. The model uses combined Top-k and nucleus sampling. Tokens are sorted based on their assigned probabilities so that only the most likely tokens are considered. Top-k sampling directly limits the maximum number of tokens to consider, while Nucleus sampling limits number of tokens based on the cumulative probability. Note: The default value varies by model, see the `Model.top_p` attribute of the `Model` returned the `getModel` function.", + "format": "float" + }, + "maxOutputTokens": { + "description": "Optional. The maximum number of tokens to include in a candidate. If unset, this will default to output_token_limit specified in the `Model` specification.", + "type": "integer", + "format": "int32" + }, + "stopSequences": { + "type": "array", + "description": "The set of character sequences (up to 5) that will stop output generation. If specified, the API will stop at the first appearance of a stop sequence. The stop sequence will not be included as part of the response.", + "items": { + "type": "string" + } + }, + "temperature": { + "format": "float", + "description": "Optional. Controls the randomness of the output. Note: The default value varies by model, see the `Model.temperature` attribute of the `Model` returned the `getModel` function. Values can range from [0.0,1.0], inclusive. A value closer to 1.0 will produce responses that are more varied and creative, while a value closer to 0.0 will typically result in more straightforward responses from the model.", + "type": "number" + }, + "topK": { + "description": "Optional. The maximum number of tokens to consider when sampling. The model uses combined Top-k and nucleus sampling. Top-k sampling considers the set of `top_k` most probable tokens. Defaults to 40. Note: The default value varies by model, see the `Model.top_k` attribute of the `Model` returned the `getModel` function.", + "format": "int32", + "type": "integer" + } + }, + "id": "GenerateTextRequest", + "type": "object", + "description": "Request to generate a text completion response from the model." + }, + "RelevantChunk": { + "properties": { + "chunkRelevanceScore": { + "type": "number", + "format": "float", + "description": "`Chunk` relevance to the query." + }, + "chunk": { + "$ref": "Chunk", + "description": "`Chunk` associated with the query." + } + }, + "id": "RelevantChunk", + "type": "object", + "description": "The information for a chunk relevant to a query." + }, + "Empty": { + "description": "A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical example is to use it as the request or the response type of an API method. For instance: service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); }", + "id": "Empty", + "properties": {}, + "type": "object" + }, + "SemanticRetrieverConfig": { + "id": "SemanticRetrieverConfig", + "description": "Configuration for retrieving grounding content from a `Corpus` or `Document` created using the Semantic Retriever API.", + "type": "object", + "properties": { + "maxChunksCount": { + "type": "integer", + "description": "Optional. Maximum number of relevant `Chunk`s to retrieve.", + "format": "int32" + }, + "metadataFilters": { + "type": "array", + "items": { + "$ref": "MetadataFilter" + }, + "description": "Optional. Filters for selecting `Document`s and/or `Chunk`s from the resource." + }, + "query": { + "description": "Required. Query to use for similarity matching `Chunk`s in the given resource.", + "$ref": "Content" + }, + "minimumRelevanceScore": { + "format": "float", + "description": "Optional. Minimum relevance score for retrieved relevant `Chunk`s.", + "type": "number" + }, + "source": { + "type": "string", + "description": "Required. Name of the resource for retrieval, e.g. corpora/123 or corpora/123/documents/abc." + } + } + }, + "GenerateTextResponse": { + "properties": { + "candidates": { + "description": "Candidate responses from the model.", + "items": { + "$ref": "TextCompletion" + }, + "type": "array" + }, + "safetyFeedback": { + "description": "Returns any safety feedback related to content filtering.", + "type": "array", + "items": { + "$ref": "SafetyFeedback" + } + }, + "filters": { + "description": "A set of content filtering metadata for the prompt and response text. This indicates which `SafetyCategory`(s) blocked a candidate from this response, the lowest `HarmProbability` that triggered a block, and the HarmThreshold setting for that category. This indicates the smallest change to the `SafetySettings` that would be necessary to unblock at least 1 response. The blocking is configured by the `SafetySettings` in the request (or the default `SafetySettings` of the API).", + "items": { + "$ref": "ContentFilter" + }, + "type": "array" + } + }, + "type": "object", + "description": "The response from the model, including candidate completions.", + "id": "GenerateTextResponse" + }, + "Chunk": { + "properties": { + "customMetadata": { + "description": "Optional. User provided custom metadata stored as key-value pairs. The maximum number of `CustomMetadata` per chunk is 20.", + "type": "array", + "items": { + "$ref": "CustomMetadata" + } + }, + "updateTime": { + "readOnly": true, + "type": "string", + "description": "Output only. The Timestamp of when the `Chunk` was last updated.", + "format": "google-datetime" + }, + "createTime": { + "format": "google-datetime", + "description": "Output only. The Timestamp of when the `Chunk` was created.", + "type": "string", + "readOnly": true + }, + "data": { + "$ref": "ChunkData", + "description": "Required. The content for the `Chunk`, such as the text string. The maximum number of tokens per chunk is 2043." + }, + "name": { + "type": "string", + "description": "Immutable. Identifier. The `Chunk` resource name. The ID (name excluding the \"corpora/*/documents/*/chunks/\" prefix) can contain up to 40 characters that are lowercase alphanumeric or dashes (-). The ID cannot start or end with a dash. If the name is empty on create, a random 12-character unique ID will be generated. Example: `corpora/{corpus_id}/documents/{document_id}/chunks/123a456b789c`" + }, + "state": { + "type": "string", + "enumDescriptions": [ + "The default value. This value is used if the state is omitted.", + "`Chunk` is being processed (embedding and vector storage).", + "`Chunk` is processed and available for querying.", + "`Chunk` failed processing." + ], + "enum": [ + "STATE_UNSPECIFIED", + "STATE_PENDING_PROCESSING", + "STATE_ACTIVE", + "STATE_FAILED" + ], + "description": "Output only. Current state of the `Chunk`.", + "readOnly": true + } + }, + "description": "A `Chunk` is a subpart of a `Document` that is treated as an independent unit for the purposes of vector representation and storage. A `Corpus` can have a maximum of 1 million `Chunk`s.", + "type": "object", + "id": "Chunk" + }, + "Schema": { + "description": "The `Schema` object allows the definition of input and output data types. These types can be objects, but also primitives and arrays. Represents a select subset of an [OpenAPI 3.0 schema object](https://spec.openapis.org/oas/v3.0.3#schema).", + "properties": { + "items": { + "description": "Optional. Schema of the elements of Type.ARRAY.", + "$ref": "Schema" + }, + "properties": { + "description": "Optional. Properties of Type.OBJECT.", + "additionalProperties": { + "$ref": "Schema" + }, + "type": "object" + }, + "required": { + "type": "array", + "description": "Optional. Required properties of Type.OBJECT.", + "items": { + "type": "string" + } + }, + "type": { + "description": "Required. Data type.", + "enumDescriptions": [ + "Not specified, should not be used.", + "String type.", + "Number type.", + "Integer type.", + "Boolean type.", + "Array type.", + "Object type." + ], + "type": "string", + "enum": [ + "TYPE_UNSPECIFIED", + "STRING", + "NUMBER", + "INTEGER", + "BOOLEAN", + "ARRAY", + "OBJECT" + ] + }, + "enum": { + "type": "array", + "description": "Optional. Possible values of the element of Type.STRING with enum format. For example we can define an Enum Direction as : {type:STRING, format:enum, enum:[\"EAST\", NORTH\", \"SOUTH\", \"WEST\"]}", + "items": { + "type": "string" + } + }, + "format": { + "type": "string", + "description": "Optional. The format of the data. This is used only for primitive datatypes. Supported formats: for NUMBER type: float, double for INTEGER type: int32, int64" + }, + "description": { + "type": "string", + "description": "Optional. A brief description of the parameter. This could contain examples of use. Parameter description may be formatted as Markdown." + }, + "nullable": { + "description": "Optional. Indicates if the value may be null.", + "type": "boolean" + } + }, + "id": "Schema", + "type": "object" + }, + "SafetyRating": { + "id": "SafetyRating", + "type": "object", + "properties": { + "blocked": { + "type": "boolean", + "description": "Was this content blocked because of this rating?" + }, + "category": { + "description": "Required. The category for this rating.", + "enumDescriptions": [ + "Category is unspecified.", + "Negative or harmful comments targeting identity and/or protected attribute.", + "Content that is rude, disrespectful, or profane.", + "Describes scenarios depicting violence against an individual or group, or general descriptions of gore.", + "Contains references to sexual acts or other lewd content.", + "Promotes unchecked medical advice.", + "Dangerous content that promotes, facilitates, or encourages harmful acts.", + "Harasment content.", + "Hate speech and content.", + "Sexually explicit content.", + "Dangerous content." + ], + "type": "string", + "enum": [ + "HARM_CATEGORY_UNSPECIFIED", + "HARM_CATEGORY_DEROGATORY", + "HARM_CATEGORY_TOXICITY", + "HARM_CATEGORY_VIOLENCE", + "HARM_CATEGORY_SEXUAL", + "HARM_CATEGORY_MEDICAL", + "HARM_CATEGORY_DANGEROUS", + "HARM_CATEGORY_HARASSMENT", + "HARM_CATEGORY_HATE_SPEECH", + "HARM_CATEGORY_SEXUALLY_EXPLICIT", + "HARM_CATEGORY_DANGEROUS_CONTENT" + ] + }, + "probability": { + "type": "string", + "description": "Required. The probability of harm for this content.", + "enumDescriptions": [ + "Probability is unspecified.", + "Content has a negligible chance of being unsafe.", + "Content has a low chance of being unsafe.", + "Content has a medium chance of being unsafe.", + "Content has a high chance of being unsafe." + ], + "enum": [ + "HARM_PROBABILITY_UNSPECIFIED", + "NEGLIGIBLE", + "LOW", + "MEDIUM", + "HIGH" + ] + } + }, + "description": "Safety rating for a piece of content. The safety rating contains the category of harm and the harm probability level in that category for a piece of content. Content is classified for safety across a number of harm categories and the probability of the harm classification is included here." + }, + "File": { + "type": "object", + "description": "A file uploaded to the API.", + "id": "File", + "properties": { + "error": { + "$ref": "Status", + "readOnly": true, + "description": "Output only. Error status if File processing failed." + }, + "updateTime": { + "description": "Output only. The timestamp of when the `File` was last updated.", + "format": "google-datetime", + "readOnly": true, + "type": "string" + }, + "name": { + "description": "Immutable. Identifier. The `File` resource name. The ID (name excluding the \"files/\" prefix) can contain up to 40 characters that are lowercase alphanumeric or dashes (-). The ID cannot start or end with a dash. If the name is empty on create, a unique name will be generated. Example: `files/123-456`", + "type": "string" + }, + "createTime": { + "type": "string", + "format": "google-datetime", + "description": "Output only. The timestamp of when the `File` was created.", + "readOnly": true + }, + "sizeBytes": { + "type": "string", + "description": "Output only. Size of the file in bytes.", + "readOnly": true, + "format": "int64" + }, + "sha256Hash": { + "type": "string", + "description": "Output only. SHA-256 hash of the uploaded bytes.", + "readOnly": true, + "format": "byte" + }, + "state": { + "readOnly": true, + "description": "Output only. Processing state of the File.", + "enum": [ + "STATE_UNSPECIFIED", + "PROCESSING", + "ACTIVE", + "FAILED" + ], + "enumDescriptions": [ + "The default value. This value is used if the state is omitted.", + "File is being processed and cannot be used for inference yet.", + "File is processed and available for inference.", + "File failed processing." + ], + "type": "string" + }, + "displayName": { + "type": "string", + "description": "Optional. The human-readable display name for the `File`. The display name must be no more than 512 characters in length, including spaces. Example: \"Welcome Image\"" + }, + "videoMetadata": { + "$ref": "VideoMetadata", + "readOnly": true, + "description": "Output only. Metadata for a video." + }, + "uri": { + "readOnly": true, + "type": "string", + "description": "Output only. The uri of the `File`." + }, + "expirationTime": { + "type": "string", + "readOnly": true, + "description": "Output only. The timestamp of when the `File` will be deleted. Only set if the `File` is scheduled to expire.", + "format": "google-datetime" + }, + "mimeType": { + "type": "string", + "description": "Output only. MIME type of the file.", + "readOnly": true + } + } + }, + "BatchUpdateChunksRequest": { + "description": "Request to batch update `Chunk`s.", + "id": "BatchUpdateChunksRequest", + "type": "object", + "properties": { + "requests": { + "items": { + "$ref": "UpdateChunkRequest" + }, + "type": "array", + "description": "Required. The request messages specifying the `Chunk`s to update. A maximum of 100 `Chunk`s can be updated in a batch." + } + } + }, + "CountMessageTokensResponse": { + "id": "CountMessageTokensResponse", + "properties": { + "tokenCount": { + "format": "int32", + "type": "integer", + "description": "The number of tokens that the `model` tokenizes the `prompt` into. Always non-negative." + } + }, + "description": "A response from `CountMessageTokens`. It returns the model's `token_count` for the `prompt`.", + "type": "object" + }, + "Corpus": { + "properties": { + "updateTime": { + "readOnly": true, + "description": "Output only. The Timestamp of when the `Corpus` was last updated.", + "type": "string", + "format": "google-datetime" + }, + "createTime": { + "description": "Output only. The Timestamp of when the `Corpus` was created.", + "type": "string", + "format": "google-datetime", + "readOnly": true + }, + "displayName": { + "description": "Optional. The human-readable display name for the `Corpus`. The display name must be no more than 512 characters in length, including spaces. Example: \"Docs on Semantic Retriever\"", + "type": "string" + }, + "name": { + "type": "string", + "description": "Immutable. Identifier. The `Corpus` resource name. The ID (name excluding the \"corpora/\" prefix) can contain up to 40 characters that are lowercase alphanumeric or dashes (-). The ID cannot start or end with a dash. If the name is empty on create, a unique name will be derived from `display_name` along with a 12 character random suffix. Example: `corpora/my-awesome-corpora-123a456b789c`" + } + }, + "id": "Corpus", + "description": "A `Corpus` is a collection of `Document`s. A project can create up to 5 corpora.", + "type": "object" + }, + "TuningExamples": { + "id": "TuningExamples", + "description": "A set of tuning examples. Can be training or validation data.", + "type": "object", + "properties": { + "examples": { + "items": { + "$ref": "TuningExample" + }, + "type": "array", + "description": "Required. The examples. Example input can be for text or discuss, but all examples in a set must be of the same type." + } + } + }, + "Example": { + "description": "An input/output example used to instruct the Model. It demonstrates how the model should respond or format its response.", + "id": "Example", + "properties": { + "input": { + "$ref": "Message", + "description": "Required. An example of an input `Message` from the user." + }, + "output": { + "$ref": "Message", + "description": "Required. An example of what the model should output given the input." + } + }, + "type": "object" + }, + "StringList": { + "id": "StringList", + "properties": { + "values": { + "description": "The string values of the metadata to store.", + "items": { + "type": "string" + }, + "type": "array" + } + }, + "description": "User provided string values assigned to a single metadata key.", + "type": "object" + }, + "SafetyFeedback": { + "type": "object", + "description": "Safety feedback for an entire request. This field is populated if content in the input and/or response is blocked due to safety settings. SafetyFeedback may not exist for every HarmCategory. Each SafetyFeedback will return the safety settings used by the request as well as the lowest HarmProbability that should be allowed in order to return a result.", + "id": "SafetyFeedback", + "properties": { + "rating": { + "description": "Safety rating evaluated from content.", + "$ref": "SafetyRating" + }, + "setting": { + "$ref": "SafetySetting", + "description": "Safety settings applied to the request." + } + } + }, + "CountMessageTokensRequest": { + "properties": { + "prompt": { + "description": "Required. The prompt, whose token count is to be returned.", + "$ref": "MessagePrompt" + } + }, + "type": "object", + "description": "Counts the number of tokens in the `prompt` sent to a model. Models may tokenize text differently, so each model may return a different `token_count`.", + "id": "CountMessageTokensRequest" + }, + "CustomMetadata": { + "id": "CustomMetadata", + "type": "object", + "description": "User provided metadata stored as key-value pairs.", + "properties": { + "stringValue": { + "description": "The string value of the metadata to store.", + "type": "string" + }, + "key": { + "description": "Required. The key of the metadata to store.", + "type": "string" + }, + "numericValue": { + "description": "The numeric value of the metadata to store.", + "type": "number", + "format": "float" + }, + "stringListValue": { + "description": "The StringList value of the metadata to store.", + "$ref": "StringList" + } + } + }, + "MessagePrompt": { + "type": "object", + "id": "MessagePrompt", + "properties": { + "messages": { + "type": "array", + "description": "Required. A snapshot of the recent conversation history sorted chronologically. Turns alternate between two authors. If the total input size exceeds the model's `input_token_limit` the input will be truncated: The oldest items will be dropped from `messages`.", + "items": { + "$ref": "Message" + } + }, + "context": { + "type": "string", + "description": "Optional. Text that should be provided to the model first to ground the response. If not empty, this `context` will be given to the model first before the `examples` and `messages`. When using a `context` be sure to provide it with every request to maintain continuity. This field can be a description of your prompt to the model to help provide context and guide the responses. Examples: \"Translate the phrase from English to French.\" or \"Given a statement, classify the sentiment as happy, sad or neutral.\" Anything included in this field will take precedence over message history if the total input size exceeds the model's `input_token_limit` and the input request is truncated." + }, + "examples": { + "type": "array", + "items": { + "$ref": "Example" + }, + "description": "Optional. Examples of what the model should generate. This includes both user input and the response that the model should emulate. These `examples` are treated identically to conversation messages except that they take precedence over the history in `messages`: If the total input size exceeds the model's `input_token_limit` the input will be truncated. Items will be dropped from `messages` before `examples`." + } + }, + "description": "All of the structured input text passed to the model as a prompt. A `MessagePrompt` contains a structured set of fields that provide context for the conversation, examples of user input/model output message pairs that prime the model to respond in different ways, and the conversation history or list of messages representing the alternating turns of the conversation between the user and the model." + }, + "CreateFileRequest": { + "type": "object", + "properties": { + "file": { + "description": "Optional. Metadata for the file to create.", + "$ref": "File" + } + }, + "description": "Request for `CreateFile`.", + "id": "CreateFileRequest" + }, + "GenerateAnswerRequest": { + "description": "Request to generate a grounded answer from the model.", + "properties": { + "safetySettings": { + "type": "array", + "items": { + "$ref": "SafetySetting" + }, + "description": "Optional. A list of unique `SafetySetting` instances for blocking unsafe content. This will be enforced on the `GenerateAnswerRequest.contents` and `GenerateAnswerResponse.candidate`. There should not be more than one setting for each `SafetyCategory` type. The API will block any contents and responses that fail to meet the thresholds set by these settings. This list overrides the default settings for each `SafetyCategory` specified in the safety_settings. If there is no `SafetySetting` for a given `SafetyCategory` provided in the list, the API will use the default safety setting for that category. Harm categories HARM_CATEGORY_HATE_SPEECH, HARM_CATEGORY_SEXUALLY_EXPLICIT, HARM_CATEGORY_DANGEROUS_CONTENT, HARM_CATEGORY_HARASSMENT are supported." + }, + "contents": { + "type": "array", + "items": { + "$ref": "Content" + }, + "description": "Required. The content of the current conversation with the model. For single-turn queries, this is a single question to answer. For multi-turn queries, this is a repeated field that contains conversation history and the last `Content` in the list containing the question. Note: GenerateAnswer currently only supports queries in English." + }, + "temperature": { + "type": "number", + "format": "float", + "description": "Optional. Controls the randomness of the output. Values can range from [0.0,1.0], inclusive. A value closer to 1.0 will produce responses that are more varied and creative, while a value closer to 0.0 will typically result in more straightforward responses from the model. A low temperature (~0.2) is usually recommended for Attributed-Question-Answering use cases." + }, + "answerStyle": { + "enumDescriptions": [ + "Unspecified answer style.", + "Succint but abstract style.", + "Very brief and extractive style.", + "Verbose style including extra details. The response may be formatted as a sentence, paragraph, multiple paragraphs, or bullet points, etc." + ], + "enum": [ + "ANSWER_STYLE_UNSPECIFIED", + "ABSTRACTIVE", + "EXTRACTIVE", + "VERBOSE" + ], + "description": "Required. Style in which answers should be returned.", + "type": "string" + }, + "semanticRetriever": { + "$ref": "SemanticRetrieverConfig", + "description": "Content retrieved from resources created via the Semantic Retriever API." + }, + "inlinePassages": { + "$ref": "GroundingPassages", + "description": "Passages provided inline with the request." + } + }, + "id": "GenerateAnswerRequest", + "type": "object" + }, + "Message": { + "id": "Message", + "properties": { + "author": { + "type": "string", + "description": "Optional. The author of this Message. This serves as a key for tagging the content of this Message when it is fed to the model as text. The author can be any alphanumeric string." + }, + "citationMetadata": { + "readOnly": true, + "$ref": "CitationMetadata", + "description": "Output only. Citation information for model-generated `content` in this `Message`. If this `Message` was generated as output from the model, this field may be populated with attribution information for any text included in the `content`. This field is used only on output." + }, + "content": { + "description": "Required. The text content of the structured `Message`.", + "type": "string" + } + }, + "description": "The base unit of structured text. A `Message` includes an `author` and the `content` of the `Message`. The `author` is used to tag messages when they are fed to the model as text.", + "type": "object" + }, + "CitationSource": { + "properties": { + "startIndex": { + "format": "int32", + "description": "Optional. Start of segment of the response that is attributed to this source. Index indicates the start of the segment, measured in bytes.", + "type": "integer" + }, + "license": { + "description": "Optional. License for the GitHub project that is attributed as a source for segment. License info is required for code citations.", + "type": "string" + }, + "uri": { + "description": "Optional. URI that is attributed as a source for a portion of the text.", + "type": "string" + }, + "endIndex": { + "description": "Optional. End of the attributed segment, exclusive.", + "format": "int32", + "type": "integer" + } + }, + "description": "A citation to a source for a portion of a specific response.", + "id": "CitationSource", + "type": "object" + }, + "GenerateMessageRequest": { + "type": "object", + "description": "Request to generate a message response from the model.", + "properties": { + "prompt": { + "description": "Required. The structured textual input given to the model as a prompt. Given a prompt, the model will return what it predicts is the next message in the discussion.", + "$ref": "MessagePrompt" + }, + "topP": { + "type": "number", + "description": "Optional. The maximum cumulative probability of tokens to consider when sampling. The model uses combined Top-k and nucleus sampling. Nucleus sampling considers the smallest set of tokens whose probability sum is at least `top_p`.", + "format": "float" + }, + "temperature": { + "type": "number", + "format": "float", + "description": "Optional. Controls the randomness of the output. Values can range over `[0.0,1.0]`, inclusive. A value closer to `1.0` will produce responses that are more varied, while a value closer to `0.0` will typically result in less surprising responses from the model." + }, + "candidateCount": { + "type": "integer", + "format": "int32", + "description": "Optional. The number of generated response messages to return. This value must be between `[1, 8]`, inclusive. If unset, this will default to `1`." + }, + "topK": { + "description": "Optional. The maximum number of tokens to consider when sampling. The model uses combined Top-k and nucleus sampling. Top-k sampling considers the set of `top_k` most probable tokens.", + "type": "integer", + "format": "int32" + } + }, + "id": "GenerateMessageRequest" + }, + "CreateFileResponse": { + "description": "Response for `CreateFile`.", + "id": "CreateFileResponse", + "type": "object", + "properties": { + "file": { + "$ref": "File", + "description": "Metadata for the created file." + } + } + }, + "CountTextTokensResponse": { + "id": "CountTextTokensResponse", + "properties": { + "tokenCount": { + "type": "integer", + "format": "int32", + "description": "The number of tokens that the `model` tokenizes the `prompt` into. Always non-negative." + } + }, + "type": "object", + "description": "A response from `CountTextTokens`. It returns the model's `token_count` for the `prompt`." + }, + "ListChunksResponse": { + "type": "object", + "id": "ListChunksResponse", + "properties": { + "nextPageToken": { + "description": "A token, which can be sent as `page_token` to retrieve the next page. If this field is omitted, there are no more pages.", + "type": "string" + }, + "chunks": { + "type": "array", + "description": "The returned `Chunk`s.", + "items": { + "$ref": "Chunk" + } + } + }, + "description": "Response from `ListChunks` containing a paginated list of `Chunk`s. The `Chunk`s are sorted by ascending `chunk.create_time`." + }, + "TransferOwnershipResponse": { + "type": "object", + "description": "Response from `TransferOwnership`.", + "properties": {}, + "id": "TransferOwnershipResponse" + }, + "BatchDeleteChunksRequest": { + "id": "BatchDeleteChunksRequest", + "properties": { + "requests": { + "items": { + "$ref": "DeleteChunkRequest" + }, + "description": "Required. The request messages specifying the `Chunk`s to delete.", + "type": "array" + } + }, + "type": "object", + "description": "Request to batch delete `Chunk`s." + }, + "ListPermissionsResponse": { + "properties": { + "permissions": { + "description": "Returned permissions.", + "type": "array", + "items": { + "$ref": "Permission" + } + }, + "nextPageToken": { + "type": "string", + "description": "A token, which can be sent as `page_token` to retrieve the next page. If this field is omitted, there are no more pages." + } + }, + "type": "object", + "id": "ListPermissionsResponse", + "description": "Response from `ListPermissions` containing a paginated list of permissions." + }, + "DeleteChunkRequest": { + "properties": { + "name": { + "type": "string", + "description": "Required. The resource name of the `Chunk` to delete. Example: `corpora/my-corpus-123/documents/the-doc-abc/chunks/some-chunk`" + } + }, + "id": "DeleteChunkRequest", + "description": "Request to delete a `Chunk`.", + "type": "object" + }, + "Status": { + "properties": { + "message": { + "description": "A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client.", + "type": "string" + }, + "code": { + "type": "integer", + "description": "The status code, which should be an enum value of google.rpc.Code.", + "format": "int32" + }, + "details": { + "items": { + "type": "object", + "additionalProperties": { + "description": "Properties of the object. Contains field @type with type URL.", + "type": "any" + } + }, + "description": "A list of messages that carry the error details. There is a common set of message types for APIs to use.", + "type": "array" + } + }, + "id": "Status", + "description": "The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains three pieces of data: error code, error message, and error details. You can find out more about this error model and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors).", + "type": "object" + }, + "Hyperparameters": { + "type": "object", + "properties": { + "batchSize": { + "format": "int32", + "description": "Immutable. The batch size hyperparameter for tuning. If not set, a default of 4 or 16 will be used based on the number of training examples.", + "type": "integer" + }, + "epochCount": { + "format": "int32", + "description": "Immutable. The number of training epochs. An epoch is one pass through the training data. If not set, a default of 5 will be used.", + "type": "integer" + }, + "learningRateMultiplier": { + "format": "float", + "type": "number", + "description": "Optional. Immutable. The learning rate multiplier is used to calculate a final learning_rate based on the default (recommended) value. Actual learning rate := learning_rate_multiplier * default learning rate Default learning rate is dependent on base model and dataset size. If not set, a default of 1.0 will be used." + }, + "learningRate": { + "type": "number", + "format": "float", + "description": "Optional. Immutable. The learning rate hyperparameter for tuning. If not set, a default of 0.001 or 0.0002 will be calculated based on the number of training examples." + } + }, + "id": "Hyperparameters", + "description": "Hyperparameters controlling the tuning process. Read more at https://ai.google.dev/docs/model_tuning_guidance" + }, + "BatchCreateChunksResponse": { + "id": "BatchCreateChunksResponse", + "properties": { + "chunks": { + "type": "array", + "description": "`Chunk`s created.", + "items": { + "$ref": "Chunk" + } + } + }, + "description": "Response from `BatchCreateChunks` containing a list of created `Chunk`s.", + "type": "object" + }, + "GroundingAttribution": { + "description": "Attribution for a source that contributed to an answer.", + "properties": { + "sourceId": { + "$ref": "AttributionSourceId", + "readOnly": true, + "description": "Output only. Identifier for the source contributing to this attribution." + }, + "content": { + "description": "Grounding source content that makes up this attribution.", + "$ref": "Content" + } + }, + "type": "object", + "id": "GroundingAttribution" + }, + "Condition": { + "id": "Condition", + "type": "object", + "properties": { + "stringValue": { + "type": "string", + "description": "The string value to filter the metadata on." + }, + "operation": { + "description": "Required. Operator applied to the given key-value pair to trigger the condition.", + "type": "string", + "enum": [ + "OPERATOR_UNSPECIFIED", + "LESS", + "LESS_EQUAL", + "EQUAL", + "GREATER_EQUAL", + "GREATER", + "NOT_EQUAL", + "INCLUDES", + "EXCLUDES" + ], + "enumDescriptions": [ + "The default value. This value is unused.", + "Supported by numeric.", + "Supported by numeric.", + "Supported by numeric & string.", + "Supported by numeric.", + "Supported by numeric.", + "Supported by numeric & string.", + "Supported by string only when `CustomMetadata` value type for the given key has a `string_list_value`.", + "Supported by string only when `CustomMetadata` value type for the given key has a `string_list_value`." + ] + }, + "numericValue": { + "type": "number", + "description": "The numeric value to filter the metadata on.", + "format": "float" + } + }, + "description": "Filter condition applicable to a single key." + }, + "ContentEmbedding": { + "description": "A list of floats representing an embedding.", + "properties": { + "values": { + "items": { + "format": "float", + "type": "number" + }, + "type": "array", + "description": "The embedding values." + } + }, + "id": "ContentEmbedding", + "type": "object" + }, + "UsageMetadata": { + "type": "object", + "description": "Metadata on the generation request's token usage.", + "id": "UsageMetadata", + "properties": { + "promptTokenCount": { + "type": "integer", + "format": "int32", + "description": "Number of tokens in the prompt." + }, + "candidatesTokenCount": { + "format": "int32", + "description": "Total number of tokens across the generated candidates.", + "type": "integer" + }, + "totalTokenCount": { + "type": "integer", + "format": "int32", + "description": "Total token count for the generation request (prompt + candidates)." + } + } + }, + "TuningTask": { + "properties": { + "trainingData": { + "description": "Required. Input only. Immutable. The model training data.", + "$ref": "Dataset" + }, + "snapshots": { + "items": { + "$ref": "TuningSnapshot" + }, + "description": "Output only. Metrics collected during tuning.", + "readOnly": true, + "type": "array" + }, + "completeTime": { + "format": "google-datetime", + "description": "Output only. The timestamp when tuning this model completed.", + "readOnly": true, + "type": "string" + }, + "hyperparameters": { + "$ref": "Hyperparameters", + "description": "Immutable. Hyperparameters controlling the tuning process. If not provided, default values will be used." + }, + "startTime": { + "format": "google-datetime", + "description": "Output only. The timestamp when tuning this model started.", + "readOnly": true, + "type": "string" + } + }, + "type": "object", + "description": "Tuning tasks that create tuned models.", + "id": "TuningTask" + }, + "QueryDocumentRequest": { + "type": "object", + "properties": { + "query": { + "type": "string", + "description": "Required. Query string to perform semantic search." + }, + "resultsCount": { + "description": "Optional. The maximum number of `Chunk`s to return. The service may return fewer `Chunk`s. If unspecified, at most 10 `Chunk`s will be returned. The maximum specified result count is 100.", + "type": "integer", + "format": "int32" + }, + "metadataFilters": { + "type": "array", + "items": { + "$ref": "MetadataFilter" + }, + "description": "Optional. Filter for `Chunk` metadata. Each `MetadataFilter` object should correspond to a unique key. Multiple `MetadataFilter` objects are joined by logical \"AND\"s. Note: `Document`-level filtering is not supported for this request because a `Document` name is already specified. Example query: (year \u003e= 2020 OR year \u003c 2010) AND (genre = drama OR genre = action) `MetadataFilter` object list: metadata_filters = [ {key = \"chunk.custom_metadata.year\" conditions = [{int_value = 2020, operation = GREATER_EQUAL}, {int_value = 2010, operation = LESS}}, {key = \"chunk.custom_metadata.genre\" conditions = [{string_value = \"drama\", operation = EQUAL}, {string_value = \"action\", operation = EQUAL}}] Example query for a numeric range of values: (year \u003e 2015 AND year \u003c= 2020) `MetadataFilter` object list: metadata_filters = [ {key = \"chunk.custom_metadata.year\" conditions = [{int_value = 2015, operation = GREATER}]}, {key = \"chunk.custom_metadata.year\" conditions = [{int_value = 2020, operation = LESS_EQUAL}]}] Note: \"AND\"s for the same key are only supported for numeric values. String values only support \"OR\"s for the same key." + } + }, + "description": "Request for querying a `Document`.", + "id": "QueryDocumentRequest" + }, + "BatchEmbedTextRequest": { + "id": "BatchEmbedTextRequest", + "type": "object", + "properties": { + "texts": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Optional. The free-form input texts that the model will turn into an embedding. The current limit is 100 texts, over which an error will be thrown." + }, + "requests": { + "items": { + "$ref": "EmbedTextRequest" + }, + "type": "array", + "description": "Optional. Embed requests for the batch. Only one of `texts` or `requests` can be set." + } + }, + "description": "Batch request to get a text embedding from the model." + }, + "AttributionSourceId": { + "id": "AttributionSourceId", + "type": "object", + "properties": { + "semanticRetrieverChunk": { + "$ref": "SemanticRetrieverChunk", + "description": "Identifier for a `Chunk` fetched via Semantic Retriever." + }, + "groundingPassage": { + "$ref": "GroundingPassageId", + "description": "Identifier for an inline passage." + } + }, + "description": "Identifier for the source contributing to this attribution." + }, + "EmbedTextResponse": { + "properties": { + "embedding": { + "description": "Output only. The embedding generated from the input text.", + "$ref": "Embedding", + "readOnly": true + } + }, + "type": "object", + "description": "The response to a EmbedTextRequest.", + "id": "EmbedTextResponse" + }, + "GroundingPassage": { + "id": "GroundingPassage", + "type": "object", + "description": "Passage included inline with a grounding configuration.", + "properties": { + "content": { + "$ref": "Content", + "description": "Content of the passage." + }, + "id": { + "description": "Identifier for the passage for attributing this passage in grounded answers.", + "type": "string" + } + } + }, + "FunctionCall": { + "id": "FunctionCall", + "properties": { + "args": { + "type": "object", + "description": "Optional. The function parameters and values in JSON object format.", + "additionalProperties": { + "description": "Properties of the object.", + "type": "any" + } + }, + "name": { + "type": "string", + "description": "Required. The name of the function to call. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 63." + } + }, + "description": "A predicted `FunctionCall` returned from the model that contains a string representing the `FunctionDeclaration.name` with the arguments and their values.", + "type": "object" + }, + "GenerationConfig": { + "id": "GenerationConfig", + "properties": { + "topK": { + "type": "integer", + "description": "Optional. The maximum number of tokens to consider when sampling. Models use nucleus sampling or combined Top-k and nucleus sampling. Top-k sampling considers the set of `top_k` most probable tokens. Models running with nucleus sampling don't allow top_k setting. Note: The default value varies by model, see the `Model.top_k` attribute of the `Model` returned from the `getModel` function. Empty `top_k` field in `Model` indicates the model doesn't apply top-k sampling and doesn't allow setting `top_k` on requests.", + "format": "int32" + }, + "maxOutputTokens": { + "type": "integer", + "description": "Optional. The maximum number of tokens to include in a candidate. Note: The default value varies by model, see the `Model.output_token_limit` attribute of the `Model` returned from the `getModel` function.", + "format": "int32" + }, + "candidateCount": { + "type": "integer", + "description": "Optional. Number of generated responses to return. Currently, this value can only be set to 1. If unset, this will default to 1.", + "format": "int32" + }, + "topP": { + "description": "Optional. The maximum cumulative probability of tokens to consider when sampling. The model uses combined Top-k and nucleus sampling. Tokens are sorted based on their assigned probabilities so that only the most likely tokens are considered. Top-k sampling directly limits the maximum number of tokens to consider, while Nucleus sampling limits number of tokens based on the cumulative probability. Note: The default value varies by model, see the `Model.top_p` attribute of the `Model` returned from the `getModel` function.", + "format": "float", + "type": "number" + }, + "responseMimeType": { + "type": "string", + "description": "Optional. Output response mimetype of the generated candidate text. Supported mimetype: `text/plain`: (default) Text output. `application/json`: JSON response in the candidates." + }, + "temperature": { + "type": "number", + "format": "float", + "description": "Optional. Controls the randomness of the output. Note: The default value varies by model, see the `Model.temperature` attribute of the `Model` returned from the `getModel` function. Values can range from [0.0, 2.0]." + }, + "responseSchema": { + "$ref": "Schema", + "description": "Optional. Output response schema of the generated candidate text when response mime type can have schema. Schema can be objects, primitives or arrays and is a subset of [OpenAPI schema](https://spec.openapis.org/oas/v3.0.3#schema). If set, a compatible response_mime_type must also be set. Compatible mimetypes: `application/json`: Schema for JSON response." + }, + "stopSequences": { + "items": { + "type": "string" + }, + "type": "array", + "description": "Optional. The set of character sequences (up to 5) that will stop output generation. If specified, the API will stop at the first appearance of a stop sequence. The stop sequence will not be included as part of the response." + } + }, + "description": "Configuration options for model generation and outputs. Not all parameters may be configurable for every model.", + "type": "object" + }, + "TextCompletion": { + "id": "TextCompletion", + "type": "object", + "description": "Output text returned from a model.", + "properties": { + "safetyRatings": { + "items": { + "$ref": "SafetyRating" + }, + "type": "array", + "description": "Ratings for the safety of a response. There is at most one rating per category." + }, + "citationMetadata": { + "readOnly": true, + "description": "Output only. Citation information for model-generated `output` in this `TextCompletion`. This field may be populated with attribution information for any text included in the `output`.", + "$ref": "CitationMetadata" + }, + "output": { + "readOnly": true, + "type": "string", + "description": "Output only. The generated text returned from the model." + } + } + }, + "BatchUpdateChunksResponse": { + "properties": { + "chunks": { + "description": "`Chunk`s updated.", + "items": { + "$ref": "Chunk" + }, + "type": "array" + } + }, + "description": "Response from `BatchUpdateChunks` containing a list of updated `Chunk`s.", + "type": "object", + "id": "BatchUpdateChunksResponse" + }, + "ListCorporaResponse": { + "properties": { + "nextPageToken": { + "type": "string", + "description": "A token, which can be sent as `page_token` to retrieve the next page. If this field is omitted, there are no more pages." + }, + "corpora": { + "description": "The returned corpora.", + "type": "array", + "items": { + "$ref": "Corpus" + } + } + }, + "description": "Response from `ListCorpora` containing a paginated list of `Corpora`. The results are sorted by ascending `corpus.create_time`.", + "id": "ListCorporaResponse", + "type": "object" + }, + "ListDocumentsResponse": { + "description": "Response from `ListDocuments` containing a paginated list of `Document`s. The `Document`s are sorted by ascending `document.create_time`.", + "id": "ListDocumentsResponse", + "properties": { + "documents": { + "description": "The returned `Document`s.", + "type": "array", + "items": { + "$ref": "Document" + } + }, + "nextPageToken": { + "type": "string", + "description": "A token, which can be sent as `page_token` to retrieve the next page. If this field is omitted, there are no more pages." + } + }, + "type": "object" + }, + "Dataset": { + "description": "Dataset for training or validation.", + "properties": { + "examples": { + "$ref": "TuningExamples", + "description": "Optional. Inline examples." + } + }, + "id": "Dataset", + "type": "object" + }, + "UpdateChunkRequest": { + "type": "object", + "properties": { + "updateMask": { + "description": "Required. The list of fields to update. Currently, this only supports updating `custom_metadata` and `data`.", + "type": "string", + "format": "google-fieldmask" + }, + "chunk": { + "description": "Required. The `Chunk` to update.", + "$ref": "Chunk" + } + }, + "id": "UpdateChunkRequest", + "description": "Request to update a `Chunk`." + }, + "TextPrompt": { + "id": "TextPrompt", + "description": "Text given to the model as a prompt. The Model will use this TextPrompt to Generate a text completion.", + "properties": { + "text": { + "type": "string", + "description": "Required. The prompt text." + } + }, + "type": "object" + }, + "ListModelsResponse": { + "description": "Response from `ListModel` containing a paginated list of Models.", + "properties": { + "nextPageToken": { + "type": "string", + "description": "A token, which can be sent as `page_token` to retrieve the next page. If this field is omitted, there are no more pages." + }, + "models": { + "items": { + "$ref": "Model" + }, + "description": "The returned Models.", + "type": "array" + } + }, + "type": "object", + "id": "ListModelsResponse" + }, + "PromptFeedback": { + "id": "PromptFeedback", + "type": "object", + "description": "A set of the feedback metadata the prompt specified in `GenerateContentRequest.content`.", + "properties": { + "safetyRatings": { + "type": "array", + "description": "Ratings for safety of the prompt. There is at most one rating per category.", + "items": { + "$ref": "SafetyRating" + } + }, + "blockReason": { + "description": "Optional. If set, the prompt was blocked and no candidates are returned. Rephrase your prompt.", + "enumDescriptions": [ + "Default value. This value is unused.", + "Prompt was blocked due to safety reasons. You can inspect `safety_ratings` to understand which safety category blocked it.", + "Prompt was blocked due to unknown reaasons." + ], + "enum": [ + "BLOCK_REASON_UNSPECIFIED", + "SAFETY", + "OTHER" + ], + "type": "string" + } + } + }, + "ListFilesResponse": { + "id": "ListFilesResponse", + "description": "Response for `ListFiles`.", + "type": "object", + "properties": { + "files": { + "type": "array", + "description": "The list of `File`s.", + "items": { + "$ref": "File" + } + }, + "nextPageToken": { + "description": "A token that can be sent as a `page_token` into a subsequent `ListFiles` call.", + "type": "string" + } + } + }, + "EmbedContentRequest": { + "type": "object", + "properties": { + "model": { + "type": "string", + "description": "Required. The model's resource name. This serves as an ID for the Model to use. This name should match a model name returned by the `ListModels` method. Format: `models/{model}`" + }, + "outputDimensionality": { + "description": "Optional. Optional reduced dimension for the output embedding. If set, excessive values in the output embedding are truncated from the end. Supported by newer models since 2024, and the earlier model (`models/embedding-001`) cannot specify this value.", + "type": "integer", + "format": "int32" + }, + "taskType": { + "type": "string", + "enum": [ + "TASK_TYPE_UNSPECIFIED", + "RETRIEVAL_QUERY", + "RETRIEVAL_DOCUMENT", + "SEMANTIC_SIMILARITY", + "CLASSIFICATION", + "CLUSTERING", + "QUESTION_ANSWERING", + "FACT_VERIFICATION" + ], + "enumDescriptions": [ + "Unset value, which will default to one of the other enum values.", + "Specifies the given text is a query in a search/retrieval setting.", + "Specifies the given text is a document from the corpus being searched.", + "Specifies the given text will be used for STS.", + "Specifies that the given text will be classified.", + "Specifies that the embeddings will be used for clustering.", + "Specifies that the given text will be used for question answering.", + "Specifies that the given text will be used for fact verification." + ], + "description": "Optional. Optional task type for which the embeddings will be used. Can only be set for `models/embedding-001`." + }, + "title": { + "type": "string", + "description": "Optional. An optional title for the text. Only applicable when TaskType is `RETRIEVAL_DOCUMENT`. Note: Specifying a `title` for `RETRIEVAL_DOCUMENT` provides better quality embeddings for retrieval." + }, + "content": { + "description": "Required. The content to embed. Only the `parts.text` fields will be counted.", + "$ref": "Content" + } + }, + "description": "Request containing the `Content` for the model to embed.", + "id": "EmbedContentRequest" + }, + "TunedModel": { + "properties": { + "state": { + "readOnly": true, + "description": "Output only. The state of the tuned model.", + "type": "string", + "enumDescriptions": [ + "The default value. This value is unused.", + "The model is being created.", + "The model is ready to be used.", + "The model failed to be created." + ], + "enum": [ + "STATE_UNSPECIFIED", + "CREATING", + "ACTIVE", + "FAILED" + ] + }, + "updateTime": { + "description": "Output only. The timestamp when this model was updated.", + "readOnly": true, + "format": "google-datetime", + "type": "string" + }, + "name": { + "readOnly": true, + "type": "string", + "description": "Output only. The tuned model name. A unique name will be generated on create. Example: `tunedModels/az2mb0bpw6i` If display_name is set on create, the id portion of the name will be set by concatenating the words of the display_name with hyphens and adding a random portion for uniqueness. Example: display_name = \"Sentence Translator\" name = \"tunedModels/sentence-translator-u3b7m\"" + }, + "tuningTask": { + "description": "Required. The tuning task that creates the tuned model.", + "$ref": "TuningTask" + }, + "displayName": { + "type": "string", + "description": "Optional. The name to display for this model in user interfaces. The display name must be up to 40 characters including spaces." + }, + "createTime": { + "type": "string", + "format": "google-datetime", + "readOnly": true, + "description": "Output only. The timestamp when this model was created." + }, + "temperature": { + "format": "float", + "type": "number", + "description": "Optional. Controls the randomness of the output. Values can range over `[0.0,1.0]`, inclusive. A value closer to `1.0` will produce responses that are more varied, while a value closer to `0.0` will typically result in less surprising responses from the model. This value specifies default to be the one used by the base model while creating the model." + }, + "description": { + "type": "string", + "description": "Optional. A short description of this model." + }, + "topP": { + "description": "Optional. For Nucleus sampling. Nucleus sampling considers the smallest set of tokens whose probability sum is at least `top_p`. This value specifies default to be the one used by the base model while creating the model.", + "type": "number", + "format": "float" + }, + "topK": { + "format": "int32", + "description": "Optional. For Top-k sampling. Top-k sampling considers the set of `top_k` most probable tokens. This value specifies default to be used by the backend while making the call to the model. This value specifies default to be the one used by the base model while creating the model.", + "type": "integer" + }, + "baseModel": { + "type": "string", + "description": "Immutable. The name of the `Model` to tune. Example: `models/text-bison-001`" + }, + "tunedModelSource": { + "description": "Optional. TunedModel to use as the starting point for training the new model.", + "$ref": "TunedModelSource" + } + }, + "description": "A fine-tuned model created using ModelService.CreateTunedModel.", + "type": "object", + "id": "TunedModel" + }, + "BatchCreateChunksRequest": { + "type": "object", + "properties": { + "requests": { + "type": "array", + "description": "Required. The request messages specifying the `Chunk`s to create. A maximum of 100 `Chunk`s can be created in a batch.", + "items": { + "$ref": "CreateChunkRequest" + } + } + }, + "id": "BatchCreateChunksRequest", + "description": "Request to batch create `Chunk`s." + }, + "ChunkData": { + "properties": { + "stringValue": { + "description": "The `Chunk` content as a string. The maximum number of tokens per chunk is 2043.", + "type": "string" + } + }, + "type": "object", + "description": "Extracted data that represents the `Chunk` content.", + "id": "ChunkData" + }, + "FunctionCallingConfig": { + "properties": { + "mode": { + "enum": [ + "MODE_UNSPECIFIED", + "AUTO", + "ANY", + "NONE" + ], + "description": "Optional. Specifies the mode in which function calling should execute. If unspecified, the default value will be set to AUTO.", + "type": "string", + "enumDescriptions": [ + "Unspecified function calling mode. This value should not be used.", + "Default model behavior, model decides to predict either a function call or a natural language repspose.", + "Model is constrained to always predicting a function call only. If \"allowed_function_names\" are set, the predicted function call will be limited to any one of \"allowed_function_names\", else the predicted function call will be any one of the provided \"function_declarations\".", + "Model will not predict any function call. Model behavior is same as when not passing any function declarations." + ] + }, + "allowedFunctionNames": { + "description": "Optional. A set of function names that, when provided, limits the functions the model will call. This should only be set when the Mode is ANY. Function names should match [FunctionDeclaration.name]. With mode set to ANY, model will predict a function call from the set of function names provided.", + "items": { + "type": "string" + }, + "type": "array" + } + }, + "description": "Configuration for specifying function calling behavior.", + "id": "FunctionCallingConfig", + "type": "object" + }, + "SafetySetting": { + "id": "SafetySetting", + "description": "Safety setting, affecting the safety-blocking behavior. Passing a safety setting for a category changes the allowed probability that content is blocked.", + "type": "object", + "properties": { + "category": { + "description": "Required. The category for this setting.", + "type": "string", + "enum": [ + "HARM_CATEGORY_UNSPECIFIED", + "HARM_CATEGORY_DEROGATORY", + "HARM_CATEGORY_TOXICITY", + "HARM_CATEGORY_VIOLENCE", + "HARM_CATEGORY_SEXUAL", + "HARM_CATEGORY_MEDICAL", + "HARM_CATEGORY_DANGEROUS", + "HARM_CATEGORY_HARASSMENT", + "HARM_CATEGORY_HATE_SPEECH", + "HARM_CATEGORY_SEXUALLY_EXPLICIT", + "HARM_CATEGORY_DANGEROUS_CONTENT" + ], + "enumDescriptions": [ + "Category is unspecified.", + "Negative or harmful comments targeting identity and/or protected attribute.", + "Content that is rude, disrespectful, or profane.", + "Describes scenarios depicting violence against an individual or group, or general descriptions of gore.", + "Contains references to sexual acts or other lewd content.", + "Promotes unchecked medical advice.", + "Dangerous content that promotes, facilitates, or encourages harmful acts.", + "Harasment content.", + "Hate speech and content.", + "Sexually explicit content.", + "Dangerous content." + ] + }, + "threshold": { + "type": "string", + "enumDescriptions": [ + "Threshold is unspecified.", + "Content with NEGLIGIBLE will be allowed.", + "Content with NEGLIGIBLE and LOW will be allowed.", + "Content with NEGLIGIBLE, LOW, and MEDIUM will be allowed.", + "All content will be allowed." + ], + "enum": [ + "HARM_BLOCK_THRESHOLD_UNSPECIFIED", + "BLOCK_LOW_AND_ABOVE", + "BLOCK_MEDIUM_AND_ABOVE", + "BLOCK_ONLY_HIGH", + "BLOCK_NONE" + ], + "description": "Required. Controls the probability threshold at which harm is blocked." + } + } + }, + "Document": { + "properties": { + "name": { + "type": "string", + "description": "Immutable. Identifier. The `Document` resource name. The ID (name excluding the \"corpora/*/documents/\" prefix) can contain up to 40 characters that are lowercase alphanumeric or dashes (-). The ID cannot start or end with a dash. If the name is empty on create, a unique name will be derived from `display_name` along with a 12 character random suffix. Example: `corpora/{corpus_id}/documents/my-awesome-doc-123a456b789c`" + }, + "displayName": { + "description": "Optional. The human-readable display name for the `Document`. The display name must be no more than 512 characters in length, including spaces. Example: \"Semantic Retriever Documentation\"", + "type": "string" + }, + "customMetadata": { + "description": "Optional. User provided custom metadata stored as key-value pairs used for querying. A `Document` can have a maximum of 20 `CustomMetadata`.", + "type": "array", + "items": { + "$ref": "CustomMetadata" + } + }, + "createTime": { + "type": "string", + "readOnly": true, + "description": "Output only. The Timestamp of when the `Document` was created.", + "format": "google-datetime" + }, + "updateTime": { + "readOnly": true, + "format": "google-datetime", + "type": "string", + "description": "Output only. The Timestamp of when the `Document` was last updated." + } + }, + "description": "A `Document` is a collection of `Chunk`s. A `Corpus` can have a maximum of 10,000 `Document`s.", + "type": "object", + "id": "Document" + }, + "FunctionResponse": { + "id": "FunctionResponse", + "properties": { + "name": { + "type": "string", + "description": "Required. The name of the function to call. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 63." + }, + "response": { + "description": "Required. The function response in JSON object format.", + "additionalProperties": { + "type": "any", + "description": "Properties of the object." + }, + "type": "object" + } + }, + "description": "The result output from a `FunctionCall` that contains a string representing the `FunctionDeclaration.name` and a structured JSON object containing any output from the function is used as context to the model. This should contain the result of a`FunctionCall` made based on model prediction.", + "type": "object" + }, + "BatchEmbedContentsResponse": { + "properties": { + "embeddings": { + "readOnly": true, + "type": "array", + "description": "Output only. The embeddings for each request, in the same order as provided in the batch request.", + "items": { + "$ref": "ContentEmbedding" + } + } + }, + "id": "BatchEmbedContentsResponse", + "type": "object", + "description": "The response to a `BatchEmbedContentsRequest`." + }, + "TunedModelSource": { + "id": "TunedModelSource", + "description": "Tuned model as a source for training a new model.", + "properties": { + "baseModel": { + "description": "Output only. The name of the base `Model` this `TunedModel` was tuned from. Example: `models/text-bison-001`", + "readOnly": true, + "type": "string" + }, + "tunedModel": { + "type": "string", + "description": "Immutable. The name of the `TunedModel` to use as the starting point for training the new model. Example: `tunedModels/my-tuned-model`" + } + }, + "type": "object" + }, + "Tool": { + "properties": { + "functionDeclarations": { + "type": "array", + "items": { + "$ref": "FunctionDeclaration" + }, + "description": "Optional. A list of `FunctionDeclarations` available to the model that can be used for function calling. The model or system does not execute the function. Instead the defined function may be returned as a FunctionCall with arguments to the client side for execution. The model may decide to call a subset of these functions by populating FunctionCall in the response. The next conversation turn may contain a FunctionResponse with the [content.role] \"function\" generation context for the next model turn." + } + }, + "id": "Tool", + "type": "object", + "description": "Tool details that the model may use to generate response. A `Tool` is a piece of code that enables the system to interact with external systems to perform an action, or set of actions, outside of knowledge and scope of the model." + }, + "CountTokensResponse": { + "type": "object", + "properties": { + "totalTokens": { + "description": "The number of tokens that the `model` tokenizes the `prompt` into. Always non-negative.", + "type": "integer", + "format": "int32" + } + }, + "description": "A response from `CountTokens`. It returns the model's `token_count` for the `prompt`.", + "id": "CountTokensResponse" + }, + "FileData": { + "id": "FileData", + "type": "object", + "properties": { + "fileUri": { + "type": "string", + "description": "Required. URI." + }, + "mimeType": { + "type": "string", + "description": "Optional. The IANA standard MIME type of the source data." + } + }, + "description": "URI based data." + }, + "SemanticRetrieverChunk": { + "type": "object", + "description": "Identifier for a `Chunk` retrieved via Semantic Retriever specified in the `GenerateAnswerRequest` using `SemanticRetrieverConfig`.", + "id": "SemanticRetrieverChunk", + "properties": { + "chunk": { + "readOnly": true, + "type": "string", + "description": "Output only. Name of the `Chunk` containing the attributed text. Example: `corpora/123/documents/abc/chunks/xyz`" + }, + "source": { + "readOnly": true, + "type": "string", + "description": "Output only. Name of the source matching the request's `SemanticRetrieverConfig.source`. Example: `corpora/123` or `corpora/123/documents/abc`" + } + } + }, + "TuningSnapshot": { + "description": "Record for a single tuning step.", + "properties": { + "meanLoss": { + "description": "Output only. The mean loss of the training examples for this step.", + "readOnly": true, + "type": "number", + "format": "float" + }, + "epoch": { + "readOnly": true, + "type": "integer", + "format": "int32", + "description": "Output only. The epoch this step was part of." + }, + "computeTime": { + "description": "Output only. The timestamp when this metric was computed.", + "readOnly": true, + "format": "google-datetime", + "type": "string" + }, + "step": { + "format": "int32", + "type": "integer", + "readOnly": true, + "description": "Output only. The tuning step." + } + }, + "id": "TuningSnapshot", + "type": "object" + }, + "ToolConfig": { + "type": "object", + "id": "ToolConfig", + "properties": { + "functionCallingConfig": { + "$ref": "FunctionCallingConfig", + "description": "Optional. Function calling config." + } + }, + "description": "The Tool configuration containing parameters for specifying `Tool` use in the request." + }, + "CountTextTokensRequest": { + "properties": { + "prompt": { + "description": "Required. The free-form input text given to the model as a prompt.", + "$ref": "TextPrompt" + } + }, + "description": "Counts the number of tokens in the `prompt` sent to a model. Models may tokenize text differently, so each model may return a different `token_count`.", + "type": "object", + "id": "CountTextTokensRequest" + }, + "Model": { + "properties": { + "displayName": { + "description": "The human-readable name of the model. E.g. \"Chat Bison\". The name can be up to 128 characters long and can consist of any UTF-8 characters.", + "type": "string" + }, + "name": { + "type": "string", + "description": "Required. The resource name of the `Model`. Format: `models/{model}` with a `{model}` naming convention of: * \"{base_model_id}-{version}\" Examples: * `models/chat-bison-001`" + }, + "outputTokenLimit": { + "format": "int32", + "description": "Maximum number of output tokens available for this model.", + "type": "integer" + }, + "topP": { + "type": "number", + "description": "For Nucleus sampling. Nucleus sampling considers the smallest set of tokens whose probability sum is at least `top_p`. This value specifies default to be used by the backend while making the call to the model.", + "format": "float" + }, + "baseModelId": { + "type": "string", + "description": "Required. The name of the base model, pass this to the generation request. Examples: * `chat-bison`" + }, + "inputTokenLimit": { + "format": "int32", + "description": "Maximum number of input tokens allowed for this model.", + "type": "integer" + }, + "version": { + "type": "string", + "description": "Required. The version number of the model. This represents the major version" + }, + "supportedGenerationMethods": { + "items": { + "type": "string" + }, + "type": "array", + "description": "The model's supported generation methods. The method names are defined as Pascal case strings, such as `generateMessage` which correspond to API methods." + }, + "topK": { + "description": "For Top-k sampling. Top-k sampling considers the set of `top_k` most probable tokens. This value specifies default to be used by the backend while making the call to the model. If empty, indicates the model doesn't use top-k sampling, and `top_k` isn't allowed as a generation parameter.", + "format": "int32", + "type": "integer" + }, + "description": { + "type": "string", + "description": "A short description of the model." + }, + "temperature": { + "description": "Controls the randomness of the output. Values can range over `[0.0,1.0]`, inclusive. A value closer to `1.0` will produce responses that are more varied, while a value closer to `0.0` will typically result in less surprising responses from the model. This value specifies default to be used by the backend while making the call to the model.", + "format": "float", + "type": "number" + } + }, + "type": "object", + "id": "Model", + "description": "Information about a Generative Language Model." + }, + "MetadataFilter": { + "properties": { + "conditions": { + "items": { + "$ref": "Condition" + }, + "description": "Required. The `Condition`s for the given key that will trigger this filter. Multiple `Condition`s are joined by logical ORs.", + "type": "array" + }, + "key": { + "description": "Required. The key of the metadata to filter on.", + "type": "string" + } + }, + "id": "MetadataFilter", + "description": "User provided filter to limit retrieval based on `Chunk` or `Document` level metadata values. Example (genre = drama OR genre = action): key = \"document.custom_metadata.genre\" conditions = [{string_value = \"drama\", operation = EQUAL}, {string_value = \"action\", operation = EQUAL}]", + "type": "object" + }, + "GroundingPassageId": { + "properties": { + "passageId": { + "type": "string", + "readOnly": true, + "description": "Output only. ID of the passage matching the `GenerateAnswerRequest`'s `GroundingPassage.id`." + }, + "partIndex": { + "description": "Output only. Index of the part within the `GenerateAnswerRequest`'s `GroundingPassage.content`.", + "type": "integer", + "format": "int32", + "readOnly": true + } + }, + "description": "Identifier for a part within a `GroundingPassage`.", + "id": "GroundingPassageId", + "type": "object" + } + }, + "parameters": { + "quotaUser": { + "type": "string", + "location": "query", + "description": "Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters." + }, + "$.xgafv": { + "type": "string", + "enum": [ + "1", + "2" + ], + "enumDescriptions": [ + "v1 error format", + "v2 error format" + ], + "description": "V1 error format.", + "location": "query" + }, + "fields": { + "type": "string", + "location": "query", + "description": "Selector specifying which fields to include in a partial response." + }, + "upload_protocol": { + "description": "Upload protocol for media (e.g. \"raw\", \"multipart\").", + "type": "string", + "location": "query" + }, + "oauth_token": { + "type": "string", + "description": "OAuth 2.0 token for the current user.", + "location": "query" + }, + "prettyPrint": { + "location": "query", + "default": "true", + "type": "boolean", + "description": "Returns response with indentations and line breaks." + }, + "callback": { + "description": "JSONP", + "location": "query", + "type": "string" + }, + "access_token": { + "location": "query", + "type": "string", + "description": "OAuth access token." + }, + "key": { + "description": "API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.", + "location": "query", + "type": "string" + }, + "uploadType": { + "description": "Legacy upload protocol for media (e.g. \"media\", \"multipart\").", + "location": "query", + "type": "string" + }, + "alt": { + "enumDescriptions": [ + "Responses with Content-Type of application/json", + "Media download with context-dependent Content-Type", + "Responses with Content-Type of application/x-protobuf" + ], + "default": "json", + "description": "Data format for response.", + "location": "query", + "enum": [ + "json", + "media", + "proto" + ], + "type": "string" + } + }, + "servicePath": "", + "id": "generativelanguage:v1beta", + "revision": "20240524", + "documentationLink": "https://developers.generativeai.google/api", + "fullyEncodeReservedExpansion": true, + "rootUrl": "https://generativelanguage.googleapis.com/", + "batchPath": "batch", + "canonicalName": "Generative Language", + "ownerDomain": "google.com", + "baseUrl": "https://generativelanguage.googleapis.com/", + "mtlsRootUrl": "https://generativelanguage.mtls.googleapis.com/", + "resources": { + "tunedModels": { + "methods": { + "get": { + "id": "generativelanguage.tunedModels.get", + "parameterOrder": [ + "name" + ], + "description": "Gets information about a specific TunedModel.", + "parameters": { + "name": { + "required": true, + "description": "Required. The resource name of the model. Format: `tunedModels/my-model-id`", + "pattern": "^tunedModels/[^/]+$", + "type": "string", + "location": "path" + } + }, + "flatPath": "v1beta/tunedModels/{tunedModelsId}", + "response": { + "$ref": "TunedModel" + }, + "path": "v1beta/{+name}", + "httpMethod": "GET" + }, + "transferOwnership": { + "path": "v1beta/{+name}:transferOwnership", + "flatPath": "v1beta/tunedModels/{tunedModelsId}:transferOwnership", + "request": { + "$ref": "TransferOwnershipRequest" + }, + "response": { + "$ref": "TransferOwnershipResponse" + }, + "parameterOrder": [ + "name" + ], + "description": "Transfers ownership of the tuned model. This is the only way to change ownership of the tuned model. The current owner will be downgraded to writer role.", + "id": "generativelanguage.tunedModels.transferOwnership", + "parameters": { + "name": { + "description": "Required. The resource name of the tuned model to transfer ownership. Format: `tunedModels/my-model-id`", + "location": "path", + "required": true, + "type": "string", + "pattern": "^tunedModels/[^/]+$" + } + }, + "httpMethod": "POST" + }, + "create": { + "flatPath": "v1beta/tunedModels", + "response": { + "$ref": "Operation" + }, + "parameterOrder": [], + "id": "generativelanguage.tunedModels.create", + "request": { + "$ref": "TunedModel" + }, + "parameters": { + "tunedModelId": { + "type": "string", + "location": "query", + "description": "Optional. The unique id for the tuned model if specified. This value should be up to 40 characters, the first character must be a letter, the last could be a letter or a number. The id must match the regular expression: [a-z]([a-z0-9-]{0,38}[a-z0-9])?." + } + }, + "path": "v1beta/tunedModels", + "description": "Creates a tuned model. Intermediate tuning progress (if any) is accessed through the [google.longrunning.Operations] service. Status and results can be accessed through the Operations service. Example: GET /v1/tunedModels/az2mb0bpw6i/operations/000-111-222", + "httpMethod": "POST" + }, + "list": { + "id": "generativelanguage.tunedModels.list", + "description": "Lists tuned models owned by the user.", + "response": { + "$ref": "ListTunedModelsResponse" + }, + "httpMethod": "GET", + "parameters": { + "pageToken": { + "type": "string", + "description": "Optional. A page token, received from a previous `ListTunedModels` call. Provide the `page_token` returned by one request as an argument to the next request to retrieve the next page. When paginating, all other parameters provided to `ListTunedModels` must match the call that provided the page token.", + "location": "query" + }, + "pageSize": { + "format": "int32", + "description": "Optional. The maximum number of `TunedModels` to return (per page). The service may return fewer tuned models. If unspecified, at most 10 tuned models will be returned. This method returns at most 1000 models per page, even if you pass a larger page_size.", + "type": "integer", + "location": "query" + }, + "filter": { + "type": "string", + "location": "query", + "description": "Optional. A filter is a full text search over the tuned model's description and display name. By default, results will not include tuned models shared with everyone. Additional operators: - owner:me - writers:me - readers:me - readers:everyone Examples: \"owner:me\" returns all tuned models to which caller has owner role \"readers:me\" returns all tuned models to which caller has reader role \"readers:everyone\" returns all tuned models that are shared with everyone" + } + }, + "flatPath": "v1beta/tunedModels", + "parameterOrder": [], + "path": "v1beta/tunedModels" + }, + "patch": { + "httpMethod": "PATCH", + "response": { + "$ref": "TunedModel" + }, + "path": "v1beta/{+name}", + "parameters": { + "updateMask": { + "description": "Required. The list of fields to update.", + "location": "query", + "format": "google-fieldmask", + "type": "string" + }, + "name": { + "description": "Output only. The tuned model name. A unique name will be generated on create. Example: `tunedModels/az2mb0bpw6i` If display_name is set on create, the id portion of the name will be set by concatenating the words of the display_name with hyphens and adding a random portion for uniqueness. Example: display_name = \"Sentence Translator\" name = \"tunedModels/sentence-translator-u3b7m\"", + "required": true, + "location": "path", + "type": "string", + "pattern": "^tunedModels/[^/]+$" + } + }, + "description": "Updates a tuned model.", + "flatPath": "v1beta/tunedModels/{tunedModelsId}", + "parameterOrder": [ + "name" + ], + "id": "generativelanguage.tunedModels.patch", + "request": { + "$ref": "TunedModel" + } + }, + "generateContent": { + "httpMethod": "POST", + "response": { + "$ref": "GenerateContentResponse" + }, + "request": { + "$ref": "GenerateContentRequest" + }, + "parameters": { + "model": { + "description": "Required. The name of the `Model` to use for generating the completion. Format: `name=models/{model}`.", + "location": "path", + "required": true, + "pattern": "^tunedModels/[^/]+$", + "type": "string" + } + }, + "flatPath": "v1beta/tunedModels/{tunedModelsId}:generateContent", + "description": "Generates a response from the model given an input `GenerateContentRequest`. Input capabilities differ between models, including tuned models. See the [model guide](https://ai.google.dev/models/gemini) and [tuning guide](https://ai.google.dev/docs/model_tuning_guidance) for details.", + "parameterOrder": [ + "model" + ], + "path": "v1beta/{+model}:generateContent", + "id": "generativelanguage.tunedModels.generateContent" + }, + "delete": { + "flatPath": "v1beta/tunedModels/{tunedModelsId}", + "id": "generativelanguage.tunedModels.delete", + "response": { + "$ref": "Empty" + }, + "description": "Deletes a tuned model.", + "httpMethod": "DELETE", + "path": "v1beta/{+name}", + "parameters": { + "name": { + "pattern": "^tunedModels/[^/]+$", + "type": "string", + "description": "Required. The resource name of the model. Format: `tunedModels/my-model-id`", + "location": "path", + "required": true + } + }, + "parameterOrder": [ + "name" + ] + }, + "generateText": { + "path": "v1beta/{+model}:generateText", + "parameters": { + "model": { + "type": "string", + "location": "path", + "pattern": "^tunedModels/[^/]+$", + "required": true, + "description": "Required. The name of the `Model` or `TunedModel` to use for generating the completion. Examples: models/text-bison-001 tunedModels/sentence-translator-u3b7m" + } + }, + "httpMethod": "POST", + "response": { + "$ref": "GenerateTextResponse" + }, + "request": { + "$ref": "GenerateTextRequest" + }, + "id": "generativelanguage.tunedModels.generateText", + "parameterOrder": [ + "model" + ], + "description": "Generates a response from the model given an input message.", + "flatPath": "v1beta/tunedModels/{tunedModelsId}:generateText" + } + }, + "resources": { + "permissions": { + "methods": { + "patch": { + "description": "Updates the permission.", + "httpMethod": "PATCH", + "id": "generativelanguage.tunedModels.permissions.patch", + "parameterOrder": [ + "name" + ], + "parameters": { + "updateMask": { + "format": "google-fieldmask", + "description": "Required. The list of fields to update. Accepted ones: - role (`Permission.role` field)", + "location": "query", + "type": "string" + }, + "name": { + "location": "path", + "description": "Output only. Identifier. The permission name. A unique name will be generated on create. Examples: tunedModels/{tuned_model}/permissions/{permission} corpora/{corpus}/permissions/{permission} Output only.", + "required": true, + "pattern": "^tunedModels/[^/]+/permissions/[^/]+$", + "type": "string" + } + }, + "request": { + "$ref": "Permission" + }, + "response": { + "$ref": "Permission" + }, + "flatPath": "v1beta/tunedModels/{tunedModelsId}/permissions/{permissionsId}", + "path": "v1beta/{+name}" + }, + "delete": { + "parameterOrder": [ + "name" + ], + "description": "Deletes the permission.", + "response": { + "$ref": "Empty" + }, + "parameters": { + "name": { + "required": true, + "description": "Required. The resource name of the permission. Formats: `tunedModels/{tuned_model}/permissions/{permission}` `corpora/{corpus}/permissions/{permission}`", + "type": "string", + "pattern": "^tunedModels/[^/]+/permissions/[^/]+$", + "location": "path" + } + }, + "path": "v1beta/{+name}", + "id": "generativelanguage.tunedModels.permissions.delete", + "httpMethod": "DELETE", + "flatPath": "v1beta/tunedModels/{tunedModelsId}/permissions/{permissionsId}" + }, + "list": { + "description": "Lists permissions for the specific resource.", + "flatPath": "v1beta/tunedModels/{tunedModelsId}/permissions", + "parameters": { + "pageSize": { + "type": "integer", + "description": "Optional. The maximum number of `Permission`s to return (per page). The service may return fewer permissions. If unspecified, at most 10 permissions will be returned. This method returns at most 1000 permissions per page, even if you pass larger page_size.", + "format": "int32", + "location": "query" + }, + "pageToken": { + "type": "string", + "location": "query", + "description": "Optional. A page token, received from a previous `ListPermissions` call. Provide the `page_token` returned by one request as an argument to the next request to retrieve the next page. When paginating, all other parameters provided to `ListPermissions` must match the call that provided the page token." + }, + "parent": { + "pattern": "^tunedModels/[^/]+$", + "required": true, + "type": "string", + "location": "path", + "description": "Required. The parent resource of the permissions. Formats: `tunedModels/{tuned_model}` `corpora/{corpus}`" + } + }, + "parameterOrder": [ + "parent" + ], + "response": { + "$ref": "ListPermissionsResponse" + }, + "path": "v1beta/{+parent}/permissions", + "id": "generativelanguage.tunedModels.permissions.list", + "httpMethod": "GET" + }, + "get": { + "response": { + "$ref": "Permission" + }, + "parameters": { + "name": { + "pattern": "^tunedModels/[^/]+/permissions/[^/]+$", + "description": "Required. The resource name of the permission. Formats: `tunedModels/{tuned_model}/permissions/{permission}` `corpora/{corpus}/permissions/{permission}`", + "type": "string", + "required": true, + "location": "path" + } + }, + "path": "v1beta/{+name}", + "httpMethod": "GET", + "flatPath": "v1beta/tunedModels/{tunedModelsId}/permissions/{permissionsId}", + "parameterOrder": [ + "name" + ], + "id": "generativelanguage.tunedModels.permissions.get", + "description": "Gets information about a specific Permission." + }, + "create": { + "request": { + "$ref": "Permission" + }, + "response": { + "$ref": "Permission" + }, + "flatPath": "v1beta/tunedModels/{tunedModelsId}/permissions", + "description": "Create a permission to a specific resource.", + "id": "generativelanguage.tunedModels.permissions.create", + "path": "v1beta/{+parent}/permissions", + "httpMethod": "POST", + "parameters": { + "parent": { + "required": true, + "description": "Required. The parent resource of the `Permission`. Formats: `tunedModels/{tuned_model}` `corpora/{corpus}`", + "type": "string", + "location": "path", + "pattern": "^tunedModels/[^/]+$" + } + }, + "parameterOrder": [ + "parent" + ] + } + } + } + } + }, + "corpora": { + "resources": { + "documents": { + "resources": { + "chunks": { + "methods": { + "batchCreate": { + "id": "generativelanguage.corpora.documents.chunks.batchCreate", + "request": { + "$ref": "BatchCreateChunksRequest" + }, + "flatPath": "v1beta/corpora/{corporaId}/documents/{documentsId}/chunks:batchCreate", + "httpMethod": "POST", + "response": { + "$ref": "BatchCreateChunksResponse" + }, + "parameters": { + "parent": { + "required": true, + "pattern": "^corpora/[^/]+/documents/[^/]+$", + "location": "path", + "type": "string", + "description": "Optional. The name of the `Document` where this batch of `Chunk`s will be created. The parent field in every `CreateChunkRequest` must match this value. Example: `corpora/my-corpus-123/documents/the-doc-abc`" + } + }, + "path": "v1beta/{+parent}/chunks:batchCreate", + "description": "Batch create `Chunk`s.", + "parameterOrder": [ + "parent" + ] + }, + "delete": { + "description": "Deletes a `Chunk`.", + "flatPath": "v1beta/corpora/{corporaId}/documents/{documentsId}/chunks/{chunksId}", + "httpMethod": "DELETE", + "id": "generativelanguage.corpora.documents.chunks.delete", + "response": { + "$ref": "Empty" + }, + "parameterOrder": [ + "name" + ], + "parameters": { + "name": { + "pattern": "^corpora/[^/]+/documents/[^/]+/chunks/[^/]+$", + "required": true, + "type": "string", + "description": "Required. The resource name of the `Chunk` to delete. Example: `corpora/my-corpus-123/documents/the-doc-abc/chunks/some-chunk`", + "location": "path" + } + }, + "path": "v1beta/{+name}" + }, + "patch": { + "parameterOrder": [ + "name" + ], + "description": "Updates a `Chunk`.", + "parameters": { + "name": { + "required": true, + "pattern": "^corpora/[^/]+/documents/[^/]+/chunks/[^/]+$", + "description": "Immutable. Identifier. The `Chunk` resource name. The ID (name excluding the \"corpora/*/documents/*/chunks/\" prefix) can contain up to 40 characters that are lowercase alphanumeric or dashes (-). The ID cannot start or end with a dash. If the name is empty on create, a random 12-character unique ID will be generated. Example: `corpora/{corpus_id}/documents/{document_id}/chunks/123a456b789c`", + "location": "path", + "type": "string" + }, + "updateMask": { + "description": "Required. The list of fields to update. Currently, this only supports updating `custom_metadata` and `data`.", + "format": "google-fieldmask", + "type": "string", + "location": "query" + } + }, + "response": { + "$ref": "Chunk" + }, + "id": "generativelanguage.corpora.documents.chunks.patch", + "path": "v1beta/{+name}", + "httpMethod": "PATCH", + "request": { + "$ref": "Chunk" + }, + "flatPath": "v1beta/corpora/{corporaId}/documents/{documentsId}/chunks/{chunksId}" + }, + "create": { + "description": "Creates a `Chunk`.", + "httpMethod": "POST", + "path": "v1beta/{+parent}/chunks", + "parameterOrder": [ + "parent" + ], + "response": { + "$ref": "Chunk" + }, + "parameters": { + "parent": { + "required": true, + "pattern": "^corpora/[^/]+/documents/[^/]+$", + "location": "path", + "type": "string", + "description": "Required. The name of the `Document` where this `Chunk` will be created. Example: `corpora/my-corpus-123/documents/the-doc-abc`" + } + }, + "id": "generativelanguage.corpora.documents.chunks.create", + "flatPath": "v1beta/corpora/{corporaId}/documents/{documentsId}/chunks", + "request": { + "$ref": "Chunk" + } + }, + "list": { + "flatPath": "v1beta/corpora/{corporaId}/documents/{documentsId}/chunks", + "description": "Lists all `Chunk`s in a `Document`.", + "parameters": { + "pageToken": { + "location": "query", + "type": "string", + "description": "Optional. A page token, received from a previous `ListChunks` call. Provide the `next_page_token` returned in the response as an argument to the next request to retrieve the next page. When paginating, all other parameters provided to `ListChunks` must match the call that provided the page token." + }, + "parent": { + "location": "path", + "description": "Required. The name of the `Document` containing `Chunk`s. Example: `corpora/my-corpus-123/documents/the-doc-abc`", + "type": "string", + "pattern": "^corpora/[^/]+/documents/[^/]+$", + "required": true + }, + "pageSize": { + "type": "integer", + "format": "int32", + "location": "query", + "description": "Optional. The maximum number of `Chunk`s to return (per page). The service may return fewer `Chunk`s. If unspecified, at most 10 `Chunk`s will be returned. The maximum size limit is 100 `Chunk`s per page." + } + }, + "httpMethod": "GET", + "path": "v1beta/{+parent}/chunks", + "id": "generativelanguage.corpora.documents.chunks.list", + "parameterOrder": [ + "parent" + ], + "response": { + "$ref": "ListChunksResponse" + } + }, + "batchUpdate": { + "id": "generativelanguage.corpora.documents.chunks.batchUpdate", + "path": "v1beta/{+parent}/chunks:batchUpdate", + "description": "Batch update `Chunk`s.", + "flatPath": "v1beta/corpora/{corporaId}/documents/{documentsId}/chunks:batchUpdate", + "request": { + "$ref": "BatchUpdateChunksRequest" + }, + "parameterOrder": [ + "parent" + ], + "response": { + "$ref": "BatchUpdateChunksResponse" + }, + "httpMethod": "POST", + "parameters": { + "parent": { + "description": "Optional. The name of the `Document` containing the `Chunk`s to update. The parent field in every `UpdateChunkRequest` must match this value. Example: `corpora/my-corpus-123/documents/the-doc-abc`", + "pattern": "^corpora/[^/]+/documents/[^/]+$", + "location": "path", + "required": true, + "type": "string" + } + } + }, + "get": { + "description": "Gets information about a specific `Chunk`.", + "parameters": { + "name": { + "pattern": "^corpora/[^/]+/documents/[^/]+/chunks/[^/]+$", + "required": true, + "type": "string", + "location": "path", + "description": "Required. The name of the `Chunk` to retrieve. Example: `corpora/my-corpus-123/documents/the-doc-abc/chunks/some-chunk`" + } + }, + "flatPath": "v1beta/corpora/{corporaId}/documents/{documentsId}/chunks/{chunksId}", + "parameterOrder": [ + "name" + ], + "response": { + "$ref": "Chunk" + }, + "id": "generativelanguage.corpora.documents.chunks.get", + "httpMethod": "GET", + "path": "v1beta/{+name}" + }, + "batchDelete": { + "parameterOrder": [ + "parent" + ], + "description": "Batch delete `Chunk`s.", + "httpMethod": "POST", + "flatPath": "v1beta/corpora/{corporaId}/documents/{documentsId}/chunks:batchDelete", + "parameters": { + "parent": { + "location": "path", + "description": "Optional. The name of the `Document` containing the `Chunk`s to delete. The parent field in every `DeleteChunkRequest` must match this value. Example: `corpora/my-corpus-123/documents/the-doc-abc`", + "required": true, + "type": "string", + "pattern": "^corpora/[^/]+/documents/[^/]+$" + } + }, + "response": { + "$ref": "Empty" + }, + "id": "generativelanguage.corpora.documents.chunks.batchDelete", + "request": { + "$ref": "BatchDeleteChunksRequest" + }, + "path": "v1beta/{+parent}/chunks:batchDelete" + } + } + } + }, + "methods": { + "delete": { + "description": "Deletes a `Document`.", + "path": "v1beta/{+name}", + "response": { + "$ref": "Empty" + }, + "id": "generativelanguage.corpora.documents.delete", + "parameters": { + "force": { + "location": "query", + "description": "Optional. If set to true, any `Chunk`s and objects related to this `Document` will also be deleted. If false (the default), a `FAILED_PRECONDITION` error will be returned if `Document` contains any `Chunk`s.", + "type": "boolean" + }, + "name": { + "description": "Required. The resource name of the `Document` to delete. Example: `corpora/my-corpus-123/documents/the-doc-abc`", + "location": "path", + "required": true, + "pattern": "^corpora/[^/]+/documents/[^/]+$", + "type": "string" + } + }, + "parameterOrder": [ + "name" + ], + "flatPath": "v1beta/corpora/{corporaId}/documents/{documentsId}", + "httpMethod": "DELETE" + }, + "create": { + "flatPath": "v1beta/corpora/{corporaId}/documents", + "parameters": { + "parent": { + "pattern": "^corpora/[^/]+$", + "type": "string", + "location": "path", + "description": "Required. The name of the `Corpus` where this `Document` will be created. Example: `corpora/my-corpus-123`", + "required": true + } + }, + "response": { + "$ref": "Document" + }, + "id": "generativelanguage.corpora.documents.create", + "path": "v1beta/{+parent}/documents", + "parameterOrder": [ + "parent" + ], + "description": "Creates an empty `Document`.", + "request": { + "$ref": "Document" + }, + "httpMethod": "POST" + }, + "query": { + "flatPath": "v1beta/corpora/{corporaId}/documents/{documentsId}:query", + "response": { + "$ref": "QueryDocumentResponse" + }, + "parameterOrder": [ + "name" + ], + "request": { + "$ref": "QueryDocumentRequest" + }, + "path": "v1beta/{+name}:query", + "description": "Performs semantic search over a `Document`.", + "id": "generativelanguage.corpora.documents.query", + "httpMethod": "POST", + "parameters": { + "name": { + "pattern": "^corpora/[^/]+/documents/[^/]+$", + "type": "string", + "description": "Required. The name of the `Document` to query. Example: `corpora/my-corpus-123/documents/the-doc-abc`", + "required": true, + "location": "path" + } + } + }, + "patch": { + "description": "Updates a `Document`.", + "response": { + "$ref": "Document" + }, + "httpMethod": "PATCH", + "path": "v1beta/{+name}", + "parameters": { + "name": { + "required": true, + "pattern": "^corpora/[^/]+/documents/[^/]+$", + "description": "Immutable. Identifier. The `Document` resource name. The ID (name excluding the \"corpora/*/documents/\" prefix) can contain up to 40 characters that are lowercase alphanumeric or dashes (-). The ID cannot start or end with a dash. If the name is empty on create, a unique name will be derived from `display_name` along with a 12 character random suffix. Example: `corpora/{corpus_id}/documents/my-awesome-doc-123a456b789c`", + "type": "string", + "location": "path" + }, + "updateMask": { + "type": "string", + "location": "query", + "format": "google-fieldmask", + "description": "Required. The list of fields to update. Currently, this only supports updating `display_name` and `custom_metadata`." + } + }, + "parameterOrder": [ + "name" + ], + "id": "generativelanguage.corpora.documents.patch", + "request": { + "$ref": "Document" + }, + "flatPath": "v1beta/corpora/{corporaId}/documents/{documentsId}" + }, + "list": { + "id": "generativelanguage.corpora.documents.list", + "parameters": { + "pageSize": { + "location": "query", + "type": "integer", + "format": "int32", + "description": "Optional. The maximum number of `Document`s to return (per page). The service may return fewer `Document`s. If unspecified, at most 10 `Document`s will be returned. The maximum size limit is 20 `Document`s per page." + }, + "parent": { + "type": "string", + "location": "path", + "required": true, + "pattern": "^corpora/[^/]+$", + "description": "Required. The name of the `Corpus` containing `Document`s. Example: `corpora/my-corpus-123`" + }, + "pageToken": { + "type": "string", + "description": "Optional. A page token, received from a previous `ListDocuments` call. Provide the `next_page_token` returned in the response as an argument to the next request to retrieve the next page. When paginating, all other parameters provided to `ListDocuments` must match the call that provided the page token.", + "location": "query" + } + }, + "description": "Lists all `Document`s in a `Corpus`.", + "response": { + "$ref": "ListDocumentsResponse" + }, + "path": "v1beta/{+parent}/documents", + "httpMethod": "GET", + "parameterOrder": [ + "parent" + ], + "flatPath": "v1beta/corpora/{corporaId}/documents" + }, + "get": { + "parameterOrder": [ + "name" + ], + "response": { + "$ref": "Document" + }, + "description": "Gets information about a specific `Document`.", + "parameters": { + "name": { + "pattern": "^corpora/[^/]+/documents/[^/]+$", + "type": "string", + "required": true, + "description": "Required. The name of the `Document` to retrieve. Example: `corpora/my-corpus-123/documents/the-doc-abc`", + "location": "path" + } + }, + "id": "generativelanguage.corpora.documents.get", + "flatPath": "v1beta/corpora/{corporaId}/documents/{documentsId}", + "path": "v1beta/{+name}", + "httpMethod": "GET" + } + } + }, + "permissions": { + "methods": { + "list": { + "httpMethod": "GET", + "path": "v1beta/{+parent}/permissions", + "flatPath": "v1beta/corpora/{corporaId}/permissions", + "response": { + "$ref": "ListPermissionsResponse" + }, + "id": "generativelanguage.corpora.permissions.list", + "parameterOrder": [ + "parent" + ], + "description": "Lists permissions for the specific resource.", + "parameters": { + "pageToken": { + "location": "query", + "description": "Optional. A page token, received from a previous `ListPermissions` call. Provide the `page_token` returned by one request as an argument to the next request to retrieve the next page. When paginating, all other parameters provided to `ListPermissions` must match the call that provided the page token.", + "type": "string" + }, + "pageSize": { + "description": "Optional. The maximum number of `Permission`s to return (per page). The service may return fewer permissions. If unspecified, at most 10 permissions will be returned. This method returns at most 1000 permissions per page, even if you pass larger page_size.", + "format": "int32", + "location": "query", + "type": "integer" + }, + "parent": { + "description": "Required. The parent resource of the permissions. Formats: `tunedModels/{tuned_model}` `corpora/{corpus}`", + "required": true, + "location": "path", + "pattern": "^corpora/[^/]+$", + "type": "string" + } + } + }, + "delete": { + "path": "v1beta/{+name}", + "parameterOrder": [ + "name" + ], + "httpMethod": "DELETE", + "description": "Deletes the permission.", + "response": { + "$ref": "Empty" + }, + "flatPath": "v1beta/corpora/{corporaId}/permissions/{permissionsId}", + "id": "generativelanguage.corpora.permissions.delete", + "parameters": { + "name": { + "type": "string", + "location": "path", + "required": true, + "pattern": "^corpora/[^/]+/permissions/[^/]+$", + "description": "Required. The resource name of the permission. Formats: `tunedModels/{tuned_model}/permissions/{permission}` `corpora/{corpus}/permissions/{permission}`" + } + } + }, + "get": { + "response": { + "$ref": "Permission" + }, + "id": "generativelanguage.corpora.permissions.get", + "parameters": { + "name": { + "type": "string", + "description": "Required. The resource name of the permission. Formats: `tunedModels/{tuned_model}/permissions/{permission}` `corpora/{corpus}/permissions/{permission}`", + "required": true, + "location": "path", + "pattern": "^corpora/[^/]+/permissions/[^/]+$" + } + }, + "httpMethod": "GET", + "description": "Gets information about a specific Permission.", + "flatPath": "v1beta/corpora/{corporaId}/permissions/{permissionsId}", + "parameterOrder": [ + "name" + ], + "path": "v1beta/{+name}" + }, + "patch": { + "request": { + "$ref": "Permission" + }, + "parameterOrder": [ + "name" + ], + "id": "generativelanguage.corpora.permissions.patch", + "flatPath": "v1beta/corpora/{corporaId}/permissions/{permissionsId}", + "path": "v1beta/{+name}", + "description": "Updates the permission.", + "httpMethod": "PATCH", + "response": { + "$ref": "Permission" + }, + "parameters": { + "name": { + "description": "Output only. Identifier. The permission name. A unique name will be generated on create. Examples: tunedModels/{tuned_model}/permissions/{permission} corpora/{corpus}/permissions/{permission} Output only.", + "type": "string", + "pattern": "^corpora/[^/]+/permissions/[^/]+$", + "location": "path", + "required": true + }, + "updateMask": { + "type": "string", + "format": "google-fieldmask", + "location": "query", + "description": "Required. The list of fields to update. Accepted ones: - role (`Permission.role` field)" + } + } + }, + "create": { + "httpMethod": "POST", + "path": "v1beta/{+parent}/permissions", + "flatPath": "v1beta/corpora/{corporaId}/permissions", + "parameters": { + "parent": { + "pattern": "^corpora/[^/]+$", + "type": "string", + "description": "Required. The parent resource of the `Permission`. Formats: `tunedModels/{tuned_model}` `corpora/{corpus}`", + "required": true, + "location": "path" + } + }, + "id": "generativelanguage.corpora.permissions.create", + "request": { + "$ref": "Permission" + }, + "response": { + "$ref": "Permission" + }, + "description": "Create a permission to a specific resource.", + "parameterOrder": [ + "parent" + ] + } + } + } + }, + "methods": { + "create": { + "parameterOrder": [], + "description": "Creates an empty `Corpus`.", + "request": { + "$ref": "Corpus" + }, + "httpMethod": "POST", + "response": { + "$ref": "Corpus" + }, + "id": "generativelanguage.corpora.create", + "flatPath": "v1beta/corpora", + "path": "v1beta/corpora", + "parameters": {} + }, + "query": { + "parameterOrder": [ + "name" + ], + "request": { + "$ref": "QueryCorpusRequest" + }, + "parameters": { + "name": { + "location": "path", + "pattern": "^corpora/[^/]+$", + "required": true, + "type": "string", + "description": "Required. The name of the `Corpus` to query. Example: `corpora/my-corpus-123`" + } + }, + "httpMethod": "POST", + "response": { + "$ref": "QueryCorpusResponse" + }, + "flatPath": "v1beta/corpora/{corporaId}:query", + "id": "generativelanguage.corpora.query", + "description": "Performs semantic search over a `Corpus`.", + "path": "v1beta/{+name}:query" + }, + "get": { + "flatPath": "v1beta/corpora/{corporaId}", + "description": "Gets information about a specific `Corpus`.", + "parameters": { + "name": { + "pattern": "^corpora/[^/]+$", + "location": "path", + "description": "Required. The name of the `Corpus`. Example: `corpora/my-corpus-123`", + "type": "string", + "required": true + } + }, + "response": { + "$ref": "Corpus" + }, + "id": "generativelanguage.corpora.get", + "path": "v1beta/{+name}", + "parameterOrder": [ + "name" + ], + "httpMethod": "GET" + }, + "delete": { + "description": "Deletes a `Corpus`.", + "flatPath": "v1beta/corpora/{corporaId}", + "id": "generativelanguage.corpora.delete", + "parameterOrder": [ + "name" + ], + "parameters": { + "force": { + "location": "query", + "description": "Optional. If set to true, any `Document`s and objects related to this `Corpus` will also be deleted. If false (the default), a `FAILED_PRECONDITION` error will be returned if `Corpus` contains any `Document`s.", + "type": "boolean" + }, + "name": { + "required": true, + "type": "string", + "pattern": "^corpora/[^/]+$", + "location": "path", + "description": "Required. The resource name of the `Corpus`. Example: `corpora/my-corpus-123`" + } + }, + "response": { + "$ref": "Empty" + }, + "httpMethod": "DELETE", + "path": "v1beta/{+name}" + }, + "patch": { + "id": "generativelanguage.corpora.patch", + "parameterOrder": [ + "name" + ], + "description": "Updates a `Corpus`.", + "flatPath": "v1beta/corpora/{corporaId}", + "parameters": { + "updateMask": { + "format": "google-fieldmask", + "type": "string", + "location": "query", + "description": "Required. The list of fields to update. Currently, this only supports updating `display_name`." + }, + "name": { + "location": "path", + "required": true, + "type": "string", + "pattern": "^corpora/[^/]+$", + "description": "Immutable. Identifier. The `Corpus` resource name. The ID (name excluding the \"corpora/\" prefix) can contain up to 40 characters that are lowercase alphanumeric or dashes (-). The ID cannot start or end with a dash. If the name is empty on create, a unique name will be derived from `display_name` along with a 12 character random suffix. Example: `corpora/my-awesome-corpora-123a456b789c`" + } + }, + "response": { + "$ref": "Corpus" + }, + "httpMethod": "PATCH", + "path": "v1beta/{+name}", + "request": { + "$ref": "Corpus" + } + }, + "list": { + "id": "generativelanguage.corpora.list", + "path": "v1beta/corpora", + "flatPath": "v1beta/corpora", + "description": "Lists all `Corpora` owned by the user.", + "parameterOrder": [], + "httpMethod": "GET", + "response": { + "$ref": "ListCorporaResponse" + }, + "parameters": { + "pageSize": { + "type": "integer", + "format": "int32", + "description": "Optional. The maximum number of `Corpora` to return (per page). The service may return fewer `Corpora`. If unspecified, at most 10 `Corpora` will be returned. The maximum size limit is 20 `Corpora` per page.", + "location": "query" + }, + "pageToken": { + "location": "query", + "type": "string", + "description": "Optional. A page token, received from a previous `ListCorpora` call. Provide the `next_page_token` returned in the response as an argument to the next request to retrieve the next page. When paginating, all other parameters provided to `ListCorpora` must match the call that provided the page token." + } + } + } + } + }, + "media": { + "methods": { + "upload": { + "mediaUpload": { + "maxSize": "2147483648", + "accept": [ + "*/*" + ], + "protocols": { + "resumable": { + "path": "/resumable/upload/v1beta/files", + "multipart": true + }, + "simple": { + "path": "/upload/v1beta/files", + "multipart": true + } + } + }, + "response": { + "$ref": "CreateFileResponse" + }, + "flatPath": "v1beta/files", + "id": "generativelanguage.media.upload", + "description": "Creates a `File`.", + "request": { + "$ref": "CreateFileRequest" + }, + "httpMethod": "POST", + "supportsMediaUpload": true, + "path": "v1beta/files", + "parameters": {}, + "parameterOrder": [] + } + } + }, + "files": { + "methods": { + "list": { + "flatPath": "v1beta/files", + "parameterOrder": [], + "httpMethod": "GET", + "id": "generativelanguage.files.list", + "description": "Lists the metadata for `File`s owned by the requesting project.", + "path": "v1beta/files", + "parameters": { + "pageSize": { + "format": "int32", + "type": "integer", + "location": "query", + "description": "Optional. Maximum number of `File`s to return per page. If unspecified, defaults to 10. Maximum `page_size` is 100." + }, + "pageToken": { + "description": "Optional. A page token from a previous `ListFiles` call.", + "type": "string", + "location": "query" + } + }, + "response": { + "$ref": "ListFilesResponse" + } + }, + "get": { + "parameterOrder": [ + "name" + ], + "path": "v1beta/{+name}", + "description": "Gets the metadata for the given `File`.", + "id": "generativelanguage.files.get", + "response": { + "$ref": "File" + }, + "parameters": { + "name": { + "required": true, + "pattern": "^files/[^/]+$", + "location": "path", + "description": "Required. The name of the `File` to get. Example: `files/abc-123`", + "type": "string" + } + }, + "flatPath": "v1beta/files/{filesId}", + "httpMethod": "GET" + }, + "delete": { + "httpMethod": "DELETE", + "parameterOrder": [ + "name" + ], + "response": { + "$ref": "Empty" + }, + "description": "Deletes the `File`.", + "id": "generativelanguage.files.delete", + "flatPath": "v1beta/files/{filesId}", + "parameters": { + "name": { + "description": "Required. The name of the `File` to delete. Example: `files/abc-123`", + "location": "path", + "required": true, + "pattern": "^files/[^/]+$", + "type": "string" + } + }, + "path": "v1beta/{+name}" + } + } + }, + "models": { + "methods": { + "generateMessage": { + "description": "Generates a response from the model given an input `MessagePrompt`.", + "request": { + "$ref": "GenerateMessageRequest" + }, + "parameterOrder": [ + "model" + ], + "path": "v1beta/{+model}:generateMessage", + "response": { + "$ref": "GenerateMessageResponse" + }, + "httpMethod": "POST", + "parameters": { + "model": { + "type": "string", + "pattern": "^models/[^/]+$", + "required": true, + "description": "Required. The name of the model to use. Format: `name=models/{model}`.", + "location": "path" + } + }, + "flatPath": "v1beta/models/{modelsId}:generateMessage", + "id": "generativelanguage.models.generateMessage" + }, + "generateContent": { + "id": "generativelanguage.models.generateContent", + "path": "v1beta/{+model}:generateContent", + "request": { + "$ref": "GenerateContentRequest" + }, + "flatPath": "v1beta/models/{modelsId}:generateContent", + "description": "Generates a response from the model given an input `GenerateContentRequest`. Input capabilities differ between models, including tuned models. See the [model guide](https://ai.google.dev/models/gemini) and [tuning guide](https://ai.google.dev/docs/model_tuning_guidance) for details.", + "parameterOrder": [ + "model" + ], + "response": { + "$ref": "GenerateContentResponse" + }, + "httpMethod": "POST", + "parameters": { + "model": { + "pattern": "^models/[^/]+$", + "description": "Required. The name of the `Model` to use for generating the completion. Format: `name=models/{model}`.", + "type": "string", + "location": "path", + "required": true + } + } + }, + "batchEmbedText": { + "httpMethod": "POST", + "description": "Generates multiple embeddings from the model given input text in a synchronous call.", + "response": { + "$ref": "BatchEmbedTextResponse" + }, + "flatPath": "v1beta/models/{modelsId}:batchEmbedText", + "parameterOrder": [ + "model" + ], + "request": { + "$ref": "BatchEmbedTextRequest" + }, + "path": "v1beta/{+model}:batchEmbedText", + "id": "generativelanguage.models.batchEmbedText", + "parameters": { + "model": { + "type": "string", + "location": "path", + "pattern": "^models/[^/]+$", + "description": "Required. The name of the `Model` to use for generating the embedding. Examples: models/embedding-gecko-001", + "required": true + } + } + }, + "get": { + "description": "Gets information about a specific Model.", + "parameterOrder": [ + "name" + ], + "path": "v1beta/{+name}", + "flatPath": "v1beta/models/{modelsId}", + "id": "generativelanguage.models.get", + "response": { + "$ref": "Model" + }, + "httpMethod": "GET", + "parameters": { + "name": { + "description": "Required. The resource name of the model. This name should match a model name returned by the `ListModels` method. Format: `models/{model}`", + "required": true, + "pattern": "^models/[^/]+$", + "type": "string", + "location": "path" + } + } + }, + "embedContent": { + "request": { + "$ref": "EmbedContentRequest" + }, + "description": "Generates an embedding from the model given an input `Content`.", + "response": { + "$ref": "EmbedContentResponse" + }, + "httpMethod": "POST", + "parameterOrder": [ + "model" + ], + "id": "generativelanguage.models.embedContent", + "flatPath": "v1beta/models/{modelsId}:embedContent", + "parameters": { + "model": { + "pattern": "^models/[^/]+$", + "description": "Required. The model's resource name. This serves as an ID for the Model to use. This name should match a model name returned by the `ListModels` method. Format: `models/{model}`", + "location": "path", + "type": "string", + "required": true + } + }, + "path": "v1beta/{+model}:embedContent" + }, + "streamGenerateContent": { + "description": "Generates a streamed response from the model given an input `GenerateContentRequest`.", + "parameters": { + "model": { + "pattern": "^models/[^/]+$", + "description": "Required. The name of the `Model` to use for generating the completion. Format: `name=models/{model}`.", + "type": "string", + "required": true, + "location": "path" + } + }, + "httpMethod": "POST", + "id": "generativelanguage.models.streamGenerateContent", + "response": { + "$ref": "GenerateContentResponse" + }, + "path": "v1beta/{+model}:streamGenerateContent", + "request": { + "$ref": "GenerateContentRequest" + }, + "parameterOrder": [ + "model" + ], + "flatPath": "v1beta/models/{modelsId}:streamGenerateContent" + }, + "embedText": { + "response": { + "$ref": "EmbedTextResponse" + }, + "httpMethod": "POST", + "parameters": { + "model": { + "type": "string", + "required": true, + "pattern": "^models/[^/]+$", + "description": "Required. The model name to use with the format model=models/{model}.", + "location": "path" + } + }, + "parameterOrder": [ + "model" + ], + "flatPath": "v1beta/models/{modelsId}:embedText", + "request": { + "$ref": "EmbedTextRequest" + }, + "description": "Generates an embedding from the model given an input message.", + "path": "v1beta/{+model}:embedText", + "id": "generativelanguage.models.embedText" + }, + "list": { + "parameterOrder": [], + "id": "generativelanguage.models.list", + "flatPath": "v1beta/models", + "response": { + "$ref": "ListModelsResponse" + }, + "httpMethod": "GET", + "description": "Lists models available through the API.", + "parameters": { + "pageSize": { + "location": "query", + "format": "int32", + "description": "The maximum number of `Models` to return (per page). The service may return fewer models. If unspecified, at most 50 models will be returned per page. This method returns at most 1000 models per page, even if you pass a larger page_size.", + "type": "integer" + }, + "pageToken": { + "type": "string", + "description": "A page token, received from a previous `ListModels` call. Provide the `page_token` returned by one request as an argument to the next request to retrieve the next page. When paginating, all other parameters provided to `ListModels` must match the call that provided the page token.", + "location": "query" + } + }, + "path": "v1beta/models" + }, + "generateText": { + "flatPath": "v1beta/models/{modelsId}:generateText", + "request": { + "$ref": "GenerateTextRequest" + }, + "description": "Generates a response from the model given an input message.", + "parameters": { + "model": { + "description": "Required. The name of the `Model` or `TunedModel` to use for generating the completion. Examples: models/text-bison-001 tunedModels/sentence-translator-u3b7m", + "location": "path", + "type": "string", + "pattern": "^models/[^/]+$", + "required": true + } + }, + "httpMethod": "POST", + "response": { + "$ref": "GenerateTextResponse" + }, + "path": "v1beta/{+model}:generateText", + "parameterOrder": [ + "model" + ], + "id": "generativelanguage.models.generateText" + }, + "batchEmbedContents": { + "id": "generativelanguage.models.batchEmbedContents", + "parameterOrder": [ + "model" + ], + "path": "v1beta/{+model}:batchEmbedContents", + "httpMethod": "POST", + "response": { + "$ref": "BatchEmbedContentsResponse" + }, + "description": "Generates multiple embeddings from the model given input text in a synchronous call.", + "flatPath": "v1beta/models/{modelsId}:batchEmbedContents", + "parameters": { + "model": { + "type": "string", + "location": "path", + "pattern": "^models/[^/]+$", + "description": "Required. The model's resource name. This serves as an ID for the Model to use. This name should match a model name returned by the `ListModels` method. Format: `models/{model}`", + "required": true + } + }, + "request": { + "$ref": "BatchEmbedContentsRequest" + } + }, + "countTokens": { + "description": "Runs a model's tokenizer on input content and returns the token count.", + "httpMethod": "POST", + "request": { + "$ref": "CountTokensRequest" + }, + "id": "generativelanguage.models.countTokens", + "parameterOrder": [ + "model" + ], + "response": { + "$ref": "CountTokensResponse" + }, + "flatPath": "v1beta/models/{modelsId}:countTokens", + "parameters": { + "model": { + "location": "path", + "type": "string", + "description": "Required. The model's resource name. This serves as an ID for the Model to use. This name should match a model name returned by the `ListModels` method. Format: `models/{model}`", + "pattern": "^models/[^/]+$", + "required": true + } + }, + "path": "v1beta/{+model}:countTokens" + }, + "countMessageTokens": { + "id": "generativelanguage.models.countMessageTokens", + "httpMethod": "POST", + "parameterOrder": [ + "model" + ], + "request": { + "$ref": "CountMessageTokensRequest" + }, + "description": "Runs a model's tokenizer on a string and returns the token count.", + "path": "v1beta/{+model}:countMessageTokens", + "response": { + "$ref": "CountMessageTokensResponse" + }, + "parameters": { + "model": { + "location": "path", + "type": "string", + "pattern": "^models/[^/]+$", + "description": "Required. The model's resource name. This serves as an ID for the Model to use. This name should match a model name returned by the `ListModels` method. Format: `models/{model}`", + "required": true + } + }, + "flatPath": "v1beta/models/{modelsId}:countMessageTokens" + }, + "countTextTokens": { + "flatPath": "v1beta/models/{modelsId}:countTextTokens", + "description": "Runs a model's tokenizer on a text and returns the token count.", + "request": { + "$ref": "CountTextTokensRequest" + }, + "parameters": { + "model": { + "type": "string", + "pattern": "^models/[^/]+$", + "required": true, + "description": "Required. The model's resource name. This serves as an ID for the Model to use. This name should match a model name returned by the `ListModels` method. Format: `models/{model}`", + "location": "path" + } + }, + "parameterOrder": [ + "model" + ], + "path": "v1beta/{+model}:countTextTokens", + "httpMethod": "POST", + "response": { + "$ref": "CountTextTokensResponse" + }, + "id": "generativelanguage.models.countTextTokens" + }, + "generateAnswer": { + "response": { + "$ref": "GenerateAnswerResponse" + }, + "id": "generativelanguage.models.generateAnswer", + "request": { + "$ref": "GenerateAnswerRequest" + }, + "parameterOrder": [ + "model" + ], + "description": "Generates a grounded answer from the model given an input `GenerateAnswerRequest`.", + "httpMethod": "POST", + "flatPath": "v1beta/models/{modelsId}:generateAnswer", + "path": "v1beta/{+model}:generateAnswer", + "parameters": { + "model": { + "location": "path", + "pattern": "^models/[^/]+$", + "type": "string", + "description": "Required. The name of the `Model` to use for generating the grounded response. Format: `model=models/{model}`.", + "required": true + } + } + } + } + } + }, + "basePath": "" +} diff --git a/vendor/github.com/google/generative-ai-go/genai/internal/generativelanguage/v1beta/generativelanguage-gen.go b/vendor/github.com/google/generative-ai-go/genai/internal/generativelanguage/v1beta/generativelanguage-gen.go new file mode 100644 index 000000000..46501dd38 --- /dev/null +++ b/vendor/github.com/google/generative-ai-go/genai/internal/generativelanguage/v1beta/generativelanguage-gen.go @@ -0,0 +1,10168 @@ +// Copyright 2024 Google LLC. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Code generated file. DO NOT EDIT. + +// Package generativelanguage provides access to the Generative Language API. +// +// For product documentation, see: https://developers.generativeai.google/api +// +// # Library status +// +// These client libraries are officially supported by Google. However, this +// library is considered complete and is in maintenance mode. This means +// that we will address critical bugs and security issues but will not add +// any new features. +// +// When possible, we recommend using our newer +// [Cloud Client Libraries for Go](https://pkg.go.dev/cloud.google.com/go) +// that are still actively being worked and iterated on. +// +// # Creating a client +// +// Usage example: +// +// import "google.golang.org/api/generativelanguage/v1beta" +// ... +// ctx := context.Background() +// generativelanguageService, err := generativelanguage.NewService(ctx) +// +// In this example, Google Application Default Credentials are used for +// authentication. For information on how to create and obtain Application +// Default Credentials, see https://developers.google.com/identity/protocols/application-default-credentials. +// +// # Other authentication options +// +// To use an API key for authentication (note: some APIs do not support API +// keys), use [google.golang.org/api/option.WithAPIKey]: +// +// generativelanguageService, err := generativelanguage.NewService(ctx, option.WithAPIKey("AIza...")) +// +// To use an OAuth token (e.g., a user token obtained via a three-legged OAuth +// flow, use [google.golang.org/api/option.WithTokenSource]: +// +// config := &oauth2.Config{...} +// // ... +// token, err := config.Exchange(ctx, ...) +// generativelanguageService, err := generativelanguage.NewService(ctx, option.WithTokenSource(config.TokenSource(ctx, token))) +// +// See [google.golang.org/api/option.ClientOption] for details on options. +package generativelanguage // import "google.golang.org/api/generativelanguage/v1beta" + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "strconv" + "strings" + + internal "github.com/google/generative-ai-go/genai/internal" + gensupport "github.com/google/generative-ai-go/genai/internal/gensupport" + googleapi "google.golang.org/api/googleapi" + option "google.golang.org/api/option" + internaloption "google.golang.org/api/option/internaloption" + htransport "google.golang.org/api/transport/http" +) + +// Always reference these packages, just in case the auto-generated code +// below doesn't. +var _ = bytes.NewBuffer +var _ = strconv.Itoa +var _ = fmt.Sprintf +var _ = json.NewDecoder +var _ = io.Copy +var _ = url.Parse +var _ = gensupport.MarshalJSON +var _ = googleapi.Version +var _ = errors.New +var _ = strings.Replace +var _ = context.Canceled +var _ = internaloption.WithDefaultEndpoint +var _ = internal.Version + +const apiId = "generativelanguage:v1beta" +const apiName = "generativelanguage" +const apiVersion = "v1beta" +const basePath = "https://generativelanguage.googleapis.com/" +const basePathTemplate = "https://generativelanguage.UNIVERSE_DOMAIN/" +const mtlsBasePath = "https://generativelanguage.mtls.googleapis.com/" + +// NewService creates a new Service. +func NewService(ctx context.Context, opts ...option.ClientOption) (*Service, error) { + opts = append(opts, internaloption.WithDefaultEndpoint(basePath)) + opts = append(opts, internaloption.WithDefaultEndpointTemplate(basePathTemplate)) + opts = append(opts, internaloption.WithDefaultMTLSEndpoint(mtlsBasePath)) + opts = append(opts, internaloption.EnableNewAuthLibrary()) + client, endpoint, err := htransport.NewClient(ctx, opts...) + if err != nil { + return nil, err + } + s, err := New(client) + if err != nil { + return nil, err + } + if endpoint != "" { + s.BasePath = endpoint + } + return s, nil +} + +// New creates a new Service. It uses the provided http.Client for requests. +// +// Deprecated: please use NewService instead. +// To provide a custom HTTP client, use option.WithHTTPClient. +// If you are using google.golang.org/api/googleapis/transport.APIKey, use option.WithAPIKey with NewService instead. +func New(client *http.Client) (*Service, error) { + if client == nil { + return nil, errors.New("client is nil") + } + s := &Service{client: client, BasePath: basePath} + s.Corpora = NewCorporaService(s) + s.Files = NewFilesService(s) + s.Media = NewMediaService(s) + s.Models = NewModelsService(s) + s.TunedModels = NewTunedModelsService(s) + return s, nil +} + +type Service struct { + client *http.Client + BasePath string // API endpoint base URL + UserAgent string // optional additional User-Agent fragment + + Corpora *CorporaService + + Files *FilesService + + Media *MediaService + + Models *ModelsService + + TunedModels *TunedModelsService +} + +func (s *Service) userAgent() string { + if s.UserAgent == "" { + return googleapi.UserAgent + } + return googleapi.UserAgent + " " + s.UserAgent +} + +func NewCorporaService(s *Service) *CorporaService { + rs := &CorporaService{s: s} + rs.Documents = NewCorporaDocumentsService(s) + rs.Permissions = NewCorporaPermissionsService(s) + return rs +} + +type CorporaService struct { + s *Service + + Documents *CorporaDocumentsService + + Permissions *CorporaPermissionsService +} + +func NewCorporaDocumentsService(s *Service) *CorporaDocumentsService { + rs := &CorporaDocumentsService{s: s} + rs.Chunks = NewCorporaDocumentsChunksService(s) + return rs +} + +type CorporaDocumentsService struct { + s *Service + + Chunks *CorporaDocumentsChunksService +} + +func NewCorporaDocumentsChunksService(s *Service) *CorporaDocumentsChunksService { + rs := &CorporaDocumentsChunksService{s: s} + return rs +} + +type CorporaDocumentsChunksService struct { + s *Service +} + +func NewCorporaPermissionsService(s *Service) *CorporaPermissionsService { + rs := &CorporaPermissionsService{s: s} + return rs +} + +type CorporaPermissionsService struct { + s *Service +} + +func NewFilesService(s *Service) *FilesService { + rs := &FilesService{s: s} + return rs +} + +type FilesService struct { + s *Service +} + +func NewMediaService(s *Service) *MediaService { + rs := &MediaService{s: s} + return rs +} + +type MediaService struct { + s *Service +} + +func NewModelsService(s *Service) *ModelsService { + rs := &ModelsService{s: s} + return rs +} + +type ModelsService struct { + s *Service +} + +func NewTunedModelsService(s *Service) *TunedModelsService { + rs := &TunedModelsService{s: s} + rs.Permissions = NewTunedModelsPermissionsService(s) + return rs +} + +type TunedModelsService struct { + s *Service + + Permissions *TunedModelsPermissionsService +} + +func NewTunedModelsPermissionsService(s *Service) *TunedModelsPermissionsService { + rs := &TunedModelsPermissionsService{s: s} + return rs +} + +type TunedModelsPermissionsService struct { + s *Service +} + +// AttributionSourceId: Identifier for the source contributing to this +// attribution. +type AttributionSourceId struct { + // GroundingPassage: Identifier for an inline passage. + GroundingPassage *GroundingPassageId `json:"groundingPassage,omitempty"` + // SemanticRetrieverChunk: Identifier for a `Chunk` fetched via Semantic + // Retriever. + SemanticRetrieverChunk *SemanticRetrieverChunk `json:"semanticRetrieverChunk,omitempty"` + // ForceSendFields is a list of field names (e.g. "GroundingPassage") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "GroundingPassage") to include in + // API requests with the JSON null value. By default, fields with empty values + // are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *AttributionSourceId) MarshalJSON() ([]byte, error) { + type NoMethod AttributionSourceId + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// BatchCreateChunksRequest: Request to batch create `Chunk`s. +type BatchCreateChunksRequest struct { + // Requests: Required. The request messages specifying the `Chunk`s to create. + // A maximum of 100 `Chunk`s can be created in a batch. + Requests []*CreateChunkRequest `json:"requests,omitempty"` + // ForceSendFields is a list of field names (e.g. "Requests") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Requests") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *BatchCreateChunksRequest) MarshalJSON() ([]byte, error) { + type NoMethod BatchCreateChunksRequest + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// BatchCreateChunksResponse: Response from `BatchCreateChunks` containing a +// list of created `Chunk`s. +type BatchCreateChunksResponse struct { + // Chunks: `Chunk`s created. + Chunks []*Chunk `json:"chunks,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the server. + googleapi.ServerResponse `json:"-"` + // ForceSendFields is a list of field names (e.g. "Chunks") to unconditionally + // include in API requests. By default, fields with empty or default values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Chunks") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *BatchCreateChunksResponse) MarshalJSON() ([]byte, error) { + type NoMethod BatchCreateChunksResponse + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// BatchDeleteChunksRequest: Request to batch delete `Chunk`s. +type BatchDeleteChunksRequest struct { + // Requests: Required. The request messages specifying the `Chunk`s to delete. + Requests []*DeleteChunkRequest `json:"requests,omitempty"` + // ForceSendFields is a list of field names (e.g. "Requests") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Requests") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *BatchDeleteChunksRequest) MarshalJSON() ([]byte, error) { + type NoMethod BatchDeleteChunksRequest + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// BatchEmbedContentsRequest: Batch request to get embeddings from the model +// for a list of prompts. +type BatchEmbedContentsRequest struct { + // Requests: Required. Embed requests for the batch. The model in each of these + // requests must match the model specified `BatchEmbedContentsRequest.model`. + Requests []*EmbedContentRequest `json:"requests,omitempty"` + // ForceSendFields is a list of field names (e.g. "Requests") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Requests") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *BatchEmbedContentsRequest) MarshalJSON() ([]byte, error) { + type NoMethod BatchEmbedContentsRequest + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// BatchEmbedContentsResponse: The response to a `BatchEmbedContentsRequest`. +type BatchEmbedContentsResponse struct { + // Embeddings: Output only. The embeddings for each request, in the same order + // as provided in the batch request. + Embeddings []*ContentEmbedding `json:"embeddings,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the server. + googleapi.ServerResponse `json:"-"` + // ForceSendFields is a list of field names (e.g. "Embeddings") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Embeddings") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *BatchEmbedContentsResponse) MarshalJSON() ([]byte, error) { + type NoMethod BatchEmbedContentsResponse + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// BatchEmbedTextRequest: Batch request to get a text embedding from the model. +type BatchEmbedTextRequest struct { + // Requests: Optional. Embed requests for the batch. Only one of `texts` or + // `requests` can be set. + Requests []*EmbedTextRequest `json:"requests,omitempty"` + // Texts: Optional. The free-form input texts that the model will turn into an + // embedding. The current limit is 100 texts, over which an error will be + // thrown. + Texts []string `json:"texts,omitempty"` + // ForceSendFields is a list of field names (e.g. "Requests") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Requests") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *BatchEmbedTextRequest) MarshalJSON() ([]byte, error) { + type NoMethod BatchEmbedTextRequest + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// BatchEmbedTextResponse: The response to a EmbedTextRequest. +type BatchEmbedTextResponse struct { + // Embeddings: Output only. The embeddings generated from the input text. + Embeddings []*Embedding `json:"embeddings,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the server. + googleapi.ServerResponse `json:"-"` + // ForceSendFields is a list of field names (e.g. "Embeddings") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Embeddings") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *BatchEmbedTextResponse) MarshalJSON() ([]byte, error) { + type NoMethod BatchEmbedTextResponse + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// BatchUpdateChunksRequest: Request to batch update `Chunk`s. +type BatchUpdateChunksRequest struct { + // Requests: Required. The request messages specifying the `Chunk`s to update. + // A maximum of 100 `Chunk`s can be updated in a batch. + Requests []*UpdateChunkRequest `json:"requests,omitempty"` + // ForceSendFields is a list of field names (e.g. "Requests") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Requests") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *BatchUpdateChunksRequest) MarshalJSON() ([]byte, error) { + type NoMethod BatchUpdateChunksRequest + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// BatchUpdateChunksResponse: Response from `BatchUpdateChunks` containing a +// list of updated `Chunk`s. +type BatchUpdateChunksResponse struct { + // Chunks: `Chunk`s updated. + Chunks []*Chunk `json:"chunks,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the server. + googleapi.ServerResponse `json:"-"` + // ForceSendFields is a list of field names (e.g. "Chunks") to unconditionally + // include in API requests. By default, fields with empty or default values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Chunks") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *BatchUpdateChunksResponse) MarshalJSON() ([]byte, error) { + type NoMethod BatchUpdateChunksResponse + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// Blob: Raw media bytes. Text should not be sent as raw bytes, use the 'text' +// field. +type Blob struct { + // Data: Raw bytes for media formats. + Data string `json:"data,omitempty"` + // MimeType: The IANA standard MIME type of the source data. Examples: - + // image/png - image/jpeg If an unsupported MIME type is provided, an error + // will be returned. For a complete list of supported types, see Supported file + // formats + // (https://ai.google.dev/gemini-api/docs/prompting_with_media#supported_file_formats). + MimeType string `json:"mimeType,omitempty"` + // ForceSendFields is a list of field names (e.g. "Data") to unconditionally + // include in API requests. By default, fields with empty or default values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Data") to include in API requests + // with the JSON null value. By default, fields with empty values are omitted + // from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *Blob) MarshalJSON() ([]byte, error) { + type NoMethod Blob + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// Candidate: A response candidate generated from the model. +type Candidate struct { + // CitationMetadata: Output only. Citation information for model-generated + // candidate. This field may be populated with recitation information for any + // text included in the `content`. These are passages that are "recited" from + // copyrighted material in the foundational LLM's training data. + CitationMetadata *CitationMetadata `json:"citationMetadata,omitempty"` + // Content: Output only. Generated content returned from the model. + Content *Content `json:"content,omitempty"` + // FinishReason: Optional. Output only. The reason why the model stopped + // generating tokens. If empty, the model has not stopped generating the + // tokens. + // + // Possible values: + // "FINISH_REASON_UNSPECIFIED" - Default value. This value is unused. + // "STOP" - Natural stop point of the model or provided stop sequence. + // "MAX_TOKENS" - The maximum number of tokens as specified in the request + // was reached. + // "SAFETY" - The candidate content was flagged for safety reasons. + // "RECITATION" - The candidate content was flagged for recitation reasons. + // "OTHER" - Unknown reason. + FinishReason string `json:"finishReason,omitempty"` + // GroundingAttributions: Output only. Attribution information for sources that + // contributed to a grounded answer. This field is populated for + // `GenerateAnswer` calls. + GroundingAttributions []*GroundingAttribution `json:"groundingAttributions,omitempty"` + // Index: Output only. Index of the candidate in the list of candidates. + Index int64 `json:"index,omitempty"` + // SafetyRatings: List of ratings for the safety of a response candidate. There + // is at most one rating per category. + SafetyRatings []*SafetyRating `json:"safetyRatings,omitempty"` + // TokenCount: Output only. Token count for this candidate. + TokenCount int64 `json:"tokenCount,omitempty"` + // ForceSendFields is a list of field names (e.g. "CitationMetadata") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "CitationMetadata") to include in + // API requests with the JSON null value. By default, fields with empty values + // are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *Candidate) MarshalJSON() ([]byte, error) { + type NoMethod Candidate + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// Chunk: A `Chunk` is a subpart of a `Document` that is treated as an +// independent unit for the purposes of vector representation and storage. A +// `Corpus` can have a maximum of 1 million `Chunk`s. +type Chunk struct { + // CreateTime: Output only. The Timestamp of when the `Chunk` was created. + CreateTime string `json:"createTime,omitempty"` + // CustomMetadata: Optional. User provided custom metadata stored as key-value + // pairs. The maximum number of `CustomMetadata` per chunk is 20. + CustomMetadata []*CustomMetadata `json:"customMetadata,omitempty"` + // Data: Required. The content for the `Chunk`, such as the text string. The + // maximum number of tokens per chunk is 2043. + Data *ChunkData `json:"data,omitempty"` + // Name: Immutable. Identifier. The `Chunk` resource name. The ID (name + // excluding the "corpora/*/documents/*/chunks/" prefix) can contain up to 40 + // characters that are lowercase alphanumeric or dashes (-). The ID cannot + // start or end with a dash. If the name is empty on create, a random + // 12-character unique ID will be generated. Example: + // `corpora/{corpus_id}/documents/{document_id}/chunks/123a456b789c` + Name string `json:"name,omitempty"` + // State: Output only. Current state of the `Chunk`. + // + // Possible values: + // "STATE_UNSPECIFIED" - The default value. This value is used if the state + // is omitted. + // "STATE_PENDING_PROCESSING" - `Chunk` is being processed (embedding and + // vector storage). + // "STATE_ACTIVE" - `Chunk` is processed and available for querying. + // "STATE_FAILED" - `Chunk` failed processing. + State string `json:"state,omitempty"` + // UpdateTime: Output only. The Timestamp of when the `Chunk` was last updated. + UpdateTime string `json:"updateTime,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the server. + googleapi.ServerResponse `json:"-"` + // ForceSendFields is a list of field names (e.g. "CreateTime") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "CreateTime") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *Chunk) MarshalJSON() ([]byte, error) { + type NoMethod Chunk + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// ChunkData: Extracted data that represents the `Chunk` content. +type ChunkData struct { + // StringValue: The `Chunk` content as a string. The maximum number of tokens + // per chunk is 2043. + StringValue string `json:"stringValue,omitempty"` + // ForceSendFields is a list of field names (e.g. "StringValue") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "StringValue") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *ChunkData) MarshalJSON() ([]byte, error) { + type NoMethod ChunkData + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// CitationMetadata: A collection of source attributions for a piece of +// content. +type CitationMetadata struct { + // CitationSources: Citations to sources for a specific response. + CitationSources []*CitationSource `json:"citationSources,omitempty"` + // ForceSendFields is a list of field names (e.g. "CitationSources") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "CitationSources") to include in + // API requests with the JSON null value. By default, fields with empty values + // are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *CitationMetadata) MarshalJSON() ([]byte, error) { + type NoMethod CitationMetadata + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// CitationSource: A citation to a source for a portion of a specific response. +type CitationSource struct { + // EndIndex: Optional. End of the attributed segment, exclusive. + EndIndex int64 `json:"endIndex,omitempty"` + // License: Optional. License for the GitHub project that is attributed as a + // source for segment. License info is required for code citations. + License string `json:"license,omitempty"` + // StartIndex: Optional. Start of segment of the response that is attributed to + // this source. Index indicates the start of the segment, measured in bytes. + StartIndex int64 `json:"startIndex,omitempty"` + // Uri: Optional. URI that is attributed as a source for a portion of the text. + Uri string `json:"uri,omitempty"` + // ForceSendFields is a list of field names (e.g. "EndIndex") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "EndIndex") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *CitationSource) MarshalJSON() ([]byte, error) { + type NoMethod CitationSource + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// Condition: Filter condition applicable to a single key. +type Condition struct { + // NumericValue: The numeric value to filter the metadata on. + NumericValue float64 `json:"numericValue,omitempty"` + // Operation: Required. Operator applied to the given key-value pair to trigger + // the condition. + // + // Possible values: + // "OPERATOR_UNSPECIFIED" - The default value. This value is unused. + // "LESS" - Supported by numeric. + // "LESS_EQUAL" - Supported by numeric. + // "EQUAL" - Supported by numeric & string. + // "GREATER_EQUAL" - Supported by numeric. + // "GREATER" - Supported by numeric. + // "NOT_EQUAL" - Supported by numeric & string. + // "INCLUDES" - Supported by string only when `CustomMetadata` value type for + // the given key has a `string_list_value`. + // "EXCLUDES" - Supported by string only when `CustomMetadata` value type for + // the given key has a `string_list_value`. + Operation string `json:"operation,omitempty"` + // StringValue: The string value to filter the metadata on. + StringValue string `json:"stringValue,omitempty"` + // ForceSendFields is a list of field names (e.g. "NumericValue") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "NumericValue") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *Condition) MarshalJSON() ([]byte, error) { + type NoMethod Condition + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +func (s *Condition) UnmarshalJSON(data []byte) error { + type NoMethod Condition + var s1 struct { + NumericValue gensupport.JSONFloat64 `json:"numericValue"` + *NoMethod + } + s1.NoMethod = (*NoMethod)(s) + if err := json.Unmarshal(data, &s1); err != nil { + return err + } + s.NumericValue = float64(s1.NumericValue) + return nil +} + +// Content: The base structured datatype containing multi-part content of a +// message. A `Content` includes a `role` field designating the producer of the +// `Content` and a `parts` field containing multi-part data that contains the +// content of the message turn. +type Content struct { + // Parts: Ordered `Parts` that constitute a single message. Parts may have + // different MIME types. + Parts []*Part `json:"parts,omitempty"` + // Role: Optional. The producer of the content. Must be either 'user' or + // 'model'. Useful to set for multi-turn conversations, otherwise can be left + // blank or unset. + Role string `json:"role,omitempty"` + // ForceSendFields is a list of field names (e.g. "Parts") to unconditionally + // include in API requests. By default, fields with empty or default values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Parts") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *Content) MarshalJSON() ([]byte, error) { + type NoMethod Content + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// ContentEmbedding: A list of floats representing an embedding. +type ContentEmbedding struct { + // Values: The embedding values. + Values []float64 `json:"values,omitempty"` + // ForceSendFields is a list of field names (e.g. "Values") to unconditionally + // include in API requests. By default, fields with empty or default values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Values") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *ContentEmbedding) MarshalJSON() ([]byte, error) { + type NoMethod ContentEmbedding + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +func (s *ContentEmbedding) UnmarshalJSON(data []byte) error { + type NoMethod ContentEmbedding + var s1 struct { + Values []gensupport.JSONFloat64 `json:"values"` + *NoMethod + } + s1.NoMethod = (*NoMethod)(s) + if err := json.Unmarshal(data, &s1); err != nil { + return err + } + s.Values = make([]float64, len(s1.Values)) + for i := range s1.Values { + s.Values[i] = float64(s1.Values[i]) + } + return nil +} + +// ContentFilter: Content filtering metadata associated with processing a +// single request. ContentFilter contains a reason and an optional supporting +// string. The reason may be unspecified. +type ContentFilter struct { + // Message: A string that describes the filtering behavior in more detail. + Message string `json:"message,omitempty"` + // Reason: The reason content was blocked during request processing. + // + // Possible values: + // "BLOCKED_REASON_UNSPECIFIED" - A blocked reason was not specified. + // "SAFETY" - Content was blocked by safety settings. + // "OTHER" - Content was blocked, but the reason is uncategorized. + Reason string `json:"reason,omitempty"` + // ForceSendFields is a list of field names (e.g. "Message") to unconditionally + // include in API requests. By default, fields with empty or default values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Message") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *ContentFilter) MarshalJSON() ([]byte, error) { + type NoMethod ContentFilter + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// Corpus: A `Corpus` is a collection of `Document`s. A project can create up +// to 5 corpora. +type Corpus struct { + // CreateTime: Output only. The Timestamp of when the `Corpus` was created. + CreateTime string `json:"createTime,omitempty"` + // DisplayName: Optional. The human-readable display name for the `Corpus`. The + // display name must be no more than 512 characters in length, including + // spaces. Example: "Docs on Semantic Retriever" + DisplayName string `json:"displayName,omitempty"` + // Name: Immutable. Identifier. The `Corpus` resource name. The ID (name + // excluding the "corpora/" prefix) can contain up to 40 characters that are + // lowercase alphanumeric or dashes (-). The ID cannot start or end with a + // dash. If the name is empty on create, a unique name will be derived from + // `display_name` along with a 12 character random suffix. Example: + // `corpora/my-awesome-corpora-123a456b789c` + Name string `json:"name,omitempty"` + // UpdateTime: Output only. The Timestamp of when the `Corpus` was last + // updated. + UpdateTime string `json:"updateTime,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the server. + googleapi.ServerResponse `json:"-"` + // ForceSendFields is a list of field names (e.g. "CreateTime") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "CreateTime") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *Corpus) MarshalJSON() ([]byte, error) { + type NoMethod Corpus + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// CountMessageTokensRequest: Counts the number of tokens in the `prompt` sent +// to a model. Models may tokenize text differently, so each model may return a +// different `token_count`. +type CountMessageTokensRequest struct { + // Prompt: Required. The prompt, whose token count is to be returned. + Prompt *MessagePrompt `json:"prompt,omitempty"` + // ForceSendFields is a list of field names (e.g. "Prompt") to unconditionally + // include in API requests. By default, fields with empty or default values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Prompt") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *CountMessageTokensRequest) MarshalJSON() ([]byte, error) { + type NoMethod CountMessageTokensRequest + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// CountMessageTokensResponse: A response from `CountMessageTokens`. It returns +// the model's `token_count` for the `prompt`. +type CountMessageTokensResponse struct { + // TokenCount: The number of tokens that the `model` tokenizes the `prompt` + // into. Always non-negative. + TokenCount int64 `json:"tokenCount,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the server. + googleapi.ServerResponse `json:"-"` + // ForceSendFields is a list of field names (e.g. "TokenCount") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "TokenCount") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *CountMessageTokensResponse) MarshalJSON() ([]byte, error) { + type NoMethod CountMessageTokensResponse + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// CountTextTokensRequest: Counts the number of tokens in the `prompt` sent to +// a model. Models may tokenize text differently, so each model may return a +// different `token_count`. +type CountTextTokensRequest struct { + // Prompt: Required. The free-form input text given to the model as a prompt. + Prompt *TextPrompt `json:"prompt,omitempty"` + // ForceSendFields is a list of field names (e.g. "Prompt") to unconditionally + // include in API requests. By default, fields with empty or default values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Prompt") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *CountTextTokensRequest) MarshalJSON() ([]byte, error) { + type NoMethod CountTextTokensRequest + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// CountTextTokensResponse: A response from `CountTextTokens`. It returns the +// model's `token_count` for the `prompt`. +type CountTextTokensResponse struct { + // TokenCount: The number of tokens that the `model` tokenizes the `prompt` + // into. Always non-negative. + TokenCount int64 `json:"tokenCount,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the server. + googleapi.ServerResponse `json:"-"` + // ForceSendFields is a list of field names (e.g. "TokenCount") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "TokenCount") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *CountTextTokensResponse) MarshalJSON() ([]byte, error) { + type NoMethod CountTextTokensResponse + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// CountTokensRequest: Counts the number of tokens in the `prompt` sent to a +// model. Models may tokenize text differently, so each model may return a +// different `token_count`. +type CountTokensRequest struct { + // Contents: Optional. The input given to the model as a prompt. This field is + // ignored when `generate_content_request` is set. + Contents []*Content `json:"contents,omitempty"` + // GenerateContentRequest: Optional. The overall input given to the model. + // CountTokens will count prompt, function calling, etc. + GenerateContentRequest *GenerateContentRequest `json:"generateContentRequest,omitempty"` + // ForceSendFields is a list of field names (e.g. "Contents") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Contents") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *CountTokensRequest) MarshalJSON() ([]byte, error) { + type NoMethod CountTokensRequest + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// CountTokensResponse: A response from `CountTokens`. It returns the model's +// `token_count` for the `prompt`. +type CountTokensResponse struct { + // TotalTokens: The number of tokens that the `model` tokenizes the `prompt` + // into. Always non-negative. + TotalTokens int64 `json:"totalTokens,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the server. + googleapi.ServerResponse `json:"-"` + // ForceSendFields is a list of field names (e.g. "TotalTokens") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "TotalTokens") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *CountTokensResponse) MarshalJSON() ([]byte, error) { + type NoMethod CountTokensResponse + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// CreateChunkRequest: Request to create a `Chunk`. +type CreateChunkRequest struct { + // Chunk: Required. The `Chunk` to create. + Chunk *Chunk `json:"chunk,omitempty"` + // Parent: Required. The name of the `Document` where this `Chunk` will be + // created. Example: `corpora/my-corpus-123/documents/the-doc-abc` + Parent string `json:"parent,omitempty"` + // ForceSendFields is a list of field names (e.g. "Chunk") to unconditionally + // include in API requests. By default, fields with empty or default values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Chunk") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *CreateChunkRequest) MarshalJSON() ([]byte, error) { + type NoMethod CreateChunkRequest + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// CreateFileRequest: Request for `CreateFile`. +type CreateFileRequest struct { + // File: Optional. Metadata for the file to create. + File *File `json:"file,omitempty"` + // ForceSendFields is a list of field names (e.g. "File") to unconditionally + // include in API requests. By default, fields with empty or default values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "File") to include in API requests + // with the JSON null value. By default, fields with empty values are omitted + // from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *CreateFileRequest) MarshalJSON() ([]byte, error) { + type NoMethod CreateFileRequest + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// CreateFileResponse: Response for `CreateFile`. +type CreateFileResponse struct { + // File: Metadata for the created file. + File *File `json:"file,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the server. + googleapi.ServerResponse `json:"-"` + // ForceSendFields is a list of field names (e.g. "File") to unconditionally + // include in API requests. By default, fields with empty or default values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "File") to include in API requests + // with the JSON null value. By default, fields with empty values are omitted + // from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *CreateFileResponse) MarshalJSON() ([]byte, error) { + type NoMethod CreateFileResponse + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// CustomMetadata: User provided metadata stored as key-value pairs. +type CustomMetadata struct { + // Key: Required. The key of the metadata to store. + Key string `json:"key,omitempty"` + // NumericValue: The numeric value of the metadata to store. + NumericValue float64 `json:"numericValue,omitempty"` + // StringListValue: The StringList value of the metadata to store. + StringListValue *StringList `json:"stringListValue,omitempty"` + // StringValue: The string value of the metadata to store. + StringValue string `json:"stringValue,omitempty"` + // ForceSendFields is a list of field names (e.g. "Key") to unconditionally + // include in API requests. By default, fields with empty or default values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Key") to include in API requests + // with the JSON null value. By default, fields with empty values are omitted + // from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *CustomMetadata) MarshalJSON() ([]byte, error) { + type NoMethod CustomMetadata + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +func (s *CustomMetadata) UnmarshalJSON(data []byte) error { + type NoMethod CustomMetadata + var s1 struct { + NumericValue gensupport.JSONFloat64 `json:"numericValue"` + *NoMethod + } + s1.NoMethod = (*NoMethod)(s) + if err := json.Unmarshal(data, &s1); err != nil { + return err + } + s.NumericValue = float64(s1.NumericValue) + return nil +} + +// Dataset: Dataset for training or validation. +type Dataset struct { + // Examples: Optional. Inline examples. + Examples *TuningExamples `json:"examples,omitempty"` + // ForceSendFields is a list of field names (e.g. "Examples") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Examples") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *Dataset) MarshalJSON() ([]byte, error) { + type NoMethod Dataset + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// DeleteChunkRequest: Request to delete a `Chunk`. +type DeleteChunkRequest struct { + // Name: Required. The resource name of the `Chunk` to delete. Example: + // `corpora/my-corpus-123/documents/the-doc-abc/chunks/some-chunk` + Name string `json:"name,omitempty"` + // ForceSendFields is a list of field names (e.g. "Name") to unconditionally + // include in API requests. By default, fields with empty or default values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Name") to include in API requests + // with the JSON null value. By default, fields with empty values are omitted + // from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *DeleteChunkRequest) MarshalJSON() ([]byte, error) { + type NoMethod DeleteChunkRequest + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// Document: A `Document` is a collection of `Chunk`s. A `Corpus` can have a +// maximum of 10,000 `Document`s. +type Document struct { + // CreateTime: Output only. The Timestamp of when the `Document` was created. + CreateTime string `json:"createTime,omitempty"` + // CustomMetadata: Optional. User provided custom metadata stored as key-value + // pairs used for querying. A `Document` can have a maximum of 20 + // `CustomMetadata`. + CustomMetadata []*CustomMetadata `json:"customMetadata,omitempty"` + // DisplayName: Optional. The human-readable display name for the `Document`. + // The display name must be no more than 512 characters in length, including + // spaces. Example: "Semantic Retriever Documentation" + DisplayName string `json:"displayName,omitempty"` + // Name: Immutable. Identifier. The `Document` resource name. The ID (name + // excluding the "corpora/*/documents/" prefix) can contain up to 40 characters + // that are lowercase alphanumeric or dashes (-). The ID cannot start or end + // with a dash. If the name is empty on create, a unique name will be derived + // from `display_name` along with a 12 character random suffix. Example: + // `corpora/{corpus_id}/documents/my-awesome-doc-123a456b789c` + Name string `json:"name,omitempty"` + // UpdateTime: Output only. The Timestamp of when the `Document` was last + // updated. + UpdateTime string `json:"updateTime,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the server. + googleapi.ServerResponse `json:"-"` + // ForceSendFields is a list of field names (e.g. "CreateTime") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "CreateTime") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *Document) MarshalJSON() ([]byte, error) { + type NoMethod Document + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// EmbedContentRequest: Request containing the `Content` for the model to +// embed. +type EmbedContentRequest struct { + // Content: Required. The content to embed. Only the `parts.text` fields will + // be counted. + Content *Content `json:"content,omitempty"` + // Model: Required. The model's resource name. This serves as an ID for the + // Model to use. This name should match a model name returned by the + // `ListModels` method. Format: `models/{model}` + Model string `json:"model,omitempty"` + // OutputDimensionality: Optional. Optional reduced dimension for the output + // embedding. If set, excessive values in the output embedding are truncated + // from the end. Supported by newer models since 2024, and the earlier model + // (`models/embedding-001`) cannot specify this value. + OutputDimensionality int64 `json:"outputDimensionality,omitempty"` + // TaskType: Optional. Optional task type for which the embeddings will be + // used. Can only be set for `models/embedding-001`. + // + // Possible values: + // "TASK_TYPE_UNSPECIFIED" - Unset value, which will default to one of the + // other enum values. + // "RETRIEVAL_QUERY" - Specifies the given text is a query in a + // search/retrieval setting. + // "RETRIEVAL_DOCUMENT" - Specifies the given text is a document from the + // corpus being searched. + // "SEMANTIC_SIMILARITY" - Specifies the given text will be used for STS. + // "CLASSIFICATION" - Specifies that the given text will be classified. + // "CLUSTERING" - Specifies that the embeddings will be used for clustering. + // "QUESTION_ANSWERING" - Specifies that the given text will be used for + // question answering. + // "FACT_VERIFICATION" - Specifies that the given text will be used for fact + // verification. + TaskType string `json:"taskType,omitempty"` + // Title: Optional. An optional title for the text. Only applicable when + // TaskType is `RETRIEVAL_DOCUMENT`. Note: Specifying a `title` for + // `RETRIEVAL_DOCUMENT` provides better quality embeddings for retrieval. + Title string `json:"title,omitempty"` + // ForceSendFields is a list of field names (e.g. "Content") to unconditionally + // include in API requests. By default, fields with empty or default values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Content") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *EmbedContentRequest) MarshalJSON() ([]byte, error) { + type NoMethod EmbedContentRequest + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// EmbedContentResponse: The response to an `EmbedContentRequest`. +type EmbedContentResponse struct { + // Embedding: Output only. The embedding generated from the input content. + Embedding *ContentEmbedding `json:"embedding,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the server. + googleapi.ServerResponse `json:"-"` + // ForceSendFields is a list of field names (e.g. "Embedding") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Embedding") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *EmbedContentResponse) MarshalJSON() ([]byte, error) { + type NoMethod EmbedContentResponse + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// EmbedTextRequest: Request to get a text embedding from the model. +type EmbedTextRequest struct { + // Model: Required. The model name to use with the format model=models/{model}. + Model string `json:"model,omitempty"` + // Text: Optional. The free-form input text that the model will turn into an + // embedding. + Text string `json:"text,omitempty"` + // ForceSendFields is a list of field names (e.g. "Model") to unconditionally + // include in API requests. By default, fields with empty or default values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Model") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *EmbedTextRequest) MarshalJSON() ([]byte, error) { + type NoMethod EmbedTextRequest + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// EmbedTextResponse: The response to a EmbedTextRequest. +type EmbedTextResponse struct { + // Embedding: Output only. The embedding generated from the input text. + Embedding *Embedding `json:"embedding,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the server. + googleapi.ServerResponse `json:"-"` + // ForceSendFields is a list of field names (e.g. "Embedding") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Embedding") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *EmbedTextResponse) MarshalJSON() ([]byte, error) { + type NoMethod EmbedTextResponse + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// Embedding: A list of floats representing the embedding. +type Embedding struct { + // Value: The embedding values. + Value []float64 `json:"value,omitempty"` + // ForceSendFields is a list of field names (e.g. "Value") to unconditionally + // include in API requests. By default, fields with empty or default values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Value") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *Embedding) MarshalJSON() ([]byte, error) { + type NoMethod Embedding + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +func (s *Embedding) UnmarshalJSON(data []byte) error { + type NoMethod Embedding + var s1 struct { + Value []gensupport.JSONFloat64 `json:"value"` + *NoMethod + } + s1.NoMethod = (*NoMethod)(s) + if err := json.Unmarshal(data, &s1); err != nil { + return err + } + s.Value = make([]float64, len(s1.Value)) + for i := range s1.Value { + s.Value[i] = float64(s1.Value[i]) + } + return nil +} + +// Empty: A generic empty message that you can re-use to avoid defining +// duplicated empty messages in your APIs. A typical example is to use it as +// the request or the response type of an API method. For instance: service Foo +// { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } +type Empty struct { + // ServerResponse contains the HTTP response code and headers from the server. + googleapi.ServerResponse `json:"-"` +} + +// Example: An input/output example used to instruct the Model. It demonstrates +// how the model should respond or format its response. +type Example struct { + // Input: Required. An example of an input `Message` from the user. + Input *Message `json:"input,omitempty"` + // Output: Required. An example of what the model should output given the + // input. + Output *Message `json:"output,omitempty"` + // ForceSendFields is a list of field names (e.g. "Input") to unconditionally + // include in API requests. By default, fields with empty or default values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Input") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *Example) MarshalJSON() ([]byte, error) { + type NoMethod Example + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// File: A file uploaded to the API. +type File struct { + // CreateTime: Output only. The timestamp of when the `File` was created. + CreateTime string `json:"createTime,omitempty"` + // DisplayName: Optional. The human-readable display name for the `File`. The + // display name must be no more than 512 characters in length, including + // spaces. Example: "Welcome Image" + DisplayName string `json:"displayName,omitempty"` + // Error: Output only. Error status if File processing failed. + Error *Status `json:"error,omitempty"` + // ExpirationTime: Output only. The timestamp of when the `File` will be + // deleted. Only set if the `File` is scheduled to expire. + ExpirationTime string `json:"expirationTime,omitempty"` + // MimeType: Output only. MIME type of the file. + MimeType string `json:"mimeType,omitempty"` + // Name: Immutable. Identifier. The `File` resource name. The ID (name + // excluding the "files/" prefix) can contain up to 40 characters that are + // lowercase alphanumeric or dashes (-). The ID cannot start or end with a + // dash. If the name is empty on create, a unique name will be generated. + // Example: `files/123-456` + Name string `json:"name,omitempty"` + // Sha256Hash: Output only. SHA-256 hash of the uploaded bytes. + Sha256Hash string `json:"sha256Hash,omitempty"` + // SizeBytes: Output only. Size of the file in bytes. + SizeBytes int64 `json:"sizeBytes,omitempty,string"` + // State: Output only. Processing state of the File. + // + // Possible values: + // "STATE_UNSPECIFIED" - The default value. This value is used if the state + // is omitted. + // "PROCESSING" - File is being processed and cannot be used for inference + // yet. + // "ACTIVE" - File is processed and available for inference. + // "FAILED" - File failed processing. + State string `json:"state,omitempty"` + // UpdateTime: Output only. The timestamp of when the `File` was last updated. + UpdateTime string `json:"updateTime,omitempty"` + // Uri: Output only. The uri of the `File`. + Uri string `json:"uri,omitempty"` + // VideoMetadata: Output only. Metadata for a video. + VideoMetadata *VideoMetadata `json:"videoMetadata,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the server. + googleapi.ServerResponse `json:"-"` + // ForceSendFields is a list of field names (e.g. "CreateTime") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "CreateTime") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *File) MarshalJSON() ([]byte, error) { + type NoMethod File + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// FileData: URI based data. +type FileData struct { + // FileUri: Required. URI. + FileUri string `json:"fileUri,omitempty"` + // MimeType: Optional. The IANA standard MIME type of the source data. + MimeType string `json:"mimeType,omitempty"` + // ForceSendFields is a list of field names (e.g. "FileUri") to unconditionally + // include in API requests. By default, fields with empty or default values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "FileUri") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *FileData) MarshalJSON() ([]byte, error) { + type NoMethod FileData + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// FunctionCall: A predicted `FunctionCall` returned from the model that +// contains a string representing the `FunctionDeclaration.name` with the +// arguments and their values. +type FunctionCall struct { + // Args: Optional. The function parameters and values in JSON object format. + Args googleapi.RawMessage `json:"args,omitempty"` + // Name: Required. The name of the function to call. Must be a-z, A-Z, 0-9, or + // contain underscores and dashes, with a maximum length of 63. + Name string `json:"name,omitempty"` + // ForceSendFields is a list of field names (e.g. "Args") to unconditionally + // include in API requests. By default, fields with empty or default values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Args") to include in API requests + // with the JSON null value. By default, fields with empty values are omitted + // from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *FunctionCall) MarshalJSON() ([]byte, error) { + type NoMethod FunctionCall + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// FunctionCallingConfig: Configuration for specifying function calling +// behavior. +type FunctionCallingConfig struct { + // AllowedFunctionNames: Optional. A set of function names that, when provided, + // limits the functions the model will call. This should only be set when the + // Mode is ANY. Function names should match [FunctionDeclaration.name]. With + // mode set to ANY, model will predict a function call from the set of function + // names provided. + AllowedFunctionNames []string `json:"allowedFunctionNames,omitempty"` + // Mode: Optional. Specifies the mode in which function calling should execute. + // If unspecified, the default value will be set to AUTO. + // + // Possible values: + // "MODE_UNSPECIFIED" - Unspecified function calling mode. This value should + // not be used. + // "AUTO" - Default model behavior, model decides to predict either a + // function call or a natural language repspose. + // "ANY" - Model is constrained to always predicting a function call only. If + // "allowed_function_names" are set, the predicted function call will be + // limited to any one of "allowed_function_names", else the predicted function + // call will be any one of the provided "function_declarations". + // "NONE" - Model will not predict any function call. Model behavior is same + // as when not passing any function declarations. + Mode string `json:"mode,omitempty"` + // ForceSendFields is a list of field names (e.g. "AllowedFunctionNames") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "AllowedFunctionNames") to include + // in API requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *FunctionCallingConfig) MarshalJSON() ([]byte, error) { + type NoMethod FunctionCallingConfig + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// FunctionDeclaration: Structured representation of a function declaration as +// defined by the OpenAPI 3.03 specification +// (https://spec.openapis.org/oas/v3.0.3). Included in this declaration are the +// function name and parameters. This FunctionDeclaration is a representation +// of a block of code that can be used as a `Tool` by the model and executed by +// the client. +type FunctionDeclaration struct { + // Description: Required. A brief description of the function. + Description string `json:"description,omitempty"` + // Name: Required. The name of the function. Must be a-z, A-Z, 0-9, or contain + // underscores and dashes, with a maximum length of 63. + Name string `json:"name,omitempty"` + // Parameters: Optional. Describes the parameters to this function. Reflects + // the Open API 3.03 Parameter Object string Key: the name of the parameter. + // Parameter names are case sensitive. Schema Value: the Schema defining the + // type used for the parameter. + Parameters *Schema `json:"parameters,omitempty"` + // ForceSendFields is a list of field names (e.g. "Description") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Description") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *FunctionDeclaration) MarshalJSON() ([]byte, error) { + type NoMethod FunctionDeclaration + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// FunctionResponse: The result output from a `FunctionCall` that contains a +// string representing the `FunctionDeclaration.name` and a structured JSON +// object containing any output from the function is used as context to the +// model. This should contain the result of a`FunctionCall` made based on model +// prediction. +type FunctionResponse struct { + // Name: Required. The name of the function to call. Must be a-z, A-Z, 0-9, or + // contain underscores and dashes, with a maximum length of 63. + Name string `json:"name,omitempty"` + // Response: Required. The function response in JSON object format. + Response googleapi.RawMessage `json:"response,omitempty"` + // ForceSendFields is a list of field names (e.g. "Name") to unconditionally + // include in API requests. By default, fields with empty or default values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Name") to include in API requests + // with the JSON null value. By default, fields with empty values are omitted + // from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *FunctionResponse) MarshalJSON() ([]byte, error) { + type NoMethod FunctionResponse + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// GenerateAnswerRequest: Request to generate a grounded answer from the model. +type GenerateAnswerRequest struct { + // AnswerStyle: Required. Style in which answers should be returned. + // + // Possible values: + // "ANSWER_STYLE_UNSPECIFIED" - Unspecified answer style. + // "ABSTRACTIVE" - Succint but abstract style. + // "EXTRACTIVE" - Very brief and extractive style. + // "VERBOSE" - Verbose style including extra details. The response may be + // formatted as a sentence, paragraph, multiple paragraphs, or bullet points, + // etc. + AnswerStyle string `json:"answerStyle,omitempty"` + // Contents: Required. The content of the current conversation with the model. + // For single-turn queries, this is a single question to answer. For multi-turn + // queries, this is a repeated field that contains conversation history and the + // last `Content` in the list containing the question. Note: GenerateAnswer + // currently only supports queries in English. + Contents []*Content `json:"contents,omitempty"` + // InlinePassages: Passages provided inline with the request. + InlinePassages *GroundingPassages `json:"inlinePassages,omitempty"` + // SafetySettings: Optional. A list of unique `SafetySetting` instances for + // blocking unsafe content. This will be enforced on the + // `GenerateAnswerRequest.contents` and `GenerateAnswerResponse.candidate`. + // There should not be more than one setting for each `SafetyCategory` type. + // The API will block any contents and responses that fail to meet the + // thresholds set by these settings. This list overrides the default settings + // for each `SafetyCategory` specified in the safety_settings. If there is no + // `SafetySetting` for a given `SafetyCategory` provided in the list, the API + // will use the default safety setting for that category. Harm categories + // HARM_CATEGORY_HATE_SPEECH, HARM_CATEGORY_SEXUALLY_EXPLICIT, + // HARM_CATEGORY_DANGEROUS_CONTENT, HARM_CATEGORY_HARASSMENT are supported. + SafetySettings []*SafetySetting `json:"safetySettings,omitempty"` + // SemanticRetriever: Content retrieved from resources created via the Semantic + // Retriever API. + SemanticRetriever *SemanticRetrieverConfig `json:"semanticRetriever,omitempty"` + // Temperature: Optional. Controls the randomness of the output. Values can + // range from [0.0,1.0], inclusive. A value closer to 1.0 will produce + // responses that are more varied and creative, while a value closer to 0.0 + // will typically result in more straightforward responses from the model. A + // low temperature (~0.2) is usually recommended for + // Attributed-Question-Answering use cases. + Temperature float64 `json:"temperature,omitempty"` + // ForceSendFields is a list of field names (e.g. "AnswerStyle") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "AnswerStyle") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *GenerateAnswerRequest) MarshalJSON() ([]byte, error) { + type NoMethod GenerateAnswerRequest + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +func (s *GenerateAnswerRequest) UnmarshalJSON(data []byte) error { + type NoMethod GenerateAnswerRequest + var s1 struct { + Temperature gensupport.JSONFloat64 `json:"temperature"` + *NoMethod + } + s1.NoMethod = (*NoMethod)(s) + if err := json.Unmarshal(data, &s1); err != nil { + return err + } + s.Temperature = float64(s1.Temperature) + return nil +} + +// GenerateAnswerResponse: Response from the model for a grounded answer. +type GenerateAnswerResponse struct { + // Answer: Candidate answer from the model. Note: The model *always* attempts + // to provide a grounded answer, even when the answer is unlikely to be + // answerable from the given passages. In that case, a low-quality or + // ungrounded answer may be provided, along with a low + // `answerable_probability`. + Answer *Candidate `json:"answer,omitempty"` + // AnswerableProbability: Output only. The model's estimate of the probability + // that its answer is correct and grounded in the input passages. A low + // answerable_probability indicates that the answer might not be grounded in + // the sources. When `answerable_probability` is low, some clients may wish to: + // * Display a message to the effect of "We couldn’t answer that question" to + // the user. * Fall back to a general-purpose LLM that answers the question + // from world knowledge. The threshold and nature of such fallbacks will depend + // on individual clients’ use cases. 0.5 is a good starting threshold. + AnswerableProbability float64 `json:"answerableProbability,omitempty"` + // InputFeedback: Output only. Feedback related to the input data used to + // answer the question, as opposed to model-generated response to the question. + // "Input data" can be one or more of the following: - Question specified by + // the last entry in `GenerateAnswerRequest.content` - Conversation history + // specified by the other entries in `GenerateAnswerRequest.content` - + // Grounding sources (`GenerateAnswerRequest.semantic_retriever` or + // `GenerateAnswerRequest.inline_passages`) + InputFeedback *InputFeedback `json:"inputFeedback,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the server. + googleapi.ServerResponse `json:"-"` + // ForceSendFields is a list of field names (e.g. "Answer") to unconditionally + // include in API requests. By default, fields with empty or default values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Answer") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *GenerateAnswerResponse) MarshalJSON() ([]byte, error) { + type NoMethod GenerateAnswerResponse + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +func (s *GenerateAnswerResponse) UnmarshalJSON(data []byte) error { + type NoMethod GenerateAnswerResponse + var s1 struct { + AnswerableProbability gensupport.JSONFloat64 `json:"answerableProbability"` + *NoMethod + } + s1.NoMethod = (*NoMethod)(s) + if err := json.Unmarshal(data, &s1); err != nil { + return err + } + s.AnswerableProbability = float64(s1.AnswerableProbability) + return nil +} + +// GenerateContentRequest: Request to generate a completion from the model. +type GenerateContentRequest struct { + // Contents: Required. The content of the current conversation with the model. + // For single-turn queries, this is a single instance. For multi-turn queries, + // this is a repeated field that contains conversation history + latest + // request. + Contents []*Content `json:"contents,omitempty"` + // GenerationConfig: Optional. Configuration options for model generation and + // outputs. + GenerationConfig *GenerationConfig `json:"generationConfig,omitempty"` + // Model: Required. The name of the `Model` to use for generating the + // completion. Format: `name=models/{model}`. + Model string `json:"model,omitempty"` + // SafetySettings: Optional. A list of unique `SafetySetting` instances for + // blocking unsafe content. This will be enforced on the + // `GenerateContentRequest.contents` and `GenerateContentResponse.candidates`. + // There should not be more than one setting for each `SafetyCategory` type. + // The API will block any contents and responses that fail to meet the + // thresholds set by these settings. This list overrides the default settings + // for each `SafetyCategory` specified in the safety_settings. If there is no + // `SafetySetting` for a given `SafetyCategory` provided in the list, the API + // will use the default safety setting for that category. Harm categories + // HARM_CATEGORY_HATE_SPEECH, HARM_CATEGORY_SEXUALLY_EXPLICIT, + // HARM_CATEGORY_DANGEROUS_CONTENT, HARM_CATEGORY_HARASSMENT are supported. + SafetySettings []*SafetySetting `json:"safetySettings,omitempty"` + // SystemInstruction: Optional. Developer set system instruction. Currently, + // text only. + SystemInstruction *Content `json:"systemInstruction,omitempty"` + // ToolConfig: Optional. Tool configuration for any `Tool` specified in the + // request. + ToolConfig *ToolConfig `json:"toolConfig,omitempty"` + // Tools: Optional. A list of `Tools` the model may use to generate the next + // response. A `Tool` is a piece of code that enables the system to interact + // with external systems to perform an action, or set of actions, outside of + // knowledge and scope of the model. The only supported tool is currently + // `Function`. + Tools []*Tool `json:"tools,omitempty"` + // ForceSendFields is a list of field names (e.g. "Contents") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Contents") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *GenerateContentRequest) MarshalJSON() ([]byte, error) { + type NoMethod GenerateContentRequest + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// GenerateContentResponse: Response from the model supporting multiple +// candidates. Note on safety ratings and content filtering. They are reported +// for both prompt in `GenerateContentResponse.prompt_feedback` and for each +// candidate in `finish_reason` and in `safety_ratings`. The API contract is +// that: - either all requested candidates are returned or no candidates at all +// - no candidates are returned only if there was something wrong with the +// prompt (see `prompt_feedback`) - feedback on each candidate is reported on +// `finish_reason` and `safety_ratings`. +type GenerateContentResponse struct { + // Candidates: Candidate responses from the model. + Candidates []*Candidate `json:"candidates,omitempty"` + // PromptFeedback: Returns the prompt's feedback related to the content + // filters. + PromptFeedback *PromptFeedback `json:"promptFeedback,omitempty"` + // UsageMetadata: Output only. Metadata on the generation requests' token + // usage. + UsageMetadata *UsageMetadata `json:"usageMetadata,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the server. + googleapi.ServerResponse `json:"-"` + // ForceSendFields is a list of field names (e.g. "Candidates") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Candidates") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *GenerateContentResponse) MarshalJSON() ([]byte, error) { + type NoMethod GenerateContentResponse + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// GenerateMessageRequest: Request to generate a message response from the +// model. +type GenerateMessageRequest struct { + // CandidateCount: Optional. The number of generated response messages to + // return. This value must be between `[1, 8]`, inclusive. If unset, this will + // default to `1`. + CandidateCount int64 `json:"candidateCount,omitempty"` + // Prompt: Required. The structured textual input given to the model as a + // prompt. Given a prompt, the model will return what it predicts is the next + // message in the discussion. + Prompt *MessagePrompt `json:"prompt,omitempty"` + // Temperature: Optional. Controls the randomness of the output. Values can + // range over `[0.0,1.0]`, inclusive. A value closer to `1.0` will produce + // responses that are more varied, while a value closer to `0.0` will typically + // result in less surprising responses from the model. + Temperature float64 `json:"temperature,omitempty"` + // TopK: Optional. The maximum number of tokens to consider when sampling. The + // model uses combined Top-k and nucleus sampling. Top-k sampling considers the + // set of `top_k` most probable tokens. + TopK int64 `json:"topK,omitempty"` + // TopP: Optional. The maximum cumulative probability of tokens to consider + // when sampling. The model uses combined Top-k and nucleus sampling. Nucleus + // sampling considers the smallest set of tokens whose probability sum is at + // least `top_p`. + TopP float64 `json:"topP,omitempty"` + // ForceSendFields is a list of field names (e.g. "CandidateCount") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "CandidateCount") to include in + // API requests with the JSON null value. By default, fields with empty values + // are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *GenerateMessageRequest) MarshalJSON() ([]byte, error) { + type NoMethod GenerateMessageRequest + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +func (s *GenerateMessageRequest) UnmarshalJSON(data []byte) error { + type NoMethod GenerateMessageRequest + var s1 struct { + Temperature gensupport.JSONFloat64 `json:"temperature"` + TopP gensupport.JSONFloat64 `json:"topP"` + *NoMethod + } + s1.NoMethod = (*NoMethod)(s) + if err := json.Unmarshal(data, &s1); err != nil { + return err + } + s.Temperature = float64(s1.Temperature) + s.TopP = float64(s1.TopP) + return nil +} + +// GenerateMessageResponse: The response from the model. This includes +// candidate messages and conversation history in the form of +// chronologically-ordered messages. +type GenerateMessageResponse struct { + // Candidates: Candidate response messages from the model. + Candidates []*Message `json:"candidates,omitempty"` + // Filters: A set of content filtering metadata for the prompt and response + // text. This indicates which `SafetyCategory`(s) blocked a candidate from this + // response, the lowest `HarmProbability` that triggered a block, and the + // HarmThreshold setting for that category. + Filters []*ContentFilter `json:"filters,omitempty"` + // Messages: The conversation history used by the model. + Messages []*Message `json:"messages,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the server. + googleapi.ServerResponse `json:"-"` + // ForceSendFields is a list of field names (e.g. "Candidates") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Candidates") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *GenerateMessageResponse) MarshalJSON() ([]byte, error) { + type NoMethod GenerateMessageResponse + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// GenerateTextRequest: Request to generate a text completion response from the +// model. +type GenerateTextRequest struct { + // CandidateCount: Optional. Number of generated responses to return. This + // value must be between [1, 8], inclusive. If unset, this will default to 1. + CandidateCount int64 `json:"candidateCount,omitempty"` + // MaxOutputTokens: Optional. The maximum number of tokens to include in a + // candidate. If unset, this will default to output_token_limit specified in + // the `Model` specification. + MaxOutputTokens int64 `json:"maxOutputTokens,omitempty"` + // Prompt: Required. The free-form input text given to the model as a prompt. + // Given a prompt, the model will generate a TextCompletion response it + // predicts as the completion of the input text. + Prompt *TextPrompt `json:"prompt,omitempty"` + // SafetySettings: Optional. A list of unique `SafetySetting` instances for + // blocking unsafe content. that will be enforced on the + // `GenerateTextRequest.prompt` and `GenerateTextResponse.candidates`. There + // should not be more than one setting for each `SafetyCategory` type. The API + // will block any prompts and responses that fail to meet the thresholds set by + // these settings. This list overrides the default settings for each + // `SafetyCategory` specified in the safety_settings. If there is no + // `SafetySetting` for a given `SafetyCategory` provided in the list, the API + // will use the default safety setting for that category. Harm categories + // HARM_CATEGORY_DEROGATORY, HARM_CATEGORY_TOXICITY, HARM_CATEGORY_VIOLENCE, + // HARM_CATEGORY_SEXUAL, HARM_CATEGORY_MEDICAL, HARM_CATEGORY_DANGEROUS are + // supported in text service. + SafetySettings []*SafetySetting `json:"safetySettings,omitempty"` + // StopSequences: The set of character sequences (up to 5) that will stop + // output generation. If specified, the API will stop at the first appearance + // of a stop sequence. The stop sequence will not be included as part of the + // response. + StopSequences []string `json:"stopSequences,omitempty"` + // Temperature: Optional. Controls the randomness of the output. Note: The + // default value varies by model, see the `Model.temperature` attribute of the + // `Model` returned the `getModel` function. Values can range from [0.0,1.0], + // inclusive. A value closer to 1.0 will produce responses that are more varied + // and creative, while a value closer to 0.0 will typically result in more + // straightforward responses from the model. + Temperature float64 `json:"temperature,omitempty"` + // TopK: Optional. The maximum number of tokens to consider when sampling. The + // model uses combined Top-k and nucleus sampling. Top-k sampling considers the + // set of `top_k` most probable tokens. Defaults to 40. Note: The default value + // varies by model, see the `Model.top_k` attribute of the `Model` returned the + // `getModel` function. + TopK int64 `json:"topK,omitempty"` + // TopP: Optional. The maximum cumulative probability of tokens to consider + // when sampling. The model uses combined Top-k and nucleus sampling. Tokens + // are sorted based on their assigned probabilities so that only the most + // likely tokens are considered. Top-k sampling directly limits the maximum + // number of tokens to consider, while Nucleus sampling limits number of tokens + // based on the cumulative probability. Note: The default value varies by + // model, see the `Model.top_p` attribute of the `Model` returned the + // `getModel` function. + TopP float64 `json:"topP,omitempty"` + // ForceSendFields is a list of field names (e.g. "CandidateCount") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "CandidateCount") to include in + // API requests with the JSON null value. By default, fields with empty values + // are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *GenerateTextRequest) MarshalJSON() ([]byte, error) { + type NoMethod GenerateTextRequest + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +func (s *GenerateTextRequest) UnmarshalJSON(data []byte) error { + type NoMethod GenerateTextRequest + var s1 struct { + Temperature gensupport.JSONFloat64 `json:"temperature"` + TopP gensupport.JSONFloat64 `json:"topP"` + *NoMethod + } + s1.NoMethod = (*NoMethod)(s) + if err := json.Unmarshal(data, &s1); err != nil { + return err + } + s.Temperature = float64(s1.Temperature) + s.TopP = float64(s1.TopP) + return nil +} + +// GenerateTextResponse: The response from the model, including candidate +// completions. +type GenerateTextResponse struct { + // Candidates: Candidate responses from the model. + Candidates []*TextCompletion `json:"candidates,omitempty"` + // Filters: A set of content filtering metadata for the prompt and response + // text. This indicates which `SafetyCategory`(s) blocked a candidate from this + // response, the lowest `HarmProbability` that triggered a block, and the + // HarmThreshold setting for that category. This indicates the smallest change + // to the `SafetySettings` that would be necessary to unblock at least 1 + // response. The blocking is configured by the `SafetySettings` in the request + // (or the default `SafetySettings` of the API). + Filters []*ContentFilter `json:"filters,omitempty"` + // SafetyFeedback: Returns any safety feedback related to content filtering. + SafetyFeedback []*SafetyFeedback `json:"safetyFeedback,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the server. + googleapi.ServerResponse `json:"-"` + // ForceSendFields is a list of field names (e.g. "Candidates") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Candidates") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *GenerateTextResponse) MarshalJSON() ([]byte, error) { + type NoMethod GenerateTextResponse + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// GenerationConfig: Configuration options for model generation and outputs. +// Not all parameters may be configurable for every model. +type GenerationConfig struct { + // CandidateCount: Optional. Number of generated responses to return. + // Currently, this value can only be set to 1. If unset, this will default to + // 1. + CandidateCount int64 `json:"candidateCount,omitempty"` + // MaxOutputTokens: Optional. The maximum number of tokens to include in a + // candidate. Note: The default value varies by model, see the + // `Model.output_token_limit` attribute of the `Model` returned from the + // `getModel` function. + MaxOutputTokens int64 `json:"maxOutputTokens,omitempty"` + // ResponseMimeType: Optional. Output response mimetype of the generated + // candidate text. Supported mimetype: `text/plain`: (default) Text output. + // `application/json`: JSON response in the candidates. + ResponseMimeType string `json:"responseMimeType,omitempty"` + // ResponseSchema: Optional. Output response schema of the generated candidate + // text when response mime type can have schema. Schema can be objects, + // primitives or arrays and is a subset of OpenAPI schema + // (https://spec.openapis.org/oas/v3.0.3#schema). If set, a compatible + // response_mime_type must also be set. Compatible mimetypes: + // `application/json`: Schema for JSON response. + ResponseSchema *Schema `json:"responseSchema,omitempty"` + // StopSequences: Optional. The set of character sequences (up to 5) that will + // stop output generation. If specified, the API will stop at the first + // appearance of a stop sequence. The stop sequence will not be included as + // part of the response. + StopSequences []string `json:"stopSequences,omitempty"` + // Temperature: Optional. Controls the randomness of the output. Note: The + // default value varies by model, see the `Model.temperature` attribute of the + // `Model` returned from the `getModel` function. Values can range from [0.0, + // 2.0]. + Temperature float64 `json:"temperature,omitempty"` + // TopK: Optional. The maximum number of tokens to consider when sampling. + // Models use nucleus sampling or combined Top-k and nucleus sampling. Top-k + // sampling considers the set of `top_k` most probable tokens. Models running + // with nucleus sampling don't allow top_k setting. Note: The default value + // varies by model, see the `Model.top_k` attribute of the `Model` returned + // from the `getModel` function. Empty `top_k` field in `Model` indicates the + // model doesn't apply top-k sampling and doesn't allow setting `top_k` on + // requests. + TopK int64 `json:"topK,omitempty"` + // TopP: Optional. The maximum cumulative probability of tokens to consider + // when sampling. The model uses combined Top-k and nucleus sampling. Tokens + // are sorted based on their assigned probabilities so that only the most + // likely tokens are considered. Top-k sampling directly limits the maximum + // number of tokens to consider, while Nucleus sampling limits number of tokens + // based on the cumulative probability. Note: The default value varies by + // model, see the `Model.top_p` attribute of the `Model` returned from the + // `getModel` function. + TopP float64 `json:"topP,omitempty"` + // ForceSendFields is a list of field names (e.g. "CandidateCount") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "CandidateCount") to include in + // API requests with the JSON null value. By default, fields with empty values + // are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *GenerationConfig) MarshalJSON() ([]byte, error) { + type NoMethod GenerationConfig + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +func (s *GenerationConfig) UnmarshalJSON(data []byte) error { + type NoMethod GenerationConfig + var s1 struct { + Temperature gensupport.JSONFloat64 `json:"temperature"` + TopP gensupport.JSONFloat64 `json:"topP"` + *NoMethod + } + s1.NoMethod = (*NoMethod)(s) + if err := json.Unmarshal(data, &s1); err != nil { + return err + } + s.Temperature = float64(s1.Temperature) + s.TopP = float64(s1.TopP) + return nil +} + +// GroundingAttribution: Attribution for a source that contributed to an +// answer. +type GroundingAttribution struct { + // Content: Grounding source content that makes up this attribution. + Content *Content `json:"content,omitempty"` + // SourceId: Output only. Identifier for the source contributing to this + // attribution. + SourceId *AttributionSourceId `json:"sourceId,omitempty"` + // ForceSendFields is a list of field names (e.g. "Content") to unconditionally + // include in API requests. By default, fields with empty or default values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Content") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *GroundingAttribution) MarshalJSON() ([]byte, error) { + type NoMethod GroundingAttribution + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// GroundingPassage: Passage included inline with a grounding configuration. +type GroundingPassage struct { + // Content: Content of the passage. + Content *Content `json:"content,omitempty"` + // Id: Identifier for the passage for attributing this passage in grounded + // answers. + Id string `json:"id,omitempty"` + // ForceSendFields is a list of field names (e.g. "Content") to unconditionally + // include in API requests. By default, fields with empty or default values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Content") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *GroundingPassage) MarshalJSON() ([]byte, error) { + type NoMethod GroundingPassage + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// GroundingPassageId: Identifier for a part within a `GroundingPassage`. +type GroundingPassageId struct { + // PartIndex: Output only. Index of the part within the + // `GenerateAnswerRequest`'s `GroundingPassage.content`. + PartIndex int64 `json:"partIndex,omitempty"` + // PassageId: Output only. ID of the passage matching the + // `GenerateAnswerRequest`'s `GroundingPassage.id`. + PassageId string `json:"passageId,omitempty"` + // ForceSendFields is a list of field names (e.g. "PartIndex") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "PartIndex") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *GroundingPassageId) MarshalJSON() ([]byte, error) { + type NoMethod GroundingPassageId + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// GroundingPassages: A repeated list of passages. +type GroundingPassages struct { + // Passages: List of passages. + Passages []*GroundingPassage `json:"passages,omitempty"` + // ForceSendFields is a list of field names (e.g. "Passages") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Passages") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *GroundingPassages) MarshalJSON() ([]byte, error) { + type NoMethod GroundingPassages + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// Hyperparameters: Hyperparameters controlling the tuning process. Read more +// at https://ai.google.dev/docs/model_tuning_guidance +type Hyperparameters struct { + // BatchSize: Immutable. The batch size hyperparameter for tuning. If not set, + // a default of 4 or 16 will be used based on the number of training examples. + BatchSize int64 `json:"batchSize,omitempty"` + // EpochCount: Immutable. The number of training epochs. An epoch is one pass + // through the training data. If not set, a default of 5 will be used. + EpochCount int64 `json:"epochCount,omitempty"` + // LearningRate: Optional. Immutable. The learning rate hyperparameter for + // tuning. If not set, a default of 0.001 or 0.0002 will be calculated based on + // the number of training examples. + LearningRate float64 `json:"learningRate,omitempty"` + // LearningRateMultiplier: Optional. Immutable. The learning rate multiplier is + // used to calculate a final learning_rate based on the default (recommended) + // value. Actual learning rate := learning_rate_multiplier * default learning + // rate Default learning rate is dependent on base model and dataset size. If + // not set, a default of 1.0 will be used. + LearningRateMultiplier float64 `json:"learningRateMultiplier,omitempty"` + // ForceSendFields is a list of field names (e.g. "BatchSize") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "BatchSize") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *Hyperparameters) MarshalJSON() ([]byte, error) { + type NoMethod Hyperparameters + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +func (s *Hyperparameters) UnmarshalJSON(data []byte) error { + type NoMethod Hyperparameters + var s1 struct { + LearningRate gensupport.JSONFloat64 `json:"learningRate"` + LearningRateMultiplier gensupport.JSONFloat64 `json:"learningRateMultiplier"` + *NoMethod + } + s1.NoMethod = (*NoMethod)(s) + if err := json.Unmarshal(data, &s1); err != nil { + return err + } + s.LearningRate = float64(s1.LearningRate) + s.LearningRateMultiplier = float64(s1.LearningRateMultiplier) + return nil +} + +// InputFeedback: Feedback related to the input data used to answer the +// question, as opposed to model-generated response to the question. +type InputFeedback struct { + // BlockReason: Optional. If set, the input was blocked and no candidates are + // returned. Rephrase your input. + // + // Possible values: + // "BLOCK_REASON_UNSPECIFIED" - Default value. This value is unused. + // "SAFETY" - Input was blocked due to safety reasons. You can inspect + // `safety_ratings` to understand which safety category blocked it. + // "OTHER" - Input was blocked due to other reasons. + BlockReason string `json:"blockReason,omitempty"` + // SafetyRatings: Ratings for safety of the input. There is at most one rating + // per category. + SafetyRatings []*SafetyRating `json:"safetyRatings,omitempty"` + // ForceSendFields is a list of field names (e.g. "BlockReason") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "BlockReason") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *InputFeedback) MarshalJSON() ([]byte, error) { + type NoMethod InputFeedback + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// ListChunksResponse: Response from `ListChunks` containing a paginated list +// of `Chunk`s. The `Chunk`s are sorted by ascending `chunk.create_time`. +type ListChunksResponse struct { + // Chunks: The returned `Chunk`s. + Chunks []*Chunk `json:"chunks,omitempty"` + // NextPageToken: A token, which can be sent as `page_token` to retrieve the + // next page. If this field is omitted, there are no more pages. + NextPageToken string `json:"nextPageToken,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the server. + googleapi.ServerResponse `json:"-"` + // ForceSendFields is a list of field names (e.g. "Chunks") to unconditionally + // include in API requests. By default, fields with empty or default values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Chunks") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *ListChunksResponse) MarshalJSON() ([]byte, error) { + type NoMethod ListChunksResponse + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// ListCorporaResponse: Response from `ListCorpora` containing a paginated list +// of `Corpora`. The results are sorted by ascending `corpus.create_time`. +type ListCorporaResponse struct { + // Corpora: The returned corpora. + Corpora []*Corpus `json:"corpora,omitempty"` + // NextPageToken: A token, which can be sent as `page_token` to retrieve the + // next page. If this field is omitted, there are no more pages. + NextPageToken string `json:"nextPageToken,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the server. + googleapi.ServerResponse `json:"-"` + // ForceSendFields is a list of field names (e.g. "Corpora") to unconditionally + // include in API requests. By default, fields with empty or default values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Corpora") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *ListCorporaResponse) MarshalJSON() ([]byte, error) { + type NoMethod ListCorporaResponse + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// ListDocumentsResponse: Response from `ListDocuments` containing a paginated +// list of `Document`s. The `Document`s are sorted by ascending +// `document.create_time`. +type ListDocumentsResponse struct { + // Documents: The returned `Document`s. + Documents []*Document `json:"documents,omitempty"` + // NextPageToken: A token, which can be sent as `page_token` to retrieve the + // next page. If this field is omitted, there are no more pages. + NextPageToken string `json:"nextPageToken,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the server. + googleapi.ServerResponse `json:"-"` + // ForceSendFields is a list of field names (e.g. "Documents") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Documents") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *ListDocumentsResponse) MarshalJSON() ([]byte, error) { + type NoMethod ListDocumentsResponse + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// ListFilesResponse: Response for `ListFiles`. +type ListFilesResponse struct { + // Files: The list of `File`s. + Files []*File `json:"files,omitempty"` + // NextPageToken: A token that can be sent as a `page_token` into a subsequent + // `ListFiles` call. + NextPageToken string `json:"nextPageToken,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the server. + googleapi.ServerResponse `json:"-"` + // ForceSendFields is a list of field names (e.g. "Files") to unconditionally + // include in API requests. By default, fields with empty or default values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Files") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *ListFilesResponse) MarshalJSON() ([]byte, error) { + type NoMethod ListFilesResponse + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// ListModelsResponse: Response from `ListModel` containing a paginated list of +// Models. +type ListModelsResponse struct { + // Models: The returned Models. + Models []*Model `json:"models,omitempty"` + // NextPageToken: A token, which can be sent as `page_token` to retrieve the + // next page. If this field is omitted, there are no more pages. + NextPageToken string `json:"nextPageToken,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the server. + googleapi.ServerResponse `json:"-"` + // ForceSendFields is a list of field names (e.g. "Models") to unconditionally + // include in API requests. By default, fields with empty or default values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Models") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *ListModelsResponse) MarshalJSON() ([]byte, error) { + type NoMethod ListModelsResponse + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// ListPermissionsResponse: Response from `ListPermissions` containing a +// paginated list of permissions. +type ListPermissionsResponse struct { + // NextPageToken: A token, which can be sent as `page_token` to retrieve the + // next page. If this field is omitted, there are no more pages. + NextPageToken string `json:"nextPageToken,omitempty"` + // Permissions: Returned permissions. + Permissions []*Permission `json:"permissions,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the server. + googleapi.ServerResponse `json:"-"` + // ForceSendFields is a list of field names (e.g. "NextPageToken") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "NextPageToken") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *ListPermissionsResponse) MarshalJSON() ([]byte, error) { + type NoMethod ListPermissionsResponse + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// ListTunedModelsResponse: Response from `ListTunedModels` containing a +// paginated list of Models. +type ListTunedModelsResponse struct { + // NextPageToken: A token, which can be sent as `page_token` to retrieve the + // next page. If this field is omitted, there are no more pages. + NextPageToken string `json:"nextPageToken,omitempty"` + // TunedModels: The returned Models. + TunedModels []*TunedModel `json:"tunedModels,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the server. + googleapi.ServerResponse `json:"-"` + // ForceSendFields is a list of field names (e.g. "NextPageToken") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "NextPageToken") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *ListTunedModelsResponse) MarshalJSON() ([]byte, error) { + type NoMethod ListTunedModelsResponse + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// Message: The base unit of structured text. A `Message` includes an `author` +// and the `content` of the `Message`. The `author` is used to tag messages +// when they are fed to the model as text. +type Message struct { + // Author: Optional. The author of this Message. This serves as a key for + // tagging the content of this Message when it is fed to the model as text. The + // author can be any alphanumeric string. + Author string `json:"author,omitempty"` + // CitationMetadata: Output only. Citation information for model-generated + // `content` in this `Message`. If this `Message` was generated as output from + // the model, this field may be populated with attribution information for any + // text included in the `content`. This field is used only on output. + CitationMetadata *CitationMetadata `json:"citationMetadata,omitempty"` + // Content: Required. The text content of the structured `Message`. + Content string `json:"content,omitempty"` + // ForceSendFields is a list of field names (e.g. "Author") to unconditionally + // include in API requests. By default, fields with empty or default values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Author") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *Message) MarshalJSON() ([]byte, error) { + type NoMethod Message + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// MessagePrompt: All of the structured input text passed to the model as a +// prompt. A `MessagePrompt` contains a structured set of fields that provide +// context for the conversation, examples of user input/model output message +// pairs that prime the model to respond in different ways, and the +// conversation history or list of messages representing the alternating turns +// of the conversation between the user and the model. +type MessagePrompt struct { + // Context: Optional. Text that should be provided to the model first to ground + // the response. If not empty, this `context` will be given to the model first + // before the `examples` and `messages`. When using a `context` be sure to + // provide it with every request to maintain continuity. This field can be a + // description of your prompt to the model to help provide context and guide + // the responses. Examples: "Translate the phrase from English to French." or + // "Given a statement, classify the sentiment as happy, sad or neutral." + // Anything included in this field will take precedence over message history if + // the total input size exceeds the model's `input_token_limit` and the input + // request is truncated. + Context string `json:"context,omitempty"` + // Examples: Optional. Examples of what the model should generate. This + // includes both user input and the response that the model should emulate. + // These `examples` are treated identically to conversation messages except + // that they take precedence over the history in `messages`: If the total input + // size exceeds the model's `input_token_limit` the input will be truncated. + // Items will be dropped from `messages` before `examples`. + Examples []*Example `json:"examples,omitempty"` + // Messages: Required. A snapshot of the recent conversation history sorted + // chronologically. Turns alternate between two authors. If the total input + // size exceeds the model's `input_token_limit` the input will be truncated: + // The oldest items will be dropped from `messages`. + Messages []*Message `json:"messages,omitempty"` + // ForceSendFields is a list of field names (e.g. "Context") to unconditionally + // include in API requests. By default, fields with empty or default values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Context") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *MessagePrompt) MarshalJSON() ([]byte, error) { + type NoMethod MessagePrompt + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// MetadataFilter: User provided filter to limit retrieval based on `Chunk` or +// `Document` level metadata values. Example (genre = drama OR genre = action): +// key = "document.custom_metadata.genre" conditions = [{string_value = +// "drama", operation = EQUAL}, {string_value = "action", operation = EQUAL}] +type MetadataFilter struct { + // Conditions: Required. The `Condition`s for the given key that will trigger + // this filter. Multiple `Condition`s are joined by logical ORs. + Conditions []*Condition `json:"conditions,omitempty"` + // Key: Required. The key of the metadata to filter on. + Key string `json:"key,omitempty"` + // ForceSendFields is a list of field names (e.g. "Conditions") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Conditions") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *MetadataFilter) MarshalJSON() ([]byte, error) { + type NoMethod MetadataFilter + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// Model: Information about a Generative Language Model. +type Model struct { + // BaseModelId: Required. The name of the base model, pass this to the + // generation request. Examples: * `chat-bison` + BaseModelId string `json:"baseModelId,omitempty"` + // Description: A short description of the model. + Description string `json:"description,omitempty"` + // DisplayName: The human-readable name of the model. E.g. "Chat Bison". The + // name can be up to 128 characters long and can consist of any UTF-8 + // characters. + DisplayName string `json:"displayName,omitempty"` + // InputTokenLimit: Maximum number of input tokens allowed for this model. + InputTokenLimit int64 `json:"inputTokenLimit,omitempty"` + // Name: Required. The resource name of the `Model`. Format: `models/{model}` + // with a `{model}` naming convention of: * "{base_model_id}-{version}" + // Examples: * `models/chat-bison-001` + Name string `json:"name,omitempty"` + // OutputTokenLimit: Maximum number of output tokens available for this model. + OutputTokenLimit int64 `json:"outputTokenLimit,omitempty"` + // SupportedGenerationMethods: The model's supported generation methods. The + // method names are defined as Pascal case strings, such as `generateMessage` + // which correspond to API methods. + SupportedGenerationMethods []string `json:"supportedGenerationMethods,omitempty"` + // Temperature: Controls the randomness of the output. Values can range over + // `[0.0,1.0]`, inclusive. A value closer to `1.0` will produce responses that + // are more varied, while a value closer to `0.0` will typically result in less + // surprising responses from the model. This value specifies default to be used + // by the backend while making the call to the model. + Temperature float64 `json:"temperature,omitempty"` + // TopK: For Top-k sampling. Top-k sampling considers the set of `top_k` most + // probable tokens. This value specifies default to be used by the backend + // while making the call to the model. If empty, indicates the model doesn't + // use top-k sampling, and `top_k` isn't allowed as a generation parameter. + TopK int64 `json:"topK,omitempty"` + // TopP: For Nucleus sampling. Nucleus sampling considers the smallest set of + // tokens whose probability sum is at least `top_p`. This value specifies + // default to be used by the backend while making the call to the model. + TopP float64 `json:"topP,omitempty"` + // Version: Required. The version number of the model. This represents the + // major version + Version string `json:"version,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the server. + googleapi.ServerResponse `json:"-"` + // ForceSendFields is a list of field names (e.g. "BaseModelId") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "BaseModelId") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *Model) MarshalJSON() ([]byte, error) { + type NoMethod Model + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +func (s *Model) UnmarshalJSON(data []byte) error { + type NoMethod Model + var s1 struct { + Temperature gensupport.JSONFloat64 `json:"temperature"` + TopP gensupport.JSONFloat64 `json:"topP"` + *NoMethod + } + s1.NoMethod = (*NoMethod)(s) + if err := json.Unmarshal(data, &s1); err != nil { + return err + } + s.Temperature = float64(s1.Temperature) + s.TopP = float64(s1.TopP) + return nil +} + +// Operation: This resource represents a long-running operation that is the +// result of a network API call. +type Operation struct { + // Done: If the value is `false`, it means the operation is still in progress. + // If `true`, the operation is completed, and either `error` or `response` is + // available. + Done bool `json:"done,omitempty"` + // Error: The error result of the operation in case of failure or cancellation. + Error *Status `json:"error,omitempty"` + // Metadata: Service-specific metadata associated with the operation. It + // typically contains progress information and common metadata such as create + // time. Some services might not provide such metadata. Any method that returns + // a long-running operation should document the metadata type, if any. + Metadata googleapi.RawMessage `json:"metadata,omitempty"` + // Name: The server-assigned name, which is only unique within the same service + // that originally returns it. If you use the default HTTP mapping, the `name` + // should be a resource name ending with `operations/{unique_id}`. + Name string `json:"name,omitempty"` + // Response: The normal, successful response of the operation. If the original + // method returns no data on success, such as `Delete`, the response is + // `google.protobuf.Empty`. If the original method is standard + // `Get`/`Create`/`Update`, the response should be the resource. For other + // methods, the response should have the type `XxxResponse`, where `Xxx` is the + // original method name. For example, if the original method name is + // `TakeSnapshot()`, the inferred response type is `TakeSnapshotResponse`. + Response googleapi.RawMessage `json:"response,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the server. + googleapi.ServerResponse `json:"-"` + // ForceSendFields is a list of field names (e.g. "Done") to unconditionally + // include in API requests. By default, fields with empty or default values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Done") to include in API requests + // with the JSON null value. By default, fields with empty values are omitted + // from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *Operation) MarshalJSON() ([]byte, error) { + type NoMethod Operation + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// Part: A datatype containing media that is part of a multi-part `Content` +// message. A `Part` consists of data which has an associated datatype. A +// `Part` can only contain one of the accepted types in `Part.data`. A `Part` +// must have a fixed IANA MIME type identifying the type and subtype of the +// media if the `inline_data` field is filled with raw bytes. +type Part struct { + // FileData: URI based data. + FileData *FileData `json:"fileData,omitempty"` + // FunctionCall: A predicted `FunctionCall` returned from the model that + // contains a string representing the `FunctionDeclaration.name` with the + // arguments and their values. + FunctionCall *FunctionCall `json:"functionCall,omitempty"` + // FunctionResponse: The result output of a `FunctionCall` that contains a + // string representing the `FunctionDeclaration.name` and a structured JSON + // object containing any output from the function is used as context to the + // model. + FunctionResponse *FunctionResponse `json:"functionResponse,omitempty"` + // InlineData: Inline media bytes. + InlineData *Blob `json:"inlineData,omitempty"` + // Text: Inline text. + Text string `json:"text,omitempty"` + // ForceSendFields is a list of field names (e.g. "FileData") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "FileData") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *Part) MarshalJSON() ([]byte, error) { + type NoMethod Part + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// Permission: Permission resource grants user, group or the rest of the world +// access to the PaLM API resource (e.g. a tuned model, corpus). A role is a +// collection of permitted operations that allows users to perform specific +// actions on PaLM API resources. To make them available to users, groups, or +// service accounts, you assign roles. When you assign a role, you grant +// permissions that the role contains. There are three concentric roles. Each +// role is a superset of the previous role's permitted operations: - reader can +// use the resource (e.g. tuned model, corpus) for inference - writer has +// reader's permissions and additionally can edit and share - owner has +// writer's permissions and additionally can delete +type Permission struct { + // EmailAddress: Optional. Immutable. The email address of the user of group + // which this permission refers. Field is not set when permission's grantee + // type is EVERYONE. + EmailAddress string `json:"emailAddress,omitempty"` + // GranteeType: Optional. Immutable. The type of the grantee. + // + // Possible values: + // "GRANTEE_TYPE_UNSPECIFIED" - The default value. This value is unused. + // "USER" - Represents a user. When set, you must provide email_address for + // the user. + // "GROUP" - Represents a group. When set, you must provide email_address for + // the group. + // "EVERYONE" - Represents access to everyone. No extra information is + // required. + GranteeType string `json:"granteeType,omitempty"` + // Name: Output only. Identifier. The permission name. A unique name will be + // generated on create. Examples: + // tunedModels/{tuned_model}/permissions/{permission} + // corpora/{corpus}/permissions/{permission} Output only. + Name string `json:"name,omitempty"` + // Role: Required. The role granted by this permission. + // + // Possible values: + // "ROLE_UNSPECIFIED" - The default value. This value is unused. + // "OWNER" - Owner can use, update, share and delete the resource. + // "WRITER" - Writer can use, update and share the resource. + // "READER" - Reader can use the resource. + Role string `json:"role,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the server. + googleapi.ServerResponse `json:"-"` + // ForceSendFields is a list of field names (e.g. "EmailAddress") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "EmailAddress") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *Permission) MarshalJSON() ([]byte, error) { + type NoMethod Permission + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// PromptFeedback: A set of the feedback metadata the prompt specified in +// `GenerateContentRequest.content`. +type PromptFeedback struct { + // BlockReason: Optional. If set, the prompt was blocked and no candidates are + // returned. Rephrase your prompt. + // + // Possible values: + // "BLOCK_REASON_UNSPECIFIED" - Default value. This value is unused. + // "SAFETY" - Prompt was blocked due to safety reasons. You can inspect + // `safety_ratings` to understand which safety category blocked it. + // "OTHER" - Prompt was blocked due to unknown reaasons. + BlockReason string `json:"blockReason,omitempty"` + // SafetyRatings: Ratings for safety of the prompt. There is at most one rating + // per category. + SafetyRatings []*SafetyRating `json:"safetyRatings,omitempty"` + // ForceSendFields is a list of field names (e.g. "BlockReason") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "BlockReason") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *PromptFeedback) MarshalJSON() ([]byte, error) { + type NoMethod PromptFeedback + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// QueryCorpusRequest: Request for querying a `Corpus`. +type QueryCorpusRequest struct { + // MetadataFilters: Optional. Filter for `Chunk` and `Document` metadata. Each + // `MetadataFilter` object should correspond to a unique key. Multiple + // `MetadataFilter` objects are joined by logical "AND"s. Example query at + // document level: (year >= 2020 OR year < 2010) AND (genre = drama OR genre = + // action) `MetadataFilter` object list: metadata_filters = [ {key = + // "document.custom_metadata.year" conditions = [{int_value = 2020, operation = + // GREATER_EQUAL}, {int_value = 2010, operation = LESS}]}, {key = + // "document.custom_metadata.year" conditions = [{int_value = 2020, operation = + // GREATER_EQUAL}, {int_value = 2010, operation = LESS}]}, {key = + // "document.custom_metadata.genre" conditions = [{string_value = "drama", + // operation = EQUAL}, {string_value = "action", operation = EQUAL}]}] Example + // query at chunk level for a numeric range of values: (year > 2015 AND year <= + // 2020) `MetadataFilter` object list: metadata_filters = [ {key = + // "chunk.custom_metadata.year" conditions = [{int_value = 2015, operation = + // GREATER}]}, {key = "chunk.custom_metadata.year" conditions = [{int_value = + // 2020, operation = LESS_EQUAL}]}] Note: "AND"s for the same key are only + // supported for numeric values. String values only support "OR"s for the same + // key. + MetadataFilters []*MetadataFilter `json:"metadataFilters,omitempty"` + // Query: Required. Query string to perform semantic search. + Query string `json:"query,omitempty"` + // ResultsCount: Optional. The maximum number of `Chunk`s to return. The + // service may return fewer `Chunk`s. If unspecified, at most 10 `Chunk`s will + // be returned. The maximum specified result count is 100. + ResultsCount int64 `json:"resultsCount,omitempty"` + // ForceSendFields is a list of field names (e.g. "MetadataFilters") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "MetadataFilters") to include in + // API requests with the JSON null value. By default, fields with empty values + // are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *QueryCorpusRequest) MarshalJSON() ([]byte, error) { + type NoMethod QueryCorpusRequest + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// QueryCorpusResponse: Response from `QueryCorpus` containing a list of +// relevant chunks. +type QueryCorpusResponse struct { + // RelevantChunks: The relevant chunks. + RelevantChunks []*RelevantChunk `json:"relevantChunks,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the server. + googleapi.ServerResponse `json:"-"` + // ForceSendFields is a list of field names (e.g. "RelevantChunks") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "RelevantChunks") to include in + // API requests with the JSON null value. By default, fields with empty values + // are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *QueryCorpusResponse) MarshalJSON() ([]byte, error) { + type NoMethod QueryCorpusResponse + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// QueryDocumentRequest: Request for querying a `Document`. +type QueryDocumentRequest struct { + // MetadataFilters: Optional. Filter for `Chunk` metadata. Each + // `MetadataFilter` object should correspond to a unique key. Multiple + // `MetadataFilter` objects are joined by logical "AND"s. Note: + // `Document`-level filtering is not supported for this request because a + // `Document` name is already specified. Example query: (year >= 2020 OR year < + // 2010) AND (genre = drama OR genre = action) `MetadataFilter` object list: + // metadata_filters = [ {key = "chunk.custom_metadata.year" conditions = + // [{int_value = 2020, operation = GREATER_EQUAL}, {int_value = 2010, operation + // = LESS}}, {key = "chunk.custom_metadata.genre" conditions = [{string_value = + // "drama", operation = EQUAL}, {string_value = "action", operation = EQUAL}}] + // Example query for a numeric range of values: (year > 2015 AND year <= 2020) + // `MetadataFilter` object list: metadata_filters = [ {key = + // "chunk.custom_metadata.year" conditions = [{int_value = 2015, operation = + // GREATER}]}, {key = "chunk.custom_metadata.year" conditions = [{int_value = + // 2020, operation = LESS_EQUAL}]}] Note: "AND"s for the same key are only + // supported for numeric values. String values only support "OR"s for the same + // key. + MetadataFilters []*MetadataFilter `json:"metadataFilters,omitempty"` + // Query: Required. Query string to perform semantic search. + Query string `json:"query,omitempty"` + // ResultsCount: Optional. The maximum number of `Chunk`s to return. The + // service may return fewer `Chunk`s. If unspecified, at most 10 `Chunk`s will + // be returned. The maximum specified result count is 100. + ResultsCount int64 `json:"resultsCount,omitempty"` + // ForceSendFields is a list of field names (e.g. "MetadataFilters") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "MetadataFilters") to include in + // API requests with the JSON null value. By default, fields with empty values + // are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *QueryDocumentRequest) MarshalJSON() ([]byte, error) { + type NoMethod QueryDocumentRequest + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// QueryDocumentResponse: Response from `QueryDocument` containing a list of +// relevant chunks. +type QueryDocumentResponse struct { + // RelevantChunks: The returned relevant chunks. + RelevantChunks []*RelevantChunk `json:"relevantChunks,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the server. + googleapi.ServerResponse `json:"-"` + // ForceSendFields is a list of field names (e.g. "RelevantChunks") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "RelevantChunks") to include in + // API requests with the JSON null value. By default, fields with empty values + // are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *QueryDocumentResponse) MarshalJSON() ([]byte, error) { + type NoMethod QueryDocumentResponse + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// RelevantChunk: The information for a chunk relevant to a query. +type RelevantChunk struct { + // Chunk: `Chunk` associated with the query. + Chunk *Chunk `json:"chunk,omitempty"` + // ChunkRelevanceScore: `Chunk` relevance to the query. + ChunkRelevanceScore float64 `json:"chunkRelevanceScore,omitempty"` + // ForceSendFields is a list of field names (e.g. "Chunk") to unconditionally + // include in API requests. By default, fields with empty or default values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Chunk") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *RelevantChunk) MarshalJSON() ([]byte, error) { + type NoMethod RelevantChunk + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +func (s *RelevantChunk) UnmarshalJSON(data []byte) error { + type NoMethod RelevantChunk + var s1 struct { + ChunkRelevanceScore gensupport.JSONFloat64 `json:"chunkRelevanceScore"` + *NoMethod + } + s1.NoMethod = (*NoMethod)(s) + if err := json.Unmarshal(data, &s1); err != nil { + return err + } + s.ChunkRelevanceScore = float64(s1.ChunkRelevanceScore) + return nil +} + +// SafetyFeedback: Safety feedback for an entire request. This field is +// populated if content in the input and/or response is blocked due to safety +// settings. SafetyFeedback may not exist for every HarmCategory. Each +// SafetyFeedback will return the safety settings used by the request as well +// as the lowest HarmProbability that should be allowed in order to return a +// result. +type SafetyFeedback struct { + // Rating: Safety rating evaluated from content. + Rating *SafetyRating `json:"rating,omitempty"` + // Setting: Safety settings applied to the request. + Setting *SafetySetting `json:"setting,omitempty"` + // ForceSendFields is a list of field names (e.g. "Rating") to unconditionally + // include in API requests. By default, fields with empty or default values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Rating") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *SafetyFeedback) MarshalJSON() ([]byte, error) { + type NoMethod SafetyFeedback + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// SafetyRating: Safety rating for a piece of content. The safety rating +// contains the category of harm and the harm probability level in that +// category for a piece of content. Content is classified for safety across a +// number of harm categories and the probability of the harm classification is +// included here. +type SafetyRating struct { + // Blocked: Was this content blocked because of this rating? + Blocked bool `json:"blocked,omitempty"` + // Category: Required. The category for this rating. + // + // Possible values: + // "HARM_CATEGORY_UNSPECIFIED" - Category is unspecified. + // "HARM_CATEGORY_DEROGATORY" - Negative or harmful comments targeting + // identity and/or protected attribute. + // "HARM_CATEGORY_TOXICITY" - Content that is rude, disrespectful, or + // profane. + // "HARM_CATEGORY_VIOLENCE" - Describes scenarios depicting violence against + // an individual or group, or general descriptions of gore. + // "HARM_CATEGORY_SEXUAL" - Contains references to sexual acts or other lewd + // content. + // "HARM_CATEGORY_MEDICAL" - Promotes unchecked medical advice. + // "HARM_CATEGORY_DANGEROUS" - Dangerous content that promotes, facilitates, + // or encourages harmful acts. + // "HARM_CATEGORY_HARASSMENT" - Harasment content. + // "HARM_CATEGORY_HATE_SPEECH" - Hate speech and content. + // "HARM_CATEGORY_SEXUALLY_EXPLICIT" - Sexually explicit content. + // "HARM_CATEGORY_DANGEROUS_CONTENT" - Dangerous content. + Category string `json:"category,omitempty"` + // Probability: Required. The probability of harm for this content. + // + // Possible values: + // "HARM_PROBABILITY_UNSPECIFIED" - Probability is unspecified. + // "NEGLIGIBLE" - Content has a negligible chance of being unsafe. + // "LOW" - Content has a low chance of being unsafe. + // "MEDIUM" - Content has a medium chance of being unsafe. + // "HIGH" - Content has a high chance of being unsafe. + Probability string `json:"probability,omitempty"` + // ForceSendFields is a list of field names (e.g. "Blocked") to unconditionally + // include in API requests. By default, fields with empty or default values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Blocked") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *SafetyRating) MarshalJSON() ([]byte, error) { + type NoMethod SafetyRating + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// SafetySetting: Safety setting, affecting the safety-blocking behavior. +// Passing a safety setting for a category changes the allowed probability that +// content is blocked. +type SafetySetting struct { + // Category: Required. The category for this setting. + // + // Possible values: + // "HARM_CATEGORY_UNSPECIFIED" - Category is unspecified. + // "HARM_CATEGORY_DEROGATORY" - Negative or harmful comments targeting + // identity and/or protected attribute. + // "HARM_CATEGORY_TOXICITY" - Content that is rude, disrespectful, or + // profane. + // "HARM_CATEGORY_VIOLENCE" - Describes scenarios depicting violence against + // an individual or group, or general descriptions of gore. + // "HARM_CATEGORY_SEXUAL" - Contains references to sexual acts or other lewd + // content. + // "HARM_CATEGORY_MEDICAL" - Promotes unchecked medical advice. + // "HARM_CATEGORY_DANGEROUS" - Dangerous content that promotes, facilitates, + // or encourages harmful acts. + // "HARM_CATEGORY_HARASSMENT" - Harasment content. + // "HARM_CATEGORY_HATE_SPEECH" - Hate speech and content. + // "HARM_CATEGORY_SEXUALLY_EXPLICIT" - Sexually explicit content. + // "HARM_CATEGORY_DANGEROUS_CONTENT" - Dangerous content. + Category string `json:"category,omitempty"` + // Threshold: Required. Controls the probability threshold at which harm is + // blocked. + // + // Possible values: + // "HARM_BLOCK_THRESHOLD_UNSPECIFIED" - Threshold is unspecified. + // "BLOCK_LOW_AND_ABOVE" - Content with NEGLIGIBLE will be allowed. + // "BLOCK_MEDIUM_AND_ABOVE" - Content with NEGLIGIBLE and LOW will be + // allowed. + // "BLOCK_ONLY_HIGH" - Content with NEGLIGIBLE, LOW, and MEDIUM will be + // allowed. + // "BLOCK_NONE" - All content will be allowed. + Threshold string `json:"threshold,omitempty"` + // ForceSendFields is a list of field names (e.g. "Category") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Category") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *SafetySetting) MarshalJSON() ([]byte, error) { + type NoMethod SafetySetting + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// Schema: The `Schema` object allows the definition of input and output data +// types. These types can be objects, but also primitives and arrays. +// Represents a select subset of an OpenAPI 3.0 schema object +// (https://spec.openapis.org/oas/v3.0.3#schema). +type Schema struct { + // Description: Optional. A brief description of the parameter. This could + // contain examples of use. Parameter description may be formatted as Markdown. + Description string `json:"description,omitempty"` + // Enum: Optional. Possible values of the element of Type.STRING with enum + // format. For example we can define an Enum Direction as : {type:STRING, + // format:enum, enum:["EAST", NORTH", "SOUTH", "WEST"]} + Enum []string `json:"enum,omitempty"` + // Format: Optional. The format of the data. This is used only for primitive + // datatypes. Supported formats: for NUMBER type: float, double for INTEGER + // type: int32, int64 + Format string `json:"format,omitempty"` + // Items: Optional. Schema of the elements of Type.ARRAY. + Items *Schema `json:"items,omitempty"` + // Nullable: Optional. Indicates if the value may be null. + Nullable bool `json:"nullable,omitempty"` + // Properties: Optional. Properties of Type.OBJECT. + Properties map[string]Schema `json:"properties,omitempty"` + // Required: Optional. Required properties of Type.OBJECT. + Required []string `json:"required,omitempty"` + // Type: Required. Data type. + // + // Possible values: + // "TYPE_UNSPECIFIED" - Not specified, should not be used. + // "STRING" - String type. + // "NUMBER" - Number type. + // "INTEGER" - Integer type. + // "BOOLEAN" - Boolean type. + // "ARRAY" - Array type. + // "OBJECT" - Object type. + Type string `json:"type,omitempty"` + // ForceSendFields is a list of field names (e.g. "Description") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Description") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *Schema) MarshalJSON() ([]byte, error) { + type NoMethod Schema + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// SemanticRetrieverChunk: Identifier for a `Chunk` retrieved via Semantic +// Retriever specified in the `GenerateAnswerRequest` using +// `SemanticRetrieverConfig`. +type SemanticRetrieverChunk struct { + // Chunk: Output only. Name of the `Chunk` containing the attributed text. + // Example: `corpora/123/documents/abc/chunks/xyz` + Chunk string `json:"chunk,omitempty"` + // Source: Output only. Name of the source matching the request's + // `SemanticRetrieverConfig.source`. Example: `corpora/123` or + // `corpora/123/documents/abc` + Source string `json:"source,omitempty"` + // ForceSendFields is a list of field names (e.g. "Chunk") to unconditionally + // include in API requests. By default, fields with empty or default values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Chunk") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *SemanticRetrieverChunk) MarshalJSON() ([]byte, error) { + type NoMethod SemanticRetrieverChunk + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// SemanticRetrieverConfig: Configuration for retrieving grounding content from +// a `Corpus` or `Document` created using the Semantic Retriever API. +type SemanticRetrieverConfig struct { + // MaxChunksCount: Optional. Maximum number of relevant `Chunk`s to retrieve. + MaxChunksCount int64 `json:"maxChunksCount,omitempty"` + // MetadataFilters: Optional. Filters for selecting `Document`s and/or `Chunk`s + // from the resource. + MetadataFilters []*MetadataFilter `json:"metadataFilters,omitempty"` + // MinimumRelevanceScore: Optional. Minimum relevance score for retrieved + // relevant `Chunk`s. + MinimumRelevanceScore float64 `json:"minimumRelevanceScore,omitempty"` + // Query: Required. Query to use for similarity matching `Chunk`s in the given + // resource. + Query *Content `json:"query,omitempty"` + // Source: Required. Name of the resource for retrieval, e.g. corpora/123 or + // corpora/123/documents/abc. + Source string `json:"source,omitempty"` + // ForceSendFields is a list of field names (e.g. "MaxChunksCount") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "MaxChunksCount") to include in + // API requests with the JSON null value. By default, fields with empty values + // are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *SemanticRetrieverConfig) MarshalJSON() ([]byte, error) { + type NoMethod SemanticRetrieverConfig + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +func (s *SemanticRetrieverConfig) UnmarshalJSON(data []byte) error { + type NoMethod SemanticRetrieverConfig + var s1 struct { + MinimumRelevanceScore gensupport.JSONFloat64 `json:"minimumRelevanceScore"` + *NoMethod + } + s1.NoMethod = (*NoMethod)(s) + if err := json.Unmarshal(data, &s1); err != nil { + return err + } + s.MinimumRelevanceScore = float64(s1.MinimumRelevanceScore) + return nil +} + +// Status: The `Status` type defines a logical error model that is suitable for +// different programming environments, including REST APIs and RPC APIs. It is +// used by gRPC (https://github.com/grpc). Each `Status` message contains three +// pieces of data: error code, error message, and error details. You can find +// out more about this error model and how to work with it in the API Design +// Guide (https://cloud.google.com/apis/design/errors). +type Status struct { + // Code: The status code, which should be an enum value of google.rpc.Code. + Code int64 `json:"code,omitempty"` + // Details: A list of messages that carry the error details. There is a common + // set of message types for APIs to use. + Details []googleapi.RawMessage `json:"details,omitempty"` + // Message: A developer-facing error message, which should be in English. Any + // user-facing error message should be localized and sent in the + // google.rpc.Status.details field, or localized by the client. + Message string `json:"message,omitempty"` + // ForceSendFields is a list of field names (e.g. "Code") to unconditionally + // include in API requests. By default, fields with empty or default values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Code") to include in API requests + // with the JSON null value. By default, fields with empty values are omitted + // from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *Status) MarshalJSON() ([]byte, error) { + type NoMethod Status + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// StringList: User provided string values assigned to a single metadata key. +type StringList struct { + // Values: The string values of the metadata to store. + Values []string `json:"values,omitempty"` + // ForceSendFields is a list of field names (e.g. "Values") to unconditionally + // include in API requests. By default, fields with empty or default values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Values") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *StringList) MarshalJSON() ([]byte, error) { + type NoMethod StringList + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// TextCompletion: Output text returned from a model. +type TextCompletion struct { + // CitationMetadata: Output only. Citation information for model-generated + // `output` in this `TextCompletion`. This field may be populated with + // attribution information for any text included in the `output`. + CitationMetadata *CitationMetadata `json:"citationMetadata,omitempty"` + // Output: Output only. The generated text returned from the model. + Output string `json:"output,omitempty"` + // SafetyRatings: Ratings for the safety of a response. There is at most one + // rating per category. + SafetyRatings []*SafetyRating `json:"safetyRatings,omitempty"` + // ForceSendFields is a list of field names (e.g. "CitationMetadata") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "CitationMetadata") to include in + // API requests with the JSON null value. By default, fields with empty values + // are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *TextCompletion) MarshalJSON() ([]byte, error) { + type NoMethod TextCompletion + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// TextPrompt: Text given to the model as a prompt. The Model will use this +// TextPrompt to Generate a text completion. +type TextPrompt struct { + // Text: Required. The prompt text. + Text string `json:"text,omitempty"` + // ForceSendFields is a list of field names (e.g. "Text") to unconditionally + // include in API requests. By default, fields with empty or default values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Text") to include in API requests + // with the JSON null value. By default, fields with empty values are omitted + // from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *TextPrompt) MarshalJSON() ([]byte, error) { + type NoMethod TextPrompt + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// Tool: Tool details that the model may use to generate response. A `Tool` is +// a piece of code that enables the system to interact with external systems to +// perform an action, or set of actions, outside of knowledge and scope of the +// model. +type Tool struct { + // FunctionDeclarations: Optional. A list of `FunctionDeclarations` available + // to the model that can be used for function calling. The model or system does + // not execute the function. Instead the defined function may be returned as a + // FunctionCall with arguments to the client side for execution. The model may + // decide to call a subset of these functions by populating FunctionCall in the + // response. The next conversation turn may contain a FunctionResponse with the + // [content.role] "function" generation context for the next model turn. + FunctionDeclarations []*FunctionDeclaration `json:"functionDeclarations,omitempty"` + // ForceSendFields is a list of field names (e.g. "FunctionDeclarations") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "FunctionDeclarations") to include + // in API requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *Tool) MarshalJSON() ([]byte, error) { + type NoMethod Tool + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// ToolConfig: The Tool configuration containing parameters for specifying +// `Tool` use in the request. +type ToolConfig struct { + // FunctionCallingConfig: Optional. Function calling config. + FunctionCallingConfig *FunctionCallingConfig `json:"functionCallingConfig,omitempty"` + // ForceSendFields is a list of field names (e.g. "FunctionCallingConfig") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "FunctionCallingConfig") to + // include in API requests with the JSON null value. By default, fields with + // empty values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *ToolConfig) MarshalJSON() ([]byte, error) { + type NoMethod ToolConfig + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// TransferOwnershipRequest: Request to transfer the ownership of the tuned +// model. +type TransferOwnershipRequest struct { + // EmailAddress: Required. The email address of the user to whom the tuned + // model is being transferred to. + EmailAddress string `json:"emailAddress,omitempty"` + // ForceSendFields is a list of field names (e.g. "EmailAddress") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "EmailAddress") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *TransferOwnershipRequest) MarshalJSON() ([]byte, error) { + type NoMethod TransferOwnershipRequest + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// TransferOwnershipResponse: Response from `TransferOwnership`. +type TransferOwnershipResponse struct { + // ServerResponse contains the HTTP response code and headers from the server. + googleapi.ServerResponse `json:"-"` +} + +// TunedModel: A fine-tuned model created using ModelService.CreateTunedModel. +type TunedModel struct { + // BaseModel: Immutable. The name of the `Model` to tune. Example: + // `models/text-bison-001` + BaseModel string `json:"baseModel,omitempty"` + // CreateTime: Output only. The timestamp when this model was created. + CreateTime string `json:"createTime,omitempty"` + // Description: Optional. A short description of this model. + Description string `json:"description,omitempty"` + // DisplayName: Optional. The name to display for this model in user + // interfaces. The display name must be up to 40 characters including spaces. + DisplayName string `json:"displayName,omitempty"` + // Name: Output only. The tuned model name. A unique name will be generated on + // create. Example: `tunedModels/az2mb0bpw6i` If display_name is set on create, + // the id portion of the name will be set by concatenating the words of the + // display_name with hyphens and adding a random portion for uniqueness. + // Example: display_name = "Sentence Translator" name = + // "tunedModels/sentence-translator-u3b7m" + Name string `json:"name,omitempty"` + // State: Output only. The state of the tuned model. + // + // Possible values: + // "STATE_UNSPECIFIED" - The default value. This value is unused. + // "CREATING" - The model is being created. + // "ACTIVE" - The model is ready to be used. + // "FAILED" - The model failed to be created. + State string `json:"state,omitempty"` + // Temperature: Optional. Controls the randomness of the output. Values can + // range over `[0.0,1.0]`, inclusive. A value closer to `1.0` will produce + // responses that are more varied, while a value closer to `0.0` will typically + // result in less surprising responses from the model. This value specifies + // default to be the one used by the base model while creating the model. + Temperature float64 `json:"temperature,omitempty"` + // TopK: Optional. For Top-k sampling. Top-k sampling considers the set of + // `top_k` most probable tokens. This value specifies default to be used by the + // backend while making the call to the model. This value specifies default to + // be the one used by the base model while creating the model. + TopK int64 `json:"topK,omitempty"` + // TopP: Optional. For Nucleus sampling. Nucleus sampling considers the + // smallest set of tokens whose probability sum is at least `top_p`. This value + // specifies default to be the one used by the base model while creating the + // model. + TopP float64 `json:"topP,omitempty"` + // TunedModelSource: Optional. TunedModel to use as the starting point for + // training the new model. + TunedModelSource *TunedModelSource `json:"tunedModelSource,omitempty"` + // TuningTask: Required. The tuning task that creates the tuned model. + TuningTask *TuningTask `json:"tuningTask,omitempty"` + // UpdateTime: Output only. The timestamp when this model was updated. + UpdateTime string `json:"updateTime,omitempty"` + + // ServerResponse contains the HTTP response code and headers from the server. + googleapi.ServerResponse `json:"-"` + // ForceSendFields is a list of field names (e.g. "BaseModel") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "BaseModel") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *TunedModel) MarshalJSON() ([]byte, error) { + type NoMethod TunedModel + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +func (s *TunedModel) UnmarshalJSON(data []byte) error { + type NoMethod TunedModel + var s1 struct { + Temperature gensupport.JSONFloat64 `json:"temperature"` + TopP gensupport.JSONFloat64 `json:"topP"` + *NoMethod + } + s1.NoMethod = (*NoMethod)(s) + if err := json.Unmarshal(data, &s1); err != nil { + return err + } + s.Temperature = float64(s1.Temperature) + s.TopP = float64(s1.TopP) + return nil +} + +// TunedModelSource: Tuned model as a source for training a new model. +type TunedModelSource struct { + // BaseModel: Output only. The name of the base `Model` this `TunedModel` was + // tuned from. Example: `models/text-bison-001` + BaseModel string `json:"baseModel,omitempty"` + // TunedModel: Immutable. The name of the `TunedModel` to use as the starting + // point for training the new model. Example: `tunedModels/my-tuned-model` + TunedModel string `json:"tunedModel,omitempty"` + // ForceSendFields is a list of field names (e.g. "BaseModel") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "BaseModel") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *TunedModelSource) MarshalJSON() ([]byte, error) { + type NoMethod TunedModelSource + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// TuningExample: A single example for tuning. +type TuningExample struct { + // Output: Required. The expected model output. + Output string `json:"output,omitempty"` + // TextInput: Optional. Text model input. + TextInput string `json:"textInput,omitempty"` + // ForceSendFields is a list of field names (e.g. "Output") to unconditionally + // include in API requests. By default, fields with empty or default values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Output") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *TuningExample) MarshalJSON() ([]byte, error) { + type NoMethod TuningExample + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// TuningExamples: A set of tuning examples. Can be training or validation +// data. +type TuningExamples struct { + // Examples: Required. The examples. Example input can be for text or discuss, + // but all examples in a set must be of the same type. + Examples []*TuningExample `json:"examples,omitempty"` + // ForceSendFields is a list of field names (e.g. "Examples") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Examples") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *TuningExamples) MarshalJSON() ([]byte, error) { + type NoMethod TuningExamples + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// TuningSnapshot: Record for a single tuning step. +type TuningSnapshot struct { + // ComputeTime: Output only. The timestamp when this metric was computed. + ComputeTime string `json:"computeTime,omitempty"` + // Epoch: Output only. The epoch this step was part of. + Epoch int64 `json:"epoch,omitempty"` + // MeanLoss: Output only. The mean loss of the training examples for this step. + MeanLoss float64 `json:"meanLoss,omitempty"` + // Step: Output only. The tuning step. + Step int64 `json:"step,omitempty"` + // ForceSendFields is a list of field names (e.g. "ComputeTime") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "ComputeTime") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *TuningSnapshot) MarshalJSON() ([]byte, error) { + type NoMethod TuningSnapshot + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +func (s *TuningSnapshot) UnmarshalJSON(data []byte) error { + type NoMethod TuningSnapshot + var s1 struct { + MeanLoss gensupport.JSONFloat64 `json:"meanLoss"` + *NoMethod + } + s1.NoMethod = (*NoMethod)(s) + if err := json.Unmarshal(data, &s1); err != nil { + return err + } + s.MeanLoss = float64(s1.MeanLoss) + return nil +} + +// TuningTask: Tuning tasks that create tuned models. +type TuningTask struct { + // CompleteTime: Output only. The timestamp when tuning this model completed. + CompleteTime string `json:"completeTime,omitempty"` + // Hyperparameters: Immutable. Hyperparameters controlling the tuning process. + // If not provided, default values will be used. + Hyperparameters *Hyperparameters `json:"hyperparameters,omitempty"` + // Snapshots: Output only. Metrics collected during tuning. + Snapshots []*TuningSnapshot `json:"snapshots,omitempty"` + // StartTime: Output only. The timestamp when tuning this model started. + StartTime string `json:"startTime,omitempty"` + // TrainingData: Required. Input only. Immutable. The model training data. + TrainingData *Dataset `json:"trainingData,omitempty"` + // ForceSendFields is a list of field names (e.g. "CompleteTime") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "CompleteTime") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *TuningTask) MarshalJSON() ([]byte, error) { + type NoMethod TuningTask + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// UpdateChunkRequest: Request to update a `Chunk`. +type UpdateChunkRequest struct { + // Chunk: Required. The `Chunk` to update. + Chunk *Chunk `json:"chunk,omitempty"` + // UpdateMask: Required. The list of fields to update. Currently, this only + // supports updating `custom_metadata` and `data`. + UpdateMask string `json:"updateMask,omitempty"` + // ForceSendFields is a list of field names (e.g. "Chunk") to unconditionally + // include in API requests. By default, fields with empty or default values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "Chunk") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *UpdateChunkRequest) MarshalJSON() ([]byte, error) { + type NoMethod UpdateChunkRequest + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// UsageMetadata: Metadata on the generation request's token usage. +type UsageMetadata struct { + // CandidatesTokenCount: Total number of tokens across the generated + // candidates. + CandidatesTokenCount int64 `json:"candidatesTokenCount,omitempty"` + // PromptTokenCount: Number of tokens in the prompt. + PromptTokenCount int64 `json:"promptTokenCount,omitempty"` + // TotalTokenCount: Total token count for the generation request (prompt + + // candidates). + TotalTokenCount int64 `json:"totalTokenCount,omitempty"` + // ForceSendFields is a list of field names (e.g. "CandidatesTokenCount") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "CandidatesTokenCount") to include + // in API requests with the JSON null value. By default, fields with empty + // values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *UsageMetadata) MarshalJSON() ([]byte, error) { + type NoMethod UsageMetadata + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +// VideoMetadata: Metadata for a video `File`. +type VideoMetadata struct { + // VideoDuration: Duration of the video. + VideoDuration string `json:"videoDuration,omitempty"` + // ForceSendFields is a list of field names (e.g. "VideoDuration") to + // unconditionally include in API requests. By default, fields with empty or + // default values are omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-ForceSendFields for more + // details. + ForceSendFields []string `json:"-"` + // NullFields is a list of field names (e.g. "VideoDuration") to include in API + // requests with the JSON null value. By default, fields with empty values are + // omitted from API requests. See + // https://pkg.go.dev/google.golang.org/api#hdr-NullFields for more details. + NullFields []string `json:"-"` +} + +func (s *VideoMetadata) MarshalJSON() ([]byte, error) { + type NoMethod VideoMetadata + return gensupport.MarshalJSON(NoMethod(*s), s.ForceSendFields, s.NullFields) +} + +type CorporaCreateCall struct { + s *Service + corpus *Corpus + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Create: Creates an empty `Corpus`. +func (r *CorporaService) Create(corpus *Corpus) *CorporaCreateCall { + c := &CorporaCreateCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.corpus = corpus + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *CorporaCreateCall) Fields(s ...googleapi.Field) *CorporaCreateCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *CorporaCreateCall) Context(ctx context.Context) *CorporaCreateCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *CorporaCreateCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *CorporaCreateCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "application/json", c.header_) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.corpus) + if err != nil { + return nil, err + } + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/corpora") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.corpora.create" call. +// Any non-2xx status code is an error. Response headers are in either +// *Corpus.ServerResponse.Header or (if a response was returned at all) in +// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check +// whether the returned error was because http.StatusNotModified was returned. +func (c *CorporaCreateCall) Do(opts ...googleapi.CallOption) (*Corpus, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &Corpus{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +type CorporaDeleteCall struct { + s *Service + name string + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Delete: Deletes a `Corpus`. +// +// - name: The resource name of the `Corpus`. Example: `corpora/my-corpus-123`. +func (r *CorporaService) Delete(name string) *CorporaDeleteCall { + c := &CorporaDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.name = name + return c +} + +// Force sets the optional parameter "force": If set to true, any `Document`s +// and objects related to this `Corpus` will also be deleted. If false (the +// default), a `FAILED_PRECONDITION` error will be returned if `Corpus` +// contains any `Document`s. +func (c *CorporaDeleteCall) Force(force bool) *CorporaDeleteCall { + c.urlParams_.Set("force", fmt.Sprint(force)) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *CorporaDeleteCall) Fields(s ...googleapi.Field) *CorporaDeleteCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *CorporaDeleteCall) Context(ctx context.Context) *CorporaDeleteCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *CorporaDeleteCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *CorporaDeleteCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "", c.header_) + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+name}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("DELETE", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "name": c.name, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.corpora.delete" call. +// Any non-2xx status code is an error. Response headers are in either +// *Empty.ServerResponse.Header or (if a response was returned at all) in +// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check +// whether the returned error was because http.StatusNotModified was returned. +func (c *CorporaDeleteCall) Do(opts ...googleapi.CallOption) (*Empty, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &Empty{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +type CorporaGetCall struct { + s *Service + name string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// Get: Gets information about a specific `Corpus`. +// +// - name: The name of the `Corpus`. Example: `corpora/my-corpus-123`. +func (r *CorporaService) Get(name string) *CorporaGetCall { + c := &CorporaGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.name = name + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *CorporaGetCall) Fields(s ...googleapi.Field) *CorporaGetCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets an optional parameter which makes the operation fail if the +// object's ETag matches the given value. This is useful for getting updates +// only after the object has changed since the last request. +func (c *CorporaGetCall) IfNoneMatch(entityTag string) *CorporaGetCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *CorporaGetCall) Context(ctx context.Context) *CorporaGetCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *CorporaGetCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *CorporaGetCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "", c.header_) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+name}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "name": c.name, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.corpora.get" call. +// Any non-2xx status code is an error. Response headers are in either +// *Corpus.ServerResponse.Header or (if a response was returned at all) in +// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check +// whether the returned error was because http.StatusNotModified was returned. +func (c *CorporaGetCall) Do(opts ...googleapi.CallOption) (*Corpus, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &Corpus{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +type CorporaListCall struct { + s *Service + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// List: Lists all `Corpora` owned by the user. +func (r *CorporaService) List() *CorporaListCall { + c := &CorporaListCall{s: r.s, urlParams_: make(gensupport.URLParams)} + return c +} + +// PageSize sets the optional parameter "pageSize": The maximum number of +// `Corpora` to return (per page). The service may return fewer `Corpora`. If +// unspecified, at most 10 `Corpora` will be returned. The maximum size limit +// is 20 `Corpora` per page. +func (c *CorporaListCall) PageSize(pageSize int64) *CorporaListCall { + c.urlParams_.Set("pageSize", fmt.Sprint(pageSize)) + return c +} + +// PageToken sets the optional parameter "pageToken": A page token, received +// from a previous `ListCorpora` call. Provide the `next_page_token` returned +// in the response as an argument to the next request to retrieve the next +// page. When paginating, all other parameters provided to `ListCorpora` must +// match the call that provided the page token. +func (c *CorporaListCall) PageToken(pageToken string) *CorporaListCall { + c.urlParams_.Set("pageToken", pageToken) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *CorporaListCall) Fields(s ...googleapi.Field) *CorporaListCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets an optional parameter which makes the operation fail if the +// object's ETag matches the given value. This is useful for getting updates +// only after the object has changed since the last request. +func (c *CorporaListCall) IfNoneMatch(entityTag string) *CorporaListCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *CorporaListCall) Context(ctx context.Context) *CorporaListCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *CorporaListCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *CorporaListCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "", c.header_) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/corpora") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.corpora.list" call. +// Any non-2xx status code is an error. Response headers are in either +// *ListCorporaResponse.ServerResponse.Header or (if a response was returned at +// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified was +// returned. +func (c *CorporaListCall) Do(opts ...googleapi.CallOption) (*ListCorporaResponse, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &ListCorporaResponse{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +// Pages invokes f for each page of results. +// A non-nil error returned from f will halt the iteration. +// The provided context supersedes any context provided to the Context method. +func (c *CorporaListCall) Pages(ctx context.Context, f func(*ListCorporaResponse) error) error { + c.ctx_ = ctx + defer c.PageToken(c.urlParams_.Get("pageToken")) + for { + x, err := c.Do() + if err != nil { + return err + } + if err := f(x); err != nil { + return err + } + if x.NextPageToken == "" { + return nil + } + c.PageToken(x.NextPageToken) + } +} + +type CorporaPatchCall struct { + s *Service + name string + corpus *Corpus + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Patch: Updates a `Corpus`. +// +// - name: Immutable. Identifier. The `Corpus` resource name. The ID (name +// excluding the "corpora/" prefix) can contain up to 40 characters that are +// lowercase alphanumeric or dashes (-). The ID cannot start or end with a +// dash. If the name is empty on create, a unique name will be derived from +// `display_name` along with a 12 character random suffix. Example: +// `corpora/my-awesome-corpora-123a456b789c`. +func (r *CorporaService) Patch(name string, corpus *Corpus) *CorporaPatchCall { + c := &CorporaPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.name = name + c.corpus = corpus + return c +} + +// UpdateMask sets the optional parameter "updateMask": Required. The list of +// fields to update. Currently, this only supports updating `display_name`. +func (c *CorporaPatchCall) UpdateMask(updateMask string) *CorporaPatchCall { + c.urlParams_.Set("updateMask", updateMask) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *CorporaPatchCall) Fields(s ...googleapi.Field) *CorporaPatchCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *CorporaPatchCall) Context(ctx context.Context) *CorporaPatchCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *CorporaPatchCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *CorporaPatchCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "application/json", c.header_) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.corpus) + if err != nil { + return nil, err + } + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+name}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("PATCH", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "name": c.name, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.corpora.patch" call. +// Any non-2xx status code is an error. Response headers are in either +// *Corpus.ServerResponse.Header or (if a response was returned at all) in +// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check +// whether the returned error was because http.StatusNotModified was returned. +func (c *CorporaPatchCall) Do(opts ...googleapi.CallOption) (*Corpus, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &Corpus{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +type CorporaQueryCall struct { + s *Service + name string + querycorpusrequest *QueryCorpusRequest + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Query: Performs semantic search over a `Corpus`. +// +// - name: The name of the `Corpus` to query. Example: `corpora/my-corpus-123`. +func (r *CorporaService) Query(name string, querycorpusrequest *QueryCorpusRequest) *CorporaQueryCall { + c := &CorporaQueryCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.name = name + c.querycorpusrequest = querycorpusrequest + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *CorporaQueryCall) Fields(s ...googleapi.Field) *CorporaQueryCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *CorporaQueryCall) Context(ctx context.Context) *CorporaQueryCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *CorporaQueryCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *CorporaQueryCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "application/json", c.header_) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.querycorpusrequest) + if err != nil { + return nil, err + } + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+name}:query") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "name": c.name, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.corpora.query" call. +// Any non-2xx status code is an error. Response headers are in either +// *QueryCorpusResponse.ServerResponse.Header or (if a response was returned at +// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified was +// returned. +func (c *CorporaQueryCall) Do(opts ...googleapi.CallOption) (*QueryCorpusResponse, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &QueryCorpusResponse{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +type CorporaDocumentsCreateCall struct { + s *Service + parent string + document *Document + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Create: Creates an empty `Document`. +// +// - parent: The name of the `Corpus` where this `Document` will be created. +// Example: `corpora/my-corpus-123`. +func (r *CorporaDocumentsService) Create(parent string, document *Document) *CorporaDocumentsCreateCall { + c := &CorporaDocumentsCreateCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.parent = parent + c.document = document + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *CorporaDocumentsCreateCall) Fields(s ...googleapi.Field) *CorporaDocumentsCreateCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *CorporaDocumentsCreateCall) Context(ctx context.Context) *CorporaDocumentsCreateCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *CorporaDocumentsCreateCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *CorporaDocumentsCreateCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "application/json", c.header_) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.document) + if err != nil { + return nil, err + } + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+parent}/documents") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "parent": c.parent, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.corpora.documents.create" call. +// Any non-2xx status code is an error. Response headers are in either +// *Document.ServerResponse.Header or (if a response was returned at all) in +// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check +// whether the returned error was because http.StatusNotModified was returned. +func (c *CorporaDocumentsCreateCall) Do(opts ...googleapi.CallOption) (*Document, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &Document{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +type CorporaDocumentsDeleteCall struct { + s *Service + name string + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Delete: Deletes a `Document`. +// +// - name: The resource name of the `Document` to delete. Example: +// `corpora/my-corpus-123/documents/the-doc-abc`. +func (r *CorporaDocumentsService) Delete(name string) *CorporaDocumentsDeleteCall { + c := &CorporaDocumentsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.name = name + return c +} + +// Force sets the optional parameter "force": If set to true, any `Chunk`s and +// objects related to this `Document` will also be deleted. If false (the +// default), a `FAILED_PRECONDITION` error will be returned if `Document` +// contains any `Chunk`s. +func (c *CorporaDocumentsDeleteCall) Force(force bool) *CorporaDocumentsDeleteCall { + c.urlParams_.Set("force", fmt.Sprint(force)) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *CorporaDocumentsDeleteCall) Fields(s ...googleapi.Field) *CorporaDocumentsDeleteCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *CorporaDocumentsDeleteCall) Context(ctx context.Context) *CorporaDocumentsDeleteCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *CorporaDocumentsDeleteCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *CorporaDocumentsDeleteCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "", c.header_) + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+name}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("DELETE", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "name": c.name, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.corpora.documents.delete" call. +// Any non-2xx status code is an error. Response headers are in either +// *Empty.ServerResponse.Header or (if a response was returned at all) in +// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check +// whether the returned error was because http.StatusNotModified was returned. +func (c *CorporaDocumentsDeleteCall) Do(opts ...googleapi.CallOption) (*Empty, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &Empty{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +type CorporaDocumentsGetCall struct { + s *Service + name string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// Get: Gets information about a specific `Document`. +// +// - name: The name of the `Document` to retrieve. Example: +// `corpora/my-corpus-123/documents/the-doc-abc`. +func (r *CorporaDocumentsService) Get(name string) *CorporaDocumentsGetCall { + c := &CorporaDocumentsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.name = name + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *CorporaDocumentsGetCall) Fields(s ...googleapi.Field) *CorporaDocumentsGetCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets an optional parameter which makes the operation fail if the +// object's ETag matches the given value. This is useful for getting updates +// only after the object has changed since the last request. +func (c *CorporaDocumentsGetCall) IfNoneMatch(entityTag string) *CorporaDocumentsGetCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *CorporaDocumentsGetCall) Context(ctx context.Context) *CorporaDocumentsGetCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *CorporaDocumentsGetCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *CorporaDocumentsGetCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "", c.header_) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+name}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "name": c.name, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.corpora.documents.get" call. +// Any non-2xx status code is an error. Response headers are in either +// *Document.ServerResponse.Header or (if a response was returned at all) in +// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check +// whether the returned error was because http.StatusNotModified was returned. +func (c *CorporaDocumentsGetCall) Do(opts ...googleapi.CallOption) (*Document, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &Document{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +type CorporaDocumentsListCall struct { + s *Service + parent string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// List: Lists all `Document`s in a `Corpus`. +// +// - parent: The name of the `Corpus` containing `Document`s. Example: +// `corpora/my-corpus-123`. +func (r *CorporaDocumentsService) List(parent string) *CorporaDocumentsListCall { + c := &CorporaDocumentsListCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.parent = parent + return c +} + +// PageSize sets the optional parameter "pageSize": The maximum number of +// `Document`s to return (per page). The service may return fewer `Document`s. +// If unspecified, at most 10 `Document`s will be returned. The maximum size +// limit is 20 `Document`s per page. +func (c *CorporaDocumentsListCall) PageSize(pageSize int64) *CorporaDocumentsListCall { + c.urlParams_.Set("pageSize", fmt.Sprint(pageSize)) + return c +} + +// PageToken sets the optional parameter "pageToken": A page token, received +// from a previous `ListDocuments` call. Provide the `next_page_token` returned +// in the response as an argument to the next request to retrieve the next +// page. When paginating, all other parameters provided to `ListDocuments` must +// match the call that provided the page token. +func (c *CorporaDocumentsListCall) PageToken(pageToken string) *CorporaDocumentsListCall { + c.urlParams_.Set("pageToken", pageToken) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *CorporaDocumentsListCall) Fields(s ...googleapi.Field) *CorporaDocumentsListCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets an optional parameter which makes the operation fail if the +// object's ETag matches the given value. This is useful for getting updates +// only after the object has changed since the last request. +func (c *CorporaDocumentsListCall) IfNoneMatch(entityTag string) *CorporaDocumentsListCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *CorporaDocumentsListCall) Context(ctx context.Context) *CorporaDocumentsListCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *CorporaDocumentsListCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *CorporaDocumentsListCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "", c.header_) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+parent}/documents") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "parent": c.parent, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.corpora.documents.list" call. +// Any non-2xx status code is an error. Response headers are in either +// *ListDocumentsResponse.ServerResponse.Header or (if a response was returned +// at all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified was +// returned. +func (c *CorporaDocumentsListCall) Do(opts ...googleapi.CallOption) (*ListDocumentsResponse, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &ListDocumentsResponse{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +// Pages invokes f for each page of results. +// A non-nil error returned from f will halt the iteration. +// The provided context supersedes any context provided to the Context method. +func (c *CorporaDocumentsListCall) Pages(ctx context.Context, f func(*ListDocumentsResponse) error) error { + c.ctx_ = ctx + defer c.PageToken(c.urlParams_.Get("pageToken")) + for { + x, err := c.Do() + if err != nil { + return err + } + if err := f(x); err != nil { + return err + } + if x.NextPageToken == "" { + return nil + } + c.PageToken(x.NextPageToken) + } +} + +type CorporaDocumentsPatchCall struct { + s *Service + name string + document *Document + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Patch: Updates a `Document`. +// +// - name: Immutable. Identifier. The `Document` resource name. The ID (name +// excluding the "corpora/*/documents/" prefix) can contain up to 40 +// characters that are lowercase alphanumeric or dashes (-). The ID cannot +// start or end with a dash. If the name is empty on create, a unique name +// will be derived from `display_name` along with a 12 character random +// suffix. Example: +// `corpora/{corpus_id}/documents/my-awesome-doc-123a456b789c`. +func (r *CorporaDocumentsService) Patch(name string, document *Document) *CorporaDocumentsPatchCall { + c := &CorporaDocumentsPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.name = name + c.document = document + return c +} + +// UpdateMask sets the optional parameter "updateMask": Required. The list of +// fields to update. Currently, this only supports updating `display_name` and +// `custom_metadata`. +func (c *CorporaDocumentsPatchCall) UpdateMask(updateMask string) *CorporaDocumentsPatchCall { + c.urlParams_.Set("updateMask", updateMask) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *CorporaDocumentsPatchCall) Fields(s ...googleapi.Field) *CorporaDocumentsPatchCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *CorporaDocumentsPatchCall) Context(ctx context.Context) *CorporaDocumentsPatchCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *CorporaDocumentsPatchCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *CorporaDocumentsPatchCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "application/json", c.header_) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.document) + if err != nil { + return nil, err + } + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+name}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("PATCH", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "name": c.name, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.corpora.documents.patch" call. +// Any non-2xx status code is an error. Response headers are in either +// *Document.ServerResponse.Header or (if a response was returned at all) in +// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check +// whether the returned error was because http.StatusNotModified was returned. +func (c *CorporaDocumentsPatchCall) Do(opts ...googleapi.CallOption) (*Document, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &Document{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +type CorporaDocumentsQueryCall struct { + s *Service + name string + querydocumentrequest *QueryDocumentRequest + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Query: Performs semantic search over a `Document`. +// +// - name: The name of the `Document` to query. Example: +// `corpora/my-corpus-123/documents/the-doc-abc`. +func (r *CorporaDocumentsService) Query(name string, querydocumentrequest *QueryDocumentRequest) *CorporaDocumentsQueryCall { + c := &CorporaDocumentsQueryCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.name = name + c.querydocumentrequest = querydocumentrequest + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *CorporaDocumentsQueryCall) Fields(s ...googleapi.Field) *CorporaDocumentsQueryCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *CorporaDocumentsQueryCall) Context(ctx context.Context) *CorporaDocumentsQueryCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *CorporaDocumentsQueryCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *CorporaDocumentsQueryCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "application/json", c.header_) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.querydocumentrequest) + if err != nil { + return nil, err + } + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+name}:query") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "name": c.name, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.corpora.documents.query" call. +// Any non-2xx status code is an error. Response headers are in either +// *QueryDocumentResponse.ServerResponse.Header or (if a response was returned +// at all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified was +// returned. +func (c *CorporaDocumentsQueryCall) Do(opts ...googleapi.CallOption) (*QueryDocumentResponse, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &QueryDocumentResponse{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +type CorporaDocumentsChunksBatchCreateCall struct { + s *Service + parent string + batchcreatechunksrequest *BatchCreateChunksRequest + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// BatchCreate: Batch create `Chunk`s. +// +// - parent: Optional. The name of the `Document` where this batch of `Chunk`s +// will be created. The parent field in every `CreateChunkRequest` must match +// this value. Example: `corpora/my-corpus-123/documents/the-doc-abc`. +func (r *CorporaDocumentsChunksService) BatchCreate(parent string, batchcreatechunksrequest *BatchCreateChunksRequest) *CorporaDocumentsChunksBatchCreateCall { + c := &CorporaDocumentsChunksBatchCreateCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.parent = parent + c.batchcreatechunksrequest = batchcreatechunksrequest + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *CorporaDocumentsChunksBatchCreateCall) Fields(s ...googleapi.Field) *CorporaDocumentsChunksBatchCreateCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *CorporaDocumentsChunksBatchCreateCall) Context(ctx context.Context) *CorporaDocumentsChunksBatchCreateCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *CorporaDocumentsChunksBatchCreateCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *CorporaDocumentsChunksBatchCreateCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "application/json", c.header_) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.batchcreatechunksrequest) + if err != nil { + return nil, err + } + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+parent}/chunks:batchCreate") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "parent": c.parent, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.corpora.documents.chunks.batchCreate" call. +// Any non-2xx status code is an error. Response headers are in either +// *BatchCreateChunksResponse.ServerResponse.Header or (if a response was +// returned at all) in error.(*googleapi.Error).Header. Use +// googleapi.IsNotModified to check whether the returned error was because +// http.StatusNotModified was returned. +func (c *CorporaDocumentsChunksBatchCreateCall) Do(opts ...googleapi.CallOption) (*BatchCreateChunksResponse, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &BatchCreateChunksResponse{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +type CorporaDocumentsChunksBatchDeleteCall struct { + s *Service + parent string + batchdeletechunksrequest *BatchDeleteChunksRequest + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// BatchDelete: Batch delete `Chunk`s. +// +// - parent: Optional. The name of the `Document` containing the `Chunk`s to +// delete. The parent field in every `DeleteChunkRequest` must match this +// value. Example: `corpora/my-corpus-123/documents/the-doc-abc`. +func (r *CorporaDocumentsChunksService) BatchDelete(parent string, batchdeletechunksrequest *BatchDeleteChunksRequest) *CorporaDocumentsChunksBatchDeleteCall { + c := &CorporaDocumentsChunksBatchDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.parent = parent + c.batchdeletechunksrequest = batchdeletechunksrequest + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *CorporaDocumentsChunksBatchDeleteCall) Fields(s ...googleapi.Field) *CorporaDocumentsChunksBatchDeleteCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *CorporaDocumentsChunksBatchDeleteCall) Context(ctx context.Context) *CorporaDocumentsChunksBatchDeleteCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *CorporaDocumentsChunksBatchDeleteCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *CorporaDocumentsChunksBatchDeleteCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "application/json", c.header_) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.batchdeletechunksrequest) + if err != nil { + return nil, err + } + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+parent}/chunks:batchDelete") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "parent": c.parent, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.corpora.documents.chunks.batchDelete" call. +// Any non-2xx status code is an error. Response headers are in either +// *Empty.ServerResponse.Header or (if a response was returned at all) in +// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check +// whether the returned error was because http.StatusNotModified was returned. +func (c *CorporaDocumentsChunksBatchDeleteCall) Do(opts ...googleapi.CallOption) (*Empty, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &Empty{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +type CorporaDocumentsChunksBatchUpdateCall struct { + s *Service + parent string + batchupdatechunksrequest *BatchUpdateChunksRequest + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// BatchUpdate: Batch update `Chunk`s. +// +// - parent: Optional. The name of the `Document` containing the `Chunk`s to +// update. The parent field in every `UpdateChunkRequest` must match this +// value. Example: `corpora/my-corpus-123/documents/the-doc-abc`. +func (r *CorporaDocumentsChunksService) BatchUpdate(parent string, batchupdatechunksrequest *BatchUpdateChunksRequest) *CorporaDocumentsChunksBatchUpdateCall { + c := &CorporaDocumentsChunksBatchUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.parent = parent + c.batchupdatechunksrequest = batchupdatechunksrequest + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *CorporaDocumentsChunksBatchUpdateCall) Fields(s ...googleapi.Field) *CorporaDocumentsChunksBatchUpdateCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *CorporaDocumentsChunksBatchUpdateCall) Context(ctx context.Context) *CorporaDocumentsChunksBatchUpdateCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *CorporaDocumentsChunksBatchUpdateCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *CorporaDocumentsChunksBatchUpdateCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "application/json", c.header_) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.batchupdatechunksrequest) + if err != nil { + return nil, err + } + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+parent}/chunks:batchUpdate") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "parent": c.parent, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.corpora.documents.chunks.batchUpdate" call. +// Any non-2xx status code is an error. Response headers are in either +// *BatchUpdateChunksResponse.ServerResponse.Header or (if a response was +// returned at all) in error.(*googleapi.Error).Header. Use +// googleapi.IsNotModified to check whether the returned error was because +// http.StatusNotModified was returned. +func (c *CorporaDocumentsChunksBatchUpdateCall) Do(opts ...googleapi.CallOption) (*BatchUpdateChunksResponse, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &BatchUpdateChunksResponse{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +type CorporaDocumentsChunksCreateCall struct { + s *Service + parent string + chunk *Chunk + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Create: Creates a `Chunk`. +// +// - parent: The name of the `Document` where this `Chunk` will be created. +// Example: `corpora/my-corpus-123/documents/the-doc-abc`. +func (r *CorporaDocumentsChunksService) Create(parent string, chunk *Chunk) *CorporaDocumentsChunksCreateCall { + c := &CorporaDocumentsChunksCreateCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.parent = parent + c.chunk = chunk + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *CorporaDocumentsChunksCreateCall) Fields(s ...googleapi.Field) *CorporaDocumentsChunksCreateCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *CorporaDocumentsChunksCreateCall) Context(ctx context.Context) *CorporaDocumentsChunksCreateCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *CorporaDocumentsChunksCreateCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *CorporaDocumentsChunksCreateCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "application/json", c.header_) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.chunk) + if err != nil { + return nil, err + } + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+parent}/chunks") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "parent": c.parent, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.corpora.documents.chunks.create" call. +// Any non-2xx status code is an error. Response headers are in either +// *Chunk.ServerResponse.Header or (if a response was returned at all) in +// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check +// whether the returned error was because http.StatusNotModified was returned. +func (c *CorporaDocumentsChunksCreateCall) Do(opts ...googleapi.CallOption) (*Chunk, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &Chunk{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +type CorporaDocumentsChunksDeleteCall struct { + s *Service + name string + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Delete: Deletes a `Chunk`. +// +// - name: The resource name of the `Chunk` to delete. Example: +// `corpora/my-corpus-123/documents/the-doc-abc/chunks/some-chunk`. +func (r *CorporaDocumentsChunksService) Delete(name string) *CorporaDocumentsChunksDeleteCall { + c := &CorporaDocumentsChunksDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.name = name + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *CorporaDocumentsChunksDeleteCall) Fields(s ...googleapi.Field) *CorporaDocumentsChunksDeleteCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *CorporaDocumentsChunksDeleteCall) Context(ctx context.Context) *CorporaDocumentsChunksDeleteCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *CorporaDocumentsChunksDeleteCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *CorporaDocumentsChunksDeleteCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "", c.header_) + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+name}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("DELETE", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "name": c.name, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.corpora.documents.chunks.delete" call. +// Any non-2xx status code is an error. Response headers are in either +// *Empty.ServerResponse.Header or (if a response was returned at all) in +// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check +// whether the returned error was because http.StatusNotModified was returned. +func (c *CorporaDocumentsChunksDeleteCall) Do(opts ...googleapi.CallOption) (*Empty, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &Empty{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +type CorporaDocumentsChunksGetCall struct { + s *Service + name string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// Get: Gets information about a specific `Chunk`. +// +// - name: The name of the `Chunk` to retrieve. Example: +// `corpora/my-corpus-123/documents/the-doc-abc/chunks/some-chunk`. +func (r *CorporaDocumentsChunksService) Get(name string) *CorporaDocumentsChunksGetCall { + c := &CorporaDocumentsChunksGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.name = name + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *CorporaDocumentsChunksGetCall) Fields(s ...googleapi.Field) *CorporaDocumentsChunksGetCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets an optional parameter which makes the operation fail if the +// object's ETag matches the given value. This is useful for getting updates +// only after the object has changed since the last request. +func (c *CorporaDocumentsChunksGetCall) IfNoneMatch(entityTag string) *CorporaDocumentsChunksGetCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *CorporaDocumentsChunksGetCall) Context(ctx context.Context) *CorporaDocumentsChunksGetCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *CorporaDocumentsChunksGetCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *CorporaDocumentsChunksGetCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "", c.header_) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+name}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "name": c.name, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.corpora.documents.chunks.get" call. +// Any non-2xx status code is an error. Response headers are in either +// *Chunk.ServerResponse.Header or (if a response was returned at all) in +// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check +// whether the returned error was because http.StatusNotModified was returned. +func (c *CorporaDocumentsChunksGetCall) Do(opts ...googleapi.CallOption) (*Chunk, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &Chunk{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +type CorporaDocumentsChunksListCall struct { + s *Service + parent string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// List: Lists all `Chunk`s in a `Document`. +// +// - parent: The name of the `Document` containing `Chunk`s. Example: +// `corpora/my-corpus-123/documents/the-doc-abc`. +func (r *CorporaDocumentsChunksService) List(parent string) *CorporaDocumentsChunksListCall { + c := &CorporaDocumentsChunksListCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.parent = parent + return c +} + +// PageSize sets the optional parameter "pageSize": The maximum number of +// `Chunk`s to return (per page). The service may return fewer `Chunk`s. If +// unspecified, at most 10 `Chunk`s will be returned. The maximum size limit is +// 100 `Chunk`s per page. +func (c *CorporaDocumentsChunksListCall) PageSize(pageSize int64) *CorporaDocumentsChunksListCall { + c.urlParams_.Set("pageSize", fmt.Sprint(pageSize)) + return c +} + +// PageToken sets the optional parameter "pageToken": A page token, received +// from a previous `ListChunks` call. Provide the `next_page_token` returned in +// the response as an argument to the next request to retrieve the next page. +// When paginating, all other parameters provided to `ListChunks` must match +// the call that provided the page token. +func (c *CorporaDocumentsChunksListCall) PageToken(pageToken string) *CorporaDocumentsChunksListCall { + c.urlParams_.Set("pageToken", pageToken) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *CorporaDocumentsChunksListCall) Fields(s ...googleapi.Field) *CorporaDocumentsChunksListCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets an optional parameter which makes the operation fail if the +// object's ETag matches the given value. This is useful for getting updates +// only after the object has changed since the last request. +func (c *CorporaDocumentsChunksListCall) IfNoneMatch(entityTag string) *CorporaDocumentsChunksListCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *CorporaDocumentsChunksListCall) Context(ctx context.Context) *CorporaDocumentsChunksListCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *CorporaDocumentsChunksListCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *CorporaDocumentsChunksListCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "", c.header_) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+parent}/chunks") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "parent": c.parent, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.corpora.documents.chunks.list" call. +// Any non-2xx status code is an error. Response headers are in either +// *ListChunksResponse.ServerResponse.Header or (if a response was returned at +// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified was +// returned. +func (c *CorporaDocumentsChunksListCall) Do(opts ...googleapi.CallOption) (*ListChunksResponse, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &ListChunksResponse{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +// Pages invokes f for each page of results. +// A non-nil error returned from f will halt the iteration. +// The provided context supersedes any context provided to the Context method. +func (c *CorporaDocumentsChunksListCall) Pages(ctx context.Context, f func(*ListChunksResponse) error) error { + c.ctx_ = ctx + defer c.PageToken(c.urlParams_.Get("pageToken")) + for { + x, err := c.Do() + if err != nil { + return err + } + if err := f(x); err != nil { + return err + } + if x.NextPageToken == "" { + return nil + } + c.PageToken(x.NextPageToken) + } +} + +type CorporaDocumentsChunksPatchCall struct { + s *Service + name string + chunk *Chunk + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Patch: Updates a `Chunk`. +// +// - name: Immutable. Identifier. The `Chunk` resource name. The ID (name +// excluding the "corpora/*/documents/*/chunks/" prefix) can contain up to 40 +// characters that are lowercase alphanumeric or dashes (-). The ID cannot +// start or end with a dash. If the name is empty on create, a random +// 12-character unique ID will be generated. Example: +// `corpora/{corpus_id}/documents/{document_id}/chunks/123a456b789c`. +func (r *CorporaDocumentsChunksService) Patch(name string, chunk *Chunk) *CorporaDocumentsChunksPatchCall { + c := &CorporaDocumentsChunksPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.name = name + c.chunk = chunk + return c +} + +// UpdateMask sets the optional parameter "updateMask": Required. The list of +// fields to update. Currently, this only supports updating `custom_metadata` +// and `data`. +func (c *CorporaDocumentsChunksPatchCall) UpdateMask(updateMask string) *CorporaDocumentsChunksPatchCall { + c.urlParams_.Set("updateMask", updateMask) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *CorporaDocumentsChunksPatchCall) Fields(s ...googleapi.Field) *CorporaDocumentsChunksPatchCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *CorporaDocumentsChunksPatchCall) Context(ctx context.Context) *CorporaDocumentsChunksPatchCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *CorporaDocumentsChunksPatchCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *CorporaDocumentsChunksPatchCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "application/json", c.header_) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.chunk) + if err != nil { + return nil, err + } + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+name}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("PATCH", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "name": c.name, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.corpora.documents.chunks.patch" call. +// Any non-2xx status code is an error. Response headers are in either +// *Chunk.ServerResponse.Header or (if a response was returned at all) in +// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check +// whether the returned error was because http.StatusNotModified was returned. +func (c *CorporaDocumentsChunksPatchCall) Do(opts ...googleapi.CallOption) (*Chunk, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &Chunk{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +type CorporaPermissionsCreateCall struct { + s *Service + parent string + permission *Permission + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Create: Create a permission to a specific resource. +// +// - parent: The parent resource of the `Permission`. Formats: +// `tunedModels/{tuned_model}` `corpora/{corpus}`. +func (r *CorporaPermissionsService) Create(parent string, permission *Permission) *CorporaPermissionsCreateCall { + c := &CorporaPermissionsCreateCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.parent = parent + c.permission = permission + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *CorporaPermissionsCreateCall) Fields(s ...googleapi.Field) *CorporaPermissionsCreateCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *CorporaPermissionsCreateCall) Context(ctx context.Context) *CorporaPermissionsCreateCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *CorporaPermissionsCreateCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *CorporaPermissionsCreateCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "application/json", c.header_) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.permission) + if err != nil { + return nil, err + } + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+parent}/permissions") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "parent": c.parent, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.corpora.permissions.create" call. +// Any non-2xx status code is an error. Response headers are in either +// *Permission.ServerResponse.Header or (if a response was returned at all) in +// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check +// whether the returned error was because http.StatusNotModified was returned. +func (c *CorporaPermissionsCreateCall) Do(opts ...googleapi.CallOption) (*Permission, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &Permission{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +type CorporaPermissionsDeleteCall struct { + s *Service + name string + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Delete: Deletes the permission. +// +// - name: The resource name of the permission. Formats: +// `tunedModels/{tuned_model}/permissions/{permission}` +// `corpora/{corpus}/permissions/{permission}`. +func (r *CorporaPermissionsService) Delete(name string) *CorporaPermissionsDeleteCall { + c := &CorporaPermissionsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.name = name + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *CorporaPermissionsDeleteCall) Fields(s ...googleapi.Field) *CorporaPermissionsDeleteCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *CorporaPermissionsDeleteCall) Context(ctx context.Context) *CorporaPermissionsDeleteCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *CorporaPermissionsDeleteCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *CorporaPermissionsDeleteCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "", c.header_) + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+name}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("DELETE", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "name": c.name, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.corpora.permissions.delete" call. +// Any non-2xx status code is an error. Response headers are in either +// *Empty.ServerResponse.Header or (if a response was returned at all) in +// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check +// whether the returned error was because http.StatusNotModified was returned. +func (c *CorporaPermissionsDeleteCall) Do(opts ...googleapi.CallOption) (*Empty, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &Empty{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +type CorporaPermissionsGetCall struct { + s *Service + name string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// Get: Gets information about a specific Permission. +// +// - name: The resource name of the permission. Formats: +// `tunedModels/{tuned_model}/permissions/{permission}` +// `corpora/{corpus}/permissions/{permission}`. +func (r *CorporaPermissionsService) Get(name string) *CorporaPermissionsGetCall { + c := &CorporaPermissionsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.name = name + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *CorporaPermissionsGetCall) Fields(s ...googleapi.Field) *CorporaPermissionsGetCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets an optional parameter which makes the operation fail if the +// object's ETag matches the given value. This is useful for getting updates +// only after the object has changed since the last request. +func (c *CorporaPermissionsGetCall) IfNoneMatch(entityTag string) *CorporaPermissionsGetCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *CorporaPermissionsGetCall) Context(ctx context.Context) *CorporaPermissionsGetCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *CorporaPermissionsGetCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *CorporaPermissionsGetCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "", c.header_) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+name}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "name": c.name, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.corpora.permissions.get" call. +// Any non-2xx status code is an error. Response headers are in either +// *Permission.ServerResponse.Header or (if a response was returned at all) in +// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check +// whether the returned error was because http.StatusNotModified was returned. +func (c *CorporaPermissionsGetCall) Do(opts ...googleapi.CallOption) (*Permission, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &Permission{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +type CorporaPermissionsListCall struct { + s *Service + parent string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// List: Lists permissions for the specific resource. +// +// - parent: The parent resource of the permissions. Formats: +// `tunedModels/{tuned_model}` `corpora/{corpus}`. +func (r *CorporaPermissionsService) List(parent string) *CorporaPermissionsListCall { + c := &CorporaPermissionsListCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.parent = parent + return c +} + +// PageSize sets the optional parameter "pageSize": The maximum number of +// `Permission`s to return (per page). The service may return fewer +// permissions. If unspecified, at most 10 permissions will be returned. This +// method returns at most 1000 permissions per page, even if you pass larger +// page_size. +func (c *CorporaPermissionsListCall) PageSize(pageSize int64) *CorporaPermissionsListCall { + c.urlParams_.Set("pageSize", fmt.Sprint(pageSize)) + return c +} + +// PageToken sets the optional parameter "pageToken": A page token, received +// from a previous `ListPermissions` call. Provide the `page_token` returned by +// one request as an argument to the next request to retrieve the next page. +// When paginating, all other parameters provided to `ListPermissions` must +// match the call that provided the page token. +func (c *CorporaPermissionsListCall) PageToken(pageToken string) *CorporaPermissionsListCall { + c.urlParams_.Set("pageToken", pageToken) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *CorporaPermissionsListCall) Fields(s ...googleapi.Field) *CorporaPermissionsListCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets an optional parameter which makes the operation fail if the +// object's ETag matches the given value. This is useful for getting updates +// only after the object has changed since the last request. +func (c *CorporaPermissionsListCall) IfNoneMatch(entityTag string) *CorporaPermissionsListCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *CorporaPermissionsListCall) Context(ctx context.Context) *CorporaPermissionsListCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *CorporaPermissionsListCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *CorporaPermissionsListCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "", c.header_) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+parent}/permissions") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "parent": c.parent, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.corpora.permissions.list" call. +// Any non-2xx status code is an error. Response headers are in either +// *ListPermissionsResponse.ServerResponse.Header or (if a response was +// returned at all) in error.(*googleapi.Error).Header. Use +// googleapi.IsNotModified to check whether the returned error was because +// http.StatusNotModified was returned. +func (c *CorporaPermissionsListCall) Do(opts ...googleapi.CallOption) (*ListPermissionsResponse, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &ListPermissionsResponse{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +// Pages invokes f for each page of results. +// A non-nil error returned from f will halt the iteration. +// The provided context supersedes any context provided to the Context method. +func (c *CorporaPermissionsListCall) Pages(ctx context.Context, f func(*ListPermissionsResponse) error) error { + c.ctx_ = ctx + defer c.PageToken(c.urlParams_.Get("pageToken")) + for { + x, err := c.Do() + if err != nil { + return err + } + if err := f(x); err != nil { + return err + } + if x.NextPageToken == "" { + return nil + } + c.PageToken(x.NextPageToken) + } +} + +type CorporaPermissionsPatchCall struct { + s *Service + name string + permission *Permission + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Patch: Updates the permission. +// +// - name: Output only. Identifier. The permission name. A unique name will be +// generated on create. Examples: +// tunedModels/{tuned_model}/permissions/{permission} +// corpora/{corpus}/permissions/{permission} Output only. +func (r *CorporaPermissionsService) Patch(name string, permission *Permission) *CorporaPermissionsPatchCall { + c := &CorporaPermissionsPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.name = name + c.permission = permission + return c +} + +// UpdateMask sets the optional parameter "updateMask": Required. The list of +// fields to update. Accepted ones: - role (`Permission.role` field) +func (c *CorporaPermissionsPatchCall) UpdateMask(updateMask string) *CorporaPermissionsPatchCall { + c.urlParams_.Set("updateMask", updateMask) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *CorporaPermissionsPatchCall) Fields(s ...googleapi.Field) *CorporaPermissionsPatchCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *CorporaPermissionsPatchCall) Context(ctx context.Context) *CorporaPermissionsPatchCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *CorporaPermissionsPatchCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *CorporaPermissionsPatchCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "application/json", c.header_) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.permission) + if err != nil { + return nil, err + } + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+name}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("PATCH", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "name": c.name, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.corpora.permissions.patch" call. +// Any non-2xx status code is an error. Response headers are in either +// *Permission.ServerResponse.Header or (if a response was returned at all) in +// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check +// whether the returned error was because http.StatusNotModified was returned. +func (c *CorporaPermissionsPatchCall) Do(opts ...googleapi.CallOption) (*Permission, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &Permission{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +type FilesDeleteCall struct { + s *Service + name string + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Delete: Deletes the `File`. +// +// - name: The name of the `File` to delete. Example: `files/abc-123`. +func (r *FilesService) Delete(name string) *FilesDeleteCall { + c := &FilesDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.name = name + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *FilesDeleteCall) Fields(s ...googleapi.Field) *FilesDeleteCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *FilesDeleteCall) Context(ctx context.Context) *FilesDeleteCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *FilesDeleteCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *FilesDeleteCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "", c.header_) + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+name}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("DELETE", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "name": c.name, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.files.delete" call. +// Any non-2xx status code is an error. Response headers are in either +// *Empty.ServerResponse.Header or (if a response was returned at all) in +// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check +// whether the returned error was because http.StatusNotModified was returned. +func (c *FilesDeleteCall) Do(opts ...googleapi.CallOption) (*Empty, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &Empty{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +type FilesGetCall struct { + s *Service + name string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// Get: Gets the metadata for the given `File`. +// +// - name: The name of the `File` to get. Example: `files/abc-123`. +func (r *FilesService) Get(name string) *FilesGetCall { + c := &FilesGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.name = name + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *FilesGetCall) Fields(s ...googleapi.Field) *FilesGetCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets an optional parameter which makes the operation fail if the +// object's ETag matches the given value. This is useful for getting updates +// only after the object has changed since the last request. +func (c *FilesGetCall) IfNoneMatch(entityTag string) *FilesGetCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *FilesGetCall) Context(ctx context.Context) *FilesGetCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *FilesGetCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *FilesGetCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "", c.header_) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+name}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "name": c.name, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.files.get" call. +// Any non-2xx status code is an error. Response headers are in either +// *File.ServerResponse.Header or (if a response was returned at all) in +// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check +// whether the returned error was because http.StatusNotModified was returned. +func (c *FilesGetCall) Do(opts ...googleapi.CallOption) (*File, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &File{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +type FilesListCall struct { + s *Service + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// List: Lists the metadata for `File`s owned by the requesting project. +func (r *FilesService) List() *FilesListCall { + c := &FilesListCall{s: r.s, urlParams_: make(gensupport.URLParams)} + return c +} + +// PageSize sets the optional parameter "pageSize": Maximum number of `File`s +// to return per page. If unspecified, defaults to 10. Maximum `page_size` is +// 100. +func (c *FilesListCall) PageSize(pageSize int64) *FilesListCall { + c.urlParams_.Set("pageSize", fmt.Sprint(pageSize)) + return c +} + +// PageToken sets the optional parameter "pageToken": A page token from a +// previous `ListFiles` call. +func (c *FilesListCall) PageToken(pageToken string) *FilesListCall { + c.urlParams_.Set("pageToken", pageToken) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *FilesListCall) Fields(s ...googleapi.Field) *FilesListCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets an optional parameter which makes the operation fail if the +// object's ETag matches the given value. This is useful for getting updates +// only after the object has changed since the last request. +func (c *FilesListCall) IfNoneMatch(entityTag string) *FilesListCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *FilesListCall) Context(ctx context.Context) *FilesListCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *FilesListCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *FilesListCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "", c.header_) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/files") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.files.list" call. +// Any non-2xx status code is an error. Response headers are in either +// *ListFilesResponse.ServerResponse.Header or (if a response was returned at +// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified was +// returned. +func (c *FilesListCall) Do(opts ...googleapi.CallOption) (*ListFilesResponse, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &ListFilesResponse{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +// Pages invokes f for each page of results. +// A non-nil error returned from f will halt the iteration. +// The provided context supersedes any context provided to the Context method. +func (c *FilesListCall) Pages(ctx context.Context, f func(*ListFilesResponse) error) error { + c.ctx_ = ctx + defer c.PageToken(c.urlParams_.Get("pageToken")) + for { + x, err := c.Do() + if err != nil { + return err + } + if err := f(x); err != nil { + return err + } + if x.NextPageToken == "" { + return nil + } + c.PageToken(x.NextPageToken) + } +} + +type MediaUploadCall struct { + s *Service + createfilerequest *CreateFileRequest + urlParams_ gensupport.URLParams + mediaInfo_ *gensupport.MediaInfo + ctx_ context.Context + header_ http.Header +} + +// Upload: Creates a `File`. +func (r *MediaService) Upload(createfilerequest *CreateFileRequest) *MediaUploadCall { + c := &MediaUploadCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.createfilerequest = createfilerequest + return c +} + +// Media specifies the media to upload in one or more chunks. The chunk size +// may be controlled by supplying a MediaOption generated by +// googleapi.ChunkSize. The chunk size defaults to +// googleapi.DefaultUploadChunkSize.The Content-Type header used in the upload +// request will be determined by sniffing the contents of r, unless a +// MediaOption generated by googleapi.ContentType is supplied. +// At most one of Media and ResumableMedia may be set. +func (c *MediaUploadCall) Media(r io.Reader, options ...googleapi.MediaOption) *MediaUploadCall { + c.mediaInfo_ = gensupport.NewInfoFromMedia(r, options) + return c +} + +// ResumableMedia specifies the media to upload in chunks and can be canceled +// with ctx. +// +// Deprecated: use Media instead. +// +// At most one of Media and ResumableMedia may be set. mediaType identifies the +// MIME media type of the upload, such as "image/png". If mediaType is "", it +// will be auto-detected. The provided ctx will supersede any context +// previously provided to the Context method. +func (c *MediaUploadCall) ResumableMedia(ctx context.Context, r io.ReaderAt, size int64, mediaType string) *MediaUploadCall { + c.ctx_ = ctx + c.mediaInfo_ = gensupport.NewInfoFromResumableMedia(r, size, mediaType) + return c +} + +// ProgressUpdater provides a callback function that will be called after every +// chunk. It should be a low-latency function in order to not slow down the +// upload operation. This should only be called when using ResumableMedia (as +// opposed to Media). +func (c *MediaUploadCall) ProgressUpdater(pu googleapi.ProgressUpdater) *MediaUploadCall { + c.mediaInfo_.SetProgressUpdater(pu) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *MediaUploadCall) Fields(s ...googleapi.Field) *MediaUploadCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. +// This context will supersede any context previously provided to the +// ResumableMedia method. +func (c *MediaUploadCall) Context(ctx context.Context) *MediaUploadCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *MediaUploadCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *MediaUploadCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "application/json", c.header_) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.createfilerequest) + if err != nil { + return nil, err + } + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/files") + if c.mediaInfo_ != nil { + urls = googleapi.ResolveRelative(c.s.BasePath, "/upload/v1beta/files") + c.urlParams_.Set("uploadType", c.mediaInfo_.UploadType()) + } + if body == nil { + body = new(bytes.Buffer) + reqHeaders.Set("Content-Type", "application/json") + } + body, getBody, cleanup := c.mediaInfo_.UploadRequest(reqHeaders, body) + defer cleanup() + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + req.GetBody = getBody + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.media.upload" call. +// Any non-2xx status code is an error. Response headers are in either +// *CreateFileResponse.ServerResponse.Header or (if a response was returned at +// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified was +// returned. +func (c *MediaUploadCall) Do(opts ...googleapi.CallOption) (*CreateFileResponse, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + rx := c.mediaInfo_.ResumableUpload(res.Header.Get("Location")) + if rx != nil { + rx.Client = c.s.client + rx.UserAgent = c.s.userAgent() + ctx := c.ctx_ + if ctx == nil { + ctx = context.TODO() + } + res, err = rx.Upload(ctx) + if err != nil { + return nil, err + } + defer res.Body.Close() + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + } + ret := &CreateFileResponse{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +type ModelsBatchEmbedContentsCall struct { + s *Service + model string + batchembedcontentsrequest *BatchEmbedContentsRequest + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// BatchEmbedContents: Generates multiple embeddings from the model given input +// text in a synchronous call. +// +// - model: The model's resource name. This serves as an ID for the Model to +// use. This name should match a model name returned by the `ListModels` +// method. Format: `models/{model}`. +func (r *ModelsService) BatchEmbedContents(model string, batchembedcontentsrequest *BatchEmbedContentsRequest) *ModelsBatchEmbedContentsCall { + c := &ModelsBatchEmbedContentsCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.model = model + c.batchembedcontentsrequest = batchembedcontentsrequest + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *ModelsBatchEmbedContentsCall) Fields(s ...googleapi.Field) *ModelsBatchEmbedContentsCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *ModelsBatchEmbedContentsCall) Context(ctx context.Context) *ModelsBatchEmbedContentsCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *ModelsBatchEmbedContentsCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *ModelsBatchEmbedContentsCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "application/json", c.header_) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.batchembedcontentsrequest) + if err != nil { + return nil, err + } + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+model}:batchEmbedContents") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "model": c.model, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.models.batchEmbedContents" call. +// Any non-2xx status code is an error. Response headers are in either +// *BatchEmbedContentsResponse.ServerResponse.Header or (if a response was +// returned at all) in error.(*googleapi.Error).Header. Use +// googleapi.IsNotModified to check whether the returned error was because +// http.StatusNotModified was returned. +func (c *ModelsBatchEmbedContentsCall) Do(opts ...googleapi.CallOption) (*BatchEmbedContentsResponse, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &BatchEmbedContentsResponse{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +type ModelsBatchEmbedTextCall struct { + s *Service + model string + batchembedtextrequest *BatchEmbedTextRequest + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// BatchEmbedText: Generates multiple embeddings from the model given input +// text in a synchronous call. +// +// - model: The name of the `Model` to use for generating the embedding. +// Examples: models/embedding-gecko-001. +func (r *ModelsService) BatchEmbedText(model string, batchembedtextrequest *BatchEmbedTextRequest) *ModelsBatchEmbedTextCall { + c := &ModelsBatchEmbedTextCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.model = model + c.batchembedtextrequest = batchembedtextrequest + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *ModelsBatchEmbedTextCall) Fields(s ...googleapi.Field) *ModelsBatchEmbedTextCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *ModelsBatchEmbedTextCall) Context(ctx context.Context) *ModelsBatchEmbedTextCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *ModelsBatchEmbedTextCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *ModelsBatchEmbedTextCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "application/json", c.header_) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.batchembedtextrequest) + if err != nil { + return nil, err + } + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+model}:batchEmbedText") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "model": c.model, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.models.batchEmbedText" call. +// Any non-2xx status code is an error. Response headers are in either +// *BatchEmbedTextResponse.ServerResponse.Header or (if a response was returned +// at all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified was +// returned. +func (c *ModelsBatchEmbedTextCall) Do(opts ...googleapi.CallOption) (*BatchEmbedTextResponse, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &BatchEmbedTextResponse{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +type ModelsCountMessageTokensCall struct { + s *Service + model string + countmessagetokensrequest *CountMessageTokensRequest + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// CountMessageTokens: Runs a model's tokenizer on a string and returns the +// token count. +// +// - model: The model's resource name. This serves as an ID for the Model to +// use. This name should match a model name returned by the `ListModels` +// method. Format: `models/{model}`. +func (r *ModelsService) CountMessageTokens(model string, countmessagetokensrequest *CountMessageTokensRequest) *ModelsCountMessageTokensCall { + c := &ModelsCountMessageTokensCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.model = model + c.countmessagetokensrequest = countmessagetokensrequest + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *ModelsCountMessageTokensCall) Fields(s ...googleapi.Field) *ModelsCountMessageTokensCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *ModelsCountMessageTokensCall) Context(ctx context.Context) *ModelsCountMessageTokensCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *ModelsCountMessageTokensCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *ModelsCountMessageTokensCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "application/json", c.header_) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.countmessagetokensrequest) + if err != nil { + return nil, err + } + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+model}:countMessageTokens") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "model": c.model, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.models.countMessageTokens" call. +// Any non-2xx status code is an error. Response headers are in either +// *CountMessageTokensResponse.ServerResponse.Header or (if a response was +// returned at all) in error.(*googleapi.Error).Header. Use +// googleapi.IsNotModified to check whether the returned error was because +// http.StatusNotModified was returned. +func (c *ModelsCountMessageTokensCall) Do(opts ...googleapi.CallOption) (*CountMessageTokensResponse, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &CountMessageTokensResponse{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +type ModelsCountTextTokensCall struct { + s *Service + model string + counttexttokensrequest *CountTextTokensRequest + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// CountTextTokens: Runs a model's tokenizer on a text and returns the token +// count. +// +// - model: The model's resource name. This serves as an ID for the Model to +// use. This name should match a model name returned by the `ListModels` +// method. Format: `models/{model}`. +func (r *ModelsService) CountTextTokens(model string, counttexttokensrequest *CountTextTokensRequest) *ModelsCountTextTokensCall { + c := &ModelsCountTextTokensCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.model = model + c.counttexttokensrequest = counttexttokensrequest + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *ModelsCountTextTokensCall) Fields(s ...googleapi.Field) *ModelsCountTextTokensCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *ModelsCountTextTokensCall) Context(ctx context.Context) *ModelsCountTextTokensCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *ModelsCountTextTokensCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *ModelsCountTextTokensCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "application/json", c.header_) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.counttexttokensrequest) + if err != nil { + return nil, err + } + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+model}:countTextTokens") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "model": c.model, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.models.countTextTokens" call. +// Any non-2xx status code is an error. Response headers are in either +// *CountTextTokensResponse.ServerResponse.Header or (if a response was +// returned at all) in error.(*googleapi.Error).Header. Use +// googleapi.IsNotModified to check whether the returned error was because +// http.StatusNotModified was returned. +func (c *ModelsCountTextTokensCall) Do(opts ...googleapi.CallOption) (*CountTextTokensResponse, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &CountTextTokensResponse{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +type ModelsCountTokensCall struct { + s *Service + model string + counttokensrequest *CountTokensRequest + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// CountTokens: Runs a model's tokenizer on input content and returns the token +// count. +// +// - model: The model's resource name. This serves as an ID for the Model to +// use. This name should match a model name returned by the `ListModels` +// method. Format: `models/{model}`. +func (r *ModelsService) CountTokens(model string, counttokensrequest *CountTokensRequest) *ModelsCountTokensCall { + c := &ModelsCountTokensCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.model = model + c.counttokensrequest = counttokensrequest + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *ModelsCountTokensCall) Fields(s ...googleapi.Field) *ModelsCountTokensCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *ModelsCountTokensCall) Context(ctx context.Context) *ModelsCountTokensCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *ModelsCountTokensCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *ModelsCountTokensCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "application/json", c.header_) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.counttokensrequest) + if err != nil { + return nil, err + } + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+model}:countTokens") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "model": c.model, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.models.countTokens" call. +// Any non-2xx status code is an error. Response headers are in either +// *CountTokensResponse.ServerResponse.Header or (if a response was returned at +// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified was +// returned. +func (c *ModelsCountTokensCall) Do(opts ...googleapi.CallOption) (*CountTokensResponse, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &CountTokensResponse{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +type ModelsEmbedContentCall struct { + s *Service + model string + embedcontentrequest *EmbedContentRequest + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// EmbedContent: Generates an embedding from the model given an input +// `Content`. +// +// - model: The model's resource name. This serves as an ID for the Model to +// use. This name should match a model name returned by the `ListModels` +// method. Format: `models/{model}`. +func (r *ModelsService) EmbedContent(model string, embedcontentrequest *EmbedContentRequest) *ModelsEmbedContentCall { + c := &ModelsEmbedContentCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.model = model + c.embedcontentrequest = embedcontentrequest + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *ModelsEmbedContentCall) Fields(s ...googleapi.Field) *ModelsEmbedContentCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *ModelsEmbedContentCall) Context(ctx context.Context) *ModelsEmbedContentCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *ModelsEmbedContentCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *ModelsEmbedContentCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "application/json", c.header_) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.embedcontentrequest) + if err != nil { + return nil, err + } + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+model}:embedContent") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "model": c.model, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.models.embedContent" call. +// Any non-2xx status code is an error. Response headers are in either +// *EmbedContentResponse.ServerResponse.Header or (if a response was returned +// at all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified was +// returned. +func (c *ModelsEmbedContentCall) Do(opts ...googleapi.CallOption) (*EmbedContentResponse, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &EmbedContentResponse{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +type ModelsEmbedTextCall struct { + s *Service + model string + embedtextrequest *EmbedTextRequest + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// EmbedText: Generates an embedding from the model given an input message. +// +// - model: The model name to use with the format model=models/{model}. +func (r *ModelsService) EmbedText(model string, embedtextrequest *EmbedTextRequest) *ModelsEmbedTextCall { + c := &ModelsEmbedTextCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.model = model + c.embedtextrequest = embedtextrequest + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *ModelsEmbedTextCall) Fields(s ...googleapi.Field) *ModelsEmbedTextCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *ModelsEmbedTextCall) Context(ctx context.Context) *ModelsEmbedTextCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *ModelsEmbedTextCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *ModelsEmbedTextCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "application/json", c.header_) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.embedtextrequest) + if err != nil { + return nil, err + } + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+model}:embedText") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "model": c.model, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.models.embedText" call. +// Any non-2xx status code is an error. Response headers are in either +// *EmbedTextResponse.ServerResponse.Header or (if a response was returned at +// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified was +// returned. +func (c *ModelsEmbedTextCall) Do(opts ...googleapi.CallOption) (*EmbedTextResponse, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &EmbedTextResponse{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +type ModelsGenerateAnswerCall struct { + s *Service + model string + generateanswerrequest *GenerateAnswerRequest + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// GenerateAnswer: Generates a grounded answer from the model given an input +// `GenerateAnswerRequest`. +// +// - model: The name of the `Model` to use for generating the grounded +// response. Format: `model=models/{model}`. +func (r *ModelsService) GenerateAnswer(model string, generateanswerrequest *GenerateAnswerRequest) *ModelsGenerateAnswerCall { + c := &ModelsGenerateAnswerCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.model = model + c.generateanswerrequest = generateanswerrequest + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *ModelsGenerateAnswerCall) Fields(s ...googleapi.Field) *ModelsGenerateAnswerCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *ModelsGenerateAnswerCall) Context(ctx context.Context) *ModelsGenerateAnswerCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *ModelsGenerateAnswerCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *ModelsGenerateAnswerCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "application/json", c.header_) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.generateanswerrequest) + if err != nil { + return nil, err + } + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+model}:generateAnswer") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "model": c.model, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.models.generateAnswer" call. +// Any non-2xx status code is an error. Response headers are in either +// *GenerateAnswerResponse.ServerResponse.Header or (if a response was returned +// at all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified was +// returned. +func (c *ModelsGenerateAnswerCall) Do(opts ...googleapi.CallOption) (*GenerateAnswerResponse, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &GenerateAnswerResponse{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +type ModelsGenerateContentCall struct { + s *Service + model string + generatecontentrequest *GenerateContentRequest + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// GenerateContent: Generates a response from the model given an input +// `GenerateContentRequest`. Input capabilities differ between models, +// including tuned models. See the model guide +// (https://ai.google.dev/models/gemini) and tuning guide +// (https://ai.google.dev/docs/model_tuning_guidance) for details. +// +// - model: The name of the `Model` to use for generating the completion. +// Format: `name=models/{model}`. +func (r *ModelsService) GenerateContent(model string, generatecontentrequest *GenerateContentRequest) *ModelsGenerateContentCall { + c := &ModelsGenerateContentCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.model = model + c.generatecontentrequest = generatecontentrequest + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *ModelsGenerateContentCall) Fields(s ...googleapi.Field) *ModelsGenerateContentCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *ModelsGenerateContentCall) Context(ctx context.Context) *ModelsGenerateContentCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *ModelsGenerateContentCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *ModelsGenerateContentCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "application/json", c.header_) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.generatecontentrequest) + if err != nil { + return nil, err + } + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+model}:generateContent") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "model": c.model, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.models.generateContent" call. +// Any non-2xx status code is an error. Response headers are in either +// *GenerateContentResponse.ServerResponse.Header or (if a response was +// returned at all) in error.(*googleapi.Error).Header. Use +// googleapi.IsNotModified to check whether the returned error was because +// http.StatusNotModified was returned. +func (c *ModelsGenerateContentCall) Do(opts ...googleapi.CallOption) (*GenerateContentResponse, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &GenerateContentResponse{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +type ModelsGenerateMessageCall struct { + s *Service + model string + generatemessagerequest *GenerateMessageRequest + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// GenerateMessage: Generates a response from the model given an input +// `MessagePrompt`. +// +// - model: The name of the model to use. Format: `name=models/{model}`. +func (r *ModelsService) GenerateMessage(model string, generatemessagerequest *GenerateMessageRequest) *ModelsGenerateMessageCall { + c := &ModelsGenerateMessageCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.model = model + c.generatemessagerequest = generatemessagerequest + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *ModelsGenerateMessageCall) Fields(s ...googleapi.Field) *ModelsGenerateMessageCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *ModelsGenerateMessageCall) Context(ctx context.Context) *ModelsGenerateMessageCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *ModelsGenerateMessageCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *ModelsGenerateMessageCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "application/json", c.header_) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.generatemessagerequest) + if err != nil { + return nil, err + } + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+model}:generateMessage") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "model": c.model, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.models.generateMessage" call. +// Any non-2xx status code is an error. Response headers are in either +// *GenerateMessageResponse.ServerResponse.Header or (if a response was +// returned at all) in error.(*googleapi.Error).Header. Use +// googleapi.IsNotModified to check whether the returned error was because +// http.StatusNotModified was returned. +func (c *ModelsGenerateMessageCall) Do(opts ...googleapi.CallOption) (*GenerateMessageResponse, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &GenerateMessageResponse{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +type ModelsGenerateTextCall struct { + s *Service + model string + generatetextrequest *GenerateTextRequest + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// GenerateText: Generates a response from the model given an input message. +// +// - model: The name of the `Model` or `TunedModel` to use for generating the +// completion. Examples: models/text-bison-001 +// tunedModels/sentence-translator-u3b7m. +func (r *ModelsService) GenerateText(model string, generatetextrequest *GenerateTextRequest) *ModelsGenerateTextCall { + c := &ModelsGenerateTextCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.model = model + c.generatetextrequest = generatetextrequest + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *ModelsGenerateTextCall) Fields(s ...googleapi.Field) *ModelsGenerateTextCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *ModelsGenerateTextCall) Context(ctx context.Context) *ModelsGenerateTextCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *ModelsGenerateTextCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *ModelsGenerateTextCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "application/json", c.header_) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.generatetextrequest) + if err != nil { + return nil, err + } + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+model}:generateText") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "model": c.model, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.models.generateText" call. +// Any non-2xx status code is an error. Response headers are in either +// *GenerateTextResponse.ServerResponse.Header or (if a response was returned +// at all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified was +// returned. +func (c *ModelsGenerateTextCall) Do(opts ...googleapi.CallOption) (*GenerateTextResponse, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &GenerateTextResponse{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +type ModelsGetCall struct { + s *Service + name string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// Get: Gets information about a specific Model. +// +// - name: The resource name of the model. This name should match a model name +// returned by the `ListModels` method. Format: `models/{model}`. +func (r *ModelsService) Get(name string) *ModelsGetCall { + c := &ModelsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.name = name + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *ModelsGetCall) Fields(s ...googleapi.Field) *ModelsGetCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets an optional parameter which makes the operation fail if the +// object's ETag matches the given value. This is useful for getting updates +// only after the object has changed since the last request. +func (c *ModelsGetCall) IfNoneMatch(entityTag string) *ModelsGetCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *ModelsGetCall) Context(ctx context.Context) *ModelsGetCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *ModelsGetCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *ModelsGetCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "", c.header_) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+name}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "name": c.name, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.models.get" call. +// Any non-2xx status code is an error. Response headers are in either +// *Model.ServerResponse.Header or (if a response was returned at all) in +// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check +// whether the returned error was because http.StatusNotModified was returned. +func (c *ModelsGetCall) Do(opts ...googleapi.CallOption) (*Model, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &Model{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +type ModelsListCall struct { + s *Service + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// List: Lists models available through the API. +func (r *ModelsService) List() *ModelsListCall { + c := &ModelsListCall{s: r.s, urlParams_: make(gensupport.URLParams)} + return c +} + +// PageSize sets the optional parameter "pageSize": The maximum number of +// `Models` to return (per page). The service may return fewer models. If +// unspecified, at most 50 models will be returned per page. This method +// returns at most 1000 models per page, even if you pass a larger page_size. +func (c *ModelsListCall) PageSize(pageSize int64) *ModelsListCall { + c.urlParams_.Set("pageSize", fmt.Sprint(pageSize)) + return c +} + +// PageToken sets the optional parameter "pageToken": A page token, received +// from a previous `ListModels` call. Provide the `page_token` returned by one +// request as an argument to the next request to retrieve the next page. When +// paginating, all other parameters provided to `ListModels` must match the +// call that provided the page token. +func (c *ModelsListCall) PageToken(pageToken string) *ModelsListCall { + c.urlParams_.Set("pageToken", pageToken) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *ModelsListCall) Fields(s ...googleapi.Field) *ModelsListCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets an optional parameter which makes the operation fail if the +// object's ETag matches the given value. This is useful for getting updates +// only after the object has changed since the last request. +func (c *ModelsListCall) IfNoneMatch(entityTag string) *ModelsListCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *ModelsListCall) Context(ctx context.Context) *ModelsListCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *ModelsListCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *ModelsListCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "", c.header_) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/models") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.models.list" call. +// Any non-2xx status code is an error. Response headers are in either +// *ListModelsResponse.ServerResponse.Header or (if a response was returned at +// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified was +// returned. +func (c *ModelsListCall) Do(opts ...googleapi.CallOption) (*ListModelsResponse, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &ListModelsResponse{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +// Pages invokes f for each page of results. +// A non-nil error returned from f will halt the iteration. +// The provided context supersedes any context provided to the Context method. +func (c *ModelsListCall) Pages(ctx context.Context, f func(*ListModelsResponse) error) error { + c.ctx_ = ctx + defer c.PageToken(c.urlParams_.Get("pageToken")) + for { + x, err := c.Do() + if err != nil { + return err + } + if err := f(x); err != nil { + return err + } + if x.NextPageToken == "" { + return nil + } + c.PageToken(x.NextPageToken) + } +} + +type ModelsStreamGenerateContentCall struct { + s *Service + model string + generatecontentrequest *GenerateContentRequest + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// StreamGenerateContent: Generates a streamed response from the model given an +// input `GenerateContentRequest`. +// +// - model: The name of the `Model` to use for generating the completion. +// Format: `name=models/{model}`. +func (r *ModelsService) StreamGenerateContent(model string, generatecontentrequest *GenerateContentRequest) *ModelsStreamGenerateContentCall { + c := &ModelsStreamGenerateContentCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.model = model + c.generatecontentrequest = generatecontentrequest + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *ModelsStreamGenerateContentCall) Fields(s ...googleapi.Field) *ModelsStreamGenerateContentCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *ModelsStreamGenerateContentCall) Context(ctx context.Context) *ModelsStreamGenerateContentCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *ModelsStreamGenerateContentCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *ModelsStreamGenerateContentCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "application/json", c.header_) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.generatecontentrequest) + if err != nil { + return nil, err + } + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+model}:streamGenerateContent") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "model": c.model, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.models.streamGenerateContent" call. +// Any non-2xx status code is an error. Response headers are in either +// *GenerateContentResponse.ServerResponse.Header or (if a response was +// returned at all) in error.(*googleapi.Error).Header. Use +// googleapi.IsNotModified to check whether the returned error was because +// http.StatusNotModified was returned. +func (c *ModelsStreamGenerateContentCall) Do(opts ...googleapi.CallOption) (*GenerateContentResponse, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &GenerateContentResponse{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +type TunedModelsCreateCall struct { + s *Service + tunedmodel *TunedModel + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Create: Creates a tuned model. Intermediate tuning progress (if any) is +// accessed through the [google.longrunning.Operations] service. Status and +// results can be accessed through the Operations service. Example: GET +// /v1/tunedModels/az2mb0bpw6i/operations/000-111-222 +func (r *TunedModelsService) Create(tunedmodel *TunedModel) *TunedModelsCreateCall { + c := &TunedModelsCreateCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.tunedmodel = tunedmodel + return c +} + +// TunedModelId sets the optional parameter "tunedModelId": The unique id for +// the tuned model if specified. This value should be up to 40 characters, the +// first character must be a letter, the last could be a letter or a number. +// The id must match the regular expression: a-z ([a-z0-9-]{0,38}[a-z0-9])?. +func (c *TunedModelsCreateCall) TunedModelId(tunedModelId string) *TunedModelsCreateCall { + c.urlParams_.Set("tunedModelId", tunedModelId) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *TunedModelsCreateCall) Fields(s ...googleapi.Field) *TunedModelsCreateCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *TunedModelsCreateCall) Context(ctx context.Context) *TunedModelsCreateCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *TunedModelsCreateCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *TunedModelsCreateCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "application/json", c.header_) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.tunedmodel) + if err != nil { + return nil, err + } + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/tunedModels") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.tunedModels.create" call. +// Any non-2xx status code is an error. Response headers are in either +// *Operation.ServerResponse.Header or (if a response was returned at all) in +// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check +// whether the returned error was because http.StatusNotModified was returned. +func (c *TunedModelsCreateCall) Do(opts ...googleapi.CallOption) (*Operation, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &Operation{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +type TunedModelsDeleteCall struct { + s *Service + name string + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Delete: Deletes a tuned model. +// +// - name: The resource name of the model. Format: `tunedModels/my-model-id`. +func (r *TunedModelsService) Delete(name string) *TunedModelsDeleteCall { + c := &TunedModelsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.name = name + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *TunedModelsDeleteCall) Fields(s ...googleapi.Field) *TunedModelsDeleteCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *TunedModelsDeleteCall) Context(ctx context.Context) *TunedModelsDeleteCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *TunedModelsDeleteCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *TunedModelsDeleteCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "", c.header_) + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+name}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("DELETE", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "name": c.name, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.tunedModels.delete" call. +// Any non-2xx status code is an error. Response headers are in either +// *Empty.ServerResponse.Header or (if a response was returned at all) in +// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check +// whether the returned error was because http.StatusNotModified was returned. +func (c *TunedModelsDeleteCall) Do(opts ...googleapi.CallOption) (*Empty, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &Empty{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +type TunedModelsGenerateContentCall struct { + s *Service + model string + generatecontentrequest *GenerateContentRequest + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// GenerateContent: Generates a response from the model given an input +// `GenerateContentRequest`. Input capabilities differ between models, +// including tuned models. See the model guide +// (https://ai.google.dev/models/gemini) and tuning guide +// (https://ai.google.dev/docs/model_tuning_guidance) for details. +// +// - model: The name of the `Model` to use for generating the completion. +// Format: `name=models/{model}`. +func (r *TunedModelsService) GenerateContent(model string, generatecontentrequest *GenerateContentRequest) *TunedModelsGenerateContentCall { + c := &TunedModelsGenerateContentCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.model = model + c.generatecontentrequest = generatecontentrequest + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *TunedModelsGenerateContentCall) Fields(s ...googleapi.Field) *TunedModelsGenerateContentCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *TunedModelsGenerateContentCall) Context(ctx context.Context) *TunedModelsGenerateContentCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *TunedModelsGenerateContentCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *TunedModelsGenerateContentCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "application/json", c.header_) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.generatecontentrequest) + if err != nil { + return nil, err + } + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+model}:generateContent") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "model": c.model, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.tunedModels.generateContent" call. +// Any non-2xx status code is an error. Response headers are in either +// *GenerateContentResponse.ServerResponse.Header or (if a response was +// returned at all) in error.(*googleapi.Error).Header. Use +// googleapi.IsNotModified to check whether the returned error was because +// http.StatusNotModified was returned. +func (c *TunedModelsGenerateContentCall) Do(opts ...googleapi.CallOption) (*GenerateContentResponse, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &GenerateContentResponse{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +type TunedModelsGenerateTextCall struct { + s *Service + model string + generatetextrequest *GenerateTextRequest + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// GenerateText: Generates a response from the model given an input message. +// +// - model: The name of the `Model` or `TunedModel` to use for generating the +// completion. Examples: models/text-bison-001 +// tunedModels/sentence-translator-u3b7m. +func (r *TunedModelsService) GenerateText(model string, generatetextrequest *GenerateTextRequest) *TunedModelsGenerateTextCall { + c := &TunedModelsGenerateTextCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.model = model + c.generatetextrequest = generatetextrequest + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *TunedModelsGenerateTextCall) Fields(s ...googleapi.Field) *TunedModelsGenerateTextCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *TunedModelsGenerateTextCall) Context(ctx context.Context) *TunedModelsGenerateTextCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *TunedModelsGenerateTextCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *TunedModelsGenerateTextCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "application/json", c.header_) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.generatetextrequest) + if err != nil { + return nil, err + } + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+model}:generateText") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "model": c.model, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.tunedModels.generateText" call. +// Any non-2xx status code is an error. Response headers are in either +// *GenerateTextResponse.ServerResponse.Header or (if a response was returned +// at all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to +// check whether the returned error was because http.StatusNotModified was +// returned. +func (c *TunedModelsGenerateTextCall) Do(opts ...googleapi.CallOption) (*GenerateTextResponse, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &GenerateTextResponse{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +type TunedModelsGetCall struct { + s *Service + name string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// Get: Gets information about a specific TunedModel. +// +// - name: The resource name of the model. Format: `tunedModels/my-model-id`. +func (r *TunedModelsService) Get(name string) *TunedModelsGetCall { + c := &TunedModelsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.name = name + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *TunedModelsGetCall) Fields(s ...googleapi.Field) *TunedModelsGetCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets an optional parameter which makes the operation fail if the +// object's ETag matches the given value. This is useful for getting updates +// only after the object has changed since the last request. +func (c *TunedModelsGetCall) IfNoneMatch(entityTag string) *TunedModelsGetCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *TunedModelsGetCall) Context(ctx context.Context) *TunedModelsGetCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *TunedModelsGetCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *TunedModelsGetCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "", c.header_) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+name}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "name": c.name, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.tunedModels.get" call. +// Any non-2xx status code is an error. Response headers are in either +// *TunedModel.ServerResponse.Header or (if a response was returned at all) in +// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check +// whether the returned error was because http.StatusNotModified was returned. +func (c *TunedModelsGetCall) Do(opts ...googleapi.CallOption) (*TunedModel, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &TunedModel{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +type TunedModelsListCall struct { + s *Service + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// List: Lists tuned models owned by the user. +func (r *TunedModelsService) List() *TunedModelsListCall { + c := &TunedModelsListCall{s: r.s, urlParams_: make(gensupport.URLParams)} + return c +} + +// Filter sets the optional parameter "filter": A filter is a full text search +// over the tuned model's description and display name. By default, results +// will not include tuned models shared with everyone. Additional operators: - +// owner:me - writers:me - readers:me - readers:everyone Examples: "owner:me" +// returns all tuned models to which caller has owner role "readers:me" returns +// all tuned models to which caller has reader role "readers:everyone" returns +// all tuned models that are shared with everyone +func (c *TunedModelsListCall) Filter(filter string) *TunedModelsListCall { + c.urlParams_.Set("filter", filter) + return c +} + +// PageSize sets the optional parameter "pageSize": The maximum number of +// `TunedModels` to return (per page). The service may return fewer tuned +// models. If unspecified, at most 10 tuned models will be returned. This +// method returns at most 1000 models per page, even if you pass a larger +// page_size. +func (c *TunedModelsListCall) PageSize(pageSize int64) *TunedModelsListCall { + c.urlParams_.Set("pageSize", fmt.Sprint(pageSize)) + return c +} + +// PageToken sets the optional parameter "pageToken": A page token, received +// from a previous `ListTunedModels` call. Provide the `page_token` returned by +// one request as an argument to the next request to retrieve the next page. +// When paginating, all other parameters provided to `ListTunedModels` must +// match the call that provided the page token. +func (c *TunedModelsListCall) PageToken(pageToken string) *TunedModelsListCall { + c.urlParams_.Set("pageToken", pageToken) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *TunedModelsListCall) Fields(s ...googleapi.Field) *TunedModelsListCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets an optional parameter which makes the operation fail if the +// object's ETag matches the given value. This is useful for getting updates +// only after the object has changed since the last request. +func (c *TunedModelsListCall) IfNoneMatch(entityTag string) *TunedModelsListCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *TunedModelsListCall) Context(ctx context.Context) *TunedModelsListCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *TunedModelsListCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *TunedModelsListCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "", c.header_) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/tunedModels") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.tunedModels.list" call. +// Any non-2xx status code is an error. Response headers are in either +// *ListTunedModelsResponse.ServerResponse.Header or (if a response was +// returned at all) in error.(*googleapi.Error).Header. Use +// googleapi.IsNotModified to check whether the returned error was because +// http.StatusNotModified was returned. +func (c *TunedModelsListCall) Do(opts ...googleapi.CallOption) (*ListTunedModelsResponse, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &ListTunedModelsResponse{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +// Pages invokes f for each page of results. +// A non-nil error returned from f will halt the iteration. +// The provided context supersedes any context provided to the Context method. +func (c *TunedModelsListCall) Pages(ctx context.Context, f func(*ListTunedModelsResponse) error) error { + c.ctx_ = ctx + defer c.PageToken(c.urlParams_.Get("pageToken")) + for { + x, err := c.Do() + if err != nil { + return err + } + if err := f(x); err != nil { + return err + } + if x.NextPageToken == "" { + return nil + } + c.PageToken(x.NextPageToken) + } +} + +type TunedModelsPatchCall struct { + s *Service + name string + tunedmodel *TunedModel + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Patch: Updates a tuned model. +// +// - name: Output only. The tuned model name. A unique name will be generated +// on create. Example: `tunedModels/az2mb0bpw6i` If display_name is set on +// create, the id portion of the name will be set by concatenating the words +// of the display_name with hyphens and adding a random portion for +// uniqueness. Example: display_name = "Sentence Translator" name = +// "tunedModels/sentence-translator-u3b7m". +func (r *TunedModelsService) Patch(name string, tunedmodel *TunedModel) *TunedModelsPatchCall { + c := &TunedModelsPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.name = name + c.tunedmodel = tunedmodel + return c +} + +// UpdateMask sets the optional parameter "updateMask": Required. The list of +// fields to update. +func (c *TunedModelsPatchCall) UpdateMask(updateMask string) *TunedModelsPatchCall { + c.urlParams_.Set("updateMask", updateMask) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *TunedModelsPatchCall) Fields(s ...googleapi.Field) *TunedModelsPatchCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *TunedModelsPatchCall) Context(ctx context.Context) *TunedModelsPatchCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *TunedModelsPatchCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *TunedModelsPatchCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "application/json", c.header_) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.tunedmodel) + if err != nil { + return nil, err + } + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+name}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("PATCH", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "name": c.name, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.tunedModels.patch" call. +// Any non-2xx status code is an error. Response headers are in either +// *TunedModel.ServerResponse.Header or (if a response was returned at all) in +// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check +// whether the returned error was because http.StatusNotModified was returned. +func (c *TunedModelsPatchCall) Do(opts ...googleapi.CallOption) (*TunedModel, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &TunedModel{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +type TunedModelsTransferOwnershipCall struct { + s *Service + name string + transferownershiprequest *TransferOwnershipRequest + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// TransferOwnership: Transfers ownership of the tuned model. This is the only +// way to change ownership of the tuned model. The current owner will be +// downgraded to writer role. +// +// - name: The resource name of the tuned model to transfer ownership. Format: +// `tunedModels/my-model-id`. +func (r *TunedModelsService) TransferOwnership(name string, transferownershiprequest *TransferOwnershipRequest) *TunedModelsTransferOwnershipCall { + c := &TunedModelsTransferOwnershipCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.name = name + c.transferownershiprequest = transferownershiprequest + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *TunedModelsTransferOwnershipCall) Fields(s ...googleapi.Field) *TunedModelsTransferOwnershipCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *TunedModelsTransferOwnershipCall) Context(ctx context.Context) *TunedModelsTransferOwnershipCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *TunedModelsTransferOwnershipCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *TunedModelsTransferOwnershipCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "application/json", c.header_) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.transferownershiprequest) + if err != nil { + return nil, err + } + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+name}:transferOwnership") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "name": c.name, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.tunedModels.transferOwnership" call. +// Any non-2xx status code is an error. Response headers are in either +// *TransferOwnershipResponse.ServerResponse.Header or (if a response was +// returned at all) in error.(*googleapi.Error).Header. Use +// googleapi.IsNotModified to check whether the returned error was because +// http.StatusNotModified was returned. +func (c *TunedModelsTransferOwnershipCall) Do(opts ...googleapi.CallOption) (*TransferOwnershipResponse, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &TransferOwnershipResponse{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +type TunedModelsPermissionsCreateCall struct { + s *Service + parent string + permission *Permission + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Create: Create a permission to a specific resource. +// +// - parent: The parent resource of the `Permission`. Formats: +// `tunedModels/{tuned_model}` `corpora/{corpus}`. +func (r *TunedModelsPermissionsService) Create(parent string, permission *Permission) *TunedModelsPermissionsCreateCall { + c := &TunedModelsPermissionsCreateCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.parent = parent + c.permission = permission + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *TunedModelsPermissionsCreateCall) Fields(s ...googleapi.Field) *TunedModelsPermissionsCreateCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *TunedModelsPermissionsCreateCall) Context(ctx context.Context) *TunedModelsPermissionsCreateCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *TunedModelsPermissionsCreateCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *TunedModelsPermissionsCreateCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "application/json", c.header_) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.permission) + if err != nil { + return nil, err + } + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+parent}/permissions") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("POST", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "parent": c.parent, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.tunedModels.permissions.create" call. +// Any non-2xx status code is an error. Response headers are in either +// *Permission.ServerResponse.Header or (if a response was returned at all) in +// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check +// whether the returned error was because http.StatusNotModified was returned. +func (c *TunedModelsPermissionsCreateCall) Do(opts ...googleapi.CallOption) (*Permission, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &Permission{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +type TunedModelsPermissionsDeleteCall struct { + s *Service + name string + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Delete: Deletes the permission. +// +// - name: The resource name of the permission. Formats: +// `tunedModels/{tuned_model}/permissions/{permission}` +// `corpora/{corpus}/permissions/{permission}`. +func (r *TunedModelsPermissionsService) Delete(name string) *TunedModelsPermissionsDeleteCall { + c := &TunedModelsPermissionsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.name = name + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *TunedModelsPermissionsDeleteCall) Fields(s ...googleapi.Field) *TunedModelsPermissionsDeleteCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *TunedModelsPermissionsDeleteCall) Context(ctx context.Context) *TunedModelsPermissionsDeleteCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *TunedModelsPermissionsDeleteCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *TunedModelsPermissionsDeleteCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "", c.header_) + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+name}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("DELETE", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "name": c.name, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.tunedModels.permissions.delete" call. +// Any non-2xx status code is an error. Response headers are in either +// *Empty.ServerResponse.Header or (if a response was returned at all) in +// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check +// whether the returned error was because http.StatusNotModified was returned. +func (c *TunedModelsPermissionsDeleteCall) Do(opts ...googleapi.CallOption) (*Empty, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &Empty{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +type TunedModelsPermissionsGetCall struct { + s *Service + name string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// Get: Gets information about a specific Permission. +// +// - name: The resource name of the permission. Formats: +// `tunedModels/{tuned_model}/permissions/{permission}` +// `corpora/{corpus}/permissions/{permission}`. +func (r *TunedModelsPermissionsService) Get(name string) *TunedModelsPermissionsGetCall { + c := &TunedModelsPermissionsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.name = name + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *TunedModelsPermissionsGetCall) Fields(s ...googleapi.Field) *TunedModelsPermissionsGetCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets an optional parameter which makes the operation fail if the +// object's ETag matches the given value. This is useful for getting updates +// only after the object has changed since the last request. +func (c *TunedModelsPermissionsGetCall) IfNoneMatch(entityTag string) *TunedModelsPermissionsGetCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *TunedModelsPermissionsGetCall) Context(ctx context.Context) *TunedModelsPermissionsGetCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *TunedModelsPermissionsGetCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *TunedModelsPermissionsGetCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "", c.header_) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+name}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "name": c.name, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.tunedModels.permissions.get" call. +// Any non-2xx status code is an error. Response headers are in either +// *Permission.ServerResponse.Header or (if a response was returned at all) in +// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check +// whether the returned error was because http.StatusNotModified was returned. +func (c *TunedModelsPermissionsGetCall) Do(opts ...googleapi.CallOption) (*Permission, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &Permission{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +type TunedModelsPermissionsListCall struct { + s *Service + parent string + urlParams_ gensupport.URLParams + ifNoneMatch_ string + ctx_ context.Context + header_ http.Header +} + +// List: Lists permissions for the specific resource. +// +// - parent: The parent resource of the permissions. Formats: +// `tunedModels/{tuned_model}` `corpora/{corpus}`. +func (r *TunedModelsPermissionsService) List(parent string) *TunedModelsPermissionsListCall { + c := &TunedModelsPermissionsListCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.parent = parent + return c +} + +// PageSize sets the optional parameter "pageSize": The maximum number of +// `Permission`s to return (per page). The service may return fewer +// permissions. If unspecified, at most 10 permissions will be returned. This +// method returns at most 1000 permissions per page, even if you pass larger +// page_size. +func (c *TunedModelsPermissionsListCall) PageSize(pageSize int64) *TunedModelsPermissionsListCall { + c.urlParams_.Set("pageSize", fmt.Sprint(pageSize)) + return c +} + +// PageToken sets the optional parameter "pageToken": A page token, received +// from a previous `ListPermissions` call. Provide the `page_token` returned by +// one request as an argument to the next request to retrieve the next page. +// When paginating, all other parameters provided to `ListPermissions` must +// match the call that provided the page token. +func (c *TunedModelsPermissionsListCall) PageToken(pageToken string) *TunedModelsPermissionsListCall { + c.urlParams_.Set("pageToken", pageToken) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *TunedModelsPermissionsListCall) Fields(s ...googleapi.Field) *TunedModelsPermissionsListCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// IfNoneMatch sets an optional parameter which makes the operation fail if the +// object's ETag matches the given value. This is useful for getting updates +// only after the object has changed since the last request. +func (c *TunedModelsPermissionsListCall) IfNoneMatch(entityTag string) *TunedModelsPermissionsListCall { + c.ifNoneMatch_ = entityTag + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *TunedModelsPermissionsListCall) Context(ctx context.Context) *TunedModelsPermissionsListCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *TunedModelsPermissionsListCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *TunedModelsPermissionsListCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "", c.header_) + if c.ifNoneMatch_ != "" { + reqHeaders.Set("If-None-Match", c.ifNoneMatch_) + } + var body io.Reader = nil + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+parent}/permissions") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("GET", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "parent": c.parent, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.tunedModels.permissions.list" call. +// Any non-2xx status code is an error. Response headers are in either +// *ListPermissionsResponse.ServerResponse.Header or (if a response was +// returned at all) in error.(*googleapi.Error).Header. Use +// googleapi.IsNotModified to check whether the returned error was because +// http.StatusNotModified was returned. +func (c *TunedModelsPermissionsListCall) Do(opts ...googleapi.CallOption) (*ListPermissionsResponse, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &ListPermissionsResponse{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} + +// Pages invokes f for each page of results. +// A non-nil error returned from f will halt the iteration. +// The provided context supersedes any context provided to the Context method. +func (c *TunedModelsPermissionsListCall) Pages(ctx context.Context, f func(*ListPermissionsResponse) error) error { + c.ctx_ = ctx + defer c.PageToken(c.urlParams_.Get("pageToken")) + for { + x, err := c.Do() + if err != nil { + return err + } + if err := f(x); err != nil { + return err + } + if x.NextPageToken == "" { + return nil + } + c.PageToken(x.NextPageToken) + } +} + +type TunedModelsPermissionsPatchCall struct { + s *Service + name string + permission *Permission + urlParams_ gensupport.URLParams + ctx_ context.Context + header_ http.Header +} + +// Patch: Updates the permission. +// +// - name: Output only. Identifier. The permission name. A unique name will be +// generated on create. Examples: +// tunedModels/{tuned_model}/permissions/{permission} +// corpora/{corpus}/permissions/{permission} Output only. +func (r *TunedModelsPermissionsService) Patch(name string, permission *Permission) *TunedModelsPermissionsPatchCall { + c := &TunedModelsPermissionsPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)} + c.name = name + c.permission = permission + return c +} + +// UpdateMask sets the optional parameter "updateMask": Required. The list of +// fields to update. Accepted ones: - role (`Permission.role` field) +func (c *TunedModelsPermissionsPatchCall) UpdateMask(updateMask string) *TunedModelsPermissionsPatchCall { + c.urlParams_.Set("updateMask", updateMask) + return c +} + +// Fields allows partial responses to be retrieved. See +// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse for more +// details. +func (c *TunedModelsPermissionsPatchCall) Fields(s ...googleapi.Field) *TunedModelsPermissionsPatchCall { + c.urlParams_.Set("fields", googleapi.CombineFields(s)) + return c +} + +// Context sets the context to be used in this call's Do method. +func (c *TunedModelsPermissionsPatchCall) Context(ctx context.Context) *TunedModelsPermissionsPatchCall { + c.ctx_ = ctx + return c +} + +// Header returns a http.Header that can be modified by the caller to add +// headers to the request. +func (c *TunedModelsPermissionsPatchCall) Header() http.Header { + if c.header_ == nil { + c.header_ = make(http.Header) + } + return c.header_ +} + +func (c *TunedModelsPermissionsPatchCall) doRequest(alt string) (*http.Response, error) { + reqHeaders := gensupport.SetHeaders(c.s.userAgent(), "application/json", c.header_) + var body io.Reader = nil + body, err := googleapi.WithoutDataWrapper.JSONReader(c.permission) + if err != nil { + return nil, err + } + c.urlParams_.Set("alt", alt) + c.urlParams_.Set("prettyPrint", "false") + urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/{+name}") + urls += "?" + c.urlParams_.Encode() + req, err := http.NewRequest("PATCH", urls, body) + if err != nil { + return nil, err + } + req.Header = reqHeaders + googleapi.Expand(req.URL, map[string]string{ + "name": c.name, + }) + return gensupport.SendRequest(c.ctx_, c.s.client, req) +} + +// Do executes the "generativelanguage.tunedModels.permissions.patch" call. +// Any non-2xx status code is an error. Response headers are in either +// *Permission.ServerResponse.Header or (if a response was returned at all) in +// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check +// whether the returned error was because http.StatusNotModified was returned. +func (c *TunedModelsPermissionsPatchCall) Do(opts ...googleapi.CallOption) (*Permission, error) { + gensupport.SetOptions(c.urlParams_, opts...) + res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } + if err != nil { + return nil, err + } + defer googleapi.CloseBody(res) + if err := googleapi.CheckResponse(res); err != nil { + return nil, gensupport.WrapError(err) + } + ret := &Permission{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil +} diff --git a/vendor/github.com/google/generative-ai-go/genai/internal/gensupport/README b/vendor/github.com/google/generative-ai-go/genai/internal/gensupport/README new file mode 100644 index 000000000..c00591c44 --- /dev/null +++ b/vendor/github.com/google/generative-ai-go/genai/internal/gensupport/README @@ -0,0 +1,12 @@ +This directory was copied from github.com/googleapis/google-api-go-client/internal/gensupport. +It is needed for the discovery client in ../generativelanguage. + +To update, first clone github.com/googleapis/google-api-go-client +into a directory we will call DIR below. +Then, from the repo root: +``` +rm genai/internal/gensupport/*.go +cp $DIR/internal/gensupport/*.go genai/internal/gensupport +``` +Then edit the params.go and resumable.go files to replace the reference to `internal.Version` +with the literal string from $DIR/internal/version.go, and remove the import of `internal`. diff --git a/vendor/github.com/google/generative-ai-go/genai/internal/gensupport/buffer.go b/vendor/github.com/google/generative-ai-go/genai/internal/gensupport/buffer.go new file mode 100644 index 000000000..3d0817ede --- /dev/null +++ b/vendor/github.com/google/generative-ai-go/genai/internal/gensupport/buffer.go @@ -0,0 +1,79 @@ +// 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 gensupport + +import ( + "bytes" + "io" + + "google.golang.org/api/googleapi" +) + +// MediaBuffer buffers data from an io.Reader to support uploading media in +// retryable chunks. It should be created with NewMediaBuffer. +type MediaBuffer struct { + media io.Reader + + chunk []byte // The current chunk which is pending upload. The capacity is the chunk size. + err error // Any error generated when populating chunk by reading media. + + // The absolute position of chunk in the underlying media. + off int64 +} + +// NewMediaBuffer initializes a MediaBuffer. +func NewMediaBuffer(media io.Reader, chunkSize int) *MediaBuffer { + return &MediaBuffer{media: media, chunk: make([]byte, 0, chunkSize)} +} + +// Chunk returns the current buffered chunk, the offset in the underlying media +// from which the chunk is drawn, and the size of the chunk. +// Successive calls to Chunk return the same chunk between calls to Next. +func (mb *MediaBuffer) Chunk() (chunk io.Reader, off int64, size int, err error) { + // There may already be data in chunk if Next has not been called since the previous call to Chunk. + if mb.err == nil && len(mb.chunk) == 0 { + mb.err = mb.loadChunk() + } + return bytes.NewReader(mb.chunk), mb.off, len(mb.chunk), mb.err +} + +// loadChunk will read from media into chunk, up to the capacity of chunk. +func (mb *MediaBuffer) loadChunk() error { + bufSize := cap(mb.chunk) + mb.chunk = mb.chunk[:bufSize] + + read := 0 + var err error + for err == nil && read < bufSize { + var n int + n, err = mb.media.Read(mb.chunk[read:]) + read += n + } + mb.chunk = mb.chunk[:read] + return err +} + +// Next advances to the next chunk, which will be returned by the next call to Chunk. +// Calls to Next without a corresponding prior call to Chunk will have no effect. +func (mb *MediaBuffer) Next() { + mb.off += int64(len(mb.chunk)) + mb.chunk = mb.chunk[0:0] +} + +type readerTyper struct { + io.Reader + googleapi.ContentTyper +} + +// ReaderAtToReader adapts a ReaderAt to be used as a Reader. +// If ra implements googleapi.ContentTyper, then the returned reader +// will also implement googleapi.ContentTyper, delegating to ra. +func ReaderAtToReader(ra io.ReaderAt, size int64) io.Reader { + r := io.NewSectionReader(ra, 0, size) + if typer, ok := ra.(googleapi.ContentTyper); ok { + return readerTyper{r, typer} + } + return r +} diff --git a/vendor/github.com/google/generative-ai-go/genai/internal/gensupport/doc.go b/vendor/github.com/google/generative-ai-go/genai/internal/gensupport/doc.go new file mode 100644 index 000000000..752c4b411 --- /dev/null +++ b/vendor/github.com/google/generative-ai-go/genai/internal/gensupport/doc.go @@ -0,0 +1,10 @@ +// 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 gensupport is an internal implementation detail used by code +// generated by the google-api-go-generator tool. +// +// This package may be modified at any time without regard for backwards +// compatibility. It should not be used directly by API users. +package gensupport diff --git a/vendor/github.com/google/generative-ai-go/genai/internal/gensupport/error.go b/vendor/github.com/google/generative-ai-go/genai/internal/gensupport/error.go new file mode 100644 index 000000000..886c6532b --- /dev/null +++ b/vendor/github.com/google/generative-ai-go/genai/internal/gensupport/error.go @@ -0,0 +1,24 @@ +// Copyright 2022 Google LLC. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package gensupport + +import ( + "errors" + + "github.com/googleapis/gax-go/v2/apierror" + "google.golang.org/api/googleapi" +) + +// WrapError creates an [apierror.APIError] from err, wraps it in err, and +// returns err. If err is not a [googleapi.Error] (or a +// [google.golang.org/grpc/status.Status]), it returns err without modification. +func WrapError(err error) error { + var herr *googleapi.Error + apiError, ok := apierror.ParseError(err, false) + if ok && errors.As(err, &herr) { + herr.Wrap(apiError) + } + return err +} diff --git a/vendor/github.com/google/generative-ai-go/genai/internal/gensupport/json.go b/vendor/github.com/google/generative-ai-go/genai/internal/gensupport/json.go new file mode 100644 index 000000000..eab49a11e --- /dev/null +++ b/vendor/github.com/google/generative-ai-go/genai/internal/gensupport/json.go @@ -0,0 +1,236 @@ +// Copyright 2015 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 gensupport + +import ( + "encoding/json" + "fmt" + "reflect" + "strings" +) + +// MarshalJSON returns a JSON encoding of schema containing only selected fields. +// A field is selected if any of the following is true: +// - it has a non-empty value +// - its field name is present in forceSendFields and it is not a nil pointer or nil interface +// - its field name is present in nullFields. +// +// The JSON key for each selected field is taken from the field's json: struct tag. +func MarshalJSON(schema interface{}, forceSendFields, nullFields []string) ([]byte, error) { + if len(forceSendFields) == 0 && len(nullFields) == 0 { + return json.Marshal(schema) + } + + mustInclude := make(map[string]bool) + for _, f := range forceSendFields { + mustInclude[f] = true + } + useNull := make(map[string]bool) + useNullMaps := make(map[string]map[string]bool) + for _, nf := range nullFields { + parts := strings.SplitN(nf, ".", 2) + field := parts[0] + if len(parts) == 1 { + useNull[field] = true + } else { + if useNullMaps[field] == nil { + useNullMaps[field] = map[string]bool{} + } + useNullMaps[field][parts[1]] = true + } + } + + dataMap, err := schemaToMap(schema, mustInclude, useNull, useNullMaps) + if err != nil { + return nil, err + } + return json.Marshal(dataMap) +} + +func schemaToMap(schema interface{}, mustInclude, useNull map[string]bool, useNullMaps map[string]map[string]bool) (map[string]interface{}, error) { + m := make(map[string]interface{}) + s := reflect.ValueOf(schema) + st := s.Type() + + for i := 0; i < s.NumField(); i++ { + jsonTag := st.Field(i).Tag.Get("json") + if jsonTag == "" { + continue + } + tag, err := parseJSONTag(jsonTag) + if err != nil { + return nil, err + } + if tag.ignore { + continue + } + + v := s.Field(i) + f := st.Field(i) + + if useNull[f.Name] { + if !isEmptyValue(v) { + return nil, fmt.Errorf("field %q in NullFields has non-empty value", f.Name) + } + m[tag.apiName] = nil + continue + } + + if !includeField(v, f, mustInclude) { + continue + } + + // If map fields are explicitly set to null, use a map[string]interface{}. + if f.Type.Kind() == reflect.Map && useNullMaps[f.Name] != nil { + ms, ok := v.Interface().(map[string]string) + if !ok { + mi, err := initMapSlow(v, f.Name, useNullMaps) + if err != nil { + return nil, err + } + m[tag.apiName] = mi + continue + } + mi := map[string]interface{}{} + for k, v := range ms { + mi[k] = v + } + for k := range useNullMaps[f.Name] { + mi[k] = nil + } + m[tag.apiName] = mi + continue + } + + // nil maps are treated as empty maps. + if f.Type.Kind() == reflect.Map && v.IsNil() { + m[tag.apiName] = map[string]string{} + continue + } + + // nil slices are treated as empty slices. + if f.Type.Kind() == reflect.Slice && v.IsNil() { + m[tag.apiName] = []bool{} + continue + } + + if tag.stringFormat { + m[tag.apiName] = formatAsString(v, f.Type.Kind()) + } else { + m[tag.apiName] = v.Interface() + } + } + return m, nil +} + +// initMapSlow uses reflection to build up a map object. This is slower than +// the default behavior so it should be used only as a fallback. +func initMapSlow(rv reflect.Value, fieldName string, useNullMaps map[string]map[string]bool) (map[string]interface{}, error) { + mi := map[string]interface{}{} + iter := rv.MapRange() + for iter.Next() { + k, ok := iter.Key().Interface().(string) + if !ok { + return nil, fmt.Errorf("field %q has keys in NullFields but is not a map[string]any", fieldName) + } + v := iter.Value().Interface() + mi[k] = v + } + for k := range useNullMaps[fieldName] { + mi[k] = nil + } + return mi, nil +} + +// formatAsString returns a string representation of v, dereferencing it first if possible. +func formatAsString(v reflect.Value, kind reflect.Kind) string { + if kind == reflect.Ptr && !v.IsNil() { + v = v.Elem() + } + + return fmt.Sprintf("%v", v.Interface()) +} + +// jsonTag represents a restricted version of the struct tag format used by encoding/json. +// It is used to describe the JSON encoding of fields in a Schema struct. +type jsonTag struct { + apiName string + stringFormat bool + ignore bool +} + +// parseJSONTag parses a restricted version of the struct tag format used by encoding/json. +// The format of the tag must match that generated by the Schema.writeSchemaStruct method +// in the api generator. +func parseJSONTag(val string) (jsonTag, error) { + if val == "-" { + return jsonTag{ignore: true}, nil + } + + var tag jsonTag + + i := strings.Index(val, ",") + if i == -1 || val[:i] == "" { + return tag, fmt.Errorf("malformed json tag: %s", val) + } + + tag = jsonTag{ + apiName: val[:i], + } + + switch val[i+1:] { + case "omitempty": + case "omitempty,string": + tag.stringFormat = true + default: + return tag, fmt.Errorf("malformed json tag: %s", val) + } + + return tag, nil +} + +// Reports whether the struct field "f" with value "v" should be included in JSON output. +func includeField(v reflect.Value, f reflect.StructField, mustInclude map[string]bool) bool { + // The regular JSON encoding of a nil pointer is "null", which means "delete this field". + // Therefore, we could enable field deletion by honoring pointer fields' presence in the mustInclude set. + // However, many fields are not pointers, so there would be no way to delete these fields. + // Rather than partially supporting field deletion, we ignore mustInclude for nil pointer fields. + // Deletion will be handled by a separate mechanism. + if f.Type.Kind() == reflect.Ptr && v.IsNil() { + return false + } + + // The "any" type is represented as an interface{}. If this interface + // is nil, there is no reasonable representation to send. We ignore + // these fields, for the same reasons as given above for pointers. + if f.Type.Kind() == reflect.Interface && v.IsNil() { + return false + } + + return mustInclude[f.Name] || !isEmptyValue(v) +} + +// isEmptyValue reports whether v is the empty value for its type. This +// implementation is based on that of the encoding/json package, but its +// correctness does not depend on it being identical. What's important is that +// this function return false in situations where v should not be sent as part +// of a PATCH operation. +func isEmptyValue(v reflect.Value) bool { + switch v.Kind() { + case reflect.Array, reflect.Map, reflect.Slice, reflect.String: + return v.Len() == 0 + case reflect.Bool: + return !v.Bool() + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return v.Int() == 0 + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return v.Uint() == 0 + case reflect.Float32, reflect.Float64: + return v.Float() == 0 + case reflect.Interface, reflect.Ptr: + return v.IsNil() + } + return false +} diff --git a/vendor/github.com/google/generative-ai-go/genai/internal/gensupport/jsonfloat.go b/vendor/github.com/google/generative-ai-go/genai/internal/gensupport/jsonfloat.go new file mode 100644 index 000000000..13c2f9302 --- /dev/null +++ b/vendor/github.com/google/generative-ai-go/genai/internal/gensupport/jsonfloat.go @@ -0,0 +1,47 @@ +// Copyright 2016 Google LLC. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package gensupport + +import ( + "encoding/json" + "errors" + "fmt" + "math" +) + +// JSONFloat64 is a float64 that supports proper unmarshaling of special float +// values in JSON, according to +// https://developers.google.com/protocol-buffers/docs/proto3#json. Although +// that is a proto-to-JSON spec, it applies to all Google APIs. +// +// The jsonpb package +// (https://github.com/golang/protobuf/blob/master/jsonpb/jsonpb.go) has +// similar functionality, but only for direct translation from proto messages +// to JSON. +type JSONFloat64 float64 + +func (f *JSONFloat64) UnmarshalJSON(data []byte) error { + var ff float64 + if err := json.Unmarshal(data, &ff); err == nil { + *f = JSONFloat64(ff) + return nil + } + var s string + if err := json.Unmarshal(data, &s); err == nil { + switch s { + case "NaN": + ff = math.NaN() + case "Infinity": + ff = math.Inf(1) + case "-Infinity": + ff = math.Inf(-1) + default: + return fmt.Errorf("google.golang.org/api/internal: bad float string %q", s) + } + *f = JSONFloat64(ff) + return nil + } + return errors.New("google.golang.org/api/internal: data not float or string") +} diff --git a/vendor/github.com/google/generative-ai-go/genai/internal/gensupport/media.go b/vendor/github.com/google/generative-ai-go/genai/internal/gensupport/media.go new file mode 100644 index 000000000..7bddd7a42 --- /dev/null +++ b/vendor/github.com/google/generative-ai-go/genai/internal/gensupport/media.go @@ -0,0 +1,310 @@ +// 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 gensupport + +import ( + "bytes" + "fmt" + "io" + "mime" + "mime/multipart" + "net/http" + "net/textproto" + "strings" + "sync" + "time" + + gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" +) + +type typeReader struct { + io.Reader + typ string +} + +// multipartReader combines the contents of multiple readers to create a multipart/related HTTP body. +// Close must be called if reads from the multipartReader are abandoned before reaching EOF. +type multipartReader struct { + pr *io.PipeReader + ctype string + mu sync.Mutex + pipeOpen bool +} + +// boundary optionally specifies the MIME boundary +func newMultipartReader(parts []typeReader, boundary string) *multipartReader { + mp := &multipartReader{pipeOpen: true} + var pw *io.PipeWriter + mp.pr, pw = io.Pipe() + mpw := multipart.NewWriter(pw) + if boundary != "" { + mpw.SetBoundary(boundary) + } + mp.ctype = "multipart/related; boundary=" + mpw.Boundary() + go func() { + for _, part := range parts { + w, err := mpw.CreatePart(typeHeader(part.typ)) + if err != nil { + mpw.Close() + pw.CloseWithError(fmt.Errorf("googleapi: CreatePart failed: %v", err)) + return + } + _, err = io.Copy(w, part.Reader) + if err != nil { + mpw.Close() + pw.CloseWithError(fmt.Errorf("googleapi: Copy failed: %v", err)) + return + } + } + + mpw.Close() + pw.Close() + }() + return mp +} + +func (mp *multipartReader) Read(data []byte) (n int, err error) { + return mp.pr.Read(data) +} + +func (mp *multipartReader) Close() error { + mp.mu.Lock() + if !mp.pipeOpen { + mp.mu.Unlock() + return nil + } + mp.pipeOpen = false + mp.mu.Unlock() + return mp.pr.Close() +} + +// CombineBodyMedia combines a json body with media content to create a multipart/related HTTP body. +// It returns a ReadCloser containing the combined body, and the overall "multipart/related" content type, with random boundary. +// +// The caller must call Close on the returned ReadCloser if reads are abandoned before reaching EOF. +func CombineBodyMedia(body io.Reader, bodyContentType string, media io.Reader, mediaContentType string) (io.ReadCloser, string) { + return combineBodyMedia(body, bodyContentType, media, mediaContentType, "") +} + +// combineBodyMedia is CombineBodyMedia but with an optional mimeBoundary field. +func combineBodyMedia(body io.Reader, bodyContentType string, media io.Reader, mediaContentType, mimeBoundary string) (io.ReadCloser, string) { + mp := newMultipartReader([]typeReader{ + {body, bodyContentType}, + {media, mediaContentType}, + }, mimeBoundary) + return mp, mp.ctype +} + +func typeHeader(contentType string) textproto.MIMEHeader { + h := make(textproto.MIMEHeader) + if contentType != "" { + h.Set("Content-Type", contentType) + } + return h +} + +// PrepareUpload determines whether the data in the supplied reader should be +// uploaded in a single request, or in sequential chunks. +// chunkSize is the size of the chunk that media should be split into. +// +// If chunkSize is zero, media is returned as the first value, and the other +// two return values are nil, true. +// +// Otherwise, a MediaBuffer is returned, along with a bool indicating whether the +// contents of media fit in a single chunk. +// +// After PrepareUpload has been called, media should no longer be used: the +// media content should be accessed via one of the return values. +func PrepareUpload(media io.Reader, chunkSize int) (r io.Reader, mb *MediaBuffer, singleChunk bool) { + if chunkSize == 0 { // do not chunk + return media, nil, true + } + mb = NewMediaBuffer(media, chunkSize) + _, _, _, err := mb.Chunk() + // If err is io.EOF, we can upload this in a single request. Otherwise, err is + // either nil or a non-EOF error. If it is the latter, then the next call to + // mb.Chunk will return the same error. Returning a MediaBuffer ensures that this + // error will be handled at some point. + return nil, mb, err == io.EOF +} + +// MediaInfo holds information for media uploads. It is intended for use by generated +// code only. +type MediaInfo struct { + // At most one of Media and MediaBuffer will be set. + media io.Reader + buffer *MediaBuffer + singleChunk bool + mType string + size int64 // mediaSize, if known. Used only for calls to progressUpdater_. + progressUpdater googleapi.ProgressUpdater + chunkRetryDeadline time.Duration +} + +// NewInfoFromMedia should be invoked from the Media method of a call. It returns a +// MediaInfo populated with chunk size and content type, and a reader or MediaBuffer +// if needed. +func NewInfoFromMedia(r io.Reader, options []googleapi.MediaOption) *MediaInfo { + mi := &MediaInfo{} + opts := googleapi.ProcessMediaOptions(options) + if !opts.ForceEmptyContentType { + mi.mType = opts.ContentType + if mi.mType == "" { + r, mi.mType = gax.DetermineContentType(r) + } + } + mi.chunkRetryDeadline = opts.ChunkRetryDeadline + mi.media, mi.buffer, mi.singleChunk = PrepareUpload(r, opts.ChunkSize) + return mi +} + +// NewInfoFromResumableMedia should be invoked from the ResumableMedia method of a +// call. It returns a MediaInfo using the given reader, size and media type. +func NewInfoFromResumableMedia(r io.ReaderAt, size int64, mediaType string) *MediaInfo { + rdr := ReaderAtToReader(r, size) + mType := mediaType + if mType == "" { + rdr, mType = gax.DetermineContentType(rdr) + } + + return &MediaInfo{ + size: size, + mType: mType, + buffer: NewMediaBuffer(rdr, googleapi.DefaultUploadChunkSize), + media: nil, + singleChunk: false, + } +} + +// SetProgressUpdater sets the progress updater for the media info. +func (mi *MediaInfo) SetProgressUpdater(pu googleapi.ProgressUpdater) { + if mi != nil { + mi.progressUpdater = pu + } +} + +// UploadType determines the type of upload: a single request, or a resumable +// series of requests. +func (mi *MediaInfo) UploadType() string { + if mi.singleChunk { + return "multipart" + } + return "resumable" +} + +// UploadRequest sets up an HTTP request for media upload. It adds headers +// as necessary, and returns a replacement for the body and a function for http.Request.GetBody. +func (mi *MediaInfo) UploadRequest(reqHeaders http.Header, body io.Reader) (newBody io.Reader, getBody func() (io.ReadCloser, error), cleanup func()) { + cleanup = func() {} + if mi == nil { + return body, nil, cleanup + } + var media io.Reader + if mi.media != nil { + // This only happens when the caller has turned off chunking. In that + // case, we write all of media in a single non-retryable request. + media = mi.media + } else if mi.singleChunk { + // The data fits in a single chunk, which has now been read into the MediaBuffer. + // We obtain that chunk so we can write it in a single request. The request can + // be retried because the data is stored in the MediaBuffer. + media, _, _, _ = mi.buffer.Chunk() + } + toCleanup := []io.Closer{} + if media != nil { + fb := readerFunc(body) + fm := readerFunc(media) + combined, ctype := CombineBodyMedia(body, "application/json", media, mi.mType) + toCleanup = append(toCleanup, combined) + if fb != nil && fm != nil { + getBody = func() (io.ReadCloser, error) { + rb := io.NopCloser(fb()) + rm := io.NopCloser(fm()) + var mimeBoundary string + if _, params, err := mime.ParseMediaType(ctype); err == nil { + mimeBoundary = params["boundary"] + } + r, _ := combineBodyMedia(rb, "application/json", rm, mi.mType, mimeBoundary) + toCleanup = append(toCleanup, r) + return r, nil + } + } + reqHeaders.Set("Content-Type", ctype) + body = combined + } + if mi.buffer != nil && mi.mType != "" && !mi.singleChunk { + // This happens when initiating a resumable upload session. + // The initial request contains a JSON body rather than media. + // It can be retried with a getBody function that re-creates the request body. + fb := readerFunc(body) + if fb != nil { + getBody = func() (io.ReadCloser, error) { + rb := io.NopCloser(fb()) + toCleanup = append(toCleanup, rb) + return rb, nil + } + } + reqHeaders.Set("X-Upload-Content-Type", mi.mType) + } + // Ensure that any bodies created in getBody are cleaned up. + cleanup = func() { + for _, closer := range toCleanup { + _ = closer.Close() + } + } + return body, getBody, cleanup +} + +// readerFunc returns a function that always returns an io.Reader that has the same +// contents as r, provided that can be done without consuming r. Otherwise, it +// returns nil. +// See http.NewRequest (in net/http/request.go). +func readerFunc(r io.Reader) func() io.Reader { + switch r := r.(type) { + case *bytes.Buffer: + buf := r.Bytes() + return func() io.Reader { return bytes.NewReader(buf) } + case *bytes.Reader: + snapshot := *r + return func() io.Reader { r := snapshot; return &r } + case *strings.Reader: + snapshot := *r + return func() io.Reader { r := snapshot; return &r } + default: + return nil + } +} + +// ResumableUpload returns an appropriately configured ResumableUpload value if the +// upload is resumable, or nil otherwise. +func (mi *MediaInfo) ResumableUpload(locURI string) *ResumableUpload { + if mi == nil || mi.singleChunk { + return nil + } + return &ResumableUpload{ + URI: locURI, + Media: mi.buffer, + MediaType: mi.mType, + Callback: func(curr int64) { + if mi.progressUpdater != nil { + mi.progressUpdater(curr, mi.size) + } + }, + ChunkRetryDeadline: mi.chunkRetryDeadline, + } +} + +// SetGetBody sets the GetBody field of req to f. This was once needed +// to gracefully support Go 1.7 and earlier which didn't have that +// field. +// +// Deprecated: the code generator no longer uses this as of +// 2019-02-19. Nothing else should be calling this anyway, but we +// won't delete this immediately; it will be deleted in as early as 6 +// months. +func SetGetBody(req *http.Request, f func() (io.ReadCloser, error)) { + req.GetBody = f +} diff --git a/vendor/github.com/google/generative-ai-go/genai/internal/gensupport/params.go b/vendor/github.com/google/generative-ai-go/genai/internal/gensupport/params.go new file mode 100644 index 000000000..5f31bc12d --- /dev/null +++ b/vendor/github.com/google/generative-ai-go/genai/internal/gensupport/params.go @@ -0,0 +1,77 @@ +// Copyright 2015 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 gensupport + +import ( + "net/http" + "net/url" + + "google.golang.org/api/googleapi" +) + +// URLParams is a simplified replacement for url.Values +// that safely builds up URL parameters for encoding. +type URLParams map[string][]string + +// Get returns the first value for the given key, or "". +func (u URLParams) Get(key string) string { + vs := u[key] + if len(vs) == 0 { + return "" + } + return vs[0] +} + +// Set sets the key to value. +// It replaces any existing values. +func (u URLParams) Set(key, value string) { + u[key] = []string{value} +} + +// SetMulti sets the key to an array of values. +// It replaces any existing values. +// Note that values must not be modified after calling SetMulti +// so the caller is responsible for making a copy if necessary. +func (u URLParams) SetMulti(key string, values []string) { + u[key] = values +} + +// Encode encodes the values into “URL encoded” form +// ("bar=baz&foo=quux") sorted by key. +func (u URLParams) Encode() string { + return url.Values(u).Encode() +} + +// SetOptions sets the URL params and any additional `CallOption` or +// `MultiCallOption` passed in. +func SetOptions(u URLParams, opts ...googleapi.CallOption) { + for _, o := range opts { + m, ok := o.(googleapi.MultiCallOption) + if ok { + u.SetMulti(m.GetMulti()) + continue + } + u.Set(o.Get()) + } +} + +// SetHeaders sets common headers for all requests. The keyvals header pairs +// should have a corresponding value for every key provided. If there is an odd +// number of keyvals this method will panic. +func SetHeaders(userAgent, contentType string, userHeaders http.Header, keyvals ...string) http.Header { + reqHeaders := make(http.Header) + reqHeaders.Set("x-goog-api-client", "gl-go/"+GoVersion()+" gdcl/"+"0.179.0") + for i := 0; i < len(keyvals); i = i + 2 { + reqHeaders.Set(keyvals[i], keyvals[i+1]) + } + reqHeaders.Set("User-Agent", userAgent) + if contentType != "" { + reqHeaders.Set("Content-Type", contentType) + } + for k, v := range userHeaders { + reqHeaders[k] = v + } + return reqHeaders +} diff --git a/vendor/github.com/google/generative-ai-go/genai/internal/gensupport/resumable.go b/vendor/github.com/google/generative-ai-go/genai/internal/gensupport/resumable.go new file mode 100644 index 000000000..3ffa632a6 --- /dev/null +++ b/vendor/github.com/google/generative-ai-go/genai/internal/gensupport/resumable.go @@ -0,0 +1,267 @@ +// 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 gensupport + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "strings" + "sync" + "time" + + "github.com/google/uuid" +) + +// ResumableUpload is used by the generated APIs to provide resumable uploads. +// It is not used by developers directly. +type ResumableUpload struct { + Client *http.Client + // URI is the resumable resource destination provided by the server after specifying "&uploadType=resumable". + URI string + UserAgent string // User-Agent for header of the request + // Media is the object being uploaded. + Media *MediaBuffer + // MediaType defines the media type, e.g. "image/jpeg". + MediaType string + + mu sync.Mutex // guards progress + progress int64 // number of bytes uploaded so far + + // Callback is an optional function that will be periodically called with the cumulative number of bytes uploaded. + Callback func(int64) + + // Retry optionally configures retries for requests made against the upload. + Retry *RetryConfig + + // ChunkRetryDeadline configures the per-chunk deadline after which no further + // retries should happen. + ChunkRetryDeadline time.Duration + + // Track current request invocation ID and attempt count for retry metrics + // and idempotency headers. + invocationID string + attempts int +} + +// Progress returns the number of bytes uploaded at this point. +func (rx *ResumableUpload) Progress() int64 { + rx.mu.Lock() + defer rx.mu.Unlock() + return rx.progress +} + +// doUploadRequest performs a single HTTP request to upload data. +// off specifies the offset in rx.Media from which data is drawn. +// size is the number of bytes in data. +// final specifies whether data is the final chunk to be uploaded. +func (rx *ResumableUpload) doUploadRequest(ctx context.Context, data io.Reader, off, size int64, final bool) (*http.Response, error) { + req, err := http.NewRequest("POST", rx.URI, data) + if err != nil { + return nil, err + } + + req.ContentLength = size + var contentRange string + if final { + if size == 0 { + contentRange = fmt.Sprintf("bytes */%v", off) + } else { + contentRange = fmt.Sprintf("bytes %v-%v/%v", off, off+size-1, off+size) + } + } else { + contentRange = fmt.Sprintf("bytes %v-%v/*", off, off+size-1) + } + req.Header.Set("Content-Range", contentRange) + req.Header.Set("Content-Type", rx.MediaType) + req.Header.Set("User-Agent", rx.UserAgent) + + // TODO(b/274504690): Consider dropping gccl-invocation-id key since it + // duplicates the X-Goog-Gcs-Idempotency-Token header (added in v0.115.0). + baseXGoogHeader := "gl-go/" + GoVersion() + " gdcl/" + "0.179.0" + invocationHeader := fmt.Sprintf("gccl-invocation-id/%s gccl-attempt-count/%d", rx.invocationID, rx.attempts) + req.Header.Set("X-Goog-Api-Client", strings.Join([]string{baseXGoogHeader, invocationHeader}, " ")) + + // Set idempotency token header which is used by GCS uploads. + req.Header.Set("X-Goog-Gcs-Idempotency-Token", rx.invocationID) + + // Google's upload endpoint uses status code 308 for a + // different purpose than the "308 Permanent Redirect" + // since-standardized in RFC 7238. Because of the conflict in + // semantics, Google added this new request header which + // causes it to not use "308" and instead reply with 200 OK + // and sets the upload-specific "X-HTTP-Status-Code-Override: + // 308" response header. + req.Header.Set("X-GUploader-No-308", "yes") + + return SendRequest(ctx, rx.Client, req) +} + +func statusResumeIncomplete(resp *http.Response) bool { + // This is how the server signals "status resume incomplete" + // when X-GUploader-No-308 is set to "yes": + return resp != nil && resp.Header.Get("X-Http-Status-Code-Override") == "308" +} + +// reportProgress calls a user-supplied callback to report upload progress. +// If old==updated, the callback is not called. +func (rx *ResumableUpload) reportProgress(old, updated int64) { + if updated-old == 0 { + return + } + rx.mu.Lock() + rx.progress = updated + rx.mu.Unlock() + if rx.Callback != nil { + rx.Callback(updated) + } +} + +// transferChunk performs a single HTTP request to upload a single chunk from rx.Media. +func (rx *ResumableUpload) transferChunk(ctx context.Context) (*http.Response, error) { + chunk, off, size, err := rx.Media.Chunk() + + done := err == io.EOF + if !done && err != nil { + return nil, err + } + + res, err := rx.doUploadRequest(ctx, chunk, off, int64(size), done) + if err != nil { + return res, err + } + + // We sent "X-GUploader-No-308: yes" (see comment elsewhere in + // this file), so we don't expect to get a 308. + if res.StatusCode == 308 { + return nil, errors.New("unexpected 308 response status code") + } + + if res.StatusCode == http.StatusOK { + rx.reportProgress(off, off+int64(size)) + } + + if statusResumeIncomplete(res) { + rx.Media.Next() + } + return res, nil +} + +// Upload starts the process of a resumable upload with a cancellable context. +// It retries using the provided back off strategy until cancelled or the +// strategy indicates to stop retrying. +// It is called from the auto-generated API code and is not visible to the user. +// Before sending an HTTP request, Upload calls any registered hook functions, +// and calls the returned functions after the request returns (see send.go). +// rx is private to the auto-generated API code. +// Exactly one of resp or err will be nil. If resp is non-nil, the caller must call resp.Body.Close. +func (rx *ResumableUpload) Upload(ctx context.Context) (resp *http.Response, err error) { + // There are a couple of cases where it's possible for err and resp to both + // be non-nil. However, we expose a simpler contract to our callers: exactly + // one of resp and err will be non-nil. This means that any response body + // must be closed here before returning a non-nil error. + prepareReturn := func(resp *http.Response, err error) (*http.Response, error) { + if err != nil { + if resp != nil && resp.Body != nil { + resp.Body.Close() + } + return nil, err + } + // This case is very unlikely but possible only if rx.ChunkRetryDeadline is + // set to a very small value, in which case no requests will be sent before + // the deadline. Return an error to avoid causing a panic. + if resp == nil { + return nil, fmt.Errorf("upload request to %v not sent, choose larger value for ChunkRetryDealine", rx.URI) + } + return resp, nil + } + // Configure retryable error criteria. + errorFunc := rx.Retry.errorFunc() + + // Configure per-chunk retry deadline. + var retryDeadline time.Duration + if rx.ChunkRetryDeadline != 0 { + retryDeadline = rx.ChunkRetryDeadline + } else { + retryDeadline = defaultRetryDeadline + } + + // Send all chunks. + for { + var pause time.Duration + + // Each chunk gets its own initialized-at-zero backoff and invocation ID. + bo := rx.Retry.backoff() + quitAfterTimer := time.NewTimer(retryDeadline) + rx.attempts = 1 + rx.invocationID = uuid.New().String() + + // Retry loop for a single chunk. + for { + pauseTimer := time.NewTimer(pause) + select { + case <-ctx.Done(): + quitAfterTimer.Stop() + pauseTimer.Stop() + if err == nil { + err = ctx.Err() + } + return prepareReturn(resp, err) + case <-pauseTimer.C: + case <-quitAfterTimer.C: + pauseTimer.Stop() + return prepareReturn(resp, err) + } + pauseTimer.Stop() + + // Check for context cancellation or timeout once more. If more than one + // case in the select statement above was satisfied at the same time, Go + // will choose one arbitrarily. + // That can cause an operation to go through even if the context was + // canceled before or the timeout was reached. + select { + case <-ctx.Done(): + quitAfterTimer.Stop() + if err == nil { + err = ctx.Err() + } + return prepareReturn(resp, err) + case <-quitAfterTimer.C: + return prepareReturn(resp, err) + default: + } + + resp, err = rx.transferChunk(ctx) + + var status int + if resp != nil { + status = resp.StatusCode + } + + // Check if we should retry the request. + if !errorFunc(status, err) { + quitAfterTimer.Stop() + break + } + + rx.attempts++ + pause = bo.Pause() + if resp != nil && resp.Body != nil { + resp.Body.Close() + } + } + + // If the chunk was uploaded successfully, but there's still + // more to go, upload the next chunk without any delay. + if statusResumeIncomplete(resp) { + resp.Body.Close() + continue + } + + return prepareReturn(resp, err) + } +} diff --git a/vendor/github.com/google/generative-ai-go/genai/internal/gensupport/retry.go b/vendor/github.com/google/generative-ai-go/genai/internal/gensupport/retry.go new file mode 100644 index 000000000..20b57d925 --- /dev/null +++ b/vendor/github.com/google/generative-ai-go/genai/internal/gensupport/retry.go @@ -0,0 +1,121 @@ +// Copyright 2021 Google LLC. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package gensupport + +import ( + "errors" + "io" + "net" + "strings" + "time" + + "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" +) + +// Backoff is an interface around gax.Backoff's Pause method, allowing tests to provide their +// own implementation. +type Backoff interface { + Pause() time.Duration +} + +// These are declared as global variables so that tests can overwrite them. +var ( + // Default per-chunk deadline for resumable uploads. + defaultRetryDeadline = 32 * time.Second + // Default backoff timer. + backoff = func() Backoff { + return &gax.Backoff{Initial: 100 * time.Millisecond} + } + // syscallRetryable is a platform-specific hook, specified in retryable_linux.go + syscallRetryable func(error) bool = func(err error) bool { return false } +) + +const ( + // statusTooManyRequests is returned by the storage API if the + // per-project limits have been temporarily exceeded. The request + // should be retried. + // https://cloud.google.com/storage/docs/json_api/v1/status-codes#standardcodes + statusTooManyRequests = 429 + + // statusRequestTimeout is returned by the storage API if the + // upload connection was broken. The request should be retried. + statusRequestTimeout = 408 +) + +// shouldRetry indicates whether an error is retryable for the purposes of this +// package, unless a ShouldRetry func is specified by the RetryConfig instead. +// It follows guidance from +// https://cloud.google.com/storage/docs/exponential-backoff . +func shouldRetry(status int, err error) bool { + if 500 <= status && status <= 599 { + return true + } + if status == statusTooManyRequests || status == statusRequestTimeout { + return true + } + if err == io.ErrUnexpectedEOF { + return true + } + // Transient network errors should be retried. + if syscallRetryable(err) { + return true + } + if err, ok := err.(interface{ Temporary() bool }); ok { + if err.Temporary() { + return true + } + } + var opErr *net.OpError + if errors.As(err, &opErr) { + if strings.Contains(opErr.Error(), "use of closed network connection") { + // TODO: check against net.ErrClosed (go 1.16+) instead of string + return true + } + } + + // If Go 1.13 error unwrapping is available, use this to examine wrapped + // errors. + if err, ok := err.(interface{ Unwrap() error }); ok { + return shouldRetry(status, err.Unwrap()) + } + return false +} + +// RetryConfig allows configuration of backoff timing and retryable errors. +type RetryConfig struct { + Backoff *gax.Backoff + ShouldRetry func(err error) bool +} + +// Get a new backoff object based on the configured values. +func (r *RetryConfig) backoff() Backoff { + if r == nil || r.Backoff == nil { + return backoff() + } + return &gax.Backoff{ + Initial: r.Backoff.Initial, + Max: r.Backoff.Max, + Multiplier: r.Backoff.Multiplier, + } +} + +// This is kind of hacky; it is necessary because ShouldRetry expects to +// handle HTTP errors via googleapi.Error, but the error has not yet been +// wrapped with a googleapi.Error at this layer, and the ErrorFunc type +// in the manual layer does not pass in a status explicitly as it does +// here. So, we must wrap error status codes in a googleapi.Error so that +// ShouldRetry can parse this correctly. +func (r *RetryConfig) errorFunc() func(status int, err error) bool { + if r == nil || r.ShouldRetry == nil { + return shouldRetry + } + return func(status int, err error) bool { + if status >= 400 { + return r.ShouldRetry(&googleapi.Error{Code: status}) + } + return r.ShouldRetry(err) + } +} diff --git a/vendor/github.com/google/generative-ai-go/genai/internal/gensupport/retryable_linux.go b/vendor/github.com/google/generative-ai-go/genai/internal/gensupport/retryable_linux.go new file mode 100644 index 000000000..a916c3da2 --- /dev/null +++ b/vendor/github.com/google/generative-ai-go/genai/internal/gensupport/retryable_linux.go @@ -0,0 +1,16 @@ +// Copyright 2020 Google LLC. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build linux +// +build linux + +package gensupport + +import "syscall" + +func init() { + // Initialize syscallRetryable to return true on transient socket-level + // errors. These errors are specific to Linux. + syscallRetryable = func(err error) bool { return err == syscall.ECONNRESET || err == syscall.ECONNREFUSED } +} diff --git a/vendor/github.com/google/generative-ai-go/genai/internal/gensupport/send.go b/vendor/github.com/google/generative-ai-go/genai/internal/gensupport/send.go new file mode 100644 index 000000000..f61b00f48 --- /dev/null +++ b/vendor/github.com/google/generative-ai-go/genai/internal/gensupport/send.go @@ -0,0 +1,206 @@ +// 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 gensupport + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "strings" + "time" + + "github.com/google/uuid" + "github.com/googleapis/gax-go/v2" + "github.com/googleapis/gax-go/v2/callctx" +) + +// Use this error type to return an error which allows introspection of both +// the context error and the error from the service. +type wrappedCallErr struct { + ctxErr error + wrappedErr error +} + +func (e wrappedCallErr) Error() string { + return fmt.Sprintf("retry failed with %v; last error: %v", e.ctxErr, e.wrappedErr) +} + +func (e wrappedCallErr) Unwrap() error { + return e.wrappedErr +} + +// Is allows errors.Is to match the error from the call as well as context +// sentinel errors. +func (e wrappedCallErr) Is(target error) bool { + return errors.Is(e.ctxErr, target) || errors.Is(e.wrappedErr, target) +} + +// SendRequest sends a single HTTP request using the given client. +// If ctx is non-nil, it calls all hooks, then sends the request with +// req.WithContext, then calls any functions returned by the hooks in +// reverse order. +func SendRequest(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) { + // Add headers set in context metadata. + if ctx != nil { + headers := callctx.HeadersFromContext(ctx) + for k, vals := range headers { + for _, v := range vals { + req.Header.Add(k, v) + } + } + } + + // Disallow Accept-Encoding because it interferes with the automatic gzip handling + // done by the default http.Transport. See https://github.com/google/google-api-go-client/issues/219. + if _, ok := req.Header["Accept-Encoding"]; ok { + return nil, errors.New("google api: custom Accept-Encoding headers not allowed") + } + if ctx == nil { + return client.Do(req) + } + return send(ctx, client, req) +} + +func send(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) { + if client == nil { + client = http.DefaultClient + } + resp, err := client.Do(req.WithContext(ctx)) + // If we got an error, and the context has been canceled, + // the context's error is probably more useful. + if err != nil { + select { + case <-ctx.Done(): + err = ctx.Err() + default: + } + } + return resp, err +} + +// SendRequestWithRetry sends a single HTTP request using the given client, +// with retries if a retryable error is returned. +// If ctx is non-nil, it calls all hooks, then sends the request with +// req.WithContext, then calls any functions returned by the hooks in +// reverse order. +func SendRequestWithRetry(ctx context.Context, client *http.Client, req *http.Request, retry *RetryConfig) (*http.Response, error) { + // Add headers set in context metadata. + if ctx != nil { + headers := callctx.HeadersFromContext(ctx) + for k, vals := range headers { + for _, v := range vals { + req.Header.Add(k, v) + } + } + } + + // Disallow Accept-Encoding because it interferes with the automatic gzip handling + // done by the default http.Transport. See https://github.com/google/google-api-go-client/issues/219. + if _, ok := req.Header["Accept-Encoding"]; ok { + return nil, errors.New("google api: custom Accept-Encoding headers not allowed") + } + if ctx == nil { + return client.Do(req) + } + return sendAndRetry(ctx, client, req, retry) +} + +func sendAndRetry(ctx context.Context, client *http.Client, req *http.Request, retry *RetryConfig) (*http.Response, error) { + if client == nil { + client = http.DefaultClient + } + + var resp *http.Response + var err error + attempts := 1 + invocationID := uuid.New().String() + baseXGoogHeader := req.Header.Get("X-Goog-Api-Client") + + // Loop to retry the request, up to the context deadline. + var pause time.Duration + var bo Backoff + if retry != nil && retry.Backoff != nil { + bo = &gax.Backoff{ + Initial: retry.Backoff.Initial, + Max: retry.Backoff.Max, + Multiplier: retry.Backoff.Multiplier, + } + } else { + bo = backoff() + } + + errorFunc := retry.errorFunc() + + for { + t := time.NewTimer(pause) + select { + case <-ctx.Done(): + t.Stop() + // If we got an error and the context has been canceled, return an error acknowledging + // both the context cancelation and the service error. + if err != nil { + return resp, wrappedCallErr{ctx.Err(), err} + } + return resp, ctx.Err() + case <-t.C: + } + + if ctx.Err() != nil { + // Check for context cancellation once more. If more than one case in a + // select is satisfied at the same time, Go will choose one arbitrarily. + // That can cause an operation to go through even if the context was + // canceled before. + if err != nil { + return resp, wrappedCallErr{ctx.Err(), err} + } + return resp, ctx.Err() + } + + // Set retry metrics and idempotency headers for GCS. + // TODO(b/274504690): Consider dropping gccl-invocation-id key since it + // duplicates the X-Goog-Gcs-Idempotency-Token header (added in v0.115.0). + invocationHeader := fmt.Sprintf("gccl-invocation-id/%s gccl-attempt-count/%d", invocationID, attempts) + xGoogHeader := strings.Join([]string{invocationHeader, baseXGoogHeader}, " ") + req.Header.Set("X-Goog-Api-Client", xGoogHeader) + req.Header.Set("X-Goog-Gcs-Idempotency-Token", invocationID) + + resp, err = client.Do(req.WithContext(ctx)) + + var status int + if resp != nil { + status = resp.StatusCode + } + + // Check if we can retry the request. A retry can only be done if the error + // is retryable and the request body can be re-created using GetBody (this + // will not be possible if the body was unbuffered). + if req.GetBody == nil || !errorFunc(status, err) { + break + } + attempts++ + var errBody error + req.Body, errBody = req.GetBody() + if errBody != nil { + break + } + + pause = bo.Pause() + if resp != nil && resp.Body != nil { + resp.Body.Close() + } + } + return resp, err +} + +// DecodeResponse decodes the body of res into target. If there is no body, +// target is unchanged. +func DecodeResponse(target interface{}, res *http.Response) error { + if res.StatusCode == http.StatusNoContent { + return nil + } + return json.NewDecoder(res.Body).Decode(target) +} diff --git a/vendor/github.com/google/generative-ai-go/genai/internal/gensupport/version.go b/vendor/github.com/google/generative-ai-go/genai/internal/gensupport/version.go new file mode 100644 index 000000000..23f6aa24e --- /dev/null +++ b/vendor/github.com/google/generative-ai-go/genai/internal/gensupport/version.go @@ -0,0 +1,53 @@ +// Copyright 2020 Google LLC. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package gensupport + +import ( + "runtime" + "strings" + "unicode" +) + +// GoVersion returns the Go runtime version. The returned string +// has no whitespace. +func GoVersion() string { + return goVersion +} + +var goVersion = goVer(runtime.Version()) + +const develPrefix = "devel +" + +func goVer(s string) string { + if strings.HasPrefix(s, develPrefix) { + s = s[len(develPrefix):] + if p := strings.IndexFunc(s, unicode.IsSpace); p >= 0 { + s = s[:p] + } + return s + } + + if strings.HasPrefix(s, "go1") { + s = s[2:] + var prerelease string + if p := strings.IndexFunc(s, notSemverRune); p >= 0 { + s, prerelease = s[:p], s[p:] + } + if strings.HasSuffix(s, ".") { + s += "0" + } else if strings.Count(s, ".") < 2 { + s += ".0" + } + if prerelease != "" { + s += "-" + prerelease + } + return s + } + return "" +} + +func notSemverRune(r rune) bool { + return !strings.ContainsRune("0123456789.", r) +} diff --git a/vendor/github.com/google/generative-ai-go/genai/internal/version.go b/vendor/github.com/google/generative-ai-go/genai/internal/version.go new file mode 100644 index 000000000..bd549c2b6 --- /dev/null +++ b/vendor/github.com/google/generative-ai-go/genai/internal/version.go @@ -0,0 +1,8 @@ +// Copyright 2022 Google LLC. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package internal + +// Version is the current tagged release of the library. +const Version = "0.13.0" diff --git a/vendor/github.com/google/generative-ai-go/genai/license.txt b/vendor/github.com/google/generative-ai-go/genai/license.txt new file mode 100644 index 000000000..b3b714d5e --- /dev/null +++ b/vendor/github.com/google/generative-ai-go/genai/license.txt @@ -0,0 +1,14 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + diff --git a/vendor/github.com/google/generative-ai-go/genai/list_models.go b/vendor/github.com/google/generative-ai-go/genai/list_models.go new file mode 100644 index 000000000..fb232994c --- /dev/null +++ b/vendor/github.com/google/generative-ai-go/genai/list_models.go @@ -0,0 +1,50 @@ +// Copyright 2023 Google LLC +// +// 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. + +package genai + +import ( + "context" + + gl "cloud.google.com/go/ai/generativelanguage/apiv1beta" + pb "cloud.google.com/go/ai/generativelanguage/apiv1beta/generativelanguagepb" + + "google.golang.org/api/iterator" +) + +func (c *Client) ListModels(ctx context.Context) *ModelInfoIterator { + return &ModelInfoIterator{ + it: c.mc.ListModels(ctx, &pb.ListModelsRequest{}), + } +} + +// A ModelInfoIterator iterates over Models. +type ModelInfoIterator struct { + it *gl.ModelIterator +} + +// Next returns the next result. Its second return value is iterator.Done if there are no more +// results. Once Next returns Done, all subsequent calls will return Done. +func (it *ModelInfoIterator) Next() (*ModelInfo, error) { + m, err := it.it.Next() + if err != nil { + return nil, err + } + return (ModelInfo{}).fromProto(m), nil +} + +// PageInfo supports pagination. See the google.golang.org/api/iterator package for details. +func (it *ModelInfoIterator) PageInfo() *iterator.PageInfo { + return it.it.PageInfo() +} diff --git a/vendor/github.com/google/generative-ai-go/internal/support/support.go b/vendor/github.com/google/generative-ai-go/internal/support/support.go new file mode 100644 index 000000000..e9f4b4547 --- /dev/null +++ b/vendor/github.com/google/generative-ai-go/internal/support/support.go @@ -0,0 +1,121 @@ +// Copyright 2024 Google LLC +// +// 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. + +// Package support provides support functions for protoveneer. +package support + +import ( + "fmt" + "time" + + "cloud.google.com/go/civil" + "google.golang.org/genproto/googleapis/type/date" + "google.golang.org/protobuf/types/known/structpb" + "google.golang.org/protobuf/types/known/timestamppb" +) + +// TransformSlice applies f to each element of from and returns +// a new slice with the results. +func TransformSlice[From, To any](from []From, f func(From) To) []To { + if from == nil { + return nil + } + to := make([]To, len(from)) + for i, e := range from { + to[i] = f(e) + } + return to +} + +// TransformMapValues applies f to each value of from, returning a new map. +// It does not change the keys. +func TransformMapValues[K comparable, VFrom, VTo any](from map[K]VFrom, f func(VFrom) VTo) map[K]VTo { + if from == nil { + return nil + } + to := map[K]VTo{} + for k, v := range from { + to[k] = f(v) + } + return to +} + +// AddrOrNil returns nil if x is the zero value for T, +// or &x otherwise. +func AddrOrNil[T comparable](x T) *T { + var z T + if x == z { + return nil + } + return &x +} + +// DerefOrZero returns the zero value for T if x is nil, +// or *x otherwise. +func DerefOrZero[T any](x *T) T { + if x == nil { + var z T + return z + } + return *x +} + +// CivilDateToProto converts a civil.Date to a date.Date. +func CivilDateToProto(d civil.Date) *date.Date { + return &date.Date{ + Year: int32(d.Year), + Month: int32(d.Month), + Day: int32(d.Day), + } +} + +// CivilDateFromProto converts a date.Date to a civil.Date. +func CivilDateFromProto(p *date.Date) civil.Date { + if p == nil { + return civil.Date{} + } + return civil.Date{ + Year: int(p.Year), + Month: time.Month(p.Month), + Day: int(p.Day), + } +} + +// MapToStructPB converts a map into a structpb.Struct. +func MapToStructPB(m map[string]any) *structpb.Struct { + if m == nil { + return nil + } + s, err := structpb.NewStruct(m) + if err != nil { + panic(fmt.Errorf("support.MapToProto: %w", err)) + } + return s +} + +// MapFromStructPB converts a structpb.Struct to a map. +func MapFromStructPB(p *structpb.Struct) map[string]any { + if p == nil { + return nil + } + return p.AsMap() +} + +// TimeFromProto converts a Timestamp into a time.Time. +func TimeFromProto(ts *timestamppb.Timestamp) time.Time { + if ts == nil { + return time.Time{} + } + return ts.AsTime() +} |
