-
Notifications
You must be signed in to change notification settings - Fork 58
feat: add embeddings API + OpenAI/OpenAI-compat #127
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
evanmschultz
wants to merge
4
commits into
charmbracelet:main
Choose a base branch
from
evanmschultz:feature-embeddings
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
4 commits
Select commit
Hold shift + click to select a range
5f4d118
feat: add embeddings core API and validation
evanmschultz 740b7e7
feat: add embeddings support for OpenAI and OpenAI-compat providers
evanmschultz 3f00daa
docs: document embeddings usage
evanmschultz d1be510
refactor: simplify embeddings API to inputs-only
evanmschultz 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,2 +1,2 @@ | ||
| // Package fantasy provides a unified interface for interacting with various AI language models. | ||
| // Package fantasy provides a unified interface for interacting with various AI language and embedding models. | ||
| package fantasy |
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,63 @@ | ||
| package fantasy | ||
|
|
||
| import ( | ||
| "context" | ||
| "fmt" | ||
| ) | ||
|
|
||
| // EmbeddingProvider represents a provider that can create embedding models. | ||
| // This is separate from Provider to avoid breaking changes. | ||
| type EmbeddingProvider interface { | ||
| EmbeddingModel(ctx context.Context, modelID string) (EmbeddingModel, error) | ||
| } | ||
|
|
||
| // EmbeddingModel represents a model that can generate embeddings. | ||
| type EmbeddingModel interface { | ||
| Embed(context.Context, EmbeddingCall) (*EmbeddingResponse, error) | ||
|
|
||
| Provider() string | ||
| Model() string | ||
| } | ||
|
|
||
| // EmbeddingCall represents a request to generate embeddings. | ||
| // Inputs must include at least one non-empty item. | ||
| type EmbeddingCall struct { | ||
| Inputs []string `json:"inputs,omitempty"` | ||
| Dimensions *int64 `json:"dimensions,omitempty"` | ||
|
|
||
| ProviderOptions ProviderOptions `json:"provider_options,omitempty"` | ||
| } | ||
|
|
||
| // Embedding represents a single embedding vector. | ||
| type Embedding struct { | ||
| Index int `json:"index"` | ||
| Vector []float32 `json:"vector"` | ||
| } | ||
|
|
||
| // EmbeddingResponse represents the response from an embedding model. | ||
| type EmbeddingResponse struct { | ||
| Model string `json:"model"` | ||
| Usage Usage `json:"usage"` | ||
| Embeddings []Embedding `json:"embeddings"` | ||
| } | ||
|
|
||
| // ValidateEmbeddingCall validates the embedding request parameters. | ||
| func ValidateEmbeddingCall(call EmbeddingCall) error { | ||
| if len(call.Inputs) == 0 { | ||
| return &Error{ | ||
| Title: "invalid argument", | ||
| Message: "embedding inputs are required", | ||
| } | ||
| } | ||
|
|
||
| for i, input := range call.Inputs { | ||
| if input == "" { | ||
| return &Error{ | ||
| Title: "invalid argument", | ||
| Message: fmt.Sprintf("embedding inputs[%d] cannot be empty", i), | ||
| } | ||
| } | ||
| } | ||
|
|
||
| return nil | ||
| } |
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,29 @@ | ||
| package fantasy | ||
|
|
||
| import ( | ||
| "testing" | ||
|
|
||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| func TestValidateEmbeddingCall(t *testing.T) { | ||
| t.Run("requires inputs", func(t *testing.T) { | ||
| err := ValidateEmbeddingCall(EmbeddingCall{}) | ||
| require.Error(t, err) | ||
| }) | ||
|
|
||
| t.Run("rejects empty inputs", func(t *testing.T) { | ||
| err := ValidateEmbeddingCall(EmbeddingCall{Inputs: []string{""}}) | ||
| require.Error(t, err) | ||
| }) | ||
|
|
||
| t.Run("accepts single input in inputs", func(t *testing.T) { | ||
| err := ValidateEmbeddingCall(EmbeddingCall{Inputs: []string{"hello"}}) | ||
| require.NoError(t, err) | ||
| }) | ||
|
|
||
| t.Run("accepts batch inputs", func(t *testing.T) { | ||
| err := ValidateEmbeddingCall(EmbeddingCall{Inputs: []string{"a", "b"}}) | ||
| require.NoError(t, err) | ||
| }) | ||
| } | ||
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,85 @@ | ||
| package openai | ||
|
|
||
| import ( | ||
| "context" | ||
|
|
||
| "charm.land/fantasy" | ||
| "github.com/openai/openai-go/v2" | ||
| "github.com/openai/openai-go/v2/packages/param" | ||
| ) | ||
|
|
||
| type embeddingModel struct { | ||
| provider string | ||
| modelID string | ||
| client openai.Client | ||
| } | ||
|
|
||
| // Model implements fantasy.EmbeddingModel. | ||
| func (e embeddingModel) Model() string { | ||
| return e.modelID | ||
| } | ||
|
|
||
| // Provider implements fantasy.EmbeddingModel. | ||
| func (e embeddingModel) Provider() string { | ||
| return e.provider | ||
| } | ||
|
|
||
| // Embed implements fantasy.EmbeddingModel. | ||
| func (e embeddingModel) Embed(ctx context.Context, call fantasy.EmbeddingCall) (*fantasy.EmbeddingResponse, error) { | ||
| if err := fantasy.ValidateEmbeddingCall(call); err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| params := openai.EmbeddingNewParams{ | ||
| Model: e.modelID, | ||
| } | ||
|
|
||
| if call.ProviderOptions != nil { | ||
| if v, ok := call.ProviderOptions[Name]; ok { | ||
| providerOptions, ok := v.(*ProviderOptions) | ||
| if !ok { | ||
| return nil, &fantasy.Error{Title: "invalid argument", Message: "openai provider options should be *openai.ProviderOptions"} | ||
| } | ||
| if providerOptions.User != nil { | ||
| params.User = param.NewOpt(*providerOptions.User) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| if call.Dimensions != nil { | ||
| params.Dimensions = param.NewOpt(*call.Dimensions) | ||
| } | ||
|
|
||
| params.Input = openai.EmbeddingNewParamsInputUnion{ | ||
| OfArrayOfStrings: call.Inputs, | ||
| } | ||
|
|
||
| response, err := e.client.Embeddings.New(ctx, params) | ||
| if err != nil { | ||
| return nil, toProviderErr(err) | ||
| } | ||
|
|
||
| embeddings := make([]fantasy.Embedding, 0, len(response.Data)) | ||
| for _, embedding := range response.Data { | ||
| vector := make([]float32, len(embedding.Embedding)) | ||
| for i, value := range embedding.Embedding { | ||
| vector[i] = float32(value) | ||
| } | ||
| embeddings = append(embeddings, fantasy.Embedding{ | ||
| Index: int(embedding.Index), | ||
| Vector: vector, | ||
| }) | ||
| } | ||
|
|
||
| usage := fantasy.Usage{ | ||
| InputTokens: response.Usage.PromptTokens, | ||
| TotalTokens: response.Usage.TotalTokens, | ||
| OutputTokens: 0, | ||
| } | ||
|
|
||
| return &fantasy.EmbeddingResponse{ | ||
| Model: response.Model, | ||
| Usage: usage, | ||
| Embeddings: embeddings, | ||
| }, nil | ||
| } |
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
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.
For tests, especially when introducing new APIs, Fantasy uses charm.land/x/vcr to record requests & replay real data.
See https://github.com/charmbracelet/fantasy/tree/main/providertests/testdata/TestOpenAICommon/openai-o4-mini for example
I've got some captures for embeddings already done: cbca0e5#diff-2599f9d193307dc4e06a66ec239c05f98fdf3ee32363d9eb3ece3ca18256f79c
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.
Added VCR provider tests + captures.