-
Notifications
You must be signed in to change notification settings - Fork 635
feat(go): add OpenAI plugin #4071
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
hugoaguirre
wants to merge
21
commits into
main
Choose a base branch
from
haguirre/openai
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
21 commits
Select commit
Hold shift + click to select a range
285764f
init openai plugin
hugoaguirre d6d1017
toToolChoice
hugoaguirre ef8ef11
add messages translation and test cases
hugoaguirre 9a33b3c
add generate functions
hugoaguirre a15f83c
docs
hugoaguirre 7d4c46f
test: config to schema
hugoaguirre cec8cad
fix schema parsing
hugoaguirre ebb59ba
fix usage tokens and tool calls
hugoaguirre c9bd210
fix stream and conv history
hugoaguirre 145bce5
update file structure
hugoaguirre dd646ee
add more live test cases
hugoaguirre 98aec5f
small refactor in translateResponse for type handling
hugoaguirre e95fc43
return error in handleResponseItem and minor doc updates
hugoaguirre 8edbb96
add structured output
hugoaguirre ec3173e
remove invalid empty config test
hugoaguirre 02f20b0
update output format handler in translator
hugoaguirre 6d98964
add ModelRef function
hugoaguirre a2ae094
add ModelRef live tests
hugoaguirre cce711f
bump openai-go to v.3.16.0
hugoaguirre 3543730
Merge branch 'main' into haguirre/openai
hugoaguirre a137acd
add OpenAI provider in README.md
hugoaguirre File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,135 @@ | ||
| // Copyright 2026 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 openai | ||
|
|
||
| import ( | ||
| "context" | ||
| "fmt" | ||
|
|
||
| "github.com/firebase/genkit/go/ai" | ||
| "github.com/openai/openai-go/v3" | ||
| "github.com/openai/openai-go/v3/responses" | ||
| ) | ||
|
|
||
| // generate is the entry point function to request content generation to the OpenAI client | ||
| func generate(ctx context.Context, client *openai.Client, model string, input *ai.ModelRequest, cb func(context.Context, *ai.ModelResponseChunk) error, | ||
| ) (*ai.ModelResponse, error) { | ||
| req, err := toOpenAIResponseParams(model, input) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| // stream mode | ||
| if cb != nil { | ||
| resp, err := generateStream(ctx, client, req, input, cb) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| return resp, nil | ||
|
|
||
| } | ||
|
|
||
| resp, err := generateComplete(ctx, client, req, input) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| return resp, nil | ||
| } | ||
|
|
||
| // generateStream starts a new streaming response | ||
| func generateStream(ctx context.Context, client *openai.Client, req *responses.ResponseNewParams, input *ai.ModelRequest, cb func(context.Context, *ai.ModelResponseChunk) error) (*ai.ModelResponse, error) { | ||
| stream := client.Responses.NewStreaming(ctx, *req) | ||
| defer stream.Close() | ||
|
|
||
| var ( | ||
| toolRefMap = make(map[string]string) | ||
| finalResp *responses.Response | ||
| ) | ||
|
|
||
| for stream.Next() { | ||
| evt := stream.Current() | ||
| chunk := &ai.ModelResponseChunk{} | ||
|
|
||
| switch v := evt.AsAny().(type) { | ||
| case responses.ResponseTextDeltaEvent: | ||
| chunk.Content = append(chunk.Content, ai.NewTextPart(v.Delta)) | ||
|
|
||
| case responses.ResponseReasoningTextDeltaEvent: | ||
| chunk.Content = append(chunk.Content, ai.NewReasoningPart(v.Delta, nil)) | ||
|
|
||
| case responses.ResponseFunctionCallArgumentsDeltaEvent: | ||
| name := toolRefMap[v.ItemID] | ||
| chunk.Content = append(chunk.Content, ai.NewToolRequestPart(&ai.ToolRequest{ | ||
| Ref: v.ItemID, | ||
| Name: name, | ||
| Input: v.Delta, | ||
| })) | ||
|
|
||
| case responses.ResponseOutputItemAddedEvent: | ||
| switch item := v.Item.AsAny().(type) { | ||
| case responses.ResponseFunctionToolCall: | ||
| toolRefMap[item.CallID] = item.Name | ||
| chunk.Content = append(chunk.Content, ai.NewToolRequestPart(&ai.ToolRequest{ | ||
| Ref: item.CallID, | ||
| Name: item.Name, | ||
| })) | ||
| } | ||
|
|
||
| case responses.ResponseCompletedEvent: | ||
| finalResp = &v.Response | ||
| } | ||
|
|
||
| if len(chunk.Content) > 0 { | ||
| if err := cb(ctx, chunk); err != nil { | ||
| return nil, fmt.Errorf("callback error: %w", err) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| if err := stream.Err(); err != nil { | ||
| return nil, fmt.Errorf("stream error: %w", err) | ||
| } | ||
|
|
||
| if finalResp != nil { | ||
| mResp, err := translateResponse(finalResp) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| mResp.Request = input | ||
| return mResp, nil | ||
| } | ||
|
|
||
| // prevent returning an error if stream does not provide [responses.ResponseCompletedEvent] | ||
| // user might already have received the chunks throughout the loop | ||
| return &ai.ModelResponse{ | ||
| Request: input, | ||
| Message: &ai.Message{Role: ai.RoleModel}, | ||
| }, nil | ||
| } | ||
|
|
||
| // generateComplete starts a new completion | ||
| func generateComplete(ctx context.Context, client *openai.Client, req *responses.ResponseNewParams, input *ai.ModelRequest) (*ai.ModelResponse, error) { | ||
| resp, err := client.Responses.New(ctx, *req) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| modelResp, err := translateResponse(resp) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| modelResp.Request = input | ||
| return modelResp, nil | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The function returns a default
ai.ModelResponseif the stream ends without aResponseCompletedEvent. This can hide potential issues, as a stream should ideally end with either a completion event or an error. Returning a default response might lead to silent failures or confusing behavior for the caller, who would receive an empty response without usage statistics.Consider returning an error if
finalRespisnilandstream.Err()is alsonilto make failures more explicit.Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Note for the future: This is an unlikely scenario but, since we are talking about streaming: The user might already have received all the chunks, failing at this point might cause the request to fail. This edge-case is to cover up a possible scenario when
responses.ResponseCompletedEventis not sent